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
Python
Python
fix tf longformer
23290836c39f73eb9d2f2b3bddfad227fea14fd2
<ide><path>src/transformers/modeling_tf_longformer.py <ide> class TFLongformerBaseModelOutput(ModelOutput): <ide> in the sequence. <ide> """ <ide> <del> last_hidden_state: tf.Tensor <add> last_hidden_state: tf.Tensor = None <ide> hidden_states: Optional[Tuple[tf.Tensor]] = None <ide> attentions: Optional[Tuple[tf.Tensor]] = None <ide> global_attentions: Optional[Tuple[tf.Tensor]] = None <ide> class TFLongformerBaseModelOutputWithPooling(ModelOutput): <ide> in the sequence. <ide> """ <ide> <del> last_hidden_state: tf.Tensor <add> last_hidden_state: tf.Tensor = None <ide> pooler_output: tf.Tensor = None <ide> hidden_states: Optional[Tuple[tf.Tensor]] = None <ide> attentions: Optional[Tuple[tf.Tensor]] = None
1
Text
Text
fix compiler warning in doc/api/addons.md
59c7df4a1099ea904de635c6357c08878dfc7093
<ide><path>doc/api/addons.md <ide> property `msg` that echoes the string passed to `createObject()`: <ide> <ide> namespace demo { <ide> <add>using v8::Context; <ide> using v8::FunctionCallbackInfo; <ide> using v8::Isolate; <ide> using v8::Local; <ide> using v8::Value; <ide> <ide> void CreateObject(const FunctionCallbackInfo<Value>& args) { <ide> Isolate* isolate = args.GetIsolate(); <add> Local<Context> context = isolate->GetCurrentContext(); <ide> <ide> Local<Object> obj = Object::New(isolate); <del> obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString(isolate)); <add> obj->Set(String::NewFromUtf8(isolate, "msg"), <add> args[0]->ToString(context).ToLocalChecked()); <ide> <ide> args.GetReturnValue().Set(obj); <ide> } <ide> that can take two `MyObject` objects as input arguments: <ide> <ide> namespace demo { <ide> <add>using v8::Context; <ide> using v8::FunctionCallbackInfo; <ide> using v8::Isolate; <ide> using v8::Local; <ide> void CreateObject(const FunctionCallbackInfo<Value>& args) { <ide> <ide> void Add(const FunctionCallbackInfo<Value>& args) { <ide> Isolate* isolate = args.GetIsolate(); <add> Local<Context> context = isolate->GetCurrentContext(); <ide> <ide> MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>( <del> args[0]->ToObject(isolate)); <add> args[0]->ToObject(context).ToLocalChecked()); <ide> MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>( <del> args[1]->ToObject(isolate)); <add> args[1]->ToObject(context).ToLocalChecked()); <ide> <ide> double sum = obj1->value() + obj2->value(); <ide> args.GetReturnValue().Set(Number::New(isolate, sum));
1
Text
Text
update translation to 673874d
710668e7f188a1d2ffe94999e5718813abab4923
<ide><path>docs/docs/ref-02-component-api.ko-KR.md <ide> forceUpdate([function callback]) <ide> <ide> `render()` 메소드가 `this.props`나 `this.state`가 아닌 다른 곳에서 데이터를 읽어오는 경우 `forceUpdate()`를 호출하여 React가 `render()`를 다시 실행하도록 만들 수 있습니다. `this.state`를 직접 변경하는 경우에도 `forceUpdate()`를 호출해야 합니다. <ide> <del>`forceUpdate()`를 호출하면 해당 컴포넌트와 그 자식들의 `render()` 함수가 호출되지만, React는 마크업이 변경된 경우에만 DOM을 업데이트합니다. <add>`forceUpdate()`를 호출하면 `shouldComponentUpdate()`를 생략하고 해당 컴포넌트 `render()` 함수가 호출됩니다. 각 자식 컴포넌트에 대해서는 `shouldComponentUpdate()`를 포함해 보통 라이프 사이클 메서드를 호출합니다. React는 마크업이 변경된 경우에만 DOM을 업데이트합니다. <ide> <ide> 특별한 경우가 아니면 `forceUpdate()`는 되도록 피하시고 `render()`에서는 `this.props`와 `this.state`에서만 읽어오세요. 그렇게 하는 것이 애플리케이션을 훨씬 단순하고 효율적으로 만들어줍니다. <ide> <ide><path>docs/docs/ref-05-events.ko-KR.md <ide> onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave <ide> onMouseMove onMouseOut onMouseOver onMouseUp <ide> ``` <ide> <add>`onMouseEnter`와 `onMouseLeave` 이벤트는 평범하게 일어나는(bubbling) 대신 입력된 컴포넌트에 남겨지도록 컴포넌트에서 전달되고 캡쳐 단계가 없습니다. <add> <ide> 프로퍼티: <ide> <ide> ```javascript <ide><path>docs/docs/tutorial.ko-KR.md <ide> next: thinking-in-react-ko-KR.html <ide> <ide> ### 서버 구동하기 <ide> <del>이 튜토리얼을 시작할 때 필요한 건 아니지만, 나중에 실행 중인 서버에 `POST` 요청을 하는 기능을 추가하게 될 것입니다. 서버를 구성하는 것이 익숙하다면, 본인이 편한 방식대로 서버를 구성해 주세요. 서버사이드에 대한 고민없이 React의 학습 그 자체에 집중하고 싶은 분들을 위해서, 몇 가지 언어로 간단한 서버코드를 작성해 놓았습니다 - JavaScript (Node.js), Python, Ruby 버전이 있고, GitHub에서 찾아보실 수 있습니다. [소스를 확인](https://github.com/reactjs/react-tutorial/)하거나 [zip 파일을 다운로드](https://github.com/reactjs/react-tutorial/archive/master.zip)하고 시작하세요. <add>이 튜토리얼을 시작할 때 필요한 건 아니지만, 나중에 실행 중인 서버에 `POST` 요청을 하는 기능을 추가하게 될 것입니다. 서버를 구성하는 것이 익숙하다면, 본인이 편한 방식대로 서버를 구성해 주세요. 서버사이드에 대한 고민없이 React의 학습 그 자체에 집중하고 싶은 분들을 위해서, 몇 가지 언어로 간단한 서버코드를 작성해 놓았습니다 - JavaScript (Node.js), Python, Ruby, Go, PHP 버전이 있고, GitHub에서 찾아보실 수 있습니다. [소스를 확인](https://github.com/reactjs/react-tutorial/)하거나 [zip 파일을 다운로드](https://github.com/reactjs/react-tutorial/archive/master.zip)하고 시작하세요. <ide> <ide> 튜토리얼을 다운로드 받아 시작한다면, `public/index.html`을 열고 바로 시작하세요. <ide>
3
Ruby
Ruby
fix generic api path functions
489f5ed9d1271795885cf3a954199a6f9bf326e8
<ide><path>Library/Homebrew/api/analytics.rb <ide> module API <ide> # <ide> # @api private <ide> module Analytics <del> extend T::Sig <add> class << self <add> extend T::Sig <ide> <del> module_function <add> sig { returns(String) } <add> def analytics_api_path <add> "analytics" <add> end <add> alias generic_analytics_api_path analytics_api_path <ide> <del> sig { returns(String) } <del> def analytics_api_path <del> "analytics" <del> end <del> alias generic_analytics_api_path analytics_api_path <del> <del> sig { params(category: String, days: T.any(Integer, String)).returns(Hash) } <del> def fetch(category, days) <del> Homebrew::API.fetch "#{analytics_api_path}/#{category}/#{days}d.json" <add> sig { params(category: String, days: T.any(Integer, String)).returns(Hash) } <add> def fetch(category, days) <add> Homebrew::API.fetch "#{analytics_api_path}/#{category}/#{days}d.json" <add> end <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/api/bottle.rb <ide> module API <ide> # <ide> # @api private <ide> module Bottle <del> extend T::Sig <add> class << self <add> extend T::Sig <ide> <del> module_function <del> <del> sig { returns(String) } <del> def bottle_api_path <del> "bottle" <del> end <del> alias generic_bottle_api_path bottle_api_path <del> <del> GITHUB_PACKAGES_SHA256_REGEX = %r{#{GitHubPackages::URL_REGEX}.*/blobs/sha256:(?<sha256>\h{64})$}.freeze <del> <del> sig { params(name: String).returns(Hash) } <del> def fetch(name) <del> Homebrew::API.fetch "#{bottle_api_path}/#{name}.json" <del> end <add> sig { returns(String) } <add> def bottle_api_path <add> "bottle" <add> end <add> alias generic_bottle_api_path bottle_api_path <ide> <del> sig { params(name: String).returns(T::Boolean) } <del> def available?(name) <del> fetch name <del> true <del> rescue ArgumentError <del> false <del> end <add> GITHUB_PACKAGES_SHA256_REGEX = %r{#{GitHubPackages::URL_REGEX}.*/blobs/sha256:(?<sha256>\h{64})$}.freeze <ide> <del> sig { params(name: String).void } <del> def fetch_bottles(name) <del> hash = fetch(name) <del> bottle_tag = Utils::Bottles.tag.to_s <add> sig { params(name: String).returns(Hash) } <add> def fetch(name) <add> Homebrew::API.fetch "#{bottle_api_path}/#{name}.json" <add> end <ide> <del> if !hash["bottles"].key?(bottle_tag) && !hash["bottles"].key?("all") <del> odie "No bottle available for #{name} on the current OS" <add> sig { params(name: String).returns(T::Boolean) } <add> def available?(name) <add> fetch name <add> true <add> rescue ArgumentError <add> false <ide> end <ide> <del> download_bottle(hash, bottle_tag) <add> sig { params(name: String).void } <add> def fetch_bottles(name) <add> hash = fetch(name) <add> bottle_tag = Utils::Bottles.tag.to_s <ide> <del> hash["dependencies"].each do |dep_hash| <del> existing_formula = begin <del> Formulary.factory dep_hash["name"] <del> rescue FormulaUnavailableError <del> # The formula might not exist if it's not installed and homebrew/core isn't tapped <del> nil <add> if !hash["bottles"].key?(bottle_tag) && !hash["bottles"].key?("all") <add> odie "No bottle available for #{name} on the current OS" <ide> end <ide> <del> next if existing_formula.present? && existing_formula.latest_version_installed? <add> download_bottle(hash, bottle_tag) <ide> <del> download_bottle(dep_hash, bottle_tag) <add> hash["dependencies"].each do |dep_hash| <add> existing_formula = begin <add> Formulary.factory dep_hash["name"] <add> rescue FormulaUnavailableError <add> # The formula might not exist if it's not installed and homebrew/core isn't tapped <add> nil <add> end <add> <add> next if existing_formula.present? && existing_formula.latest_version_installed? <add> <add> download_bottle(dep_hash, bottle_tag) <add> end <ide> end <del> end <ide> <del> sig { params(url: String).returns(T.nilable(String)) } <del> def checksum_from_url(url) <del> match = url.match GITHUB_PACKAGES_SHA256_REGEX <del> return if match.blank? <add> sig { params(url: String).returns(T.nilable(String)) } <add> def checksum_from_url(url) <add> match = url.match GITHUB_PACKAGES_SHA256_REGEX <add> return if match.blank? <ide> <del> match[:sha256] <del> end <add> match[:sha256] <add> end <ide> <del> sig { params(hash: Hash, tag: Symbol).void } <del> def download_bottle(hash, tag) <del> bottle = hash["bottles"][tag] <del> bottle ||= hash["bottles"]["all"] <del> return if bottle.blank? <add> sig { params(hash: Hash, tag: Symbol).void } <add> def download_bottle(hash, tag) <add> bottle = hash["bottles"][tag] <add> bottle ||= hash["bottles"]["all"] <add> return if bottle.blank? <ide> <del> sha256 = bottle["sha256"] || checksum_from_url(bottle["url"]) <del> bottle_filename = ::Bottle::Filename.new(hash["name"], hash["pkg_version"], tag, hash["rebuild"]) <add> sha256 = bottle["sha256"] || checksum_from_url(bottle["url"]) <add> bottle_filename = ::Bottle::Filename.new(hash["name"], hash["pkg_version"], tag, hash["rebuild"]) <ide> <del> resource = Resource.new hash["name"] <del> resource.url bottle["url"] <del> resource.sha256 sha256 <del> resource.version hash["pkg_version"] <del> resource.downloader.resolved_basename = bottle_filename <add> resource = Resource.new hash["name"] <add> resource.url bottle["url"] <add> resource.sha256 sha256 <add> resource.version hash["pkg_version"] <add> resource.downloader.resolved_basename = bottle_filename <ide> <del> resource.fetch <add> resource.fetch <ide> <del> # Map the name of this formula to the local bottle path to allow the <del> # formula to be loaded by passing just the name to `Formulary::factory`. <del> Formulary.map_formula_name_to_local_bottle_path hash["name"], resource.downloader.cached_location <add> # Map the name of this formula to the local bottle path to allow the <add> # formula to be loaded by passing just the name to `Formulary::factory`. <add> Formulary.map_formula_name_to_local_bottle_path hash["name"], resource.downloader.cached_location <add> end <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/api/cask.rb <ide> module API <ide> # <ide> # @api private <ide> module Cask <del> extend T::Sig <add> class << self <add> extend T::Sig <ide> <del> module_function <del> <del> sig { params(name: String).returns(Hash) } <del> def fetch(name) <del> Homebrew::API.fetch "cask/#{name}.json" <add> sig { params(name: String).returns(Hash) } <add> def fetch(name) <add> Homebrew::API.fetch "cask/#{name}.json" <add> end <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/api/formula.rb <ide> module API <ide> # <ide> # @api private <ide> module Formula <del> extend T::Sig <add> class << self <add> extend T::Sig <ide> <del> module_function <add> sig { returns(String) } <add> def formula_api_path <add> "formula" <add> end <add> alias generic_formula_api_path formula_api_path <ide> <del> sig { returns(String) } <del> def formula_api_path <del> "formula" <del> end <del> alias generic_formula_api_path formula_api_path <del> <del> sig { params(name: String).returns(Hash) } <del> def fetch(name) <del> Homebrew::API.fetch "#{formula_api_path}/#{name}.json" <add> sig { params(name: String).returns(Hash) } <add> def fetch(name) <add> Homebrew::API.fetch "#{formula_api_path}/#{name}.json" <add> end <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/api/versions.rb <ide> module API <ide> # <ide> # @api private <ide> module Versions <del> extend T::Sig <add> class << self <add> extend T::Sig <ide> <del> module_function <del> <del> def formulae <del> # The result is cached by Homebrew::API.fetch <del> Homebrew::API.fetch "versions-formulae.json" <del> end <del> <del> def linux <del> # The result is cached by Homebrew::API.fetch <del> Homebrew::API.fetch "versions-linux.json" <del> end <add> def formulae <add> # The result is cached by Homebrew::API.fetch <add> Homebrew::API.fetch "versions-formulae.json" <add> end <ide> <del> def casks <del> # The result is cached by Homebrew::API.fetch <del> Homebrew::API.fetch "versions-casks.json" <del> end <add> def linux <add> # The result is cached by Homebrew::API.fetch <add> Homebrew::API.fetch "versions-linux.json" <add> end <ide> <del> sig { params(name: String).returns(T.nilable(PkgVersion)) } <del> def latest_formula_version(name) <del> versions = if OS.mac? || Homebrew::EnvConfig.force_homebrew_on_linux? <del> formulae <del> else <del> linux <add> def casks <add> # The result is cached by Homebrew::API.fetch <add> Homebrew::API.fetch "versions-casks.json" <ide> end <ide> <del> return unless versions.key? name <add> sig { params(name: String).returns(T.nilable(PkgVersion)) } <add> def latest_formula_version(name) <add> versions = if OS.mac? || Homebrew::EnvConfig.force_homebrew_on_linux? <add> formulae <add> else <add> linux <add> end <ide> <del> version = Version.new(versions[name]["version"]) <del> revision = versions[name]["revision"] <del> PkgVersion.new(version, revision) <del> end <add> return unless versions.key? name <ide> <del> sig { params(token: String).returns(T.nilable(Version)) } <del> def latest_cask_version(token) <del> return unless casks.key? token <add> version = Version.new(versions[name]["version"]) <add> revision = versions[name]["revision"] <add> PkgVersion.new(version, revision) <add> end <ide> <del> Version.new(casks[token]["version"]) <add> sig { params(token: String).returns(T.nilable(Version)) } <add> def latest_cask_version(token) <add> return unless casks.key? token <add> <add> Version.new(casks[token]["version"]) <add> end <ide> end <ide> end <ide> end
5
Javascript
Javascript
add more info
e50e91c7a83ec148ea3ee929bbfe1924dcbb060b
<ide><path>src/ngMock/angular-mocks.js <ide> angular.mock.$ControllerDecorator = ['$delegate', function($delegate) { <ide> * @ngdoc service <ide> * @name $componentController <ide> * @description <del> * A service that can be used to create instances of component controllers. <del> * <div class="alert alert-info"> <add> * A service that can be used to create instances of component controllers. Useful for unit-testing. <add> * <ide> * Be aware that the controller will be instantiated and attached to the scope as specified in <ide> * the component definition object. If you do not provide a `$scope` object in the `locals` param <ide> * then the helper will create a new isolated scope as a child of `$rootScope`. <del> * </div> <add> * <add> * If you are using `$element` or `$attrs` in the controller, make sure to provide them as `locals`. <add> * The `$element` must be a jqLite-wrapped DOM element, and `$attrs` should be an object that <add> * has all properties / functions that you are using in the controller. If this is getting too complex, <add> * you should compile the component instead and access the component's controller via the <add> * {@link angular.element#methods `controller`} function. <add> * <add> * See also the section on {@link guide/component#unit-testing-component-controllers unit-testing component controllers} <add> * in the guide. <add> * <ide> * @param {string} componentName the name of the component whose controller we want to instantiate <ide> * @param {Object} locals Injection locals for Controller. <ide> * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used
1
Text
Text
fix stray paren on increment and decrement
e172adfb9b6674475301204da58723eb1bdb2308
<ide><path>guide/english/javascript/arithmetic-operation/index.md <ide> JavaScript provides the user with five arithmetic operators: `+`, `-`, `*`, `/` <ide> 5 + "foo" // concatenates the string and the number and returns "5foo" <ide> "foo" + "bar" // concatenates the strings and returns "foobar" <ide> <del>_Hint:_ There is a handy <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_(' target='_blank' rel='nofollow'>increment</a>) operator that is a great shortcut when you're adding numbers by 1. <add>_Hint:_ There is a handy <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment' target='_blank' rel='nofollow'>increment</a>(++) operator that is a great shortcut when you're adding numbers by 1. <ide> <ide> ## Subtraction <ide> <ide> _Hint:_ There is a handy <a href='https://developer.mozilla.org/en-US/docs/Web/J <ide> true - 3 // interprets true as 1 and returns -2 <ide> 5 - "foo" // returns NaN (Not a Number) <ide> <del>_Hint:_ There is a handy <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement_(--' target='_blank' rel='nofollow'>decrement</a>) operator that is a great shortcut when you're subtracting numbers by 1. <add>_Hint:_ There is a handy <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement_(--' target='_blank' rel='nofollow'>decrement</a>(--) operator that is a great shortcut when you're subtracting numbers by 1. <ide> <ide> ## Multiplication <ide>
1
Python
Python
fix separate compilation mode with distutils
fc22e9d653d5cb703654181431db17252ecc825c
<ide><path>numpy/core/setup.py <ide> def get_mathlib_info(*args): <ide> join('src', 'multiarray', 'hashdescr.c'), <ide> join('src', 'multiarray', 'arrayobject.c'), <ide> join('src', 'multiarray', 'buffer.c'), <add> join('src', 'multiarray', 'datetime.c'), <ide> join('src', 'multiarray', 'numpyos.c'), <ide> join('src', 'multiarray', 'conversion_utils.c'), <ide> join('src', 'multiarray', 'flagsobject.c'),
1
Python
Python
add test integrated with middleware
a68e78bd0b5174d2c8a40497d3d5842f66c65a34
<ide><path>tests/test_middleware.py <add> <add>from django.conf.urls import patterns, url <add>from django.contrib.auth.models import User <add>from rest_framework.authentication import TokenAuthentication <add>from rest_framework.authtoken.models import Token <add>from rest_framework.test import APITestCase <add>from rest_framework.views import APIView <add> <add> <add>urlpatterns = patterns( <add> '', <add> url(r'^$', APIView.as_view(authentication_classes=(TokenAuthentication,))), <add>) <add> <add> <add>class MyMiddleware(object): <add> <add> def process_response(self, request, response): <add> assert hasattr(request, 'user'), '`user` is not set on request' <add> assert request.user.is_authenticated(), '`user` is not authenticated' <add> return response <add> <add> <add>class TestMiddleware(APITestCase): <add> <add> urls = 'tests.test_middleware' <add> <add> def test_middleware_can_access_user_when_processing_response(self): <add> user = User.objects.create_user('john', 'john@example.com', 'password') <add> key = 'abcd1234' <add> Token.objects.create(key=key, user=user) <add> <add> with self.settings( <add> MIDDLEWARE_CLASSES=('tests.test_middleware.MyMiddleware',) <add> ): <add> auth = 'Token ' + key <add> self.client.get('/', HTTP_AUTHORIZATION=auth)
1
Javascript
Javascript
fix iso week parsing for small years
80680ee0992383be1b50d41a259863f2154f777b
<ide><path>moment.js <ide> <ide> // left zero fill a number <ide> // see http://jsperf.com/left-zero-filling for performance comparison <del> function leftZeroFill(number, targetLength) { <add> function leftZeroFill(number, targetLength, forceSign) { <ide> var output = Math.abs(number) + '', <ide> sign = number >= 0; <ide> <ide> while (output.length < targetLength) { <ide> output = '0' + output; <ide> } <del> return (sign ? '' : '-') + output; <add> return (sign ? (forceSign ? '+' : '') : '-') + output; <ide> } <ide> <ide> // helper function for _.addTime and _.subtractTime <ide> //compute day of the year from weeks and weekdays <ide> if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { <ide> fixYear = function (val) { <add> var int_val = parseInt(val, 10); <ide> return val ? <del> (val.length < 3 ? (parseInt(val, 10) > 68 ? '19' + val : '20' + val) : val) : <add> (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) : <ide> (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]); <ide> }; <ide> <ide> <ide> //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday <ide> function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { <del> var d = new Date(Date.UTC(year, 0)).getUTCDay(), <add> // The only solid way to create an iso date from year is to use <add> // a string format (Date.UTC handles only years > 1900). Don't ask why <add> // it doesn't need Z at the end. <add> var d = new Date(leftZeroFill(year, 6, true) + '-01-01').getUTCDay(), <ide> daysToAdd, dayOfYear; <ide> <ide> weekday = weekday != null ? weekday : firstDayOfWeek; <ide><path>test/moment/create.js <ide> exports.create = { <ide> //can parse other stuff too <ide> test.equal(moment('1999-W37-4 3:30', 'GGGG-[W]WW-E HH:mm').format('YYYY MM DD HH:mm'), '1999 09 16 03:30', "parsing weeks and hours"); <ide> <add> // Years less than 100 <add> ver('0098-06', 'GGGG-WW', "0098 02 03", "small years work", true); <add> <ide> test.done(); <ide> }, <ide>
2
PHP
PHP
move segments processing
a9444e1ddb2cbc95008fee7174c3fef683889155
<ide><path>src/Illuminate/Support/NamespacedItemResolver.php <ide> public function parseKey($key) <ide> return $this->parsed[$key]; <ide> } <ide> <del> $segments = explode('.', $key); <del> <ide> // If the key does not contain a double colon, it means the key is not in a <ide> // namespace, and is just a regular configuration item. Namespaces are a <ide> // tool for organizing configuration items for things such as modules. <ide> if (strpos($key, '::') === false) <ide> { <add> $segments = explode('.', $key); <add> <ide> $parsed = $this->parseBasicSegments($segments); <ide> } <ide> else
1
Javascript
Javascript
fix extra newline in validation
10c44e5a94f4875ee8cd8b39437e67e06a61fed9
<ide><path>schemas/ajv.absolutePath.js <ide> <ide> const getErrorFor = (shouldBeAbsolute, data, schema) => { <ide> const message = shouldBeAbsolute ? <del> `The provided value ${JSON.stringify(data)} is not an absolute path!\n` <del> : `A relative path is expected. However the provided value ${JSON.stringify(data)} is an absolute path!\n`; <add> `The provided value ${JSON.stringify(data)} is not an absolute path!` <add> : `A relative path is expected. However the provided value ${JSON.stringify(data)} is an absolute path!`; <ide> <ide> return { <ide> keyword: "absolutePath", <ide><path>test/Validation.test.js <ide> describe("Validation", () => { <ide> }, <ide> message: [ <ide> " - configuration.output.filename: A relative path is expected. However the provided value \"/bar\" is an absolute path!", <del> "", <ide> ] <ide> }, { <ide> name: "absolute path", <ide> describe("Validation", () => { <ide> }, <ide> message: [ <ide> " - configuration.context: The provided value \"baz\" is not an absolute path!", <del> "", <ide> ] <ide> }]; <ide> testCases.forEach((testCase) => {
2
Mixed
Python
update the old interfaces
3fe78376913cfa310a13990589d312d47440399d
<ide><path>docs/templates/optimizers.md <ide> An optimizer is one of the two arguments required for compiling a Keras model: <ide> from keras import optimizers <ide> <ide> model = Sequential() <del>model.add(Dense(64, init='uniform', input_shape=(10,))) <add>model.add(Dense(64, kernel_initializer='uniform', input_shape=(10,))) <ide> model.add(Activation('tanh')) <ide> model.add(Activation('softmax')) <ide> <ide> sgd = optimizers.SGD(lr=0.01, clipvalue=0.5) <ide> <ide> --- <ide> <del>{{autogenerated}} <ide>\ No newline at end of file <add>{{autogenerated}} <ide><path>examples/mnist_net2net.py <ide> def make_deeper_student_model(teacher_model, train_data, <ide> # add another fc layer to make original fc1 deeper <ide> if init == 'net2deeper': <ide> # net2deeper for fc layer with relu, is just an identity initializer <del> model.add(Dense(64, init='identity', <add> model.add(Dense(64, kernel_initializer='identity', <ide> activation='relu', name='fc1-deeper')) <ide> elif init == 'random-init': <ide> model.add(Dense(64, activation='relu', name='fc1-deeper'))
2
Ruby
Ruby
add formula_file_to_name and alias_file_to_name
c2a5a8388f81d8160df61f6ccd4b9161921bd1e5
<ide><path>Library/Homebrew/tap.rb <ide> def formula_files <ide> <ide> # an array of all {Formula} names of this {Tap}. <ide> def formula_names <del> @formula_names ||= formula_files.map { |f| "#{name}/#{f.basename(".rb")}" } <add> @formula_names ||= formula_files.map { |f| formula_file_to_name(f) } <ide> end <ide> <ide> # path to the directory of all alias files for this {Tap}. <ide> def alias_files <ide> # an array of all aliases of this {Tap}. <ide> # @private <ide> def aliases <del> @aliases ||= alias_files.map { |f| "#{name}/#{f.basename}" } <add> @aliases ||= alias_files.map { |f| alias_file_to_name(f) } <ide> end <ide> <ide> # a table mapping alias to formula name <ide> def alias_table <ide> return @alias_table if @alias_table <ide> @alias_table = Hash.new <ide> alias_files.each do |alias_file| <del> @alias_table["#{name}/#{alias_file.basename}"] = "#{name}/#{alias_file.resolved_path.basename(".rb")}" <add> @alias_table[alias_file_to_name(alias_file)] = formula_file_to_name(alias_file.resolved_path) <ide> end <ide> @alias_table <ide> end <ide> def self.each <ide> def self.names <ide> map(&:name) <ide> end <add> <add> private <add> <add> def formula_file_to_name(file) <add> "#{name}/#{file.basename(".rb")}" <add> end <add> <add> def alias_file_to_name(file) <add> "#{name}/#{file.basename}" <add> end <ide> end
1
Python
Python
fix www asset compilation
f600197ad47916687830177c9787c4616f7854a2
<ide><path>dev/breeze/src/airflow_breeze/utils/run_utils.py <ide> def run_compile_www_assets( <ide> ) <ide> thread.start() <ide> else: <del> _run_compile_internally(command_to_execute, dry_run, verbose) <add> return _run_compile_internally(command_to_execute, dry_run, verbose)
1
Javascript
Javascript
use pip install . in quickstart [ci skip]
3ca5c7082df36a1970277c4accc0f02176dc2459
<ide><path>website/src/widgets/quickstart-install.js <ide> const QuickstartInstall = ({ id, title }) => { <ide> </QS> <ide> <QS package="source">pip install -r requirements.txt</QS> <ide> <QS package="source">python setup.py build_ext --inplace</QS> <del> <QS package="source">python setup.py install</QS> <del> {(train || hardware == 'gpu') && ( <del> <QS package="source">pip install -e '.[{pipExtras}]'</QS> <del> )} <del> <add> <QS package="source"> <add> pip install {train || hardware == 'gpu' ? `'.[${pipExtras}]'` : '.'} <add> </QS> <ide> <QS config="train" package="conda" comment prompt={false}> <ide> # packages only available via pip <ide> </QS>
1
Python
Python
add chinese ptb tags to glossary
cc5aeaed29c067f60d11e07496704406a1577a35
<ide><path>spacy/glossary.py <ide> def explain(term): <ide> "FW": "foreign word", <ide> "HYPH": "punctuation mark, hyphen", <ide> "IN": "conjunction, subordinating or preposition", <del> "JJ": "adjective", <add> "JJ": "adjective (English), other noun-modifier (Chinese)", <ide> "JJR": "adjective, comparative", <ide> "JJS": "adjective, superlative", <ide> "LS": "list item marker", <ide> def explain(term): <ide> "WP": "wh-pronoun, personal", <ide> "WP$": "wh-pronoun, possessive", <ide> "WRB": "wh-adverb", <del> "SP": "space", <add> "SP": "space (English), sentence-final particle (Chinese)", <ide> "ADD": "email", <ide> "NFP": "superfluous punctuation", <ide> "GW": "additional word in multi-word expression", <ide> def explain(term): <ide> "VVIZU": 'infinitive with "zu", full', <ide> "VVPP": "perfect participle, full", <ide> "XY": "non-word containing non-letter", <add> # POS Tags (Chinese) <add> # OntoNotes / Chinese Penn Treebank <add> # https://repository.upenn.edu/cgi/viewcontent.cgi?article=1039&context=ircs_reports <add> "AD": "adverb", <add> "AS": "aspect marker", <add> "BA": "把 in ba-construction", <add> # "CD": "cardinal number", <add> "CS": "subordinating conjunction", <add> "DEC": "的 in a relative clause", <add> "DEG": "associative 的", <add> "DER": "得 in V-de const. and V-de-R", <add> "DEV": "地 before VP", <add> "ETC": "for words 等, 等等", <add> # "FW": "foreign words" <add> "IJ": "interjection", <add> # "JJ": "other noun-modifier", <add> "LB": "被 in long bei-const", <add> "LC": "localizer", <add> "M": "measure word", <add> "MSP": "other particle", <add> # "NN": "common noun", <add> "NR": "proper noun", <add> "NT": "temporal noun", <add> "OD": "ordinal number", <add> "ON": "onomatopoeia", <add> "P": "preposition excluding 把 and 被", <add> "PN": "pronoun", <add> "PU": "punctuation", <add> "SB": "被 in short bei-const", <add> # "SP": "sentence-final particle", <add> "VA": "predicative adjective", <add> "VC": "是 (copula)", <add> "VE": "有 as the main verb", <add> "VV": "other verb", <ide> # Noun chunks <ide> "NP": "noun phrase", <ide> "PP": "prepositional phrase",
1
Python
Python
prevent the root logger from inialising
cbb8c66da328b1b000ec433234909d3f3fcda4da
<ide><path>spacy/util.py <ide> # fmt: on <ide> <ide> <del>logging.basicConfig(format="%(message)s") <ide> logger = logging.getLogger("spacy") <add>logger_stream_handler = logging.StreamHandler() <add>logger_stream_handler.setFormatter(logging.Formatter('%(message)s')) <add>logger.addHandler(logger_stream_handler) <ide> <ide> <ide> class ENV_VARS:
1
Text
Text
update pull request template
69d68a371ffd63d21de0ba7bde81f4a150bc37f8
<ide><path>.github/pull_request_template.md <del>### Summary <add><!-- <add>About this template <ide> <del><!-- Provide a general description of the code changes in your pull <del>request... were there any bugs you had fixed? If so, mention them. If <del>these bugs have open GitHub issues, be sure to tag them here as well, <del>to keep the conversation linked together. --> <add>The following template aims to help contributors write a good description for their pull requests. <add>We'd like you to provide a description of the changes in your pull request (i.e. bugs fixed or features added), motivation behind the changes, and complete the checklist below before opening a pull request. <ide> <del>### Other Information <add>Feel free to discard it if you need to (e.g. when you just fix a typo). --> <ide> <del><!-- If there's anything else that's important and relevant to your pull <del>request, mention that information here. This could include <del>benchmarks, or other information. <add>### Motivation / Background <ide> <del>If you are updating any of the CHANGELOG files or are asked to update the <del>CHANGELOG files by reviewers, please add the CHANGELOG entry at the top of the file. <add><!-- Describe why this Pull Request needs to be merged. What bug have you fixed? What feature have you added? Why is it important? --> <ide> <del>Finally, if your pull request affects documentation or any non-code <del>changes, guidelines for those changes are [available <del>here](https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation) <add>This Pull Request has been created because [REPLACE ME] <ide> <del>Thanks for contributing to Rails! --> <add>### Detail <add> <add>This Pull Request changes [REPLACE ME] <add> <add>### Additional information <add> <add><!-- Provide additional information such as benchmarks, reference to other repositories or alternative solutions. --> <add> <add>### Checklist <add> <add>Before submitting the PR make sure the following are checked: <add> <add>* [ ] This Pull Request is related to one change. Changes that are unrelated should be opened in separate PRs. <add>* [ ] There are no typos in commit messages and comments. <add>* [ ] Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: `[Fix #issue-number]` <add>* [ ] Feature branch is up-to-date with `main` (if not - rebase it). <add>* [ ] Pull request only contains one commit for bug fixes and small features. If it's a larger feature, multiple commits are permitted but must be descriptive. <add>* [ ] Tests are added if you fix a bug or add a feature. <add>* [ ] CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included. <add>* [ ] PR is not in a draft state. <add>* [ ] CI is passing. <ide> <ide> <!-- <ide> Note: Please avoid making *Draft* pull requests, as they still send <ide> notifications to everyone watching the Rails repo. <ide> Create a pull request when it is ready for review and feedback <ide> from the Rails team :). <del>--> <add> <add>If your pull request affects documentation or any non-code <add>changes, guidelines for those changes are [available <add>here](https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation) <add> <add>Thanks for contributing to Rails! -->
1
Text
Text
fix import in readme
3e8c91c5f8e142f341b407bdebfe4fe4e0930914
<ide><path>packages/react-dom/README.md <ide> npm install react react-dom <ide> ### In the browser <ide> <ide> ```js <del>import { createRoot } from 'react-dom'; <add>import { createRoot } from 'react-dom/client'; <ide> <ide> function App() { <ide> return <div>Hello World</div>;
1
Javascript
Javascript
add a timeout to address a ci failures
76e295e7ef2fabe993251b5a82266542cae7b3aa
<ide><path>test/configCases/plugins/profiling-plugin/index.js <ide> it("should have proper setup record inside of the json stream", (done) => { <ide> // convert json stream to valid <ide> var source = JSON.parse(fs.readFileSync(path.join(__dirname, "events.json"), "utf-8").toString() + "{}]"); <ide> expect(source[0].id).toEqual(1); <add> done(); <ide> }, 500) <ide> });
1
Javascript
Javascript
fix lint warnings in bundler index
90a696597cd4cab05e4ea57497b8026feebeb27f
<ide><path>packager/react-packager/src/Bundler/index.js <ide> <ide> const assert = require('assert'); <ide> const fs = require('fs'); <del>const path = require('path'); <ide> const Cache = require('../node-haste').Cache; <ide> const Transformer = require('../JSTransformer'); <ide> const Resolver = require('../Resolver'); <ide> const imageSize = require('image-size'); <ide> const version = require('../../../../package.json').version; <ide> const denodeify = require('denodeify'); <ide> <add>const { <add> sep: pathSeparator, <add> join: joinPath, <add> relative: relativePath, <add> dirname: pathDirname, <add> extname, <add>} = require('path'); <add> <ide> import AssetServer from '../AssetServer'; <ide> import Module from '../node-haste/Module'; <ide> import ResolutionResponse from '../node-haste/DependencyGraph/ResolutionResponse'; <ide> class Bundler { <ide> 'react-packager-cache', <ide> version, <ide> opts.cacheVersion, <del> opts.projectRoots.join(',').split(path.sep).join('-'), <add> opts.projectRoots.join(',').split(pathSeparator).join('-'), <ide> mtime, <ide> ]; <ide> <ide> class Bundler { <ide> projectRoots: opts.projectRoots, <ide> resetCache: opts.resetCache, <ide> transformCode: <del> (module, code, options) => <del> this._transformer.transformFile(module.path, code, options, transformCacheKey), <add> (module, code, transformCodeOptions) => this._transformer.transformFile( <add> module.path, <add> code, <add> transformCodeOptions, <add> transformCacheKey, <add> ), <ide> transformCacheKey, <ide> }); <ide> <ide> class Bundler { <ide> }); <ide> } <ide> <del> _sourceHMRURL(platform, path) { <add> _sourceHMRURL(platform, hmrpath) { <ide> return this._hmrURL( <ide> '', <ide> platform, <ide> 'bundle', <del> path, <add> hmrpath, <ide> ); <ide> } <ide> <del> _sourceMappingHMRURL(platform, path) { <add> _sourceMappingHMRURL(platform, hmrpath) { <ide> // Chrome expects `sourceURL` when eval'ing code <ide> return this._hmrURL( <ide> '\/\/# sourceURL=', <ide> platform, <ide> 'map', <del> path, <add> hmrpath, <ide> ); <ide> } <ide> <ide> class Bundler { <ide> } <ide> <ide> // Replaces '\' with '/' for Windows paths. <del> if (path.sep === '\\') { <add> if (pathSeparator === '\\') { <ide> filePath = filePath.replace(/\\/g, '/'); <ide> } <ide> <ide> const extensionStart = filePath.lastIndexOf('.'); <del> let resource = filePath.substring( <add> const resource = filePath.substring( <ide> matchingRoot.length, <ide> extensionStart !== -1 ? extensionStart : undefined, <ide> ); <ide> class Bundler { <ide> const numModuleSystemDependencies = <ide> this._resolver.getModuleSystemDependencies({dev, unbundle}).length; <ide> <add> const dependencyIndex = <add> (response.numPrependedDependencies || 0) + numModuleSystemDependencies; <ide> <del> const dependencyIndex = (response.numPrependedDependencies || 0) + numModuleSystemDependencies; <ide> if (dependencyIndex in response.dependencies) { <ide> entryFilePath = response.dependencies[dependencyIndex].path; <ide> } <ide> class Bundler { <ide> <ide> _generateAssetObjAndCode(module, assetPlugins, platform: mixed = null) { <ide> const relPath = getPathRelativeToRoot(this._projectRoots, module.path); <del> var assetUrlPath = path.join('/assets', path.dirname(relPath)); <add> var assetUrlPath = joinPath('/assets', pathDirname(relPath)); <ide> <ide> // On Windows, change backslashes to slashes to get proper URL path from file path. <del> if (path.sep === '\\') { <add> if (pathSeparator === '\\') { <ide> assetUrlPath = assetUrlPath.replace(/\\/g, '/'); <ide> } <ide> <ide> // Test extension against all types supported by image-size module. <ide> // If it's not one of these, we won't treat it as an image. <del> let isImage = [ <add> const isImage = [ <ide> 'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff' <del> ].indexOf(path.extname(module.path).slice(1)) !== -1; <add> ].indexOf(extname(module.path).slice(1)) !== -1; <ide> <ide> return Promise.all([ <ide> isImage ? sizeOf(module.path) : null, <ide> class Bundler { <ide> const assetData = res[1]; <ide> const asset = { <ide> __packager_asset: true, <del> fileSystemLocation: path.dirname(module.path), <add> fileSystemLocation: pathDirname(module.path), <ide> httpServerLocation: assetUrlPath, <ide> width: dimensions ? dimensions.width / module.resolution : undefined, <ide> height: dimensions ? dimensions.height / module.resolution : undefined, <ide> class Bundler { <ide> return asset; <ide> } <ide> <del> let [currentAssetPlugin, ...remainingAssetPlugins] = assetPlugins; <add> const [currentAssetPlugin, ...remainingAssetPlugins] = assetPlugins; <ide> /* $FlowFixMe: dynamic requires prevent static typing :'( */ <del> let assetPluginFunction = require(currentAssetPlugin); <del> let result = assetPluginFunction(asset); <add> const assetPluginFunction = require(currentAssetPlugin); <add> const result = assetPluginFunction(asset); <ide> <ide> // If the plugin was an async function, wait for it to fulfill before <ide> // applying the remaining plugins <ide> class Bundler { <ide> ? this._transformOptionsModule(mainModuleName, options, this) <ide> : null; <ide> return Promise.resolve(extraOptions) <del> .then(extraOptions => Object.assign(options, extraOptions)); <add> .then(extraOpts => Object.assign(options, extraOpts)); <ide> } <ide> <ide> getResolver() { <ide> class Bundler { <ide> <ide> function getPathRelativeToRoot(roots, absPath) { <ide> for (let i = 0; i < roots.length; i++) { <del> const relPath = path.relative(roots[i], absPath); <add> const relPath = relativePath(roots[i], absPath); <ide> if (relPath[0] !== '.') { <ide> return relPath; <ide> } <ide><path>packager/react-packager/src/node-haste/Module.js <ide> const extractRequires = require('./lib/extractRequires'); <ide> const invariant = require('invariant'); <ide> const isAbsolutePath = require('absolute-path'); <ide> const jsonStableStringify = require('json-stable-stringify'); <del>const path = require('path'); <add> <add>const {join: joinPath, relative: relativePath, extname} = require('path'); <ide> <ide> import type Cache from './Cache'; <ide> import type ModuleCache from './ModuleCache'; <ide> class Module { <ide> return this.path; <ide> } <ide> <del> return path.join(name, path.relative(p.root, this.path)).replace(/\\/g, '/'); <add> return joinPath(name, relativePath(p.root, this.path)).replace(/\\/g, '/'); <ide> }); <ide> }) <ide> ); <ide> class Module { <ide> } <ide> <ide> isJSON() { <del> return path.extname(this.path) === '.json'; <add> return extname(this.path) === '.json'; <ide> } <ide> <ide> isAsset() {
2
Python
Python
fix json serialization in merge layer
9c56b91548980f9c3aa8a5a4c7b41db3ed7f76bc
<ide><path>keras/engine/topology.py <ide> def get_config(self): <ide> <ide> if isinstance(self.mode, python_types.LambdaType): <ide> if py3: <del> mode = marshal.dumps(self.mode.__code__) <add> mode = marshal.dumps(self.mode.__code__).decode('raw_unicode_escape') <ide> else: <del> mode = marshal.dumps(self.mode.func_code) <add> mode = marshal.dumps(self.mode.func_code).decode('raw_unicode_escape') <ide> mode_type = 'lambda' <ide> elif callable(self.mode): <ide> mode = self.mode.__name__ <ide> def from_config(cls, config): <ide> if mode_type == 'function': <ide> mode = globals()[config['mode']] <ide> elif mode_type == 'lambda': <del> mode = marshal.loads(config['mode']) <add> mode = marshal.loads(config['mode'].encode('raw_unicode_escape')) <ide> mode = python_types.FunctionType(mode, globals()) <ide> else: <ide> mode = config['mode']
1
Mixed
Ruby
fix #to_json for unreadable io objects, fixes
813f8e333dabb2050d6b668b7bdd68b4979e8af4
<ide><path>activesupport/CHANGELOG.md <add>* `IO#to_json` now returns the `to_s` representation, rather than <add> attempting to convert to an array. This fixes a bug where `IO#to_json` <add> would raise an `IOError` when called on an unreadable object. <add> <add> Fixes #26132. <add> <add> *Paul Kuruvilla* <add> <ide> * `Hash#slice` now falls back to Ruby 2.5+'s built-in definition if defined. <ide> <ide> *Akira Matsuda* <ide><path>activesupport/lib/active_support/core_ext/object/json.rb <ide> def as_json(options = nil) #:nodoc: <ide> end <ide> end <ide> <add>class IO <add> def as_json(options = nil) #:nodoc: <add> to_s <add> end <add>end <add> <ide> class Range <ide> def as_json(options = nil) #:nodoc: <ide> to_s <ide><path>activesupport/test/json/encoding_test.rb <ide> def test_to_json_works_when_as_json_returns_NaN_number <ide> assert_equal '{"number":null}', NaNNumber.new.to_json <ide> end <ide> <add> def test_to_json_works_on_io_objects <add> assert_equal STDOUT.to_s.to_json, STDOUT.to_json <add> end <add> <ide> private <ide> <ide> def object_keys(json_object)
3
Python
Python
omit none in max_rows for np.loadtxt docstring
4577a69516bcc0406aaaa48304c8a2cbd82c58c9
<ide><path>numpy/lib/npyio.py <ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None, <ide> .. versionadded:: 1.14.0 <ide> max_rows : int, optional <ide> Read `max_rows` lines of content after `skiprows` lines. The default <del> (None) is to read all the lines. <add> is to read all the lines. <ide> <ide> .. versionadded:: 1.16.0 <ide>
1
Python
Python
remove dead code
8bb8e33db87b04640b5648eb96ce978585725d1a
<ide><path>libcloud/drivers/voxel.py <ide> def list_images(self): <ide> result = self.connection.request('', params=params).object <ide> return self._to_images(result) <ide> <del> name = kwargs["name"] <del> image = kwargs["image"] <del> size = kwargs["size"] <del> params = {'Action': 'RunInstances', <del> 'ImageId': image.id, <del> 'MinCount': kwargs.get('mincount','1'), <del> 'MaxCount': kwargs.get('maxcount','1'), <del> 'InstanceType': size.id} <del> <del> try: params['SecurityGroup'] = kwargs['securitygroup'] <del> except KeyError: pass <del> <del> try: params['KeyName'] = kwargs['keyname'] <del> except KeyError: pass <del> <del> object = self.connection.request('/', params=params).object <del> nodes = self._to_nodes(object, 'instancesSet/item') <del> <del> if len(nodes) == 1: <del> return nodes[0] <del> else: return nodes <del> <ide> def create_node(self, **kwargs): <ide> size = kwargs["size"] <ide> cores = size.ram / RAM_PER_CPU
1
Ruby
Ruby
remove scons audit
b917cccf195abd365185d867c0db1cf578b85990
<ide><path>Library/Homebrew/rubocops/text.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> problem %q(use "xcodebuild *args" instead of "system 'xcodebuild', *args") <ide> end <ide> <del> find_method_with_args(body_node, :system, "scons") do <del> problem "use \"scons *args\" instead of \"system 'scons', *args\"" <del> end <del> <ide> find_method_with_args(body_node, :system, "go", "get") do <ide> problem "Do not use `go get`. Please ask upstream to implement Go vendoring" <ide> end <ide><path>Library/Homebrew/test/rubocops/text_spec.rb <ide> def install <ide> RUBY <ide> end <ide> <del> it "When scons is executed" do <del> expect_offense(<<~RUBY) <del> class Foo < Formula <del> url "https://brew.sh/foo-1.0.tgz" <del> homepage "https://brew.sh" <del> <del> def install <del> system "scons", "foo", "bar" <del> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ use \"scons *args\" instead of \"system 'scons', *args\" <del> end <del> end <del> RUBY <del> end <del> <ide> it "When plist_options are not defined when using a formula-defined plist", :ruby23 do <ide> expect_offense(<<~RUBY) <ide> class Foo < Formula
2
Text
Text
guide solution for work with data in d3
a8334f88c0e3da317a12f86029a8aabf6e220d56
<ide><path>guide/english/certifications/data-visualization/data-visualization-with-d3/work-with-data-in-d3/index.md <ide> title: Work with Data in D3 <ide> --- <ide> ## Work with Data in D3 <add>![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:") <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/data-visualization/data-visualization-with-d3/work-with-data-in-d3/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>### Problem Explanation: <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add>This challenge uses the `select`, `selectAll`, `append`, and `text` methods seen in previous challenges. It adds 2 new D3 methods: `data` and `enter` to target the given data and display an element on the page for each datum <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>#### Relevant Links <add> <add>From the official D3 documentation: <add>* [data](https://github.com/d3/d3-selection/blob/master/README.md#selection_data) <add>* [enter](https://github.com/d3/d3-selection/blob/master/README.md#selection_enter) <add> <add>## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1 <add> <add>* After selecting the correct HTML nodes, use the `data` method with the `dataset` variable passed as an argument to make the D3 object aware of the data <add> <add>> _try to solve the problem now_ <add> <add>## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2 <add> <add>* Use the `enter` method to ensure that your HTML document has enough elements of the type you specified in `selectAll` for each datum <add> <add>> _try to solve the problem now_ <add> <add>## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3 <add> <add>* Now that the D3 object is aware of your data and has created enough elements for each datum, `append` the elements of the specified type and add the `text` required in the instructions <add> <add>> _try to solve the problem now_ <add> <add>## Spoiler Alert! <add> <add>**Solution ahead!** <add> <add>## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution: <add>```javascript <add><body> <add> <script> <add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9]; <add> <add> d3.select('body').selectAll('h2') <add> .data(dataset) <add> .enter() <add> .append('h2') <add> .text('New Title'); <add> <add> </script> <add></body> <add>``` <add> <add># Code Explanation: <add> <add>* `d3` targets the D3 object <add>* `select('body')` is used to `select` the 'body' element of the HTML document <add>* `selectAll('h2')` is used to `selectAll` of the 'h2' elements that are children to 'body' <add>* `data(dataset)` calls the D3 `data` method and uses the given dataset as an argument <add>* `enter()` uses the D3 `enter` method to check the current number of elements selected and create any missing ones according to the amount needed by the dataset <add>* `append('h2')` takes these newly created elements from `enter` and ensures they are created as 'h2' elements <add>* `text('New Title')` changes the text of every element selected to 'New Title' <add>* The dataset contains 9 datum, so the final solution should show 9 'h2' elements with the text 'New Title' <add> <add> <add>## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS: <add> <add>* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution. <add>* Add an explanation of your solution. <add>* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:") <add>* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_) <add> <add>> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.
1
Ruby
Ruby
add the other test back in
0029ad2929d1ece249047b381299e63ba9b858fa
<ide><path>Library/Homebrew/test/test_dependency_collector.rb <ide> def test_x11_min_version_and_tag <ide> assert_predicate dep, :optional? <ide> end <ide> <add> def test_ant_dep <add> @d.add :ant => :build <add> assert_equal find_dependency("ant"), Dependency.new("ant", [:build]) <add> end <add> <ide> def test_raises_typeerror_for_unknown_classes <ide> assert_raises(TypeError) { @d.add(Class.new) } <ide> end
1
Javascript
Javascript
convert the method parameter to lowercase
e4e32120cec8ba53fc1f69415d6a8ac10b9c9756
<ide><path>lib/core/Axios.js <ide> Axios.prototype.request = function request(config) { <ide> } <ide> <ide> config = utils.merge(defaults, this.defaults, { method: 'get' }, config); <add> config.method = config.method.toLowerCase(); <ide> <ide> // Support baseURL config <ide> if (config.baseURL && !isAbsoluteURL(config.url)) { <ide><path>test/specs/requests.spec.js <ide> describe('requests', function () { <ide> }); <ide> }); <ide> <add> it('should treat method value as lowercase string', function (done) { <add> axios({ <add> url: '/foo', <add> method: 'POST' <add> }).then(function (response) { <add> expect(response.config.method).toBe('post'); <add> done(); <add> }); <add> <add> getAjaxRequest().then(function (request) { <add> request.respondWith({ <add> status: 200 <add> }); <add> }); <add> }); <add> <ide> it('should allow string arg as url, and config arg', function (done) { <ide> axios.post('/foo'); <ide>
2
Java
Java
fix crash with non-zero blurradius less than 1
dc01eff72d23e1dd3f7ecf30859992ee3bf7c664
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java <ide> public void onFailure(String id, Throwable throwable) { <ide> } <ide> <ide> public void setBlurRadius(float blurRadius) { <del> if (blurRadius == 0) { <add> int pixelBlurRadius = (int) PixelUtil.toPixelFromDIP(blurRadius); <add> if (pixelBlurRadius == 0) { <ide> mIterativeBoxBlurPostProcessor = null; <ide> } else { <del> mIterativeBoxBlurPostProcessor = <del> new IterativeBoxBlurPostProcessor((int) PixelUtil.toPixelFromDIP(blurRadius)); <add> mIterativeBoxBlurPostProcessor = new IterativeBoxBlurPostProcessor(pixelBlurRadius); <ide> } <ide> mIsDirty = true; <ide> }
1
Javascript
Javascript
remove unreachable return statement
14b1297b512f71ee7c6a4fcd5b1397b4d70d52ee
<ide><path>src/ng/sce.js <ide> function $SceDelegateProvider() { <ide> } else { <ide> throw $sceMinErr('isecrurl', <ide> 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', maybeTrusted.toString()); <del> return; <ide> } <ide> } else if (type === SCE_CONTEXTS.HTML) { <ide> return htmlSanitizer(maybeTrusted);
1
Text
Text
add advantage of exception handling to the article
5ff05b9832763424814b1939bb8b426bb26022f2
<ide><path>guide/english/java/exception-handling/index.md <ide> All exception and errors types are sub classes of class Throwable, which is base <ide> <ide> ## How to use try-catch clause <ide> <del>``` <add>```java <ide> try { <ide> // block of code to monitor for errors <ide> // the code you think can raise an exception <ide> finally { <ide> // block of code to be executed after try block ends <ide> } <ide> ``` <add>## Advantage of Exception Handling <add>The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application which is why we use exception handling.
1
Go
Go
skip if client < 1.40
1ada1c83914dd4694570cf2ea1ce240bb4a8d183
<ide><path>integration/container/ipcmode_linux_test.go <ide> func TestDaemonIpcModeShareableFromConfig(t *testing.T) { <ide> // by default, even when the daemon default is private. <ide> func TestIpcModeOlderClient(t *testing.T) { <ide> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "requires a daemon with DefaultIpcMode: private") <add> c := testEnv.APIClient() <add> skip.If(t, versions.LessThan(c.ClientVersion(), "1.40"), "requires client API >= 1.40") <add> <ide> t.Parallel() <ide> <ide> ctx := context.Background() <ide> <ide> // pre-check: default ipc mode in daemon is private <del> c := testEnv.APIClient() <ide> cID := container.Create(t, ctx, c, container.WithAutoRemove) <ide> <ide> inspect, err := c.ContainerInspect(ctx, cID)
1
Text
Text
fix outdated documentation for `family` property
4ad342a5a55611a5c299da992ac473b8a0349f8f
<ide><path>doc/api/dgram.md <ide> exist and calls such as `socket.address()` and `socket.setTTL()` will fail. <ide> <ide> <!-- YAML <ide> added: v0.1.99 <add>changes: <add> - version: v18.0.0 <add> pr-url: https://github.com/nodejs/node/pull/41431 <add> description: The `family` property now returns a number instead of a string. <ide> --> <ide> <ide> The `'message'` event is emitted when a new datagram is available on a socket. <ide> The event handler function is passed two arguments: `msg` and `rinfo`. <ide> * `msg` {Buffer} The message. <ide> * `rinfo` {Object} Remote address information. <ide> * `address` {string} The sender address. <del> * `family` {string} The address family (`'IPv4'` or `'IPv6'`). <add> * `family` {number} The address family (`4` for IPv4 or `6` for IPv6). <ide> * `port` {number} The sender port. <ide> * `size` {number} The message size. <ide> <ide><path>doc/api/net.md <ide> Emitted when the server has been bound after calling [`server.listen()`][]. <ide> <ide> <!-- YAML <ide> added: v0.1.90 <add>changes: <add> - version: v18.0.0 <add> pr-url: https://github.com/nodejs/node/pull/41431 <add> description: The `family` property now returns a number instead of a string. <ide> --> <ide> <ide> * Returns: {Object|string|null} <ide> <ide> Returns the bound `address`, the address `family` name, and `port` of the server <ide> as reported by the operating system if listening on an IP socket <ide> (useful to find which port was assigned when getting an OS-assigned address): <del>`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. <add>`{ port: 12346, family: 4, address: '127.0.0.1' }`. <ide> <ide> For a server listening on a pipe or Unix domain socket, the name is returned <ide> as a string. <ide> Not applicable to Unix sockets. <ide> <ide> * `err` {Error|null} The error object. See [`dns.lookup()`][]. <ide> * `address` {string} The IP address. <del>* `family` {string|null} The address type. See [`dns.lookup()`][]. <add>* `family` {number|null} The address type. See [`dns.lookup()`][]. <ide> * `host` {string} The host name. <ide> <ide> ### Event: `'ready'` <ide> See also: [`socket.setTimeout()`][]. <ide> <ide> <!-- YAML <ide> added: v0.1.90 <add>changes: <add> - version: v18.0.0 <add> pr-url: https://github.com/nodejs/node/pull/41431 <add> description: The `family` property now returns a number instead of a string. <ide> --> <ide> <ide> * Returns: {Object} <ide> <ide> Returns the bound `address`, the address `family` name and `port` of the <ide> socket as reported by the operating system: <del>`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` <add>`{ port: 12346, family: 4, address: '127.0.0.1' }` <ide> <ide> ### `socket.bufferSize` <ide> <ide><path>doc/api/os.md <ide> always `[0, 0, 0]`. <ide> <ide> <!-- YAML <ide> added: v0.6.0 <add>changes: <add> - version: v18.0.0 <add> pr-url: https://github.com/nodejs/node/pull/41431 <add> description: The `family` property now returns a number instead of a string. <ide> --> <ide> <ide> * Returns: {Object} <ide> The properties available on the assigned network address object include: <ide> <ide> * `address` {string} The assigned IPv4 or IPv6 address <ide> * `netmask` {string} The IPv4 or IPv6 network mask <del>* `family` {string} Either `IPv4` or `IPv6` <add>* `family` {number} Either `4` (for IPv4) or `6` (for IPv6) <ide> * `mac` {string} The MAC address of the network interface <ide> * `internal` {boolean} `true` if the network interface is a loopback or <ide> similar interface that is not remotely accessible; otherwise `false` <ide> * `scopeid` {number} The numeric IPv6 scope ID (only specified when `family` <del> is `IPv6`) <add> is `6`) <ide> * `cidr` {string} The assigned IPv4 or IPv6 address with the routing prefix <ide> in CIDR notation. If the `netmask` is invalid, this property is set <ide> to `null`. <ide> The properties available on the assigned network address object include: <ide> { <ide> address: '127.0.0.1', <ide> netmask: '255.0.0.0', <del> family: 'IPv4', <add> family: 4, <ide> mac: '00:00:00:00:00:00', <ide> internal: true, <ide> cidr: '127.0.0.1/8' <ide> }, <ide> { <ide> address: '::1', <ide> netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', <del> family: 'IPv6', <add> family: 6, <ide> mac: '00:00:00:00:00:00', <ide> scopeid: 0, <ide> internal: true, <ide> The properties available on the assigned network address object include: <ide> { <ide> address: '192.168.1.108', <ide> netmask: '255.255.255.0', <del> family: 'IPv4', <add> family: 4, <ide> mac: '01:02:03:0a:0b:0c', <ide> internal: false, <ide> cidr: '192.168.1.108/24' <ide> }, <ide> { <ide> address: 'fe80::a00:27ff:fe4e:66a1', <ide> netmask: 'ffff:ffff:ffff:ffff::', <del> family: 'IPv6', <add> family: 6, <ide> mac: '01:02:03:0a:0b:0c', <ide> scopeid: 1, <ide> internal: false, <ide><path>doc/api/tls.md <ide> tlsSocket.once('session', (session) => { <ide> <ide> <!-- YAML <ide> added: v0.11.4 <add>changes: <add> - version: v18.0.0 <add> pr-url: https://github.com/nodejs/node/pull/41431 <add> description: The `family` property now returns a number instead of a string. <ide> --> <ide> <ide> * Returns: {Object} <ide> <ide> Returns the bound `address`, the address `family` name, and `port` of the <ide> underlying socket as reported by the operating system: <del>`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. <add>`{ port: 12346, family: 4, address: '127.0.0.1' }`. <ide> <ide> ### `tlsSocket.authorizationError` <ide>
4
Python
Python
remove the incorrect exception 'm.h.t'
648dc607556fea5409c288bf3cead42ffa79bc5b
<ide><path>spacy/lang/da/tokenizer_exceptions.py <ide> "lic.", "lign.", "lin.", "ling.merc.", "litt.", "Ll.", "loc.cit.", <ide> "lok.", "lrs.", "ltr.", "m/s", "M/S", "m.a.o.", "m.fl.", "m.m.", "m.v.", <ide> "m.v.h.", "Mag.", "maks.", "md.", "mdr.", "mdtl.", "mezz.", "mfl.", <del> "m.h.p.", "m.h.t", "m.h.t.", "mht.", "mik.", "min.", "mio.", "modt.", "Mr.", <add> "m.h.p.", "m.h.t.", "mht.", "mik.", "min.", "mio.", "modt.", "Mr.", <ide> "mrk.", "mul.", "mv.", "n.br.", "n.f.", "nat.", "nb.", "Ndr.", <ide> "nedenst.", "nl.", "nr.", "Nr.", "nto.", "nuv.", "o/m", "o.a.", "o.fl.", <ide> "o.h.", "o.l.", "o.lign.", "o.m.a.", "o.s.fr.", "obl.", "obs.",
1
Text
Text
update serverrendering.md to react 0.14
83992b59fcce20dbf1c145a803a73753dd3d0341
<ide><path>docs/recipes/ServerRendering.md <ide> The first thing that we need to do on every request is create a new Redux store <ide> <ide> When rendering, we will wrap `<App />`, our root component, inside a `<Provider>` to make the store available to all components in the component tree, as we saw in [Usage with React](../basics/UsageWithReact.md). <ide> <del>The key step in server side rendering is to render the initial HTML of our component _**before**_ we send it to the client side. To do this, we use [React.renderToString()](https://facebook.github.io/react/docs/top-level-api.html#react.rendertostring). <add>The key step in server side rendering is to render the initial HTML of our component _**before**_ we send it to the client side. To do this, we use [ReactDOMServer.renderToString()](https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring). <ide> <ide> We then get the initial state from our Redux store using [`store.getState()`](../api/Store.md#getState). We will see how this is passed along in our `renderFullPage` function. <ide> <ide> ```js <add>import { renderToString } from 'react-dom/server'; <add> <ide> function handleRender(req, res) { <ide> // Create a new Redux store instance <ide> const store = createStore(counterApp); <ide> <ide> // Render the component to a string <del> const html = React.renderToString( <add> const html = renderToString( <ide> <Provider store={store}> <del> {() => <App />} <add> <App /> <ide> </Provider> <ide> ); <ide> <ide> Let’s take a look at our new client file: <ide> <ide> ```js <ide> import React from 'react'; <add>import { render } from 'react-dom'; <ide> import { createStore } from 'redux'; <ide> import { Provider } from 'react-redux'; <ide> import App from './containers/App'; <ide> const initialState = window.__INITIAL_STATE__; <ide> // Create Redux store with initial state <ide> const store = createStore(counterApp, initialState); <ide> <del>React.render( <add>render( <ide> <Provider store={store}> <del> {() => <App />} <add> <App /> <ide> </Provider>, <ide> document.getElementById('root') <ide> ); <ide> ``` <ide> <ide> You can set up your build tool of choice (Webpack, Browserify, etc.) to compile a bundle file into `dist/bundle.js`. <ide> <del>When the page loads, the bundle file will be started up and [`React.render()`](https://facebook.github.io/react/docs/top-level-api.html#react.render) will hook into the `data-react-id` attributes from the server-rendered HTML. This will connect our newly-started React instance to the virtual DOM used on the server. Since we have the same initial state for our Redux store and used the same code for all our view components, the result will be the same real DOM. <add>When the page loads, the bundle file will be started up and [`ReactDOM.render()`](https://facebook.github.io/react/docs/top-level-api.html#reactdom.render) will hook into the `data-react-id` attributes from the server-rendered HTML. This will connect our newly-started React instance to the virtual DOM used on the server. Since we have the same initial state for our Redux store and used the same code for all our view components, the result will be the same real DOM. <ide> <ide> And that’s it! That is all we need to do to implement server side rendering. <ide> <ide> The request contains information about the URL requested, including any query pa <ide> <ide> ```js <ide> import qs from 'qs'; // Add this at the top of the file <add>import { renderToString } from 'react-dom/server'; <ide> <ide> function handleRender(req, res) { <ide> // Read the counter from the request, if provided <ide> function handleRender(req, res) { <ide> const store = createStore(counterApp, initialState); <ide> <ide> // Render the component to a string <del> const html = React.renderToString( <add> const html = renderToString( <ide> <Provider store={store}> <del> {() => <App />} <add> <App /> <ide> </Provider> <ide> ); <ide> <ide> On the server side, we simply wrap our existing code in the `fetchCounter` and r <ide> ```js <ide> // Add this to our imports <ide> import { fetchCounter } from './api/counter'; <add>import { renderToString } from 'react-dom/server'; <ide> <ide> function handleRender(req, res) { <ide> // Query our mock API asynchronously <ide> function handleRender(req, res) { <ide> const store = createStore(counterApp, initialState); <ide> <ide> // Render the component to a string <del> const html = React.renderToString( <add> const html = renderToString( <ide> <Provider store={store}> <del> {() => <App />} <add> <App /> <ide> </Provider> <ide> ); <ide>
1
Python
Python
add doc string
4812a5a7678fffef1751ba45ad5ae0b5e8854b70
<ide><path>examples/single_model_scripts/run_multiple_choice.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. <del>""" Finetuning the library models for multiple choice (Bert, XLM, XLNet).""" <add>""" Finetuning the library models for multiple choice (Bert, Roberta, XLNet).""" <ide> <ide> from __future__ import absolute_import, division, print_function <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide> <del>ALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys()) for conf in (BertConfig, XLNetConfig)), ()) <add>ALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys()) for conf in (BertConfig, XLNetConfig, RobertaConfig)), ()) <ide> <ide> MODEL_CLASSES = { <ide> 'bert': (BertConfig, BertForMultipleChoice, BertTokenizer), <ide> def train(args, train_dataset, model, tokenizer): <ide> <ide> <ide> def evaluate(args, model, tokenizer, prefix="", test=False): <del> # Loop to handle MNLI double evaluation (matched, mis-matched) <ide> eval_task_names = (args.task_name,) <ide> eval_outputs_dirs = (args.output_dir,) <ide> <ide> def evaluate(args, model, tokenizer, prefix="", test=False): <ide> result = {"eval_acc": acc, "eval_loss": eval_loss} <ide> results.update(result) <ide> <del> output_eval_file = os.path.join(eval_output_dir, "is_test_" + str(test) + "_eval_results.txt") <add> output_eval_file = os.path.join(eval_output_dir, "is_test_" + str(test).lower() + "_eval_results.txt") <ide> <ide> with open(output_eval_file, "w") as writer: <ide> logger.info("***** Eval results {} *****".format(str(prefix) + " is test:" + str(test))) <ide> def main(): <ide> if not args.do_train: <ide> args.output_dir = args.model_name_or_path <ide> checkpoints = [args.output_dir] <del> if args.eval_all_checkpoints: #can not use this to do test!! just for different paras <del> checkpoints = list(os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + '/**/' + WEIGHTS_NAME, recursive=True))) <del> logging.getLogger("pytorch_transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging <add> # if args.eval_all_checkpoints: # can not use this to do test!! <add> # checkpoints = list(os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + '/**/' + WEIGHTS_NAME, recursive=True))) <add> # logging.getLogger("pytorch_transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging <ide> logger.info("Evaluate the following checkpoints: %s", checkpoints) <ide> for checkpoint in checkpoints: <ide> global_step = checkpoint.split('-')[-1] if len(checkpoints) > 1 else "" <ide><path>examples/single_model_scripts/utils_multiple_choice.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. <del>""" BERT classification fine-tuning: utilities to work with GLUE tasks """ <add>""" BERT multiple choice fine-tuning: utilities to work with multiple choice tasks of reading comprehension """ <ide> <ide> from __future__ import absolute_import, division, print_function <ide> <ide> def __init__(self, example_id, question, contexts, endings, label=None): <ide> """Constructs a InputExample. <ide> <ide> Args: <del> guid: Unique id for the example. <del> text_a: string. The untokenized text of the first sequence. For single <del> sequence tasks, only this sequence must be specified. <del> text_b: (Optional) string. The untokenized text of the second sequence. <del> Only must be specified for sequence pair tasks. <add> example_id: Unique id for the example. <add> contexts: list of str. The untokenized text of the first sequence (context of corresponding question). <add> question: string. The untokenized text of the second sequence (qustion). <add> endings: list of str. multiple choice's options. Its length must be equal to contexts' length. <ide> label: (Optional) string. The label of the example. This should be <ide> specified for train and dev examples, but not for test examples. <ide> """ <ide> def __init__(self, <ide> <ide> <ide> class DataProcessor(object): <del> """Base class for data converters for sequence classification data sets.""" <add> """Base class for data converters for multiple choice data sets.""" <ide> <ide> def get_train_examples(self, data_dir): <ide> """Gets a collection of `InputExample`s for the train set.""" <ide> def get_dev_examples(self, data_dir): <ide> raise NotImplementedError() <ide> <ide> def get_test_examples(self, data_dir): <del> """Gets a collection of `InputExample`s for the dev set.""" <add> """Gets a collection of `InputExample`s for the test set.""" <ide> raise NotImplementedError() <ide> <ide> def get_labels(self): <ide> def get_labels(self): <ide> <ide> <ide> class RaceProcessor(DataProcessor): <del> """Processor for the MRPC data set (GLUE version).""" <add> """Processor for the RACE data set.""" <ide> <ide> def get_train_examples(self, data_dir): <ide> """See base class.""" <ide> def _create_examples(self, lines, set_type): <ide> InputExample( <ide> example_id=race_id, <ide> question=question, <del> contexts=[article, article, article, article], <add> contexts=[article, article, article, article], # this is not efficient but convenient <ide> endings=[options[0], options[1], options[2], options[3]], <ide> label=truth)) <ide> return examples <ide> <ide> class SwagProcessor(DataProcessor): <del> """Processor for the MRPC data set (GLUE version).""" <add> """Processor for the SWAG data set.""" <ide> <ide> def get_train_examples(self, data_dir): <ide> """See base class.""" <ide> def get_dev_examples(self, data_dir): <ide> <ide> def get_test_examples(self, data_dir): <ide> """See base class.""" <del> logger.info("LOOKING AT {} test".format(data_dir)) <add> logger.info("LOOKING AT {} dev".format(data_dir)) <add> raise ValueError( <add> "For swag testing, the input file does not contain a label column. It can not be tested in current code" <add> "setting!" <add> ) <ide> return self._create_examples(self._read_csv(os.path.join(data_dir, "test.csv")), "test") <del> <ide> def get_labels(self): <ide> """See base class.""" <ide> return ["0", "1", "2", "3"] <ide> def _create_examples(self, lines, type): <ide> <ide> <ide> class ArcProcessor(DataProcessor): <del> """Processor for the MRPC data set (GLUE version).""" <add> """Processor for the ARC data set (request from allennlp).""" <ide> <ide> def get_train_examples(self, data_dir): <ide> """See base class.""" <ide> def _read_json(self, input_file): <ide> def _create_examples(self, lines, type): <ide> """Creates examples for the training and dev sets.""" <ide> <add> #There are two types of labels. They should be normalized <ide> def normalize(truth): <ide> if truth in "ABCD": <ide> return ord(truth) - ord("A") <ide> def normalize(truth): <ide> four_choice = 0 <ide> five_choice = 0 <ide> other_choices = 0 <add> # we deleted example which has more than or less than four choices <ide> for line in tqdm.tqdm(lines, desc="read arc data"): <ide> data_raw = json.loads(line.strip("\n")) <ide> if len(data_raw["question"]["choices"]) == 3: <ide> def normalize(truth): <ide> question = question_choices["stem"] <ide> id = data_raw["id"] <ide> options = question_choices["choices"] <del> <ide> if len(options) == 4: <ide> examples.append( <ide> InputExample( <ide> def convert_examples_to_features(examples, label_list, max_seq_length, <ide> tokens_a = tokenizer.tokenize(context) <ide> tokens_b = None <ide> if example.question.find("_") != -1: <add> #this is for cloze question <ide> tokens_b = tokenizer.tokenize(example.question.replace("_", ending)) <ide> else: <del> tokens_b = tokenizer.tokenize(example.question) <del> tokens_b += [sep_token] <del> if sep_token_extra: <del> tokens_b += [sep_token] <del> tokens_b += tokenizer.tokenize(ending) <add> tokens_b = tokenizer.tokenize(example.question + " " + ending) <add> # you can add seq token between quesiotn and ending. This does not make too much difference. <add> # tokens_b = tokenizer.tokenize(example.question) <add> # tokens_b += [sep_token] <add> # if sep_token_extra: <add> # tokens_b += [sep_token] <add> # tokens_b += tokenizer.tokenize(ending) <ide> <ide> special_tokens_count = 4 if sep_token_extra else 3 <ide> _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - special_tokens_count) <ide> def _truncate_seq_pair(tokens_a, tokens_b, max_length): <ide> # one token at a time. This makes more sense than truncating an equal percent <ide> # of tokens from each, since if one sequence is very short then each token <ide> # that's truncated likely contains more information than a longer sequence. <add> <add> # However, since we'd better not to remove tokens of options and questions, you can choose to use a bigger <add> # length or only pop from context <ide> while True: <ide> total_length = len(tokens_a) + len(tokens_b) <ide> if total_length <= max_length: <ide> break <del> # if len(tokens_a) > len(tokens_b): <del> # tokens_a.pop() <del> # else: <del> # tokens_b.pop() <del> tokens_a.pop() <add> if len(tokens_a) > len(tokens_b): <add> tokens_a.pop() <add> else: <add> logger.info('Attention! you are removing from question + options. Try to use a bigger max seq length!') <add> tokens_b.pop() <ide> <ide> <ide> processors = { <ide><path>pytorch_transformers/modeling_roberta.py <ide> class RobertaForSequenceClassification(BertPreTrainedModel): <ide> <ide> Examples:: <ide> <del> tokenizer = RoertaTokenizer.from_pretrained('roberta-base') <add> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') <ide> model = RobertaForSequenceClassification.from_pretrained('roberta-base') <ide> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <ide> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 <ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=No <ide> <ide> return outputs # (loss), logits, (hidden_states), (attentions) <ide> <del> <add>@add_start_docstrings("""Roberta Model with a multiple choice classification head on top (a linear layer on top of <add> the pooled output and a softmax) e.g. for RocStories/SWAG tasks. """, <add> ROBERTA_START_DOCSTRING, ROBERTA_INPUTS_DOCSTRING) <ide> class RobertaForMultipleChoice(BertPreTrainedModel): <add> r""" <add> Inputs: <add> **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, num_choices, sequence_length)``: <add> Indices of input sequence tokens in the vocabulary. <add> The second dimension of the input (`num_choices`) indicates the number of choices to score. <add> To match pre-training, RoBerta input sequence should be formatted with [CLS] and [SEP] tokens as follows: <add> <add> (a) For sequence pairs: <add> <add> ``tokens: [CLS] is this jack ##son ##ville ? [SEP] [SEP] no it is not . [SEP]`` <add> <add> ``token_type_ids: 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1`` <add> <add> (b) For single sequences: <add> <add> ``tokens: [CLS] the dog is hairy . [SEP]`` <add> <add> ``token_type_ids: 0 0 0 0 0 0 0`` <add> <add> Indices can be obtained using :class:`pytorch_transformers.BertTokenizer`. <add> See :func:`pytorch_transformers.PreTrainedTokenizer.encode` and <add> :func:`pytorch_transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details. <add> **token_type_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, num_choices, sequence_length)``: <add> Segment token indices to indicate first and second portions of the inputs. <add> The second dimension of the input (`num_choices`) indicates the number of choices to score. <add> Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1`` <add> **attention_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, num_choices, sequence_length)``: <add> Mask to avoid performing attention on padding token indices. <add> The second dimension of the input (`num_choices`) indicates the number of choices to score. <add> Mask values selected in ``[0, 1]``: <add> ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens. <add> **head_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``: <add> Mask to nullify selected heads of the self-attention modules. <add> Mask values selected in ``[0, 1]``: <add> ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**. <add> **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``: <add> Labels for computing the multiple choice classification loss. <add> Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension <add> of the input tensors. (see `input_ids` above) <add> <add> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: <add> **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: <add> Classification loss. <add> **classification_scores**: ``torch.FloatTensor`` of shape ``(batch_size, num_choices)`` where `num_choices` is the size of the second dimension <add> of the input tensors. (see `input_ids` above). <add> Classification scores (before SoftMax). <add> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``) <add> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings) <add> of shape ``(batch_size, sequence_length, hidden_size)``: <add> Hidden-states of the model at the output of each layer plus the initial embedding outputs. <add> **attentions**: (`optional`, returned when ``config.output_attentions=True``) <add> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: <add> Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. <add> <add> Examples:: <add> <add> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') <add> model = RobertaForMultipleChoice.from_pretrained('roberta-base') <add> choices = ["Hello, my dog is cute", "Hello, my cat is amazing"] <add> input_ids = torch.tensor([tokenizer.encode(s, add_special_tokens=True) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices <add> labels = torch.tensor(1).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, labels=labels) <add> loss, classification_scores = outputs[:2] <add> <add> """ <ide> config_class = RobertaConfig <ide> pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP <ide> base_model_prefix = "roberta" <ide><path>pytorch_transformers/modeling_xlnet.py <ide> def forward(self, input_ids, token_type_ids=None, input_mask=None, attention_mas <ide> <ide> return outputs # return (loss), logits, mems, (hidden states), (attentions) <ide> <del> <add>@add_start_docstrings("""XLNet Model with a multiple choice classification head on top (a linear layer on top of <add> the pooled output and a softmax) e.g. for RACE/SWAG tasks. """, <add> XLNET_START_DOCSTRING, XLNET_INPUTS_DOCSTRING) <ide> class XLNetForMultipleChoice(XLNetPreTrainedModel): <ide> r""" <add> Inputs: <add> **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, num_choices, sequence_length)``: <add> Indices of input sequence tokens in the vocabulary. <add> The second dimension of the input (`num_choices`) indicates the number of choices to scores. <add> **token_type_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, num_choices, sequence_length)``: <add> Segment token indices to indicate first and second portions of the inputs. <add> The second dimension of the input (`num_choices`) indicates the number of choices to score. <add> Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1`` <add> **attention_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, num_choices, sequence_length)``: <add> Mask to avoid performing attention on padding token indices. <add> The second dimension of the input (`num_choices`) indicates the number of choices to score. <add> Mask values selected in ``[0, 1]``: <add> ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens. <add> **head_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``: <add> Mask to nullify selected heads of the self-attention modules. <add> Mask values selected in ``[0, 1]``: <add> ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**. <add> **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``: <add> Labels for computing the multiple choice classification loss. <add> Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension <add> of the input tensors. (see `input_ids` above) <add> <add> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: <add> **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: <add> Classification loss. <add> **classification_scores**: ``torch.FloatTensor`` of shape ``(batch_size, num_choices)`` where `num_choices` is the size of the second dimension <add> of the input tensors. (see `input_ids` above). <add> Classification scores (before SoftMax). <add> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``) <add> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings) <add> of shape ``(batch_size, sequence_length, hidden_size)``: <add> Hidden-states of the model at the output of each layer plus the initial embedding outputs. <add> **attentions**: (`optional`, returned when ``config.output_attentions=True``) <add> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: <add> Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. <add> <add> Examples:: <add> <add> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') <add> model = XLNetForMultipleChoice.from_pretrained('xlnet-base-cased') <add> choices = ["Hello, my dog is cute", "Hello, my cat is amazing"] <add> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices <add> labels = torch.tensor(1).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, labels=labels) <add> loss, classification_scores = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide> class XLNetForQuestionAnswering(XLNetPreTrainedModel): <ide> <ide> Examples:: <ide> <del> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <add> tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') <ide> model = XLMForQuestionAnswering.from_pretrained('xlnet-large-cased') <ide> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <ide> start_positions = torch.tensor([1])
4
PHP
PHP
update requesthandler tests for new view classes
b0d0e06b9739ee849694eb091d5a622df7b4a509
<ide><path>lib/Cake/Test/Case/Controller/Component/RequestHandlerComponentTest.php <ide> public function testRenderAsWithAttachment() { <ide> <ide> $this->RequestHandler->renderAs($this->Controller, 'xml', array('attachment' => 'myfile.xml')); <ide> <del> $expected = 'RequestHandlerTest' . DS . 'xml'; <del> $this->assertEquals($expected, $this->Controller->viewPath); <add> $this->assertEquals('Xml', $this->Controller->viewClass); <ide> } <ide> <ide> /**
1
Javascript
Javascript
improve date format
17dcc40ffd5d7dcce06170a0b7d4a53375628082
<ide><path>src/locale/sl.js <ide> export default moment.defineLocale('sl', { <ide> longDateFormat : { <ide> LT : 'H:mm', <ide> LTS : 'H:mm:ss', <del> L : 'DD.MM.YYYY', <add> L : 'DD. MM. YYYY', <ide> LL : 'D. MMMM YYYY', <ide> LLL : 'D. MMMM YYYY H:mm', <ide> LLLL : 'dddd, D. MMMM YYYY H:mm' <ide><path>src/test/locale/sl.js <ide> test('format', function (assert) { <ide> ['a A', 'pm PM'], <ide> ['[the] DDDo [day of the year]', 'the 45. day of the year'], <ide> ['LTS', '15:25:50'], <del> ['L', '14.02.2010'], <add> ['L', '14. 02. 2010'], <ide> ['LL', '14. februar 2010'], <ide> ['LLL', '14. februar 2010 15:25'], <ide> ['LLLL', 'nedelja, 14. februar 2010 15:25'], <del> ['l', '14.2.2010'], <add> ['l', '14. 2. 2010'], <ide> ['ll', '14. feb. 2010'], <ide> ['lll', '14. feb. 2010 15:25'], <ide> ['llll', 'ned., 14. feb. 2010 15:25']
2
Java
Java
add copytouricomponentsbuilder method
0e7eecfe348428efa9e6ab4c2cda1c83d2ca7201
<ide><path>spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java <ide> public URI toUri() { <ide> } <ide> } <ide> <add> @Override <add> protected void copyToUriComponentsBuilder(UriComponentsBuilder builder) { <add> builder.scheme(getScheme()); <add> builder.userInfo(getUserInfo()); <add> builder.host(getHost()); <add> builder.port(getPort()); <add> builder.replacePath(""); <add> this.path.copyToUriComponentsBuilder(builder); <add> builder.replaceQueryParams(getQueryParams()); <add> builder.fragment(getFragment()); <add> } <add> <add> <ide> @Override <ide> public boolean equals(Object obj) { <ide> if (this == obj) { <ide> interface PathComponent extends Serializable { <ide> void verify(); <ide> <ide> PathComponent expand(UriTemplateVariables uriVariables); <add> <add> void copyToUriComponentsBuilder(UriComponentsBuilder builder); <ide> } <ide> <ide> <ide> public PathComponent expand(UriTemplateVariables uriVariables) { <ide> return new FullPathComponent(expandedPath); <ide> } <ide> <add> @Override <add> public void copyToUriComponentsBuilder(UriComponentsBuilder builder) { <add> builder.path(getPath()); <add> } <add> <ide> @Override <ide> public boolean equals(Object obj) { <ide> return (this == obj || (obj instanceof FullPathComponent && <ide> static final class PathSegmentComponent implements PathComponent { <ide> private final List<String> pathSegments; <ide> <ide> public PathSegmentComponent(List<String> pathSegments) { <add> Assert.notNull(pathSegments); <ide> this.pathSegments = Collections.unmodifiableList(new ArrayList<String>(pathSegments)); <ide> } <ide> <ide> public PathComponent expand(UriTemplateVariables uriVariables) { <ide> return new PathSegmentComponent(expandedPathSegments); <ide> } <ide> <add> @Override <add> public void copyToUriComponentsBuilder(UriComponentsBuilder builder) { <add> builder.pathSegment(getPathSegments().toArray(new String[getPathSegments().size()])); <add> } <add> <ide> @Override <ide> public boolean equals(Object obj) { <ide> return (this == obj || (obj instanceof PathSegmentComponent && <ide> static final class PathComponentComposite implements PathComponent { <ide> private final List<PathComponent> pathComponents; <ide> <ide> public PathComponentComposite(List<PathComponent> pathComponents) { <add> Assert.notNull(pathComponents); <ide> this.pathComponents = pathComponents; <ide> } <ide> <ide> public PathComponent expand(UriTemplateVariables uriVariables) { <ide> } <ide> return new PathComponentComposite(expandedComponents); <ide> } <add> <add> @Override <add> public void copyToUriComponentsBuilder(UriComponentsBuilder builder) { <add> for (PathComponent pathComponent : this.pathComponents) { <add> pathComponent.copyToUriComponentsBuilder(builder); <add> } <add> } <ide> } <ide> <ide> <ide> public PathComponent expand(UriTemplateVariables uriVariables) { <ide> return this; <ide> } <ide> @Override <add> public void copyToUriComponentsBuilder(UriComponentsBuilder builder) { <add> } <add> @Override <ide> public boolean equals(Object obj) { <ide> return (this == obj); <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public URI toUri() { <ide> } <ide> } <ide> <add> @Override <add> protected void copyToUriComponentsBuilder(UriComponentsBuilder builder) { <add> builder.scheme(getScheme()); <add> builder.schemeSpecificPart(getSchemeSpecificPart()); <add> builder.fragment(getFragment()); <add> } <add> <ide> <ide> @Override <ide> public boolean equals(Object obj) { <ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponents.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public final String toString() { <ide> return toUriString(); <ide> } <ide> <add> /** <add> * Set all components of the given UriComponentsBuilder. <add> * @since 4.2 <add> */ <add> protected abstract void copyToUriComponentsBuilder(UriComponentsBuilder builder); <add> <ide> <ide> // static expansion helpers <ide> <ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java <ide> public UriComponentsBuilder scheme(String scheme) { <ide> */ <ide> public UriComponentsBuilder uriComponents(UriComponents uriComponents) { <ide> Assert.notNull(uriComponents, "'uriComponents' must not be null"); <del> this.scheme = uriComponents.getScheme(); <del> if (uriComponents instanceof OpaqueUriComponents) { <del> this.ssp = uriComponents.getSchemeSpecificPart(); <del> resetHierarchicalComponents(); <del> } <del> else { <del> if (uriComponents.getUserInfo() != null) { <del> this.userInfo = uriComponents.getUserInfo(); <del> } <del> if (uriComponents.getHost() != null) { <del> this.host = uriComponents.getHost(); <del> } <del> if (uriComponents.getPort() != -1) { <del> this.port = String.valueOf(uriComponents.getPort()); <del> } <del> if (StringUtils.hasLength(uriComponents.getPath())) { <del> List<String> segments = uriComponents.getPathSegments(); <del> if (segments.isEmpty()) { <del> // Perhaps "/" <del> this.pathBuilder.addPath(uriComponents.getPath()); <del> } <del> else { <del> this.pathBuilder.addPathSegments(segments.toArray(new String[segments.size()])); <del> } <del> } <del> if (!uriComponents.getQueryParams().isEmpty()) { <del> this.queryParams.clear(); <del> this.queryParams.putAll(uriComponents.getQueryParams()); <del> } <del> resetSchemeSpecificPart(); <del> } <del> if (uriComponents.getFragment() != null) { <del> this.fragment = uriComponents.getFragment(); <del> } <add> uriComponents.copyToUriComponentsBuilder(this); <ide> return this; <ide> } <ide> <ide> public UriComponentsBuilder replaceQueryParam(String name, Object... values) { <ide> return this; <ide> } <ide> <add> /** <add> * Set the query parameter values overriding all existing query values. <add> * @param params the query parameter name <add> * @return this UriComponentsBuilder <add> */ <add> public UriComponentsBuilder replaceQueryParams(MultiValueMap<String, String> params) { <add> Assert.notNull(params, "'params' must not be null"); <add> this.queryParams.clear(); <add> this.queryParams.putAll(params); <add> return this; <add> } <add> <ide> /** <ide> * Set the URI fragment. The given fragment may contain URI template variables, <ide> * and may also be {@code null} to clear the fragment of this builder. <ide><path>spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java <ide> public void fromHttpRequestWithForwardedProtoMultiValueHeader() { <ide> assertEquals("https://a.example.org/mvc-showcase", result.toString()); <ide> } <ide> <add> // SPR-12742 <add> <add> @Test <add> public void fromHttpRequestWithTrailingSlash() throws Exception { <add> UriComponents before = UriComponentsBuilder.fromPath("/foo/").build(); <add> UriComponents after = UriComponentsBuilder.newInstance().uriComponents(before).build(); <add> assertEquals("/foo/", after.getPath()); <add> } <add> <ide> @Test <ide> public void path() throws URISyntaxException { <ide> UriComponentsBuilder builder = UriComponentsBuilder.fromPath("/foo/bar"); <ide><path>spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.io.ObjectOutputStream; <ide> import java.net.URI; <ide> import java.net.URISyntaxException; <add>import java.util.Arrays; <ide> <ide> import org.junit.Test; <ide> <ide> public void serializable() throws Exception { <ide> assertThat(uriComponents.toString(), equalTo(readObject.toString())); <ide> } <ide> <add> @Test <add> public void copyToUriComponentsBuilder() { <add> UriComponents source = UriComponentsBuilder.fromPath("/foo/bar").pathSegment("ba/z").build(); <add> UriComponentsBuilder targetBuilder = UriComponentsBuilder.newInstance(); <add> source.copyToUriComponentsBuilder(targetBuilder); <add> UriComponents result = targetBuilder.build().encode(); <add> assertEquals("/foo/bar/ba%2Fz", result.getPath()); <add> assertEquals(Arrays.asList("foo", "bar", "ba%2Fz"), result.getPathSegments()); <add> } <add> <ide> @Test <ide> public void equalsHierarchicalUriComponents() throws Exception { <ide> UriComponents uriComponents1 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bar={baz}").build();
6
Javascript
Javascript
fix race in test case
96703ca57a6e5dbd4a8a9b61dd0c72bb3e7171ba
<ide><path>test/Compiler-caching.test.js <ide> describe("Compiler (caching)", () => { <ide> <ide> // Copy over file since we"ll be modifying some of them <ide> fs.mkdirSync(fixturePath); <del> fs.createReadStream(path.join(__dirname, "fixtures", "a.js")).pipe( <del> fs.createWriteStream(aFilepath) <del> ); <del> fs.createReadStream(path.join(__dirname, "fixtures", "c.js")).pipe( <del> fs.createWriteStream(cFilepath) <del> ); <add> fs.copyFileSync(path.join(__dirname, "fixtures", "a.js"), aFilepath); <add> fs.copyFileSync(path.join(__dirname, "fixtures", "c.js"), cFilepath); <ide> <ide> fixtureCount++; <ide> return {
1
Javascript
Javascript
fix typo in ignoreplugin
aa172f0a359ab3c0b0987101c64c8b41b07d581f
<ide><path>lib/IgnorePlugin.js <ide> class IgnorePlugin { <ide> * Only returns true if a "resourceRegExp" exists <ide> * and the resource given matches the regexp. <ide> */ <del> checkResouce(resource) { <add> checkResource(resource) { <ide> if(!this.resourceRegExp) { <ide> return false; <ide> } <ide> class IgnorePlugin { <ide> if(!result) { <ide> return true; <ide> } <del> return this.checkResouce(result.request) && this.checkContext(result.context); <add> return this.checkResource(result.request) && this.checkContext(result.context); <ide> } <ide> <ide> checkIgnore(result, callback) {
1
Java
Java
add mergedannotation.getroot() method
83cb51aec694dd7b6d9100140a1e11ee03571e02
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/MergedAnnotation.java <ide> @Nullable <ide> MergedAnnotation<?> getParent(); <ide> <add> /** <add> * Get the root annotation, i.e. the {@link #getDepth() depth} {@code 0} <add> * annotation as directly declared on the source. <add> * @return the root annotation <add> */ <add> MergedAnnotation<?> getRoot(); <add> <ide> /** <ide> * Determine if the specified attribute name has a non-default value when <ide> * compared to the annotation declaration. <ide><path>spring-core/src/main/java/org/springframework/core/annotation/MissingMergedAnnotation.java <ide> public MergedAnnotation<?> getParent() { <ide> return null; <ide> } <ide> <add> @Override <add> public MergedAnnotation<?> getRoot() { <add> return this; <add> } <add> <ide> @Override <ide> public int getDepth() { <ide> return -1; <ide><path>spring-core/src/main/java/org/springframework/core/annotation/TypeMappedAnnotation.java <ide> public MergedAnnotation<?> getParent() { <ide> this.valueExtractor, this.aggregateIndex, this.resolvedRootMirrors); <ide> } <ide> <add> @Override <add> public MergedAnnotation<?> getRoot() { <add> if (getDepth() == 0) { <add> return this; <add> } <add> AnnotationTypeMapping rootMapping = this.mapping.getRoot(); <add> return new TypeMappedAnnotation<>(rootMapping, this.source, this.rootAttributes, <add> this.valueExtractor, this.aggregateIndex, this.resolvedRootMirrors); <add> } <add> <ide> @Override <ide> public boolean hasDefaultValue(String attributeName) { <ide> int attributeIndex = getAttributeIndex(attributeName, true); <ide><path>spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java <ide> public void getParent() { <ide> .isEqualTo(ComposedTransactionalComponent.class); <ide> } <ide> <add> @Test <add> public void getRootWhenNotDirect() { <add> MergedAnnotations annotations = MergedAnnotations.from(ComposedTransactionalComponentClass.class); <add> MergedAnnotation<?> annotation = annotations.get(TransactionalComponent.class); <add> assertThat(annotation.getDepth()).isGreaterThan(0); <add> assertThat(annotation.getRoot().getType()).isEqualTo(ComposedTransactionalComponent.class); <add> } <add> <add> @Test <add> public void getRootWhenDirect() { <add> MergedAnnotations annotations = MergedAnnotations.from(ComposedTransactionalComponentClass.class); <add> MergedAnnotation<?> annotation = annotations.get(ComposedTransactionalComponent.class); <add> assertThat(annotation.getDepth()).isEqualTo(0); <add> assertThat(annotation.getRoot()).isSameAs(annotation); <add> } <add> <ide> @Test <ide> public void collectMultiValueMapFromNonAnnotatedClass() { <ide> MultiValueMap<String, Object> map = MergedAnnotations.from( <ide><path>spring-core/src/test/java/org/springframework/core/annotation/MissingMergedAnnotationTests.java <ide> public void getParentReturnsNull() { <ide> assertThat(this.missing.getParent()).isNull(); <ide> } <ide> <add> @Test <add> public void getRootReturnsEmptyAnnotation() { <add> assertThat(this.missing.getRoot()).isSameAs(this.missing); <add> } <add> <ide> @Test <ide> public void hasNonDefaultValueThrowsNoSuchElementException() { <ide> assertThatNoSuchElementException().isThrownBy(
5
Text
Text
fix typo in `tools/code_cache/readme.md`
c18ca140a12b543a3f970ef379f384ebd3297c3d
<ide><path>tools/code_cache/README.md <ide> <ide> This is the V8 code cache builder of Node.js. It pre-compiles all the <ide> JavaScript native modules of Node.js and serializes the code cache (including <del>the bytecodes) that will be embeded into the Node.js executable. When a Node.js <add>the bytecodes) that will be embedded into the Node.js executable. When a Node.js <ide> JavaScript native module is `require`d at runtime, Node.js can deserialize from <ide> the code cache instead of parsing the source code and generating the bytecode <ide> for it before execution, which should reduce the load time of these JavaScript
1
Text
Text
provide initial edits to "your first package" docs
e7a14bf17fa185a004cd2904cbac1cd80b9ddfb3
<ide><path>docs/your-first-package.md <ide> # Creating Your First Package <ide> <del>Let's take a look at creating our first package. <add>Let's take a look at creating your first package. <ide> <del>To get started hit `cmd-p`, and start typing "Package Generator." to generate <del>the package. Once you select the package generator command, it'll ask you for a <add>To get started, hit `cmd-p`, and start typing "Package Generator" to generate <add>a package. Once you select the "Generate Package" command, it'll ask you for a <ide> name for your new package. Let's call ours _changer_. <ide> <del>Now, _changer_ is going to have a default set of folders and files created for <del>us. Hit `cmd-r` to reload Atom, then hit `cmd-p` and start typing "Changer." <del>You'll see a new `Changer:Toggle` command which, if selected, pops up a new <del>message. So far, so good! <add>Atom will pop open a new window, showing the _changer_ with a default set of <add>folders and files created for us. Hit `cmd-p` and start typing "Changer." You'll <add>see a new `Changer:Toggle` command which, if selected, pops up a greeting. So far, <add>so good! <ide> <ide> In order to demonstrate the capabilities of Atom and its API, our Changer plugin <ide> is going to do two things: <ide> Since Changer is primarily concerned with the file tree, let's write a <ide> key binding that works only when the tree is focused. Instead of using the <ide> default `toggle`, our keybinding executes a new command called `magic`. <ide> <del>_keymaps/changer.cson_ can easily become this: <add>_keymaps/changer.cson_ should change to look like this: <ide> <ide> ```coffeescript <ide> '.tree-view': <ide> Notice that the keybinding is called `ctrl-V` &mdash; that's actually `ctrl-shif <ide> You can use capital letters to denote using `shift` for your binding. <ide> <ide> `.tree-view` represents the parent container for the tree view. <del>Keybindings only work within the context of where they're entered. For example, <del>hitting `ctrl-V` anywhere other than tree won't do anything. You can map to <del>`body` if you want to scope to anywhere in Atom, or just `.editor` for the <del>editor portion. <add>Keybindings only work within the context of where they're entered. In this case, <add>hitting `ctrl-V` anywhere other than tree won't do anything. Obviously, you can <add>bind to any part of the editor using element, id, or class names. For example, <add>you can map to `body` if you want to scope to anywhere in Atom, or just `.editor` <add>for the editor portion. <ide> <del>To bind keybindings to a command, we'll use the `rootView.command` method. This <del>takes a command name and executes a function in the code. For example: <add>To bind keybindings to a command, we'll need to do a bit of association in our <add>CoffeeScript code using the `rootView.command` method. This method takes a command <add>name and executes a callback function. Open up _lib/changer-view.coffee_, and <add>change `rootView.command "changer:toggle" to look like this: <ide> <ide> ```coffeescript <ide> rootView.command "changer:magic", => @magic() <ide> ``` <ide> <del>It's common practice to namespace your commands with your package name, and <del>separate it with a colon (`:`). Rename the existing `toggle` method to `magic` <del>to get the binding to work. <add>It's common practice to namespace your commands with your package name, separated <add>with a colon (`:`). <ide> <del>Reload the editor, click on the tree, hit your keybinding, and...nothing <del>happens! What the heck?! <add>Every time you reload the Atom editor, changes to your package code will be reevaluated, <add>just as if you were writing a script for the browser. Reload the editor, click on <add>the tree, hit your keybinding, and...nothing happens! What the heck?! <ide> <del>Open up the _package.json_ file, and notice the key that says <del>`activationEvents`. Basically, this tells Atom to not load a package until it <del>hears a certain event. Let's change the event to `changer:magic` and reload the <del>editor. <add>Open up the _package.json_ file, and find the property called `activationEvents`. <add>Basically, this key tells Atom to not load a package until it hears a certain event. <add>Change the event to `changer:magic` and reload the editor: <add> <add>```json <add>"activationEvents": ["changer:toggle"] <add>``` <ide> <ide> Hitting the key binding on the tree now works! <ide> <ide> Hitting the key binding on the tree now works! <ide> The next step is to hide elements in the tree that aren't modified. To do that, <ide> we'll first try and get a list of files that have not changed. <ide> <del>All packages are able to use jQuery in their code. In fact, we have [a list of <del>some of the bundled libraries Atom provides by default](#included-libraries). <add>All packages are able to use jQuery in their code. In fact, there's [a list of <add>the bundled libraries Atom provides by default][bundled-libs]. <ide> <del>Let's bring in jQuery: <add>We bring in jQuery by requiring the `atom` package and binding it to the `$` variable: <ide> <ide> ```coffeescript <ide> {$} = require 'atom' <ide> ``` <ide> <del>Now, we can query the tree to get us a list of every file that _wasn't_ <del>modified: <add>Now, we can define the `magic` method to query the tree to get us a list of every <add>file that _wasn't_ modified: <ide> <ide> ```coffeescript <ide> magic: -> <ide> $('ol.entries li').each (i, el) -> <del> if !$(el).hasClass("modified") <add> if !$(el).hasClass("status-modified") <ide> console.log el <ide> ``` <ide> <del>You can access the dev console by hitting `alt-cmd-i`. When we execute the <del>`changer:magic` command, the browser console lists the items that are not being <del>modified. Let's add a class to each of these elements called `hide-me`: <add>You can access the dev console by hitting `alt-cmd-i`. Here, you'll see all the <add>statements from `console` calls. When we execute the `changer:magic` command, the <add>browser console lists items that are not being modified (_i.e._, those without the <add>`status-modified` class). Let's add a class to each of these elements called `hide-me`: <ide> <ide> ```coffeescript <ide> magic: -> <ide> $('ol.entries li').each (i, el) -> <del> if !$(el).hasClass("modified") <add> if !$(el).hasClass("status-modified") <ide> $(el).addClass("hide-me") <ide> ``` <ide> <ide> ol.entries .hide-me { <ide> } <ide> ``` <ide> <del>Refresh atom, and run the `changer` command. You'll see all the non-changed <add>Refresh Atom, and run the `changer` command. You'll see all the non-changed <ide> files disappear from the tree. There are a number of ways you can get the list <ide> back; let's just naively iterate over the same elements and remove the class: <ide> <ide> ```coffeescript <ide> magic: -> <ide> $('ol.entries li').each (i, el) -> <del> if !$(el).hasClass("modified") <add> if !$(el).hasClass("status-modified") <ide> if !$(el).hasClass("hide-me") <ide> $(el).addClass("hide-me") <ide> else <ide> magic: -> <ide> The next goal of this package is to append a panel to the Atom editor that lists <ide> some information about the modified files. <ide> <del>To do that, we're going to first create a new class method called `content`. <add>To do that, we're going to first open up [the style guide][style-guide]. The Style <add>Guide lists every type of UI element that can be created by an Atom package. Aside <add>from helping you avoid writing fresh code from scratch, it ensures that packages <add>have the same look and feel no matter how they're built. <add> <ide> Every package that extends from the `View` class can provide an optional class <ide> method called `content`. The `content` method constructs the DOM that your <ide> package uses as its UI. The principals of `content` are built entirely on <del>[SpacePen], which we'll touch upon only briefly here. <add>[SpacePen][space-pen], which we'll touch upon only briefly here. <ide> <ide> Our display will simply be an unordered list of the file names, and their <del>modified times. Let's start by carving out a `div` to hold the filenames: <add>modified times. A basic Panel element will work well for us. Let's start by <add>carving out a `div` to hold the filenames: <ide> <ide> ```coffeescript <ide> @content: -> <del> @div class: 'modified-files-container', => <del> @ul class: 'modified-files-list', outlet: 'modifiedFilesList', => <del> @li 'Test' <del> @li 'Test2' <add> @div class: "panel", => <add> @div class: "panel-heading", "Modified Files" <add> @div class: "panel-body padded", outlet: 'modifiedFilesContainer', => <add> @ul class: 'modified-files-list', outlet: 'modifiedFilesList', => <add> @li 'Modified File Test' <add> @li 'Modified File Test' <ide> ``` <ide> <del>You can add any HTML5 attribute you like. `outlet` names the variable your <del>package can uses to manipulate the element directly. The fat pipe (`=>`) <del>indicates that the next set are nested children. <add>You can add any HTML attribute you like. `outlet` names the variable your <add>package can use to manipulate the element directly. The fat pipe (`=>`) <add>indicates that the next DOM set are nested children. <ide> <del>We'll add one more line to `magic` to make this pane appear: <add>We'll add one more line to the end of the `magic` method to make this pane appear: <ide> <ide> ```coffeescript <ide> rootView.vertical.append(this) <ide> ``` <ide> <del>If you hit the key command, you'll see a box appear right underneath the editor. <del>Success! <add>If you refresh Atom and hit the key command, you'll see a box appear right underneath <add>the editor. Success! <ide> <del>Before we populate this, let's apply some logic to toggle the pane off and on, <del>just like we did with the tree view: <add>As you might have guessed, `rootView.vertical.append` tells Atom to append `this` <add>item (_i.e._, whatever is defined by`@content`) _vertically_ to the editor. If <add>we had called `rootView.horizontal.append`, the pane would be attached to the <add>right-hand side of the editor. <add> <add>Before we populate this panel for real, let's apply some logic to toggle the pane <add>off and on, just like we did with the tree view. Replace the `rootView.vertical.append` <add>call with this code: <ide> <ide> ```coffeescript <ide> # toggles the pane <ide> the view. You can then swap between `show()` and `hide()`, and instead of <ide> forcing Atom to add and remove the element as we're doing here, it'll just set a <ide> CSS property to control your package's visibility. <ide> <del>Refresh Atom, hit the key combo, and see your test list. <add>Refresh Atom, hit the key combo, and watch your test list appear and disappear. <ide> <ide> ## Calling Node.js Code <ide> <del>Since Atom is built on top of Node.js, you can call any of its libraries, <add>Since Atom is built on top of [Node.js][node], you can call any of its libraries, <ide> including other modules that your package requires. <ide> <ide> We'll iterate through our resulting tree, and construct the path to our modified <del>file based on its depth in the tree: <add>file based on its depth in the tree. We'll use Node to handle path joining for <add>directories. <add> <add>Add the following Node module to the top of your file: <ide> <ide> ```coffeescript <ide> path = require 'path' <add>``` <ide> <del># ... <add>Then, add these lines to your `magic` method, _before_ your pane drawing code: <ide> <add>```coffeescript <ide> modifiedFiles = [] <ide> # for each single entry... <del>$('ol.entries li.file.modified span.name').each (i, el) -> <add>$('ol.entries li.file.status-modified span.name').each (i, el) -> <ide> filePath = [] <ide> # ...grab its name... <ide> filePath.unshift($(el).text()) <ide> <ide> # ... then find its parent directories, and grab their names <del> parents = $(el).parents('.directory.modified') <add> parents = $(el).parents('.directory.status-modified') <ide> parents.each (i, el) -> <ide> filePath.unshift($(el).find('div.header span.name').eq(0).text()) <ide> <ide> $('ol.entries li.file.modified span.name').each (i, el) -> <ide> using the node.js [`path` library][path] to get the proper directory separator <ide> for our system. <ide> <del>Let's remove the two `@li` elements we added in `@content`, so that we can <add>Remove the two `@li` elements we added in `@content`, so that we can <ide> populate our `modifiedFilesList` with real information. We'll do that by <ide> iterating over `modifiedFiles`, accessing a file's last modified time, and <ide> appending it to `modifiedFilesList`: <ide> we'll just clear the `modifiedFilesList` each time it's closed: <ide> ```coffeescript <ide> # toggles the pane <ide> if @hasParent() <del> @modifiedFilesList.empty() <add> @modifiedFilesList.empty() # added this to clear the list on close <ide> rootView.vertical.children().last().remove() <ide> else <ide> for file in modifiedFiles <ide> else <ide> rootView.vertical.append(this) <ide> ``` <ide> <del># Included Libraries <del> <del>FIXME: Describe `require 'atom' <del> <del>In addition to core node.js modules, all packages can `require` the following <del>popular libraries into their packages: <del> <del>* [SpacePen] (as `require 'space-pen'`) <del>* [jQuery] (as `require 'jquery'`) <del>* [Underscore] (as `require 'underscore'`) <del> <del>Additional libraries can be found by browsing Atom's *node_modules* folder. <del> <del>[file-tree]: https://github.com/atom/tree-view <del>[status-bar]: https://github.com/atom/status-bar <del>[cs-syntax]: https://github.com/atom/language-coffee-script <del>[npm]: http://en.wikipedia.org/wiki/Npm_(software) <del>[npm-keys]: https://npmjs.org/doc/json.html <del>[apm]: https://github.com/atom/apm <del>[git-tag]: http://git-scm.com/book/en/Git-Basics-Tagging <del>[wrap-guide]: https://github.com/atom/wrap-guide/ <del>[keymaps]: internals/keymaps.md <del>[theme-variables]: theme-variables.md <del>[tm-tokens]: http://manual.macromates.com/en/language_grammars.html <del>[spacepen]: https://github.com/nathansobo/space-pen <add>[bundled-libs]: ../creating-a-package.html#included-libraries <add>[styleguide]: https://github.com/atom/styleguide <add>[space-pen]: https://github.com/atom/space-pen <add>[node]: http://nodejs.org/ <ide> [path]: http://nodejs.org/docs/latest/api/path.html <del>[jquery]: http://jquery.com/ <del>[underscore]: http://underscorejs.org/ <del>[jasmine]: https://github.com/pivotal/jasmine <del>[cson]: https://github.com/atom/season <del>[less]: http://lesscss.org <del>[ui-variables]: https://github.com/atom/atom-dark-ui/blob/master/stylesheets/ui-variables.less
1
Python
Python
add german stopwords
4d9aae7d6a52dbc17809d9204acc42f384ad8532
<ide><path>spacy/de/language_data.py <ide> import re <ide> <ide> <del>STOP_WORDS = set() <add>STOP_WORDS = set(""" <add>a ab aber ach acht achte achten achter achtes <add>ag alle allein allem allen aller allerdings alles <add>allgemeinen als also am an andere anderen <add>andern anders au auch auf aus ausser außer <add>ausserdem außerdem b bald bei beide beiden <add>beim beispiel bekannt bereits besonders <add>besser besten bin bis bisher bist da <add>dabei dadurch dafür dagegen daher <add>dahin dahinter damals damit danach <add>daneben dank dann daran darauf <add>daraus darf darfst darin darüber <add>darum darunter das dasein daselbst <add>dass daß dasselbe davon davor dazu <add>dazwischen dein deine deinem deiner <add>dem dementsprechend demgegenüber <add>demgemäss demgemäß demselben <add>demzufolge den denen denn denselben <add>der deren derjenige derjenigen dermassen <add>dermaßen derselbe derselben des deshalb <add>desselben dessen deswegen dich die diejenige <add>diejenigen dies diese dieselbe dieselben diesem <add>diesen dieser dieses dir doch dort drei drin dritte <add>dritten dritter drittes du durch durchaus dürfen <add>dürft durfte durften eben ebenso ehrlich ei eigen <add>eigene eigenen eigener eigenes ein einander eine <add>einem einen einer eines einigeeinigen einiger einiges <add>einmal einmaleins elf en ende endlich entweder <add>er erst erste ersten erster erstes es etwa etwas euch <add>früher fünf fünfte fünften fünfter fünftes für gab ganz <add>ganze ganzen ganzer ganzes gar gedurft gegen <add>gegenüber gehabt gehen geht gekannt gekonnt gemacht <add>gemocht gemusst genug gerade gern gesagt geschweige <add>gewesen gewollt geworden gibt ging gleich gott gross <add>groß grosse große grossen großen grosser großer <add>grosses großes gut gute guter gutes habe haben habt <add>hast hat hatte hätte hatten hätten heisst her heute hier <add>hin hinter hoch ich ihm ihn ihnen ihr ihre ihrem ihrer <add>ihres im immer in indem infolgedessen ins irgend ist <add>ja jahr jahre jahren je jede jedem jeden jeder jedermann <add>jedermanns jedoch jemand jemandem jemanden jene <add>jenem jenen jener jenes jetzt kam kann kannst kaum kein <add>keine keinem keinen keiner kleine kleinen kleiner kleines <add>kommen kommt können könnt konnte könnte konnten kurz <add>lang lange leicht leide lieber los machen macht machte mag <add>magst mahn man manche manchem manchen mancher <add>manches mann mehr mein meine meinem meinen meiner <add>meines mensch menschen mich mir mit mittel mochte <add>möchte mochten mögen möglich mögt morgen muss muß <add>müssen musst müsst musste mussten na nach nachdem nahm <add>natürlich neben nein neue neuen neun neunte neunten neunter <add>neuntes nicht nichts nie niemand niemandem niemanden noch <add>nun nur ob oben oder offen oft ohne ordnung recht rechte <add>rechten rechter rechtes richtig rund sa sache sagt sagte sah satt <add>schlecht Schluss schon sechs sechste sechsten sechster sechstes <add>sehr sei seid seien sein seine seinem seinen seiner seines seit <add>seitdem selbst selbst sich sie sieben siebente siebenten siebenter <add>siebentes sind so solang solche solchem solchen solcher solches <add>soll sollen sollte sollten sondern sonst sowie später statt tag tage <add>tagen tat teil tel tritt trotzdem tun über überhaupt übrigens uhr <add>um und uns unser unsere unserer unter vergangenen viel viele <add>vielem vielen vielleicht vier vierte vierten vierter viertes vom von <add>vor wahr während währenddem währenddessen wann war wäre <add>waren wart warum was wegen weil weit weiter weitere weiteren <add>weiteres welche welchem welchen welcher welches wem wen <add>wenig wenige weniger weniges wenigstens wenn wer werde <add>werden werdet wessen wie wieder will willst wir wird wirklich <add>wirst wo wohl wollen wollt wollte wollten worden wurde würde <add>wurden würden zehn zehnte zehnten zehnter zehntes zeit zu <add>zuerst zugleich zum zunächst zur zurück zusammen zwanzig <add>zwar zwei zweite zweiten zweiter zweites zwischen <add>""".split()) <ide> <ide> <ide> TOKENIZER_PREFIXES = map(re.escape, r'''
1
Go
Go
fix a lb rule race in loadbalancer
4d1a5ce9681bb56aed2d7be1d23d5af642e429c0
<ide><path>libnetwork/service_linux.go <ide> func (c *controller) addServiceBinding(name, sid, nid, eid string, vip net.IP, i <ide> } <ide> c.Unlock() <ide> <add> // Add endpoint IP to special "tasks.svc_name" so that the <add> // applications have access to DNS RR. <add> n.(*network).addSvcRecords("tasks."+name, ip, nil, false) <add> <ide> s.Lock() <add> defer s.Unlock() <add> <ide> lb, ok := s.loadBalancers[nid] <ide> if !ok { <ide> // Create a new load balancer if we are seeing this <ide> func (c *controller) addServiceBinding(name, sid, nid, eid string, vip net.IP, i <ide> } <ide> <ide> lb.backEnds[eid] = ip <del> s.Unlock() <del> <del> // Add endpoint IP to special "tasks.svc_name" so that the <del> // applications have access to DNS RR. <del> n.(*network).addSvcRecords("tasks."+name, ip, nil, false) <ide> <ide> // Add loadbalancer service and backend in all sandboxes in <ide> // the network only if vip is valid. <ide> func (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, in <ide> } <ide> c.Unlock() <ide> <add> // Delete the special "tasks.svc_name" backend record. <add> n.(*network).deleteSvcRecords("tasks."+name, ip, nil, false) <add> <ide> s.Lock() <add> defer s.Unlock() <add> <ide> lb, ok := s.loadBalancers[nid] <ide> if !ok { <del> s.Unlock() <ide> return nil <ide> } <ide> <del> // Delete the special "tasks.svc_name" backend record. <del> n.(*network).deleteSvcRecords("tasks."+name, ip, nil, false) <ide> delete(lb.backEnds, eid) <del> <ide> if len(lb.backEnds) == 0 { <ide> // All the backends for this service have been <ide> // removed. Time to remove the load balancer and also <ide> func (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, in <ide> // remove the service itself. <ide> delete(c.serviceBindings, sid) <ide> } <del> s.Unlock() <ide> <ide> // Remove loadbalancer service(if needed) and backend in all <ide> // sandboxes in the network only if the vip is valid. <ide> func (sb *sandbox) addLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*P <ide> // destination. <ide> s.SchedName = "" <ide> if err := i.NewDestination(s, d); err != nil && err != syscall.EEXIST { <del> logrus.Errorf("Failed to create real server %s for vip %s fwmark %d: %v", ip, vip, fwMark, err) <add> logrus.Errorf("Failed to create real server %s for vip %s fwmark %d in sb %s: %v", ip, vip, fwMark, sb.containerID, err) <ide> } <ide> } <ide>
1
Javascript
Javascript
add debug mode
3d505ef0c53ee2a886f41891ab56ead6deb67257
<ide><path>src/js/player.js <ide> class Player extends Component { <ide> // Init state userActive_ <ide> this.userActive_ = false; <ide> <add> // Init debugEnabled_ <add> this.debugEnabled_ = false; <add> <ide> // if the global option object was accidentally blown away by <ide> // someone, bail early with an informative error <ide> if (!this.options_ || <ide> class Player extends Component { <ide> }); <ide> } <ide> <add> // Enable debug mode to fire debugon event for all plugins. <add> if (options.debug) { <add> this.debug(true); <add> } <add> <ide> this.options_.playerOptions = playerOptionsCopy; <ide> <ide> this.middleware_ = []; <ide> class Player extends Component { <ide> // IE10-specific (2012 flex spec), available for completeness <ide> 'msFlexOrder' in elem.style); <ide> } <add> <add> /** <add> * Set debug mode to enable/disable logs at info level. <add> * <add> * @param {boolean} enabled <add> * @fires Player#debugon <add> * @fires Player#debugoff <add> */ <add> debug(enabled) { <add> if (enabled === undefined) { <add> return this.debugEnabled_; <add> } <add> if (enabled) { <add> this.trigger('debugon'); <add> this.previousLogLevel_ = this.log.level; <add> this.log.level('debug'); <add> this.debugEnabled_ = true; <add> } else { <add> this.trigger('debugoff'); <add> this.log.level(this.previousLogLevel_); <add> this.previousLogLevel_ = undefined; <add> this.debugEnabled_ = false; <add> } <add> } <ide> } <ide> <ide> /** <ide><path>test/unit/player.test.js <ide> QUnit.test('Should accept multiple calls to currentTime after player initializat <ide> assert.equal(player.currentTime(), 800, 'The last value passed is stored as the currentTime value'); <ide> }); <ide> <add>QUnit.test('Should fire debugon event when debug mode is enabled', function(assert) { <add> const player = TestHelpers.makePlayer({}); <add> const debugOnSpy = sinon.spy(); <add> <add> player.on('debugon', debugOnSpy); <add> player.debug(true); <add> <add> assert.ok(debugOnSpy.calledOnce, 'debugon event was fired'); <add> player.dispose(); <add>}); <add> <add>QUnit.test('Should fire debugoff event when debug mode is disabled', function(assert) { <add> const player = TestHelpers.makePlayer({}); <add> const debugOffSpy = sinon.spy(); <add> <add> player.on('debugoff', debugOffSpy); <add> player.debug(false); <add> <add> assert.ok(debugOffSpy.calledOnce, 'debugoff event was fired'); <add> player.dispose(); <add>}); <add> <add>QUnit.test('Should enable debug mode and store log level when calling options', function(assert) { <add> const player = TestHelpers.makePlayer({debug: true}); <add> <add> assert.ok(player.previousLogLevel_, 'debug', 'previous log level is stored when enabling debug'); <add> player.dispose(); <add>}); <add> <add>QUnit.test('Should restore previous log level when disabling debug mode', function(assert) { <add> const player = TestHelpers.makePlayer(); <add> <add> player.log.level('error'); <add> player.debug(true); <add> assert.ok(player.log.level(), 'debug', 'log level is debug when debug is enabled'); <add> <add> player.debug(false); <add> assert.ok(player.log.level(), 'error', 'previous log level was restored'); <add> player.dispose(); <add>}); <add> <add>QUnit.test('Should return if debug is enabled or disabled', function(assert) { <add> const player = TestHelpers.makePlayer(); <add> <add> player.debug(true); <add> const enabled = player.debug(); <add> <add> assert.ok(enabled); <add> <add> player.debug(false); <add> const disabled = player.debug(); <add> <add> assert.notOk(disabled); <add> player.dispose(); <add>}); <add> <ide> const testOrSkip = 'pictureInPictureEnabled' in document ? 'test' : 'skip'; <ide> <ide> QUnit[testOrSkip]('Should only allow requestPictureInPicture if the tech supports it', function(assert) { <ide> QUnit[testOrSkip]('Should only allow requestPictureInPicture if the tech support <ide> delete player.tech_.el_.disablePictureInPicture; <ide> player.requestPictureInPicture(); <ide> assert.equal(count, 1, 'requestPictureInPicture not passed through when tech does not support'); <del> <ide> });
2
Java
Java
expose logprefix in clientresponse
09b6730f3d89b55819ea9bea66314269b7cc4fd9
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientResponse.java <ide> public interface ClientResponse { <ide> */ <ide> Mono<WebClientResponseException> createException(); <ide> <add> /** <add> * Return a log message prefix to use to correlate messages for this response. <add> * The prefix is based on the {@linkplain ClientRequest#logPrefix() client <add> * log prefix}, which itself is based on the value of the request attribute <add> * {@link ClientRequest#LOG_ID_ATTRIBUTE} along with some extra formatting <add> * so that the prefix can be conveniently prepended with no further <add> * formatting no separators required. <add> * @return the log message prefix or an empty String if the <add> * {@link ClientRequest#LOG_ID_ATTRIBUTE} was not set. <add> * @since 5.2.3 <add> */ <add> String logPrefix(); <add> <ide> <ide> // Static builder methods <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponse.java <ide> public Mono<WebClientResponseException> createException() { <ide> }); <ide> } <ide> <add> @Override <add> public String logPrefix() { <add> return this.logPrefix; <add> } <add> <ide> // Used by DefaultClientResponseBuilder <ide> HttpRequest request() { <ide> return this.requestSupplier.get(); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/support/ClientResponseWrapper.java <ide> public Mono<WebClientResponseException> createException() { <ide> return this.delegate.createException(); <ide> } <ide> <add> @Override <add> public String logPrefix() { <add> return this.delegate.logPrefix(); <add> } <add> <ide> /** <ide> * Implementation of the {@code Headers} interface that can be subclassed <ide> * to adapt the headers in a
3
Text
Text
adjust wording to eliminate awkward typography
c4d75ea104e0e9a9f9180d6a2750886dc28a1012
<ide><path>doc/api/modules.md <ide> By default, Node.js will treat the following as CommonJS modules: <ide> * Files with an extension that is not `.mjs`, `.cjs`, `.json`, `.node`, or `.js` <ide> (when the nearest parent `package.json` file contains a top-level field <ide> [`"type"`][] with a value of `"module"`, those files will be recognized as <del> CommonJS modules only if they are being `require`d, not when used as the <del> command-line entry point of the program). <add> CommonJS modules only if they are being included via `require()`, not when <add> used as the command-line entry point of the program). <ide> <ide> See [Determining module system][] for more details. <ide>
1
Java
Java
add experiment for running the js on view creation
2dd33b16df16bc51437d7eab78741959fb450abd
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java <ide> import com.facebook.react.bridge.WritableMap; <ide> import com.facebook.react.bridge.WritableNativeMap; <ide> import com.facebook.react.common.annotations.VisibleForTesting; <add>import com.facebook.react.config.ReactFeatureFlags; <ide> import com.facebook.react.modules.appregistry.AppRegistry; <ide> import com.facebook.react.modules.core.DeviceEventManagerModule; <ide> import com.facebook.react.modules.deviceinfo.DeviceInfoModule; <ide> public void startReactApplication( <ide> mInitialUITemplate = initialUITemplate; <ide> <ide> mReactInstanceManager.createReactContextInBackground(); <del> <add> // if in this experiment, we initialize the root earlier in startReactApplication <add> // instead of waiting for the initial measure <add> if (ReactFeatureFlags.enableEagerRootViewAttachment) { <add> attachToReactInstanceManager(); <add> } <ide> } finally { <ide> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java <ide> public class ReactFeatureFlags { <ide> /** Feature flag to configure eager initialization of MapBuffer So file */ <ide> public static boolean enableEagerInitializeMapBufferSoFile = false; <ide> <add> /** Feature flag to configure eager attachment of the root view/initialisation of the JS code */ <add> public static boolean enableEagerRootViewAttachment = false; <add> <ide> private static boolean mapBufferSerializationEnabled = false; <ide> <ide> /** Enables or disables MapBuffer Serialization */
2
Python
Python
add tests for .ctypes.data_as
e2fa2ce5c06f902b7a50e1a7d34794cce0f076b7
<ide><path>numpy/core/tests/test_multiarray.py <ide> def test_ctypes_data_as_holds_reference(self, arr): <ide> break_cycles() <ide> assert_(arr_ref() is None, "unknowable whether ctypes pointer holds a reference") <ide> <add> def test_ctypes_as_parameter_holds_reference(self): <add> arr = np.array([None]).copy() <add> <add> arr_ref = weakref.ref(arr) <add> <add> ctypes_ptr = arr.ctypes._as_parameter_ <add> <add> # `ctypes_ptr` should hold onto `arr` <add> del arr <add> break_cycles() <add> assert_(arr_ref() is not None, "ctypes pointer did not hold onto a reference") <add> <add> # but when the `ctypes_ptr` object dies, so should `arr` <add> del ctypes_ptr <add> break_cycles() <add> assert_(arr_ref() is None, "unknowable whether ctypes pointer holds a reference") <add> <add> def test_ctypes_data_as_no_circular_reference(self): <add> # check array reference count based on the buffer the array points to <add> data = b'\x00' * 128 <add> ref_count = sys.getrefcount(data) <add> <add> arr = np.frombuffer(data) <add> ctypes_ptr = arr.ctypes.data_as(ctypes.c_void_p) <add> <add> del arr, ctypes_ptr <add> # Do not call gc before checking circular reference <add> assert_(sys.getrefcount(data) == ref_count, "Found ctypes pointer circular reference") <add> <ide> <ide> class TestWritebackIfCopy(object): <ide> # all these tests use the WRITEBACKIFCOPY mechanism
1
PHP
PHP
fix remaining failing test
094c7a7504522b85146cee68e0d73e671beb6919
<ide><path>tests/Database/DatabaseMySqlSchemaGrammarTest.php <ide> public function testCharsetCollationCreateTable() <ide> $conn = $this->getConnection(); <ide> $conn->shouldReceive('getConfig')->once()->with('charset')->andReturn('utf8'); <ide> $conn->shouldReceive('getConfig')->once()->with('collation')->andReturn('utf8_unicode_ci'); <add> $conn->shouldReceive('getConfig')->once()->with('engine')->andReturn(null); <ide> <ide> $statements = $blueprint->toSql($conn, $this->getGrammar()); <ide>
1
Java
Java
android support for perspective transform
3e760f48c5a28b592cb60c4060ca28a1574f6274
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java <ide> import android.os.Build; <ide> import android.view.View; <ide> <add>import com.facebook.react.bridge.ReadableArray; <ide> import com.facebook.react.bridge.ReadableMap; <ide> import com.facebook.react.uimanager.annotations.ReactProp; <add>import com.facebook.react.uimanager.DisplayMetricsHolder; <ide> <ide> /** <ide> * Base class that should be suitable for the majority of subclasses of {@link ViewManager}. <ide> private static final String PROP_DECOMPOSED_MATRIX_SCALE_Y = "scaleY"; <ide> private static final String PROP_DECOMPOSED_MATRIX_TRANSLATE_X = "translateX"; <ide> private static final String PROP_DECOMPOSED_MATRIX_TRANSLATE_Y = "translateY"; <add> private static final String PROP_DECOMPOSED_MATRIX_PERSPECTIVE = "perspective"; <ide> private static final String PROP_OPACITY = "opacity"; <ide> private static final String PROP_ELEVATION = "elevation"; <ide> private static final String PROP_RENDER_TO_HARDWARE_TEXTURE = "renderToHardwareTextureAndroid"; <ide> private static final String PROP_ACCESSIBILITY_LABEL = "accessibilityLabel"; <ide> private static final String PROP_ACCESSIBILITY_COMPONENT_TYPE = "accessibilityComponentType"; <ide> private static final String PROP_ACCESSIBILITY_LIVE_REGION = "accessibilityLiveRegion"; <ide> private static final String PROP_IMPORTANT_FOR_ACCESSIBILITY = "importantForAccessibility"; <add> private static final int PERSPECTIVE_ARRAY_INVERTED_CAMERA_DISTANCE_INDEX = 2; <add> private static final float CAMERA_DISTANCE_NORMALIZATION_MULTIPLIER = 5; <ide> <ide> // DEPRECATED <ide> private static final String PROP_ROTATION = "rotation"; <ide> private static void setTransformMatrix(View view, ReadableMap matrix) { <ide> (float) matrix.getDouble(PROP_DECOMPOSED_MATRIX_SCALE_X)); <ide> view.setScaleY( <ide> (float) matrix.getDouble(PROP_DECOMPOSED_MATRIX_SCALE_Y)); <add> <add> if (matrix.hasKey(PROP_DECOMPOSED_MATRIX_PERSPECTIVE)) { <add> ReadableArray perspectiveArray = matrix.getArray(PROP_DECOMPOSED_MATRIX_PERSPECTIVE); <add> if (perspectiveArray.size() > PERSPECTIVE_ARRAY_INVERTED_CAMERA_DISTANCE_INDEX) { <add> float cameraDistance = (float)(-1 / perspectiveArray.getDouble(PERSPECTIVE_ARRAY_INVERTED_CAMERA_DISTANCE_INDEX)); <add> float scale = DisplayMetricsHolder.getScreenDisplayMetrics().density; <add> <add> // The following converts the matrix's perspective to a camera distance <add> // such that the camera perspective looks the same on Android and iOS <add> float normalizedCameraDistance = scale * cameraDistance * CAMERA_DISTANCE_NORMALIZATION_MULTIPLIER; <add> <add> view.setCameraDistance(normalizedCameraDistance); <add> } <add> } <ide> } <ide> <ide> private static void resetTransformMatrix(View view) { <ide> private static void resetTransformMatrix(View view) { <ide> view.setScaleX(1); <ide> view.setScaleY(1); <ide> } <del>} <add>} <ide>\ No newline at end of file
1
Text
Text
revise url.resolve() text
6023bedc07bbbd6128aabe8bb9b4f193f40712c5
<ide><path>doc/api/url.md <ide> changes: <ide> <ide> > Stability: 3 - Legacy: Use the WHATWG URL API instead. <ide> <del>* `from` {string} The Base URL being resolved against. <del>* `to` {string} The HREF URL being resolved. <add>* `from` {string} The base URL to use if `to` is a relative URL. <add>* `to` {string} The target URL to resolve. <ide> <ide> The `url.resolve()` method resolves a target URL relative to a base URL in a <del>manner similar to that of a Web browser resolving an anchor tag HREF. <add>manner similar to that of a web browser resolving an anchor tag. <ide> <ide> ```js <ide> const url = require('url'); <ide> url.resolve('http://example.com/', '/one'); // 'http://example.com/one' <ide> url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' <ide> ``` <ide> <del>You can achieve the same result using the WHATWG URL API: <add>To achieve the same result using the WHATWG URL API: <ide> <ide> ```js <ide> function resolve(from, to) {
1
Python
Python
add drain option when canceling dataflow pipelines
e5713e00b3afcba6f78006ec0e360da317858e4d
<ide><path>airflow/providers/google/cloud/hooks/dataflow.py <ide> class _DataflowJobsController(LoggingMixin): <ide> :param num_retries: Maximum number of retries in case of connection problems. <ide> :param multiple_jobs: If set to true this task will be searched by name prefix (``name`` parameter), <ide> not by specific job ID, then actions will be performed on all matching jobs. <add> :param drain_pipeline: Optional, set to True if want to stop streaming job by draining it <add> instead of canceling. <ide> """ <ide> <ide> def __init__( <ide> def __init__( <ide> job_id: Optional[str] = None, <ide> num_retries: int = 0, <ide> multiple_jobs: bool = False, <add> drain_pipeline: bool = False, <ide> ) -> None: <ide> <ide> super().__init__() <ide> def __init__( <ide> self._job_id = job_id <ide> self._num_retries = num_retries <ide> self._poll_sleep = poll_sleep <add> self.drain_pipeline = drain_pipeline <ide> self._jobs: Optional[List[dict]] = None <ide> <ide> def is_job_running(self) -> bool: <ide> def get_jobs(self, refresh=False) -> List[dict]: <ide> return self._jobs <ide> <ide> def cancel(self) -> None: <del> """Cancels current job""" <add> """Cancels or drains current job""" <ide> jobs = self.get_jobs() <ide> job_ids = [job['id'] for job in jobs if job['currentState'] not in DataflowJobStatus.TERMINAL_STATES] <ide> if job_ids: <ide> batch = self._dataflow.new_batch_http_request() <ide> self.log.info("Canceling jobs: %s", ", ".join(job_ids)) <del> for job_id in job_ids: <add> for job in jobs: <add> requested_state = ( <add> DataflowJobStatus.JOB_STATE_DRAINED <add> if self.drain_pipeline and job['type'] == DataflowJobType.JOB_TYPE_STREAMING <add> else DataflowJobStatus.JOB_STATE_CANCELLED <add> ) <ide> batch.add( <ide> self._dataflow.projects() <ide> .locations() <ide> .jobs() <ide> .update( <ide> projectId=self._project_number, <ide> location=self._job_location, <del> jobId=job_id, <del> body={"requestedState": DataflowJobStatus.JOB_STATE_CANCELLED}, <add> jobId=job['id'], <add> body={"requestedState": requested_state}, <ide> ) <ide> ) <ide> batch.execute() <ide> def __init__( <ide> delegate_to: Optional[str] = None, <ide> poll_sleep: int = 10, <ide> impersonation_chain: Optional[Union[str, Sequence[str]]] = None, <add> drain_pipeline: bool = False, <ide> ) -> None: <ide> self.poll_sleep = poll_sleep <add> self.drain_pipeline = drain_pipeline <ide> super().__init__( <ide> gcp_conn_id=gcp_conn_id, <ide> delegate_to=delegate_to, <ide> def _start_dataflow( <ide> job_id=job_id, <ide> num_retries=self.num_retries, <ide> multiple_jobs=multiple_jobs, <add> drain_pipeline=self.drain_pipeline, <ide> ) <ide> job_controller.wait_for_done() <ide> <ide> def start_template_dataflow( <ide> location=location, <ide> poll_sleep=self.poll_sleep, <ide> num_retries=self.num_retries, <add> drain_pipeline=self.drain_pipeline, <ide> ) <ide> jobs_controller.wait_for_done() <ide> return response["job"] <ide> def is_job_dataflow_running( <ide> name=name, <ide> location=location, <ide> poll_sleep=self.poll_sleep, <add> drain_pipeline=self.drain_pipeline, <ide> ) <ide> return jobs_controller.is_job_running() <ide> <ide> def cancel_job( <ide> job_id=job_id, <ide> location=location, <ide> poll_sleep=self.poll_sleep, <add> drain_pipeline=self.drain_pipeline, <ide> ) <ide> jobs_controller.cancel() <ide><path>airflow/providers/google/cloud/operators/dataflow.py <ide> def __init__( <ide> <ide> def execute(self, context): <ide> self.hook = DataflowHook( <del> gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, poll_sleep=self.poll_sleep <add> gcp_conn_id=self.gcp_conn_id, <add> delegate_to=self.delegate_to, <add> poll_sleep=self.poll_sleep, <ide> ) <ide> dataflow_options = copy.copy(self.dataflow_default_options) <ide> dataflow_options.update(self.options) <ide> class DataflowStartFlexTemplateOperator(BaseOperator): <ide> For this to work, the service account making the request must have <ide> domain-wide delegation enabled. <ide> :type delegate_to: str <add> :param drain_pipeline: Optional, set to True if want to stop streaming job by draining it <add> instead of canceling during during killing task instance. See: <add> https://cloud.google.com/dataflow/docs/guides/stopping-a-pipeline <add> :type drain_pipeline: bool <ide> """ <ide> <ide> template_fields = ["body", 'location', 'project_id', 'gcp_conn_id'] <ide> def __init__( <ide> project_id: Optional[str] = None, <ide> gcp_conn_id: str = 'google_cloud_default', <ide> delegate_to: Optional[str] = None, <add> drain_pipeline: bool = False, <ide> *args, <ide> **kwargs, <ide> ) -> None: <ide> def __init__( <ide> self.delegate_to = delegate_to <ide> self.job_id = None <ide> self.hook: Optional[DataflowHook] = None <add> self.drain_pipeline = drain_pipeline <ide> <ide> def execute(self, context): <ide> self.hook = DataflowHook( <del> gcp_conn_id=self.gcp_conn_id, <del> delegate_to=self.delegate_to, <add> gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, drain_pipeline=self.drain_pipeline <ide> ) <ide> <ide> def set_current_job_id(job_id): <ide> def on_kill(self) -> None: <ide> self.hook.cancel_job(job_id=self.job_id, project_id=self.project_id) <ide> <ide> <add># pylint: disable=too-many-instance-attributes <ide> class DataflowCreatePythonJobOperator(BaseOperator): <ide> """ <ide> Launching Cloud Dataflow jobs written in python. Note that both <ide> class DataflowCreatePythonJobOperator(BaseOperator): <ide> Cloud Platform for the dataflow job status while the job is in the <ide> JOB_STATE_RUNNING state. <ide> :type poll_sleep: int <add> :param drain_pipeline: Optional, set to True if want to stop streaming job by draining it <add> instead of canceling during during killing task instance. See: <add> https://cloud.google.com/dataflow/docs/guides/stopping-a-pipeline <add> :type drain_pipeline: bool <ide> """ <ide> <ide> template_fields = ['options', 'dataflow_default_options', 'job_name', 'py_file'] <ide> def __init__( # pylint: disable=too-many-arguments <ide> gcp_conn_id: str = 'google_cloud_default', <ide> delegate_to: Optional[str] = None, <ide> poll_sleep: int = 10, <add> drain_pipeline: bool = False, <ide> **kwargs, <ide> ) -> None: <ide> <ide> def __init__( # pylint: disable=too-many-arguments <ide> self.gcp_conn_id = gcp_conn_id <ide> self.delegate_to = delegate_to <ide> self.poll_sleep = poll_sleep <add> self.drain_pipeline = drain_pipeline <ide> self.job_id = None <ide> self.hook = None <ide> <ide> def execute(self, context): <ide> self.py_file = tmp_gcs_file.name <ide> <ide> self.hook = DataflowHook( <del> gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, poll_sleep=self.poll_sleep <add> gcp_conn_id=self.gcp_conn_id, <add> delegate_to=self.delegate_to, <add> poll_sleep=self.poll_sleep, <add> drain_pipeline=self.drain_pipeline, <ide> ) <ide> dataflow_options = self.dataflow_default_options.copy() <ide> dataflow_options.update(self.options) <ide><path>tests/providers/google/cloud/hooks/test_dataflow.py <ide> def test_start_template_dataflow(self, mock_conn, mock_controller, mock_uuid): <ide> poll_sleep=10, <ide> project_number=TEST_PROJECT, <ide> location=DEFAULT_DATAFLOW_LOCATION, <add> drain_pipeline=False, <ide> ) <ide> mock_controller.return_value.wait_for_done.assert_called_once() <ide> <ide> def test_start_template_dataflow_with_custom_region_as_variable( <ide> poll_sleep=10, <ide> project_number=TEST_PROJECT, <ide> location=TEST_LOCATION, <add> drain_pipeline=False, <ide> ) <ide> mock_controller.return_value.wait_for_done.assert_called_once() <ide> <ide> def test_start_template_dataflow_with_custom_region_as_parameter( <ide> poll_sleep=10, <ide> project_number=TEST_PROJECT, <ide> location=TEST_LOCATION, <add> drain_pipeline=False, <ide> ) <ide> mock_controller.return_value.wait_for_done.assert_called_once() <ide> <ide> def test_start_template_dataflow_with_runtime_env(self, mock_conn, mock_dataflow <ide> num_retries=5, <ide> poll_sleep=10, <ide> project_number=TEST_PROJECT, <add> drain_pipeline=False, <ide> ) <ide> mock_uuid.assert_called_once_with() <ide> <ide> def test_start_template_dataflow_update_runtime_env(self, mock_conn, mock_datafl <ide> num_retries=5, <ide> poll_sleep=10, <ide> project_number=TEST_PROJECT, <add> drain_pipeline=False, <ide> ) <ide> mock_uuid.assert_called_once_with() <ide> <ide> def test_cancel_job(self, mock_get_conn, jobs_controller): <ide> name=UNIQUE_JOB_NAME, <ide> poll_sleep=10, <ide> project_number=TEST_PROJECT, <add> drain_pipeline=False, <ide> ) <ide> jobs_controller.cancel() <ide> <ide> def test_dataflow_job_cancel_job(self): <ide> ) <ide> mock_batch.add.assert_called_once_with(mock_update.return_value) <ide> <add> @parameterized.expand( <add> [ <add> (False, "JOB_TYPE_BATCH", "JOB_STATE_CANCELLED"), <add> (False, "JOB_TYPE_STREAMING", "JOB_STATE_CANCELLED"), <add> (True, "JOB_TYPE_BATCH", "JOB_STATE_CANCELLED"), <add> (True, "JOB_TYPE_STREAMING", "JOB_STATE_DRAINED"), <add> ] <add> ) <add> def test_dataflow_job_cancel_or_drain_job(self, drain_pipeline, job_type, requested_state): <add> job = { <add> "id": TEST_JOB_ID, <add> "name": UNIQUE_JOB_NAME, <add> "currentState": DataflowJobStatus.JOB_STATE_RUNNING, <add> "type": job_type, <add> } <add> get_method = self.mock_dataflow.projects.return_value.locations.return_value.jobs.return_value.get <add> get_method.return_value.execute.return_value = job <add> # fmt: off <add> job_list_nest_method = (self.mock_dataflow <add> .projects.return_value. <add> locations.return_value. <add> jobs.return_value.list_next) <add> job_list_nest_method.return_value = None <add> # fmt: on <add> dataflow_job = _DataflowJobsController( <add> dataflow=self.mock_dataflow, <add> project_number=TEST_PROJECT, <add> name=UNIQUE_JOB_NAME, <add> location=TEST_LOCATION, <add> poll_sleep=10, <add> job_id=TEST_JOB_ID, <add> num_retries=20, <add> multiple_jobs=False, <add> drain_pipeline=drain_pipeline, <add> ) <add> dataflow_job.cancel() <add> <add> get_method.assert_called_once_with(jobId=TEST_JOB_ID, location=TEST_LOCATION, projectId=TEST_PROJECT) <add> <add> get_method.return_value.execute.assert_called_once_with(num_retries=20) <add> <add> self.mock_dataflow.new_batch_http_request.assert_called_once_with() <add> <add> mock_batch = self.mock_dataflow.new_batch_http_request.return_value <add> mock_update = self.mock_dataflow.projects.return_value.locations.return_value.jobs.return_value.update <add> mock_update.assert_called_once_with( <add> body={'requestedState': requested_state}, <add> jobId='test-job-id', <add> location=TEST_LOCATION, <add> projectId='test-project', <add> ) <add> mock_batch.add.assert_called_once_with(mock_update.return_value) <add> mock_batch.execute.assert_called_once() <add> <ide> def test_dataflow_job_cancel_job_no_running_jobs(self): <ide> mock_jobs = self.mock_dataflow.projects.return_value.locations.return_value.jobs <ide> get_method = mock_jobs.return_value.get <ide><path>tests/providers/google/cloud/operators/test_mlengine_utils.py <ide> def test_successful_run(self): <ide> hook_instance.start_python_dataflow.return_value = None <ide> summary.execute(None) <ide> mock_dataflow_hook.assert_called_once_with( <del> gcp_conn_id='google_cloud_default', delegate_to=None, poll_sleep=10 <add> gcp_conn_id='google_cloud_default', delegate_to=None, poll_sleep=10, drain_pipeline=False <ide> ) <ide> hook_instance.start_python_dataflow.assert_called_once_with( <ide> job_name='{{task.task_id}}',
4
Javascript
Javascript
fix broken symbolication
ad95aea51dceae1df82f8a8972357aae414e24aa
<ide><path>packager/react-packager/src/Server/index.js <ide> class Server { <ide> const symbolicatingLogEntry = <ide> print(log(createActionStartEntry('Symbolicating'))); <ide> <del> new Promise.resolve(req.rawBody).then(body => { <add> Promise.resolve(req.rawBody).then(body => { <ide> const stack = JSON.parse(body).stack; <ide> <ide> // In case of multiple bundles / HMR, some stack frames can have
1
Ruby
Ruby
remove lasgn since ast is mutated
0042054ea873a8d25d9bbdc4c7fe0febe1b76042
<ide><path>activerecord/lib/active_record/associations/class_methods/join_dependency/join_association.rb <ide> def join_target_table(relation, condition) <ide> conditions << process_conditions(options[:conditions], aliased_table_name) <ide> end <ide> <del> join = relation.join(target_table, join_type) <add> ands = relation.create_and(conditions) <ide> <del> join.on(*conditions) <add> join = relation.create_join( <add> relation.froms.first, <add> target_table, <add> relation.create_on(ands), <add> join_type) <add> <add> relation.from join <ide> end <ide> <ide> def join_has_and_belongs_to_many_to(relation) <ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def build_joins(manager, joins) <ide> <ide> # FIXME: refactor this to build an AST <ide> join_dependency.join_associations.each do |association| <del> manager = association.join_to(manager) <add> association.join_to(manager) <ide> end <ide> <ide> return manager unless join_ast
2
Java
Java
add blank line between java and javax imports
d945ae919140b4f7436ffb8c4b6bc1843c264bad
<ide><path>spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.accessibility.Accessible; <ide> import javax.swing.JFrame; <ide> import javax.swing.RootPaneContainer; <ide><path>spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedJCacheableService.java <ide> import java.io.IOException; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.atomic.AtomicLong; <add> <ide> import javax.cache.annotation.CacheDefaults; <ide> import javax.cache.annotation.CacheKey; <ide> import javax.cache.annotation.CachePut; <ide><path>spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java <ide> package org.springframework.transaction.aspectj; <ide> <ide> import java.io.IOException; <add> <ide> import javax.transaction.Transactional; <ide> <ide> import org.junit.Before; <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/ProviderCreatingFactoryBean.java <ide> package org.springframework.beans.factory.config; <ide> <ide> import java.io.Serializable; <add> <ide> import javax.inject.Provider; <ide> <ide> import org.springframework.beans.BeansException; <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java <ide> import java.util.function.Consumer; <ide> import java.util.function.Predicate; <ide> import java.util.stream.Stream; <add> <ide> import javax.inject.Provider; <ide> <ide> import org.springframework.beans.BeanUtils; <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java <ide> import java.io.InputStream; <ide> import java.util.HashSet; <ide> import java.util.Set; <add> <ide> import javax.xml.parsers.ParserConfigurationException; <ide> <ide> import org.w3c.dom.Document; <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java <ide> import java.util.Set; <ide> import java.util.concurrent.Callable; <ide> import java.util.stream.Collectors; <add> <ide> import javax.annotation.Priority; <ide> import javax.security.auth.Subject; <ide> <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Optional; <add> <ide> import javax.inject.Inject; <ide> import javax.inject.Named; <ide> import javax.inject.Provider; <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java <ide> package org.springframework.beans.factory.config; <ide> <ide> import java.util.Date; <add> <ide> import javax.inject.Provider; <ide> <ide> import org.junit.After; <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/serviceloader/ServiceLoaderTests.java <ide> <ide> import java.util.List; <ide> import java.util.ServiceLoader; <add> <ide> import javax.xml.parsers.DocumentBuilderFactory; <ide> <ide> import org.junit.Test; <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java <ide> import java.security.ProtectionDomain; <ide> import java.util.PropertyPermission; <ide> import java.util.Set; <add> <ide> import javax.security.auth.AuthPermission; <ide> import javax.security.auth.Subject; <ide> <ide><path>spring-context-indexer/src/main/java/org/springframework/context/index/processor/CandidateComponentsIndexer.java <ide> import java.util.LinkedHashSet; <ide> import java.util.List; <ide> import java.util.Set; <add> <ide> import javax.annotation.processing.Completion; <ide> import javax.annotation.processing.ProcessingEnvironment; <ide> import javax.annotation.processing.Processor; <ide><path>spring-context-indexer/src/main/java/org/springframework/context/index/processor/IndexedStereotypesProvider.java <ide> import java.util.HashSet; <ide> import java.util.LinkedHashSet; <ide> import java.util.Set; <add> <ide> import javax.lang.model.element.AnnotationMirror; <ide> import javax.lang.model.element.Element; <ide> import javax.lang.model.element.ElementKind; <ide><path>spring-context-indexer/src/main/java/org/springframework/context/index/processor/MetadataCollector.java <ide> import java.util.HashSet; <ide> import java.util.List; <ide> import java.util.Set; <add> <ide> import javax.annotation.processing.ProcessingEnvironment; <ide> import javax.annotation.processing.RoundEnvironment; <ide> import javax.lang.model.element.Element; <ide><path>spring-context-indexer/src/main/java/org/springframework/context/index/processor/MetadataStore.java <ide> import java.io.IOException; <ide> import java.io.InputStream; <ide> import java.io.OutputStream; <add> <ide> import javax.annotation.processing.ProcessingEnvironment; <ide> import javax.tools.FileObject; <ide> import javax.tools.StandardLocation; <ide><path>spring-context-indexer/src/main/java/org/springframework/context/index/processor/PackageInfoStereotypesProvider.java <ide> <ide> import java.util.HashSet; <ide> import java.util.Set; <add> <ide> import javax.lang.model.element.Element; <ide> import javax.lang.model.element.ElementKind; <ide> <ide><path>spring-context-indexer/src/main/java/org/springframework/context/index/processor/StandardStereotypesProvider.java <ide> <ide> import java.util.LinkedHashSet; <ide> import java.util.Set; <add> <ide> import javax.lang.model.element.AnnotationMirror; <ide> import javax.lang.model.element.Element; <ide> import javax.lang.model.element.ElementKind; <ide><path>spring-context-indexer/src/main/java/org/springframework/context/index/processor/StereotypesProvider.java <ide> package org.springframework.context.index.processor; <ide> <ide> import java.util.Set; <add> <ide> import javax.lang.model.element.Element; <ide> <ide> /** <ide><path>spring-context-indexer/src/main/java/org/springframework/context/index/processor/TypeHelper.java <ide> import java.util.ArrayList; <ide> import java.util.Collections; <ide> import java.util.List; <add> <ide> import javax.annotation.processing.ProcessingEnvironment; <ide> import javax.lang.model.element.AnnotationMirror; <ide> import javax.lang.model.element.Element; <ide><path>spring-context-indexer/src/test/java/org/springframework/context/index/processor/CandidateComponentsIndexerTests.java <ide> import java.io.File; <ide> import java.io.FileInputStream; <ide> import java.io.IOException; <add> <ide> import javax.annotation.ManagedBean; <ide> import javax.inject.Named; <ide> import javax.persistence.Converter; <ide> import org.springframework.context.index.sample.MetaControllerIndexed; <ide> import org.springframework.context.index.sample.SampleComponent; <ide> import org.springframework.context.index.sample.SampleController; <add>import org.springframework.context.index.sample.SampleEmbedded; <ide> import org.springframework.context.index.sample.SampleMetaController; <ide> import org.springframework.context.index.sample.SampleMetaIndexedController; <ide> import org.springframework.context.index.sample.SampleNonStaticEmbedded; <ide> import org.springframework.context.index.sample.cdi.SampleTransactional; <ide> import org.springframework.context.index.sample.jpa.SampleConverter; <ide> import org.springframework.context.index.sample.jpa.SampleEmbeddable; <del>import org.springframework.context.index.sample.SampleEmbedded; <ide> import org.springframework.context.index.sample.jpa.SampleEntity; <ide> import org.springframework.context.index.sample.jpa.SampleMappedSuperClass; <ide> import org.springframework.context.index.sample.type.Repo; <ide><path>spring-context-indexer/src/test/java/org/springframework/context/index/test/TestCompiler.java <ide> import java.util.Collections; <ide> import java.util.List; <ide> import java.util.stream.Collectors; <add> <ide> import javax.annotation.processing.Processor; <ide> import javax.tools.JavaCompiler; <ide> import javax.tools.JavaFileObject; <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCache.java <ide> package org.springframework.cache.jcache; <ide> <ide> import java.util.concurrent.Callable; <add> <ide> import javax.cache.Cache; <ide> import javax.cache.processor.EntryProcessor; <ide> import javax.cache.processor.EntryProcessorException; <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCacheManager.java <ide> <ide> import java.util.Collection; <ide> import java.util.LinkedHashSet; <add> <ide> import javax.cache.CacheManager; <ide> import javax.cache.Caching; <ide> <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheManagerFactoryBean.java <ide> <ide> import java.net.URI; <ide> import java.util.Properties; <add> <ide> import javax.cache.CacheManager; <ide> import javax.cache.Caching; <ide> <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/AbstractJCacheKeyOperation.java <ide> import java.lang.annotation.Annotation; <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> import javax.cache.annotation.CacheMethodDetails; <ide> <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/AbstractJCacheOperation.java <ide> import java.util.LinkedHashSet; <ide> import java.util.List; <ide> import java.util.Set; <add> <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> import javax.cache.annotation.CacheKey; <ide> import javax.cache.annotation.CacheMethodDetails; <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/AbstractKeyCacheInterceptor.java <ide> package org.springframework.cache.jcache.interceptor; <ide> <ide> import java.lang.annotation.Annotation; <add> <ide> import javax.cache.annotation.CacheKeyInvocationContext; <ide> <ide> import org.springframework.cache.interceptor.CacheErrorHandler; <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/AnnotationJCacheOperationSource.java <ide> import java.lang.reflect.Method; <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.cache.annotation.CacheDefaults; <ide> import javax.cache.annotation.CacheKeyGenerator; <ide> import javax.cache.annotation.CacheMethodDetails; <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/CachePutOperation.java <ide> <ide> import java.lang.reflect.Method; <ide> import java.util.List; <add> <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> import javax.cache.annotation.CacheMethodDetails; <ide> import javax.cache.annotation.CachePut; <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/CacheResolverAdapter.java <ide> <ide> import java.util.Collection; <ide> import java.util.Collections; <add> <ide> import javax.cache.annotation.CacheInvocationContext; <ide> <ide> import org.springframework.cache.Cache; <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/DefaultCacheInvocationContext.java <ide> import java.lang.reflect.Method; <ide> import java.util.Arrays; <ide> import java.util.Set; <add> <ide> import javax.cache.annotation.CacheInvocationContext; <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/DefaultCacheKeyInvocationContext.java <ide> package org.springframework.cache.jcache.interceptor; <ide> <ide> import java.lang.annotation.Annotation; <add> <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> import javax.cache.annotation.CacheKeyInvocationContext; <ide> <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/DefaultCacheMethodDetails.java <ide> import java.util.Collections; <ide> import java.util.LinkedHashSet; <ide> import java.util.Set; <add> <ide> import javax.cache.annotation.CacheMethodDetails; <ide> <ide> /** <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheOperation.java <ide> package org.springframework.cache.jcache.interceptor; <ide> <ide> import java.lang.annotation.Annotation; <add> <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> import javax.cache.annotation.CacheMethodDetails; <ide> <ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/KeyGeneratorAdapter.java <ide> import java.lang.reflect.Method; <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> import javax.cache.annotation.CacheKeyGenerator; <ide> import javax.cache.annotation.CacheKeyInvocationContext; <ide><path>spring-context-support/src/main/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMap.java <ide> import java.io.File; <ide> import java.io.IOException; <ide> import java.io.InputStream; <add> <ide> import javax.activation.FileTypeMap; <ide> import javax.activation.MimetypesFileTypeMap; <ide> <ide><path>spring-context-support/src/main/java/org/springframework/mail/javamail/InternetAddressEditor.java <ide> package org.springframework.mail.javamail; <ide> <ide> import java.beans.PropertyEditorSupport; <add> <ide> import javax.mail.internet.AddressException; <ide> import javax.mail.internet.InternetAddress; <ide> <ide><path>spring-context-support/src/main/java/org/springframework/mail/javamail/JavaMailSender.java <ide> package org.springframework.mail.javamail; <ide> <ide> import java.io.InputStream; <add> <ide> import javax.mail.internet.MimeMessage; <ide> <ide> import org.springframework.mail.MailException; <ide><path>spring-context-support/src/main/java/org/springframework/mail/javamail/JavaMailSenderImpl.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Properties; <add> <ide> import javax.activation.FileTypeMap; <ide> import javax.mail.Address; <ide> import javax.mail.AuthenticationFailedException; <ide><path>spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMailMessage.java <ide> package org.springframework.mail.javamail; <ide> <ide> import java.util.Date; <add> <ide> import javax.mail.MessagingException; <ide> import javax.mail.internet.MimeMessage; <ide> <ide><path>spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java <ide> import java.io.OutputStream; <ide> import java.io.UnsupportedEncodingException; <ide> import java.util.Date; <add> <ide> import javax.activation.DataHandler; <ide> import javax.activation.DataSource; <ide> import javax.activation.FileDataSource; <ide><path>spring-context-support/src/main/java/org/springframework/scheduling/commonj/TimerManagerFactoryBean.java <ide> <ide> import java.util.LinkedList; <ide> import java.util.List; <add> <ide> import javax.naming.NamingException; <ide> <ide> import commonj.timers.Timer; <ide><path>spring-context-support/src/main/java/org/springframework/scheduling/commonj/WorkManagerTaskExecutor.java <ide> import java.util.concurrent.Callable; <ide> import java.util.concurrent.Future; <ide> import java.util.concurrent.FutureTask; <add> <ide> import javax.naming.NamingException; <ide> <ide> import commonj.work.Work; <ide><path>spring-context-support/src/main/java/org/springframework/scheduling/quartz/LocalDataSourceJobStore.java <ide> <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.quartz.SchedulerConfigException; <ide><path>spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java <ide> import java.util.Properties; <ide> import java.util.concurrent.Executor; <ide> import java.util.concurrent.TimeUnit; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.quartz.Scheduler; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/JCacheCacheManagerTests.java <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.cache.Cache; <ide> import javax.cache.CacheManager; <ide> <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AbstractCacheOperationTests.java <ide> <ide> import java.lang.annotation.Annotation; <ide> import java.lang.reflect.Method; <add> <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> import javax.cache.annotation.CacheMethodDetails; <ide> <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AnnotatedJCacheableService.java <ide> import java.io.IOException; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.atomic.AtomicLong; <add> <ide> import javax.cache.annotation.CacheDefaults; <ide> import javax.cache.annotation.CacheKey; <ide> import javax.cache.annotation.CachePut; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AnnotationCacheOperationSourceTests.java <ide> <ide> import java.lang.reflect.Method; <ide> import java.util.Comparator; <add> <ide> import javax.cache.annotation.CacheDefaults; <ide> import javax.cache.annotation.CacheKeyGenerator; <ide> import javax.cache.annotation.CacheRemove; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CachePutOperationTests.java <ide> package org.springframework.cache.jcache.interceptor; <ide> <ide> import java.io.IOException; <add> <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> import javax.cache.annotation.CacheMethodDetails; <ide> import javax.cache.annotation.CachePut; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResolverAdapterTests.java <ide> import java.lang.annotation.Annotation; <ide> import java.lang.reflect.Method; <ide> import java.util.Collection; <add> <ide> import javax.cache.annotation.CacheInvocationContext; <ide> import javax.cache.annotation.CacheMethodDetails; <ide> import javax.cache.annotation.CacheResolver; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResultOperationTests.java <ide> import java.io.IOException; <ide> import java.lang.annotation.Annotation; <ide> import java.util.Set; <add> <ide> import javax.cache.annotation.CacheInvocationParameter; <ide> import javax.cache.annotation.CacheKey; <ide> import javax.cache.annotation.CacheMethodDetails; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheErrorHandlerTests.java <ide> <ide> import java.util.Arrays; <ide> import java.util.concurrent.atomic.AtomicLong; <add> <ide> import javax.cache.annotation.CacheDefaults; <ide> import javax.cache.annotation.CachePut; <ide> import javax.cache.annotation.CacheRemove; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheKeyGeneratorTests.java <ide> import java.lang.reflect.Method; <ide> import java.util.Arrays; <ide> import java.util.concurrent.atomic.AtomicLong; <add> <ide> import javax.cache.annotation.CacheDefaults; <ide> import javax.cache.annotation.CacheKey; <ide> import javax.cache.annotation.CacheResult; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/support/TestableCacheKeyGenerator.java <ide> package org.springframework.cache.jcache.support; <ide> <ide> import java.lang.annotation.Annotation; <add> <ide> import javax.cache.annotation.CacheKeyGenerator; <ide> import javax.cache.annotation.CacheKeyInvocationContext; <ide> import javax.cache.annotation.GeneratedCacheKey; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/support/TestableCacheResolver.java <ide> package org.springframework.cache.jcache.support; <ide> <ide> import java.lang.annotation.Annotation; <add> <ide> import javax.cache.Cache; <ide> import javax.cache.annotation.CacheInvocationContext; <ide> import javax.cache.annotation.CacheResolver; <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/support/TestableCacheResolverFactory.java <ide> package org.springframework.cache.jcache.support; <ide> <ide> import java.lang.annotation.Annotation; <add> <ide> import javax.cache.annotation.CacheMethodDetails; <ide> import javax.cache.annotation.CacheResolver; <ide> import javax.cache.annotation.CacheResolverFactory; <ide><path>spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java <ide> import java.util.GregorianCalendar; <ide> import java.util.List; <ide> import java.util.Properties; <add> <ide> import javax.activation.FileTypeMap; <ide> import javax.mail.Address; <ide> import javax.mail.Message; <ide><path>spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java <ide> <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Test; <ide><path>spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/MethodValidationTests.java <ide> <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <add> <ide> import javax.validation.Validator; <ide> import javax.validation.constraints.Max; <ide> import javax.validation.constraints.NotNull; <ide><path>spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/SpringValidatorAdapterTests.java <ide> import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.validation.Constraint; <ide> import javax.validation.ConstraintValidator; <ide> import javax.validation.ConstraintValidatorContext; <ide><path>spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/ValidatorFactoryTests.java <ide> import java.util.List; <ide> import java.util.Optional; <ide> import java.util.Set; <add> <ide> import javax.validation.Constraint; <ide> import javax.validation.ConstraintValidator; <ide> import javax.validation.ConstraintValidatorContext; <ide><path>spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java <ide> import java.util.Map; <ide> import java.util.Set; <ide> import java.util.concurrent.ConcurrentHashMap; <add> <ide> import javax.annotation.PostConstruct; <ide> import javax.annotation.PreDestroy; <ide> import javax.annotation.Resource; <ide><path>spring-context/src/main/java/org/springframework/context/annotation/MBeanExportConfiguration.java <ide> package org.springframework.context.annotation; <ide> <ide> import java.util.Map; <add> <ide> import javax.management.MBeanServer; <ide> import javax.naming.NamingException; <ide> <ide><path>spring-context/src/main/java/org/springframework/context/support/LiveBeansView.java <ide> import java.util.Iterator; <ide> import java.util.LinkedHashSet; <ide> import java.util.Set; <add> <ide> import javax.management.MBeanServer; <ide> import javax.management.ObjectName; <ide> <ide><path>spring-context/src/main/java/org/springframework/ejb/access/AbstractRemoteSlsbInvokerInterceptor.java <ide> import java.lang.reflect.InvocationTargetException; <ide> import java.lang.reflect.Method; <ide> import java.rmi.RemoteException; <add> <ide> import javax.ejb.EJBHome; <ide> import javax.ejb.EJBObject; <ide> import javax.naming.NamingException; <ide><path>spring-context/src/main/java/org/springframework/ejb/access/AbstractSlsbInvokerInterceptor.java <ide> <ide> import java.lang.reflect.InvocationTargetException; <ide> import java.lang.reflect.Method; <add> <ide> import javax.naming.Context; <ide> import javax.naming.NamingException; <ide> <ide><path>spring-context/src/main/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptor.java <ide> <ide> import java.lang.reflect.InvocationTargetException; <ide> import java.lang.reflect.Method; <add> <ide> import javax.ejb.CreateException; <ide> import javax.ejb.EJBLocalHome; <ide> import javax.ejb.EJBLocalObject; <ide><path>spring-context/src/main/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptor.java <ide> <ide> import java.lang.reflect.InvocationTargetException; <ide> import java.rmi.RemoteException; <add> <ide> import javax.ejb.CreateException; <ide> import javax.ejb.EJBObject; <ide> import javax.naming.NamingException; <ide><path>spring-context/src/main/java/org/springframework/format/number/money/CurrencyUnitFormatter.java <ide> package org.springframework.format.number.money; <ide> <ide> import java.util.Locale; <add> <ide> import javax.money.CurrencyUnit; <ide> import javax.money.Monetary; <ide> <ide><path>spring-context/src/main/java/org/springframework/format/number/money/Jsr354NumberFormatAnnotationFormatterFactory.java <ide> import java.util.Currency; <ide> import java.util.Locale; <ide> import java.util.Set; <add> <ide> import javax.money.CurrencyUnit; <ide> import javax.money.Monetary; <ide> import javax.money.MonetaryAmount; <ide><path>spring-context/src/main/java/org/springframework/format/number/money/MonetaryAmountFormatter.java <ide> package org.springframework.format.number.money; <ide> <ide> import java.util.Locale; <add> <ide> import javax.money.MonetaryAmount; <ide> import javax.money.format.MonetaryAmountFormat; <ide> import javax.money.format.MonetaryFormats; <ide><path>spring-context/src/main/java/org/springframework/jmx/access/ConnectorDelegate.java <ide> <ide> import java.io.IOException; <ide> import java.util.Map; <add> <ide> import javax.management.MBeanServerConnection; <ide> import javax.management.remote.JMXConnector; <ide> import javax.management.remote.JMXConnectorFactory; <ide><path>spring-context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java <ide> import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.management.Attribute; <ide> import javax.management.InstanceNotFoundException; <ide> import javax.management.IntrospectionException; <ide><path>spring-context/src/main/java/org/springframework/jmx/access/NotificationListenerRegistrar.java <ide> import java.net.MalformedURLException; <ide> import java.util.Arrays; <ide> import java.util.Map; <add> <ide> import javax.management.MBeanServerConnection; <ide> import javax.management.ObjectName; <ide> import javax.management.remote.JMXServiceURL; <ide><path>spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.management.DynamicMBean; <ide> import javax.management.JMException; <ide> import javax.management.MBeanException; <ide><path>spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractConfigurableMBeanInfoAssembler.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.management.modelmbean.ModelMBeanNotificationInfo; <ide> <ide> import org.springframework.jmx.export.metadata.JmxMetadataUtils; <ide><path>spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java <ide> import java.lang.reflect.Method; <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.management.Descriptor; <ide> import javax.management.JMException; <ide> import javax.management.MBeanOperationInfo; <ide><path>spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java <ide> <ide> import java.beans.PropertyDescriptor; <ide> import java.lang.reflect.Method; <add> <ide> import javax.management.Descriptor; <ide> import javax.management.MBeanParameterInfo; <ide> import javax.management.modelmbean.ModelMBeanNotificationInfo; <ide><path>spring-context/src/main/java/org/springframework/jmx/export/naming/IdentityNamingStrategy.java <ide> package org.springframework.jmx.export.naming; <ide> <ide> import java.util.Hashtable; <add> <ide> import javax.management.MalformedObjectNameException; <ide> import javax.management.ObjectName; <ide> <ide><path>spring-context/src/main/java/org/springframework/jmx/export/naming/KeyNamingStrategy.java <ide> <ide> import java.io.IOException; <ide> import java.util.Properties; <add> <ide> import javax.management.MalformedObjectNameException; <ide> import javax.management.ObjectName; <ide> <ide><path>spring-context/src/main/java/org/springframework/jmx/export/naming/MetadataNamingStrategy.java <ide> package org.springframework.jmx.export.naming; <ide> <ide> import java.util.Hashtable; <add> <ide> import javax.management.MalformedObjectNameException; <ide> import javax.management.ObjectName; <ide> <ide><path>spring-context/src/main/java/org/springframework/jmx/support/ConnectorServerFactoryBean.java <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> import java.util.Properties; <add> <ide> import javax.management.JMException; <ide> import javax.management.MBeanServer; <ide> import javax.management.MalformedObjectNameException; <ide><path>spring-context/src/main/java/org/springframework/jmx/support/JmxUtils.java <ide> import java.lang.reflect.Method; <ide> import java.util.Hashtable; <ide> import java.util.List; <add> <ide> import javax.management.DynamicMBean; <ide> import javax.management.JMX; <ide> import javax.management.MBeanParameterInfo; <ide><path>spring-context/src/main/java/org/springframework/jmx/support/MBeanRegistrationSupport.java <ide> <ide> import java.util.LinkedHashSet; <ide> import java.util.Set; <add> <ide> import javax.management.InstanceAlreadyExistsException; <ide> import javax.management.InstanceNotFoundException; <ide> import javax.management.JMException; <ide><path>spring-context/src/main/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBean.java <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> import java.util.Properties; <add> <ide> import javax.management.MBeanServerConnection; <ide> import javax.management.remote.JMXConnector; <ide> import javax.management.remote.JMXConnectorFactory; <ide><path>spring-context/src/main/java/org/springframework/jmx/support/NotificationListenerHolder.java <ide> import java.util.Collections; <ide> import java.util.LinkedHashSet; <ide> import java.util.Set; <add> <ide> import javax.management.MalformedObjectNameException; <ide> import javax.management.NotificationFilter; <ide> import javax.management.NotificationListener; <ide><path>spring-context/src/main/java/org/springframework/jmx/support/ObjectNameManager.java <ide> package org.springframework.jmx.support; <ide> <ide> import java.util.Hashtable; <add> <ide> import javax.management.MalformedObjectNameException; <ide> import javax.management.ObjectName; <ide> <ide><path>spring-context/src/main/java/org/springframework/jmx/support/WebSphereMBeanServerFactoryBean.java <ide> <ide> import java.lang.reflect.InvocationTargetException; <ide> import java.lang.reflect.Method; <add> <ide> import javax.management.MBeanServer; <ide> <ide> import org.springframework.beans.factory.FactoryBean; <ide><path>spring-context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java <ide> <ide> import java.lang.reflect.Method; <ide> import java.lang.reflect.Modifier; <add> <ide> import javax.naming.Context; <ide> import javax.naming.NamingException; <ide> <ide><path>spring-context/src/main/java/org/springframework/jndi/JndiTemplate.java <ide> <ide> import java.util.Hashtable; <ide> import java.util.Properties; <add> <ide> import javax.naming.Context; <ide> import javax.naming.InitialContext; <ide> import javax.naming.NameNotFoundException; <ide><path>spring-context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java <ide> import java.util.HashSet; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.naming.NameNotFoundException; <ide> import javax.naming.NamingException; <ide> <ide><path>spring-context/src/main/java/org/springframework/remoting/rmi/JndiRmiClientInterceptor.java <ide> import java.lang.reflect.InvocationTargetException; <ide> import java.lang.reflect.Method; <ide> import java.rmi.RemoteException; <add> <ide> import javax.naming.Context; <ide> import javax.naming.NamingException; <ide> <ide><path>spring-context/src/main/java/org/springframework/remoting/rmi/JndiRmiServiceExporter.java <ide> import java.rmi.Remote; <ide> import java.rmi.RemoteException; <ide> import java.util.Properties; <add> <ide> import javax.naming.NamingException; <ide> <ide> import org.springframework.beans.factory.DisposableBean; <ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutor.java <ide> import java.util.concurrent.Executor; <ide> import java.util.concurrent.Executors; <ide> import java.util.concurrent.Future; <add> <ide> import javax.enterprise.concurrent.ManagedExecutors; <ide> import javax.enterprise.concurrent.ManagedTask; <ide> <ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/ConcurrentTaskScheduler.java <ide> import java.util.concurrent.ScheduledExecutorService; <ide> import java.util.concurrent.ScheduledFuture; <ide> import java.util.concurrent.TimeUnit; <add> <ide> import javax.enterprise.concurrent.LastExecution; <ide> import javax.enterprise.concurrent.ManagedScheduledExecutorService; <ide> <ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedAwareThreadFactory.java <ide> <ide> import java.util.Properties; <ide> import java.util.concurrent.ThreadFactory; <add> <ide> import javax.naming.NamingException; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedTaskExecutor.java <ide> <ide> import java.util.Properties; <ide> import java.util.concurrent.Executor; <add> <ide> import javax.naming.NamingException; <ide> <ide> import org.springframework.beans.factory.InitializingBean; <ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedTaskScheduler.java <ide> <ide> import java.util.Properties; <ide> import java.util.concurrent.ScheduledExecutorService; <add> <ide> import javax.naming.NamingException; <ide> <ide> import org.springframework.beans.factory.InitializingBean; <ide><path>spring-context/src/main/java/org/springframework/scripting/support/StandardScriptEvaluator.java <ide> <ide> import java.io.IOException; <ide> import java.util.Map; <add> <ide> import javax.script.Bindings; <ide> import javax.script.ScriptEngine; <ide> import javax.script.ScriptEngineManager; <ide><path>spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java <ide> <ide> import java.io.IOException; <ide> import java.lang.reflect.InvocationTargetException; <add> <ide> import javax.script.Invocable; <ide> import javax.script.ScriptEngine; <ide> import javax.script.ScriptEngineManager; <ide><path>spring-context/src/main/java/org/springframework/scripting/support/StandardScriptUtils.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.script.Bindings; <ide> import javax.script.ScriptContext; <ide> import javax.script.ScriptEngine; <ide><path>spring-context/src/main/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessor.java <ide> <ide> import java.util.Iterator; <ide> import java.util.Set; <add> <ide> import javax.validation.ConstraintViolation; <ide> import javax.validation.Validation; <ide> import javax.validation.Validator; <ide><path>spring-context/src/main/java/org/springframework/validation/beanvalidation/LocalValidatorFactoryBean.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Properties; <add> <ide> import javax.validation.Configuration; <ide> import javax.validation.ConstraintValidatorFactory; <ide> import javax.validation.MessageInterpolator; <ide><path>spring-context/src/main/java/org/springframework/validation/beanvalidation/LocaleContextMessageInterpolator.java <ide> package org.springframework.validation.beanvalidation; <ide> <ide> import java.util.Locale; <add> <ide> import javax.validation.MessageInterpolator; <ide> <ide> import org.springframework.context.i18n.LocaleContextHolder; <ide><path>spring-context/src/main/java/org/springframework/validation/beanvalidation/MethodValidationInterceptor.java <ide> <ide> import java.lang.reflect.Method; <ide> import java.util.Set; <add> <ide> import javax.validation.ConstraintViolation; <ide> import javax.validation.ConstraintViolationException; <ide> import javax.validation.Validation; <ide><path>spring-context/src/main/java/org/springframework/validation/beanvalidation/MethodValidationPostProcessor.java <ide> package org.springframework.validation.beanvalidation; <ide> <ide> import java.lang.annotation.Annotation; <add> <ide> import javax.validation.Validator; <ide> import javax.validation.ValidatorFactory; <ide> <ide><path>spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java <ide> import java.util.Map; <ide> import java.util.Set; <ide> import java.util.TreeMap; <add> <ide> import javax.validation.ConstraintViolation; <ide> import javax.validation.ElementKind; <ide> import javax.validation.Path; <ide><path>spring-context/src/test/java/example/scannable/AutowiredQualifierFooService.java <ide> package example.scannable; <ide> <ide> import java.util.concurrent.Future; <add> <ide> import javax.annotation.PostConstruct; <ide> <ide> import org.springframework.beans.factory.annotation.Autowired; <ide><path>spring-context/src/test/java/example/scannable/FooServiceImpl.java <ide> import java.util.Comparator; <ide> import java.util.List; <ide> import java.util.concurrent.Future; <add> <ide> import javax.annotation.PostConstruct; <ide> <ide> import org.springframework.beans.factory.BeanFactory; <ide><path>spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <add> <ide> import javax.inject.Inject; <ide> import javax.inject.Named; <ide> import javax.inject.Qualifier; <ide><path>spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <del> <ide> import org.junit.BeforeClass; <ide> import org.junit.Test; <ide> <ide><path>spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java <ide> package org.springframework.context.annotation; <ide> <ide> import java.util.Properties; <add> <ide> import javax.annotation.PostConstruct; <ide> import javax.annotation.PreDestroy; <ide> import javax.annotation.Resource; <ide><path>spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java <ide> import java.util.Arrays; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.annotation.PostConstruct; <ide> <ide> import org.junit.Before; <ide><path>spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java <ide> import java.util.Collections; <ide> import java.util.Iterator; <ide> import java.util.Properties; <add> <ide> import javax.inject.Inject; <ide> <ide> import org.junit.Rule; <ide><path>spring-context/src/test/java/org/springframework/context/annotation/Spr3775InitDestroyLifecycleTests.java <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <add> <ide> import javax.annotation.PostConstruct; <ide> import javax.annotation.PreDestroy; <ide> <ide><path>spring-context/src/test/java/org/springframework/context/annotation/configuration/AutowiredConfigurationTests.java <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.util.List; <ide> import java.util.Optional; <add> <ide> import javax.inject.Provider; <ide> <ide> import org.junit.Test; <ide><path>spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java <ide> import java.util.List; <ide> import java.util.Set; <ide> import java.util.function.Supplier; <add> <ide> import javax.annotation.Resource; <ide> import javax.inject.Provider; <ide> <ide><path>spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java <ide> import java.util.Set; <ide> import java.util.concurrent.CountDownLatch; <ide> import java.util.concurrent.TimeUnit; <add> <ide> import javax.annotation.PostConstruct; <ide> <ide> import org.junit.After; <ide><path>spring-context/src/test/java/org/springframework/context/support/LiveBeansViewTests.java <ide> <ide> import java.lang.management.ManagementFactory; <ide> import java.util.Set; <add> <ide> import javax.management.MalformedObjectNameException; <ide> import javax.management.ObjectName; <ide> <ide><path>spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java <ide> package org.springframework.ejb.access; <ide> <ide> import java.lang.reflect.Proxy; <add> <ide> import javax.ejb.CreateException; <ide> import javax.ejb.EJBLocalHome; <ide> import javax.ejb.EJBLocalObject; <ide><path>spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java <ide> <ide> import java.rmi.ConnectException; <ide> import java.rmi.RemoteException; <add> <ide> import javax.ejb.CreateException; <ide> import javax.ejb.EJBHome; <ide> import javax.ejb.EJBObject; <ide><path>spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java <ide> <ide> import java.lang.reflect.Proxy; <ide> import java.rmi.RemoteException; <add> <ide> import javax.ejb.CreateException; <ide> import javax.ejb.EJBHome; <ide> import javax.ejb.EJBObject; <ide><path>spring-context/src/test/java/org/springframework/format/number/money/MoneyFormattingTests.java <ide> package org.springframework.format.number.money; <ide> <ide> import java.util.Locale; <add> <ide> import javax.money.CurrencyUnit; <ide> import javax.money.MonetaryAmount; <ide> <ide><path>spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java <ide> import java.net.BindException; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.management.Descriptor; <ide> import javax.management.MBeanServerConnection; <ide> import javax.management.remote.JMXConnectorServer; <ide><path>spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java <ide> <ide> import java.net.BindException; <ide> import java.net.MalformedURLException; <add> <ide> import javax.management.MBeanServerConnection; <ide> import javax.management.remote.JMXConnector; <ide> import javax.management.remote.JMXConnectorFactory; <ide><path>spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java <ide> import java.text.ParseException; <ide> import java.text.SimpleDateFormat; <ide> import java.util.Date; <add> <ide> import javax.management.ObjectName; <ide> <ide> import org.junit.Test; <ide><path>spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.management.Attribute; <ide> import javax.management.InstanceNotFoundException; <ide> import javax.management.JMException; <ide><path>spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java <ide> <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.management.Attribute; <ide> import javax.management.AttributeChangeNotification; <ide> import javax.management.MalformedObjectNameException; <ide><path>spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java <ide> <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.management.Descriptor; <ide> import javax.management.MBeanInfo; <ide> import javax.management.MBeanParameterInfo; <ide><path>spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java <ide> package org.springframework.jmx.export.assembler; <ide> <ide> import java.util.Properties; <add> <ide> import javax.management.MBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanInfo; <ide><path>spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerComboTests.java <ide> package org.springframework.jmx.export.assembler; <ide> <ide> import java.util.Properties; <add> <ide> import javax.management.MBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanInfo; <ide><path>spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerMappedTests.java <ide> package org.springframework.jmx.export.assembler; <ide> <ide> import java.util.Properties; <add> <ide> import javax.management.MBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanInfo; <ide><path>spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java <ide> package org.springframework.jmx.export.assembler; <ide> <ide> import java.util.Properties; <add> <ide> import javax.management.MBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanInfo; <ide><path>spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerTests.java <ide> <ide> import java.lang.reflect.Method; <ide> import java.util.Properties; <add> <ide> import javax.management.modelmbean.ModelMBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanInfo; <ide> <ide><path>spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java <ide> package org.springframework.jmx.export.assembler; <ide> <ide> import java.util.Properties; <add> <ide> import javax.management.MBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanAttributeInfo; <ide> import javax.management.modelmbean.ModelMBeanInfo; <ide><path>spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java <ide> <ide> import java.io.IOException; <ide> import java.net.MalformedURLException; <add> <ide> import javax.management.InstanceNotFoundException; <ide> import javax.management.MBeanServer; <ide> import javax.management.MBeanServerConnection; <ide><path>spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java <ide> package org.springframework.jmx.support; <ide> <ide> import java.beans.PropertyDescriptor; <add> <ide> import javax.management.DynamicMBean; <ide> import javax.management.MBeanServer; <ide> import javax.management.MBeanServerFactory; <ide><path>spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java <ide> package org.springframework.jmx.support; <ide> <ide> import java.net.MalformedURLException; <add> <ide> import javax.management.MBeanServerConnection; <ide> import javax.management.remote.JMXConnectorServer; <ide> import javax.management.remote.JMXConnectorServerFactory; <ide><path>spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java <ide> <ide> import java.lang.management.ManagementFactory; <ide> import java.util.List; <add> <ide> import javax.management.MBeanServer; <ide> import javax.management.MBeanServerFactory; <ide> <ide><path>spring-context/src/test/java/org/springframework/jndi/JndiLocatorDelegateTests.java <ide> package org.springframework.jndi; <ide> <ide> import java.lang.reflect.Field; <add> <ide> import javax.naming.spi.NamingManager; <ide> <ide> import org.junit.Test; <ide><path>spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java <ide> import java.util.Hashtable; <ide> import java.util.Map; <ide> import java.util.logging.Logger; <add> <ide> import javax.naming.Binding; <ide> import javax.naming.Context; <ide> import javax.naming.InitialContext; <ide><path>spring-context/src/test/java/org/springframework/tests/mock/jndi/ExpectedLookupTemplate.java <ide> <ide> import java.util.Map; <ide> import java.util.concurrent.ConcurrentHashMap; <add> <ide> import javax.naming.NamingException; <ide> <ide> import org.springframework.jndi.JndiTemplate; <ide><path>spring-context/src/test/java/org/springframework/tests/mock/jndi/SimpleNamingContext.java <ide> import java.util.Hashtable; <ide> import java.util.Iterator; <ide> import java.util.Map; <add> <ide> import javax.naming.Binding; <ide> import javax.naming.Context; <ide> import javax.naming.Name; <ide><path>spring-context/src/test/java/org/springframework/tests/mock/jndi/SimpleNamingContextBuilder.java <ide> package org.springframework.tests.mock.jndi; <ide> <ide> import java.util.Hashtable; <add> <ide> import javax.naming.Context; <ide> import javax.naming.NamingException; <ide> import javax.naming.spi.InitialContextFactory; <ide><path>spring-context/src/test/java/org/springframework/util/MBeanTestUtils.java <ide> <ide> import java.lang.management.ManagementFactory; <ide> import java.lang.reflect.Field; <add> <ide> import javax.management.MBeanServer; <ide> import javax.management.MBeanServerFactory; <ide> <ide><path>spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationTests.java <ide> <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <add> <ide> import javax.validation.Validator; <ide> import javax.validation.constraints.Max; <ide> import javax.validation.constraints.NotNull; <ide><path>spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Set; <add> <ide> import javax.validation.Constraint; <ide> import javax.validation.ConstraintValidator; <ide> import javax.validation.ConstraintValidatorContext; <ide><path>spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java <ide> import java.util.List; <ide> import java.util.Optional; <ide> import java.util.Set; <add> <ide> import javax.validation.Constraint; <ide> import javax.validation.ConstraintValidator; <ide> import javax.validation.ConstraintValidatorContext; <ide><path>spring-core/src/main/java/org/springframework/lang/NonNull.java <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <add> <ide> import javax.annotation.Nonnull; <ide> import javax.annotation.meta.TypeQualifierNickname; <ide> <ide><path>spring-core/src/main/java/org/springframework/lang/NonNullApi.java <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <add> <ide> import javax.annotation.Nonnull; <ide> import javax.annotation.meta.TypeQualifierDefault; <ide> <ide><path>spring-core/src/main/java/org/springframework/lang/NonNullFields.java <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <add> <ide> import javax.annotation.Nonnull; <ide> import javax.annotation.meta.TypeQualifierDefault; <ide> <ide><path>spring-core/src/main/java/org/springframework/lang/Nullable.java <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <add> <ide> import javax.annotation.Nonnull; <ide> import javax.annotation.meta.TypeQualifierNickname; <ide> import javax.annotation.meta.When; <ide><path>spring-core/src/main/java/org/springframework/util/SocketUtils.java <ide> import java.util.Random; <ide> import java.util.SortedSet; <ide> import java.util.TreeSet; <add> <ide> import javax.net.ServerSocketFactory; <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/xml/AbstractStaxHandler.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.xml.XMLConstants; <ide> import javax.xml.namespace.QName; <ide> import javax.xml.stream.XMLStreamException; <ide><path>spring-core/src/main/java/org/springframework/util/xml/AbstractStaxXMLReader.java <ide> <ide> import java.util.LinkedHashMap; <ide> import java.util.Map; <add> <ide> import javax.xml.namespace.QName; <ide> import javax.xml.stream.Location; <ide> import javax.xml.stream.XMLStreamException; <ide><path>spring-core/src/main/java/org/springframework/util/xml/AbstractXMLEventReader.java <ide> package org.springframework.util.xml; <ide> <ide> import java.util.NoSuchElementException; <add> <ide> import javax.xml.stream.XMLEventReader; <ide> import javax.xml.stream.XMLStreamException; <ide> <ide><path>spring-core/src/main/java/org/springframework/util/xml/ListBasedXMLEventReader.java <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> import java.util.NoSuchElementException; <add> <ide> import javax.xml.stream.XMLStreamConstants; <ide> import javax.xml.stream.XMLStreamException; <ide> import javax.xml.stream.events.Characters; <ide><path>spring-core/src/main/java/org/springframework/util/xml/SimpleNamespaceContext.java <ide> import java.util.LinkedHashSet; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.xml.XMLConstants; <ide> import javax.xml.namespace.NamespaceContext; <ide> <ide><path>spring-core/src/main/java/org/springframework/util/xml/StaxEventHandler.java <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.xml.namespace.QName; <ide> import javax.xml.stream.Location; <ide> import javax.xml.stream.XMLEventFactory; <ide><path>spring-core/src/main/java/org/springframework/util/xml/StaxEventXMLReader.java <ide> package org.springframework.util.xml; <ide> <ide> import java.util.Iterator; <add> <ide> import javax.xml.namespace.QName; <ide> import javax.xml.stream.Location; <ide> import javax.xml.stream.XMLEventReader; <ide><path>spring-core/src/main/java/org/springframework/util/xml/StaxStreamHandler.java <ide> package org.springframework.util.xml; <ide> <ide> import java.util.Map; <add> <ide> import javax.xml.XMLConstants; <ide> import javax.xml.namespace.QName; <ide> import javax.xml.stream.XMLStreamException; <ide><path>spring-core/src/main/java/org/springframework/util/xml/StaxUtils.java <ide> <ide> import java.util.List; <ide> import java.util.function.Supplier; <add> <ide> import javax.xml.stream.XMLEventFactory; <ide> import javax.xml.stream.XMLEventReader; <ide> import javax.xml.stream.XMLEventWriter; <ide><path>spring-core/src/main/java/org/springframework/util/xml/XMLEventStreamReader.java <ide> package org.springframework.util.xml; <ide> <ide> import java.util.Iterator; <add> <ide> import javax.xml.namespace.NamespaceContext; <ide> import javax.xml.namespace.QName; <ide> import javax.xml.stream.Location; <ide><path>spring-core/src/main/java/org/springframework/util/xml/XMLEventStreamWriter.java <ide> import java.util.ArrayList; <ide> import java.util.Iterator; <ide> import java.util.List; <add> <ide> import javax.xml.namespace.NamespaceContext; <ide> import javax.xml.namespace.QName; <ide> import javax.xml.stream.XMLEventFactory; <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java <ide> import java.util.Date; <ide> import java.util.List; <ide> import java.util.Set; <add> <ide> import javax.annotation.Nonnull; <ide> import javax.annotation.ParametersAreNonnullByDefault; <ide> import javax.annotation.Resource; <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationAwareOrderComparatorTests.java <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.annotation.Priority; <ide> <ide> import org.junit.Test; <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java <ide> public void foo() { <ide> <ide> public static class ImplementsInterfaceWithGenericAnnotatedMethod implements InterfaceWithGenericAnnotatedMethod<String> { <ide> <add> @Override <ide> public void foo(String t) { <ide> } <ide> } <ide> public void foo(String t) { <ide> <ide> public static class ExtendsBaseClassWithGenericAnnotatedMethod extends BaseClassWithGenericAnnotatedMethod<String> { <ide> <add> @Override <ide> public void foo(String t) { <ide> } <ide> } <ide><path>spring-core/src/test/java/org/springframework/util/Base64UtilsTests.java <ide> package org.springframework.util; <ide> <ide> import java.io.UnsupportedEncodingException; <add> <ide> import javax.xml.bind.DatatypeConverter; <ide> <ide> import org.junit.Test; <ide><path>spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java <ide> import java.net.InetAddress; <ide> import java.net.ServerSocket; <ide> import java.util.SortedSet; <add> <ide> import javax.net.ServerSocketFactory; <ide> <ide> import org.junit.Rule; <ide><path>spring-core/src/test/java/org/springframework/util/xml/AbstractStaxHandlerTestCase.java <ide> import java.io.StringReader; <ide> import java.io.StringWriter; <ide> import java.net.Socket; <add> <ide> import javax.xml.parsers.DocumentBuilder; <ide> import javax.xml.parsers.DocumentBuilderFactory; <ide> import javax.xml.stream.XMLStreamException; <ide><path>spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java <ide> <ide> import java.io.ByteArrayInputStream; <ide> import java.io.InputStream; <add> <ide> import javax.xml.stream.XMLInputFactory; <ide> import javax.xml.stream.XMLStreamException; <ide> import javax.xml.transform.Transformer; <ide><path>spring-core/src/test/java/org/springframework/util/xml/DomContentHandlerTests.java <ide> package org.springframework.util.xml; <ide> <ide> import java.io.StringReader; <add> <ide> import javax.xml.parsers.DocumentBuilder; <ide> import javax.xml.parsers.DocumentBuilderFactory; <ide> <ide><path>spring-core/src/test/java/org/springframework/util/xml/ListBasedXMLEventReaderTests.java <ide> import java.io.StringWriter; <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.xml.stream.XMLEventReader; <ide> import javax.xml.stream.XMLEventWriter; <ide> import javax.xml.stream.XMLInputFactory; <ide><path>spring-core/src/test/java/org/springframework/util/xml/SimpleNamespaceContextTests.java <ide> import java.util.HashSet; <ide> import java.util.Iterator; <ide> import java.util.Set; <add> <ide> import javax.xml.XMLConstants; <ide> <ide> import org.junit.Test; <ide><path>spring-core/src/test/java/org/springframework/util/xml/StaxEventXMLReaderTests.java <ide> <ide> import java.io.InputStream; <ide> import java.io.StringReader; <add> <ide> import javax.xml.stream.XMLEventReader; <ide> import javax.xml.stream.XMLInputFactory; <ide> import javax.xml.stream.XMLStreamException; <ide><path>spring-core/src/test/java/org/springframework/util/xml/StaxResultTests.java <ide> <ide> package org.springframework.util.xml; <ide> <del>import org.junit.Before; <del>import org.junit.Test; <add>import java.io.Reader; <add>import java.io.StringReader; <add>import java.io.StringWriter; <ide> <ide> import javax.xml.stream.XMLEventWriter; <ide> import javax.xml.stream.XMLOutputFactory; <ide> import javax.xml.transform.Transformer; <ide> import javax.xml.transform.TransformerFactory; <ide> import javax.xml.transform.stream.StreamSource; <del>import java.io.Reader; <del>import java.io.StringReader; <del>import java.io.StringWriter; <ide> <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertNull; <del>import static org.junit.Assert.assertThat; <del>import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; <add>import org.junit.Before; <add>import org.junit.Test; <add> <add>import static org.junit.Assert.*; <add>import static org.xmlunit.matchers.CompareMatcher.*; <ide> <ide> /** <ide> * @author Arjen Poutsma <ide><path>spring-core/src/test/java/org/springframework/util/xml/StaxSourceTests.java <ide> <ide> package org.springframework.util.xml; <ide> <del>import org.junit.Before; <del>import org.junit.Test; <del>import org.w3c.dom.Document; <del>import org.xml.sax.InputSource; <add>import java.io.StringReader; <add>import java.io.StringWriter; <ide> <ide> import javax.xml.parsers.DocumentBuilder; <ide> import javax.xml.parsers.DocumentBuilderFactory; <ide> import javax.xml.transform.TransformerFactory; <ide> import javax.xml.transform.dom.DOMResult; <ide> import javax.xml.transform.stream.StreamResult; <del>import java.io.StringReader; <del>import java.io.StringWriter; <ide> <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertNull; <del>import static org.junit.Assert.assertThat; <del>import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.w3c.dom.Document; <add>import org.xml.sax.InputSource; <add> <add>import static org.junit.Assert.*; <add>import static org.xmlunit.matchers.CompareMatcher.*; <ide> <ide> /** <ide> * @author Arjen Poutsma <ide><path>spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java <ide> <ide> import java.io.InputStream; <ide> import java.io.StringReader; <add> <ide> import javax.xml.namespace.QName; <ide> import javax.xml.stream.XMLInputFactory; <ide> import javax.xml.stream.XMLStreamException; <ide><path>spring-core/src/test/java/org/springframework/util/xml/StaxUtilsTests.java <ide> <ide> import java.io.StringReader; <ide> import java.io.StringWriter; <add> <ide> import javax.xml.stream.XMLInputFactory; <ide> import javax.xml.stream.XMLOutputFactory; <ide> import javax.xml.stream.XMLStreamReader; <ide><path>spring-core/src/test/java/org/springframework/util/xml/TransformerUtilsTests.java <ide> package org.springframework.util.xml; <ide> <ide> import java.util.Properties; <add> <ide> import javax.xml.transform.ErrorListener; <ide> import javax.xml.transform.OutputKeys; <ide> import javax.xml.transform.Result; <ide><path>spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamReaderTests.java <ide> <ide> package org.springframework.util.xml; <ide> <del>import org.junit.Before; <del>import org.junit.Test; <del>import org.w3c.dom.Node; <del>import org.xmlunit.util.Predicate; <add>import java.io.StringReader; <add>import java.io.StringWriter; <ide> <ide> import javax.xml.stream.XMLEventReader; <ide> import javax.xml.stream.XMLInputFactory; <ide> import javax.xml.transform.Transformer; <ide> import javax.xml.transform.TransformerFactory; <ide> import javax.xml.transform.stax.StAXSource; <ide> import javax.xml.transform.stream.StreamResult; <del>import java.io.StringReader; <del>import java.io.StringWriter; <ide> <del>import static org.junit.Assert.assertThat; <del>import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.w3c.dom.Node; <add>import org.xmlunit.util.Predicate; <add> <add>import static org.junit.Assert.*; <add>import static org.xmlunit.matchers.CompareMatcher.*; <ide> <ide> public class XMLEventStreamReaderTests { <ide> <ide><path>spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamWriterTests.java <ide> <ide> package org.springframework.util.xml; <ide> <del>import org.junit.Before; <del>import org.junit.Test; <del>import org.w3c.dom.Node; <del>import org.xmlunit.util.Predicate; <add>import java.io.StringWriter; <ide> <ide> import javax.xml.stream.XMLEventFactory; <ide> import javax.xml.stream.XMLEventWriter; <ide> import javax.xml.stream.XMLOutputFactory; <del>import java.io.StringWriter; <ide> <del>import static org.junit.Assert.assertThat; <del>import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.w3c.dom.Node; <add>import org.xmlunit.util.Predicate; <add> <add>import static org.junit.Assert.*; <add>import static org.xmlunit.matchers.CompareMatcher.*; <ide> <ide> public class XMLEventStreamWriterTests { <ide> <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/SqlRowSetResultSetExtractor.java <ide> <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <add> <ide> import javax.sql.rowset.CachedRowSet; <ide> import javax.sql.rowset.RowSetFactory; <ide> import javax.sql.rowset.RowSetProvider; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataContext.java <ide> import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataProviderFactory.java <ide> <ide> import java.util.Arrays; <ide> import java.util.List; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataContext.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.function.Consumer; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcInsert.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcCall.java <ide> import java.util.Arrays; <ide> import java.util.LinkedHashSet; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.jdbc.core.JdbcTemplate; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcInsert.java <ide> <ide> import java.util.Arrays; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.jdbc.core.JdbcTemplate; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReader.java <ide> package org.springframework.jdbc.core.support; <ide> <ide> import java.util.Properties; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.beans.factory.support.BeanDefinitionRegistry; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/support/JdbcDaoSupport.java <ide> package org.springframework.jdbc.core.support; <ide> <ide> import java.sql.Connection; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.support.DaoSupport; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDataSource.java <ide> import java.io.PrintWriter; <ide> import java.sql.SQLException; <ide> import java.util.logging.Logger; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.beans.factory.InitializingBean; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DelegatingDataSource.java <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <ide> import java.util.logging.Logger; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.beans.factory.InitializingBean; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java <ide> import java.sql.Connection; <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/SmartDataSource.java <ide> package org.springframework.jdbc.datasource; <ide> <ide> import java.sql.Connection; <add> <ide> import javax.sql.DataSource; <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.lang.Nullable; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/WebSphereDataSourceAdapter.java <ide> import java.lang.reflect.Method; <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/AbstractEmbeddedDatabaseConfigurer.java <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DerbyEmbeddedDatabaseConfigurer.java <ide> <ide> import java.sql.SQLException; <ide> import java.util.Properties; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.LogFactory; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java <ide> import java.sql.SQLException; <ide> import java.util.UUID; <ide> import java.util.logging.Logger; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/SimpleDriverDataSourceFactory.java <ide> package org.springframework.jdbc.datasource.embedded; <ide> <ide> import java.sql.Driver; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.jdbc.datasource.SimpleDriverDataSource; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/DatabasePopulatorUtils.java <ide> package org.springframework.jdbc.datasource.init; <ide> <ide> import java.sql.Connection; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.java <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.core.io.Resource; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/AbstractRoutingDataSource.java <ide> import java.sql.SQLException; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.beans.factory.InitializingBean; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookup.java <ide> import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.lang.Nullable; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/BatchSqlUpdate.java <ide> import java.util.Deque; <ide> import java.util.Iterator; <ide> import java.util.List; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/MappingSqlQuery.java <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.lang.Nullable; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/MappingSqlQueryWithParameters.java <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.jdbc.core.RowMapper; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/RdbmsOperation.java <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/SqlCall.java <ide> <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.jdbc.core.CallableStatementCreator; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/SqlFunction.java <ide> <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.TypeMismatchDataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/SqlQuery.java <ide> <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/SqlUpdate.java <ide> package org.springframework.jdbc.object; <ide> <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/StoredProcedure.java <ide> <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/UpdatableSqlQuery.java <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.jdbc.core.RowMapper; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/DatabaseStartupValidator.java <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <ide> import java.util.concurrent.TimeUnit; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/JdbcUtils.java <ide> import java.sql.SQLFeatureNotSupportedException; <ide> import java.sql.Statement; <ide> import java.sql.Types; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslator.java <ide> import java.sql.BatchUpdateException; <ide> import java.sql.SQLException; <ide> import java.util.Arrays; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.CannotAcquireLockException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodesFactory.java <ide> <ide> import java.util.Collections; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/incrementer/AbstractIdentityColumnMaxValueIncrementer.java <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/incrementer/AbstractSequenceMaxValueIncrementer.java <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/incrementer/MySQLMaxValueIncrementer.java <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.dao.DataAccessException; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/xml/Jdbc4SqlXmlHandler.java <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.sql.SQLXML; <add> <ide> import javax.xml.transform.Result; <ide> import javax.xml.transform.Source; <ide> import javax.xml.transform.dom.DOMResult; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/xml/SqlXmlHandler.java <ide> import java.io.Reader; <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <add> <ide> import javax.xml.transform.Result; <ide> import javax.xml.transform.Source; <ide> <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/config/InitializeDatabaseIntegrationTests.java <ide> <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.After; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java <ide> import java.sql.Statement; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Before; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Before; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Before; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.After; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/CallMetaDataContextTests.java <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.After; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcCallTests.java <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.sql.Types; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Assert; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcInsertTests.java <ide> import java.sql.DatabaseMetaData; <ide> import java.sql.ResultSet; <ide> import java.util.HashMap; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.After; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java <ide> import java.util.ArrayList; <ide> import java.util.Date; <ide> import java.util.List; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Before; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReaderTests.java <ide> import java.sql.Connection; <ide> import java.sql.ResultSet; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Test; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcDaoSupportTests.java <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Test; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> import javax.transaction.RollbackException; <ide> import javax.transaction.Status; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java <ide> import java.sql.SQLException; <ide> import java.sql.Savepoint; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.After; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTests.java <ide> import java.io.ByteArrayOutputStream; <ide> import java.io.PrintWriter; <ide> import java.sql.Connection; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Test; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/TestDataSourceWrapper.java <ide> <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <add> <ide> import javax.sql.DataSource; <ide> <ide> public class TestDataSourceWrapper extends AbstractDataSource { <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapterTests.java <ide> <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Test; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookupTests.java <ide> <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Rule; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/object/BatchSqlUpdateTests.java <ide> import java.sql.DatabaseMetaData; <ide> import java.sql.PreparedStatement; <ide> import java.sql.Types; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Test; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericSqlQueryTests.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Before; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericStoredProcedureTests.java <ide> import java.sql.Types; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Test; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Before; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlUpdateTests.java <ide> import java.sql.Types; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.After; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.After; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/support/DataFieldMaxValueIncrementerTests.java <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Test; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java <ide> import java.sql.DatabaseMetaData; <ide> import java.sql.SQLException; <ide> import java.util.Arrays; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.junit.Test; <ide><path>spring-jms/src/main/java/org/springframework/jms/connection/CachingConnectionFactory.java <ide> import java.util.Map; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.ConcurrentMap; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.Destination; <ide><path>spring-jms/src/main/java/org/springframework/jms/connection/ChainedExceptionListener.java <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.jms.ExceptionListener; <ide> import javax.jms.JMSException; <ide> <ide><path>spring-jms/src/main/java/org/springframework/jms/connection/JmsResourceHolder.java <ide> import java.util.HashMap; <ide> import java.util.LinkedList; <ide> import java.util.Map; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.JMSException; <ide><path>spring-jms/src/main/java/org/springframework/jms/connection/SingleConnectionFactory.java <ide> import java.util.LinkedHashSet; <ide> import java.util.List; <ide> import java.util.Set; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.ExceptionListener; <ide><path>spring-jms/src/main/java/org/springframework/jms/connection/TransactionAwareConnectionFactoryProxy.java <ide> import java.lang.reflect.Proxy; <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.JMSContext; <ide><path>spring-jms/src/main/java/org/springframework/jms/core/JmsMessageOperations.java <ide> package org.springframework.jms.core; <ide> <ide> import java.util.Map; <add> <ide> import javax.jms.Destination; <ide> <ide> import org.springframework.lang.Nullable; <ide><path>spring-jms/src/main/java/org/springframework/jms/core/JmsMessagingTemplate.java <ide> package org.springframework.jms.core; <ide> <ide> import java.util.Map; <add> <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/AbstractJmsListeningContainer.java <ide> import java.util.Iterator; <ide> import java.util.LinkedList; <ide> import java.util.List; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.JMSException; <ide> <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java <ide> import java.util.HashSet; <ide> import java.util.Set; <ide> import java.util.concurrent.Executor; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.JMSException; <ide> import javax.jms.MessageConsumer; <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/SimpleMessageListenerContainer.java <ide> import java.util.HashSet; <ide> import java.util.Set; <ide> import java.util.concurrent.Executor; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.Destination; <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/adapter/MessageListenerAdapter.java <ide> package org.springframework.jms.listener.adapter; <ide> <ide> import java.lang.reflect.InvocationTargetException; <add> <ide> import javax.jms.JMSException; <ide> import javax.jms.Message; <ide> import javax.jms.MessageListener; <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/endpoint/StandardJmsActivationSpecFactory.java <ide> package org.springframework.jms.listener.endpoint; <ide> <ide> import java.util.Map; <add> <ide> import javax.jms.JMSException; <ide> import javax.jms.Queue; <ide> import javax.jms.Session; <ide><path>spring-jms/src/main/java/org/springframework/jms/support/JmsMessageHeaderAccessor.java <ide> <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.jms.Destination; <ide> <ide> import org.springframework.lang.Nullable; <ide><path>spring-jms/src/main/java/org/springframework/jms/support/SimpleJmsHeaderMapper.java <ide> import java.util.HashSet; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide> import javax.jms.Message; <ide><path>spring-jms/src/main/java/org/springframework/jms/support/converter/MappingJackson2MessageConverter.java <ide> import java.io.UnsupportedEncodingException; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.jms.BytesMessage; <ide> import javax.jms.JMSException; <ide> import javax.jms.Message; <ide><path>spring-jms/src/main/java/org/springframework/jms/support/converter/MarshallingMessageConverter.java <ide> import java.io.IOException; <ide> import java.io.StringReader; <ide> import java.io.StringWriter; <add> <ide> import javax.jms.BytesMessage; <ide> import javax.jms.JMSException; <ide> import javax.jms.Message; <ide><path>spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java <ide> package org.springframework.jms.support.converter; <ide> <ide> import java.util.Map; <add> <ide> import javax.jms.JMSException; <ide> import javax.jms.Session; <ide> <ide><path>spring-jms/src/main/java/org/springframework/jms/support/converter/SimpleMessageConverter.java <ide> import java.util.Enumeration; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.jms.BytesMessage; <ide> import javax.jms.JMSException; <ide> import javax.jms.MapMessage; <ide><path>spring-jms/src/main/java/org/springframework/jms/support/destination/JndiDestinationResolver.java <ide> <ide> import java.util.Map; <ide> import java.util.concurrent.ConcurrentHashMap; <add> <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide> import javax.jms.Queue; <ide><path>spring-jms/src/test/java/org/springframework/jms/StubTextMessage.java <ide> <ide> import java.util.Enumeration; <ide> import java.util.concurrent.ConcurrentHashMap; <add> <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide> import javax.jms.TextMessage; <ide><path>spring-jms/src/test/java/org/springframework/jms/annotation/AbstractJmsAnnotationDrivenTests.java <ide> package org.springframework.jms.annotation; <ide> <ide> import java.lang.reflect.Method; <add> <ide> import javax.jms.JMSException; <ide> import javax.jms.Session; <ide> <ide><path>spring-jms/src/test/java/org/springframework/jms/config/JmsListenerContainerFactoryIntegrationTests.java <ide> import java.lang.reflect.Method; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.jms.JMSException; <ide> import javax.jms.Message; <ide> import javax.jms.MessageListener; <ide><path>spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java <ide> import java.util.Iterator; <ide> import java.util.Map; <ide> import java.util.Set; <add> <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.Message; <ide> import javax.jms.MessageListener; <ide><path>spring-jms/src/test/java/org/springframework/jms/config/MethodJmsListenerEndpointTests.java <ide> import java.util.Arrays; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.jms.Destination; <ide> import javax.jms.InvalidDestinationException; <ide> import javax.jms.JMSException; <ide><path>spring-jms/src/test/java/org/springframework/jms/core/JmsMessagingTemplateTests.java <ide> import java.io.Writer; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide> import javax.jms.MessageFormatException; <ide><path>spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java <ide> import java.io.PrintWriter; <ide> import java.io.StringWriter; <ide> import java.util.List; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.DeliveryMode; <ide><path>spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.jms.ConnectionFactory; <ide> <ide> import org.junit.Test; <ide><path>spring-jms/src/test/java/org/springframework/jms/listener/DefaultMessageListenerContainerTests.java <ide> <ide> import java.util.concurrent.CountDownLatch; <ide> import java.util.concurrent.TimeUnit; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.Destination; <ide><path>spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java <ide> <ide> import java.util.HashSet; <ide> import java.util.Set; <add> <ide> import javax.jms.Connection; <ide> import javax.jms.ConnectionFactory; <ide> import javax.jms.ExceptionListener; <ide><path>spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java <ide> <ide> import java.io.ByteArrayInputStream; <ide> import java.io.Serializable; <add> <ide> import javax.jms.BytesMessage; <ide> import javax.jms.InvalidDestinationException; <ide> import javax.jms.JMSException; <ide><path>spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java <ide> import java.lang.reflect.Method; <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.jms.DeliveryMode; <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide><path>spring-jms/src/test/java/org/springframework/jms/listener/adapter/ResponsiveMessageDelegate.java <ide> <ide> import java.io.Serializable; <ide> import java.util.Map; <add> <ide> import javax.jms.BytesMessage; <ide> import javax.jms.MapMessage; <ide> import javax.jms.ObjectMessage; <ide><path>spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java <ide> import java.io.Serializable; <ide> import java.util.Arrays; <ide> import java.util.Enumeration; <add> <ide> import javax.jms.CompletionListener; <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide><path>spring-jms/src/test/java/org/springframework/jms/support/JmsMessageHeaderAccessorTests.java <ide> package org.springframework.jms.support; <ide> <ide> import java.util.Map; <add> <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide> <ide><path>spring-jms/src/test/java/org/springframework/jms/support/SimpleJmsHeaderMapperTests.java <ide> <ide> import java.util.Date; <ide> import java.util.Map; <add> <ide> import javax.jms.DeliveryMode; <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide><path>spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java <ide> import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.jms.BytesMessage; <ide> import javax.jms.JMSException; <ide> import javax.jms.MapMessage; <ide><path>spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java <ide> import java.util.Date; <ide> import java.util.HashMap; <ide> import java.util.Map; <add> <ide> import javax.jms.BytesMessage; <ide> import javax.jms.JMSException; <ide> import javax.jms.Session; <ide><path>spring-jms/src/test/java/org/springframework/jms/support/converter/MessagingMessageConverterTests.java <ide> package org.springframework.jms.support.converter; <ide> <ide> import java.io.Serializable; <add> <ide> import javax.jms.JMSException; <ide> import javax.jms.ObjectMessage; <ide> import javax.jms.Session; <ide><path>spring-messaging/src/main/java/org/springframework/messaging/converter/MarshallingMessageConverter.java <ide> import java.io.StringWriter; <ide> import java.io.Writer; <ide> import java.util.Arrays; <add> <ide> import javax.xml.transform.Result; <ide> import javax.xml.transform.Source; <ide> import javax.xml.transform.stream.StreamResult; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandlerTests.java <ide> import java.security.Principal; <ide> import java.util.LinkedHashMap; <ide> import java.util.Map; <add> <ide> import javax.security.auth.Subject; <ide> <ide> import com.fasterxml.jackson.annotation.JsonView; <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/HibernateTemplate.java <ide> import java.util.Collection; <ide> import java.util.Iterator; <ide> import java.util.List; <add> <ide> import javax.persistence.PersistenceException; <ide> <ide> import org.apache.commons.logging.Log; <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/HibernateTransactionManager.java <ide> <ide> import java.sql.Connection; <ide> import java.sql.ResultSet; <add> <ide> import javax.persistence.PersistenceException; <ide> import javax.sql.DataSource; <ide> <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/LocalSessionFactoryBean.java <ide> import java.io.File; <ide> import java.io.IOException; <ide> import java.util.Properties; <add> <ide> import javax.sql.DataSource; <ide> <ide> import org.hibernate.Interceptor; <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/LocalSessionFactoryBuilder.java <ide> import java.util.concurrent.Callable; <ide> import java.util.concurrent.ExecutionException; <ide> import java.util.concurrent.Future; <add> <ide> import javax.persistence.AttributeConverter; <ide> import javax.persistence.Converter; <ide> import javax.persistence.Embeddable; <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/SessionFactoryUtils.java <ide> <ide> import java.lang.reflect.Method; <ide> import java.util.Map; <add> <ide> import javax.persistence.PersistenceException; <ide> import javax.sql.DataSource; <ide>
300
Python
Python
remove dependency on examples/seq2seq from rag
fe326bd5cf1aa4ec65286e6500070f5440420a82
<ide><path>examples/rag/callbacks.py <ide> import logging <ide> import os <add>from pathlib import Path <ide> <del>from pytorch_lightning.callbacks import ModelCheckpoint <add>import numpy as np <add>import pytorch_lightning as pl <add>import torch <add>from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint <add>from pytorch_lightning.utilities import rank_zero_only <add> <add>from utils import save_json <add> <add> <add>def count_trainable_parameters(model): <add> model_parameters = filter(lambda p: p.requires_grad, model.parameters()) <add> params = sum([np.prod(p.size()) for p in model_parameters]) <add> return params <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide> def get_checkpoint_callback(output_dir, metric): <ide> period=0, # maybe save a checkpoint every time val is run, not just end of epoch. <ide> ) <ide> return checkpoint_callback <add> <add> <add>def get_early_stopping_callback(metric, patience): <add> return EarlyStopping( <add> monitor=f"val_{metric}", # does this need avg? <add> mode="min" if "loss" in metric else "max", <add> patience=patience, <add> verbose=True, <add> ) <add> <add> <add>class Seq2SeqLoggingCallback(pl.Callback): <add> def on_batch_end(self, trainer, pl_module): <add> lrs = {f"lr_group_{i}": param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups)} <add> pl_module.logger.log_metrics(lrs) <add> <add> @rank_zero_only <add> def _write_logs( <add> self, trainer: pl.Trainer, pl_module: pl.LightningModule, type_path: str, save_generations=True <add> ) -> None: <add> logger.info(f"***** {type_path} results at step {trainer.global_step:05d} *****") <add> metrics = trainer.callback_metrics <add> trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]}) <add> # Log results <add> od = Path(pl_module.hparams.output_dir) <add> if type_path == "test": <add> results_file = od / "test_results.txt" <add> generations_file = od / "test_generations.txt" <add> else: <add> # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json <add> # If people want this it will be easy enough to add back. <add> results_file = od / f"{type_path}_results/{trainer.global_step:05d}.txt" <add> generations_file = od / f"{type_path}_generations/{trainer.global_step:05d}.txt" <add> results_file.parent.mkdir(exist_ok=True) <add> generations_file.parent.mkdir(exist_ok=True) <add> with open(results_file, "a+") as writer: <add> for key in sorted(metrics): <add> if key in ["log", "progress_bar", "preds"]: <add> continue <add> val = metrics[key] <add> if isinstance(val, torch.Tensor): <add> val = val.item() <add> msg = f"{key}: {val:.6f}\n" <add> writer.write(msg) <add> <add> if not save_generations: <add> return <add> <add> if "preds" in metrics: <add> content = "\n".join(metrics["preds"]) <add> generations_file.open("w+").write(content) <add> <add> @rank_zero_only <add> def on_train_start(self, trainer, pl_module): <add> try: <add> npars = pl_module.model.model.num_parameters() <add> except AttributeError: <add> npars = pl_module.model.num_parameters() <add> <add> n_trainable_pars = count_trainable_parameters(pl_module) <add> # mp stands for million parameters <add> trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6}) <add> <add> @rank_zero_only <add> def on_test_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule): <add> save_json(pl_module.metrics, pl_module.metrics_save_path) <add> return self._write_logs(trainer, pl_module, "test") <add> <add> @rank_zero_only <add> def on_validation_end(self, trainer: pl.Trainer, pl_module): <add> save_json(pl_module.metrics, pl_module.metrics_save_path) <add> # Uncommenting this will save val generations <add> # return self._write_logs(trainer, pl_module, "valid") <ide><path>examples/rag/finetune.py <ide> sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # noqa: E402 # isort:skip <ide> <ide> from examples.lightning_base import BaseTransformer, add_generic_args, generic_train # noqa: E402 # isort:skip <del>from examples.rag.callbacks import get_checkpoint_callback # noqa: E402 # isort:skip <add>from examples.rag.callbacks import ( # noqa: E402 # isort:skip <add> get_checkpoint_callback, <add> get_early_stopping_callback, <add> Seq2SeqLoggingCallback, <add>) <ide> from examples.rag.distributed_retriever import RagPyTorchDistributedRetriever # noqa: E402 # isort:skip <ide> from examples.rag.utils import ( # noqa: E402 # isort:skip <del> Seq2SeqDataset, <ide> calculate_exact_match, <del> is_rag_model, <del> set_extra_model_params, <del>) <del>from examples.seq2seq.callbacks import Seq2SeqLoggingCallback, get_early_stopping_callback # noqa: E402 # isort:skip <del>from examples.seq2seq.utils import ( # noqa: E402 # isort:skip <ide> flatten_list, <ide> get_git_info, <add> is_rag_model, <ide> lmap, <ide> pickle_save, <ide> save_git_info, <ide> save_json, <add> set_extra_model_params, <add> Seq2SeqDataset, <ide> ) <ide> <ide> logging.basicConfig(level=logging.INFO) <ide> def get_dataset(self, type_path) -> Seq2SeqDataset: <ide> <ide> def get_dataloader(self, type_path: str, batch_size: int, shuffle: bool = False) -> DataLoader: <ide> dataset = self.get_dataset(type_path) <del> sampler = None <del> if self.hparams.sortish_sampler and type_path == "train": <del> assert self.hparams.gpus <= 1 # TODO: assert earlier <del> sampler = dataset.make_sortish_sampler(batch_size) <del> shuffle = False <ide> <ide> dataloader = DataLoader( <ide> dataset, <ide> batch_size=batch_size, <ide> collate_fn=dataset.collate_fn, <ide> shuffle=shuffle, <ide> num_workers=self.num_workers, <del> sampler=sampler, <ide> ) <ide> return dataloader <ide> <ide> def add_model_specific_args(parser, root_dir): <ide> help="The maximum total input sequence length after tokenization. Sequences longer " <ide> "than this will be truncated, sequences shorter will be padded.", <ide> ) <del> parser.add_argument("--sortish_sampler", action="store_true", default=False) <ide> parser.add_argument("--logger_name", type=str, choices=["default", "wandb", "wandb_shared"], default="default") <ide> parser.add_argument("--n_train", type=int, default=-1, required=False, help="# examples. -1 means use all.") <ide> parser.add_argument("--n_val", type=int, default=-1, required=False, help="# examples. -1 means use all.") <ide><path>examples/rag/utils.py <add>import itertools <add>import json <ide> import linecache <add>import os <add>import pickle <ide> import re <add>import socket <ide> import string <ide> from collections import Counter <ide> from logging import getLogger <ide> from pathlib import Path <del>from typing import Dict, List <add>from typing import Callable, Dict, Iterable, List <ide> <add>import git <ide> import torch <ide> from torch.utils.data import Dataset <ide> <del>from examples.seq2seq.utils import SortishSampler, trim_batch <ide> from transformers import BartTokenizer, RagTokenizer, T5Tokenizer <ide> <ide> <ide> def encode_line(tokenizer, line, max_length, padding_side, pad_to_max_length=Tru <ide> ) <ide> <ide> <add>def trim_batch( <add> input_ids, <add> pad_token_id, <add> attention_mask=None, <add>): <add> """Remove columns that are populated exclusively by pad_token_id""" <add> keep_column_mask = input_ids.ne(pad_token_id).any(dim=0) <add> if attention_mask is None: <add> return input_ids[:, keep_column_mask] <add> else: <add> return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) <add> <add> <ide> class Seq2SeqDataset(Dataset): <ide> def __init__( <ide> self, <ide> def collate_fn(self, batch) -> Dict[str, torch.Tensor]: <ide> } <ide> return batch <ide> <del> def make_sortish_sampler(self, batch_size): <del> return SortishSampler(self.src_lens, batch_size) <del> <ide> <ide> logger = getLogger(__name__) <ide> <ide> <add>def flatten_list(summary_ids: List[List]): <add> return [x for x in itertools.chain.from_iterable(summary_ids)] <add> <add> <add>def save_git_info(folder_path: str) -> None: <add> """Save git information to output_dir/git_log.json""" <add> repo_infos = get_git_info() <add> save_json(repo_infos, os.path.join(folder_path, "git_log.json")) <add> <add> <add>def save_json(content, path, indent=4, **json_dump_kwargs): <add> with open(path, "w") as f: <add> json.dump(content, f, indent=indent, **json_dump_kwargs) <add> <add> <add>def load_json(path): <add> with open(path) as f: <add> return json.load(f) <add> <add> <add>def get_git_info(): <add> repo = git.Repo(search_parent_directories=True) <add> repo_infos = { <add> "repo_id": str(repo), <add> "repo_sha": str(repo.head.object.hexsha), <add> "repo_branch": str(repo.active_branch), <add> "hostname": str(socket.gethostname()), <add> } <add> return repo_infos <add> <add> <add>def lmap(f: Callable, x: Iterable) -> List: <add> """list(map(f, x))""" <add> return list(map(f, x)) <add> <add> <add>def pickle_save(obj, path): <add> """pickle.dump(obj, path)""" <add> with open(path, "wb") as f: <add> return pickle.dump(obj, f) <add> <add> <ide> def normalize_answer(s): <ide> """Lower text and remove punctuation, articles and extra whitespace.""" <ide>
3
Text
Text
update the pr template
8d3d8b34401fa128a26c39a385670c20352e76b9
<ide><path>PULL_REQUEST_TEMPLATE.md <ide> Make sure tests pass on both Travis and Circle CI. <ide> **Code formatting** <ide> <ide> Look around. Match the style of the rest of the codebase. See also the simple [style guide](https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md#style-guide). <add> <add>For more info, see the ["Pull Requests" section of our "Contributing" guidelines](https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md#pull-requests).
1
PHP
PHP
ignore case in blade foreach compiler
4591d90f6de700a7b67dedb0147d2c9dcf6acd51
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php <ide> protected function compileFor($expression) <ide> */ <ide> protected function compileForeach($expression) <ide> { <del> preg_match('/\( *(.*) +as *([^\)]*)/', $expression, $matches); <add> preg_match('/\( *(.*) +as *([^\)]*)/i', $expression, $matches); <ide> <ide> $iteratee = trim($matches[1]); <ide> <ide><path>tests/View/ViewBladeCompilerTest.php <ide> public function testForeachStatementsAreCompiled() <ide> $this->assertEquals($expected, $compiler->compileString($string)); <ide> } <ide> <add> public function testForeachStatementsAreCompileWithUppercaseSyntax() <add> { <add> $compiler = new BladeCompiler($this->getFiles(), __DIR__); <add> $string = '@foreach ($this->getUsers() AS $user) <add>test <add>@endforeach'; <add> $expected = '<?php $__currentLoopData = $this->getUsers(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getFirstLoop(); ?> <add>test <add><?php endforeach; $__env->popLoop(); $loop = $__env->getFirstLoop(); ?>'; <add> $this->assertEquals($expected, $compiler->compileString($string)); <add> } <add> <ide> public function testNestedForeachStatementsAreCompiled() <ide> { <ide> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
2
Ruby
Ruby
fix typo /a http/an http/ [ci skip]
db6884a772740900a9e67e59abe77b6a260c72c3
<ide><path>activestorage/app/models/active_storage/blob.rb <ide> def delete <ide> end <ide> <ide> # Deletes the file on the service and then destroys the blob record. This is the recommended way to dispose of unwanted <del> # blobs. Note, though, that deleting the file off the service will initiate a HTTP connection to the service, which may <add> # blobs. Note, though, that deleting the file off the service will initiate an HTTP connection to the service, which may <ide> # be slow or prevented, so you should not use this method inside a transaction or in callbacks. Use #purge_later instead. <ide> def purge <ide> destroy
1
Java
Java
copy cookies and hints to serverresponse builders
c152d246a8ce99628ea5b28f91e96cfbeb434186
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultEntityResponseBuilder.java <ide> public EntityResponse.Builder<T> hint(String key, Object value) { <ide> return this; <ide> } <ide> <add> @Override <add> public EntityResponse.Builder<T> hints(Consumer<Map<String, Object>> hintsConsumer) { <add> hintsConsumer.accept(this.hints); <add> return this; <add> } <add> <ide> @Override <ide> public EntityResponse.Builder<T> lastModified(ZonedDateTime lastModified) { <ide> this.headers.setLastModified(lastModified); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilder.java <ide> public ServerResponse.BodyBuilder hint(String key, Object value) { <ide> return this; <ide> } <ide> <add> @Override <add> public ServerResponse.BodyBuilder hints(Consumer<Map<String, Object>> hintsConsumer) { <add> hintsConsumer.accept(this.hints); <add> return this; <add> } <add> <ide> @Override <ide> public ServerResponse.BodyBuilder lastModified(ZonedDateTime lastModified) { <ide> this.headers.setLastModified(lastModified); <ide> public <T, P extends Publisher<T>> Mono<ServerResponse> body(P publisher, Class< <ide> <ide> return new DefaultEntityResponseBuilder<>(publisher, <ide> BodyInserters.fromPublisher(publisher, elementClass)) <del> .headers(this.headers) <ide> .status(this.statusCode) <add> .headers(this.headers) <add> .cookies(cookies -> cookies.addAll(this.cookies)) <add> .hints(hints -> hints.putAll(this.hints)) <ide> .build() <ide> .map(entityResponse -> entityResponse); <ide> } <ide> public <T, P extends Publisher<T>> Mono<ServerResponse> body(P publisher, <ide> <ide> return new DefaultEntityResponseBuilder<>(publisher, <ide> BodyInserters.fromPublisher(publisher, typeReference)) <del> .headers(this.headers) <ide> .status(this.statusCode) <add> .headers(this.headers) <add> .cookies(cookies -> cookies.addAll(this.cookies)) <add> .hints(hints -> hints.putAll(this.hints)) <ide> .build() <ide> .map(entityResponse -> entityResponse); <ide> } <ide> public Mono<ServerResponse> syncBody(Object body) { <ide> <ide> return new DefaultEntityResponseBuilder<>(body, <ide> BodyInserters.fromObject(body)) <del> .headers(this.headers) <ide> .status(this.statusCode) <add> .headers(this.headers) <add> .cookies(cookies -> cookies.addAll(this.cookies)) <add> .hints(hints -> hints.putAll(this.hints)) <ide> .build() <ide> .map(entityResponse -> entityResponse); <ide> } <ide> public Mono<ServerResponse> body(BodyInserter<?, ? super ServerHttpResponse> ins <ide> @Override <ide> public Mono<ServerResponse> render(String name, Object... modelAttributes) { <ide> return new DefaultRenderingResponseBuilder(name) <del> .headers(this.headers) <ide> .status(this.statusCode) <add> .headers(this.headers) <add> .cookies(cookies -> cookies.addAll(this.cookies)) <ide> .modelAttributes(modelAttributes) <ide> .build() <ide> .map(renderingResponse -> renderingResponse); <ide> public Mono<ServerResponse> render(String name, Object... modelAttributes) { <ide> @Override <ide> public Mono<ServerResponse> render(String name, Map<String, ?> model) { <ide> return new DefaultRenderingResponseBuilder(name) <del> .headers(this.headers) <ide> .status(this.statusCode) <add> .headers(this.headers) <add> .cookies(cookies -> cookies.addAll(this.cookies)) <ide> .modelAttributes(model) <ide> .build() <ide> .map(renderingResponse -> renderingResponse); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/EntityResponse.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.net.URI; <ide> import java.time.Instant; <ide> import java.time.ZonedDateTime; <add>import java.util.Map; <ide> import java.util.Set; <ide> import java.util.function.Consumer; <ide> <ide> static <T, P extends Publisher<T>> Builder<P> fromPublisher(P publisher, <ide> */ <ide> Builder<T> hint(String key, Object value); <ide> <add> /** <add> * Manipulate serialization hint with the given consumer. <add> * <add> * @param hintsConsumer a function that consumes the hints <add> * @return this builder <add> * @since 5.1.6 <add> */ <add> Builder<T> hints(Consumer<Map<String, Object>> hintsConsumer); <add> <ide> /** <ide> * Build the response. <ide> * @return the built response <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ServerResponse.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> interface BodyBuilder extends HeadersBuilder<BodyBuilder> { <ide> */ <ide> BodyBuilder hint(String key, Object value); <ide> <add> /** <add> * Manipulate serialization hint with the given consumer. <add> * <add> * @param hintsConsumer a function that consumes the hints <add> * @return this builder <add> * @since 5.1.6 <add> */ <add> BodyBuilder hints(Consumer<Map<String, Object>> hintsConsumer); <add> <ide> /** <ide> * Set the body of the response to the given asynchronous {@code Publisher} and return it. <ide> * This convenience method combines {@link #body(BodyInserter)} and <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilderTests.java <ide> import org.springframework.mock.web.test.server.MockServerWebExchange; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <add>import org.springframework.web.reactive.function.BodyInserters; <ide> import org.springframework.web.reactive.result.view.ViewResolver; <ide> <ide> import static org.junit.Assert.*; <ide> public void cookies() { <ide> .verify(); <ide> } <ide> <add> @Test <add> public void copyCookies() { <add> Mono<ServerResponse> serverResponse = ServerResponse.ok() <add> .cookie(ResponseCookie.from("foo", "bar").build()) <add> .syncBody("body"); <add> <add> assertFalse(serverResponse.block().cookies().isEmpty()); <add> <add> serverResponse = ServerResponse.ok() <add> .cookie(ResponseCookie.from("foo", "bar").build()) <add> .body(BodyInserters.fromObject("body")); <add> <add> <add> assertFalse(serverResponse.block().cookies().isEmpty()); <add> } <add> <add> <ide> @Test <ide> public void build() { <ide> ResponseCookie cookie = ResponseCookie.from("name", "value").build();
5
Javascript
Javascript
add more validation in `pdfworker.fromport`
47a9d38280fc54d156c77ad89e7ac1b2b4bcc4ec
<ide><path>src/display/api.js <ide> var PDFWorker = (function PDFWorkerClosure() { <ide> * @param {PDFWorkerParameters} params - The worker initialization parameters. <ide> */ <ide> PDFWorker.fromPort = function(params) { <add> if (!params || !params.port) { <add> throw new Error('PDFWorker.fromPort - invalid method signature.'); <add> } <ide> if (pdfWorkerPorts.has(params.port)) { <ide> return pdfWorkerPorts.get(params.port); <ide> }
1
Ruby
Ruby
read all formula in a 'rescue' block
ab9ccd7d8977e7929d948695b1f3d585cfb882f2
<ide><path>Library/Homebrew/formula.rb <ide> def self.read name <ide> def self.read_all <ide> # yields once for each <ide> Formulary.names.each do |name| <del> require Formula.path(name) <del> klass_name = Formula.class_s(name) <del> klass = eval(klass_name) <del> yield name, klass <add> begin <add> require Formula.path(name) <add> klass_name = Formula.class_s(name) <add> klass = eval(klass_name) <add> yield name, klass <add> rescue Exception=>e <add> opoo "Error importing #{name}:" <add> puts "#{e}" <add> end <ide> end <ide> end <ide>
1
Python
Python
raise e983 early on in docbin init
f3f7afa21f05b19f84f2bc1692253f5b8ff5410a
<ide><path>spacy/errors.py <ide> class Errors: <ide> "to token boundaries.") <ide> E982 = ("The `Token.ent_iob` attribute should be an integer indexing " <ide> "into {values}, but found {value}.") <del> E983 = ("Invalid key for '{dict}': {key}. Available keys: " <add> E983 = ("Invalid key(s) for '{dict}': {key}. Available keys: " <ide> "{keys}") <ide> E984 = ("Invalid component config for '{name}': component block needs either " <ide> "a key `factory` specifying the registered function used to " <ide><path>spacy/tokens/_serialize.py <ide> from .doc import Doc <ide> from ..vocab import Vocab <ide> from ..compat import copy_reg <del>from ..attrs import SPACY, ORTH, intify_attr <add>from ..attrs import SPACY, ORTH, intify_attr, IDS <ide> from ..errors import Errors <ide> from ..util import ensure_path, SimpleFrozenList <ide> <ide> def __init__( <ide> <ide> DOCS: https://spacy.io/api/docbin#init <ide> """ <del> attrs = sorted([intify_attr(attr) for attr in attrs]) <add> try: <add> attrs = sorted([intify_attr(attr) for attr in attrs]) <add> except TypeError: <add> non_valid = [attr for attr in attrs if intify_attr(attr) is None] <add> raise KeyError(Errors.E983.format(dict="attrs", key=non_valid, keys=IDS.keys())) from None <ide> self.version = "0.1" <ide> self.attrs = [attr for attr in attrs if attr != ORTH and attr != SPACY] <ide> self.attrs.insert(0, ORTH) # Ensure ORTH is always attrs[0]
2
PHP
PHP
fix coding standards
ee4a116936efe6c015ecd69cd55885ce8fbdf7f8
<ide><path>app/webroot/index.php <ide> if (function_exists('ini_set')) { <ide> ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path')); <ide> } <del> if (!include('Cake' . DS . 'bootstrap.php')) { <add> if (!include ('Cake' . DS . 'bootstrap.php')) { <ide> $failed = true; <ide> } <ide> } else { <del> if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <add> if (!include (CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <ide> $failed = true; <ide> } <ide> } <ide><path>app/webroot/test.php <ide> if (function_exists('ini_set')) { <ide> ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path')); <ide> } <del> if (!include('Cake' . DS . 'bootstrap.php')) { <add> if (!include ('Cake' . DS . 'bootstrap.php')) { <ide> $failed = true; <ide> } <ide> } else { <del> if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <add> if (!include (CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <ide> $failed = true; <ide> } <ide> } <ide><path>lib/Cake/Console/Templates/skel/Console/cake.php <ide> ini_set('include_path', $root . PATH_SEPARATOR . __CAKE_PATH__ . PATH_SEPARATOR . ini_get('include_path')); <ide> } <ide> <del>if (!include($dispatcher)) { <add>if (!include ($dispatcher)) { <ide> trigger_error('Could not locate CakePHP core files.', E_USER_ERROR); <ide> } <ide> unset($paths, $path, $dispatcher, $root, $ds); <ide><path>lib/Cake/Console/Templates/skel/webroot/index.php <ide> if (function_exists('ini_set')) { <ide> ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path')); <ide> } <del> if (!include('Cake' . DS . 'bootstrap.php')) { <add> if (!include ('Cake' . DS . 'bootstrap.php')) { <ide> $failed = true; <ide> } <ide> } else { <del> if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <add> if (!include (CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <ide> $failed = true; <ide> } <ide> } <ide><path>lib/Cake/Console/Templates/skel/webroot/test.php <ide> if (function_exists('ini_set')) { <ide> ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path')); <ide> } <del> if (!include('Cake' . DS . 'bootstrap.php')) { <add> if (!include ('Cake' . DS . 'bootstrap.php')) { <ide> $failed = true; <ide> } <ide> } else { <del> if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <add> if (!include (CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <ide> $failed = true; <ide> } <ide> }
5
Text
Text
update removeclippedsubviews default value
d5678e95e1d12704ee8c2101d722b84f8ce5732e
<ide><path>docs/Performance.md <ide> should continue to render rows. <ide> "When true, offscreen child views (whose `overflow` value is `hidden`) <ide> are removed from their native backing superview when offscreen. This <ide> can improve scrolling performance on long lists. The default value is <del>false." <add>`true`."(note:before version 0.14-rc, the default value is `false`). <ide> <ide> This is an extremely important optimization to apply on large ListViews. <ide> On Android the `overflow` value is always `hidden` so you don't need to
1
Ruby
Ruby
use drop rather than calculate the array length
d440fa07dc9b20880d0f22071319d8a9babe4e6b
<ide><path>activerecord/lib/active_record/associations/join_dependency.rb <ide> def graft(*associations) <ide> end <ide> <ide> def join_associations <del> join_parts.last(join_parts.length - 1) <add> join_parts.drop 1 <ide> end <ide> <ide> def join_base
1
PHP
PHP
update doc block
6ca78def627f665ae76a58031b7fc7d836091903
<ide><path>src/Illuminate/Foundation/Testing/TestResponse.php <ide> public function decodeResponseJson() <ide> } <ide> <ide> /** <del> * Alias for the "decodeResponseJson" method. <add> * Validate and return the decoded response JSON. <ide> * <ide> * @return array <ide> */
1
Javascript
Javascript
remove stray console log
abc0d3c534743897c02a8e434e2ccabde9026c07
<ide><path>spec/text-editor-element-spec.js <ide> describe('TextEditorElement', () => { <ide> }) <ide> <ide> it("honors the 'readonly' attribute", async function() { <del> console.log('set attribute'); <ide> jasmineContent.innerHTML = "<atom-text-editor readonly>" <ide> const element = jasmineContent.firstChild <ide>
1
Javascript
Javascript
remove unused import (patch)
8082eddaeff82479831ceee0791c010cc8aa8919
<ide><path>examples/with-apollo/lib/with-apollo-client.js <ide> import initApollo from './init-apollo' <ide> import Head from 'next/head' <ide> import { getDataFromTree } from 'react-apollo' <del>import propTypes from 'prop-types' <ide> <ide> export default (App) => { <ide> return class Apollo extends React.Component { <ide> export default (App) => { <ide> return <App {...this.props} apolloClient={this.apolloClient} /> <ide> } <ide> } <del>} <ide>\ No newline at end of file <add>}
1
PHP
PHP
add missing params for parent call
beff12d8a55d74fd24719c47897f673c9e1c2cae
<ide><path>lib/Cake/Test/Case/Model/BehaviorCollectionTest.php <ide> public function afterFind(Model $model, $results, $primary = false) { <ide> public function beforeSave(Model $model, $options = array()) { <ide> $settings = $this->settings[$model->alias]; <ide> if (!isset($settings['beforeSave']) || $settings['beforeSave'] === 'off') { <del> return parent::beforeSave($model); <add> return parent::beforeSave($model, $options); <ide> } <ide> switch ($settings['beforeSave']) { <ide> case 'on': <ide> public function beforeSave(Model $model, $options = array()) { <ide> public function afterSave(Model $model, $created, $options = array()) { <ide> $settings = $this->settings[$model->alias]; <ide> if (!isset($settings['afterSave']) || $settings['afterSave'] === 'off') { <del> return parent::afterSave($model, $created); <add> return parent::afterSave($model, $created, $options); <ide> } <ide> $string = 'modified after'; <ide> if ($created) { <ide> public function afterSave(Model $model, $created, $options = array()) { <ide> public function beforeValidate(Model $model, $options = array()) { <ide> $settings = $this->settings[$model->alias]; <ide> if (!isset($settings['validate']) || $settings['validate'] === 'off') { <del> return parent::beforeValidate($model); <add> return parent::beforeValidate($model, $options); <ide> } <ide> switch ($settings['validate']) { <ide> case 'on':
1
Python
Python
add function to check for table existence
03834af4975fec637d6626bedd6ccb4fdf70e339
<ide><path>airflow/hooks/hive_hooks.py <ide> from tempfile import NamedTemporaryFile <ide> <ide> <del>from thrift.transport import TSocket <del>from thrift.transport import TTransport <add>from thrift.transport import TSocket, TTransport <ide> from thrift.protocol import TBinaryProtocol <ide> from hive_service import ThriftHive <ide> import pyhs2 <ide> def max_partition(self, schema, table_name, field=None, filter=None): <ide> return max([p[field] for p in parts]) <ide> <ide> <add> def table_exists(self, table_name, db='default'): <add> ''' <add> Check if table exists <add> <add> >>> hh = HiveMetastoreHook() <add> >>> hh.table_exists(db='airflow', table_name='static_babynames') <add> True <add> >>> hh.table_exists(db='airflow', table_name='does_not_exist') <add> False <add> ''' <add> try: <add> t = self.get_table(table_name, db) <add> return True <add> except Exception as e: <add> return False <add> <add> <ide> class HiveServer2Hook(BaseHook): <ide> ''' <ide> Wrapper around the pyhs2 library
1
Python
Python
add refesh time for server side
41a29c99c3f36149035219abc8f20d681bdcf5e8
<ide><path>glances/glances.py <ide> class GlancesHandler(SimpleXMLRPCRequestHandler): <ide> Main XMLRPC handler <ide> """ <ide> rpc_paths = ('/RPC2',) <add> <add> def log_message(self, format, *args): <add> # No message displayed on the server side <add> pass <ide> <ide> <ide> class GlancesInstance(): <ide> """ <ide> All the methods of this class are published as XML RPC methods <del> """ <add> """ <add> <add> def __init__(self, refresh_time = 1): <add> self.timer = Timer(0) <add> self.refresh_time = refresh_time <add> <add> def __update__(self): <add> # Never update more than 1 time per refresh_time <add> if self.timer.finished(): <add> stats.update() <add> self.timer = Timer(self.refresh_time) <ide> <ide> def init(self): <del> # Return the Glances version <add> # Return the Glances version <ide> return __version__ <del> <add> <ide> def getAll(self): <ide> # Update and return all the stats <del> stats.update() <add> self.__update__() <ide> return json.dumps(stats.getAll()) <ide> <ide> def getCpu(self): <ide> # Update and return CPU stats <del> stats.update() <add> self.__update__() <ide> return json.dumps(stats.getCpu()) <ide> <ide> def getLoad(self): <ide> # Update and return LOAD stats <del> stats.update() <add> self.__update__() <ide> return json.dumps(stats.getLoad()) <ide> <ide> def getMem(self): <ide> # Update and return MEM stats <del> stats.update() <add> self.__update__() <ide> return json.dumps(stats.getMem()) <ide> <ide> def getMemSwap(self): <ide> # Update and return MEMSWAP stats <del> stats.update() <add> self.__update__() <ide> return json.dumps(stats.getMemSwap()) <ide> <ide> <ide> class GlancesServer(): <ide> This class creates and manages the TCP client <ide> """ <ide> <del> def __init__(self, bind_address, bind_port = 61209, RequestHandler = GlancesHandler): <add> def __init__(self, bind_address, bind_port = 61209, <add> RequestHandler = GlancesHandler, <add> refresh_time = 1): <ide> self.server = SimpleXMLRPCServer((bind_address, bind_port), <ide> requestHandler = RequestHandler) <ide> self.server.register_introspection_functions() <del> self.server.register_instance(GlancesInstance()) <add> self.server.register_instance(GlancesInstance(refresh_time)) <ide> return <ide> <ide> def serve_forever(self): <ide> def __init__(self, server_address, server_port = 61209): <ide> try: <ide> self.client = xmlrpclib.ServerProxy('http://%s:%d' % (server_address, server_port)) <ide> except: <del> print _("Error: creating client socket http://%s:%d") % (server_address, server_port) <add> print _("Error: creating client socket http://%s:%d") % (server_address, server_port) <ide> return <ide> <ide> def client_init(self): <ide> def signal_handler(signal, frame): <ide> import collections <ide> <ide> # Init the server <del> print(_("Glances is listenning on %s:%s") % (bind_ip, server_port)) <del> server = GlancesServer(bind_ip, server_port, GlancesHandler) <add> print(_("Glances server is running on %s:%s") % (bind_ip, server_port)) <add> server = GlancesServer(bind_ip, server_port, GlancesHandler, refresh_time) <ide> <ide> # Init stats <ide> stats = glancesStats(server_tag = True)
1
Python
Python
decrease memory usage of lstm text gen example
b9fbc458ed70e6bffdfc5af9d9f0ad554b6c0cec
<ide><path>examples/lstm_text_generation.py <ide> print('nb sequences:', len(sentences)) <ide> <ide> print('Vectorization...') <del>X = np.zeros((len(sentences), maxlen, len(chars))) <del>y = np.zeros((len(sentences), len(chars))) <add>X = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool) <add>y = np.zeros((len(sentences), len(chars)), dtype=np.bool) <ide> for i, sentence in enumerate(sentences): <ide> for t, char in enumerate(sentence): <del> X[i, t, char_indices[char]] = 1. <del> y[i, char_indices[next_chars[i]]] = 1. <add> X[i, t, char_indices[char]] = 1 <add> y[i, char_indices[next_chars[i]]] = 1 <ide> <ide> <ide> # build the model: 2 stacked LSTM
1
Python
Python
teach gyp msvs generator about marmasm
06c10cdc4c20e46885e3af94281ec63cda5e7712
<ide><path>tools/gyp/pylib/gyp/MSVSSettings.py <ide> def _ValidateSettings(validators, settings, stderr): <ide> _lib = _Tool('VCLibrarianTool', 'Lib') <ide> _manifest = _Tool('VCManifestTool', 'Manifest') <ide> _masm = _Tool('MASM', 'MASM') <add>_armasm = _Tool('ARMASM', 'ARMASM') <ide> <ide> <ide> _AddTool(_compile) <ide> def _ValidateSettings(validators, settings, stderr): <ide> _AddTool(_lib) <ide> _AddTool(_manifest) <ide> _AddTool(_masm) <add>_AddTool(_armasm) <ide> # Add sections only found in the MSBuild settings. <ide> _msbuild_validators[''] = {} <ide> _msbuild_validators['ProjectReference'] = {} <ide><path>tools/gyp/pylib/gyp/generator/msvs.py <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> <ide> <ide> def _GenerateMSBuildFiltersFile(filters_path, source_files, <del> rule_dependencies, extension_to_rule_name): <add> rule_dependencies, extension_to_rule_name, <add> platforms): <ide> """Generate the filters file. <ide> <ide> This file is used by Visual Studio to organize the presentation of source <ide> def _GenerateMSBuildFiltersFile(filters_path, source_files, <ide> filter_group = [] <ide> source_group = [] <ide> _AppendFiltersForMSBuild('', source_files, rule_dependencies, <del> extension_to_rule_name, filter_group, source_group) <add> extension_to_rule_name, platforms, <add> filter_group, source_group) <ide> if filter_group: <ide> content = ['Project', <ide> {'ToolsVersion': '4.0', <ide> def _GenerateMSBuildFiltersFile(filters_path, source_files, <ide> <ide> <ide> def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, <del> extension_to_rule_name, <add> extension_to_rule_name, platforms, <ide> filter_group, source_group): <ide> """Creates the list of filters and sources to be added in the filter file. <ide> <ide> def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, <ide> # Recurse and add its dependents. <ide> _AppendFiltersForMSBuild(filter_name, source.contents, <ide> rule_dependencies, extension_to_rule_name, <del> filter_group, source_group) <add> platforms, filter_group, source_group) <ide> else: <ide> # It's a source. Create a source entry. <ide> _, element = _MapFileToMsBuildSourceType(source, rule_dependencies, <del> extension_to_rule_name) <add> extension_to_rule_name, <add> platforms) <ide> source_entry = [element, {'Include': source}] <ide> # Specify the filter it is part of, if any. <ide> if parent_filter_name: <ide> def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, <ide> <ide> <ide> def _MapFileToMsBuildSourceType(source, rule_dependencies, <del> extension_to_rule_name): <add> extension_to_rule_name, platforms): <ide> """Returns the group and element type of the source file. <ide> <ide> Arguments: <ide> def _MapFileToMsBuildSourceType(source, rule_dependencies, <ide> elif ext in ['.s', '.asm']: <ide> group = 'masm' <ide> element = 'MASM' <add> for platform in platforms: <add> if platform.lower() in ['arm', 'arm64']: <add> element = 'MARMASM' <ide> elif ext == '.idl': <ide> group = 'midl' <ide> element = 'Midl' <ide> def _AddSources2(spec, sources, exclusions, grouped_sources, <ide> detail.append(['ForcedIncludeFiles', '']) <ide> <ide> group, element = _MapFileToMsBuildSourceType(source, rule_dependencies, <del> extension_to_rule_name) <add> extension_to_rule_name, <add> _GetUniquePlatforms(spec)) <ide> grouped_sources[group].append([element, {'Include': source}] + detail) <ide> <ide> <ide> def _GenerateMSBuildProject(project, options, version, generator_flags): <ide> <ide> _GenerateMSBuildFiltersFile(project.path + '.filters', sources, <ide> rule_dependencies, <del> extension_to_rule_name) <add> extension_to_rule_name, _GetUniquePlatforms(spec)) <ide> missing_sources = _VerifySourcesExist(sources, project_dir) <ide> <ide> for configuration in configurations.itervalues(): <ide> def _GenerateMSBuildProject(project, options, version, generator_flags): <ide> import_masm_targets_section = [ <ide> ['Import', <ide> {'Project': r'$(VCTargetsPath)\BuildCustomizations\masm.targets'}]] <add> import_marmasm_props_section = [ <add> ['Import', <add> {'Project': r'$(VCTargetsPath)\BuildCustomizations\marmasm.props'}]] <add> import_marmasm_targets_section = [ <add> ['Import', <add> {'Project': r'$(VCTargetsPath)\BuildCustomizations\marmasm.targets'}]] <ide> macro_section = [['PropertyGroup', {'Label': 'UserMacros'}]] <ide> <ide> content = [ <ide> def _GenerateMSBuildProject(project, options, version, generator_flags): <ide> content += _GetMSBuildLocalProperties(project.msbuild_toolset) <ide> content += import_cpp_props_section <ide> content += import_masm_props_section <add> content += import_marmasm_props_section <ide> content += _GetMSBuildExtensions(props_files_of_rules) <ide> content += _GetMSBuildPropertySheets(configurations) <ide> content += macro_section <ide> def _GenerateMSBuildProject(project, options, version, generator_flags): <ide> content += _GetMSBuildProjectReferences(project) <ide> content += import_cpp_targets_section <ide> content += import_masm_targets_section <add> content += import_marmasm_targets_section <ide> content += _GetMSBuildExtensionTargets(targets_files_of_rules) <ide> <ide> if spec.get('msvs_external_builder'):
2
Javascript
Javascript
add clearqueue for clearing non-fx queues
d857315967a1cc07b73924bbdf2eb12f4f910c45
<ide><path>src/data.js <ide> jQuery.extend({ <ide> <ide> if( fn !== undefined ) <ide> fn.call(elem, function() { jQuery(elem).dequeue(type); }); <del> } <add> }, <ide> }); <ide> <ide> jQuery.fn.extend({ <ide> jQuery.fn.extend({ <ide> return this.each(function(){ <ide> jQuery.dequeue( this, type ); <ide> }); <add> }, <add> clearQueue: function(type){ <add> return this.queue( type, [] ); <ide> } <ide> }); <ide>\ No newline at end of file <ide><path>test/unit/data.js <ide> test("queue() with other types",function() { <ide> $div.removeData(); <ide> }); <ide> <del>test("queue() passes in the next item in the queue as a parameter", function() { <add>test("queue(name) passes in the next item in the queue as a parameter", function() { <ide> expect(2); <ide> <ide> var div = jQuery({}); <ide> test("queue() passes in the next item in the queue as a parameter", function() { <ide> div.dequeue("foo"); <ide> <ide> div.removeData(); <add>}); <add> <add> expect(1); <add> <add> var div = jQuery({}); <add> var counter = 0; <add> <add> div.queue("foo", function(next) { <add> counter++; <add> jQuery(this).clearQueue("foo"); <add> next(); <add> }).queue("foo", function(next) { <add> counter++; <add> }); <add> <add> div.dequeue("foo"); <add> <add> equals(counter, 1, "the queue was cleared"); <add>test("queue(name) passes in the next item in the queue as a parameter", function() { <add> expect(2); <add> <add> var div = jQuery({}); <add> var counter = 0; <add> <add> div.queue("foo", function(next) { <add> equals(++counter, 1, "Dequeueing"); <add> next(); <add> }).queue("foo", function(next) { <add> equals(++counter, 2, "Next was called"); <add> next(); <add> }).queue("bar", function() { <add> equals(++counter, 3, "Other queues are not triggered by next()") <add> }); <add> <add> div.dequeue("foo"); <add> <add> div.removeData(); <add>}); <add> <add>test("queue() passes in the next item in the queue as a parameter to fx queues", function() { <add> expect(2); <add> <add> var div = jQuery({}); <add> var counter = 0; <add> <add> div.queue(function(next) { <add> equals(++counter, 1, "Dequeueing"); <add> next(); <add> }).queue(function(next) { <add> equals(++counter, 2, "Next was called"); <add> next(); <add> }).queue(function() { <add> equals(++counter, 3, "Other queues are not triggered by next()") <add> }); <add> <add> div.dequeue(); <add> <add> div.removeData(); <add>}); <add> <add>test("clearQueue(name) clears the queue", function() { <add> expect(1); <add> <add> var div = jQuery({}); <add> var counter = 0; <add> <add> div.queue("foo", function(next) { <add> counter++; <add> jQuery(this).clearQueue("foo"); <add> next(); <add> }).queue("foo", function(next) { <add> counter++; <add> }); <add> <add> div.dequeue("foo"); <add> <add> equals(counter, 1, "the queue was cleared"); <add>}); <add> <add>test("clearQueue() clears the fx queue", function() { <add> expect(1); <add> <add> var div = jQuery({}); <add> var counter = 0; <add> <add> div.queue(function(next) { <add> counter++; <add> jQuery(this).clearQueue(); <add> next(); <add> }).queue(function(next) { <add> counter++; <add> }); <add> <add> div.dequeue(); <add> <add> equals(counter, 1, "the queue was cleared"); <ide> })
2
Javascript
Javascript
remove highlight caching for now
8aabd026adad3c03d593600700c70c169e7a1492
<ide><path>src/text-editor-component.js <ide> class LinesTileComponent { <ide> constructor (props) { <ide> this.props = props <ide> this.linesVnode = null <del> this.highlightsVnode = null <ide> etch.initialize(this) <ide> } <ide> <ide> class LinesTileComponent { <ide> if (newProps.width !== this.props.width) { <ide> this.linesVnode = null <ide> } <del> if (newProps.measuredContent || (!newProps.highlightDecorations && this.props.highlightDecorations)) { <del> this.highlightsVnode = null <del> } <ide> this.props = newProps <ide> etch.updateSync(this) <ide> } <ide> class LinesTileComponent { <ide> renderHighlights () { <ide> const {top, height, width, lineHeight, highlightDecorations} = this.props <ide> <del> if (!this.highlightsVnode) { <del> let children = null <del> if (highlightDecorations) { <del> const decorationCount = highlightDecorations.length <del> children = new Array(decorationCount) <del> for (let i = 0; i < decorationCount; i++) { <del> const highlightProps = Object.assign( <del> {parentTileTop: top, lineHeight}, <del> highlightDecorations[i] <del> ) <del> children[i] = $(HighlightComponent, highlightProps) <del> highlightDecorations[i].flashRequested = false <del> } <add> let children = null <add> if (highlightDecorations) { <add> const decorationCount = highlightDecorations.length <add> children = new Array(decorationCount) <add> for (let i = 0; i < decorationCount; i++) { <add> const highlightProps = Object.assign( <add> {parentTileTop: top, lineHeight}, <add> highlightDecorations[i] <add> ) <add> children[i] = $(HighlightComponent, highlightProps) <add> highlightDecorations[i].flashRequested = false <ide> } <del> <del> this.highlightsVnode = $.div( <del> { <del> style: { <del> position: 'absolute', <del> contain: 'strict', <del> height: height + 'px', <del> width: width + 'px' <del> }, <del> }, children <del> ) <ide> } <ide> <del> return this.highlightsVnode <add> return $.div( <add> { <add> style: { <add> position: 'absolute', <add> contain: 'strict', <add> height: height + 'px', <add> width: width + 'px' <add> }, <add> }, children <add> ) <ide> } <ide> <ide> renderLines () {
1
Python
Python
improve code on f-strings and brevity
dbee5f072f68c57bce3443e5ed07fe496ba9d76d
<ide><path>ciphers/enigma_machine2.py <ide> def _validator( <ide> rotorpos1, rotorpos2, rotorpos3 = rotpos <ide> if not 0 < rotorpos1 <= len(abc): <ide> raise ValueError( <del> f"First rotor position is not within range of 1..26 (" f"{rotorpos1}" <add> "First rotor position is not within range of 1..26 (" f"{rotorpos1}" <ide> ) <ide> if not 0 < rotorpos2 <= len(abc): <ide> raise ValueError( <del> f"Second rotor position is not within range of 1..26 (" f"{rotorpos2})" <add> "Second rotor position is not within range of 1..26 (" f"{rotorpos2})" <ide> ) <ide> if not 0 < rotorpos3 <= len(abc): <ide> raise ValueError( <del> f"Third rotor position is not within range of 1..26 (" f"{rotorpos3})" <add> "Third rotor position is not within range of 1..26 (" f"{rotorpos3})" <ide> ) <ide> <ide> # Validates string and returns dict <ide><path>ciphers/hill_cipher.py <ide> class HillCipher: <ide> # take x and return x % len(key_string) <ide> modulus = numpy.vectorize(lambda x: x % 36) <ide> <del> to_int = numpy.vectorize(lambda x: round(x)) <add> to_int = numpy.vectorize(round) <ide> <ide> def __init__(self, encrypt_key: numpy.ndarray) -> None: <ide> """ <ide><path>data_structures/hashing/number_theory/prime_numbers.py <ide> def check_prime(number): <ide> elif number == special_non_primes[-1]: <ide> return 3 <ide> <del> return all([number % i for i in range(2, number)]) <add> return all(number % i for i in range(2, number)) <ide> <ide> <ide> def next_prime(value, factor=1, **kwargs): <ide><path>divide_and_conquer/strassen_matrix_multiplication.py <ide> def strassen(matrix1: list, matrix2: list) -> list: <ide> """ <ide> if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]: <ide> raise Exception( <del> f"Unable to multiply these matrices, please check the dimensions. \n" <add> "Unable to multiply these matrices, please check the dimensions. \n" <ide> f"Matrix A:{matrix1} \nMatrix B:{matrix2}" <ide> ) <ide> dimension1 = matrix_dimensions(matrix1) <ide><path>dynamic_programming/rod_cutting.py <ide> def _enforce_args(n: int, prices: list): <ide> <ide> if n > len(prices): <ide> raise ValueError( <del> f"Each integral piece of rod must have a corresponding " <add> "Each integral piece of rod must have a corresponding " <ide> f"price. Got n = {n} but length of prices = {len(prices)}" <ide> ) <ide> <ide><path>hashes/enigma_machine.py <ide> def engine(input_character): <ide> print("\n" + "".join(code)) <ide> print( <ide> f"\nYour Token is {token} please write it down.\nIf you want to decode " <del> f"this message again you should input same digits as token!" <add> "this message again you should input same digits as token!" <ide> ) <ide><path>maths/integration_by_simpson_approx.py <ide> def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo <ide> assert callable( <ide> function <ide> ), f"the function(object) passed should be callable your input : {function}" <del> assert isinstance(a, float) or isinstance( <del> a, int <del> ), f"a should be float or integer your input : {a}" <del> assert isinstance(function(a), float) or isinstance(function(a), int), ( <add> assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" <add> assert isinstance(function(a), (float, int)), ( <ide> "the function should return integer or float return type of your function, " <ide> f"{type(a)}" <ide> ) <del> assert isinstance(b, float) or isinstance( <del> b, int <del> ), f"b should be float or integer your input : {b}" <add> assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" <ide> assert ( <ide> isinstance(precision, int) and precision > 0 <ide> ), f"precision should be positive integer your input : {precision}" <ide><path>matrix/matrix_operation.py <ide> def _verify_matrix_sizes( <ide> shape = _shape(matrix_a) + _shape(matrix_b) <ide> if shape[0] != shape[3] or shape[1] != shape[2]: <ide> raise ValueError( <del> f"operands could not be broadcast together with shape " <add> "operands could not be broadcast together with shape " <ide> f"({shape[0], shape[1]}), ({shape[2], shape[3]})" <ide> ) <ide> return (shape[0], shape[2]), (shape[1], shape[3]) <ide><path>project_euler/problem_067/sol1.py <ide> def solution(): <ide> triangle = f.readlines() <ide> <ide> a = map(lambda x: x.rstrip("\r\n").split(" "), triangle) <del> a = list(map(lambda x: list(map(lambda y: int(y), x)), a)) <add> a = list(map(lambda x: list(map(int, x)), a)) <ide> <ide> for i in range(1, len(a)): <ide> for j in range(len(a[i])): <ide><path>sorts/external_sort.py <ide> def split(self, block_size, sort_key=None): <ide> i += 1 <ide> <ide> def cleanup(self): <del> map(lambda f: os.remove(f), self.block_filenames) <add> map(os.remove, self.block_filenames) <ide> <ide> <ide> class NWayMerge:
10
PHP
PHP
add config file
6bf532e9665e280bd643059997db397427d27d42
<ide><path>tests/test_app/invalid_routes/routes.php <add><?php <add>/** <add> * Test routes file with routes that trigger a missing route class error. <add> * Application requests should have InvalidArgument error rendered. <add> */ <add>$routes->setRouteClass('DoesNotExist'); <add>$routes->get('/', ['controller' => 'Pages']);
1
Go
Go
remove unused parameter
0f134b4bf81a4d0160932852854b190b7ee7e3b9
<ide><path>graph.go <ide> func (graph *Graph) Create(layerData Archive, container *Container, comment, aut <ide> img.Container = container.ID <ide> img.ContainerConfig = *container.Config <ide> } <del> if err := graph.Register(nil, layerData, layerData != nil, img); err != nil { <add> if err := graph.Register(nil, layerData, img); err != nil { <ide> return nil, err <ide> } <ide> return img, nil <ide> } <ide> <ide> // Register imports a pre-existing image into the graph. <ide> // FIXME: pass img as first argument <del>func (graph *Graph) Register(jsonData []byte, layerData Archive, store bool, img *Image) error { <add>func (graph *Graph) Register(jsonData []byte, layerData Archive, img *Image) error { <ide> if err := ValidateID(img.ID); err != nil { <ide> return err <ide> } <ide> func (graph *Graph) Register(jsonData []byte, layerData Archive, store bool, img <ide> if err != nil { <ide> return fmt.Errorf("Mktemp failed: %s", err) <ide> } <del> if err := StoreImage(img, jsonData, layerData, tmp, store); err != nil { <add> if err := StoreImage(img, jsonData, layerData, tmp); err != nil { <ide> return err <ide> } <ide> // Commit <ide><path>image.go <ide> func LoadImage(root string) (*Image, error) { <ide> return img, nil <ide> } <ide> <del>func StoreImage(img *Image, jsonData []byte, layerData Archive, root string, store bool) error { <add>func StoreImage(img *Image, jsonData []byte, layerData Archive, root string) error { <ide> // Check that root doesn't already exist <ide> if _, err := os.Stat(root); err == nil { <ide> return fmt.Errorf("Image %s already exists", img.ID) <ide><path>server.go <ide> func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin <ide> return err <ide> } <ide> defer layer.Close() <del> if err := srv.runtime.graph.Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf.FormatProgress("Downloading", "%8v/%v (%v)"), sf), false, img); err != nil { <add> if err := srv.runtime.graph.Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf.FormatProgress("Downloading", "%8v/%v (%v)"), sf), img); err != nil { <ide> return err <ide> } <ide> }
3
Ruby
Ruby
match the units in `duration` (milliseconds)
0c0dba1caf72f78558554a28ca4fc01923cec6f1
<ide><path>activesupport/lib/active_support/notifications/instrumenter.rb <ide> def finish! <ide> @allocation_count_finish = now_allocations <ide> end <ide> <add> # Returns the CPU time (in milliseconds) passed since the call to <add> # +start!+ and the call to +finish!+ <ide> def cpu_time <del> @cpu_time_finish - @cpu_time_start <add> (@cpu_time_finish - @cpu_time_start) * 1000 <ide> end <ide> <add> # Returns the idle time time (in milliseconds) passed since the call to <add> # +start!+ and the call to +finish!+ <ide> def idle_time <ide> duration - cpu_time <ide> end <ide> <add> # Returns the number of allocations made since the call to +start!+ and <add> # the call to +finish!+ <ide> def allocations <ide> @allocation_count_finish - @allocation_count_start <ide> end
1
Ruby
Ruby
fix missed deprecations
0a1f2ad4f11f004611c1379899b027d86bc99304
<ide><path>activerecord/lib/active_record/railtie.rb <ide> class Railtie < Rails::Railtie # :nodoc: <ide> # this connection is trivial: the rest of the pool would need to be <ide> # populated anyway. <ide> <del> clear_active_connections!(:all) <del> flush_idle_connections!(:all) <add> connection_handler.clear_active_connections!(:all) <add> connection_handler.flush_idle_connections!(:all) <ide> end <ide> end <ide> end
1
PHP
PHP
add stub method for reseting sequences
7d34e2993d16057c424a8012a67d8d4810ea751c
<ide><path>lib/Cake/Database/Connection.php <ide> public function releaseSavePoint($name) { <ide> } <ide> <ide> /** <del> * Rollsback a save point by its name <add> * Rollback a save point by its name <ide> * <ide> * @param string $name <ide> * @return void <ide> public function rollbackSavepoint($name) { <ide> $this->execute($this->_driver->rollbackSavePointSQL($name)); <ide> } <ide> <add>/** <add> * Reset a sequence. <add> * <add> * Useful with database platforms that support sequences. <add> * <add> * @param string $table The table to reset. <add> * @param string $key The key to reset. <add> * @return boolean <add> */ <add> public function resetSequence($table, $key) { <add> // TODO implement this. <add> } <add> <ide> /** <ide> * Quotes value to be used safely in database query <ide> *
1
Text
Text
add tests to personal library
bd593667f6fbfc3233b1378a873a40c911d0a66b
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/personal-library.md <ide> forumTopicId: 301571 <ide> <ide> ## Description <ide> <section id='description'> <del>Build a full stack JavaScript app that is functionally similar to this: <a href="https://personal-library.freecodecamp.rocks/" target="_blank">https://personal-library.freecodecamp.rocks/</a>. <del>Working on this project will involve you writing your code on Repl.it on our starter project. After completing this project you can copy your public Repl.it URL (to the homepage of your app) into this screen to test it! Optionally you may choose to write your project on another platform but must be publicly visible for our testing. <del>Start this project on Repl.it using <a href="https://repl.it/github/freeCodeCamp/boilerplate-project-library/">this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-project-library/'>this repository</a> on GitHub! If you use Repl.it, remember to save the link to your project somewhere safe! <add> <add>Build a full stack JavaScript app that is functionally similar to [this site](https://personal-library.freecodecamp.rocks/). Working on this project will involve you writing your code using one of the following methods: <add> <add>- Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-personal-library) and complete your project locally. <add>- Use [our repl.it starter project](https://repl.it/github/freeCodeCamp/boilerplate-personal-library) to complete your project. <add>- Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo. <add> <add>When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field. <add> <ide> </section> <ide> <ide> ## Instructions <ide> <section id='instructions'> <ide> <add>1. Add your MongoDB connection string to `.env` without quotes as `DB` <add> Example: `DB=mongodb://admin:pass@1234.mlab.com:1234/fccpersonallib` <add>2. In your `.env` file set `NODE_ENV` to `test`, without quotes <add>3. You need to create all routes within `routes/api.js` <add>4. You will create all functional tests in `tests/2_functional-tests.js` <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: I can provide my own project, not the example URL. <add> - text: You can provide your own project, not the example URL. <ide> testString: | <ide> getUserInput => { <ide> assert(!/.*\/personal-library\.freecodecamp\.rocks/.test(getUserInput('url'))); <ide> } <del> - text: I can post a title to /api/books to add a book and returned will be the object with the title and a unique _id. <del> testString: '' <del> - text: I can get /api/books to retrieve an array of all books containing title, _id, and commentcount. <del> testString: '' <del> - text: I can get /api/books/{id} to retrieve a single object of a book containing _title, _id, & an array of comments (empty array if no comments present). <del> testString: '' <del> - text: I can post a comment to /api/books/{id} to add a comment to a book and returned will be the books object similar to get /api/books/{id} including the new comment. <del> testString: '' <del> - text: I can delete /api/books/{_id} to delete a book from the collection. Returned will be 'delete successful' if successful. <del> testString: '' <del> - text: If I try to request a book that doesn't exist I will be returned 'no book exists'. <del> testString: '' <del> - text: I can send a delete request to /api/books to delete all books in the database. Returned will be 'complete delete successful' if successful. <del> testString: '' <del> - text: All 6 functional tests required are complete and passing. <del> testString: '' <del> <add> - text: You can send a <b>POST</b> request to <code>/api/books</code> with <code>title</code> as part of the form data to add a book. The returned response will be an object with the <code>title</code> and a unique <code>_id</code> as keys. If <code>title</code> is not included in the request, the returned response should be the string <code>missing required field title</code>. <add> testString: "async getUserInput => { <add> try { <add> let data1 = await $.post(getUserInput('url') + '/api/books', { 'title': 'Faux Book 1' }); <add> assert.isObject(data1); <add> assert.property(data1,'title'); <add> assert.equal(data1.title, 'Faux Book 1'); <add> assert.property(data1,'_id'); <add> let data2 = await $.post(getUserInput('url') + '/api/books'); <add> assert.isString(data2); <add> assert.equal(data2, 'missing required field title'); <add> } catch(err) { <add> throw new Error(err.responseText || err.message); <add> } <add> }" <add> - text: You can send a <b>GET</b> request to <code>/api/books</code> and receive a JSON response representing all the books. The JSON response will be an array of objects with each object (book) containing <code>title</code>, <code>_id</code>, and <code>commentcount</code> properties. <add> testString: "async getUserInput => { <add> try { <add> let url = getUserInput('url') + '/api/books'; <add> let a = $.post(url, { 'title': 'Faux Book A' }); <add> let b = $.post(url, { 'title': 'Faux Book B' }); <add> let c = $.post(url, { 'title': 'Faux Book C' }); <add> Promise.all([a,b,c]).then(async () => { <add> let data = await $.get(url); <add> assert.isArray(data); <add> assert.isAtLeast(data.length,3); <add> data.forEach((book) => { <add> assert.isObject(book); <add> assert.property(book, 'title'); <add> assert.isString(book.title); <add> assert.property(book, '_id'); <add> assert.property(book, 'commentcount'); <add> assert.isNumber(book.commentcount); <add> }); <add> }); <add> } catch(err) { <add> throw new Error(err.responseText || err.message); <add> } <add> }" <add> - text: You can send a <b>GET</b> request to <code>/api/books/{_id}</code> to retrieve a single object of a book containing the properties <code>title</code>, <code>_id</code>, and a <code>comments</code> array (empty array if no comments present). If no book is found, return the string <code>no book exists</code>. <add> testString: "async getUserInput => { <add> try { <add> let url = getUserInput('url') + '/api/books'; <add> let noBook = await $.get(url + '/5f665eb46e296f6b9b6a504d'); <add> assert.isString(noBook); <add> assert.equal(noBook, 'no book exists'); <add> let sampleBook = await $.post(url, { 'title': 'Faux Book Alpha' }); <add> assert.isObject(sampleBook); <add> let bookId = sampleBook._id; <add> let bookQuery = await $.get(url + '/' + bookId); <add> assert.isObject(bookQuery); <add> assert.property(bookQuery, 'title'); <add> assert.equal(bookQuery.title, 'Faux Book Alpha' ); <add> assert.property(bookQuery, 'comments'); <add> assert.isArray(bookQuery.comments); <add> } catch(err) { <add> throw new Error(err.responseText || err.message); <add> } <add> }" <add> - text: You can send a <b>POST</b> request containing <code>comment</code> as the form body data to <code>/api/books/{_id}</code> to add a comment to a book. The returned response will be the books object similar to <b>GET</b> <code>/api/books/{_id}</code> request in an earlier test. If <code>comment</code> is not included in the request, return the string <code>missing required field comment</code>`. If no book is found, return the string <code>no book exists</code>. <add> testString: "async getUserInput => { <add> try { <add> let url = getUserInput('url') + '/api/books'; <add> let commentTarget = await $.post(url, { 'title': 'Notable Book' }); <add> assert.isObject(commentTarget); <add> let bookId = commentTarget._id; <add> let bookCom1 = await $.post(url + '/' + bookId, {'comment': 'This book is fab!'}); <add> let bookCom2 = await $.post(url + '/' + bookId, {'comment': 'I did not care for it'}); <add> assert.isObject(bookCom2); <add> assert.property(bookCom2,'_id'); <add> assert.property(bookCom2,'title'); <add> assert.property(bookCom2,'comments'); <add> assert.lengthOf(bookCom2.comments, 2); <add> bookCom2.comments.forEach((comment) => { <add> assert.isString(comment); <add> assert.oneOf(comment, ['This book is fab!','I did not care for it']); <add> }); <add> let commentErr = await $.post(url + '/' + bookId); <add> assert.isString(commentErr); <add> assert.equal(commentErr, 'missing required field comment'); <add> let failingComment = await $.post(url + '/5f665eb46e296f6b9b6a504d', { 'comment': 'Never Seen Comment' }); <add> assert.isString(failingComment); <add> assert.equal(failingComment, 'no book exists'); <add> } catch(err) { <add> throw new Error(err.responseText || err.message); <add> } <add> }" <add> - text: You can send a <b>DELETE</b> request to <code>/api/books/{_id}</code> to delete a book from the collection. The returned response will be the string <code>delete successful</code> if successful. If no book is found, return the string <code>no book exists</code>. <add> testString: "async getUserInput => { <add> try { <add> let url = getUserInput('url') + '/api/books'; <add> let deleteTarget = await $.post(url, { 'title': 'Deletable Book' }); <add> assert.isObject(deleteTarget); <add> let bookId = deleteTarget._id; <add> let doDelete = await $.ajax({url: url + '/' + bookId, type: 'DELETE'}); <add> assert.isString(doDelete); <add> assert.equal(doDelete, 'delete successful'); <add> let failingDelete = await $.ajax({url: url + '/5f665eb46e296f6b9b6a504d', type: 'DELETE'}); <add> assert.isString(failingDelete); <add> assert.equal(failingDelete, 'no book exists'); <add> } catch(err) { <add> throw new Error(err.responseText || err.message); <add> } <add> }" <add> - text: You can send a <b>DELETE</b> request to <code>/api/books</code> to delete all books in the database. The returned response will be the string <code>'complete delete successful</code> if successful. <add> testString: "async getUserInput => { <add> try { <add> const deleteAll = await $.ajax({ url: getUserInput('url') + '/api/books', type: 'DELETE' }); <add> assert.isString(deleteAll); <add> assert.equal(deleteAll, 'complete delete successful'); <add> } catch(err) { <add> throw new Error(err.responseText || err.message); <add> } <add> }" <add> - text: All 10 functional tests required are complete and passing. <add> testString: "async getUserInput => { <add> try { <add> const getTests = await $.get(getUserInput('url') + '/_api/get-tests' ); <add> assert.isArray(getTests); <add> assert.isAtLeast(getTests.length, 10, 'At least 10 tests passed'); <add> getTests.forEach(test => { <add> assert.equal(test.state, 'passed', 'Test in Passed State'); <add> assert.isAtLeast(test.assertions.length, 1, 'At least one assertion per test'); <add> }); <add> } catch(err) { <add> throw new Error(err.responseText || err.message); <add> } <add> }" <ide> ``` <ide> <ide> </section>
1
Javascript
Javascript
add spec for tvnavigationeventemitter
781c68cb43a5e4bb2a3a7e5053b673de6484a9d3
<ide><path>Libraries/Components/AppleTV/NativeTVNavigationEventEmitter.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <add>export interface Spec extends TurboModule { <add> +addListener: (eventName: string) => void; <add> +removeListeners: (count: number) => void; <add>} <add> <add>export default TurboModuleRegistry.get<Spec>('TVNavigationEventEmitter'); <ide><path>Libraries/Components/AppleTV/TVEventHandler.js <ide> 'use strict'; <ide> <ide> const Platform = require('../../Utilities/Platform'); <del>const TVNavigationEventEmitter = require('../../BatchedBridge/NativeModules') <del> .TVNavigationEventEmitter; <ide> const NativeEventEmitter = require('../../EventEmitter/NativeEventEmitter'); <ide> <add>import NativeTVNavigationEventEmitter from './NativeTVNavigationEventEmitter'; <add> <ide> function TVEventHandler() { <ide> this.__nativeTVNavigationEventListener = null; <ide> this.__nativeTVNavigationEventEmitter = null; <ide> TVEventHandler.prototype.enable = function( <ide> component: ?any, <ide> callback: Function, <ide> ) { <del> if (Platform.OS === 'ios' && !TVNavigationEventEmitter) { <add> if (Platform.OS === 'ios' && !NativeTVNavigationEventEmitter) { <ide> return; <ide> } <ide> <ide> this.__nativeTVNavigationEventEmitter = new NativeEventEmitter( <del> TVNavigationEventEmitter, <add> NativeTVNavigationEventEmitter, <ide> ); <ide> this.__nativeTVNavigationEventListener = this.__nativeTVNavigationEventEmitter.addListener( <ide> 'onHWKeyEvent',
2
Python
Python
fix flaky on_kill
e2345ffca9013de8dedaa6c75dbecb48c073353f
<ide><path>tests/dags/test_on_kill.py <ide> class DummyWithOnKill(DummyOperator): <ide> def execute(self, context): <ide> import os <ide> <add> self.log.info("Signalling that I am running") <add> # signal to the test that we've started <add> with open("/tmp/airflow_on_kill_running", "w") as f: <add> f.write("ON_KILL_RUNNING") <add> self.log.info("Signalled") <add> <ide> # This runs extra processes, so that we can be sure that we correctly <ide> # tidy up all processes launched by a task when killing <ide> if not os.fork(): <ide> def execute(self, context): <ide> <ide> def on_kill(self): <ide> self.log.info("Executing on_kill") <del> with open("/tmp/airflow_on_kill", "w") as f: <add> with open("/tmp/airflow_on_kill_killed", "w") as f: <ide> f.write("ON_KILL_TEST") <add> self.log.info("Executed on_kill") <ide> <ide> <ide> # DAG tests backfill with pooled tasks <ide> # Previously backfill would queue the task but never run it <ide> dag1 = DAG(dag_id='test_on_kill', start_date=datetime(2015, 1, 1)) <add> <ide> dag1_task1 = DummyWithOnKill(task_id='task1', dag=dag1, owner='airflow') <ide><path>tests/task/task_runner/test_standard_task_runner.py <ide> def test_on_kill(self): <ide> Test that ensures that clearing in the UI SIGTERMS <ide> the task <ide> """ <del> path = "/tmp/airflow_on_kill" <add> path_on_kill_running = "/tmp/airflow_on_kill_running" <add> path_on_kill_killed = "/tmp/airflow_on_kill_killed" <ide> try: <del> os.unlink(path) <add> os.unlink(path_on_kill_running) <add> except OSError: <add> pass <add> try: <add> os.unlink(path_on_kill_killed) <ide> except OSError: <ide> pass <ide> <ide> def test_on_kill(self): <ide> runner = StandardTaskRunner(job1) <ide> runner.start() <ide> <del> # give the task some time to startup <add> with timeout(seconds=3): <add> while True: <add> runner_pgid = os.getpgid(runner.process.pid) <add> if runner_pgid == runner.process.pid: <add> break <add> time.sleep(0.01) <add> <add> processes = list(self._procs_in_pgroup(runner_pgid)) <add> <add> logging.info("Waiting for the task to start") <add> with timeout(seconds=4): <add> while True: <add> if os.path.exists(path_on_kill_running): <add> break <add> time.sleep(0.01) <add> logging.info("Task started. Give the task some time to settle") <ide> time.sleep(3) <del> <del> pgid = os.getpgid(runner.process.pid) <del> assert pgid > 0 <del> assert pgid != os.getpgid(0), "Task should be in a different process group to us" <del> <del> processes = list(self._procs_in_pgroup(pgid)) <del> <add> logging.info(f"Terminating processes {processes} belonging to {runner_pgid} group") <ide> runner.terminate() <del> <ide> session.close() # explicitly close as `create_session`s commit will blow up otherwise <ide> <del> # Wait some time for the result <del> with timeout(seconds=40): <add> logging.info("Waiting for the on kill killed file to appear") <add> with timeout(seconds=4): <ide> while True: <del> if os.path.exists(path): <add> if os.path.exists(path_on_kill_killed): <ide> break <ide> time.sleep(0.01) <add> logging.info("The file appeared") <ide> <del> with open(path) as f: <add> with open(path_on_kill_killed) as f: <ide> assert "ON_KILL_TEST" == f.readline() <ide> <ide> for process in processes:
2
Javascript
Javascript
set maxwidth during title draw to avoid overflow
fb302d5f0074b5d367386319e696d5718b78a88d
<ide><path>src/core/core.title.js <ide> module.exports = function(Chart) { <ide> top = me.top, <ide> left = me.left, <ide> bottom = me.bottom, <del> right = me.right; <add> right = me.right, <add> maxWidth; <ide> <ide> ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour <ide> ctx.font = titleFont; <ide> module.exports = function(Chart) { <ide> if (me.isHorizontal()) { <ide> titleX = left + ((right - left) / 2); // midpoint of the width <ide> titleY = top + ((bottom - top) / 2); // midpoint of the height <add> maxWidth = right - left; <ide> } else { <ide> titleX = opts.position === 'left' ? left + (fontSize / 2) : right - (fontSize / 2); <ide> titleY = top + ((bottom - top) / 2); <add> maxWidth = bottom - top; <ide> rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5); <ide> } <ide> <ide> module.exports = function(Chart) { <ide> ctx.rotate(rotation); <ide> ctx.textAlign = 'center'; <ide> ctx.textBaseline = 'middle'; <del> ctx.fillText(opts.text, 0, 0); <add> ctx.fillText(opts.text, 0, 0, maxWidth); <ide> ctx.restore(); <ide> } <ide> }
1
Python
Python
combine legacy sections of _formatarray
fdd5c2d309c859f91784716ab03671c362ebbaba
<ide><path>numpy/core/arrayprint.py <ide> def _formatArray(a, format_function, rank, max_line_len, next_line_prefix, <ide> if rank == 0: <ide> return format_function(a[()]) + '\n' <ide> <del> if summary_insert and 2*edge_items < len(a): <add> show_summary = summary_insert and 2*edge_items < len(a) <add> <add> if show_summary: <ide> leading_items = edge_items <ide> trailing_items = edge_items <del> summary_insert1 = summary_insert + separator <del> if legacy == '1.13': <del> summary_insert1 = summary_insert + ', ' <ide> else: <ide> leading_items = 0 <ide> trailing_items = len(a) <del> summary_insert1 = "" <ide> <ide> if rank == 1: <ide> s = "" <ide> def _formatArray(a, format_function, rank, max_line_len, next_line_prefix, <ide> word = format_function(a[i]) + separator <ide> s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) <ide> <del> if summary_insert1: <del> s, line = _extendLine(s, line, summary_insert1, max_line_len, <del> next_line_prefix) <add> if show_summary: <add> if legacy == '1.13': <add> word = summary_insert + ", " <add> else: <add> word = summary_insert + separator <add> s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) <ide> <ide> for i in range(trailing_items, 1, -1): <ide> word = format_function(a[-i]) + separator <ide> def _formatArray(a, format_function, rank, max_line_len, next_line_prefix, <ide> s = '[' + s[len(next_line_prefix):] <ide> else: <ide> s = '[' <del> sep = separator.rstrip() <del> line_sep = '\n'*max(rank-1, 1) <add> line_sep = separator.rstrip() + '\n'*(rank - 1) <ide> for i in range(leading_items): <ide> if i > 0: <ide> s += next_line_prefix <ide> s += _formatArray(a[i], format_function, rank-1, max_line_len, <ide> " " + next_line_prefix, separator, edge_items, <ide> summary_insert, legacy) <del> s = s.rstrip() + sep.rstrip() + line_sep <add> s = s.rstrip() + line_sep <ide> <del> if summary_insert1: <add> if show_summary: <ide> if legacy == '1.13': <del> s += next_line_prefix + summary_insert1 + "\n" <add> # trailing space, fixed number of newlines, and fixed separator <add> s += next_line_prefix + summary_insert + ", \n" <ide> else: <del> s += next_line_prefix + summary_insert1.strip() + line_sep <add> s += next_line_prefix + summary_insert + line_sep <ide> <ide> for i in range(trailing_items, 1, -1): <ide> if leading_items or i != trailing_items: <ide> s += next_line_prefix <ide> s += _formatArray(a[-i], format_function, rank-1, max_line_len, <ide> " " + next_line_prefix, separator, edge_items, <ide> summary_insert, legacy) <del> s = s.rstrip() + sep.rstrip() + line_sep <add> s = s.rstrip() + line_sep <ide> if leading_items or trailing_items > 1: <ide> s += next_line_prefix <ide> s += _formatArray(a[-1], format_function, rank-1, max_line_len,
1
Python
Python
add admin to installed apps to avoid test failures
20f1203aaca951d58afe01a31ac7c7a056dd70c5
<ide><path>tests/conftest.py <ide> def pytest_configure(config): <ide> 'django.contrib.messages.middleware.MessageMiddleware', <ide> ), <ide> INSTALLED_APPS=( <add> 'django.contrib.admin', <ide> 'django.contrib.auth', <ide> 'django.contrib.contenttypes', <ide> 'django.contrib.sessions',
1
Python
Python
add linspace benchmark
e34d2a7b1e8d70d3fd99552dc77626add7a59e16
<ide><path>benchmarks/benchmarks/bench_function_base.py <ide> <ide> import numpy as np <ide> <add>class Linspace(Benchmark): <add> def setup(self): <add> self.d = np.array([1, 2, 3]) <add> <add> def time_linspace_scalar(self): <add> np.linspace(0, 10, 2) <add> <add> def time_linspace_array(self): <add> np.linspace(self.d, 10, 10) <ide> <ide> class Histogram1D(Benchmark): <ide> def setup(self):
1
Ruby
Ruby
add missing closing tag [ci skip]
77bdbb5f41307f5566f41964479369521a616223
<ide><path>activejob/lib/active_job/exceptions.rb <ide> module ClassMethods <ide> # ==== Options <ide> # * <tt>:wait</tt> - Re-enqueues the job with a delay specified either in seconds (default: 3 seconds), <ide> # as a computing proc that the number of executions so far as an argument, or as a symbol reference of <del> # <tt>:exponentially_longer<>, which applies the wait algorithm of <tt>(executions ** 4) + 2</tt> <add> # <tt>:exponentially_longer</tt>, which applies the wait algorithm of <tt>(executions ** 4) + 2</tt> <ide> # (first wait 3s, then 18s, then 83s, etc) <ide> # * <tt>:attempts</tt> - Re-enqueues the job the specified number of times (default: 5 attempts) <ide> # * <tt>:queue</tt> - Re-enqueues the job on a different queue
1
Go
Go
use net/http instead of x/ctxhttp
3e5b9cb46688ee5d6886ad3be4cb591f1ba49ed1
<ide><path>client/request.go <ide> import ( <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/versions" <ide> "github.com/pkg/errors" <del> "golang.org/x/net/context/ctxhttp" <ide> ) <ide> <ide> // serverResponse is a wrapper for http API responses. <ide> func (cli *Client) sendRequest(ctx context.Context, method, path string, query u <ide> func (cli *Client) doRequest(ctx context.Context, req *http.Request) (serverResponse, error) { <ide> serverResp := serverResponse{statusCode: -1, reqURL: req.URL} <ide> <del> resp, err := ctxhttp.Do(ctx, cli.client, req) <add> req = req.WithContext(ctx) <add> resp, err := cli.client.Do(req) <ide> if err != nil { <ide> if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") { <ide> return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err)
1
Java
Java
introduce httpmessage hierarchy
bab3b6fd1c4946cdba59aca365aba1a7f4ca6033
<add><path>spring-web-reactive/src/main/java/org/springframework/http/ReactiveHttpInputMessage.java <del><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/ServerHttpRequest.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.reactive.web.http; <add> <add>package org.springframework.http; <ide> <ide> import java.nio.ByteBuffer; <ide> <ide> import org.reactivestreams.Publisher; <ide> <ide> /** <del> * Represent a server-side HTTP request. <add> * Represents a "reactive" HTTP input message, consisting of {@linkplain #getHeaders() headers} <add> * and a readable {@linkplain #getBody() streaming body }. <add> * <add> * <p>Typically implemented by an HTTP request on the server-side, or a response on the client-side. <ide> * <del> * @author Rossen Stoyanchev <add> * @author Arjen Poutsma <ide> */ <del>public interface ServerHttpRequest extends HttpRequest { <add>public interface ReactiveHttpInputMessage extends HttpMessage { <ide> <ide> /** <del> * Return the body of the message as a reactive stream. <add> * Return the body of the message as an publisher of {@code ByteBuffer}s. <add> * @return the body <ide> */ <ide> Publisher<ByteBuffer> getBody(); <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/http/ReactiveHttpOutputMessage.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.http; <add> <add>import java.nio.ByteBuffer; <add> <add>import org.reactivestreams.Publisher; <add> <add>/** <add> * Represents a "reactive" HTTP output message, consisting of {@linkplain #getHeaders() headers} <add> * and the capability to add a {@linkplain #addBody(Publisher) body}. <add> * <add> * <p>Typically implemented by an HTTP request on the client-side, or a response on the server-side. <add> * <add> * @author Arjen Poutsma <add> */ <add>public interface ReactiveHttpOutputMessage extends HttpMessage { <add> <add> /** <add> * Adds the given publisher of {@link ByteBuffer}s as a body. A HTTP/1.1 message has <add> * one body, but HTTP/1.2 supports multiple bodies. <add> * @param body the body to add <add> * @return a publisher that indicates completion <add> */ <add> Publisher<Void> addBody(Publisher<ByteBuffer> body); <add> <add>} <add><path>spring-web-reactive/src/main/java/org/springframework/http/client/ReactiveClientHttpRequest.java <del><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/HttpRequest.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.reactive.web.http; <ide> <del>import java.net.URI; <add>package org.springframework.http.client; <ide> <del>import org.springframework.http.HttpMethod; <add>import org.springframework.http.HttpRequest; <add>import org.springframework.http.ReactiveHttpOutputMessage; <ide> <ide> /** <del> * @author Rossen Stoyanchev <add> * Represents a "reactive" client-side HTTP request. <add> * <add> * @author Arjen Poutsma <ide> */ <del>public interface HttpRequest extends HttpMessage { <del> <del> HttpMethod getMethod(); <del> <del> URI getURI(); <add>public interface ReactiveClientHttpRequest extends HttpRequest, ReactiveHttpOutputMessage { <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/http/client/ReactiveClientHttpResponse.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.http.client; <add> <add>import java.io.Closeable; <add>import java.io.IOException; <add> <add>import org.springframework.http.HttpStatus; <add>import org.springframework.http.ReactiveHttpInputMessage; <add> <add>/** <add> * Represents a "reactive" client-side HTTP response. <add> * <add> * @author Arjen Poutsma <add> */ <add>public interface ReactiveClientHttpResponse extends ReactiveHttpInputMessage, Closeable { <add> <add> /** <add> * Return the HTTP status code of the response. <add> * @return the HTTP status as an HttpStatus enum value <add> * @throws IOException in case of I/O errors <add> */ <add> HttpStatus getStatusCode() throws IOException; <add> <add> /** <add> * Return the HTTP status code of the response as integer <add> * @return the HTTP status as an integer <add> * @throws IOException in case of I/O errors <add> */ <add> int getRawStatusCode() throws IOException; <add> <add> /** <add> * Return the HTTP status text of the response. <add> * @return the HTTP status text <add> * @throws IOException in case of I/O errors <add> */ <add> String getStatusText() throws IOException; <add> <add> /** <add> * Close this response, freeing any resources created. <add> */ <add> @Override <add> void close(); <add> <add>} <add><path>spring-web-reactive/src/main/java/org/springframework/http/server/ReactiveServerHttpRequest.java <del><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/HttpMessage.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.reactive.web.http; <ide> <del>import org.springframework.http.HttpHeaders; <add>package org.springframework.http.server; <add> <add>import org.springframework.http.HttpRequest; <add>import org.springframework.http.ReactiveHttpInputMessage; <ide> <ide> /** <del> * @author Rossen Stoyanchev <add> * Represents a "reactive" server-side HTTP request <add> * <add> * @author Arjen Poutsma <ide> */ <del>public interface HttpMessage { <del> <del> HttpHeaders getHeaders(); <add>public interface ReactiveServerHttpRequest extends HttpRequest, ReactiveHttpInputMessage { <ide> <ide> } <add><path>spring-web-reactive/src/main/java/org/springframework/http/server/ReactiveServerHttpResponse.java <del><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/ServerHttpResponse.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.reactive.web.http; <ide> <del>import java.nio.ByteBuffer; <del> <del>import org.reactivestreams.Publisher; <add>package org.springframework.http.server; <ide> <ide> import org.springframework.http.HttpStatus; <add>import org.reactivestreams.Publisher; <add>import org.springframework.http.ReactiveHttpOutputMessage; <ide> <ide> /** <del> * Represent a server-side HTTP response. <add> * Represents a "reactive" server-side HTTP response. <ide> * <del> * @author Rossen Stoyanchev <add> * @author Arjen Poutsma <ide> */ <del>public interface ServerHttpResponse extends HttpMessage { <add>public interface ReactiveServerHttpResponse <add> extends ReactiveHttpOutputMessage { <ide> <add> /** <add> * Set the HTTP status code of the response. <add> * @param status the HTTP status as an HttpStatus enum value <add> */ <ide> void setStatusCode(HttpStatus status); <del> <add> <ide> /** <ide> * Write the response headers. This method must be invoked to send responses without body. <ide> * @return A {@code Publisher<Void>} used to signal the demand, and receive a notification <ide> * when the handling is complete (success or error) including the flush of the data on the <ide> * network. <ide> */ <ide> Publisher<Void> writeHeaders(); <del> <del> /** <del> * Write the provided reactive stream of bytes to the response body. Most servers <del> * support multiple {@code writeWith} calls. Headers are written automatically <del> * before the body, so not need to call {@link #writeHeaders()} explicitly. <del> * @param contentPublisher the stream to write in the response body. <del> * @return A {@code Publisher<Void>} used to signal the demand, and receive a notification <del> * when the handling is complete (success or error) including the flush of the data on the <del> * network. <del> */ <del> Publisher<Void> writeWith(Publisher<ByteBuffer> contentPublisher); <del> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/DispatcherHandler.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch; <ide> <add>import java.util.ArrayList; <add>import java.util.List; <add>import java.util.Map; <add> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.reactivestreams.Publisher; <add>import reactor.Publishers; <add> <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.beans.factory.BeanFactoryUtils; <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator; <ide> import org.springframework.http.HttpStatus; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> import org.springframework.reactive.web.http.HttpHandler; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <del>import reactor.Publishers; <del> <del>import java.util.ArrayList; <del>import java.util.List; <del>import java.util.Map; <ide> <ide> /** <ide> * Central dispatcher for HTTP request handlers/controllers. Dispatches to registered <ide> protected void initStrategies(ApplicationContext context) { <ide> <ide> <ide> @Override <del> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { <add> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) { <ide> <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Processing " + request.getMethod() + " request for [" + request.getURI() + "]"); <ide> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse resp <ide> <ide> } <ide> <del> protected Object getHandler(ServerHttpRequest request) { <add> protected Object getHandler(ReactiveServerHttpRequest request) { <ide> Object handler = null; <ide> for (HandlerMapping handlerMapping : this.handlerMappings) { <ide> handler = handlerMapping.getHandler(request); <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/HandlerAdapter.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch; <ide> <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> <ide> /** <ide> * Interface that must be implemented for each handler type to handle an HTTP request. <ide> public interface HandlerAdapter { <ide> * @throws Exception in case of errors <ide> * @return An {@link HandlerResult} instance <ide> */ <del> HandlerResult handle(ServerHttpRequest request, ServerHttpResponse response, Object handler) throws Exception; <add> HandlerResult handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response, Object handler) throws Exception; <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/HandlerMapping.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch; <ide> <del>import org.springframework.reactive.web.http.ServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> */ <ide> public interface HandlerMapping { <ide> <del> Object getHandler(ServerHttpRequest request); <add> Object getHandler(ReactiveServerHttpRequest request); <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/HandlerResultHandler.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch; <ide> <ide> import org.reactivestreams.Publisher; <ide> <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> <ide> /** <ide> * Process the {@link HandlerResult}, usually returned by an {@link HandlerAdapter}. <ide> public interface HandlerResultHandler { <ide> * when the handling is complete (success or error) including the flush of the data on the <ide> * network. <ide> */ <del> Publisher<Void> handleResult(ServerHttpRequest request, ServerHttpResponse response, HandlerResult result); <add> Publisher<Void> handleResult(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response, HandlerResult result); <ide> <ide> } <ide>\ No newline at end of file <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/SimpleHandlerResultHandler.java <ide> import reactor.Publishers; <ide> <ide> import org.springframework.core.Ordered; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> <ide> /** <ide> * Supports {@link HandlerResult} with a {@code Publisher<Void>} value. <ide> public boolean supports(HandlerResult result) { <ide> } <ide> <ide> @Override <del> public Publisher<Void> handleResult(ServerHttpRequest request, ServerHttpResponse response, HandlerResult result) { <add> public Publisher<Void> handleResult(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response, HandlerResult result) { <ide> Publisher<Void> handleComplete = Publishers.completable((Publisher<?>)result.getValue()); <ide> return Publishers.concat(Publishers.from(Arrays.asList(handleComplete, response.writeHeaders()))); <ide> } <del> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/handler/HttpHandlerAdapter.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch.handler; <ide> <ide> import org.reactivestreams.Publisher; <ide> <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> import org.springframework.reactive.web.dispatch.HandlerAdapter; <ide> import org.springframework.reactive.web.dispatch.HandlerResult; <ide> import org.springframework.reactive.web.http.HttpHandler; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <del> <ide> <ide> /** <ide> * Support use of {@link HttpHandler} with <ide> public boolean supports(Object handler) { <ide> } <ide> <ide> @Override <del> public HandlerResult handle(ServerHttpRequest request, ServerHttpResponse response, Object handler) { <add> public HandlerResult handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response, Object handler) { <ide> HttpHandler httpHandler = (HttpHandler)handler; <ide> Publisher<Void> completion = httpHandler.handle(request, response); <ide> return new HandlerResult(httpHandler, completion); <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/handler/SimpleUrlHandlerMapping.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch.handler; <ide> <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <add>import org.springframework.http.server.ReactiveServerHttpRequest; <ide> import org.springframework.reactive.web.dispatch.HandlerMapping; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del> <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> public void setHandlers(Map<String, Object> handlers) { <ide> <ide> <ide> @Override <del> public Object getHandler(ServerHttpRequest request) { <add> public Object getHandler(ReactiveServerHttpRequest request) { <ide> return this.handlerMap.get(request.getURI().getPath()); <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/HandlerMethodArgumentResolver.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.reactive.web.dispatch.method; <ide> <add>package org.springframework.reactive.web.dispatch.method; <ide> <ide> import org.springframework.core.MethodParameter; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <ide> <ide> <ide> /** <ide> public interface HandlerMethodArgumentResolver { <ide> <ide> boolean supportsParameter(MethodParameter parameter); <ide> <del> Object resolveArgument(MethodParameter parameter, ServerHttpRequest request); <add> Object resolveArgument(MethodParameter parameter, ReactiveServerHttpRequest request); <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/InvocableHandlerMethod.java <ide> import org.springframework.core.GenericTypeResolver; <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.ParameterNameDiscoverer; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <ide> import org.springframework.util.ReflectionUtils; <ide> import org.springframework.web.method.HandlerMethod; <ide> <ide> public void setHandlerMethodArgumentResolvers(List<HandlerMethodArgumentResolver <ide> } <ide> <ide> <del> public Object invokeForRequest(ServerHttpRequest request, Object... providedArgs) throws Exception { <add> public Object invokeForRequest(ReactiveServerHttpRequest request, Object... providedArgs) throws Exception { <ide> Object[] args = getMethodArgumentValues(request, providedArgs); <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Invoking [" + getBeanType().getSimpleName() + "." + <ide> public Object invokeForRequest(ServerHttpRequest request, Object... providedArgs <ide> return returnValue; <ide> } <ide> <del> private Object[] getMethodArgumentValues(ServerHttpRequest request, Object... providedArgs) throws Exception { <add> private Object[] getMethodArgumentValues(ReactiveServerHttpRequest request, Object... providedArgs) throws Exception { <ide> MethodParameter[] parameters = getMethodParameters(); <ide> Object[] args = new Object[parameters.length]; <ide> for (int i = 0; i < parameters.length; i++) { <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/annotation/RequestBodyArgumentResolver.java <ide> <ide> package org.springframework.reactive.web.dispatch.method.annotation; <ide> <add>import java.nio.ByteBuffer; <add>import java.nio.charset.Charset; <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.List; <add>import java.util.concurrent.CompletableFuture; <add>import java.util.concurrent.TimeUnit; <add> <ide> import org.reactivestreams.Publisher; <add>import reactor.Publishers; <add>import reactor.core.publisher.convert.CompletableFutureConverter; <add>import reactor.core.publisher.convert.RxJava1Converter; <add>import reactor.core.publisher.convert.RxJava1SingleConverter; <add>import reactor.rx.Promise; <add>import reactor.rx.Stream; <add>import reactor.rx.Streams; <add>import rx.Observable; <add>import rx.Single; <add> <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.convert.ConversionService; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.MediaType; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <ide> import org.springframework.reactive.codec.decoder.ByteToMessageDecoder; <ide> import org.springframework.reactive.web.dispatch.method.HandlerMethodArgumentResolver; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <ide> import org.springframework.web.bind.annotation.RequestBody; <ide> <del>import java.nio.ByteBuffer; <del>import java.nio.charset.Charset; <del>import java.util.ArrayList; <del>import java.util.Collections; <del>import java.util.List; <del> <ide> /** <ide> * @author Sebastien Deleuze <ide> * @author Stephane Maldini <ide> public boolean supportsParameter(MethodParameter parameter) { <ide> <ide> @Override <ide> @SuppressWarnings("unchecked") <del> public Object resolveArgument(MethodParameter parameter, ServerHttpRequest request) { <add> public Object resolveArgument(MethodParameter parameter, ReactiveServerHttpRequest request) { <ide> <ide> MediaType mediaType = resolveMediaType(request); <ide> ResolvableType type = ResolvableType.forMethodParameter(parameter); <ide> public Object resolveArgument(MethodParameter parameter, ServerHttpRequest reque <ide> } <ide> } <ide> <del> private MediaType resolveMediaType(ServerHttpRequest request) { <add> private MediaType resolveMediaType(ReactiveServerHttpRequest request) { <ide> String acceptHeader = request.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE); <ide> List<MediaType> mediaTypes = MediaType.parseMediaTypes(acceptHeader); <ide> MediaType.sortBySpecificityAndQuality(mediaTypes); <ide> return ( mediaTypes.size() > 0 ? mediaTypes.get(0) : MediaType.TEXT_PLAIN); <ide> } <ide> <del> private ByteToMessageDecoder<?> resolveDeserializers(ServerHttpRequest request, ResolvableType type, MediaType mediaType, Object[] hints) { <add> private ByteToMessageDecoder<?> resolveDeserializers(ReactiveServerHttpRequest request, ResolvableType type, MediaType mediaType, Object[] hints) { <ide> for (ByteToMessageDecoder<?> deserializer : this.deserializers) { <ide> if (deserializer.canDecode(type, mediaType, hints)) { <ide> return deserializer; <ide> private ByteToMessageDecoder<?> resolveDeserializers(ServerHttpRequest request, <ide> return null; <ide> } <ide> <del> private List<ByteToMessageDecoder<ByteBuffer>> resolvePreProcessors(ServerHttpRequest request, ResolvableType type, MediaType mediaType, Object[] hints) { <add> private List<ByteToMessageDecoder<ByteBuffer>> resolvePreProcessors(ReactiveServerHttpRequest request, ResolvableType type, MediaType mediaType, Object[] hints) { <ide> List<ByteToMessageDecoder<ByteBuffer>> preProcessors = new ArrayList<>(); <ide> for (ByteToMessageDecoder<ByteBuffer> preProcessor : this.preProcessors) { <ide> if (preProcessor.canDecode(type, mediaType, hints)) { <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/annotation/RequestMappingHandlerAdapter.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch.method.annotation; <ide> <ide> import java.nio.ByteBuffer; <ide> import org.springframework.beans.factory.InitializingBean; <ide> import org.springframework.reactive.codec.decoder.ByteBufferDecoder; <ide> import org.springframework.reactive.codec.decoder.ByteToMessageDecoder; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> import org.springframework.reactive.codec.decoder.JacksonJsonDecoder; <ide> import org.springframework.reactive.codec.decoder.JsonObjectDecoder; <ide> import org.springframework.reactive.codec.decoder.StringDecoder; <ide> import org.springframework.reactive.web.dispatch.HandlerAdapter; <ide> import org.springframework.reactive.web.dispatch.HandlerResult; <ide> import org.springframework.reactive.web.dispatch.method.HandlerMethodArgumentResolver; <ide> import org.springframework.reactive.web.dispatch.method.InvocableHandlerMethod; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <ide> import org.springframework.web.method.HandlerMethod; <ide> <ide> <ide> public boolean supports(Object handler) { <ide> } <ide> <ide> @Override <del> public HandlerResult handle(ServerHttpRequest request, ServerHttpResponse response, <add> public HandlerResult handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response, <ide> Object handler) throws Exception { <ide> <ide> final InvocableHandlerMethod invocable = new InvocableHandlerMethod((HandlerMethod) handler); <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/annotation/RequestMappingHandlerMapping.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch.method.annotation; <ide> <ide> import java.util.Arrays; <ide> import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.core.annotation.AnnotationUtils; <ide> import org.springframework.http.HttpMethod; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <ide> import org.springframework.reactive.web.dispatch.HandlerMapping; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> protected void detectHandlerMethods(final Object bean) { <ide> } <ide> <ide> @Override <del> public Object getHandler(ServerHttpRequest request) { <add> public Object getHandler(ReactiveServerHttpRequest request) { <ide> String path = request.getURI().getPath(); <ide> HttpMethod method = request.getMethod(); <ide> for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : this.methodMap.entrySet()) { <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/annotation/RequestParamArgumentResolver.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch.method.annotation; <ide> <ide> <ide> import org.springframework.core.MethodParameter; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <ide> import org.springframework.reactive.web.dispatch.method.HandlerMethodArgumentResolver; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <ide> import org.springframework.web.bind.annotation.RequestParam; <ide> import org.springframework.web.util.UriComponents; <ide> import org.springframework.web.util.UriComponentsBuilder; <ide> public boolean supportsParameter(MethodParameter parameter) { <ide> <ide> <ide> @Override <del> public Object resolveArgument(MethodParameter param, ServerHttpRequest request) { <add> public Object resolveArgument(MethodParameter param, ReactiveServerHttpRequest request) { <ide> RequestParam annotation = param.getParameterAnnotation(RequestParam.class); <ide> String name = (annotation.value().length() != 0 ? annotation.value() : param.getParameterName()); <ide> UriComponents uriComponents = UriComponentsBuilder.fromUri(request.getURI()).build(); <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/annotation/ResponseBodyResultHandler.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch.method.annotation; <ide> <add>import java.lang.reflect.Type; <add>import java.nio.ByteBuffer; <add>import java.nio.charset.Charset; <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.List; <add>import java.util.concurrent.CompletableFuture; <add> <ide> import org.reactivestreams.Publisher; <add>import reactor.Publishers; <add>import reactor.core.publisher.convert.CompletableFutureConverter; <add>import reactor.core.publisher.convert.RxJava1Converter; <add>import reactor.core.publisher.convert.RxJava1SingleConverter; <add>import reactor.rx.Promise; <add>import rx.Observable; <add>import rx.Single; <add> <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.Ordered; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.annotation.AnnotatedElementUtils; <ide> import org.springframework.core.convert.ConversionService; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.MediaType; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> import org.springframework.reactive.codec.encoder.MessageToByteEncoder; <ide> import org.springframework.reactive.web.dispatch.HandlerResult; <ide> import org.springframework.reactive.web.dispatch.HandlerResultHandler; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <ide> import org.springframework.web.bind.annotation.ResponseBody; <ide> import org.springframework.web.method.HandlerMethod; <del>import reactor.Publishers; <del> <del>import java.nio.ByteBuffer; <del>import java.nio.charset.Charset; <del>import java.util.ArrayList; <del>import java.util.Collections; <del>import java.util.List; <ide> <ide> <ide> /** <ide> public boolean supports(HandlerResult result) { <ide> <ide> @Override <ide> @SuppressWarnings("unchecked") <del> public Publisher<Void> handleResult(ServerHttpRequest request, ServerHttpResponse response, <add> public Publisher<Void> handleResult(ReactiveServerHttpRequest request, <add> ReactiveServerHttpResponse response, <ide> HandlerResult result) { <ide> <ide> Object value = result.getValue(); <ide> public Publisher<Void> handleResult(ServerHttpRequest request, ServerHttpRespons <ide> outputStream = postProcessor.encode(outputStream, elementType, mediaType, hints.toArray()); <ide> } <ide> response.getHeaders().setContentType(mediaType); <del> return response.writeWith(outputStream); <add> return response.addBody(outputStream); <ide> } <ide> return Publishers.error(new IllegalStateException( <ide> "Return value type '" + returnType.getParameterType().getName() + "' with media type '" + mediaType + "' not supported" )); <ide> } <ide> <del> private MediaType resolveMediaType(ServerHttpRequest request) { <add> private MediaType resolveMediaType(ReactiveServerHttpRequest request) { <ide> String acceptHeader = request.getHeaders().getFirst(HttpHeaders.ACCEPT); <ide> List<MediaType> mediaTypes = MediaType.parseMediaTypes(acceptHeader); <ide> MediaType.sortBySpecificityAndQuality(mediaTypes); <ide> return ( mediaTypes.size() > 0 ? mediaTypes.get(0) : MediaType.TEXT_PLAIN); <ide> } <ide> <del> private MessageToByteEncoder<?> resolveSerializer(ServerHttpRequest request, ResolvableType type, MediaType mediaType, Object[] hints) { <add> private MessageToByteEncoder<?> resolveSerializer(ReactiveServerHttpRequest request, ResolvableType type, MediaType mediaType, Object[] hints) { <ide> for (MessageToByteEncoder<?> codec : this.serializers) { <ide> if (codec.canEncode(type, mediaType, hints)) { <ide> return codec; <ide> private MessageToByteEncoder<?> resolveSerializer(ServerHttpRequest request, Res <ide> return null; <ide> } <ide> <del> private List<MessageToByteEncoder<ByteBuffer>> resolvePostProcessors(ServerHttpRequest request, ResolvableType type, MediaType mediaType, Object[] hints) { <add> private List<MessageToByteEncoder<ByteBuffer>> resolvePostProcessors(ReactiveServerHttpRequest request, ResolvableType type, MediaType mediaType, Object[] hints) { <ide> List<MessageToByteEncoder<ByteBuffer>> postProcessors = new ArrayList<>(); <ide> for (MessageToByteEncoder<ByteBuffer> postProcessor : this.postProcessors) { <ide> if (postProcessor.canEncode(type, mediaType, hints)) { <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/HttpHandler.java <ide> <ide> import org.reactivestreams.Publisher; <ide> <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> <ide> /** <ide> * Interface for handlers that process HTTP requests and generate an HTTP response. <ide> * @author Arjen Poutsma <ide> * @author Rossen Stoyanchev <ide> * @author Sebastien Deleuze <del> * @see ServerHttpRequest#getBody() <del> * @see ServerHttpResponse#writeWith(Publisher) <add> * @see ReactiveServerHttpRequest#getBody() <add> * @see ReactiveServerHttpResponse#addBody(Publisher) <ide> */ <ide> public interface HttpHandler { <ide> <ide> public interface HttpHandler { <ide> * when the handling is complete (success or error) including the flush of the data on the <ide> * network. <ide> */ <del> Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response); <add> Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response); <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/reactor/ReactorServerHttpRequest.java <ide> /* <del> * Copyright (c) 2011-2015 Pivotal Software Inc, All Rights Reserved. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * You may obtain a copy of the License at <ide> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <add> * http://www.apache.org/licenses/LICENSE-2.0 <ide> * <ide> * Unless required by applicable law or agreed to in writing, software <ide> * distributed under the License is distributed on an "AS IS" BASIS, <ide> import reactor.io.net.http.HttpChannel; <ide> import reactor.rx.Stream; <ide> import reactor.rx.Streams; <add>import java.net.URI; <add>import java.net.URISyntaxException; <add>import java.nio.ByteBuffer; <add> <add>import org.reactivestreams.Publisher; <add>import reactor.io.buffer.Buffer; <add>import reactor.io.net.http.HttpChannel; <add> <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.http.HttpMethod; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.util.Assert; <ide> <ide> /** <ide> * @author Stephane Maldini <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/reactor/ReactorServerHttpResponse.java <ide> /* <del> * Copyright (c) 2011-2015 Pivotal Software Inc, All Rights Reserved. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * You may obtain a copy of the License at <ide> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <add> * http://www.apache.org/licenses/LICENSE-2.0 <ide> * <ide> * Unless required by applicable law or agreed to in writing, software <ide> * distributed under the License is distributed on an "AS IS" BASIS, <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/rxnetty/RxNettyServerHttpRequest.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.http.rxnetty; <ide> <add>import java.net.URI; <add>import java.net.URISyntaxException; <add>import java.nio.ByteBuffer; <add> <ide> import io.netty.buffer.ByteBuf; <ide> import io.reactivex.netty.protocol.http.server.HttpServerRequest; <ide> import org.reactivestreams.Publisher; <del>import org.springframework.http.HttpHeaders; <del>import org.springframework.http.HttpMethod; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del>import org.springframework.util.Assert; <del> <ide> import reactor.core.publisher.convert.RxJava1Converter; <ide> import rx.Observable; <ide> <del>import java.net.URI; <del>import java.net.URISyntaxException; <del>import java.nio.ByteBuffer; <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.http.HttpMethod; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.util.Assert; <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> * @author Stephane Maldini <ide> */ <del>public class RxNettyServerHttpRequest implements ServerHttpRequest { <add>public class RxNettyServerHttpRequest implements ReactiveServerHttpRequest { <ide> <ide> private final HttpServerRequest<ByteBuf> request; <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/rxnetty/RxNettyServerHttpResponse.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.http.rxnetty; <ide> <add>import java.nio.ByteBuffer; <add> <ide> import io.netty.handler.codec.http.HttpResponseStatus; <ide> import io.reactivex.netty.protocol.http.server.HttpServerResponse; <ide> import org.reactivestreams.Publisher; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpStatus; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <ide> import org.springframework.util.Assert; <ide> <ide> import reactor.Publishers; <ide> import reactor.core.publisher.convert.RxJava1Converter; <ide> import reactor.io.buffer.Buffer; <ide> import rx.Observable; <ide> <del>import java.nio.ByteBuffer; <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.http.HttpStatus; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <add>import org.springframework.util.Assert; <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> * @author Stephane Maldini <ide> */ <del>public class RxNettyServerHttpResponse implements ServerHttpResponse { <add>public class RxNettyServerHttpResponse implements ReactiveServerHttpResponse { <ide> <ide> private final HttpServerResponse<?> response; <ide> <ide> public Publisher<Void> writeHeaders() { <ide> } <ide> <ide> @Override <del> public Publisher<Void> writeWith(Publisher<ByteBuffer> contentPublisher) { <add> public Publisher<Void> addBody(Publisher<ByteBuffer> contentPublisher) { <ide> applyHeaders(); <ide> Observable<byte[]> contentObservable = RxJava1Converter.from(contentPublisher).map(content -> new Buffer(content).asBytes()); <ide> return RxJava1Converter.from(this.response.writeBytes(contentObservable)); <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/servlet/ServletServerHttpRequest.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.http.servlet; <ide> <ide> import java.net.URI; <ide> import java.nio.charset.Charset; <ide> import java.util.Enumeration; <ide> import java.util.Map; <del> <ide> import javax.servlet.http.HttpServletRequest; <ide> <ide> import org.reactivestreams.Publisher; <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.MediaType; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.LinkedCaseInsensitiveMap; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> */ <del>public class ServletServerHttpRequest implements ServerHttpRequest { <add>public class ServletServerHttpRequest implements ReactiveServerHttpRequest { <ide> <ide> private final HttpServletRequest servletRequest; <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/http/servlet/ServletServerHttpResponse.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.http.servlet; <ide> <ide> import java.nio.ByteBuffer; <ide> import java.util.List; <ide> import java.util.Map; <del> <ide> import javax.servlet.http.HttpServletResponse; <ide> <ide> import org.reactivestreams.Publisher; <ide> import reactor.Publishers; <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpStatus; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> import org.springframework.util.Assert; <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> */ <del>public class ServletServerHttpResponse implements ServerHttpResponse { <add>public class ServletServerHttpResponse implements ReactiveServerHttpResponse { <ide> <ide> private final HttpServletResponse servletResponse; <ide> <ide> public Publisher<Void> writeHeaders() { <ide> } <ide> <ide> @Override <del> public Publisher<Void> writeWith(final Publisher<ByteBuffer> contentPublisher) { <add> public Publisher<Void> addBody(final Publisher<ByteBuffer> contentPublisher) { <ide> applyHeaders(); <ide> return (s -> contentPublisher.subscribe(responseSubscriber)); <ide> } <ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/web/dispatch/handler/SimpleUrlHandlerMappingIntegrationTests.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.reactive.web.dispatch.handler; <ide> <ide> import java.net.URI; <ide> <ide> import org.springframework.http.RequestEntity; <ide> import org.springframework.http.ResponseEntity; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> import org.springframework.reactive.web.dispatch.DispatcherHandler; <ide> import org.springframework.reactive.web.dispatch.SimpleHandlerResultHandler; <ide> import org.springframework.reactive.web.http.AbstractHttpHandlerIntegrationTests; <ide> import org.springframework.reactive.web.http.HttpHandler; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <del>import org.springframework.reactive.web.http.ServerHttpResponse; <ide> import org.springframework.web.client.RestTemplate; <ide> import org.springframework.web.context.support.StaticWebApplicationContext; <ide> <ide> public TestHandlerMapping() { <ide> private static class FooHandler implements HttpHandler { <ide> <ide> @Override <del> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { <del> return response.writeWith(Streams.just(Buffer.wrap("foo").byteBuffer())); <add> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) { <add> return response.addBody(Streams.just(Buffer.wrap("foo").byteBuffer())); <ide> } <ide> } <ide> <ide> private static class BarHandler implements HttpHandler { <ide> <ide> @Override <del> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { <del> return response.writeWith(Streams.just(Buffer.wrap("bar").byteBuffer())); <add> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) { <add> return response.addBody(Streams.just(Buffer.wrap("bar").byteBuffer())); <ide> } <ide> } <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/web/dispatch/method/annotation/RequestMappingHandlerMappingTests.java <ide> import java.net.URISyntaxException; <ide> import java.nio.ByteBuffer; <ide> <del>import static org.junit.Assert.assertEquals; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.reactivestreams.Publisher; <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <del>import org.springframework.reactive.web.http.ServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> import org.springframework.web.context.support.StaticWebApplicationContext; <ide> import org.springframework.web.method.HandlerMethod; <ide> <add>import static org.junit.Assert.assertEquals; <add> <ide> /** <ide> * @author Sebastien Deleuze <ide> */ <ide> public void setup() { <ide> <ide> @Test <ide> public void path() throws NoSuchMethodException { <del> ServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, "boo"); <add> ReactiveServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, "boo"); <ide> HandlerMethod handler = (HandlerMethod) this.mapping.getHandler(request); <ide> assertEquals(TestController.class.getMethod("boo"), handler.getMethod()); <ide> } <ide> <ide> @Test <ide> public void method() throws NoSuchMethodException { <del> ServerHttpRequest request = new MockServerHttpRequest(HttpMethod.POST, "foo"); <add> ReactiveServerHttpRequest request = new MockServerHttpRequest(HttpMethod.POST, "foo"); <ide> HandlerMethod handler = (HandlerMethod) this.mapping.getHandler(request); <ide> assertEquals(TestController.class.getMethod("postFoo"), handler.getMethod()); <ide> <ide> public String boo() { <ide> <ide> } <ide> <del> private static class MockServerHttpRequest implements ServerHttpRequest{ <add> private static class MockServerHttpRequest implements ReactiveServerHttpRequest{ <ide> <ide> private HttpMethod method; <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/web/http/EchoHandler.java <ide> <ide> import org.reactivestreams.Publisher; <ide> <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <add> <ide> /** <ide> * @author Arjen Poutsma <ide> */ <ide> public class EchoHandler implements HttpHandler { <ide> <ide> @Override <del> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { <del> return response.writeWith(request.getBody()); <add> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) { <add> return response.addBody(request.getBody()); <ide> } <ide> } <ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/web/http/RandomHandler.java <ide> import reactor.io.buffer.Buffer; <ide> import reactor.rx.Streams; <ide> <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <add> <ide> import static org.junit.Assert.assertEquals; <ide> <ide> /** <ide> public class RandomHandler implements HttpHandler { <ide> private final Random rnd = new Random(); <ide> <ide> @Override <del> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { <add> public Publisher<Void> handle(ReactiveServerHttpRequest request, ReactiveServerHttpResponse response) { <ide> <ide> request.getBody().subscribe(new Subscriber<ByteBuffer>() { <ide> private Subscription s; <ide> public void onComplete() { <ide> }); <ide> <ide> response.getHeaders().setContentLength(RESPONSE_SIZE); <del> return response.writeWith(Streams.just(ByteBuffer.wrap(randomBytes()))); <add> return response.addBody(Streams.just(ByteBuffer.wrap(randomBytes()))); <ide> } <ide> <ide> private byte[] randomBytes() { <ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/web/http/XmlHandler.java <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.reactivestreams.Publisher; <add>import reactor.io.buffer.Buffer; <add>import reactor.rx.Streams; <ide> <ide> import org.springframework.http.MediaType; <add>import org.springframework.http.server.ReactiveServerHttpRequest; <add>import org.springframework.http.server.ReactiveServerHttpResponse; <ide> import org.springframework.reactive.io.BufferOutputStream; <ide> import org.springframework.reactive.io.ByteBufferPublisherInputStream; <ide> <ide> import static org.junit.Assert.fail; <del>import reactor.io.buffer.Buffer; <del>import reactor.rx.Streams; <ide> <ide> /** <ide> * @author Arjen Poutsma <ide> public class XmlHandler implements HttpHandler { <ide> private static final Log logger = LogFactory.getLog(XmlHandler.class); <ide> <ide> @Override <del> public Publisher<Void> handle(ServerHttpRequest request, <del> ServerHttpResponse response) { <add> public Publisher<Void> handle(ReactiveServerHttpRequest request, <add> ReactiveServerHttpResponse response) { <ide> try { <ide> JAXBContext jaxbContext = JAXBContext.newInstance(XmlHandlerIntegrationTests.Person.class); <ide> Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); <ide> public Publisher<Void> handle(ServerHttpRequest request, <ide> bos.close(); <ide> buffer.flip(); <ide> <del> return response.writeWith(Streams.just(buffer.byteBuffer())); <add> return response.addBody(Streams.just(buffer.byteBuffer())); <ide> } <ide> catch (Exception ex) { <ide> logger.error(ex, ex);
32
Text
Text
add a note on actioncontroller guide about 404
43800057fc1cabe626f00d30dc302e2dde56fdfd
<ide><path>guides/source/action_controller_overview.md <ide> Rails default exception handling displays a "500 Server Error" message for all e <ide> <ide> ### The Default 500 and 404 Templates <ide> <del>By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and style, but remember that they are static HTML; i.e. you can't use ERB, SCSS, CoffeeScript, or layouts for them. <add>By default a production application will render either a 404 or a 500 error message, in the development environment all unhandled exceptions are raised. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and style, but remember that they are static HTML; i.e. you can't use ERB, SCSS, CoffeeScript, or layouts for them. <ide> <ide> ### `rescue_from` <ide> <ide> end <ide> <ide> WARNING: You shouldn't do `rescue_from Exception` or `rescue_from StandardError` unless you have a particular reason as it will cause serious side-effects (e.g. you won't be able to see exception details and tracebacks during development). <ide> <del>NOTE: Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized and the action gets executed. <add>NOTE: When running in the production environment, all <add>`ActiveRecord::RecordNotFound` errors render the 404 error page. Unless you need <add>a custom behavior you don't need to handle this. <add> <add>NOTE: Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized and the action gets executed. <ide> <ide> Force HTTPS protocol <ide> --------------------
1
Mixed
Javascript
replace ipv6only option with `'udp6-only'` type
aafdc2fcad51ec0f4ecd99424d6d2055d7878fab
<ide><path>doc/api/quic.md <ide> added: REPLACEME <ide> IPv6 address or a host name. If a host name is given, it will be resolved <ide> to an IP address. <ide> * `port` {number} The local port to bind to. <del> * `type` {string} Either `'udp4'` or `'upd6'` to use either IPv4 or IPv6, <del> respectively. **Default**: `'udp4'`. <del> * `ipv6Only` {boolean} If `type` is `'udp6'`, then setting `ipv6Only` to <del> `true` will disable dual-stack support on the UDP binding -- that is, <del> binding to address `'::'` will not make `'0.0.0.0'` be bound. The option <del> is ignored if `type` is `'udp4'`. **Default**: `false`. <add> * `type` {string} Can be one of `'udp4'`, `'upd6'`, or `'udp6-only'` to <add> use IPv4, IPv6, or IPv6 with dual-stack mode disabled. <add> **Default**: `'udp4'`. <ide> * `lookup` {Function} A custom DNS lookup function. Default `dns.lookup()`. <ide> * `maxConnections` {number} The maximum number of total active inbound <ide> connections. <ide> added: REPLACEME <ide> IPv6 address or a host name. If a host name is given, it will be resolved <ide> to an IP address. <ide> * `port` {number} The local port to bind to. <del> * `type` {string} Either `'udp4'` or `'upd6'` to use either IPv4 or IPv6, <del> respectively. **Default**: `'udp4'`. <del> * `ipv6Only` {boolean} If `type` is `'udp6'`, then setting `ipv6Only` to <del> `true` will disable dual-stack support on the UDP binding -- that is, <del> binding to address `'::'` will not make `'0.0.0.0'` be bound. The option <del> is ignored if `type` is `'udp4'`. **Default**: `false`. <add> * `type` {string} Can be one of `'udp4'`, `'upd6'`, or `'udp6-only'` to <add> use IPv4, IPv6, or IPv6 with dual-stack mode disabled. <add> **Default**: `'udp4'`. <ide> * Returns: {QuicEndpoint} <ide> <ide> Creates and adds a new `QuicEndpoint` to the `QuicSocket` instance. <ide> added: REPLACEME <ide> `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see <ide> [OpenSSL Options][] for more information. <ide> * `idleTimeout` {number} <del> * `ipv6Only` {boolean} If `type` is `'udp6'`, then setting `ipv6Only` to <del> `true` will disable dual-stack support on the UDP binding -- that is, <del> binding to address `'::'` will not make `'0.0.0.0'` be bound. The option <del> is ignored if `type` is `'udp4'`. **Default**: `false`. <ide> * `key` {string|string[]|Buffer|Buffer[]|Object[]} Private keys in PEM format. <ide> PEM allows the option of private keys being encrypted. Encrypted keys will <ide> be decrypted with `options.passphrase`. Multiple keys using different <ide><path>lib/internal/quic/core.js <ide> class QuicEndpoint { <ide> const state = this[kInternalState]; <ide> state.socket = socket; <ide> state.address = address || (type === AF_INET6 ? '::' : '0.0.0.0'); <del> state.ipv6Only = !!ipv6Only; <add> state.ipv6Only = ipv6Only; <ide> state.lookup = lookup || (type === AF_INET6 ? lookup6 : lookup4); <ide> state.port = port; <del> state.reuseAddr = !!reuseAddr; <add> state.reuseAddr = reuseAddr; <ide> state.type = type; <ide> state.udpSocket = dgram.createSocket(type === AF_INET6 ? 'udp6' : 'udp4'); <ide> <ide> class QuicEndpoint { <ide> state.socket[kEndpointBound](this); <ide> } <ide> <del> [kDestroy](error) { <add> destroy(error) { <add> if (this.destroyed) <add> return; <add> <add> const state = this[kInternalState]; <add> state.state = kSocketDestroyed; <add> <ide> const handle = this[kHandle]; <del> if (handle !== undefined) { <del> this[kHandle] = undefined; <del> handle[owner_symbol] = undefined; <del> handle.ondone = () => { <del> const state = this[kInternalState]; <del> state.udpSocket.close((err) => { <del> if (err) error = err; <del> state.socket[kEndpointClose](this, error); <del> }); <del> }; <del> handle.waitForPendingCallbacks(); <del> } <add> if (handle === undefined) <add> return; <add> <add> this[kHandle] = undefined; <add> handle[owner_symbol] = undefined; <add> handle.ondone = () => { <add> state.udpSocket.close((err) => { <add> if (err) error = err; <add> state.socket[kEndpointClose](this, error); <add> }); <add> }; <add> handle.waitForPendingCallbacks(); <ide> } <ide> <ide> // If the QuicEndpoint is bound, returns an object detailing <ide> class QuicEndpoint { <ide> state.udpSocket.unref(); <ide> return this; <ide> } <del> <del> destroy(error) { <del> const state = this[kInternalState]; <del> if (this.destroyed) <del> return; <del> state.state = kSocketDestroyed; <del> this[kDestroy](error); <del> } <ide> } <ide> <ide> // QuicSocket wraps a UDP socket plus the associated TLS context and QUIC <ide> class QuicSocket extends EventEmitter { <ide> port, <ide> type = 'udp4', <ide> } = { ...preferredAddress }; <del> const typeVal = getSocketType(type); <add> const [ typeVal ] = getSocketType(type); <ide> // If preferred address is set, we need to perform a lookup on it <ide> // to get the IP address. Only after that lookup completes can we <ide> // continue with the listen operation, passing in the resolved <ide> class QuicClientSession extends QuicSession { <ide> autoStart: true, <ide> dcid: undefined, <ide> handshakeStarted: false, <del> ipv6Only: undefined, <ide> minDHSize: undefined, <ide> port: undefined, <ide> ready: 0, <ide> class QuicClientSession extends QuicSession { <ide> autoStart, <ide> alpn, <ide> dcid, <del> ipv6Only, <ide> minDHSize, <ide> port, <ide> preferredAddressPolicy, <ide> class QuicClientSession extends QuicSession { <ide> state.autoStart = autoStart; <ide> state.handshakeStarted = autoStart; <ide> state.dcid = dcid; <del> state.ipv6Only = ipv6Only; <ide> state.minDHSize = minDHSize; <ide> state.port = port || 0; <ide> state.preferredAddressPolicy = preferredAddressPolicy; <ide><path>lib/internal/quic/util.js <ide> function validateNumber(value, name, <ide> <ide> function getSocketType(type = 'udp4') { <ide> switch (type) { <del> case 'udp4': return AF_INET; <del> case 'udp6': return AF_INET6; <add> case 'udp4': return [AF_INET, false]; <add> case 'udp6': return [AF_INET6, false]; <add> case 'udp6-only': return [AF_INET6, true]; <ide> } <ide> throw new ERR_INVALID_ARG_VALUE('options.type', type); <ide> } <ide> function validateQuicClientSessionOptions(options = {}) { <ide> address = 'localhost', <ide> alpn = '', <ide> dcid: dcid_value, <del> ipv6Only = false, <ide> minDHSize = 1024, <ide> port = 0, <ide> preferredAddressPolicy = 'ignore', <ide> function validateQuicClientSessionOptions(options = {}) { <ide> if (preferredAddressPolicy !== undefined) <ide> validateString(preferredAddressPolicy, 'options.preferredAddressPolicy'); <ide> <del> validateBoolean(ipv6Only, 'options.ipv6Only'); <ide> validateBoolean(requestOCSP, 'options.requestOCSP'); <ide> validateBoolean(verifyHostnameIdentity, 'options.verifyHostnameIdentity'); <ide> validateBoolean(qlog, 'options.qlog'); <ide> function validateQuicClientSessionOptions(options = {}) { <ide> address, <ide> alpn, <ide> dcid, <del> ipv6Only, <ide> minDHSize, <ide> port, <ide> preferredAddressPolicy: <ide> function validateQuicEndpointOptions(options = {}, name = 'options') { <ide> throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); <ide> const { <ide> address, <del> ipv6Only = false, <ide> lookup, <ide> port = 0, <ide> reuseAddr = false, <ide> function validateQuicEndpointOptions(options = {}, name = 'options') { <ide> validatePort(port, 'options.port'); <ide> validateString(type, 'options.type'); <ide> validateLookup(lookup); <del> validateBoolean(ipv6Only, 'options.ipv6Only'); <ide> validateBoolean(reuseAddr, 'options.reuseAddr'); <ide> validateBoolean(preferred, 'options.preferred'); <add> const [typeVal, ipv6Only] = getSocketType(type); <ide> return { <del> address, <add> type: typeVal, <ide> ipv6Only, <add> address, <ide> lookup, <ide> port, <ide> preferred, <ide> reuseAddr, <del> type: getSocketType(type), <ide> }; <ide> } <ide> <ide> function validateQuicSocketOptions(options = {}) { <ide> retryTokenTimeout = DEFAULT_RETRYTOKEN_EXPIRATION, <ide> server = {}, <ide> statelessResetSecret, <del> type = endpoint.type || 'udp4', <ide> validateAddressLRU = false, <ide> validateAddress = false, <ide> } = options; <ide> <del> validateQuicEndpointOptions(endpoint, 'options.endpoint'); <add> const { type } = validateQuicEndpointOptions(endpoint, 'options.endpoint'); <ide> validateObject(client, 'options.client'); <ide> validateObject(server, 'options.server'); <del> validateString(type, 'options.type'); <ide> validateLookup(lookup); <ide> validateBoolean(validateAddress, 'options.validateAddress'); <ide> validateBoolean(validateAddressLRU, 'options.validateAddressLRU'); <ide> function validateQuicSocketOptions(options = {}) { <ide> maxStatelessResetsPerHost, <ide> retryTokenTimeout, <ide> server, <del> type: getSocketType(type), <add> type, <ide> validateAddress: validateAddress || validateAddressLRU, <ide> validateAddressLRU, <ide> qlog, <ide> function validateQuicSocketConnectOptions(options = {}) { <ide> } = options; <ide> if (address !== undefined) <ide> validateString(address, 'options.address'); <del> return { <del> type: getSocketType(type), <del> address, <del> }; <add> const [typeVal] = getSocketType(type); <add> return { type: typeVal, address }; <ide> } <ide> <ide> function validateCreateSecureContextOptions(options = {}) { <ide><path>test/parallel/test-quic-errors-quicsocket-connect.js <ide> const client = createQuicSocket(); <ide> }); <ide> }); <ide> <del>['a', 1n, 1, [], {}].forEach((ipv6Only) => { <del> assert.throws(() => client.connect({ ipv6Only }), { <del> code: 'ERR_INVALID_ARG_TYPE' <del> }); <del>}); <del> <ide> [1, 1n, false, [], {}].forEach((preferredAddressPolicy) => { <ide> assert.throws(() => client.connect({ preferredAddressPolicy }), { <ide> code: 'ERR_INVALID_ARG_TYPE' <ide> assert.throws(() => client.connect(), { <ide> // Client QuicSession Related: <ide> // <ide> // [x] idleTimeout - must be a number greater than zero <del>// [x] ipv6Only - must be a boolean <ide> // [x] activeConnectionIdLimit - must be a number between 2 and 8 <ide> // [x] maxAckDelay - must be a number greater than zero <ide> // [x] maxData - must be a number greater than zero <ide><path>test/parallel/test-quic-errors-quicsocket-create.js <ide> const { createQuicSocket } = require('net'); <ide> }); <ide> }); <ide> <del>// Test invalid QuicSocket ipv6Only argument option <del>[1, NaN, 1n, null, {}, []].forEach((ipv6Only) => { <del> assert.throws(() => createQuicSocket({ endpoint: { ipv6Only } }), { <del> code: 'ERR_INVALID_ARG_TYPE' <del> }); <del>}); <del> <ide> // Test invalid QuicSocket reuseAddr argument option <ide> [1, NaN, 1n, null, {}, []].forEach((reuseAddr) => { <ide> assert.throws(() => createQuicSocket({ endpoint: { reuseAddr } }), { <ide><path>test/parallel/test-quic-ipv6only.js <ide> const { once } = require('events'); <ide> <ide> const kALPN = 'zzz'; <ide> <del>// Setting `type` to `udp4` while setting `ipv6Only` to `true` is possible. <del>// The ipv6Only setting will be ignored. <del>async function ipv4() { <del> const server = createQuicSocket({ <del> endpoint: { <del> type: 'udp4', <del> ipv6Only: true <del> } <del> }); <del> server.on('error', common.mustNotCall()); <del> server.listen({ key, cert, ca, alpn: kALPN }); <del> await once(server, 'ready'); <del> server.close(); <del>} <del> <ide> // Connecting to ipv6 server using "127.0.0.1" should work when <ide> // `ipv6Only` is set to `false`. <ide> async function ipv6() { <del> const server = createQuicSocket({ <del> endpoint: { <del> type: 'udp6', <del> ipv6Only: false <del> } }); <add> const server = createQuicSocket({ endpoint: { type: 'udp6' } }); <ide> const client = createQuicSocket({ client: { key, cert, ca, alpn: kALPN } }); <ide> <ide> server.listen({ key, cert, ca, alpn: kALPN }); <ide> async function ipv6() { <ide> <ide> const session = client.connect({ <ide> address: common.localhostIPv4, <del> port: server.endpoints[0].address.port, <del> ipv6Only: true, <add> port: server.endpoints[0].address.port <ide> }); <ide> <ide> await once(session, 'secure'); <ide> async function ipv6() { <ide> // When the `ipv6Only` set to `true`, a client cann't connect to it <ide> // through "127.0.0.1". <ide> async function ipv6Only() { <del> const server = createQuicSocket({ <del> endpoint: { <del> type: 'udp6', <del> ipv6Only: true <del> } }); <add> const server = createQuicSocket({ endpoint: { type: 'udp6-only' } }); <ide> const client = createQuicSocket({ client: { key, cert, ca, alpn: kALPN } }); <ide> <ide> server.listen({ key, cert, ca, alpn: kALPN }); <ide> async function ipv6Only() { <ide> address: common.localhostIPv4, <ide> port: server.endpoints[0].address.port, <ide> idleTimeout: common.platformTimeout(1), <del> ipv6Only: true, <ide> }); <ide> <ide> session.on('secure', common.mustNotCall()); <ide> async function mismatch() { <ide> ]); <ide> } <ide> <del>ipv4() <del> .then(ipv6) <add>ipv6() <ide> .then(ipv6Only) <ide> .then(mismatch) <ide> .then(common.mustCall());
6
Python
Python
add tests for transform_fieldname methods
dc650f77b5f377bbfab3da66455feb57b195a1da
<ide><path>rest_framework/tests/test_serializer.py <ide> def test_serializer_supports_slug_many_relationships(self): <ide> serializer = SimpleSlugSourceModelSerializer(data={'text': 'foo', 'targets': [1, 2]}) <ide> self.assertTrue(serializer.is_valid()) <ide> self.assertEqual(serializer.data, {'text': 'foo', 'targets': [1, 2]}) <add> <add> <add>class TransformMethodsSerializer(serializers.Serializer): <add> a = serializers.CharField() <add> b_renamed = serializers.CharField(source='b') <add> <add> def transform_a(self, obj, value): <add> return value.lower() <add> <add> def transform_b_renamed(self, obj, value): <add> if value is not None: <add> return 'and ' + value <add> <add> <add>class TestSerializerTransformMethods(TestCase): <add> def setUp(self): <add> self.s = TransformMethodsSerializer() <add> <add> def test_transform_methods(self): <add> self.assertEqual( <add> self.s.to_native({'a': 'GREEN EGGS', 'b': 'HAM'}), <add> { <add> 'a': 'green eggs', <add> 'b_renamed': 'and HAM', <add> } <add> ) <add> <add> def test_missing_fields(self): <add> self.assertEqual( <add> self.s.to_native({'a': 'GREEN EGGS'}), <add> { <add> 'a': 'green eggs', <add> 'b_renamed': None, <add> } <add> )
1
Text
Text
add note about adding new images
262983f88ebeb4a117e1ddce14b939e1e11fa201
<ide><path>docs/Images.md <ide> And `button.js` code contains <ide> <ide> Packager will bundle and serve the image corresponding to device's screen density, e.g. on iPhone 5s `check@2x.png` will be used, on Nexus 5 – `check@3x.png`. If there is no image matching the screen density, the closest best option will be selected. <ide> <add>On Windows, you might need to restart the packager if you add new images to your project. <add> <ide> Here are some benefits that you get: <ide> <ide> 1. Same system on iOS and Android.
1