content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Javascript | Javascript | add proptype for injectjavascript | 13b4c2d77b855a1e20b153700bdfa5106bfcc346 | <ide><path>Libraries/Components/WebView/WebView.android.js
<ide> class WebView extends React.Component {
<ide> * @platform android
<ide> */
<ide> allowUniversalAccessFromFileURLs: PropTypes.bool,
<add>
<add> /**
<add> * Function that accepts a string that will be passed to the WebView and
<add> * executed immediately as JavaScript.
<add> */
<add> injectJavaScript: PropTypes.func,
<ide> };
<ide>
<ide> static defaultProps = {
<ide><path>Libraries/Components/WebView/WebView.ios.js
<ide> class WebView extends React.Component {
<ide> * to tap them before they start playing. The default value is `true`.
<ide> */
<ide> mediaPlaybackRequiresUserAction: PropTypes.bool,
<add>
<add> /**
<add> * Function that accepts a string that will be passed to the WebView and
<add> * executed immediately as JavaScript.
<add> */
<add> injectJavaScript: PropTypes.func,
<ide> };
<ide>
<ide> state = { | 2 |
Go | Go | remove "root" and "" special cases in libcontainer | d98069030dc842741fdff16e1818f2a34ec0167f | <ide><path>pkg/libcontainer/nsinit/init.go
<ide> func (ns *linuxNs) Init(container *libcontainer.Container, uncleanRootfs, consol
<ide> }
<ide>
<ide> func setupUser(container *libcontainer.Container) error {
<del> switch container.User {
<del> case "root", "":
<del> if err := system.Setgroups(nil); err != nil {
<del> return err
<del> }
<del> if err := system.Setresgid(0, 0, 0); err != nil {
<del> return err
<del> }
<del> if err := system.Setresuid(0, 0, 0); err != nil {
<del> return err
<del> }
<del> default:
<del> uid, gid, suppGids, err := user.GetUserGroupSupplementary(container.User, syscall.Getuid(), syscall.Getgid())
<del> if err != nil {
<del> return err
<del> }
<del> if err := system.Setgroups(suppGids); err != nil {
<del> return err
<del> }
<del> if err := system.Setgid(gid); err != nil {
<del> return err
<del> }
<del> if err := system.Setuid(uid); err != nil {
<del> return err
<del> }
<add> uid, gid, suppGids, err := user.GetUserGroupSupplementary(container.User, syscall.Getuid(), syscall.Getgid())
<add> if err != nil {
<add> return fmt.Errorf("GetUserGroupSupplementary %s", err)
<add> }
<add> if err := system.Setgroups(suppGids); err != nil {
<add> return fmt.Errorf("setgroups %s", err)
<add> }
<add> if err := system.Setgid(gid); err != nil {
<add> return fmt.Errorf("setgid %s", err)
<add> }
<add> if err := system.Setuid(uid); err != nil {
<add> return fmt.Errorf("setuid %s", err)
<ide> }
<ide> return nil
<ide> } | 1 |
Ruby | Ruby | return results while parsing | 8d100a0508f201417784553b4738262ccad448cb | <ide><path>Library/Homebrew/cmd/search.rb
<ide> def search
<ide> end
<ide>
<ide> if search_results.empty? and not blacklisted? query
<del> pulls = GitHub.find_pull_requests rx
<del> unless pulls.empty?
<del> puts "Open pull requests matching \"#{query}\":", *pulls.map { |p| " #{p}" }
<del> end
<add> puts "No formula found for \"#{query}\". Searching open pull requests..."
<add> GitHub.find_pull_requests(rx) { |pull| puts pull }
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/utils.rb
<ide> def find_pull_requests rx
<ide> require 'open-uri'
<ide> require 'vendor/multi_json'
<ide>
<del> pulls = []
<ide> query = rx.source.delete '.*'
<ide> uri = URI.parse("http://github.com/api/v2/json/issues/search/mxcl/homebrew/open/#{query}")
<ide>
<ide> open uri do |f|
<ide> MultiJson.decode(f.read)["issues"].each do |pull|
<del> pulls << pull['pull_request_url'] if rx.match pull['title'] and pull["pull_request_url"]
<add> yield pull['pull_request_url'] if rx.match pull['title'] and pull["pull_request_url"]
<ide> end
<ide> end
<del> pulls
<ide> rescue
<del> []
<add> nil
<ide> end
<ide> end | 2 |
Text | Text | update urls of plugins and loaders | 5201377b46f710c5759accfac622ef4c6055392e | <ide><path>README.md
<ide> within webpack itself use this plugin interface. This makes webpack very
<ide> |[extract-text-webpack-plugin][extract]|![extract-npm]|![extract-size]|Extract text from a bundle, or bundles, into a separate file|
<ide>
<ide> [common-npm]: https://img.shields.io/npm/v/webpack.svg
<del>[extract]: https://github.com/webpack/extract-text-webpack-plugin
<add>[extract]: https://github.com/webpack-contrib/extract-text-webpack-plugin
<ide> [extract-npm]: https://img.shields.io/npm/v/extract-text-webpack-plugin.svg
<ide> [extract-size]: https://packagephobia.now.sh/badge?p=extract-text-webpack-plugin
<ide> [mini-css]: https://github.com/webpack-contrib/mini-css-extract-plugin
<ide> [mini-css-npm]: https://img.shields.io/npm/v/mini-css-extract-plugin.svg
<ide> [mini-css-size]: https://packagephobia.now.sh/badge?p=mini-css-extract-plugin
<del>[component]: https://github.com/webpack/component-webpack-plugin
<add>[component]: https://github.com/webpack-contrib/component-webpack-plugin
<ide> [component-npm]: https://img.shields.io/npm/v/component-webpack-plugin.svg
<ide> [component-size]: https://packagephobia.now.sh/badge?p=component-webpack-plugin
<del>[compression]: https://github.com/webpack/compression-webpack-plugin
<add>[compression]: https://github.com/webpack-contrib/compression-webpack-plugin
<ide> [compression-npm]: https://img.shields.io/npm/v/compression-webpack-plugin.svg
<ide> [compression-size]: https://packagephobia.now.sh/badge?p=compression-webpack-plugin
<del>[i18n]: https://github.com/webpack/i18n-webpack-plugin
<add>[i18n]: https://github.com/webpack-contrib/i18n-webpack-plugin
<ide> [i18n-npm]: https://img.shields.io/npm/v/i18n-webpack-plugin.svg
<ide> [i18n-size]: https://packagephobia.now.sh/badge?p=i18n-webpack-plugin
<del>[html-plugin]: https://github.com/ampedandwired/html-webpack-plugin
<add>[html-plugin]: https://github.com/jantimon/html-webpack-plugin
<ide> [html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg
<ide> [html-plugin-size]: https://packagephobia.now.sh/badge?p=html-webpack-plugin
<ide>
<ide> or are automatically applied via regex from your webpack configuration.
<ide> |[file-loader][file]|![file-npm]|![file-size]|Emits the file into the output folder and returns the (relative) url|
<ide>
<ide>
<del>[raw]: https://github.com/webpack/raw-loader
<add>[raw]: https://github.com/webpack-contrib/raw-loader
<ide> [raw-npm]: https://img.shields.io/npm/v/raw-loader.svg
<ide> [raw-size]: https://packagephobia.now.sh/badge?p=raw-loader
<del>[val]: https://github.com/webpack/val-loader
<add>[val]: https://github.com/webpack-contrib/val-loader
<ide> [val-npm]: https://img.shields.io/npm/v/val-loader.svg
<ide> [val-size]: https://packagephobia.now.sh/badge?p=val-loader
<del>[url]: https://github.com/webpack/url-loader
<add>[url]: https://github.com/webpack-contrib/url-loader
<ide> [url-npm]: https://img.shields.io/npm/v/url-loader.svg
<ide> [url-size]: https://packagephobia.now.sh/badge?p=url-loader
<del>[file]: https://github.com/webpack/file-loader
<add>[file]: https://github.com/webpack-contrib/file-loader
<ide> [file-npm]: https://img.shields.io/npm/v/file-loader.svg
<ide> [file-size]: https://packagephobia.now.sh/badge?p=file-loader
<ide>
<ide> #### JSON
<ide>
<ide> |Name|Status|Install Size|Description|
<ide> |:--:|:----:|:----------:|:----------|
<del>|<a href="https://github.com/webpack/json-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/json.svg"></a>|![json-npm]|![json-size]|Loads a JSON file (included by default)|
<del>|<a href="https://github.com/webpack/json5-loader"><img width="48" height="10.656" src="https://cdn.rawgit.com/json5/json5-logo/master/json5-logo.svg"></a>|![json5-npm]|![json5-size]|Loads and transpiles a JSON 5 file|
<add>|<a href="https://github.com/webpack-contrib/json-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/json.svg"></a>|![json-npm]|![json-size]|Loads a JSON file (included by default)|
<add>|<a href="https://github.com/webpack-contrib/json5-loader"><img width="48" height="10.656" src="https://cdn.rawgit.com/json5/json5-logo/master/json5-logo.svg"></a>|![json5-npm]|![json5-size]|Loads and transpiles a JSON 5 file|
<ide> |<a href="https://github.com/awnist/cson-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a>|![cson-npm]|![cson-size]|Loads and transpiles a CSON file|
<ide>
<ide>
<ide> or are automatically applied via regex from your webpack configuration.
<ide>
<ide> |Name|Status|Install Size|Description|
<ide> |:--:|:----:|:----------:|:----------|
<del>|<a href="https://github.com/webpack/script-loader">`<script>`</a>|![script-npm]|![script-size]|Executes a JavaScript file once in global context (like in script tag), `require()`s are not parsed|
<add>|<a href="https://github.com/webpack-contrib/script-loader">`<script>`</a>|![script-npm]|![script-size]|Executes a JavaScript file once in global context (like in script tag), `require()`s are not parsed|
<ide> |<a href="https://github.com/babel/babel-loader"><img width="48" height="48" title="babel-loader" src="https://worldvectorlogo.com/logos/babel-10.svg"></a>|![babel-npm]|![babel-size]|Loads ES2015+ code and transpiles to ES5 using <a href="https://github.com/babel/babel">Babel</a>|
<ide> |<a href="https://github.com/jupl/traceur-loader"><img width="48" height="48" src="https://google.github.com/traceur-compiler/logo/tc.svg"></a>|![traceur-npm]|![traceur-size]|Loads ES2015+ code and transpiles to ES5 using [Traceur](https://github.com/google/traceur-compiler)|
<ide> |<a href="https://github.com/TypeStrong/ts-loader"><img width="48" height="48" src="https://cdn.rawgit.com/Microsoft/TypeScript/master/doc/logo.svg"></a>|![type-npm]|![type-size]|Loads TypeScript like JavaScript|
<ide> |[`awesome-typescript-loader`](https://github.com/s-panferov/awesome-typescript-loader)|![awesome-typescript-npm]|![awesome-typescript-size]|Awesome TypeScript loader for webpack|
<del>|<a href="https://github.com/webpack/coffee-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a>|![coffee-npm]|![coffee-size]|Loads CoffeeScript like JavaScript|
<add>|<a href="https://github.com/webpack-contrib/coffee-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a>|![coffee-npm]|![coffee-size]|Loads CoffeeScript like JavaScript|
<ide>
<ide>
<ide> [script-npm]: https://img.shields.io/npm/v/script-loader.svg
<ide> or are automatically applied via regex from your webpack configuration.
<ide>
<ide> |Name|Status|Install Size|Description|
<ide> |:--:|:----:|:----------:|:----------|
<del>|<a href="https://github.com/webpack/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5.svg"></a>|![html-npm]|![html-size]|Exports HTML as string, requires references to static resources|
<add>|<a href="https://github.com/webpack-contrib/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5.svg"></a>|![html-npm]|![html-size]|Exports HTML as string, requires references to static resources|
<ide> |<a href="https://github.com/pugjs/pug-loader"><img width="48" height="48" src="https://cdn.rawgit.com/pugjs/pug-logo/master/SVG/pug-final-logo-_-colour-128.svg"></a>|![pug-npm]|![pug-size]|Loads Pug templates and returns a function|
<del>|<a href="https://github.com/webpack/jade-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/jade-3.svg"></a>|![jade-npm]|![jade-size]|Loads Jade templates and returns a function|
<ide> |<a href="https://github.com/peerigon/markdown-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/markdown.svg"></a>|![md-npm]|![md-size]|Compiles Markdown to HTML|
<ide> |<a href="https://github.com/posthtml/posthtml-loader"><img width="48" height="48" src="http://posthtml.github.io/posthtml/logo.svg"></a>|![posthtml-npm]|![posthtml-size]|Loads and transforms a HTML file using [PostHTML](https://github.com/posthtml/posthtml)|
<del>|<a href="https://github.com/altano/handlebars-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/handlebars-1.svg"></a>|![hbs-npm]|![hbs-size]| Compiles Handlebars to HTML|
<add>|<a href="https://github.com/pcardune/handlebars-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/handlebars-1.svg"></a>|![hbs-npm]|![hbs-size]| Compiles Handlebars to HTML|
<ide>
<ide>
<ide> [html-npm]: https://img.shields.io/npm/v/html-loader.svg
<ide> or are automatically applied via regex from your webpack configuration.
<ide>
<ide> |Name|Status|Install Size|Description|
<ide> |:--:|:----:|:----------:|:----------|
<del>|<a href="https://github.com/webpack/style-loader">`<style>`</a>|![style-npm]|![style-size]|Add exports of a module as style to DOM|
<del>|<a href="https://github.com/webpack/css-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/css-3.svg"></a>|![css-npm]|![css-size]|Loads CSS file with resolved imports and returns CSS code|
<del>|<a href="https://github.com/webpack/less-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/less-63.svg"></a>|![less-npm]|![less-size]|Loads and compiles a LESS file|
<del>|<a href="https://github.com/jtangelder/sass-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/sass-1.svg"></a>|![sass-npm]|![sass-size]|Loads and compiles a Sass/SCSS file|
<add>|<a href="https://github.com/webpack-contrib/style-loader">`<style>`</a>|![style-npm]|![style-size]|Add exports of a module as style to DOM|
<add>|<a href="https://github.com/webpack-contrib/css-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/css-3.svg"></a>|![css-npm]|![css-size]|Loads CSS file with resolved imports and returns CSS code|
<add>|<a href="https://github.com/webpack-contrib/less-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/less-63.svg"></a>|![less-npm]|![less-size]|Loads and compiles a LESS file|
<add>|<a href="https://github.com/webpack-contrib/sass-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/sass-1.svg"></a>|![sass-npm]|![sass-size]|Loads and compiles a Sass/SCSS file|
<ide> |<a href="https://github.com/shama/stylus-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/stylus.svg"></a>|![stylus-npm]|![stylus-size]|Loads and compiles a Stylus file|
<ide> |<a href="https://github.com/postcss/postcss-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/postcss.svg"></a>|![postcss-npm]|![postcss-size]|Loads and transforms a CSS/SSS file using [PostCSS](http://postcss.org)|
<ide>
<ide> or are automatically applied via regex from your webpack configuration.
<ide>
<ide> |Name|Status|Install Size|Description|
<ide> |:--:|:----:|:----------:|:----------|
<del>|<a href="https://github.com/webpack/mocha-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/mocha.svg"></a>|![mocha-npm]|![mocha-size]|Tests with mocha (Browser/NodeJS)|
<del>|<a href="https://github.com/MoOx/eslint-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/eslint.svg"></a>|![eslint-npm]|![eslint-size]|PreLoader for linting code using ESLint|
<add>|<a href="https://github.com/webpack-contrib/mocha-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/mocha.svg"></a>|![mocha-npm]|![mocha-size]|Tests with mocha (Browser/NodeJS)|
<add>|<a href="https://github.com/webpack-contrib/eslint-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/eslint.svg"></a>|![eslint-npm]|![eslint-size]|PreLoader for linting code using ESLint|
<ide> |<a href="https://github.com/webpack-contrib/jshint-loader"><img width="48" height="20.64" src="http://jshint.com/res/jshint-dark.png"></a>|![jshint-npm]|![jshint-size]|PreLoader for linting code using JSHint|
<ide>
<ide> [mocha-npm]: https://img.shields.io/npm/v/mocha-loader.svg
<ide> or are automatically applied via regex from your webpack configuration.
<ide> |<a href="https://github.com/vuejs/vue-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/vue-9.svg"></a>|![vue-npm]|![vue-size]|Loads and compiles Vue Components|
<ide> |<a href="https://github.com/webpack-contrib/polymer-webpack-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/polymer.svg"></a>|![polymer-npm]|![polymer-size]|Process HTML & CSS with preprocessor of choice and `require()` Web Components like first-class modules|
<ide> |<a href="https://github.com/TheLarkInn/angular2-template-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/angular-icon-1.svg"></a>|![angular-npm]|![angular-size]| Loads and compiles Angular 2 Components|
<del>|<a href="https://github.com/riot/tag-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/riot.svg"></a>|![riot-npm]|![riot-size]| Riot official webpack loader|
<add>|<a href="https://github.com/riot/webpack-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/riot.svg"></a>|![riot-npm]|![riot-size]| Riot official webpack loader|
<ide>
<ide>
<ide> | 1 |
PHP | PHP | add custom errors key to validation test | d0b1cfea1843bac76aabe55e3c3c35b727fd89bb | <ide><path>src/Illuminate/Foundation/Testing/TestResponse.php
<ide> public function assertJsonCount(int $count, $key = null)
<ide> /**
<ide> * Assert that the response has the given JSON validation errors for the given keys.
<ide> *
<del> * @param string|array $keys
<add> * @param string|array $keys
<add> * @param string $responseKey
<ide> * @return $this
<ide> */
<del> public function assertJsonValidationErrors($keys)
<add> public function assertJsonValidationErrors($keys, $responseKey = 'errors')
<ide> {
<ide> $keys = Arr::wrap($keys);
<ide>
<ide> PHPUnit::assertNotEmpty($keys, 'No keys were provided.');
<ide>
<del> $errors = $this->json()['errors'] ?? [];
<add> $errors = $this->json()[$responseKey] ?? [];
<ide>
<ide> $errorMessage = $errors
<del> ? 'Response has the following JSON validation errors:'.
<del> PHP_EOL.PHP_EOL.json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE).PHP_EOL
<del> : 'Response does not have JSON validation errors.';
<add> ? 'Response has the following JSON validation errors:' .
<add> PHP_EOL . PHP_EOL . json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL
<add> : 'Response does not have JSON validation errors.';
<ide>
<ide> foreach ($keys as $key) {
<ide> PHPUnit::assertArrayHasKey(
<ide> $key,
<ide> $errors,
<del> "Failed to find a validation error in the response for key: '{$key}'".PHP_EOL.PHP_EOL.$errorMessage
<add> "Failed to find a validation error in the response for key: '{$key}'" . PHP_EOL . PHP_EOL . $errorMessage
<ide> );
<ide> }
<ide>
<ide> public function assertJsonValidationErrors($keys)
<ide> /**
<ide> * Assert that the response has no JSON validation errors for the given keys.
<ide> *
<del> * @param string|array $keys
<add> * @param string|array $keys
<add> * @param string $responseKey
<ide> * @return $this
<ide> */
<del> public function assertJsonMissingValidationErrors($keys = null)
<add> public function assertJsonMissingValidationErrors($keys = null, string $responseKey = 'errors')
<ide> {
<ide> $json = $this->json();
<ide>
<del> if (! array_key_exists('errors', $json)) {
<del> PHPUnit::assertArrayNotHasKey('errors', $json);
<add> if (!array_key_exists($responseKey, $json)) {
<add> PHPUnit::assertArrayNotHasKey($responseKey, $json);
<ide>
<ide> return $this;
<ide> }
<ide>
<del> $errors = $json['errors'];
<add> $errors = $json[$responseKey];
<ide>
<ide> if (is_null($keys) && count($errors) > 0) {
<ide> PHPUnit::fail(
<del> 'Response has unexpected validation errors: '.PHP_EOL.PHP_EOL.
<add> 'Response has unexpected validation errors: ' . PHP_EOL . PHP_EOL .
<ide> json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
<ide> );
<ide> }
<ide><path>tests/Foundation/FoundationTestResponseTest.php
<ide> public function testAssertJsonValidationErrors()
<ide> $testResponse->assertJsonValidationErrors('foo');
<ide> }
<ide>
<add> public function testAssertJsonValidationErrorsCustomErrorsName()
<add> {
<add> $data = [
<add> 'status' => 'ok',
<add> 'data' => ['foo' => 'oops'],
<add> ];
<add>
<add> $testResponse = TestResponse::fromBaseResponse(
<add> (new Response)->setContent(json_encode($data))
<add> );
<add>
<add> $testResponse->assertJsonValidationErrors('foo','data');
<add> }
<add>
<ide> public function testAssertJsonValidationErrorsCanFail()
<ide> {
<ide> $this->expectException(AssertionFailedError::class);
<ide> public function testAssertJsonMissingValidationErrorsWithoutArgumentCanFail()
<ide> $testResponse->assertJsonMissingValidationErrors();
<ide> }
<ide>
<add> public function testAssertJsonMissingValidationErrorsCustomErrorsName()
<add> {
<add> $data = [
<add> 'status' => 'ok',
<add> 'data' => ['foo' => 'oops'],
<add> ];
<add>
<add> $testResponse = TestResponse::fromBaseResponse(
<add> (new Response)->setContent(json_encode($data))
<add> );
<add>
<add> $testResponse->assertJsonMissingValidationErrors('bar','data');
<add> }
<add>
<ide> public function testMacroable()
<ide> {
<ide> TestResponse::macro('foo', function () { | 2 |
Python | Python | offer option of padding-sensitive batching | 77af0a6bb48721f43fba2715191d0fe79867f0b7 | <ide><path>spacy/cli/train.py
<ide> def create_train_batches(nlp, corpus, cfg):
<ide> )
<ide>
<ide> epoch = 0
<add> batch_strategy = cfg.get("batch_by", "sequences")
<ide> while True:
<ide> if len(train_examples) == 0:
<ide> raise ValueError(Errors.E988)
<ide> epoch += 1
<del> if cfg.get("batch_by_words", True):
<add> if batch_strategy == "padded":
<add> batches = util.minibatch_by_padded_size(
<add> train_examples,
<add> size=cfg["batch_size"],
<add> buffer=256,
<add> discard_oversize=cfg["discard_oversize"],
<add> )
<add> elif batch_strategy == "words":
<ide> batches = util.minibatch_by_words(
<ide> train_examples,
<ide> size=cfg["batch_size"],
<ide> def create_train_batches(nlp, corpus, cfg):
<ide> train_examples,
<ide> size=cfg["batch_size"],
<ide> )
<del>
<add>
<ide> # make sure the minibatch_by_words result is not empty, or we'll have an infinite training loop
<ide> try:
<ide> first = next(batches) | 1 |
Text | Text | update example image url | b93785be5db5ee533c7ca5efa70265f87e3f0b16 | <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/add-images-to-your-website.english.md
<ide> forumTopicId: 16640
<ide> <section id='description'>
<ide> You can add images to your website by using the <code>img</code> element, and point to a specific image's URL using the <code>src</code> attribute.
<ide> An example of this would be:
<del><code><img src="https://www.your-image-source.com/your-image.jpg"></code>
<add><code><img src="https://www.freecatphotoapp.com/your-image.jpg"></code>
<ide> Note that <code>img</code> elements are self-closing.
<ide> All <code>img</code> elements <strong>must</strong> have an <code>alt</code> attribute. The text inside an <code>alt</code> attribute is used for screen readers to improve accessibility and is displayed if the image fails to load.
<ide> <strong>Note:</strong> If the image is purely decorative, using an empty <code>alt</code> attribute is a best practice.
<ide> Ideally the <code>alt</code> attribute should not contain special characters unless needed.
<ide> Let's add an <code>alt</code> attribute to our <code>img</code> example above:
<del><code><img src="https://www.your-image-source.com/your-image.jpg" alt="Author standing on a beach with two thumbs up."></code>
<add><code><img src="https://www.freecatphotoapp.com/your-image.jpg" alt="A business cat wearing a necktie."></code>
<ide> </section>
<ide>
<ide> ## Instructions | 1 |
Text | Text | add docs for collection routes | 5b11e23f6fb35834057fba35832a597ce443cc77 | <ide><path>docs/api-guide/viewsets.md
<ide> The default routers included with REST framework will provide routes for a stand
<ide> def destroy(self, request, pk=None):
<ide> pass
<ide>
<del>If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@link` or `@action` decorators. The `@link` decorator will route `GET` requests, and the `@action` decorator will route `POST` requests.
<add>If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@collection_link`, `@collection_action`, `@link`, or `@action` decorators. The `@collection_link` and `@link` decorator will route `GET` requests, and the `@collection_action` and `@action` decorator will route `POST` requests.
<add>
<add>The `@link` and `@action` decorators contain `pk` in their URL pattern and are intended for methods which require a single instance. The `@collection_link` and `@collection_action` decorators are intended for methods which operate on a collection of objects.
<ide>
<ide> For example:
<ide>
<ide> For example:
<ide> return Response(serializer.errors,
<ide> status=status.HTTP_400_BAD_REQUEST)
<ide>
<del>The `@action` and `@link` decorators can additionally take extra arguments that will be set for the routed view only. For example...
<add> @collection_link()
<add> def recent_users(self, request):
<add> recent_users = User.objects.all().order('-last_login')
<add> page = self.paginate_queryset(recent_users)
<add> serializer = self.get_pagination_serializer(page)
<add> return Response(serializer.data)
<add>
<add>The decorators can additionally take extra arguments that will be set for the routed view only. For example...
<ide>
<ide> @action(permission_classes=[IsAdminOrIsSelf])
<ide> def set_password(self, request, pk=None):
<ide> ...
<ide>
<del>The `@action` decorator will route `POST` requests by default, but may also accept other HTTP methods, by using the `method` argument. For example:
<add>The `@collection_action` and `@action` decorators will route `POST` requests by default, but may also accept other HTTP methods, by using the `method` argument. For example:
<ide>
<ide> @action(methods=['POST', 'DELETE'])
<ide> def unset_password(self, request, pk=None): | 1 |
Javascript | Javascript | clarify subclasses of ember.coreview | 07ed2e2bedba5a9b584800d4d84517fd03a28c78 | <ide><path>packages/ember-handlebars/lib/views/metamorph_view.js
<ide> Ember._MetamorphView = Ember.View.extend(Ember._Metamorph);
<ide> /**
<ide> @class _SimpleMetamorphView
<ide> @namespace Ember
<del> @extends Ember.View
<add> @extends Ember.CoreView
<ide> @uses Ember._Metamorph
<ide> @private
<ide> */
<ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.warn("The VIEW_PRESERVES_CONTEXT flag has been removed and the functionali
<ide> */
<ide> Ember.TEMPLATES = {};
<ide>
<add>/**
<add> `Ember.CoreView` is
<add>
<add> @class CoreView
<add> @namespace Ember
<add> @extends Ember.Object
<add> @uses Ember.Evented
<add>*/
<add>
<ide> Ember.CoreView = Ember.Object.extend(Ember.Evented, {
<ide> isView: true,
<ide>
<ide> class:
<ide>
<ide> @class View
<ide> @namespace Ember
<del> @extends Ember.Object
<del> @uses Ember.Evented
<add> @extends Ember.CoreView
<ide> */
<ide> Ember.View = Ember.CoreView.extend(
<ide> /** @scope Ember.View.prototype */ { | 2 |
Javascript | Javascript | fix typo in types.js (react-devtools-shared) | acf8ada4c00105f933ea87ad425e83cdcd115ba0 | <ide><path>packages/react-devtools-shared/src/types.js
<ide> export type ComponentFilter =
<ide>
<ide> export type HookName = string | null;
<ide> // Map of hook source ("<filename>:<line-number>:<column-number>") to name.
<del>// Hook source is used instead of the hook itself becuase the latter is not stable between element inspections.
<add>// Hook source is used instead of the hook itself because the latter is not stable between element inspections.
<ide> // We use a Map rather than an Array because of nested hooks and traversal ordering.
<ide> export type HookSourceLocationKey = string;
<ide> export type HookNames = Map<HookSourceLocationKey, HookName>; | 1 |
Java | Java | improve testsubject javadoc | 9bf589d07ca555fbb46752ff54f857d809ec9c96 | <ide><path>src/main/java/rx/subjects/TestSubject.java
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide>
<add>import rx.Observable;
<ide> import rx.Observer;
<ide> import rx.Scheduler;
<ide> import rx.functions.Action0;
<ide>
<ide> /**
<ide> * A variety of Subject that is useful for testing purposes. It operates on a {@link TestScheduler} and allows
<del> * you to precisely time emissions and notifications to the Subject's subscribers.
<add> * you to precisely time emissions and notifications to the Subject's subscribers using relative virtual time
<add> * controlled by the {@link TestScheduler}.
<ide> *
<ide> * @param <T>
<ide> * the type of item observed by and emitted by the subject
<ide> protected TestSubject(OnSubscribe<T> onSubscribe, SubjectSubscriptionManager<T>
<ide> this.innerScheduler = scheduler.createWorker();
<ide> }
<ide>
<add> /**
<add> * Schedule a call to {@code onCompleted} at relative time of "now()" on TestScheduler.
<add> */
<ide> @Override
<ide> public void onCompleted() {
<ide> onCompleted(innerScheduler.now());
<ide> private void _onCompleted() {
<ide> }
<ide>
<ide> /**
<del> * Schedule a call to the {@code onCompleted} methods of all of the subscribers to this Subject to begin at
<del> * a particular time.
<add> * Schedule a call to {@code onCompleted} relative to "now()" +n milliseconds in the future.
<ide> *
<ide> * @param timeInMilliseconds
<del> * the time at which to begin calling the {@code onCompleted} methods of the subscribers
<add> * the number of milliseconds in the future relative to "now()" at which to call {@code onCompleted}
<ide> */
<ide> public void onCompleted(long timeInMilliseconds) {
<ide> innerScheduler.schedule(new Action0() {
<ide> public void call() {
<ide> }, timeInMilliseconds, TimeUnit.MILLISECONDS);
<ide> }
<ide>
<add> /**
<add> * Schedule a call to {@code onError} at relative time of "now()" on TestScheduler.
<add> */
<ide> @Override
<ide> public void onError(final Throwable e) {
<ide> onError(e, innerScheduler.now());
<ide> private void _onError(final Throwable e) {
<ide> }
<ide>
<ide> /**
<del> * Schedule a call to the {@code onError} methods of all of the subscribers to this Subject to begin at
<del> * a particular time.
<add> * Schedule a call to {@code onError} relative to "now()" +n milliseconds in the future.
<ide> *
<ide> * @param e
<del> * the {@code Throwable} to pass to the {@code onError} methods of the subscribers
<add> * the {@code Throwable} to pass to the {@code onError} method
<ide> * @param timeInMilliseconds
<del> * the time at which to begin calling the {@code onError} methods of the subscribers
<add> * the number of milliseconds in the future relative to "now()" at which to call {@code onError}
<ide> */
<ide> public void onError(final Throwable e, long timeInMilliseconds) {
<ide> innerScheduler.schedule(new Action0() {
<ide> public void call() {
<ide> }, timeInMilliseconds, TimeUnit.MILLISECONDS);
<ide> }
<ide>
<add> /**
<add> * Schedule a call to {@code onNext} at relative time of "now()" on TestScheduler.
<add> */
<ide> @Override
<ide> public void onNext(T v) {
<ide> onNext(v, innerScheduler.now());
<ide> private void _onNext(T v) {
<ide> }
<ide>
<ide> /**
<del> * Emit an item to all of the subscribers to this Subject at a particular time.
<add> * Schedule a call to {@code onNext} relative to "now()" +n milliseconds in the future.
<ide> *
<ide> * @param v
<ide> * the item to emit
<ide> * @param timeInMilliseconds
<del> * the time at which to begin calling the {@code onNext} methods of the subscribers in order to emit
<del> * the item
<add> * the number of milliseconds in the future relative to "now()" at which to call {@code onNext}
<ide> */
<ide> public void onNext(final T v, long timeInMilliseconds) {
<ide> innerScheduler.schedule(new Action0() { | 1 |
Text | Text | update changelog [ci skip] | 5f8d39c7b3a1acb5842117b24806030b981442f3 | <ide><path>CHANGELOG.md
<ide> ### v3.10.0-beta.2 (UNRELEASED)
<ide>
<ide> - [#17846](https://github.com/emberjs/ember.js/pull/17846) [BUGFIX] Fix issues with template-only components causing errors in subsequent updates.
<add>- [#17870](https://github.com/emberjs/ember.js/pull/17870) / [#17871](https://github.com/emberjs/ember.js/pull/17871) [BUGFIX] Fix issue where `...attributes` may incorrectly overwrite attributes unexpectedly, depending on its position.
<ide>
<ide> ### v3.10.0-beta.1 (April 02, 2019)
<ide> | 1 |
Python | Python | fix flaky onnx tests | b41cc0b86a93c863afc3eddf7af736807218dbe7 | <ide><path>tests/test_onnx.py
<ide> import unittest
<del>from os.path import dirname, exists
<ide> from pathlib import Path
<del>from shutil import rmtree
<ide> from tempfile import NamedTemporaryFile, TemporaryDirectory
<ide>
<ide> from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
<ide> def test_quantize_tf(self):
<ide> def test_quantize_pytorch(self):
<ide> for model in OnnxExportTestCase.MODEL_TO_TEST:
<ide> path = self._test_export(model, "pt", 12)
<del> quantized_path = quantize(Path(path))
<add> quantized_path = quantize(path)
<ide>
<ide> # Ensure the actual quantized model is not bigger than the original one
<ide> if quantized_path.stat().st_size >= Path(path).stat().st_size:
<ide> def _test_export(self, model, framework, opset, tokenizer=None):
<ide> try:
<ide> # Compute path
<ide> with TemporaryDirectory() as tempdir:
<del> path = tempdir + "/model.onnx"
<add> path = Path(tempdir).joinpath("model.onnx")
<ide>
<ide> # Remove folder if exists
<del> if exists(dirname(path)):
<del> rmtree(dirname(path))
<add> if path.parent.exists():
<add> path.parent.rmdir()
<ide>
<del> # Export
<del> convert(framework, model, path, opset, tokenizer)
<add> # Export
<add> convert(framework, model, path, opset, tokenizer)
<ide>
<del> return path
<add> return path
<ide> except Exception as e:
<ide> self.fail(e)
<ide> | 1 |
Text | Text | fix typo in reactredux.md | 5f1252c734d2fa67e1e8b494a001506004d3ef4b | <ide><path>docs/faq/ReactRedux.md
<ide> Both Redux and React's Context API deal with "prop drilling". That said, they bo
<ide>
<ide> **Differences**
<ide>
<del>With Redux, you get the the power of [Redux Dev Tools Extension](https://github.com/zalmoxisus/redux-devtools-extension). It automatically logs every action your app performs, and it allows time traveling – you can click on any past action and jump to that point in time. Redux also supports the concept of middleware, where you may bind customized function calls on every action dispatch. Such examples include an automatic event logger, interception of certain actions, etc.
<add>With Redux, you get the power of [Redux Dev Tools Extension](https://github.com/zalmoxisus/redux-devtools-extension). It automatically logs every action your app performs, and it allows time traveling – you can click on any past action and jump to that point in time. Redux also supports the concept of middleware, where you may bind customized function calls on every action dispatch. Such examples include an automatic event logger, interception of certain actions, etc.
<ide>
<ide> With React's Context API, you deal with a pair of components speaking only to each other. This gives you nice isolation between irrelevant data. You also have the flexibility of how you may use the data with your components, i.e., you can provide the state of a parent component, and you may pass context data as props to wrapped components.
<ide> | 1 |
PHP | PHP | fix failing test | 0b9bdf78833ef19f8f3e146e19f5bf7295f0a254 | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testDateTimeSecured() {
<ide> 'Contact.date.day',
<ide> 'Contact.date.hour',
<ide> 'Contact.date.minute',
<del> 'Contact.date.meridian',
<ide> ];
<ide> $this->assertEquals($expected, $this->Form->fields);
<ide> | 1 |
Text | Text | remove redundant text | b73dfb9cc15e96994c4d6a5ff8b2a18538bcaf74 | <ide><path>docs/api-guide/authentication.md
<ide> Unauthenticated responses that are denied permission will result in an `HTTP 401
<ide>
<ide> WWW-Authenticate: Basic realm="api"
<ide>
<del>**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https` only. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
<add>**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
<ide>
<ide> ## TokenAuthentication
<ide>
<ide> The `curl` command line tool may be useful for testing token authenticated APIs.
<ide>
<ide> ---
<ide>
<del>**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
<add>**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`.
<ide>
<ide> ---
<ide>
<ide> Finally, sync your database.
<ide>
<ide> ---
<ide>
<del>**Note:** If you use `OAuth2Authentication` in production you must ensure that your API is only available over `https` only.
<add>**Note:** If you use `OAuth2Authentication` in production you must ensure that your API is only available over `https`.
<ide>
<ide> ---
<ide> | 1 |
Javascript | Javascript | remove unnecessary require | 7afb73715f161ea14924eceb6f03b502f32ac8fd | <ide><path>lib/internal/bootstrap/node.js
<ide> setupGlobalURL();
<ide> }
<ide>
<del> // Ensure setURLConstructor() is called before the native
<del> // URL::ToObject() method is used.
<del> NativeModule.require('internal/url');
<del>
<ide> // On OpenBSD process.execPath will be relative unless we
<ide> // get the full path before process.execPath is used.
<ide> if (process.platform === 'openbsd') {
<ide><path>lib/url.js
<ide> const {
<ide> ERR_INVALID_ARG_TYPE
<ide> } = require('internal/errors').codes;
<ide>
<add>// This ensures setURLConstructor() is called before the native
<add>// URL::ToObject() method is used.
<ide> const { spliceOne } = require('internal/util');
<ide>
<ide> // WHATWG URL implementation provided by internal/url | 2 |
Python | Python | fix circular import in lemmatizer | ed2b106f4d0d0061680ddfa5299028b3c843ef51 | <ide><path>spacy/lemmatizer.py
<ide>
<ide> import ujson as json
<ide>
<del>from .en.lemmatizer import INDEX, EXC, RULES
<ide> from .symbols import POS, NOUN, VERB, ADJ, PUNCT
<ide> from .symbols import VerbForm_inf, VerbForm_none
<ide> from .symbols import Number_sing
<ide>
<ide> class Lemmatizer(object):
<ide> @classmethod
<del> def load(cls, path, rules=None):
<del> index = dict(INDEX)
<del> exc = dict(EXC)
<del> rules = dict(RULES)
<del> return cls(index, exc, rules)
<add> def load(cls, path, index=None, exc=None, rules=None):
<add> return cls(index or {}, exc or {}, rules or {})
<ide>
<ide> def __init__(self, index, exceptions, rules):
<ide> self.index = index
<ide> def is_base_form(self, univ_pos, morphology=None):
<ide> morphology = {} if morphology is None else morphology
<ide> others = [key for key in morphology if key not in (POS, 'number', 'pos', 'verbform')]
<ide> true_morph_key = morphology.get('morph', 0)
<del> print(univ_pos, morphology)
<ide> if univ_pos == 'noun' and morphology.get('Number') == 'sing':
<ide> return True
<ide> elif univ_pos == 'verb' and morphology.get('VerbForm') == 'inf': | 1 |
Ruby | Ruby | use the schema_search_path in prepared statements | cfc95d89aeffba5a026afcf272bdf3ff231a8983 | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def exec_no_cache(sql, binds)
<ide> end
<ide>
<ide> def exec_cache(sql, binds)
<del> unless @statements.key? sql
<add> sql_key = "#{schema_search_path}-#{sql}"
<add> unless @statements.key? sql_key
<ide> nextkey = @statements.next_key
<ide> @connection.prepare nextkey, sql
<del> @statements[sql] = nextkey
<add> @statements[sql_key] = nextkey
<ide> end
<ide>
<del> key = @statements[sql]
<add> key = @statements[sql_key]
<ide>
<ide> # Clear the queue
<ide> @connection.get_last_result | 1 |
Python | Python | remove redundant pickling during training | 8870d491f1f4c1b50791484d234c2890f225abef | <ide><path>spacy/cli/train.py
<ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0,
<ide> util.set_env_log(False)
<ide> epoch_model_path = output_path / ('model%d' % i)
<ide> nlp.to_disk(epoch_model_path)
<del> with (output_path / ('model%d.pickle' % i)).open('wb') as file_:
<del> dill.dump(nlp, file_, -1)
<ide> nlp_loaded = lang_class(pipeline=pipeline)
<ide> nlp_loaded = nlp_loaded.from_disk(epoch_model_path)
<ide> scorer = nlp_loaded.evaluate( | 1 |
Python | Python | fix names used in dft.old refft->rfft | 0d68afb5705489943e3ec611ebb1d8a515153583 | <ide><path>numpy/dft/old.py
<ide> from fftpack import ifft2 as inverse_fft2d
<ide> from fftpack import ifftn as inverse_fftnd
<ide> from fftpack import ihfft as inverse_hermite_fft
<del>from fftpack import irefft as inverse_real_fft
<del>from fftpack import irefft2 as inverse_real_fft2d
<del>from fftpack import irefftn as inverse_real_fftnd
<del>from fftpack import refft as real_fft
<del>from fftpack import refft2 as real_fft2d
<del>from fftpack import refftn as real_fftnd
<add>from fftpack import irfft as inverse_real_fft
<add>from fftpack import irfft2 as inverse_real_fft2d
<add>from fftpack import irfftn as inverse_real_fftnd
<add>from fftpack import rfft as real_fft
<add>from fftpack import rfft2 as real_fft2d
<add>from fftpack import rfftn as real_fftnd | 1 |
Python | Python | update resnet with logging utils | 8f63feaa9669f8eed773bb568ee45987a473dbb3 | <ide><path>official/resnet/resnet.py
<ide> import tensorflow as tf
<ide>
<ide> from official.utils.arg_parsers import parsers # pylint: disable=g-bad-import-order
<add>from official.utils.logging import hooks_helper
<ide>
<ide> _BATCH_NORM_DECAY = 0.997
<ide> _BATCH_NORM_EPSILON = 1e-5
<ide> def resnet_main(flags, model_function, input_function):
<ide> })
<ide>
<ide> for _ in range(flags.train_epochs // flags.epochs_per_eval):
<del> tensors_to_log = {
<del> 'learning_rate': 'learning_rate',
<del> 'cross_entropy': 'cross_entropy',
<del> 'train_accuracy': 'train_accuracy'
<del> }
<del>
<del> logging_hook = tf.train.LoggingTensorHook(
<del> tensors=tensors_to_log, every_n_iter=100)
<add> train_hooks = hooks_helper.get_train_hooks(flags.hooks, batch_size=flags.batch_size)
<ide>
<ide> print('Starting a training cycle.')
<ide>
<ide> def input_fn_train():
<ide> flags.epochs_per_eval, flags.num_parallel_calls,
<ide> flags.multi_gpu)
<ide>
<del> classifier.train(input_fn=input_fn_train, hooks=[logging_hook])
<add> classifier.train(input_fn=input_fn_train, hooks=train_hooks)
<ide>
<ide> print('Starting to evaluate.')
<ide> # Evaluate the model and print results
<ide><path>official/utils/arg_parsers/parsers.py
<ide> class ExampleParser(argparse.ArgumentParser):
<ide> def __init__(self):
<ide> super(ExampleParser, self).__init__(parents=[
<del> official.utils.arg_parsers.LocationParser(data_dir=True, model_dir=True),
<del> official.utils.arg_parsers.DummyParser(use_synthetic_data=True),
<add> arg_parsers.LocationParser(data_dir=True, model_dir=True),
<add> arg_parsers.DummyParser(use_synthetic_data=True),
<ide> ])
<ide>
<ide> self.add_argument(
<ide> class BaseParser(argparse.ArgumentParser):
<ide> epochs_per_eval: Create a flag to specify the frequency of testing.
<ide> batch_size: Create a flag to specify the batch size.
<ide> multi_gpu: Create a flag to allow the use of all available GPUs.
<add> hooks: Create a flag to specify hooks for logging.
<ide> """
<ide>
<ide> def __init__(self, add_help=False, data_dir=True, model_dir=True,
<ide> train_epochs=True, epochs_per_eval=True, batch_size=True,
<del> multi_gpu=True):
<add> multi_gpu=True, hooks=True):
<ide> super(BaseParser, self).__init__(add_help=add_help)
<ide>
<ide> if data_dir:
<ide> def __init__(self, add_help=False, data_dir=True, model_dir=True,
<ide> help="If set, run across all available GPUs."
<ide> )
<ide>
<add> if hooks:
<add> self.add_argument(
<add> "--hooks", "-hk", nargs="+", default=["LoggingTensorHook"],
<add> help="[default: %(default)s] A list of strings to specify the names "
<add> "of train hooks. "
<add> "Example: --hooks LoggingTensorHook ExamplesPerSecondHook. "
<add> "Allowed hook names (case-insensitive): LoggingTensorHook, "
<add> "ProfilerHook, ExamplesPerSecondHook. "
<add> "See official.utils.logging.hooks_helper for details.",
<add> metavar="<HK>"
<add> )
<add>
<ide>
<ide> class PerformanceParser(argparse.ArgumentParser):
<ide> """Default parser for specifying performance tuning arguments.
<ide> def __init__(self, add_help=False, data_format=True):
<ide> "always compatible with CPU. If left unspecified, the data "
<ide> "format will be chosen automatically based on whether TensorFlow"
<ide> "was built for CPU or GPU.",
<del> metavar="<CF>",
<add> metavar="<CF>"
<ide> )
<ide><path>official/utils/arg_parsers/parsers_test.py
<ide> def test_default_setting(self):
<ide> train_epochs=534,
<ide> epochs_per_eval=15,
<ide> batch_size=256,
<add> hooks=["LoggingTensorHook"],
<ide> num_parallel_calls=18,
<ide> inter_op_parallelism_threads=5,
<ide> intra_op_parallelism_thread=10,
<ide><path>official/utils/logging/hooks_helper.py
<ide> def get_profiler_hook(save_steps=1000, **kwargs): # pylint: disable=unused-argu
<ide>
<ide> def get_examples_per_second_hook(every_n_steps=100,
<ide> batch_size=128,
<del> warm_steps=10,
<add> warm_steps=5,
<ide> **kwargs): # pylint: disable=unused-argument
<ide> """Function to get ExamplesPerSecondHook.
<ide> | 4 |
Text | Text | remove unnecessary code tags to allow translation | a75a866602bf38e1602fdd7e342fdb741905c473 | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-basic-css-by-building-a-cafe-menu/5f3c866dbf362f99b9a0c6d0.md
<ide> The `p` elements are nested in an `article` element with the class attribute of
<ide> .item p { }
<ide> ```
<ide>
<del>Using the above selector, add a `display` property with value `inline-block` so the `p` elements behave more like `inline` elements.
<add>Using the above selector, add a `display` property with value `inline-block` so the `p` elements behave more like inline elements.
<ide>
<ide> # --hints--
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-basic-css-by-building-a-cafe-menu/5f3c866de7a5b784048f94b1.md
<ide> dashedName: step-37
<ide>
<ide> That is kind of what you want, but now it would be nice if the flavor and price were on the same line. `p` elements are <dfn>block-level</dfn> elements, so they take up the entire width of their parent element.
<ide>
<del>To get them on the same line, you need to apply some styling to the `p` elements, so they behave more like `inline` elements. Add a `class` attribute with the value `item` to the first `article` element under the `Coffee` heading.
<add>To get them on the same line, you need to apply some styling to the `p` elements, so they behave more like <dfn>inline</dfn> elements. Add a `class` attribute with the value `item` to the first `article` element under the `Coffee` heading.
<ide>
<ide> # --hints--
<ide> | 2 |
Javascript | Javascript | convert `web/debugger.js` to a *basic* module | 8fa73dbfabac988ea3226a3aca20b46ba9dabfaf | <ide><path>gulpfile.js
<ide> function replaceWebpackRequire() {
<ide> return replace("__webpack_require__", "__w_pdfjs_require__");
<ide> }
<ide>
<add>function replaceNonWebpackImport() {
<add> return replace("__non_webpack_import__", "import");
<add>}
<add>
<ide> function replaceJSRootName(amdName, jsName) {
<ide> // Saving old-style JS module name.
<ide> return replace(
<ide> function createMainBundle(defines) {
<ide> .src("./src/pdf.js")
<ide> .pipe(webpack2Stream(mainFileConfig))
<ide> .pipe(replaceWebpackRequire())
<add> .pipe(replaceNonWebpackImport())
<ide> .pipe(replaceJSRootName(mainAMDName, "pdfjsLib"));
<ide> }
<ide>
<ide> function createScriptingBundle(defines, extraOptions = undefined) {
<ide> .src("./src/pdf.scripting.js")
<ide> .pipe(webpack2Stream(scriptingFileConfig))
<ide> .pipe(replaceWebpackRequire())
<add> .pipe(replaceNonWebpackImport())
<ide> .pipe(
<ide> replace(
<ide> 'root["' + scriptingAMDName + '"] = factory()',
<ide> function createSandboxBundle(defines, extraOptions = undefined) {
<ide> .src("./src/pdf.sandbox.js")
<ide> .pipe(webpack2Stream(sandboxFileConfig))
<ide> .pipe(replaceWebpackRequire())
<add> .pipe(replaceNonWebpackImport())
<ide> .pipe(replaceJSRootName(sandboxAMDName, "pdfjsSandbox"));
<ide> }
<ide>
<ide> function createWorkerBundle(defines) {
<ide> .src("./src/pdf.worker.js")
<ide> .pipe(webpack2Stream(workerFileConfig))
<ide> .pipe(replaceWebpackRequire())
<add> .pipe(replaceNonWebpackImport())
<ide> .pipe(replaceJSRootName(workerAMDName, "pdfjsWorker"));
<ide> }
<ide>
<ide> function createWebBundle(defines, options) {
<ide> defaultPreferencesDir: options.defaultPreferencesDir,
<ide> }
<ide> );
<del> return gulp.src("./web/viewer.js").pipe(webpack2Stream(viewerFileConfig));
<add> return gulp
<add> .src("./web/viewer.js")
<add> .pipe(webpack2Stream(viewerFileConfig))
<add> .pipe(replaceNonWebpackImport());
<ide> }
<ide>
<ide> function createComponentsBundle(defines) {
<ide> function createComponentsBundle(defines) {
<ide> .src("./web/pdf_viewer.component.js")
<ide> .pipe(webpack2Stream(componentsFileConfig))
<ide> .pipe(replaceWebpackRequire())
<add> .pipe(replaceNonWebpackImport())
<ide> .pipe(replaceJSRootName(componentsAMDName, "pdfjsViewer"));
<ide> }
<ide>
<ide> function createImageDecodersBundle(defines) {
<ide> .src("./src/pdf.image_decoders.js")
<ide> .pipe(webpack2Stream(componentsFileConfig))
<ide> .pipe(replaceWebpackRequire())
<add> .pipe(replaceNonWebpackImport())
<ide> .pipe(replaceJSRootName(imageDecodersAMDName, "pdfjsImageDecoders"));
<ide> }
<ide>
<ide> function buildLibHelper(bundleDefines, inputStream, outputDir) {
<ide> // __non_webpack_require__ has to be used.
<ide> // In this target, we don't create a bundle, so we have to replace the
<ide> // occurrences of __non_webpack_require__ ourselves.
<del> function babelPluginReplaceNonWebPackRequire(babel) {
<add> function babelPluginReplaceNonWebpackImports(babel) {
<ide> return {
<ide> visitor: {
<ide> Identifier(curPath, state) {
<ide> if (curPath.node.name === "__non_webpack_require__") {
<ide> curPath.replaceWith(babel.types.identifier("require"));
<add> } else if (curPath.node.name === "__non_webpack_import__") {
<add> curPath.replaceWith(babel.types.identifier("import"));
<ide> }
<ide> },
<ide> },
<ide> function buildLibHelper(bundleDefines, inputStream, outputDir) {
<ide> regenerator: true,
<ide> },
<ide> ],
<del> babelPluginReplaceNonWebPackRequire,
<add> babelPluginReplaceNonWebpackImports,
<ide> ],
<ide> }).code;
<ide> const removeCjsSrc =
<ide><path>web/app.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>/* globals PDFBug, Stats */
<ide>
<ide> import {
<ide> animationStarted,
<ide> const PDFViewerApplication = {
<ide> _docStats: null,
<ide> _wheelUnusedTicks: 0,
<ide> _idleCallbacks: new Set(),
<add> _PDFBug: null,
<ide>
<ide> // Called once when the document is loaded.
<ide> async initialize(appConfig) {
<ide> const PDFViewerApplication = {
<ide> this.findBar?.reset();
<ide> this.toolbar.reset();
<ide> this.secondaryToolbar.reset();
<add> this._PDFBug?.cleanup();
<ide>
<del> if (typeof PDFBug !== "undefined") {
<del> PDFBug.cleanup();
<del> }
<ide> await Promise.all(promises);
<ide> },
<ide>
<ide> async function loadFakeWorker() {
<ide>
<ide> async function initPDFBug(enabledTabs) {
<ide> const { debuggerScriptPath, mainContainer } = PDFViewerApplication.appConfig;
<del> await loadScript(debuggerScriptPath);
<add> const { PDFBug } =
<add> typeof PDFJSDev === "undefined" || !PDFJSDev.test("PRODUCTION")
<add> ? await import(debuggerScriptPath) // eslint-disable-line no-unsanitized/method
<add> : await __non_webpack_import__(debuggerScriptPath); // eslint-disable-line no-undef
<ide> PDFBug.init({ OPS }, mainContainer, enabledTabs);
<add>
<add> PDFViewerApplication._PDFBug = PDFBug;
<ide> }
<ide>
<ide> function reportPageStatsPDFBug({ pageNumber }) {
<del> if (typeof Stats === "undefined" || !Stats.enabled) {
<add> if (!globalThis.Stats?.enabled) {
<ide> return;
<ide> }
<ide> const pageView = PDFViewerApplication.pdfViewer.getPageView(
<ide> /* index = */ pageNumber - 1
<ide> );
<del> const pageStats = pageView?.pdfPage?.stats;
<del> if (!pageStats) {
<del> return;
<del> }
<del> Stats.add(pageNumber, pageStats);
<add> globalThis.Stats.add(pageNumber, pageView?.pdfPage?.stats);
<ide> }
<ide>
<ide> function webViewerInitialized() {
<ide><path>web/debugger.js
<ide> * limitations under the License.
<ide> */
<ide>
<del>"use strict";
<add>let opMap;
<ide>
<del>// eslint-disable-next-line no-var
<del>var FontInspector = (function FontInspectorClosure() {
<add>const FontInspector = (function FontInspectorClosure() {
<ide> let fonts;
<ide> let active = false;
<ide> const fontAttribute = "data-font-name";
<ide> var FontInspector = (function FontInspectorClosure() {
<ide> };
<ide> })();
<ide>
<del>let opMap;
<del>
<ide> // Manages all the page steppers.
<del>//
<del>// eslint-disable-next-line no-var
<del>var StepperManager = (function StepperManagerClosure() {
<add>const StepperManager = (function StepperManagerClosure() {
<ide> let steppers = [];
<ide> let stepperDiv = null;
<ide> let stepperControls = null;
<ide> const Stepper = (function StepperClosure() {
<ide> return Stepper;
<ide> })();
<ide>
<del>// eslint-disable-next-line no-var
<del>var Stats = (function Stats() {
<add>const Stats = (function Stats() {
<ide> let stats = [];
<ide> function clear(node) {
<ide> node.textContent = ""; // Remove any `node` contents from the DOM.
<ide> var Stats = (function Stats() {
<ide> })();
<ide>
<ide> // Manages all the debugging tools.
<del>window.PDFBug = (function PDFBugClosure() {
<add>const PDFBug = (function PDFBugClosure() {
<ide> const panelWidth = 300;
<ide> const buttons = [];
<ide> let activePanel = null;
<ide> window.PDFBug = (function PDFBugClosure() {
<ide> container.style.right = panelWidth + "px";
<ide>
<ide> // Initialize all the debugging tools.
<del> for (const [i, tool] of this.tools.entries()) {
<add> for (const tool of this.tools) {
<ide> const panel = document.createElement("div");
<ide> const panelButton = document.createElement("button");
<ide> panelButton.textContent = tool.name;
<ide> panelButton.addEventListener("click", event => {
<ide> event.preventDefault();
<del> this.selectPanel(i);
<add> this.selectPanel(tool);
<ide> });
<ide> controls.appendChild(panelButton);
<ide> panels.appendChild(panel);
<ide> window.PDFBug = (function PDFBugClosure() {
<ide> },
<ide> };
<ide> })();
<add>
<add>globalThis.FontInspector = FontInspector;
<add>globalThis.StepperManager = StepperManager;
<add>globalThis.Stats = Stats;
<add>
<add>export { PDFBug }; | 3 |
Javascript | Javascript | display better error message for assertion | beb23570dc4bfb6af53cbb95d4b2840857067863 | <ide><path>test/parallel/test-zlib-random-byte-pipes.js
<ide> const gunz = zlib.createGunzip();
<ide> inp.pipe(gzip).pipe(gunz).pipe(out);
<ide>
<ide> out.on('data', common.mustCall((c) => {
<del> assert.strictEqual(c, inp._hash, 'hashes should match');
<add> assert.strictEqual(c, inp._hash, `Hash '${c}' equals '${inp._hash}'.`);
<ide> })); | 1 |
Python | Python | fix syntax iterators | e28f90b672379b65db409bda0650d2a65bc5b5fe | <ide><path>spacy/lang/de/syntax_iterators.py
<ide> def noun_chunks(obj):
<ide> # and not just "eine Tasse", same for "das Thema Familie".
<ide> labels = ['sb', 'oa', 'da', 'nk', 'mo', 'ag', 'ROOT', 'root', 'cj', 'pd', 'og', 'app']
<ide> doc = obj.doc # Ensure works on both Doc and Span.
<del> np_label = doc.vocab.strings['NP']
<del> np_deps = set(doc.vocab.strings[label] for label in labels)
<del> close_app = doc.vocab.strings['nk']
<add> np_label = doc.vocab.strings.add('NP')
<add> np_deps = set(doc.vocab.strings.add(label) for label in labels)
<add> close_app = doc.vocab.strings.add('nk')
<ide>
<ide> rbracket = 0
<ide> for i, word in enumerate(obj):
<ide><path>spacy/lang/en/__init__.py
<ide> class EnglishDefaults(Language.Defaults):
<ide> lemma_rules = dict(LEMMA_RULES)
<ide> lemma_index = dict(LEMMA_INDEX)
<ide> lemma_exc = dict(LEMMA_EXC)
<del> sytax_iterators = dict(SYNTAX_ITERATORS)
<add> syntax_iterators = dict(SYNTAX_ITERATORS)
<ide>
<ide>
<ide> class English(Language):
<ide><path>spacy/lang/en/syntax_iterators.py
<ide> def noun_chunks(obj):
<ide> labels = ['nsubj', 'dobj', 'nsubjpass', 'pcomp', 'pobj',
<ide> 'attr', 'ROOT']
<ide> doc = obj.doc # Ensure works on both Doc and Span.
<del> np_deps = [doc.vocab.strings[label] for label in labels]
<del> conj = doc.vocab.strings['conj']
<del> np_label = doc.vocab.strings['NP']
<add> np_deps = [doc.vocab.strings.add(label) for label in labels]
<add> conj = doc.vocab.strings.add('conj')
<add> np_label = doc.vocab.strings.add('NP')
<ide> seen = set()
<ide> for i, word in enumerate(obj):
<ide> if word.pos not in (NOUN, PROPN, PRON): | 3 |
PHP | PHP | add missing translation for `mimetypes` validation | 537b6288fba5181bff6011facecbf05b6de0bbb0 | <ide><path>resources/lang/en/validation.php
<ide> 'string' => 'The :attribute may not be greater than :max characters.',
<ide> 'array' => 'The :attribute may not have more than :max items.',
<ide> ],
<add> 'mimetypes' => 'The :attribute must be a file of type: :values.',
<ide> 'mimes' => 'The :attribute must be a file of type: :values.',
<ide> 'min' => [
<ide> 'numeric' => 'The :attribute must be at least :min.', | 1 |
Java | Java | add params and remoteaddress to request builder | b2d8180f825e3193464c4bc7bdf67a0ba8bf7867 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequestBuilder.java
<ide> import java.net.URI;
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.security.Principal;
<add>import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.converter.GenericHttpMessageConverter;
<ide> import org.springframework.http.converter.HttpMessageConverter;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide> class DefaultServerRequestBuilder implements ServerRequest.Builder {
<ide>
<ide> private final Map<String, Object> attributes = new LinkedHashMap<>();
<ide>
<add> private final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
<add>
<add> @Nullable
<add> private InetSocketAddress remoteAddress;
<add>
<ide> private byte[] body = new byte[0];
<ide>
<ide>
<ide> public DefaultServerRequestBuilder(ServerRequest other) {
<ide> Assert.notNull(other, "ServerRequest must not be null");
<ide> this.servletRequest = other.servletRequest();
<del> this.messageConverters = other.messageConverters();
<add> this.messageConverters = new ArrayList<>(other.messageConverters());
<ide> this.methodName = other.methodName();
<ide> this.uri = other.uri();
<ide> headers(headers -> headers.addAll(other.headers().asHttpHeaders()));
<ide> cookies(cookies -> cookies.addAll(other.cookies()));
<ide> attributes(attributes -> attributes.putAll(other.attributes()));
<add> params(params -> params.addAll(other.params()));
<add> this.remoteAddress = other.remoteAddress().orElse(null);
<ide> }
<ide>
<ide> @Override
<ide> public ServerRequest.Builder attributes(Consumer<Map<String, Object>> attributes
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public ServerRequest.Builder param(String name, String... values) {
<add> for (String value : values) {
<add> this.params.add(name, value);
<add> }
<add> return this;
<add> }
<add>
<add> @Override
<add> public ServerRequest.Builder params(Consumer<MultiValueMap<String, String>> paramsConsumer) {
<add> paramsConsumer.accept(this.params);
<add> return this;
<add> }
<add>
<add> @Override
<add> public ServerRequest.Builder remoteAddress(InetSocketAddress remoteAddress) {
<add> this.remoteAddress = remoteAddress;
<add> return this;
<add> }
<add>
<add>
<ide> @Override
<ide> public ServerRequest build() {
<del> return new BuiltServerRequest(this.servletRequest, this.methodName, this.uri,
<del> this.headers, this.cookies, this.attributes, this.body, this.messageConverters);
<add> return new BuiltServerRequest(this.servletRequest, this.methodName, this.uri, this.headers, this.cookies,
<add> this.attributes, this.params, this.remoteAddress, this.body, this.messageConverters);
<ide> }
<ide>
<ide>
<ide> private static class BuiltServerRequest implements ServerRequest {
<ide>
<ide> private final List<HttpMessageConverter<?>> messageConverters;
<ide>
<add> private final MultiValueMap<String, String> params;
<add>
<add> @Nullable
<add> private final InetSocketAddress remoteAddress;
<add>
<ide> public BuiltServerRequest(HttpServletRequest servletRequest, String methodName, URI uri,
<ide> HttpHeaders headers, MultiValueMap<String, Cookie> cookies,
<del> Map<String, Object> attributes, byte[] body,
<del> List<HttpMessageConverter<?>> messageConverters) {
<add> Map<String, Object> attributes, MultiValueMap<String, String> params,
<add> @Nullable InetSocketAddress remoteAddress, byte[] body, List<HttpMessageConverter<?>> messageConverters) {
<ide>
<ide> this.servletRequest = servletRequest;
<ide> this.methodName = methodName;
<ide> this.uri = uri;
<del> this.headers = headers;
<del> this.cookies = cookies;
<del> this.attributes = attributes;
<add> this.headers = new HttpHeaders(headers);
<add> this.cookies = new LinkedMultiValueMap<>(cookies);
<add> this.attributes = new LinkedHashMap<>(attributes);
<add> this.params = new LinkedMultiValueMap<>(params);
<add> this.remoteAddress = remoteAddress;
<ide> this.body = body;
<ide> this.messageConverters = messageConverters;
<ide> }
<ide> public MultiValueMap<String, Cookie> cookies() {
<ide>
<ide> @Override
<ide> public Optional<InetSocketAddress> remoteAddress() {
<del> return Optional.empty();
<add> return Optional.ofNullable(this.remoteAddress);
<ide> }
<ide>
<ide> @Override
<ide> public Map<String, Object> attributes() {
<ide>
<ide> @Override
<ide> public MultiValueMap<String, String> params() {
<del> return new LinkedMultiValueMap<>();
<add> return this.params;
<ide> }
<ide>
<ide> @Override
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/ServerRequest.java
<ide> interface Builder {
<ide> */
<ide> Builder attributes(Consumer<Map<String, Object>> attributesConsumer);
<ide>
<add> /**
<add> * Add a parameter with the given name and value.
<add> * @param name the parameter name
<add> * @param values the parameter value(s)
<add> * @return this builder
<add> */
<add> Builder param(String name, String... values);
<add>
<add> /**
<add> * Manipulate this request's parameters with the given consumer.
<add> * <p>The map provided to the consumer is "live", so that the consumer can be used to
<add> * {@linkplain MultiValueMap#set(Object, Object) overwrite} existing cookies,
<add> * {@linkplain MultiValueMap#remove(Object) remove} cookies, or use any of the other
<add> * {@link MultiValueMap} methods.
<add> * @param paramsConsumer a function that consumes the parameters map
<add> * @return this builder
<add> */
<add> Builder params(Consumer<MultiValueMap<String, String>> paramsConsumer);
<add>
<add> /**
<add> * Set the remote address of the request.
<add> * @param remoteAddress the remote address
<add> * @return this builder
<add> */
<add> Builder remoteAddress(InetSocketAddress remoteAddress);
<add>
<ide> /**
<ide> * Build the request.
<ide> * @return the built request
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestBuilderTests.java
<ide> package org.springframework.web.servlet.function;
<ide>
<ide> import java.io.IOException;
<add>import java.net.InetSocketAddress;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide>
<ide> import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.http.converter.StringHttpMessageConverter;
<ide> import org.springframework.web.servlet.handler.PathPatternsTestUtils;
<add>import org.springframework.web.testfixture.servlet.MockCookie;
<ide> import org.springframework.web.testfixture.servlet.MockHttpServletRequest;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> class DefaultServerRequestBuilderTests {
<ide> void from() throws ServletException, IOException {
<ide> MockHttpServletRequest request = PathPatternsTestUtils.initRequest("POST", "https://example.com", true);
<ide> request.addHeader("foo", "bar");
<add> request.setCookies(new MockCookie("foo", "bar"));
<add> request.setAttribute("foo", "bar");
<add> request.addParameter("foo", "bar");
<add> request.setRemoteHost("127.0.0.1");
<add> request.setRemotePort(80);
<ide>
<ide> ServerRequest other = ServerRequest.create(request, messageConverters);
<ide>
<ide> ServerRequest result = ServerRequest.from(other)
<ide> .method(HttpMethod.HEAD)
<del> .header("foo", "bar")
<del> .headers(httpHeaders -> httpHeaders.set("baz", "qux"))
<del> .cookie("foo", "bar")
<del> .cookies(cookies -> cookies.set("baz", new Cookie("baz", "qux")))
<del> .attribute("foo", "bar")
<del> .attributes(attributes -> attributes.put("baz", "qux"))
<add> .header("baz", "qux")
<add> .headers(httpHeaders -> httpHeaders.set("quux", "quuz"))
<add> .cookie("baz", "qux")
<add> .cookies(cookies -> cookies.set("quux", new Cookie("quux", "quuz")))
<add> .attribute("baz", "qux")
<add> .attributes(attributes -> attributes.put("quux", "quuz"))
<add> .param("baz", "qux")
<add> .params(params -> params.set("quux", "quuz"))
<ide> .body("baz")
<ide> .build();
<ide>
<ide> assertThat(result.method()).isEqualTo(HttpMethod.HEAD);
<del> assertThat(result.headers().asHttpHeaders().size()).isEqualTo(2);
<ide> assertThat(result.headers().asHttpHeaders().getFirst("foo")).isEqualTo("bar");
<ide> assertThat(result.headers().asHttpHeaders().getFirst("baz")).isEqualTo("qux");
<del> assertThat(result.cookies().size()).isEqualTo(2);
<add> assertThat(result.headers().asHttpHeaders().getFirst("quux")).isEqualTo("quuz");
<add>
<ide> assertThat(result.cookies().getFirst("foo").getValue()).isEqualTo("bar");
<ide> assertThat(result.cookies().getFirst("baz").getValue()).isEqualTo("qux");
<del> assertThat(result.attributes().size()).isEqualTo(other.attributes().size() + 2);
<add> assertThat(result.cookies().getFirst("quux").getValue()).isEqualTo("quuz");
<add>
<ide> assertThat(result.attributes().get("foo")).isEqualTo("bar");
<ide> assertThat(result.attributes().get("baz")).isEqualTo("qux");
<add> assertThat(result.attributes().get("quux")).isEqualTo("quuz");
<add>
<add> assertThat(result.params().getFirst("foo")).isEqualTo("bar");
<add> assertThat(result.params().getFirst("baz")).isEqualTo("qux");
<add> assertThat(result.params().getFirst("quux")).isEqualTo("quuz");
<add>
<add> assertThat(result.remoteAddress()).contains(new InetSocketAddress("127.0.0.1", 80));
<ide>
<ide> String body = result.body(String.class);
<ide> assertThat(body).isEqualTo("baz"); | 3 |
Go | Go | remove useless anonymous field mentions | 42e35ecff36fcb07e45c19f880af84f8532a3fac | <ide><path>engine/streams.go
<ide> func NewOutput() *Output {
<ide>
<ide> // Return true if something was written on this output
<ide> func (o *Output) Used() bool {
<del> o.Mutex.Lock()
<del> defer o.Mutex.Unlock()
<add> o.Lock()
<add> defer o.Unlock()
<ide> return o.used
<ide> }
<ide>
<ide> // Add attaches a new destination to the Output. Any data subsequently written
<ide> // to the output will be written to the new destination in addition to all the others.
<ide> // This method is thread-safe.
<ide> func (o *Output) Add(dst io.Writer) {
<del> o.Mutex.Lock()
<del> defer o.Mutex.Unlock()
<add> o.Lock()
<add> defer o.Unlock()
<ide> o.dests = append(o.dests, dst)
<ide> }
<ide>
<ide> func (o *Output) Add(dst io.Writer) {
<ide> // destination in addition to all the others. This method is thread-safe.
<ide> func (o *Output) Set(dst io.Writer) {
<ide> o.Close()
<del> o.Mutex.Lock()
<del> defer o.Mutex.Unlock()
<add> o.Lock()
<add> defer o.Unlock()
<ide> o.dests = []io.Writer{dst}
<ide> }
<ide>
<ide> func (o *Output) AddString(dst *string) error {
<ide> // Write writes the same data to all registered destinations.
<ide> // This method is thread-safe.
<ide> func (o *Output) Write(p []byte) (n int, err error) {
<del> o.Mutex.Lock()
<del> defer o.Mutex.Unlock()
<add> o.Lock()
<add> defer o.Unlock()
<ide> o.used = true
<ide> var firstErr error
<ide> for _, dst := range o.dests {
<ide> func (o *Output) Write(p []byte) (n int, err error) {
<ide> // AddTail and AddString tasks to complete.
<ide> // The Close method of each destination is called if it exists.
<ide> func (o *Output) Close() error {
<del> o.Mutex.Lock()
<del> defer o.Mutex.Unlock()
<add> o.Lock()
<add> defer o.Unlock()
<ide> var firstErr error
<ide> for _, dst := range o.dests {
<ide> if closer, ok := dst.(io.WriteCloser); ok { | 1 |
Mixed | Text | add action cable testing guides | a4099debcfd7e5e1fe3e5fd9111b7cb0242eb56d | <ide><path>actioncable/CHANGELOG.md
<add>* Merge [`action-cable-testing`](https://github.com/palkan/action-cable-testing) to Rails.
<add>
<add> *Vladimir Dementyev*
<add>
<ide> * The JavaScript WebSocket client will no longer try to reconnect
<ide> when you call `reject_unauthorized_connection` on the connection.
<ide>
<ide><path>actioncable/lib/action_cable/connection/test_case.rb
<ide> def initialize(request)
<ide> # def test_connects_with_proper_cookie
<ide> # # Simulate the connection request with a cookie.
<ide> # cookies["user_id"] = users(:john).id
<del>
<add> #
<ide> # connect
<ide> #
<ide> # # Assert the connection identifier matches the fixture.
<ide><path>guides/source/6_0_release_notes.md
<ide> Highlights in Rails 6.0:
<ide> * Action Mailbox
<ide> * Action Text
<ide> * Parallel Testing
<add>* Action Cable Testing
<ide>
<ide> These release notes cover only the major changes. To learn about various bug
<ide> fixes and changes, please refer to the change logs or check out the [list of
<ide> test suite. While forking processes is the default method, threading is
<ide> supported as well. Running tests in parallel reduces the time it takes
<ide> your entire test suite to run.
<ide>
<add>### Action Cable Testing
<add>
<add>[Pull Request](https://github.com/rails/rails/pull/33659)
<add>
<add>[Action Cable testing tools](testing.html#testing-action-cable) allow you to test your
<add>Action Cable functionality at any level: connections, channels, broadcasts.
<add>
<ide> Railties
<ide> --------
<ide>
<ide><path>guides/source/action_cable_overview.md
<ide> internally, irrespective of whether the application server is multi-threaded or
<ide>
<ide> Accordingly, Action Cable works with popular servers like Unicorn, Puma, and
<ide> Passenger.
<add>
<add>## Testing
<add>
<add>You can find detailed instructions on how to test your Action Cable functionality in the
<add>[testing guide](testing.html#testing-action-cable).
<ide><path>guides/source/testing.md
<ide> Rails creates a `test` directory for you as soon as you create a Rails project u
<ide>
<ide> ```bash
<ide> $ ls -F test
<del>application_system_test_case.rb fixtures/ integration/ models/ test_helper.rb
<del>controllers/ helpers/ mailers/ system/
<add>application_system_test_case.rb controllers/ helpers/ mailers/ system/
<add>channels/ fixtures/ integration/ models/ test_helper.rb
<ide> ```
<ide>
<del>The `helpers`, `mailers`, and `models` directories are meant to hold tests for view helpers, mailers, and models, respectively. The `controllers` directory is meant to hold tests for controllers, routes, and views. The `integration` directory is meant to hold tests for interactions between controllers.
<add>The `helpers`, `mailers`, and `models` directories are meant to hold tests for view helpers, mailers, and models, respectively. The `channels` directory is meant to hold tests for Action Cable connection and channels. The `controllers` directory is meant to hold tests for controllers, routes, and views. The `integration` directory is meant to hold tests for interactions between controllers.
<ide>
<ide> The system test directory holds system tests, which are used for full browser
<ide> testing of your application. System tests allow you to test your application
<ide> class ProductTest < ActiveJob::TestCase
<ide> end
<ide> ```
<ide>
<add>Testing Action Cable
<add>--------------------
<add>
<add>Since Action Cable is used at different levels inside your application,
<add>you'll need to test both the channels and connection classes themsleves and that other
<add>entities broadcast correct messages.
<add>
<add>### Connection Test Case
<add>
<add>By default, when you generate new Rails application with Action Cable, a test for the base connection class (`ApplicationCable::Connection`) is generated as well under `test/channels/application_cable` directory.
<add>
<add>Connection tests aim to check whether a connection's identifiers gets assigned properly
<add>or that any improper connection requests are rejected. Here is an example:
<add>
<add>```ruby
<add>class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
<add> test "connects with params" do
<add> # Simulate a connection opening by calling the `connect` method
<add> connect params: { user_id: 42 }
<add>
<add> # You can access the Connection object via `connection` in tests
<add> assert_equal connection.user_id, "42"
<add> end
<add>
<add> test "rejects connection without params" do
<add> # Use `assert_reject_connection` matcher to verify that
<add> # connection is rejected
<add> assert_reject_connection { connect }
<add> end
<add>end
<add>```
<add>
<add>You can also specify request cookies the same way you do in integration tests:
<add>
<add>
<add>```ruby
<add>test "connects with_cookies" do
<add> cookies.signed[:user_id] = "42"
<add>
<add> connect
<add>
<add> assert_equal connection.user_id, "42"
<add>end
<add>```
<add>
<add>See the API documentation for [`AcionCable::Connection::TestCase`](http://api.rubyonrails.org/classes/ActionCable/Connection/TestCase.html) for more information.
<add>
<add>
<add>### Channel Test Case
<add>
<add>By default, when you generate a channel, an associated test will be generated as well
<add>under the `test/channels` directory. Here's an example test with a chat channel:
<add>
<add>```ruby
<add>require "test_helper"
<add>
<add>class ChatChannelTest < ActionCable::Channel::TestCase
<add> test "subscribes and stream for room" do
<add> # Simulate a subscription creation by calling `subscribe`
<add> subscribe room: "15"
<add>
<add> # You can access the Channel object via `subscription` in tests
<add> assert subscription.confirmed?
<add> assert_has_stream "chat_15"
<add> end
<add>end
<add>```
<add>
<add>This test is pretty simple and only asserts that the channel subscribes the connection to a particular stream.
<add>
<add>You can also specify the underlying connection identifiers. Here's an example test with a web notifications channel:
<add>
<add>```ruby
<add>require "test_helper"
<add>
<add>class WebNotificationsChannelTest < ActionCable::Channel::TestCase
<add> test "subscribes and stream for user" do
<add> stub_connection current_user: users[:john]
<add>
<add> subscribe
<add>
<add> assert_has_stream_for users[:john]
<add> end
<add>end
<add>```
<add>
<add>See the API documentation for [`AcionCable::Channel::TestCase`](http://api.rubyonrails.org/classes/ActionCable/Channel/TestCase.html) for more information.
<add>
<add>### Custom Assertions And Testing Broadcasts Inside Other Components
<add>
<add>Action Cable ships with a bunch of custom assertions that can be used to lessen the verbosity of tests. For a full list of available assertions, see the API documentation for [`ActionCable::TestHelper`](http://api.rubyonrails.org/classes/ActionCable/TestHelper.html).
<add>
<add>It's a good practice to ensure that the correct message has been broadcasted inside another components (e.g. inside your controllers). This is precisely where
<add>the custom assertions provided by Action Cable are pretty useful. For instance,
<add>within a model:
<add>
<add>```ruby
<add>require 'test_helper'
<add>
<add>class ProductTest < ActionCable::TestCase
<add> test "broadcast status after charge" do
<add> assert_broadcast_on("products:#{product.id}", type: "charged") do
<add> product.charge(account)
<add> end
<add> end
<add>end
<add>```
<add>
<ide> Additional Testing Resources
<ide> ----------------------------
<ide> | 5 |
Mixed | Javascript | return this from net.socket.end() | 324f1115b3a3c28d19261772442ea52bd191ed85 | <ide><path>doc/api/net.md
<ide> server will still send some data.
<ide> If `data` is specified, it is equivalent to calling
<ide> `socket.write(data, encoding)` followed by [`socket.end()`][].
<ide>
<add>Returns `socket`.
<add>
<ide> ### socket.localAddress
<ide> <!-- YAML
<ide> added: v0.9.6
<ide><path>lib/net.js
<ide> Socket.prototype.end = function(data, encoding) {
<ide> this.read(0);
<ide> else
<ide> maybeDestroy(this);
<add>
<add> return this;
<ide> };
<ide>
<ide>
<ide><path>test/parallel/test-socket-write-after-fin.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const net = require('net');
<del>const expected = 'hello1hello2hello3\nTHUNDERMUSCLE!';
<add>const expected = 'hello1hello2hello3\nbye';
<ide>
<ide> const server = net.createServer({
<ide> allowHalfOpen: true
<ide> server.listen(0, common.mustCall(function() {
<ide> sock.write('hello1');
<ide> sock.write('hello2');
<ide> sock.write('hello3\n');
<del> sock.end('THUNDERMUSCLE!');
<add> assert.strictEqual(sock.end('bye'), sock);
<add>
<ide> })); | 3 |
Javascript | Javascript | fix perf issues with lazy sets | b58e0799e2351d97c4a7fb28a292e32fd9bc4013 | <ide><path>lib/util/LazySet.js
<ide> const merge = (targetSet, toMerge) => {
<ide> /**
<ide> * @template T
<ide> * @param {Set<Iterable<T>>} targetSet set where iterables should be added
<del> * @param {Array<Iterable<T> | LazySet<T>>} toDeepMerge iterables or lazy set to be flattened
<add> * @param {Array<LazySet<T>>} toDeepMerge lazy sets to be flattened
<ide> * @returns {void}
<ide> */
<ide> const flatten = (targetSet, toDeepMerge) => {
<ide> for (const set of toDeepMerge) {
<del> if (set instanceof LazySet) {
<del> if (set._set.size > 0) targetSet.add(set._set);
<del> if (set._needMerge) {
<del> for (const mergedSet of set._toMerge) {
<del> targetSet.add(mergedSet);
<del> }
<del> flatten(targetSet, set._toDeepMerge);
<add> if (set._set.size > 0) targetSet.add(set._set);
<add> if (set._needMerge) {
<add> for (const mergedSet of set._toMerge) {
<add> targetSet.add(mergedSet);
<ide> }
<del> } else {
<del> targetSet.add(set);
<add> flatten(targetSet, set._toDeepMerge);
<ide> }
<ide> }
<ide> };
<ide> class LazySet {
<ide> this._set = new Set(iterable);
<ide> /** @type {Set<Iterable<T>>} */
<ide> this._toMerge = new Set();
<del> /** @type {Array<Iterable<T> | LazySet<T>>} */
<add> /** @type {Array<LazySet<T>>} */
<ide> this._toDeepMerge = [];
<ide> this._needMerge = false;
<ide> this._deopt = false;
<ide> class LazySet {
<ide> this._needMerge = false;
<ide> }
<ide>
<add> _isEmpty() {
<add> return (
<add> this._set.size === 0 &&
<add> this._toMerge.size === 0 &&
<add> this._toDeepMerge.length === 0
<add> );
<add> }
<add>
<ide> get size() {
<ide> if (this._needMerge) this._merge();
<ide> return this._set.size;
<ide> class LazySet {
<ide> _set.add(item);
<ide> }
<ide> } else {
<del> this._toDeepMerge.push(iterable);
<del> this._needMerge = true;
<del> // Avoid being too memory hungry
<del> if (this._toDeepMerge.length > 100000) {
<del> this._flatten();
<del> if (this._toMerge.size > 100000) this._merge();
<add> if (iterable instanceof LazySet) {
<add> if (!iterable._isEmpty()) {
<add> this._toDeepMerge.push(iterable);
<add> this._needMerge = true;
<add> if (this._toDeepMerge.length > 100000) {
<add> this._flatten();
<add> }
<add> }
<add> } else {
<add> this._toMerge.add(iterable);
<add> this._needMerge = true;
<ide> }
<add> if (this._toMerge.size > 100000) this._merge();
<ide> }
<ide> return this;
<ide> }
<ide><path>test/LazySet.unittest.js
<add>const LazySet = require("../lib/util/LazySet");
<add>
<add>describe("LazySet", () => {
<add> it("addAll", () => {
<add> const a = new Set(["a"]);
<add> const sut = new LazySet(a);
<add> const empty = new LazySet([]);
<add> expect(sut.size).toBe(1);
<add> sut.addAll(empty);
<add> expect(sut._toDeepMerge).toStrictEqual([]);
<add> expect(sut.size).toBe(1);
<add> const b = new Set(["b"]);
<add> sut.addAll(b);
<add> expect(sut._toMerge).toContain(b);
<add> expect(sut.size).toBe(2);
<add> const c = new LazySet(["c"]);
<add> sut.addAll(c);
<add> expect(sut._toDeepMerge).toContain(c);
<add> expect(sut.size).toBe(3);
<add> expect(sut._toDeepMerge).toStrictEqual([]);
<add> });
<add>}); | 2 |
Javascript | Javascript | fix abc to abs | 720bb21c91b3b964d1bd58a23a6cf3bc6aead903 | <ide><path>examples/js/nodes/math/Math1Node.js
<ide> THREE.Math1Node.TAN = 'tan';
<ide> THREE.Math1Node.ASIN = 'asin';
<ide> THREE.Math1Node.ACOS = 'acos';
<ide> THREE.Math1Node.ARCTAN = 'atan';
<del>THREE.Math1Node.ABS = 'abc';
<add>THREE.Math1Node.ABS = 'abs';
<ide> THREE.Math1Node.SIGN = 'sign';
<ide> THREE.Math1Node.LENGTH = 'length';
<ide> THREE.Math1Node.NEGATE = 'negate'; | 1 |
Javascript | Javascript | use foreachbail from enhanced-resolve | b54f2ac65c37090d826d462c7fc3399bda4e1ccc | <ide><path>lib/CacheFacade.js
<ide>
<ide> "use strict";
<ide>
<add>const { forEachBail } = require("enhanced-resolve");
<ide> const asyncLib = require("neo-async");
<ide> const getLazyHashedEtag = require("./cache/getLazyHashedEtag");
<ide> const mergeEtags = require("./cache/mergeEtags");
<ide> class MultiItemCache {
<ide> * @returns {void}
<ide> */
<ide> get(callback) {
<del> let i = 0;
<del> let resultFound = false;
<del> const generateGetCallback = (/** @type {Boolean} */ lastItem) => {
<del> return (
<del> /** @type {import("./WebpackError")} */ err,
<del> /** @type {T} */ res
<del> ) => {
<del> if (resultFound) return;
<del> resultFound = !!(err || res || false);
<del> if (err) return callback(err);
<del> if (res !== undefined) return callback(null, res);
<del> if (lastItem) return callback();
<del> };
<del> };
<del> do {
<del> this._items[i].get(generateGetCallback(i === this._items.length - 1));
<del> } while (++i < this._items.length);
<add> forEachBail(this._items, (item, callback) => item.get(callback), callback);
<ide> }
<ide>
<ide> /**
<ide><path>test/MultiItemCache.unittest.js
<ide> describe("MultiItemCache", () => {
<ide> const multiItemCache = new MultiItemCache(itemCaches);
<ide> let callbacks = 0;
<ide> const callback = (err, res) => {
<del> expect(err).toBeUndefined();
<add> expect(err).toBeNull();
<ide> expect(res).toBeUndefined();
<ide> ++callbacks;
<ide> }; | 2 |
Javascript | Javascript | remove the unused radiocheck regex | 94fff6ff625be9fbbb54db53d9acec63f0919370 | <ide><path>src/attributes.js
<ide> var rclass = /[\n\t\r]/g,
<ide> rspecialurl = /^(?:href|src|style)$/,
<ide> rtype = /^(?:button|input)$/i,
<ide> rfocusable = /^(?:button|input|object|select|textarea)$/i,
<del> rclickable = /^a(?:rea)?$/i,
<del> rradiocheck = /^(?:radio|checkbox)$/i;
<add> rclickable = /^a(?:rea)?$/i;
<ide>
<ide> jQuery.props = {
<ide> "for": "htmlFor", | 1 |
Mixed | Javascript | add numericseparator to util.inspect | 85764c0e1a9b2e6fc1734a3977dc11651a4bec80 | <ide><path>doc/api/util.md
<ide> stream.write('With ES6');
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/41003
<add> description: The `numericSeparator` option is supported now.
<ide> - version:
<ide> - v14.6.0
<ide> - v12.19.0
<ide> changes:
<ide> set to `'set'`, only getters with a corresponding setter are inspected.
<ide> This might cause side effects depending on the getter function.
<ide> **Default:** `false`.
<add> * `numericSeparator` {boolean} If set to `true`, an underscore is used to
<add> separate every three digits in all bigints and numbers.
<add> **Default:** `false`.
<ide> * Returns: {string} The representation of `object`.
<ide>
<ide> The `util.inspect()` method returns a string representation of `object` that is
<ide> assert.strict.equal(
<ide> );
<ide> ```
<ide>
<add>The `numericSeparator` option adds an underscore every three digits to all
<add>numbers.
<add>
<add>```js
<add>const { inspect } = require('util');
<add>
<add>const thousand = 1_000;
<add>const million = 1_000_000;
<add>const bigNumber = 123_456_789n;
<add>const bigDecimal = 1_234.123_45;
<add>
<add>console.log(thousand, million, bigNumber, bigDecimal);
<add>// 1_000 1_000_000 123_456_789n 1_234.123_45
<add>```
<add>
<ide> `util.inspect()` is a synchronous method intended for debugging. Its maximum
<ide> output length is approximately 128 MB. Inputs that result in longer output will
<ide> be truncated.
<ide><path>lib/internal/util/inspect.js
<ide> const {
<ide> MathMin,
<ide> MathRound,
<ide> MathSqrt,
<add> MathTrunc,
<ide> Number,
<add> NumberIsFinite,
<ide> NumberIsNaN,
<ide> NumberParseFloat,
<ide> NumberParseInt,
<ide> const inspectDefaultOptions = ObjectSeal({
<ide> breakLength: 80,
<ide> compact: 3,
<ide> sorted: false,
<del> getters: false
<add> getters: false,
<add> numericSeparator: false,
<ide> });
<ide>
<ide> const kObjectType = 0;
<ide> function getUserOptions(ctx, isCrossContext) {
<ide> compact: ctx.compact,
<ide> sorted: ctx.sorted,
<ide> getters: ctx.getters,
<add> numericSeparator: ctx.numericSeparator,
<ide> ...ctx.userOptions
<ide> };
<ide>
<ide> function inspect(value, opts) {
<ide> breakLength: inspectDefaultOptions.breakLength,
<ide> compact: inspectDefaultOptions.compact,
<ide> sorted: inspectDefaultOptions.sorted,
<del> getters: inspectDefaultOptions.getters
<add> getters: inspectDefaultOptions.getters,
<add> numericSeparator: inspectDefaultOptions.numericSeparator,
<ide> };
<ide> if (arguments.length > 1) {
<ide> // Legacy...
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> formatter = formatArrayBuffer;
<ide> } else if (keys.length === 0 && protoProps === undefined) {
<ide> return prefix +
<del> `{ byteLength: ${formatNumber(ctx.stylize, value.byteLength)} }`;
<add> `{ byteLength: ${formatNumber(ctx.stylize, value.byteLength, false)} }`;
<ide> }
<ide> braces[0] = `${prefix}{`;
<ide> ArrayPrototypeUnshift(keys, 'byteLength');
<ide> function handleMaxCallStackSize(ctx, err, constructorName, indentationLvl) {
<ide> assert.fail(err.stack);
<ide> }
<ide>
<del>function formatNumber(fn, value) {
<del> // Format -0 as '-0'. Checking `value === -0` won't distinguish 0 from -0.
<del> return fn(ObjectIs(value, -0) ? '-0' : `${value}`, 'number');
<add>function addNumericSeparator(integerString) {
<add> let result = '';
<add> let i = integerString.length;
<add> const start = integerString.startsWith('-') ? 1 : 0;
<add> for (; i >= start + 4; i -= 3) {
<add> result = `_${integerString.slice(i - 3, i)}${result}`;
<add> }
<add> return i === integerString.length ?
<add> integerString :
<add> `${integerString.slice(0, i)}${result}`;
<add>}
<add>
<add>function addNumericSeparatorEnd(integerString) {
<add> let result = '';
<add> let i = 0;
<add> for (; i < integerString.length - 3; i += 3) {
<add> result += `${integerString.slice(i, i + 3)}_`;
<add> }
<add> return i === 0 ?
<add> integerString :
<add> `${result}${integerString.slice(i)}`;
<add>}
<add>
<add>function formatNumber(fn, number, numericSeparator) {
<add> if (!numericSeparator) {
<add> // Format -0 as '-0'. Checking `number === -0` won't distinguish 0 from -0.
<add> if (ObjectIs(number, -0)) {
<add> return fn('-0', 'number');
<add> }
<add> return fn(`${number}`, 'number');
<add> }
<add> const integer = MathTrunc(number);
<add> const string = String(integer);
<add> if (integer === number) {
<add> if (!NumberIsFinite(number) || string.includes('e')) {
<add> return fn(string, 'number');
<add> }
<add> return fn(`${addNumericSeparator(string)}`, 'number');
<add> }
<add> if (NumberIsNaN(number)) {
<add> return fn(string, 'number');
<add> }
<add> return fn(`${
<add> addNumericSeparator(string)
<add> }.${
<add> addNumericSeparatorEnd(String(number).slice(string.length + 1))
<add> }`, 'number');
<ide> }
<ide>
<del>function formatBigInt(fn, value) {
<del> return fn(`${value}n`, 'bigint');
<add>function formatBigInt(fn, bigint, numericSeparator) {
<add> const string = String(bigint);
<add> if (!numericSeparator) {
<add> return fn(`${string}n`, 'bigint');
<add> }
<add> return fn(`${addNumericSeparator(string)}n`, 'bigint');
<ide> }
<ide>
<ide> function formatPrimitive(fn, value, ctx) {
<ide> function formatPrimitive(fn, value, ctx) {
<ide> return fn(strEscape(value), 'string') + trailer;
<ide> }
<ide> if (typeof value === 'number')
<del> return formatNumber(fn, value);
<add> return formatNumber(fn, value, ctx.numericSeparator);
<ide> if (typeof value === 'bigint')
<del> return formatBigInt(fn, value);
<add> return formatBigInt(fn, value, ctx.numericSeparator);
<ide> if (typeof value === 'boolean')
<ide> return fn(`${value}`, 'boolean');
<ide> if (typeof value === 'undefined')
<ide> function formatTypedArray(value, length, ctx, ignored, recurseTimes) {
<ide> const elementFormatter = value.length > 0 && typeof value[0] === 'number' ?
<ide> formatNumber :
<ide> formatBigInt;
<del> for (let i = 0; i < maxLength; ++i)
<del> output[i] = elementFormatter(ctx.stylize, value[i]);
<add> for (let i = 0; i < maxLength; ++i) {
<add> output[i] = elementFormatter(ctx.stylize, value[i], ctx.numericSeparator);
<add> }
<ide> if (remaining > 0) {
<ide> output[maxLength] = `... ${remaining} more item${remaining > 1 ? 's' : ''}`;
<ide> }
<ide> function tryStringify(arg) {
<ide> if (!CIRCULAR_ERROR_MESSAGE) {
<ide> try {
<ide> const a = {}; a.a = a; JSONStringify(a);
<del> } catch (err) {
<del> CIRCULAR_ERROR_MESSAGE = firstErrorLine(err);
<add> } catch (circularError) {
<add> CIRCULAR_ERROR_MESSAGE = firstErrorLine(circularError);
<ide> }
<ide> }
<ide> if (err.name === 'TypeError' &&
<ide> function formatWithOptions(inspectOptions, ...args) {
<ide> return formatWithOptionsInternal(inspectOptions, args);
<ide> }
<ide>
<add>function formatNumberNoColor(number, options) {
<add> return formatNumber(
<add> stylizeNoColor,
<add> number,
<add> options?.numericSeparator ?? inspectDefaultOptions.numericSeparator
<add> );
<add>}
<add>
<add>function formatBigIntNoColor(bigint, options) {
<add> return formatBigInt(
<add> stylizeNoColor,
<add> bigint,
<add> options?.numericSeparator ?? inspectDefaultOptions.numericSeparator
<add> );
<add>}
<add>
<ide> function formatWithOptionsInternal(inspectOptions, args) {
<ide> const first = args[0];
<ide> let a = 0;
<ide> function formatWithOptionsInternal(inspectOptions, args) {
<ide> case 115: // 's'
<ide> const tempArg = args[++a];
<ide> if (typeof tempArg === 'number') {
<del> tempStr = formatNumber(stylizeNoColor, tempArg);
<add> tempStr = formatNumberNoColor(tempArg, inspectOptions);
<ide> } else if (typeof tempArg === 'bigint') {
<del> tempStr = `${tempArg}n`;
<add> tempStr = formatBigIntNoColor(tempArg, inspectOptions);
<ide> } else if (typeof tempArg !== 'object' ||
<ide> tempArg === null ||
<ide> !hasBuiltInToString(tempArg)) {
<ide> function formatWithOptionsInternal(inspectOptions, args) {
<ide> case 100: // 'd'
<ide> const tempNum = args[++a];
<ide> if (typeof tempNum === 'bigint') {
<del> tempStr = `${tempNum}n`;
<add> tempStr = formatBigIntNoColor(tempNum, inspectOptions);
<ide> } else if (typeof tempNum === 'symbol') {
<ide> tempStr = 'NaN';
<ide> } else {
<del> tempStr = formatNumber(stylizeNoColor, Number(tempNum));
<add> tempStr = formatNumberNoColor(Number(tempNum), inspectOptions);
<ide> }
<ide> break;
<ide> case 79: // 'O'
<ide> function formatWithOptionsInternal(inspectOptions, args) {
<ide> case 105: // 'i'
<ide> const tempInteger = args[++a];
<ide> if (typeof tempInteger === 'bigint') {
<del> tempStr = `${tempInteger}n`;
<add> tempStr = formatBigIntNoColor(tempInteger, inspectOptions);
<ide> } else if (typeof tempInteger === 'symbol') {
<ide> tempStr = 'NaN';
<ide> } else {
<del> tempStr = formatNumber(stylizeNoColor,
<del> NumberParseInt(tempInteger));
<add> tempStr = formatNumberNoColor(
<add> NumberParseInt(tempInteger), inspectOptions);
<ide> }
<ide> break;
<ide> case 102: // 'f'
<ide> const tempFloat = args[++a];
<ide> if (typeof tempFloat === 'symbol') {
<ide> tempStr = 'NaN';
<ide> } else {
<del> tempStr = formatNumber(stylizeNoColor,
<del> NumberParseFloat(tempFloat));
<add> tempStr = formatNumberNoColor(
<add> NumberParseFloat(tempFloat), inspectOptions);
<ide> }
<ide> break;
<ide> case 99: // 'c'
<ide><path>test/parallel/test-util-format.js
<ide> assert.strictEqual(
<ide> '1180591620717411303424n 12345678901234567890123n'
<ide> );
<ide>
<add>{
<add> const { numericSeparator } = util.inspect.defaultOptions;
<add> util.inspect.defaultOptions.numericSeparator = true;
<add>
<add> assert.strictEqual(
<add> util.format('%d', 1180591620717411303424),
<add> '1.1805916207174113e+21'
<add> );
<add>
<add> assert.strictEqual(
<add> util.format(
<add> '%d %s %i', 118059162071741130342, 118059162071741130342, 123_123_123),
<add> '118_059_162_071_741_140_000 118_059_162_071_741_140_000 123_123_123'
<add> );
<add>
<add> assert.strictEqual(
<add> util.format(
<add> '%d %s',
<add> 1_180_591_620_717_411_303_424n,
<add> 12_345_678_901_234_567_890_123n
<add> ),
<add> '1_180_591_620_717_411_303_424n 12_345_678_901_234_567_890_123n'
<add> );
<add>
<add> assert.strictEqual(
<add> util.format('%i', 1_180_591_620_717_411_303_424n),
<add> '1_180_591_620_717_411_303_424n'
<add> );
<add>
<add> util.inspect.defaultOptions.numericSeparator = numericSeparator;
<add>}
<ide> // Integer format specifier
<ide> assert.strictEqual(util.format('%i'), '%i');
<ide> assert.strictEqual(util.format('%i', 42.0), '42');
<ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(
<ide> "{ ['__proto__']: { a: 1 } }"
<ide> );
<ide> }
<add>
<add>{
<add> const { numericSeparator } = util.inspect.defaultOptions;
<add> util.inspect.defaultOptions.numericSeparator = true;
<add>
<add> assert.strictEqual(
<add> util.inspect(1234567891234567891234),
<add> '1.234567891234568e+21'
<add> );
<add> assert.strictEqual(
<add> util.inspect(123456789.12345678),
<add> '123_456_789.123_456_78'
<add> );
<add>
<add> assert.strictEqual(util.inspect(10_000_000), '10_000_000');
<add> assert.strictEqual(util.inspect(1_000_000), '1_000_000');
<add> assert.strictEqual(util.inspect(100_000), '100_000');
<add> assert.strictEqual(util.inspect(99_999.9), '99_999.9');
<add> assert.strictEqual(util.inspect(9_999), '9_999');
<add> assert.strictEqual(util.inspect(999), '999');
<add> assert.strictEqual(util.inspect(NaN), 'NaN');
<add> assert.strictEqual(util.inspect(Infinity), 'Infinity');
<add> assert.strictEqual(util.inspect(-Infinity), '-Infinity');
<add>
<add> assert.strictEqual(
<add> util.inspect(new Float64Array([100_000_000])),
<add> 'Float64Array(1) [ 100_000_000 ]'
<add> );
<add> assert.strictEqual(
<add> util.inspect(new BigInt64Array([9_100_000_100n])),
<add> 'BigInt64Array(1) [ 9_100_000_100n ]'
<add> );
<add>
<add> assert.strictEqual(
<add> util.inspect(123456789),
<add> '123_456_789'
<add> );
<add> assert.strictEqual(
<add> util.inspect(123456789n),
<add> '123_456_789n'
<add> );
<add>
<add> util.inspect.defaultOptions.numericSeparator = numericSeparator;
<add>
<add> assert.strictEqual(
<add> util.inspect(123456789.12345678, { numericSeparator: true }),
<add> '123_456_789.123_456_78'
<add> );
<add>} | 4 |
Ruby | Ruby | remove defunct ivars | 588c321e74b67b1ede87446cda818b9060efb48c | <ide><path>activerecord/lib/active_record/associations/join_dependency/join_part.rb
<ide> class JoinPart # :nodoc:
<ide>
<ide> def initialize(base_klass, children)
<ide> @base_klass = base_klass
<del> @column_names_with_alias = nil
<ide> @children = children
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/model_schema.rb
<ide> def reset_column_information
<ide> undefine_attribute_methods
<ide> connection.schema_cache.clear_table_cache!(table_name) if table_exists?
<ide>
<del> @arel_engine = nil
<del> @column_names = nil
<del> @column_types = nil
<del> @content_columns = nil
<del> @default_attributes = nil
<del> @dynamic_methods_hash = nil
<del> @inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
<del> @relation = nil
<del> @time_zone_column_names = nil
<del> @cached_time_zone = nil
<add> @arel_engine = nil
<add> @column_names = nil
<add> @column_types = nil
<add> @content_columns = nil
<add> @default_attributes = nil
<add> @inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
<add> @relation = nil
<ide> end
<ide>
<ide> private | 2 |
Go | Go | add windows specific exec root for plugins | 26517a01610215d218ad7236a5b5d44539220d12 | <ide><path>daemon/daemon.go
<ide> func NewDaemon(config *Config, registryService registry.Service, containerdRemot
<ide> // Plugin system initialization should happen before restore. Do not change order.
<ide> d.pluginManager, err = plugin.NewManager(plugin.ManagerConfig{
<ide> Root: filepath.Join(config.Root, "plugins"),
<del> ExecRoot: "/run/docker/plugins", // possibly needs fixing
<add> ExecRoot: getPluginExecRoot(config.Root),
<ide> Store: d.PluginStore,
<ide> Executor: containerdRemote,
<ide> RegistryService: registryService,
<ide><path>daemon/daemon_linux.go
<ide> import (
<ide> "github.com/docker/docker/pkg/mount"
<ide> )
<ide>
<add>// On Linux, plugins use a static path for storing execution state,
<add>// instead of deriving path from daemon's exec-root. This is because
<add>// plugin socket files are created here and they cannot exceed max
<add>// path length of 108 bytes.
<add>func getPluginExecRoot(root string) string {
<add> return "/run/docker/plugins"
<add>}
<add>
<ide> func (daemon *Daemon) cleanupMountsByID(id string) error {
<ide> logrus.Debugf("Cleaning up old mountid %s: start.", id)
<ide> f, err := os.Open("/proc/self/mountinfo")
<ide><path>daemon/daemon_windows.go
<ide> package daemon
<ide> import (
<ide> "fmt"
<ide> "os"
<add> "path/filepath"
<ide> "strings"
<ide>
<ide> "github.com/Microsoft/hcsshim"
<ide> const (
<ide> windowsMinCPUCount = 1
<ide> )
<ide>
<add>// Windows has no concept of an execution state directory. So use config.Root here.
<add>func getPluginExecRoot(root string) string {
<add> return filepath.Join(root, "plugins")
<add>}
<add>
<ide> func getBlkioWeightDevices(config *containertypes.HostConfig) ([]blkiodev.WeightDevice, error) {
<ide> return nil, nil
<ide> } | 3 |
Text | Text | fix minor typos in the blog post | 89538d44a957cc5b4470fe37376cfcaa05dfb2f1 | <ide><path>docs/_posts/2015-12-18-react-components-elements-and-instances.md
<ide> The difference between **components, their instances, and elements** confuses ma
<ide>
<ide> If you’re new to React, you probably only worked with component classes and instances before. For example, you may declare a `Button` *component* by creating a class. When the app is running, you may have several *instances* of this component on screen, each with its own properties and local state. This is the traditional object-oriented UI programming. Why introduce *elements*?
<ide>
<del>In this traditional UI model, it is up to you take care of creating and destroying child component instances. If a `Form` component wants to render a `Button` component, it needs to create its instance, and manually keep it up to date with any new information.
<add>In this traditional UI model, it is up to you to take care of creating and destroying child component instances. If a `Form` component wants to render a `Button` component, it needs to create its instance, and manually keep it up to date with any new information.
<ide>
<ide> ```js
<ide> class Form extends TraditionalObjectOrientedView {
<ide> const DeleteAccount = () => (
<ide> );
<ide> ```
<ide>
<del>This mix and matching helps keep components decoupled from each other, as they can express both *is-a* () and *has-a* relationships exclusively through composition:
<add>This mix and matching helps keep components decoupled from each other, as they can express both *is-a* and *has-a* relationships exclusively through composition:
<ide>
<ide> * `Button` is a DOM `<button>` with specific properties.
<ide> * `DangerButton` is a `Button` with specific properties. | 1 |
Text | Text | change os x to macos in readme | 5a3e0664d261422f11a78faaf101d70c73b3a5a8 | <ide><path>README.md
<ide> To build jQuery, you need to have the latest Node.js/npm and git 1.7 or later. E
<ide>
<ide> For Windows, you have to download and install [git](https://git-scm.com/downloads) and [Node.js](https://nodejs.org/en/download/).
<ide>
<del>OS X users should install [Homebrew](https://brew.sh/). Once Homebrew is installed, run `brew install git` to install git,
<add>macOS users should install [Homebrew](https://brew.sh/). Once Homebrew is installed, run `brew install git` to install git,
<ide> and `brew install node` to install Node.js.
<ide>
<ide> Linux/BSD users should use their appropriate package managers to install git and Node.js, or build from source | 1 |
Text | Text | add notes about negative offsets in buffer.md | 2de67343a1bcf846fcf9a6ef14e569143f0f3863 | <ide><path>doc/api/buffer.md
<ide> added: v5.3.0
<ide> -->
<ide>
<ide> * `value` {string|Buffer|Uint8Array|integer} What to search for.
<del>* `byteOffset` {integer} Where to begin searching in `buf`. **Default:** `0`.
<add>* `byteOffset` {integer} Where to begin searching in `buf`. If negative, then
<add> offset is calculated from the end of `buf`. **Default:** `0`.
<ide> * `encoding` {string} If `value` is a string, this is its encoding.
<ide> **Default:** `'utf8'`.
<ide> * Returns: {boolean} `true` if `value` was found in `buf`, `false` otherwise.
<ide> changes:
<ide> -->
<ide>
<ide> * `value` {string|Buffer|Uint8Array|integer} What to search for.
<del>* `byteOffset` {integer} Where to begin searching in `buf`. **Default:** `0`.
<add>* `byteOffset` {integer} Where to begin searching in `buf`. If negative, then
<add> offset is calculated from the end of `buf`. **Default:** `0`.
<ide> * `encoding` {string} If `value` is a string, this is the encoding used to
<ide> determine the binary representation of the string that will be searched for in
<ide> `buf`. **Default:** `'utf8'`.
<ide> changes:
<ide> -->
<ide>
<ide> * `value` {string|Buffer|Uint8Array|integer} What to search for.
<del>* `byteOffset` {integer} Where to begin searching in `buf`.
<del> **Default:** [`buf.length`]` - 1`.
<add>* `byteOffset` {integer} Where to begin searching in `buf`. If negative, then
<add> offset is calculated from the end of `buf`. **Default:**
<add> [`buf.length`]` - 1`.
<ide> * `encoding` {string} If `value` is a string, this is the encoding used to
<ide> determine the binary representation of the string that will be searched for in
<ide> `buf`. **Default:** `'utf8'`. | 1 |
Javascript | Javascript | reuse mixin array build logic | 80c11595d506cf1dafae565f7889137085aead9c | <ide><path>packages/ember-metal/lib/mixin.js
<ide> export function mixin(obj, ...args) {
<ide> export default class Mixin {
<ide> constructor(mixins, properties) {
<ide> this.properties = properties;
<del>
<del> let length = mixins && mixins.length;
<del>
<del> if (length > 0) {
<del> let m = new Array(length);
<del>
<del> for (let i = 0; i < length; i++) {
<del> let x = mixins[i];
<del> if (x instanceof Mixin) {
<del> m[i] = x;
<del> } else {
<del> m[i] = new Mixin(undefined, x);
<del> }
<del> }
<del>
<del> this.mixins = m;
<del> } else {
<del> this.mixins = undefined;
<del> }
<add> this.mixins = buildMixinsArray(mixins);
<ide> this.ownerConstructor = undefined;
<ide> this._without = undefined;
<ide> this[NAME_KEY] = null;
<ide> export default class Mixin {
<ide> @param arguments*
<ide> @private
<ide> */
<del> reopen() {
<del> let currentMixin;
<add> reopen(...args) {
<add> if (args.length === 0) { return; }
<ide>
<ide> if (this.properties) {
<del> currentMixin = new Mixin(undefined, this.properties);
<add> let currentMixin = new Mixin(undefined, this.properties);
<ide> this.properties = undefined;
<ide> this.mixins = [currentMixin];
<ide> } else if (!this.mixins) {
<ide> this.mixins = [];
<ide> }
<ide>
<del> let mixins = this.mixins;
<del> let idx;
<del>
<del> for (idx = 0; idx < arguments.length; idx++) {
<del> currentMixin = arguments[idx];
<del> assert(
<del> `Expected hash or Mixin instance, got ${Object.prototype.toString.call(currentMixin)}`,
<del> typeof currentMixin === 'object' && currentMixin !== null &&
<del> Object.prototype.toString.call(currentMixin) !== '[object Array]'
<del> );
<del>
<del> if (currentMixin instanceof Mixin) {
<del> mixins.push(currentMixin);
<del> } else {
<del> mixins.push(new Mixin(undefined, currentMixin));
<del> }
<del> }
<del>
<add> this.mixins = this.mixins.concat(buildMixinsArray(args));
<ide> return this;
<ide> }
<ide>
<ide> export default class Mixin {
<ide>
<ide> }
<ide>
<add>function buildMixinsArray(mixins) {
<add> let length = mixins && mixins.length;
<add> let m;
<add>
<add> if (length > 0) {
<add> m = new Array(length);
<add> for (let i = 0; i < length; i++) {
<add> let x = mixins[i];
<add> assert(
<add> `Expected hash or Mixin instance, got ${Object.prototype.toString.call(x)}`,
<add> typeof x === 'object' && x !== null && Object.prototype.toString.call(x) !== '[object Array]'
<add> );
<add>
<add> if (x instanceof Mixin) {
<add> m[i] = x;
<add> } else {
<add> m[i] = new Mixin(undefined, x);
<add> }
<add> }
<add> }
<add>
<add> return m;
<add>}
<add>
<ide> if (ENV._ENABLE_BINDING_SUPPORT) {
<ide> // slotting this so that the legacy addon can add the function here
<ide> // without triggering an error due to the Object.seal done below | 1 |
PHP | PHP | fix all warnings except todo warnings | 56225bcca3aca9959d072641aef7639390f119af | <ide><path>lib/Cake/Console/Command/ConsoleShell.php
<ide> public function main($command = null) {
<ide>
<ide> if ($this->_isValidModel($modelToCheck)) {
<ide> $findCommand = "\$data = \$this->$command;";
<add> //@codingStandardsIgnoreStart
<ide> @eval($findCommand);
<add> //@codingStandardsIgnoreEnd
<ide>
<ide> if (is_array($data)) {
<ide> foreach ($data as $idx => $results) {
<ide> public function main($command = null) {
<ide> list($foo, $data) = explode("->save", $command);
<ide> $data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
<ide> $saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
<add> //@codingStandardsIgnoreStart
<ide> @eval($saveCommand);
<add> //@codingStandardsIgnoreEnd
<ide> $this->out(__d('cake_console', 'Saved record for %s', $modelToSave));
<ide> }
<ide> break;
<ide> public function main($command = null) {
<ide> if ($this->_isValidModel($modelToCheck)) {
<ide> // Get the column info for this model
<ide> $fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
<add> //@codingStandardsIgnoreStart
<ide> @eval($fieldsCommand);
<add> //@codingStandardsIgnoreEnd
<ide>
<ide> if (is_array($data)) {
<ide> foreach ($data as $field => $type) {
<ide> public function main($command = null) {
<ide> $this->out(print_r(Hash::combine(Router::$routes, '{n}.template', '{n}.defaults'), true));
<ide> break;
<ide> case (preg_match("/^route\s+(\(.*\))$/i", $command, $tmp) == true):
<add> //@codingStandardsIgnoreStart
<ide> if ($url = eval('return array' . $tmp[1] . ';')) {
<add> //@codingStandardsIgnoreEnd
<ide> $this->out(Router::url($url));
<ide> }
<ide> break;
<ide> protected function _loadRoutes() {
<ide> Router::reload();
<ide> extract(Router::getNamedExpressions());
<ide>
<add> //@codingStandardsIgnoreStart
<ide> if (!@include APP . 'Config' . DS . 'routes.php') {
<add> //@codingStandardsIgnoreEnd
<ide> return false;
<ide> }
<ide> CakePlugin::routes();
<ide><path>lib/Cake/Console/Shell.php
<ide> public function createFile($path, $contents) {
<ide> protected function _checkUnitTest() {
<ide> if (class_exists('PHPUnit_Framework_TestCase')) {
<ide> return true;
<add> //@codingStandardsIgnoreStart
<ide> } elseif (@include 'PHPUnit' . DS . 'Autoload.php') {
<add> //@codingStandardsIgnoreEnd
<ide> return true;
<ide> } elseif (App::import('Vendor', 'phpunit', array('file' => 'PHPUnit' . DS . 'Autoload.php'))) {
<ide> return true;
<ide><path>lib/Cake/Error/exceptions.php
<ide> class MissingControllerException extends CakeException {
<ide>
<ide> protected $_messageTemplate = 'Controller class %s could not be found.';
<ide>
<add>//@codingStandardsIgnoreStart
<ide> public function __construct($message, $code = 404) {
<ide> parent::__construct($message, $code);
<ide> }
<add>//@codingStandardsIgnoreEnd
<ide>
<ide> }
<ide>
<ide> class MissingActionException extends CakeException {
<ide>
<ide> protected $_messageTemplate = 'Action %s::%s() could not be found.';
<ide>
<add>//@codingStandardsIgnoreStart
<ide> public function __construct($message, $code = 404) {
<ide> parent::__construct($message, $code);
<ide> }
<add>//@codingStandardsIgnoreEnd
<ide>
<ide> }
<ide>
<ide> class PrivateActionException extends CakeException {
<ide>
<ide> protected $_messageTemplate = 'Private Action %s::%s() is not directly accessible.';
<ide>
<add>//@codingStandardsIgnoreStart
<ide> public function __construct($message, $code = 404, Exception $previous = null) {
<ide> parent::__construct($message, $code, $previous);
<ide> }
<add>//@codingStandardsIgnoreEnd
<ide>
<ide> }
<ide>
<ide> class NotImplementedException extends CakeException {
<ide>
<ide> protected $_messageTemplate = '%s is not implemented.';
<ide>
<add>//@codingStandardsIgnoreStart
<ide> public function __construct($message, $code = 501) {
<ide> parent::__construct($message, $code);
<ide> }
<add>//@codingStandardsIgnoreEnd
<ide>
<ide> }
<ide><path>lib/Cake/Model/Datasource/Database/Sqlite.php
<ide> public function column($real) {
<ide>
<ide> $col = strtolower(str_replace(')', '', $real));
<ide> $limit = null;
<del> @list($col, $limit) = explode('(', $col);
<add> if (strpos($col, '(') !== false) {
<add> list($col, $limit) = explode('(', $col);
<add> }
<ide>
<ide> if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
<ide> return $col;
<ide><path>lib/Cake/Network/CakeSocket.php
<ide> public function connect() {
<ide> $scheme = 'ssl://';
<ide> }
<ide>
<add> //@codingStandardsIgnoreStart
<ide> if ($this->config['persistent'] == true) {
<ide> $this->connection = @pfsockopen($scheme . $this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
<ide> } else {
<ide> $this->connection = @fsockopen($scheme . $this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
<ide> }
<add> //@codingStandardsIgnoreEnd
<ide>
<ide> if (!empty($errNum) || !empty($errStr)) {
<ide> $this->setLastError($errNum, $errStr);
<ide><path>lib/Cake/Network/Email/MailTransport.php
<ide> public function send(CakeEmail $email) {
<ide> * @return void
<ide> */
<ide> protected function _mail($to, $subject, $message, $headers, $params = null) {
<add> //@codingStandardsIgnoreStart
<ide> if (!@mail($to, $subject, $message, $headers, $params)) {
<ide> throw new SocketException(__d('cake_dev', 'Could not send email.'));
<ide> }
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide>
<ide> }
<ide><path>lib/Cake/Test/Case/BasicsTest.php
<ide> public function testCache() {
<ide>
<ide> $result = cache('basics_test');
<ide> $this->assertEquals('simple cache write', $result);
<del> @unlink(CACHE . 'basics_test');
<add> if (file_exists(CACHE . 'basics_test')) {
<add> unlink(CACHE . 'basics_test');
<add> }
<ide>
<ide> cache('basics_test', 'expired', '+1 second');
<ide> sleep(2);
<ide> public function testTranslateDomainCategoryPlural() {
<ide> * @return void
<ide> */
<ide> public function testLogError() {
<del> @unlink(LOGS . 'error.log');
<add> if (file_exists(LOGS . 'error.log')) {
<add> unlink(LOGS . 'error.log');
<add> }
<ide>
<ide> // disable stderr output for this test
<ide> if (CakeLog::stream('stderr')) {
<ide><path>lib/Cake/Test/Case/Cache/Engine/MemcacheEngineTest.php
<ide> public function testMultipleServers() {
<ide>
<ide> foreach ($servers as $server) {
<ide> list($host, $port) = explode(':', $server);
<add> //@codingStandardsIgnoreStart
<ide> if (!@$Memcache->connect($host, $port)) {
<ide> $available = false;
<ide> }
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide>
<ide> $this->skipIf(!$available, 'Need memcache servers at ' . implode(', ', $servers) . ' to run this test.');
<ide><path>lib/Cake/Test/Case/Core/ConfigureTest.php
<ide> public function testDump() {
<ide> $result = file_get_contents(TMP . 'config_test.php');
<ide> $this->assertContains('<?php', $result);
<ide> $this->assertContains('$config = ', $result);
<del> @unlink(TMP . 'config_test.php');
<add> if (file_exists(TMP . 'config_test.php')) {
<add> unlink(TMP . 'config_test.php');
<add> }
<ide> }
<ide>
<ide> /**
<ide> public function testDumpPartial() {
<ide> $this->assertContains('Error', $result);
<ide> $this->assertNotContains('debug', $result);
<ide>
<del> @unlink(TMP . 'config_test.php');
<add> if (file_exists(TMP . 'config_test.php')) {
<add> unlink(TMP . 'config_test.php');
<add> }
<ide> }
<ide>
<ide> }
<ide><path>lib/Cake/Test/Case/Error/ErrorHandlerTest.php
<ide> public function testErrorSuppressed() {
<ide> $this->_restoreError = true;
<ide>
<ide> ob_start();
<add> //@codingStandardsIgnoreStart
<ide> @include 'invalid.file';
<add> //@codingStandardsIgnoreEnd
<ide> $result = ob_get_clean();
<ide> $this->assertTrue(empty($result));
<ide> }
<ide> public function testHandleErrorDebugOff() {
<ide> Configure::write('debug', 0);
<ide> Configure::write('Error.trace', false);
<ide> if (file_exists(LOGS . 'debug.log')) {
<del> @unlink(LOGS . 'debug.log');
<add> unlink(LOGS . 'debug.log');
<ide> }
<ide>
<ide> set_error_handler('ErrorHandler::handleError');
<ide> public function testHandleErrorDebugOff() {
<ide> '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} (Notice|Debug): Notice \(8\): Undefined variable:\s+out in \[.+ line \d+\]$/',
<ide> $result[0]
<ide> );
<del> @unlink(LOGS . 'debug.log');
<add> if (file_exists(LOGS . 'debug.log')) {
<add> unlink(LOGS . 'debug.log');
<add> }
<ide> }
<ide>
<ide> /**
<ide> public function testHandleErrorLoggingTrace() {
<ide> Configure::write('debug', 0);
<ide> Configure::write('Error.trace', true);
<ide> if (file_exists(LOGS . 'debug.log')) {
<del> @unlink(LOGS . 'debug.log');
<add> unlink(LOGS . 'debug.log');
<ide> }
<ide>
<ide> set_error_handler('ErrorHandler::handleError');
<ide> public function testHandleErrorLoggingTrace() {
<ide> );
<ide> $this->assertRegExp('/^Trace:/', $result[1]);
<ide> $this->assertRegExp('/^ErrorHandlerTest\:\:testHandleErrorLoggingTrace\(\)/', $result[2]);
<del> @unlink(LOGS . 'debug.log');
<add> if (file_exists(LOGS . 'debug.log')) {
<add> unlink(LOGS . 'debug.log');
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Log/CakeLogTest.php
<ide> public function testConfig() {
<ide> $this->assertEquals(array('file'), $result);
<ide>
<ide> if (file_exists(LOGS . 'error.log')) {
<del> @unlink(LOGS . 'error.log');
<add> unlink(LOGS . 'error.log');
<ide> }
<ide> CakeLog::write(LOG_WARNING, 'Test warning');
<ide> $this->assertTrue(file_exists(LOGS . 'error.log'));
<ide><path>lib/Cake/Test/Case/View/Helper/JsHelperTest.php
<ide> class JsEncodingObject {
<ide>
<ide> protected $_title = 'Old thing';
<ide>
<add> //@codingStandardsIgnoreStart
<ide> private $__noshow = 'Never ever';
<add> //@codingStandardsIgnoreEnd
<ide>
<ide> }
<ide>
<ide> public function testWriteScriptsInFile() {
<ide> $this->assertTrue(file_exists(WWW_ROOT . $filename[1]));
<ide> $contents = file_get_contents(WWW_ROOT . $filename[1]);
<ide> $this->assertRegExp('/one\s=\s1;\ntwo\s=\s2;/', $contents);
<del> @unlink(WWW_ROOT . $filename[1]);
<add> if (file_exists(WWW_ROOT . $filename[1])) {
<add> unlink(WWW_ROOT . $filename[1]);
<add> }
<ide>
<ide> Configure::write('Cache.disable', true);
<ide> $this->Js->buffer('one = 1;');
<ide><path>lib/Cake/Test/Case/View/ViewTest.php
<ide> public function testRenderCache() {
<ide>
<ide> $this->assertRegExp('/^some cacheText/', $result);
<ide>
<del> @unlink($path);
<add> if (file_exists($path)) {
<add> unlink($path);
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/TestSuite/CakeTestSuiteCommand.php
<ide> public function run(array $argv, $exit = true) {
<ide> $result = $skeleton->generate(true);
<ide>
<ide> if (!$result['incomplete']) {
<add> //@codingStandardsIgnoreStart
<ide> eval(str_replace(array('<?php', '?>'), '', $result['code']));
<add> //@codingStandardsIgnoreEnd
<ide> $suite = new PHPUnit_Framework_TestSuite(
<ide> $this->arguments['test'] . 'Test'
<ide> );
<ide><path>lib/Cake/TestSuite/ControllerTestCase.php
<ide> abstract class ControllerTestCase extends CakeTestCase {
<ide> *
<ide> * @var boolean
<ide> */
<del> private $__dirtyController = false;
<add> protected $_dirtyController = false;
<ide>
<ide> /**
<ide> * Used to enable calling ControllerTestCase::testAction() without the testing
<ide> protected function _testAction($url = '', $options = array()) {
<ide> $this->headers = Router::currentRoute()->response->header();
<ide> return;
<ide> }
<del> if ($this->__dirtyController) {
<add> if ($this->_dirtyController) {
<ide> $this->controller = null;
<ide> }
<ide>
<ide> protected function _testAction($url = '', $options = array()) {
<ide> if (isset($this->controller->View)) {
<ide> $this->view = $this->controller->View->fetch('__view_no_layout__');
<ide> }
<del> $this->__dirtyController = true;
<add> $this->_dirtyController = true;
<ide> $this->headers = $Dispatch->response->header();
<ide>
<ide> $_GET = $restore['get'];
<ide> public function generate($controller, $mocks = array()) {
<ide> }
<ide>
<ide> $_controller->constructClasses();
<del> $this->__dirtyController = false;
<add> $this->_dirtyController = false;
<ide>
<ide> $this->controller = $_controller;
<ide> return $this->controller;
<ide><path>lib/Cake/Utility/Debugger.php
<ide> public static function excerpt($file, $line, $context = 2) {
<ide> if (!file_exists($file)) {
<ide> return array();
<ide> }
<del> $data = @explode("\n", file_get_contents($file));
<add> $data = file_get_contents($file);
<add> if (!empty($data) && strpos($data, "\n") !== false) {
<add> $data = explode("\n", $data);
<add> }
<ide>
<ide> if (empty($data) || !isset($data[$line])) {
<ide> return;
<ide><path>lib/Cake/Utility/Folder.php
<ide> public function chmod($path, $mode = false, $recursive = true, $exceptions = arr
<ide> }
<ide>
<ide> if ($recursive === false && is_dir($path)) {
<add> //@codingStandardsIgnoreStart
<ide> if (@chmod($path, intval($mode, 8))) {
<add> //@codingStandardsIgnoreEnd
<ide> $this->_messages[] = __d('cake_dev', '%s changed to %s', $path, $mode);
<ide> return true;
<ide> }
<ide> public function chmod($path, $mode = false, $recursive = true, $exceptions = arr
<ide> continue;
<ide> }
<ide>
<add> //@codingStandardsIgnoreStart
<ide> if (@chmod($fullpath, intval($mode, 8))) {
<add> //@codingStandardsIgnoreEnd
<ide> $this->_messages[] = __d('cake_dev', '%s changed to %s', $fullpath, $mode);
<ide> } else {
<ide> $this->_errors[] = __d('cake_dev', '%s NOT changed to %s', $fullpath, $mode);
<ide> public function delete($path = null) {
<ide> foreach ($iterator as $item) {
<ide> $filePath = $item->getPathname();
<ide> if ($item->isFile() || $item->isLink()) {
<add> //@codingStandardsIgnoreStart
<ide> if (@unlink($filePath)) {
<add> //@codingStandardsIgnoreEnd
<ide> $this->_messages[] = __d('cake_dev', '%s removed', $filePath);
<ide> } else {
<ide> $this->_errors[] = __d('cake_dev', '%s NOT removed', $filePath);
<ide> }
<ide> } elseif ($item->isDir() && !$item->isDot()) {
<add> //@codingStandardsIgnoreStart
<ide> if (@rmdir($filePath)) {
<add> //@codingStandardsIgnoreEnd
<ide> $this->_messages[] = __d('cake_dev', '%s removed', $filePath);
<ide> } else {
<ide> $this->_errors[] = __d('cake_dev', '%s NOT removed', $filePath);
<ide> public function delete($path = null) {
<ide> }
<ide>
<ide> $path = rtrim($path, DS);
<add> //@codingStandardsIgnoreStart
<ide> if (@rmdir($path)) {
<add> //@codingStandardsIgnoreEnd
<ide> $this->_messages[] = __d('cake_dev', '%s removed', $path);
<ide> } else {
<ide> $this->_errors[] = __d('cake_dev', '%s NOT removed', $path);
<ide> public function copy($options = array()) {
<ide> }
<ide>
<ide> $exceptions = array_merge(array('.', '..', '.svn'), $options['skip']);
<add> //@codingStandardsIgnoreStart
<ide> if ($handle = @opendir($fromDir)) {
<add> //@codingStandardsIgnoreEnd
<ide> while (false !== ($item = readdir($handle))) {
<ide> if (!in_array($item, $exceptions)) {
<ide> $from = Folder::addPathElement($fromDir, $item);
<ide><path>lib/Cake/View/Helper.php
<ide> public function assetTimestamp($path) {
<ide> $filepath = preg_replace('/^' . preg_quote($this->request->webroot, '/') . '/', '', $path);
<ide> $webrootPath = WWW_ROOT . str_replace('/', DS, $filepath);
<ide> if (file_exists($webrootPath)) {
<add> //@codingStandardsIgnoreStart
<ide> return $path . '?' . @filemtime($webrootPath);
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide> $segments = explode('/', ltrim($filepath, '/'));
<ide> if ($segments[0] === 'theme') {
<ide> $theme = $segments[1];
<ide> unset($segments[0], $segments[1]);
<ide> $themePath = App::themePath($theme) . 'webroot' . DS . implode(DS, $segments);
<add> //@codingStandardsIgnoreStart
<ide> return $path . '?' . @filemtime($themePath);
<add> //@codingStandardsIgnoreEnd
<ide> } else {
<ide> $plugin = Inflector::camelize($segments[0]);
<ide> if (CakePlugin::loaded($plugin)) {
<ide> unset($segments[0]);
<ide> $pluginPath = CakePlugin::path($plugin) . 'webroot' . DS . implode(DS, $segments);
<add> //@codingStandardsIgnoreStart
<ide> return $path . '?' . @filemtime($pluginPath);
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide> }
<ide> }
<ide><path>lib/Cake/View/MediaView.php
<ide> public function render($view = null, $layout = null) {
<ide>
<ide> if ($this->_isActive()) {
<ide> $extension = strtolower($extension);
<add> //@codingStandardsIgnoreStart
<ide> $fileSize = @filesize($path);
<add> //@codingStandardsIgnoreEnd
<ide> $handle = fopen($path, 'rb');
<ide>
<ide> if ($handle === false) {
<ide> protected function _isActive() {
<ide> * @return boolean
<ide> */
<ide> protected function _clearBuffer() {
<add> //@codingStandardsIgnoreStart
<ide> return @ob_end_clean();
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide>
<ide> /**
<ide> protected function _clearBuffer() {
<ide> * @return void
<ide> */
<ide> protected function _flushBuffer() {
<add> //@codingStandardsIgnoreStart
<ide> @flush();
<ide> @ob_flush();
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide>
<ide> }
<ide><path>lib/Cake/View/View.php
<ide> public function renderCache($filename, $timeStart) {
<ide>
<ide> if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
<ide> if (time() >= $match['1']) {
<add> //@codingStandardsIgnoreStart
<ide> @unlink($filename);
<add> //@codingStandardsIgnoreEnd
<ide> unset ($out);
<ide> return false;
<ide> } else {
<ide><path>lib/Cake/basics.php
<ide> function cache($path, $data = null, $expires = '+1 day', $target = 'cache') {
<ide> $filetime = false;
<ide>
<ide> if (file_exists($filename)) {
<add> //@codingStandardsIgnoreStart
<ide> $filetime = @filemtime($filename);
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide>
<ide> if ($data === null) {
<ide> if (file_exists($filename) && $filetime !== false) {
<ide> if ($filetime + $timediff < $now) {
<add> //@codingStandardsIgnoreStart
<ide> @unlink($filename);
<add> //@codingStandardsIgnoreEnd
<ide> } else {
<add> //@codingStandardsIgnoreStart
<ide> $data = @file_get_contents($filename);
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide> }
<ide> } elseif (is_writable(dirname($filename))) {
<add> //@codingStandardsIgnoreStart
<ide> @file_put_contents($filename, $data, LOCK_EX);
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide> return $data;
<ide> }
<ide> function clearCache($params = null, $type = 'views', $ext = '.php') {
<ide> $cache = CACHE . $type . DS . $params;
<ide>
<ide> if (is_file($cache . $ext)) {
<add> //@codingStandardsIgnoreStart
<ide> @unlink($cache . $ext);
<add> //@codingStandardsIgnoreEnd
<ide> return true;
<ide> } elseif (is_dir($cache)) {
<ide> $files = glob($cache . '*');
<ide> function clearCache($params = null, $type = 'views', $ext = '.php') {
<ide>
<ide> foreach ($files as $file) {
<ide> if (is_file($file) && strrpos($file, DS . 'empty') !== strlen($file) - 6) {
<add> //@codingStandardsIgnoreStart
<ide> @unlink($file);
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide> }
<ide> return true;
<ide> function clearCache($params = null, $type = 'views', $ext = '.php') {
<ide> }
<ide> foreach ($files as $file) {
<ide> if (is_file($file) && strrpos($file, DS . 'empty') !== strlen($file) - 6) {
<add> //@codingStandardsIgnoreStart
<ide> @unlink($file);
<add> //@codingStandardsIgnoreEnd
<ide> }
<ide> }
<ide> return true; | 21 |
Java | Java | remove references to asyncconfigurersupport | b06d267232f3951e4d4bdbfbb04c4ce1d83f3b8c | <ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncConfigurer.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2021 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> * {@link AsyncUncaughtExceptionHandler} instance used to process exception thrown from
<ide> * async method with {@code void} return type.
<ide> *
<del> * <p>Consider using {@link AsyncConfigurerSupport} providing default implementations for
<del> * both methods if only one element needs to be customized. Furthermore, backward compatibility
<del> * of this interface will be insured in case new customization options are introduced
<del> * in the future.
<del> *
<ide> * <p>See @{@link EnableAsync} for usage examples.
<ide> *
<ide> * @author Chris Beams
<ide> * @author Stephane Nicoll
<ide> * @since 3.1
<ide> * @see AbstractAsyncConfiguration
<ide> * @see EnableAsync
<del> * @see AsyncConfigurerSupport
<ide> */
<ide> public interface AsyncConfigurer {
<ide>
<ide><path>spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 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 void handleExceptionWithListenableFuture() {
<ide> private void assertFutureWithException(Future<Object> result,
<ide> TestableAsyncUncaughtExceptionHandler exceptionHandler) {
<ide> assertThatExceptionOfType(ExecutionException.class).isThrownBy(
<del> result::get)
<del> .withCauseExactlyInstanceOf(UnsupportedOperationException.class);
<add> result::get)
<add> .withCauseExactlyInstanceOf(UnsupportedOperationException.class);
<ide> assertThat(exceptionHandler.isCalled()).as("handler should never be called with Future return type").isFalse();
<ide> }
<ide>
<ide> public void execute(Runnable r) {
<ide>
<ide> @Configuration
<ide> @EnableAsync
<del> static class ConfigWithExceptionHandler extends AsyncConfigurerSupport {
<add> static class ConfigWithExceptionHandler implements AsyncConfigurer {
<ide>
<ide> @Bean
<ide> public ITestBean target() {
<ide><path>spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerIntegrationTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.scheduling.annotation.Async;
<del>import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
<add>import org.springframework.scheduling.annotation.AsyncConfigurer;
<ide> import org.springframework.scheduling.annotation.EnableAsync;
<ide> import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
<ide> import org.springframework.stereotype.Component;
<ide> public class EventPublishingTestExecutionListenerIntegrationTests {
<ide> private static final CountDownLatch countDownLatch = new CountDownLatch(1);
<ide>
<ide> private final TestContextManager testContextManager = new TestContextManager(ExampleTestCase.class);
<add>
<ide> private final TestContext testContext = testContextManager.getTestContext();
<add>
<ide> // Note that the following invocation of getApplicationContext() forces eager
<ide> // loading of the test's ApplicationContext which consequently results in the
<ide> // publication of all test execution events. Otherwise, TestContext#publishEvent
<ide> // would never fire any events for ExampleTestCase.
<ide> private final TestExecutionListener listener = testContext.getApplicationContext().getBean(TestExecutionListener.class);
<add>
<ide> private final Object testInstance = new ExampleTestCase();
<add>
<ide> private final Method traceableTestMethod = ReflectionUtils.findMethod(ExampleTestCase.class, "traceableTest");
<ide>
<ide>
<ide> public void beforeTestMethodAnnotationWithFailingCondition() throws Exception {
<ide> public void beforeTestMethodAnnotationWithFailingEventListener() throws Exception {
<ide> Method method = ReflectionUtils.findMethod(ExampleTestCase.class, "testWithFailingEventListener");
<ide> assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
<del> testContextManager.beforeTestMethod(testInstance, method))
<del> .withMessageContaining("Boom!");
<add> testContextManager.beforeTestMethod(testInstance, method))
<add> .withMessageContaining("Boom!");
<ide> verify(listener, only()).beforeTestMethod(testContext);
<ide> }
<ide>
<ide> public void beforeTestMethodAnnotationWithFailingAsyncEventListener() throws Exc
<ide>
<ide> verify(listener, only()).beforeTestMethod(testContext);
<ide> assertThat(TrackingAsyncUncaughtExceptionHandler.asyncException.getMessage())
<del> .startsWith("Asynchronous exception for test method [" + methodName + "] in thread [" + THREAD_NAME_PREFIX);
<add> .startsWith("Asynchronous exception for test method [" + methodName + "] in thread [" + THREAD_NAME_PREFIX);
<ide> }
<ide>
<ide> @Test
<ide> public void testWithFailingAsyncEventListener() {
<ide>
<ide> @Configuration
<ide> @EnableAsync(proxyTargetClass = true)
<del> static class TestEventListenerConfiguration extends AsyncConfigurerSupport {
<add> static class TestEventListenerConfiguration implements AsyncConfigurer {
<ide>
<ide> @Override
<ide> public Executor getAsyncExecutor() {
<ide> static class AsyncTestEventComponent {
<ide> public void beforeTestMethodWithAsyncFailure(BeforeTestMethodEvent event) throws Exception {
<ide> this.listener.beforeTestMethod(event.getSource());
<ide> throw new RuntimeException(String.format("Asynchronous exception for test method [%s] in thread [%s]",
<del> event.getTestContext().getTestMethod().getName(), Thread.currentThread().getName()));
<add> event.getTestContext().getTestMethod().getName(), Thread.currentThread().getName()));
<ide> }
<ide>
<ide> } | 3 |
Javascript | Javascript | remove timermixin on reactcontentsizeupdatetest | 4d6943168b427d70a2bf16212fef690863504e94 | <ide><path>IntegrationTests/ReactContentSizeUpdateTest.js
<ide> const createReactClass = require('create-react-class');
<ide> const ReactNative = require('react-native');
<ide> const RCTNativeAppEventEmitter = require('RCTNativeAppEventEmitter');
<ide> const Subscribable = require('Subscribable');
<del>const TimerMixin = require('react-timer-mixin');
<ide>
<ide> const {View} = ReactNative;
<ide>
<ide> const newReactViewHeight = 202;
<ide>
<ide> const ReactContentSizeUpdateTest = createReactClass({
<ide> displayName: 'ReactContentSizeUpdateTest',
<del> mixins: [Subscribable.Mixin, TimerMixin],
<add> mixins: [Subscribable.Mixin],
<add> _timeoutID: (null: ?TimeoutID),
<ide>
<ide> UNSAFE_componentWillMount: function() {
<ide> this.addListenerOn(
<ide> const ReactContentSizeUpdateTest = createReactClass({
<ide> },
<ide>
<ide> componentDidMount: function() {
<del> this.setTimeout(() => {
<add> this._timeoutID = setTimeout(() => {
<ide> this.updateViewSize();
<ide> }, 1000);
<ide> },
<ide>
<add> componentWillUnmount: function() {
<add> if (this._timeoutID != null) {
<add> clearTimeout(this._timeoutID);
<add> }
<add> },
<add>
<ide> rootViewDidChangeIntrinsicSize: function(intrinsicSize) {
<ide> if (
<ide> intrinsicSize.height === newReactViewHeight && | 1 |
Python | Python | complete the example | 6879dcd5041a64327d0245263347a91f35e96a95 | <ide><path>numpy/lib/npyio.py
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> ... hello world,11
<ide> ... numpy,5''')
<ide> >>> np.genfromtxt(f, dtype='S12,S12', delimiter=',')
<add> array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')],
<add> dtype=[('f0', 'S12'), ('f1', 'S12')])
<ide>
<ide> """
<ide> if max_rows is not None: | 1 |
Python | Python | fix broken mysql migration | cb70150bf602337f890d59b85ffb1fb9ec90bb26 | <ide><path>airflow/migrations/versions/e959f08ac86c_change_field_in_dagcode_to_mediumtext_.py
<ide> def upgrade(): # noqa: D103
<ide> conn = op.get_bind() # pylint: disable=no-member
<ide> if conn.dialect.name == "mysql":
<del> op.alter_column(table_name='dag_code', column_name='source_code', type_=mysql.MEDIUMTEXT)
<add> op.alter_column(
<add> table_name='dag_code', column_name='source_code', type_=mysql.MEDIUMTEXT, nullable=False
<add> )
<ide>
<ide>
<ide> def downgrade(): # noqa: D103
<ide> conn = op.get_bind() # pylint: disable=no-member
<ide> if conn.dialect.name == "mysql":
<del> op.alter_column(table_name='dag_code', column_name='source_code', type_=mysql.TEXT)
<add> op.alter_column(table_name='dag_code', column_name='source_code', type_=mysql.TEXT, nullable=False) | 1 |
Javascript | Javascript | add express state extentions to app | a0278c114d0193303e045567f1e283c0d0df3382 | <ide><path>server/server.js
<ide> var R = require('ramda'),
<ide> cookieParser = require('cookie-parser'),
<ide> compress = require('compression'),
<ide> session = require('express-session'),
<add> expressState = require('express-state'),
<ide> logger = require('morgan'),
<ide> errorHandler = require('errorhandler'),
<ide> methodOverride = require('method-override'),
<ide> var generateKey =
<ide> * Create Express server.
<ide> */
<ide> var app = loopback();
<add>expressState.extend(app);
<ide> var PassportConfigurator =
<ide> require('loopback-component-passport').PassportConfigurator;
<ide> var passportConfigurator = new PassportConfigurator(app); | 1 |
Go | Go | reduce time for testruntwoconcurrentcontainers | 94f1e574b6469021c7c7fd3cad857a011cf93815 | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunUserNotFound(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) {
<ide> sleepTime := "2"
<del> if daemonPlatform == "windows" {
<del> sleepTime = "20" // Make more reliable on Windows
<del> }
<ide> group := sync.WaitGroup{}
<ide> group.Add(2)
<ide> | 1 |
Ruby | Ruby | install specific bundler version | 2cbbdb51bf3bbe1841a6a382b19932d838fc7d25 | <ide><path>Library/Homebrew/dev-cmd/tests.rb
<ide> def tests
<ide> ENV["GIT_#{role}_DATE"] = "Sun Jan 22 19:59:13 2017 +0000"
<ide> end
<ide>
<del> Homebrew.install_gem_setup_path! "bundler"
<add> # TODO: unpin this version when this error no longer shows:
<add> # bundler-1.15.0/lib/bundler/shared_helpers.rb:25:
<add> # stack level too deep (SystemStackError)
<add> Homebrew.install_gem_setup_path! "bundler", "1.14.6"
<ide> system "bundle", "install" unless quiet_system("bundle", "check")
<ide>
<ide> parallel = true | 1 |
Javascript | Javascript | add addcipherprototypefunctions function | d024c2cda11fd3db79c4846d871c596d41b9998d | <ide><path>lib/internal/crypto/cipher.js
<ide> function Cipheriv(cipher, key, iv, options) {
<ide> createCipherWithIV.call(this, cipher, key, options, true, iv);
<ide> }
<ide>
<del>inherits(Cipheriv, LazyTransform);
<del>
<del>Cipheriv.prototype._transform = Cipher.prototype._transform;
<del>Cipheriv.prototype._flush = Cipher.prototype._flush;
<del>Cipheriv.prototype.update = Cipher.prototype.update;
<del>Cipheriv.prototype.final = Cipher.prototype.final;
<del>Cipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
<del>Cipheriv.prototype.getAuthTag = Cipher.prototype.getAuthTag;
<del>Cipheriv.prototype.setAuthTag = Cipher.prototype.setAuthTag;
<del>Cipheriv.prototype.setAAD = Cipher.prototype.setAAD;
<add>function addCipherPrototypeFunctions(constructor) {
<add> constructor.prototype._transform = Cipher.prototype._transform;
<add> constructor.prototype._flush = Cipher.prototype._flush;
<add> constructor.prototype.update = Cipher.prototype.update;
<add> constructor.prototype.final = Cipher.prototype.final;
<add> constructor.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
<add> constructor.prototype.getAuthTag = Cipher.prototype.getAuthTag;
<add> constructor.prototype.setAuthTag = Cipher.prototype.setAuthTag;
<add> constructor.prototype.setAAD = Cipher.prototype.setAAD;
<add>}
<ide>
<add>inherits(Cipheriv, LazyTransform);
<add>addCipherPrototypeFunctions(Cipheriv);
<ide>
<ide> function Decipher(cipher, password, options) {
<ide> if (!(this instanceof Decipher))
<ide> function Decipher(cipher, password, options) {
<ide> }
<ide>
<ide> inherits(Decipher, LazyTransform);
<del>
<del>Decipher.prototype._transform = Cipher.prototype._transform;
<del>Decipher.prototype._flush = Cipher.prototype._flush;
<del>Decipher.prototype.update = Cipher.prototype.update;
<del>Decipher.prototype.final = Cipher.prototype.final;
<del>Decipher.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
<del>Decipher.prototype.getAuthTag = Cipher.prototype.getAuthTag;
<del>Decipher.prototype.setAuthTag = Cipher.prototype.setAuthTag;
<del>Decipher.prototype.setAAD = Cipher.prototype.setAAD;
<add>addCipherPrototypeFunctions(Decipher);
<ide>
<ide>
<ide> function Decipheriv(cipher, key, iv, options) {
<ide> function Decipheriv(cipher, key, iv, options) {
<ide> }
<ide>
<ide> inherits(Decipheriv, LazyTransform);
<del>
<del>Decipheriv.prototype._transform = Cipher.prototype._transform;
<del>Decipheriv.prototype._flush = Cipher.prototype._flush;
<del>Decipheriv.prototype.update = Cipher.prototype.update;
<del>Decipheriv.prototype.final = Cipher.prototype.final;
<del>Decipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
<del>Decipheriv.prototype.getAuthTag = Cipher.prototype.getAuthTag;
<del>Decipheriv.prototype.setAuthTag = Cipher.prototype.setAuthTag;
<del>Decipheriv.prototype.setAAD = Cipher.prototype.setAAD;
<del>
<add>addCipherPrototypeFunctions(Decipheriv);
<ide>
<ide> module.exports = {
<ide> Cipher, | 1 |
Go | Go | fix fail message in testeventsimageimport | 8fd2b52146b443dd464df5199d79c69047c81eea | <ide><path>integration-cli/docker_cli_events_test.go
<ide> func TestEventsImageImport(t *testing.T) {
<ide> event := strings.TrimSpace(events[len(events)-1])
<ide>
<ide> if !strings.HasSuffix(event, ": import") {
<del> t.Fatalf("Missing pull event - got:%q", event)
<add> t.Fatalf("Missing import event - got:%q", event)
<ide> }
<ide>
<ide> logDone("events - image import is logged") | 1 |
Javascript | Javascript | run worker tests only on supported node versions | 1a2b7751eb1db4028556d9861b92c0dc3dcf635a | <ide><path>test/configCases/worker/node-worker-named/test.filter.js
<add>var supportsWorker = require("../../../helpers/supportsWorker");
<add>
<add>module.exports = function (config) {
<add> return supportsWorker();
<add>};
<ide><path>test/configCases/worker/node-worker/test.filter.js
<add>var supportsWorker = require("../../../helpers/supportsWorker");
<add>
<add>module.exports = function (config) {
<add> return supportsWorker();
<add>};
<ide><path>test/configCases/worker/web-worker/test.filter.js
<add>var supportsWorker = require("../../../helpers/supportsWorker");
<add>
<add>module.exports = function (config) {
<add> return supportsWorker();
<add>};
<ide><path>test/helpers/supportsWorker.js
<add>module.exports = function supportsWebAssembly() {
<add> try {
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> return require("worker_threads") !== "undefined";
<add> } catch (e) {
<add> return false;
<add> }
<add>}; | 4 |
Go | Go | remove comment and b.utilizecache check | 1a5ea50aa81112c745030b3cf421a9baebcdb9f5 | <ide><path>builder/internals.go
<ide> func (b *Builder) runContextCommand(args []string, allowRemote bool, allowDecomp
<ide> if err != nil {
<ide> return err
<ide> }
<del> // If we do not have at least one hash, never use the cache
<del> if hit && b.UtilizeCache {
<add>
<add> if hit {
<ide> return nil
<ide> }
<ide> | 1 |
Javascript | Javascript | reduce usage of require('util') | b8d4bafa03c5253446ec699ecf08f452d3186b2d | <ide><path>lib/internal/http2/core.js
<ide> const net = require('net');
<ide> const { Duplex } = require('stream');
<ide> const tls = require('tls');
<ide> const { URL } = require('url');
<del>const util = require('util');
<ide>
<ide> const { kIncomingMessage } = require('_http_common');
<ide> const { kServerResponse } = require('_http_server');
<ide> const {
<ide> } = require('internal/stream_base_commons');
<ide> const { kTimeout } = require('internal/timers');
<ide> const { isArrayBufferView } = require('internal/util/types');
<add>const { format } = require('internal/util/inspect');
<ide>
<ide> const hasOwnProperty = Object.prototype.hasOwnProperty;
<ide>
<ide> const { UV_EOF } = internalBinding('uv');
<ide>
<ide> const { StreamPipe } = internalBinding('stream_pipe');
<ide> const { _connectionListener: httpConnectionListener } = http;
<del>const debug = util.debuglog('http2');
<add>const debug = require('internal/util/debuglog').debuglog('http2');
<ide>
<ide> const kMaxFrameSize = (2 ** 24) - 1;
<ide> const kMaxInt = (2 ** 32) - 1;
<ide> class Http2Session extends EventEmitter {
<ide> localSettings: this.localSettings,
<ide> remoteSettings: this.remoteSettings
<ide> };
<del> return `Http2Session ${util.format(obj)}`;
<add> return `Http2Session ${format(obj)}`;
<ide> }
<ide>
<ide> // The socket owned by this session
<ide> class Http2Stream extends Duplex {
<ide> readableState: this._readableState,
<ide> writableState: this._writableState
<ide> };
<del> return `Http2Stream ${util.format(obj)}`;
<add> return `Http2Stream ${format(obj)}`;
<ide> }
<ide>
<ide> get bufferSize() { | 1 |
PHP | PHP | fix flakey memcached tests | e9f3c95d35c51f486fa4d608be4f6611bd259f72 | <ide><path>tests/Integration/Cache/MemcachedTaggedCacheTest.php
<ide> public function testMemcachedCanStoreAndRetrieveTaggedCacheItems()
<ide> {
<ide> $store = Cache::store('memcached');
<ide>
<del> $store->tags(['people', 'artists'])->put('John', 'foo', 1);
<del> $store->tags(['people', 'authors'])->put('Anne', 'bar', 1);
<add> $store->tags(['people', 'artists'])->put('John', 'foo', 2);
<add> $store->tags(['people', 'authors'])->put('Anne', 'bar', 2);
<ide>
<ide> $this->assertSame('foo', $store->tags(['people', 'artists'])->get('John'));
<ide> $this->assertSame('bar', $store->tags(['people', 'authors'])->get('Anne'));
<ide> public function testMemcachedCanStoreManyTaggedCacheItems()
<ide> {
<ide> $store = Cache::store('memcached');
<ide>
<del> $store->tags(['people', 'artists'])->putMany(['John' => 'foo', 'Jane' => 'bar'], 1);
<add> $store->tags(['people', 'artists'])->putMany(['John' => 'foo', 'Jane' => 'bar'], 2);
<ide>
<ide> $this->assertSame('foo', $store->tags(['people', 'artists'])->get('John'));
<ide> $this->assertSame('bar', $store->tags(['people', 'artists'])->get('Jane')); | 1 |
PHP | PHP | add tests for invalid values and __tostring() | 7c2761d5e6378e46d9bfbeeb6d248fea3346e68c | <ide><path>tests/TestCase/Utility/TimeTest.php
<ide> public function testToString() {
<ide> $this->assertTimeFormat('dimanche 20 avril 2014 22:10:00 UTC', (string)$time);
<ide> }
<ide>
<add>/**
<add> * Data provider for invalid values.
<add> *
<add> * @return array
<add> */
<add> public function invalidDataProvider() {
<add> return [
<add> [null],
<add> [false],
<add> [''],
<add> ['0000-00-00'],
<add> ['0000-00-00 00:00:00'],
<add> ];
<add> }
<add>
<add>/**
<add> * Test that invalid datetime values do not trigger errors.
<add> *
<add> * @dataProvider invalidDataProvider
<add> * @return void
<add> */
<add> public function testToStringInvalid($value) {
<add> $time = new Time($value);
<add> $this->assertInternalType('string', (string)$time);
<add> $this->assertNotEmpty((string)$time);
<add> }
<add>
<ide> /**
<ide> * Tests diffForHumans
<ide> * | 1 |
Text | Text | add explanation of deadlock with example | 20c0fd9a04c1951978eb51da8995af7b2f247e45 | <ide><path>guide/english/computer-science/deadlock/index.md
<ide> title: Deadlock
<ide> ---
<ide>
<del>## Deadlock
<add>## Deadlocks
<ide>
<ide> ### The Deadlock Problem
<add>
<add>Deadlock is a situation which occurs when a process or thread enters a waiting state because a resource requested is being held by another waiting process, which in turn is waiting for another resource held by another waiting process.
<add>In a deadlock state a process is unable to change its state(waiting) indefinitely because the resources requested by it are being used by another waiting process.
<ide> - A set of blocked processes each holding a resource and waiting to acquire a resource held by another process in the set.
<del>- Example
<del> - System has 2 disk drives.
<del> - P 1 and P 2 each hold one disk drive and each needs another one.
<add>- Example:
<add>Let there be 2 processes P1 and P2 and 2 resources R1 and R2. Both P1 and P2 require Both R1 and R2 to complete their tasks. Suppose P1 acquires R1 first. In the mean time P2 acquires R2. Now when P1 requests for R2 it will have to wait (because R2 is being held by P2). Similarly, when P2 requests for R1 it will also have to wait. Neither P1 nor P2 will not be able to change their waiting state since both are holding the resource required by the other process and none will release its resource until their allocated task is over. Hence the system will be in deadlock.
<ide>
<ide> #### Bridge Crossing Example
<ide> 
<ide> Deadlock can arise if four conditions hold simultaneously.
<ide>
<ide> - **Circular Wait** – It imposes a total ordering of all resource types, and require that each process requests resources in an increasing order of enumeration.
<ide>
<add>### Deadlock Avoidance
<add>Provide information to Operating system that which all resources any process will require during its lifetime.
<add>Then at every request the system can decide whether to grant that request or not.
<add>This decision depends upon resources currently available, resources currently allocated to each process and future request and release of resources by each process.
<add>Safe State: state is safe if the system can allocate resources to every process in some order and still avoid deadlock.
<add>Safe sequence – is an order {P1, P2, … Pn} in which the processes can be allocated resources safely.<br>
<add>NOTE:
<add>Safe state – No deadlock
<add>Unsafe State - Deadlock may or may not occur
<add>
<add>Conclusion
<add>Do not grant the request immediately
<add>Check whether granting the request will leave the system in safe state or not?
<add>If yes, grant the request otherwise do not grant the request
<add>
<add>### Algorithms for deadlock avoidance
<add>
<add>#### Resource allocation graph algorithm
<add><i>Resource Allocation graph</i> - this technique can be employed when there is single instance of every resource. In resource allocation graph for deadlock avoidance we introduce a third kind of edge called the claim edge which is a dotted line from a process towards a resource meaning that the resource can be requested by the process in future.
<add>When ever a process requests for a resource the claim edge is changed to request edge and if the resource can be granted the request edge is changed to assignment edge. After this change look for a cycle in the graph. If no cycle exists, then the system is in safe state and the deadlock will not occur else the system is in unsafe state and deadlock may or may not occur.
<add>
<add>#### Banker’s algorithm
<add><i>Banker's Algorithm</i> - this technique is used when there are multiple instances of a resource. This algorithm requires four data structures to be implemented:
<add>Available – no. of available resources of each type
<add>Max – maximum need of any process for any resource
<add>Allocation – number of resources allocated to each process
<add>Need – (Max – Allocation)
<ide>
<ide> #### More information :
<ide> - [Deadlock](https://en.wikipedia.org/wiki/Deadlock) | 1 |
Text | Text | use link name | 28032cb257da90e5ac082aab9ca112d5a84dd863 | <ide><path>docs/converting-a-text-mate-bundle.md
<ide> the editor to see it in action!
<ide> ### Further Reading
<ide>
<ide> * Check out [Publishing a Package](publish-a-package.html) for more information
<del> on publishing the package you just created to [atom.io](https://atom.io).
<add> on publishing the package you just created to [atom.io][atomio].
<ide>
<ide> [atomio]: https://atom.io
<ide> [CSS]: http://en.wikipedia.org/wiki/Cascading_Style_Sheets
<ide><path>docs/converting-a-text-mate-theme.md
<ide> __Syntax Theme__ dropdown menu to enable your new theme.
<ide> ### Further Reading
<ide>
<ide> * Check out [Publishing a Package](publish-a-package.html) for more information
<del> on publishing the theme you just created to [atom.io](https://atom.io).
<add> on publishing the theme you just created to [atom.io][atomio].
<ide>
<ide> [atomio]: https://atom.io
<ide> [CSS]: http://en.wikipedia.org/wiki/Cascading_Style_Sheets | 2 |
Ruby | Ruby | remove warning of unused variable | 9f69f0156907aee642fc43ca6524f4f37abd5388 | <ide><path>activesupport/test/core_ext/hash_ext_test.rb
<ide> def test_extract
<ide> original = {:a => 1, :b => 2, :c => 3, :d => 4}
<ide> expected = {:a => 1, :b => 2}
<ide>
<del> assert_equal expected, {:a => 1, :b => 2, :c => 3, :d => 4}.extract!(:a, :b)
<add> assert_equal expected, original.extract!(:a, :b)
<ide> end
<ide>
<ide> def test_except | 1 |
Ruby | Ruby | preserve signature of #initialize in tests | 3c9bee268bde9675e8091068750a89bb35d4b2f2 | <ide><path>Library/Homebrew/test/test_formula.rb
<ide> def test_formula_spec_integration
<ide> mirror 'http://example.org/test-0.2.tbz'
<ide> sha256 TEST_SHA256
<ide> end
<del>
<del> def initialize
<del> super "test", Pathname.new(__FILE__).expand_path, :stable
<del> end
<del> end.new
<add> end.new("test", Pathname.new(__FILE__).expand_path, :stable)
<ide>
<ide> assert_equal 'http://example.com', f.homepage
<ide> assert_version_equal '0.1', f.version
<ide><path>Library/Homebrew/test/test_formula_install.rb
<ide> def test_script_install
<ide> f = Class.new(ScriptFileFormula) do
<ide> url "file://#{File.expand_path(__FILE__)}"
<ide> version "1"
<del> def initialize
<del> super "test_script_formula", Pathname.new(__FILE__).expand_path, :stable
<del> end
<del> end.new
<add> end.new("test_script_formula", Pathname.new(__FILE__).expand_path, :stable)
<ide>
<ide> temporary_install(f) { assert_equal 1, f.bin.children.length }
<ide> end | 2 |
Python | Python | remove check in binary_crossentropy | 0332b95cdf622bf3a6fbe66f5d4eda5ee482dd90 | <ide><path>keras/objectives.py
<ide> def categorical_crossentropy(y_true, y_pred):
<ide> return cce
<ide>
<ide> def binary_crossentropy(y_true, y_pred):
<del> if y_true.shape[-1] != 1:
<del> raise Exception("binary_crossentropy can only be used with scalar outputs.")
<ide> y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon)
<ide> bce = T.nnet.binary_crossentropy(y_pred, y_true)
<ide> return bce | 1 |
Python | Python | change .first() to .scalar() | 37c0038a18ace092079d23988f76d90493ff294c | <ide><path>airflow/models/serialized_dag.py
<ide> def write_dag(
<ide> (timezone.utcnow() - timedelta(seconds=min_update_interval)) < cls.last_updated,
<ide> )
<ide> )
<del> .first()
<del> is not None
<add> .scalar()
<ide> ):
<del> # TODO: .first() is not None can be changed to .scalar() once we update to sqlalchemy 1.4+
<del> # as the associated sqlalchemy bug for MySQL was fixed
<del> # related issue : https://github.com/sqlalchemy/sqlalchemy/issues/5481
<ide> return False
<ide>
<ide> log.debug("Checking if DAG (%s) changed", dag.dag_id) | 1 |
Java | Java | simplify boolean not operation | 2f9d0a7de8e2f1247dd4a34811220106f7359aa5 | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterUtils.java
<ide> public static ParsedSql parseSqlStatement(final String sql) {
<ide> String parameter = null;
<ide> if (j < statement.length && c == ':' && statement[j] == '{') {
<ide> // :{x} style parameter
<del> while (j < statement.length && !('}' == statement[j])) {
<add> while (j < statement.length && '}' != statement[j]) {
<ide> j++;
<ide> if (':' == statement[j] || '{' == statement[j]) {
<ide> throw new InvalidDataAccessApiUsageException("Parameter name contains invalid character '" +
<ide> private static int skipCommentsAndQuotes(char[] statement, int position) {
<ide> if (statement[position] == START_SKIP[i].charAt(0)) {
<ide> boolean match = true;
<ide> for (int j = 1; j < START_SKIP[i].length(); j++) {
<del> if (!(statement[position + j] == START_SKIP[i].charAt(j))) {
<add> if (statement[position + j] != START_SKIP[i].charAt(j)) {
<ide> match = false;
<ide> break;
<ide> }
<ide> private static int skipCommentsAndQuotes(char[] statement, int position) {
<ide> // last comment not closed properly
<ide> return statement.length;
<ide> }
<del> if (!(statement[m + n] == STOP_SKIP[i].charAt(n))) {
<add> if (statement[m + n] != STOP_SKIP[i].charAt(n)) {
<ide> endMatch = false;
<ide> break;
<ide> } | 1 |
Javascript | Javascript | fix codestyle for typeof comparison | 43363e2795393a00fd77312a16d6b80e626c29de | <ide><path>packages/react-reconciler/src/ReactFiberHooks.new.js
<ide> function mountEffect(
<ide> ): void {
<ide> if (__DEV__) {
<ide> // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
<del> if ('undefined' !== typeof jest) {
<add> if (typeof jest !== 'undefined') {
<ide> warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber);
<ide> }
<ide> }
<ide> function updateEffect(
<ide> ): void {
<ide> if (__DEV__) {
<ide> // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
<del> if ('undefined' !== typeof jest) {
<add> if (typeof jest !== 'undefined') {
<ide> warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber);
<ide> }
<ide> }
<ide> function dispatchAction<S, A>(
<ide> }
<ide> if (__DEV__) {
<ide> // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
<del> if ('undefined' !== typeof jest) {
<add> if (typeof jest !== 'undefined') {
<ide> warnIfNotScopedWithMatchingAct(fiber);
<ide> warnIfNotCurrentlyActingUpdatesInDev(fiber);
<ide> } | 1 |
Javascript | Javascript | handle invalid login | 070c2481326d3243a7a3f822c481dc389893d034 | <ide><path>common/models/user.js
<ide> module.exports = function(User) {
<ide> res.cookie('access_token', accessToken.id, config);
<ide> res.cookie('userId', accessToken.userId, config);
<ide> }
<del>
<add> debug('before pass login');
<ide> return req.logIn(user, function(err) {
<ide> if (err) {
<ide> return next(err);
<ide> module.exports = function(User) {
<ide> });
<ide> });
<ide>
<add> User.afterRemoteError('login', function(ctx, usr, next) {
<add> var res = ctx.res;
<add> var req = ctx.req;
<add> // var args = ctx.args;
<add>
<add>
<add> debug('after pass lgin');
<add> req.flash('errors', {
<add> msg: 'Invalid username or password.'
<add> });
<add> return res.redirect('/');
<add> });
<add>
<ide> User.afterRemote('logout', function(ctx, result, next) {
<ide> var res = ctx.result;
<ide> res.clearCookie('access_token'); | 1 |
Text | Text | add details on how gatsby works | e1d98e3402ef848258bdc529aaf33bdefa970335 | <ide><path>guide/english/gatsbyjs/index.md
<ide> Gatsby is a static site generator for [React](https://guide.freecodecamp.org/rea
<ide>
<ide> The Gatsby environment provides several "starters" to help configure static sites quickly. Starters can be found here: [Starter Library](https://www.gatsbyjs.org/starters/).
<ide>
<del>### Installation and using the Gatsby CLI
<add>### How Gatsby works
<add>Gatsby builds sites with the data provided by developer, regardless of the source.
<add>
<add>#### Data sources
<add>Gatsby accepts the data behind the site in various formats, such as:
<add>
<add>1- CMSs: Wordpress, Contenful, Drupal, etc.
<add>2- Markdown: Documentation, posts, etc.
<add>3- Data: APIs, Databasses, JSON, CSV, etc.
<ide>
<add>#### Build
<add>Gatsby's build is powered by GraphQL and rendered through HTML, CSS, and React.
<add>
<add>#### Deploy
<add>Gatsby deploys the site on a static web host such as Amazon S3, Netlify, Github Pages, Surge.sh and many more.
<add>
<add>### Installation and using the Gatsby CLI
<ide> * Node: `npm install --global gatsby-cli`
<ide> * Get started with the official Gatsby starter: `gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-default`
<ide> * After that change to the newly created directory `cd gatsby-site`
<ide> * `gatsby develop` starts a hot-reloading development server. The site will reload when changes in `src/pages` will be saved.
<ide> * To generate the static HTML pages use `gatsby build`
<ide> * `gatsby serve` will start a local server that will present your built site.
<ide>
<del>#### More Information:
<add>### More Information:
<ide> For tutorials and more information check out the Gatsby.js official site: [Gatsby.js official site](https://www.gatsbyjs.org/tutorial/) | 1 |
Python | Python | fix accuracy with sparse_categorical_crossentropy | 63c1757df519bc5756c0d7d79dabd5ec0420f3c8 | <ide><path>keras/engine/training.py
<ide> def compile(self, optimizer, loss, metrics=[], loss_weights=None,
<ide> if output_shape[-1] == 1:
<ide> # case: binary accuracy
<ide> self.metrics.append(metrics_module.binary_accuracy(y_true, y_pred))
<add> elif self.loss_functions[i] == objectives.sparse_categorical_crossentropy:
<add> # case: categorical accuracy with sparse targets
<add> self.metrics.append(
<add> metrics_module.sparse_categorical_accuracy(y_true, y_pred))
<ide> else:
<del> # case: categorical accuracy
<add> # case: categorical accuracy with dense targets
<ide> self.metrics.append(metrics_module.categorical_accuracy(y_true, y_pred))
<ide> if len(self.output_names) == 1:
<ide> self.metrics_names.append('acc')
<ide><path>keras/metrics.py
<ide> def categorical_accuracy(y_true, y_pred):
<ide> K.argmax(y_pred, axis=-1)))
<ide>
<ide>
<add>def sparse_categorical_accuracy(y_true, y_pred):
<add> return K.mean(K.equal(K.max(y_true, axis=-1),
<add> K.argmax(y_pred, axis=-1)))
<add>
<add>
<ide> from .utils.generic_utils import get_from_module
<ide> def get(identifier):
<ide> return get_from_module(identifier, globals(), 'metric') | 2 |
Javascript | Javascript | trim large test output to not exceed limit | f71d3f2c091bc7828f120baf025c51d2f633b47b | <ide><path>run-tests.js
<ide> async function main() {
<ide> children.delete(child)
<ide> if (code) {
<ide> if (isFinalRun) {
<del> outputChunks.forEach((chunk) => process.stdout.write(chunk))
<add> // limit out to last 64kb so that we don't
<add> // run out of log room in CI
<add> let trimmedOutputSize = 0
<add> const trimmedOutputLimit = 64 * 1024
<add> const trimmedOutput = []
<add>
<add> for (let i = outputChunks.length; i >= 0; i--) {
<add> const chunk = outputChunks[i]
<add> if (!chunk) continue
<add>
<add> trimmedOutputSize += chunk.byteLength || chunk.length
<add> trimmedOutput.unshift(chunk)
<add>
<add> if (trimmedOutputSize > trimmedOutputLimit) {
<add> break
<add> }
<add> }
<add> trimmedOutput.forEach((chunk) => process.stdout.write(chunk))
<ide> }
<ide> reject(new Error(`failed with code: ${code}`))
<ide> } | 1 |
Ruby | Ruby | use a method that actually exists | dfa331ae154c0475dfc631528071bdb06947acc2 | <ide><path>actionpack/test/controller/integration_test.rb
<ide> def test_xml_http_request_override_accept
<ide>
<ide> class IntegrationTestTest < Test::Unit::TestCase
<ide> def setup
<del> @test = ::ActionDispatch::IntegrationTest.new(:default_test)
<add> @test = ::ActionDispatch::IntegrationTest.new(:app)
<ide> @test.class.stubs(:fixture_table_names).returns([])
<ide> @session = @test.open_session
<ide> end | 1 |
Python | Python | update documentation for isfortran | d07e84c499aaaa04b0723bf80e7c41aba7b5d51c | <ide><path>numpy/core/numeric.py
<ide> def require(a, dtype=None, requirements=None):
<ide>
<ide> def isfortran(a):
<ide> """
<del> Returns True if array is arranged in Fortran-order in memory
<del> and not C-order.
<add> Returns True if the array is Fortran contiguous but *not* C contiguous.
<add>
<add> This function is obsolete and, because of changes due to relaxed stride
<add> checking, its return value for the same array may differ for versions
<add> of Numpy >= 1.10 and previous versions. If you only want to check if an
<add> array is Fortran contiguous use ``a.flags.f_contiguous`` instead.
<ide>
<ide> Parameters
<ide> ---------- | 1 |
Python | Python | remove unused constant | 797fb77dd77603459f4b6f3f0789580494333e2c | <ide><path>libcloud/compute/base.py
<ide> # script.
<ide> SSH_CONNECT_TIMEOUT = 5 * 60
<ide>
<del># Keyword arguments which are specific to deploy_node() method, but not
<del># create_node()
<del>DEPLOY_NODE_KWARGS = ['deploy', 'ssh_username', 'ssh_alternate_usernames',
<del> 'ssh_port', 'ssh_timeout', 'ssh_key', 'timeout',
<del> 'max_tries', 'ssh_interface']
<ide> __all__ = [
<ide> 'Node',
<ide> 'NodeState', | 1 |
Text | Text | update doc of publicencrypt method | eff9252181abe6ebd19252af652f29581711e665 | <ide><path>doc/api/crypto.md
<ide> treated as the key with no passphrase and will use `RSA_PKCS1_PADDING`.
<ide> <!-- YAML
<ide> added: v1.1.0
<ide> -->
<del>- `private_key` {Object | string}
<add>- `public_key` {Object | string}
<ide> - `key` {string} A PEM encoded private key.
<ide> - `passphrase` {string} An optional passphrase for the private key.
<ide> - `padding` {crypto.constants} An optional padding value defined in
<ide> be passed instead of a public key.
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<del>- `private_key` {Object | string}
<add>- `public_key` {Object | string}
<ide> - `key` {string} A PEM encoded private key.
<ide> - `passphrase` {string} An optional passphrase for the private key.
<ide> - `padding` {crypto.constants} An optional padding value defined in
<ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`,
<ide> `RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`.
<ide> - `buffer` {Buffer | TypedArray | DataView}
<ide>
<del>Encrypts `buffer` with `public_key`.
<add>Encrypts the content of `buffer` with `public_key` and returns a new
<add>[`Buffer`][] with encrypted content.
<ide>
<ide> `public_key` can be an object or a string. If `public_key` is a string, it is
<ide> treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`. | 1 |
Text | Text | add bmeurer to collaborators | f30820fdca62da000ba7f6fc586ca1ff65e54a0f | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Benjamin Gruenbaum** <[email protected]>
<ide> * [bmeck](https://github.com/bmeck) -
<ide> **Bradley Farias** <[email protected]>
<add>* [bmeurer](https://github.com/bmeurer) -
<add>**Benedikt Meurer** <[email protected]>
<ide> * [bnoordhuis](https://github.com/bnoordhuis) -
<ide> **Ben Noordhuis** <[email protected]>
<ide> * [brendanashworth](https://github.com/brendanashworth) - | 1 |
PHP | PHP | add cache options to cell | e27925e280bc75f2e78f5ae5bc053e520816098b | <ide><path>src/View/Cell.php
<ide> abstract class Cell {
<ide> */
<ide> protected $_validCellOptions = [];
<ide>
<add>/**
<add> * Caching setup.
<add> *
<add> * @var array|bool
<add> */
<add> protected $_cache = false;
<add>
<ide> /**
<ide> * Constructor.
<ide> *
<ide> public function __construct(Request $request = null, Response $response = null,
<ide> $this->{$var} = $cellOptions[$var];
<ide> }
<ide> }
<add> if (!empty($cellOptions['cache'])) {
<add> $this->_cache = $cellOptions['cache'];
<add> }
<ide> }
<ide>
<ide> /**
<ide> public function render($template = null) {
<ide> if ($template === null) {
<ide> $template = $this->template;
<ide> }
<del>
<ide> $this->View = null;
<ide> $this->getView();
<del>
<ide> $this->View->layout = false;
<del> $className = explode('\\', get_class($this));
<del> $className = array_pop($className);
<del> $name = substr($className, 0, strpos($className, 'Cell'));
<del> $this->View->subDir = 'Cell' . DS . $name;
<ide>
<del> try {
<del> return $this->View->render($template);
<del> } catch (MissingTemplateException $e) {
<del> throw new MissingCellViewException(['file' => $template, 'name' => $name]);
<add> $cache = [];
<add> if ($this->_cache) {
<add> $cache = $this->_cacheConfig($template);
<add> }
<add>
<add> $render = function () use ($template) {
<add> $className = explode('\\', get_class($this));
<add> $className = array_pop($className);
<add> $name = substr($className, 0, strpos($className, 'Cell'));
<add> $this->View->subDir = 'Cell' . DS . $name;
<add>
<add> try {
<add> return $this->View->render($template);
<add> } catch (MissingTemplateException $e) {
<add> throw new MissingCellViewException(['file' => $template, 'name' => $name]);
<add> }
<add> };
<add>
<add> if ($cache) {
<add> return $this->View->cache(function() use ($render) {
<add> echo $render();
<add> }, $cache);
<add> }
<add> return $render();
<add> }
<add>
<add>/**
<add> * Generate the cache key to use for this cell.
<add> *
<add> * If the key is undefined, the cell class and template will be used.
<add> *
<add> * @param string $template The template being rendered.
<add> * @return array The cache configuration.
<add> */
<add> protected function _cacheConfig($template) {
<add> if (empty($this->_cache)) {
<add> return [];
<add> }
<add> $key = 'cell_' . Inflector::underscore(get_class($this)) . '_' . $template;
<add> $key = str_replace('\\', '_', $key);
<add> $default = [
<add> 'config' => 'default',
<add> 'key' => $key
<add> ];
<add> if ($this->_cache === true) {
<add> return $default;
<ide> }
<add> return $this->_cache + $default;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/CellTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\View;
<ide>
<add>use Cake\Cache\Cache;
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> public function testCellInheritsCustomViewClass() {
<ide> $this->assertSame('TestApp\View\CustomJsonView', $cell->viewClass);
<ide> }
<ide>
<add>/**
<add> * Test cached render.
<add> *
<add> * @return void
<add> */
<add> public function testCachedRenderSimple() {
<add> $mock = $this->getMock('Cake\Cache\CacheEngine');
<add> $mock->method('init')
<add> ->will($this->returnValue(true));
<add> $mock->method('read')
<add> ->will($this->returnValue(false));
<add> $mock->expects($this->once())
<add> ->method('write')
<add> ->with('cell_test_app_view_cell_articles_cell_display', "dummy\n");
<add> Cache::config('default', $mock);
<add>
<add> $cell = $this->View->cell('Articles', [], ['cache' => true]);
<add> $result = $cell->render();
<add> $this->assertEquals("dummy\n", $result);
<add> Cache::drop('default');
<add> }
<add>
<add>/**
<add> * Test cached render array config
<add> *
<add> * @return void
<add> */
<add> public function testCachedRenderArrayConfig() {
<add> $mock = $this->getMock('Cake\Cache\CacheEngine');
<add> $mock->method('init')
<add> ->will($this->returnValue(true));
<add> $mock->method('read')
<add> ->will($this->returnValue(false));
<add> $mock->expects($this->once())
<add> ->method('write')
<add> ->with('my_key', "dummy\n");
<add> Cache::config('cell', $mock);
<add>
<add> $cell = $this->View->cell('Articles', [], [
<add> 'cache' => ['key' => 'my_key', 'config' => 'cell']
<add> ]);
<add> $result = $cell->render();
<add> $this->assertEquals("dummy\n", $result);
<add> Cache::drop('cell');
<add> }
<add>
<ide> } | 2 |
Ruby | Ruby | spam people with commit rights on test failures | 84e6ad3fb9d6a1ba3b71b058e19388de5c67a07f | <ide><path>ci/cruise_config.rb
<ide> Project.configure do |project|
<ide> project.build_command = 'ruby ci/ci_build.rb'
<del> project.email_notifier.emails = ['[email protected]']
<del># project.email_notifier.emails = ['[email protected]','[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
<add># project.email_notifier.emails = ['[email protected]']
<add> project.email_notifier.emails = ['[email protected]','[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
<ide> project.email_notifier.from = '[email protected]'
<ide> end | 1 |
Ruby | Ruby | kill amo base | 6944b391cddbf1a3ffb3ac4ac588fa4b3d50f430 | <ide><path>activemodel/lib/active_model.rb
<ide>
<ide> module ActiveModel
<ide> autoload :APICompliant, 'active_model/api_compliant'
<del> autoload :Base, 'active_model/base'
<ide> autoload :DeprecatedErrorMethods, 'active_model/deprecated_error_methods'
<ide> autoload :Errors, 'active_model/errors'
<ide> autoload :Name, 'active_model/naming'
<ide><path>activemodel/lib/active_model/base.rb
<del>module ActiveModel
<del> class Base
<del> include Observing
<del> # disabled, until they're tested
<del> # include Callbacks
<del> # include Validations
<del> end
<del>end
<ide>\ No newline at end of file
<ide><path>activemodel/test/cases/observing_test.rb
<ide> require 'cases/helper'
<ide>
<del>class ObservedModel < ActiveModel::Base
<add>class ObservedModel
<add> include ActiveModel::Observing
<add>
<ide> class Observer
<ide> end
<ide> end
<ide> def on_spec(record)
<ide> end
<ide> end
<ide>
<del>class Foo < ActiveModel::Base
<add>class Foo
<add> include ActiveModel::Observing
<ide> end
<ide>
<ide> class ObservingTest < ActiveModel::TestCase | 3 |
Javascript | Javascript | fix inconsistent menu order | b83aaa8dfba0131901dafa76d0fff367896a5795 | <ide><path>docs/list.js
<ide> var list = {
<ide> "DodecahedronBufferGeometry": "api/geometries/DodecahedronBufferGeometry",
<ide> "DodecahedronGeometry": "api/geometries/DodecahedronGeometry",
<ide> "EdgesGeometry": "api/geometries/EdgesGeometry",
<del> "ExtrudeGeometry": "api/geometries/ExtrudeGeometry",
<ide> "ExtrudeBufferGeometry": "api/geometries/ExtrudeBufferGeometry",
<add> "ExtrudeGeometry": "api/geometries/ExtrudeGeometry",
<ide> "IcosahedronBufferGeometry": "api/geometries/IcosahedronBufferGeometry",
<ide> "IcosahedronGeometry": "api/geometries/IcosahedronGeometry",
<ide> "LatheBufferGeometry": "api/geometries/LatheBufferGeometry", | 1 |
Python | Python | add test for multidimensional argmax | 0eadb3629d6dcff537946584a1ad2ab85d177a9b | <ide><path>numpy/core/tests/test_multiarray.py
<ide>
<ide> from numpy.testing import *
<ide> from numpy.core import *
<add>from numpy import random
<ide>
<ide> class test_flags(ScipyTestCase):
<ide> def setUp(self):
<ide> def check_unicode(self):
<ide> assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]])
<ide>
<ide>
<add>class test_argmax(ScipyTestCase):
<add> def check_all(self):
<add> a = random.normal(0,1,(4,5,6,7,8))
<add> for i in xrange(a.ndim):
<add> amax = a.max(i)
<add> aargmax = a.argmax(i)
<add> axes = range(a.ndim)
<add> axes.remove(i)
<add> assert all(amax == aargmax.choose(*a.transpose(i,*axes)))
<add>
<add>
<ide> # Import tests from unicode
<ide> set_local_path()
<ide> from test_unicode import * | 1 |
Python | Python | reintroduce docstrings in programmatic start | 494cc5d67452038c9b477d41cb2760b33ab4d5b8 | <ide><path>celery/app/base.py
<ide> def close(self):
<ide> _deregister_app(self)
<ide>
<ide> def start(self, argv=None):
<add> """Run :program:`celery` using `argv`.
<add>
<add> Uses :data:`sys.argv` if `argv` is not specified.
<add> """
<ide> from celery.bin.celery import celery
<ide>
<ide> celery.params[0].default = self
<ide>
<add> if argv is None:
<add> argv = sys.argv
<add>
<ide> try:
<ide> celery.main(args=argv, standalone_mode=False)
<ide> except Exit as e:
<ide> def start(self, argv=None):
<ide> celery.params[0].default = None
<ide>
<ide> def worker_main(self, argv=None):
<add> """Run :program:`celery worker` using `argv`.
<add>
<add> Uses :data:`sys.argv` if `argv` is not specified.
<add> """
<ide> if argv is None:
<ide> argv = sys.argv
<ide>
<ide><path>t/unit/app/test_app.py
<ide> def test_pickle_app(self):
<ide> for key, value in changes.items():
<ide> assert restored.conf[key] == value
<ide>
<del> # def test_worker_main(self):
<del> # from celery.bin import worker as worker_bin
<del> #
<del> # class worker(worker_bin.worker):
<del> #
<del> # def execute_from_commandline(self, argv):
<del> # return argv
<del> #
<del> # prev, worker_bin.worker = worker_bin.worker, worker
<del> # try:
<del> # ret = self.app.worker_main(argv=['--version'])
<del> # assert ret == ['--version']
<del> # finally:
<del> # worker_bin.worker = prev
<add> @patch('celery.bin.celery.celery')
<add> def test_worker_main(self, mocked_celery):
<add> self.app.worker_main(argv=['worker', '--help'])
<add>
<add> mocked_celery.main.assert_called_with(
<add> args=['worker', '--help'], standalone_mode=False)
<ide>
<ide> def test_config_from_envvar(self):
<ide> os.environ['CELERYTEST_CONFIG_OBJECT'] = 't.unit.app.test_app'
<ide> def test_config_from_envvar_more(self, key='CELERY_HARNESS_CFG1'):
<ide> assert self.app.conf['FOO'] == 10
<ide> assert self.app.conf['BAR'] == 20
<ide>
<add> @patch('celery.bin.celery.celery')
<add> def test_start(self, mocked_celery):
<add> self.app.start()
<add> mocked_celery.main.assert_called()
<add>
<ide> @pytest.mark.parametrize('url,expected_fields', [
<ide> ('pyamqp://', {
<ide> 'hostname': 'localhost', | 2 |
PHP | PHP | fix lint error | f528bb29ba87bec6f20e0e66b69b72821416b60b | <ide><path>lib/Cake/Controller/Component/SecurityComponent.php
<ide> protected function _expireTokens($tokens) {
<ide> * @param string $method Method to execute
<ide> * @param array $params Parameters to send to method
<ide> * @return mixed Controller callback method's response
<add> * @throws BadRequestException When a the blackholeCallback is not callable.
<ide> */
<ide> protected function _callback(Controller $controller, $method, $params = array()) {
<ide> if (is_callable(array($controller, $method))) { | 1 |
Python | Python | add timing inside trainer | 1198ba8fbac8c103950f58f19f76c18b37ee99b5 | <ide><path>examples/seq2seq/finetune_trainer.py
<ide> import logging
<ide> import os
<ide> import sys
<del>import time
<ide> from dataclasses import dataclass, field
<ide> from typing import Optional
<ide>
<ide> class DataTrainingArguments:
<ide> )
<ide>
<ide>
<del>def speed_metrics(split, start_time, num_samples):
<del> """
<del> Measure and return speed performance metrics.
<del>
<del> This function requires a time snapshot `start_time` before the operation to be measured starts and this
<del> function should be run immediately after the operation to be measured has completed.
<del>
<del> Args:
<del> - split: one of train, val, test
<del> - start_time: operation start time
<del> - num_samples: number of samples processed
<del>
<del> """
<del> runtime = time.time() - start_time
<del> result = {}
<del>
<del> samples_per_second = 1 / (runtime / num_samples)
<del> result[f"{split}_samples_per_second"] = round(samples_per_second, 3)
<del> result[f"{split}_runtime"] = round(runtime, 4)
<del>
<del> result[f"{split}_n_ojbs"] = num_samples
<del> return result
<del>
<del>
<ide> def handle_metrics(split, metrics, output_dir):
<ide> """
<ide> Log and save metrics
<ide> def handle_metrics(split, metrics, output_dir):
<ide> """
<ide>
<ide> logger.info(f"***** {split} metrics *****")
<del> for key, value in metrics.items():
<del> logger.info(f" {key} = {value}")
<add> for key in sorted(metrics.keys()):
<add> logger.info(f" {key} = {metrics[key]}")
<ide> save_json(metrics, os.path.join(output_dir, f"{split}_results.json"))
<ide>
<ide>
<ide> def main():
<ide> if training_args.do_train:
<ide> logger.info("*** Train ***")
<ide>
<del> start_time = time.time()
<del> trainer.train(
<add> train_result = trainer.train(
<ide> model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None
<ide> )
<del> metrics = speed_metrics("train", start_time, data_args.n_train)
<add> metrics = train_result.metrics
<add> metrics["train_n_objs"] = data_args.n_train
<ide>
<ide> trainer.save_model() # this also saves the tokenizer
<ide>
<ide> def main():
<ide> if training_args.do_eval:
<ide> logger.info("*** Evaluate ***")
<ide>
<del> start_time = time.time()
<ide> metrics = trainer.evaluate(metric_key_prefix="val")
<del> metrics.update(speed_metrics("val", start_time, data_args.n_val))
<add> metrics["val_n_objs"] = data_args.n_val
<ide> metrics["val_loss"] = round(metrics["val_loss"], 4)
<ide>
<ide> if trainer.is_world_process_zero():
<ide> def main():
<ide> if training_args.do_predict:
<ide> logger.info("*** Predict ***")
<ide>
<del> start_time = time.time()
<ide> test_output = trainer.predict(test_dataset=test_dataset, metric_key_prefix="test")
<ide> metrics = test_output.metrics
<del> metrics.update(speed_metrics("test", start_time, data_args.n_test))
<add> metrics["test_n_objs"] = data_args.n_test
<ide>
<ide> if trainer.is_world_process_zero():
<ide> metrics["test_loss"] = round(metrics["test_loss"], 4)
<ide><path>examples/test_examples.py
<ide> def test_run_glue(self):
<ide>
<ide> with patch.object(sys, "argv", testargs):
<ide> result = run_glue.main()
<del> del result["eval_loss"]
<del> for value in result.values():
<del> self.assertGreaterEqual(value, 0.75)
<add> self.assertGreaterEqual(result["eval_accuracy"], 0.75)
<ide>
<ide> @require_torch_non_multi_gpu_but_fix_me
<ide> def test_run_clm(self):
<ide><path>src/transformers/trainer.py
<ide> import os
<ide> import re
<ide> import shutil
<add>import time
<ide> import warnings
<ide> from pathlib import Path
<ide> from typing import Any, Callable, Dict, List, Optional, Tuple, Union
<ide> default_compute_objective,
<ide> default_hp_space,
<ide> set_seed,
<add> speed_metrics,
<ide> )
<ide> from .training_args import TrainingArguments
<ide> from .utils import logging
<ide> def train(self, model_path: Optional[str] = None, trial: Union["optuna.Trial", D
<ide> logger.info(f" Total optimization steps = {max_steps}")
<ide>
<ide> self.state.epoch = 0
<add> start_time = time.time()
<ide> epochs_trained = 0
<ide> steps_trained_in_current_epoch = 0
<ide>
<ide> def train(self, model_path: Optional[str] = None, trial: Union["optuna.Trial", D
<ide> state_dict = torch.load(os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME))
<ide> self.model.load_state_dict(state_dict)
<ide>
<add> metrics = speed_metrics("train", start_time, self.state.max_steps)
<ide> if self._total_flos is not None:
<ide> self.store_flos()
<del> self.log({"total_flos": self.state.total_flos})
<add> metrics["total_flos"] = self.state.total_flos
<add> self.log(metrics)
<ide>
<ide> self.control = self.callback_handler.on_train_end(self.args, self.state, self.control)
<ide> # add remaining tr_loss
<ide> self._total_loss_scalar += tr_loss.item()
<ide>
<del> return TrainOutput(self.state.global_step, self._total_loss_scalar / self.state.global_step)
<add> return TrainOutput(self.state.global_step, self._total_loss_scalar / self.state.global_step, metrics)
<ide>
<ide> def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch):
<ide> if self.control.should_log:
<ide> def evaluate(
<ide> raise ValueError("eval_dataset must implement __len__")
<ide>
<ide> eval_dataloader = self.get_eval_dataloader(eval_dataset)
<add> start_time = time.time()
<ide>
<ide> output = self.prediction_loop(
<ide> eval_dataloader,
<ide> def evaluate(
<ide> metric_key_prefix=metric_key_prefix,
<ide> )
<ide>
<add> n_samples = len(eval_dataset if eval_dataset is not None else self.eval_dataset)
<add> output.metrics.update(speed_metrics(metric_key_prefix, start_time, n_samples))
<ide> self.log(output.metrics)
<ide>
<ide> if self.args.tpu_metrics_debug or self.args.debug:
<ide> def predict(
<ide> raise ValueError("test_dataset must implement __len__")
<ide>
<ide> test_dataloader = self.get_test_dataloader(test_dataset)
<add> start_time = time.time()
<ide>
<del> return self.prediction_loop(
<add> output = self.prediction_loop(
<ide> test_dataloader, description="Prediction", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix
<ide> )
<add> output.metrics.update(speed_metrics(metric_key_prefix, start_time, len(test_dataset)))
<add> return output
<ide>
<ide> def prediction_loop(
<ide> self,
<ide><path>src/transformers/trainer_utils.py
<ide>
<ide> import copy
<ide> import random
<add>import time
<ide> from typing import Any, Dict, NamedTuple, Optional, Tuple, Union
<ide>
<ide> import numpy as np
<ide> class PredictionOutput(NamedTuple):
<ide> class TrainOutput(NamedTuple):
<ide> global_step: int
<ide> training_loss: float
<add> metrics: Dict[str, float]
<ide>
<ide>
<ide> PREFIX_CHECKPOINT_DIR = "checkpoint"
<ide> def total_processes_number(local_rank):
<ide>
<ide> return torch.distributed.get_world_size()
<ide> return 1
<add>
<add>
<add>def speed_metrics(split, start_time, num_samples=None):
<add> """
<add> Measure and return speed performance metrics.
<add>
<add> This function requires a time snapshot `start_time` before the operation to be measured starts and this function
<add> should be run immediately after the operation to be measured has completed.
<add>
<add> Args:
<add> - split: name to prefix metric (like train, eval, test...)
<add> - start_time: operation start time
<add> - num_samples: number of samples processed
<add> """
<add> runtime = time.time() - start_time
<add> result = {f"{split}_runtime": round(runtime, 4)}
<add> if num_samples is not None:
<add> samples_per_second = 1 / (runtime / num_samples)
<add> result[f"{split}_samples_per_second"] = round(samples_per_second, 3)
<add> return result
<ide><path>src/transformers/training_args.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<del>import dataclasses
<ide> import json
<ide> import os
<del>from dataclasses import dataclass, field
<add>from dataclasses import asdict, dataclass, field
<ide> from enum import Enum
<ide> from typing import Any, Dict, List, Optional, Tuple
<ide>
<ide> def __post_init__(self):
<ide> self.run_name = self.output_dir
<ide>
<ide> if is_torch_available() and self.device.type != "cuda" and self.fp16:
<del> raise ValueError("AMP (`--fp16`) can only be used on CUDA devices.")
<add> raise ValueError("Mixed precision training with AMP or APEX (`--fp16`) can only be used on CUDA devices.")
<add>
<add> def __repr__(self):
<add> # We override the default repr to remove deprecated arguments from the repr. This method should be removed once
<add> # those deprecated arguments are removed form TrainingArguments. (TODO: v5)
<add> self_as_dict = asdict(self)
<add> del self_as_dict["per_gpu_train_batch_size"]
<add> del self_as_dict["per_gpu_eval_batch_size"]
<add> attrs_as_str = [f"{k}={v}" for k, v in self_as_dict.items()]
<add> return f"{self.__class__.__name__}({', '.join(attrs_as_str)})"
<ide>
<ide> @property
<ide> def train_batch_size(self) -> int:
<ide> def to_dict(self):
<ide> """
<ide> Serializes this instance while replace `Enum` by their values (for JSON serialization support).
<ide> """
<del> d = dataclasses.asdict(self)
<add> d = asdict(self)
<ide> for k, v in d.items():
<ide> if isinstance(v, Enum):
<ide> d[k] = v.value
<ide><path>tests/test_trainer.py
<ide> def check_best_model_has_been_loaded(
<ide> metrics = trainer.evaluate()
<ide> self.assertEqual(metrics[metric], best_value)
<ide>
<add> def check_trainer_state_are_the_same(self, trainer_state, trainer_state1):
<add> # We'll pop things so operate on copies.
<add> state = trainer_state.copy()
<add> state1 = trainer_state1.copy()
<add> # Log history main contain different logs for the time metrics (after resuming a training).
<add> log_history = state.pop("log_history", None)
<add> log_history1 = state1.pop("log_history", None)
<add> self.assertEqual(state, state1)
<add> for log, log1 in zip(log_history, log_history1):
<add> _ = log.pop("train_runtime", None)
<add> _ = log1.pop("train_runtime", None)
<add> _ = log.pop("train_samples_per_second", None)
<add> _ = log1.pop("train_samples_per_second", None)
<add> self.assertEqual(log, log1)
<add>
<ide> def test_trainer_works_with_dict(self):
<ide> # Edge case because Apex with mode O2 will change our models to return dicts. This test checks it doesn't break
<ide> # anything.
<ide> def test_can_resume_training(self):
<ide> state1 = dataclasses.asdict(trainer.state)
<ide> self.assertEqual(a, a1)
<ide> self.assertEqual(b, b1)
<del> self.assertEqual(state, state1)
<add> self.check_trainer_state_are_the_same(state, state1)
<ide>
<ide> # Now check with a later checkpoint that it also works when we span over one epoch
<ide> checkpoint = os.path.join(tmpdir, "checkpoint-15")
<ide> def test_can_resume_training(self):
<ide> state1 = dataclasses.asdict(trainer.state)
<ide> self.assertEqual(a, a1)
<ide> self.assertEqual(b, b1)
<del> self.assertEqual(state, state1)
<add> self.check_trainer_state_are_the_same(state, state1)
<ide>
<ide> # With a regular model that is not a PreTrainedModel
<ide> with tempfile.TemporaryDirectory() as tmpdir:
<ide> def test_can_resume_training(self):
<ide> state1 = dataclasses.asdict(trainer.state)
<ide> self.assertEqual(a, a1)
<ide> self.assertEqual(b, b1)
<del> self.assertEqual(state, state1)
<add> self.check_trainer_state_are_the_same(state, state1)
<ide>
<ide> # Now check with a later checkpoint that it also works when we span over one epoch
<ide> checkpoint = os.path.join(tmpdir, "checkpoint-15")
<ide> def test_can_resume_training(self):
<ide> state1 = dataclasses.asdict(trainer.state)
<ide> self.assertEqual(a, a1)
<ide> self.assertEqual(b, b1)
<del> self.assertEqual(state, state1)
<add> self.check_trainer_state_are_the_same(state, state1)
<ide>
<ide> def test_resume_training_with_gradient_accumulation(self):
<ide> if torch.cuda.device_count() > 2:
<ide> def test_resume_training_with_gradient_accumulation(self):
<ide> state1 = dataclasses.asdict(trainer.state)
<ide> self.assertEqual(a, a1)
<ide> self.assertEqual(b, b1)
<del> self.assertEqual(state, state1)
<add> self.check_trainer_state_are_the_same(state, state1)
<ide>
<ide> def test_load_best_model_at_end(self):
<ide> total = int(self.n_epochs * 64 / self.batch_size) | 6 |
Python | Python | update linode driver to use authentication classes | 7d19b97acb4d30c0994893f8d10e834ef3fe39e5 | <ide><path>libcloud/drivers/linode.py
<ide> #
<ide>
<ide> from libcloud.types import Provider, NodeState
<del>from libcloud.base import ConnectionKey, Response, NodeDriver, NodeSize, Node, NodeLocation
<add>from libcloud.base import ConnectionKey, Response
<add>from libcloud.base import NodeDriver, NodeSize, Node, NodeLocation
<add>from libcloud.base import NodeAuthPassword, NodeAuthSSHKey
<ide> from libcloud.base import NodeImage
<ide> from copy import copy
<ide>
<ide> def destroy_node(self, node):
<ide> self.connection.request(LINODE_ROOT, params=params)
<ide> return True
<ide>
<del> def create_node(self, options, **kwargs):
<add> def create_node(self, name, options, **kwargs):
<ide> # Create
<ide> #
<ide> # Creates a Linode instance.
<ide> def create_node(self, options, **kwargs):
<ide> if payment not in ["1", "12", "24"]:
<ide> raise LinodeException(0xFB, "Invalid subscription (1, 12, 24)")
<ide>
<add> ssh = None
<add> root = None
<ide> # SSH key and/or root password
<del> ssh = None if "ssh" not in kwargs else kwargs["ssh"]
<del> root = None if "root" not in kwargs else kwargs["root"]
<add> if isinstance(options.auth, NodeAuthSSHKey):
<add> ssh = options.auth.pubkey
<add> elif isinstance(options.auth, NodeAuthPassword):
<add> root = options.auth.password
<add>
<ide> if not ssh and not root:
<ide> raise LinodeException(0xFB, "Need SSH key or root password")
<ide> if len(root) < 6: | 1 |
Text | Text | remove whitespace when testing user input | 037d8635019df67c0556644fd75b85cd734eb084 | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fac56271087806def55b33.md
<ide> assert.equal(document.querySelector('fieldset:nth-child(3) > label:nth-child(3)'
<ide> You should place the text before the `select` element.
<ide>
<ide> ```js
<del>assert.match(document.querySelector('fieldset:nth-child(3) > label:nth-child(3)')?.innerHTML?.replace(/[\t\n]+/g, ''), /^How did you hear about us\?/);
<add>assert.match(document.querySelector('fieldset:nth-child(3) > label:nth-child(3)')?.innerHTML?.trim().replace(/[\t\n]+/g, ''), /^How did you hear about us\?/);
<ide> ```
<ide>
<ide> # --seed-- | 1 |
Ruby | Ruby | improve api document on object#blank? | d309737928cb52deb2bfc2d2342a73d203a68fbd | <ide><path>activesupport/lib/active_support/core_ext/object/blank.rb
<ide> require "concurrent/map"
<ide>
<ide> class Object
<del> # An object is blank if it's false, empty, or a whitespace string.
<del> # For example, +false+, '', ' ', +nil+, [], and {} are all blank.
<add> # An object is blank if it's falsey, empty, or a whitespace string.
<add> # For example, +nil+, +false+, [], {}, '', and ' ' are all blank.
<ide> #
<ide> # This simplifies
<ide> # | 1 |
Ruby | Ruby | follow code conventions on docs | ab880b9eb0aab83e9c000a89e9f0ca636a8b9f78 | <ide><path>actionpack/lib/action_dispatch/routing/url_for.rb
<ide> def url_options
<ide> #
<ide> # Examples:
<ide> #
<del> # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :port=>'8080' # => 'http://somehost.org:8080/tasks/testing'
<del> # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok'
<del> # url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/'
<del> # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33'
<add> # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :port => '8080' # => 'http://somehost.org:8080/tasks/testing'
<add> # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok'
<add> # url_for :controller => 'tasks', :action => 'testing', :trailing_slash => true # => 'http://somehost.org/tasks/testing/'
<add> # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33'
<ide> def url_for(options = nil)
<ide> case options
<ide> when String
<ide><path>actionpack/lib/action_dispatch/testing/assertions/selector.rb
<ide> def css_select(*args)
<ide> # assert_select "title", "Welcome"
<ide> #
<ide> # # Page title is "Welcome" and there is only one title element
<del> # assert_select "title", {:count=>1, :text=>"Welcome"},
<add> # assert_select "title", {:count => 1, :text => "Welcome"},
<ide> # "Wrong title or more than one title element"
<ide> #
<ide> # # Page contains no forms
<ide><path>actionpack/lib/action_view/base.rb
<ide> module ActionView #:nodoc:
<ide> #
<ide> # Here are some basic examples:
<ide> #
<del> # xml.em("emphasized") # => <em>emphasized</em>
<del> # xml.em { xml.b("emph & bold") } # => <em><b>emph & bold</b></em>
<del> # xml.a("A Link", "href"=>"http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
<del> # xml.target("name"=>"compile", "option"=>"fast") # => <target option="fast" name="compile"\>
<del> # # NOTE: order of attributes is not specified.
<add> # xml.em("emphasized") # => <em>emphasized</em>
<add> # xml.em { xml.b("emph & bold") } # => <em><b>emph & bold</b></em>
<add> # xml.a("A Link", "href" => "http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
<add> # xml.target("name" => "compile", "option" => "fast") # => <target option="fast" name="compile"\>
<add> # # NOTE: order of attributes is not specified.
<ide> #
<ide> # Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
<ide> #
<ide><path>actionpack/lib/action_view/helpers/form_options_helper.rb
<ide> def time_zone_select(object, method, priority_zones = nil, options = {}, html_op
<ide> # You can optionally provide html attributes as the last element of the array.
<ide> #
<ide> # Examples:
<del> # options_for_select([ "Denmark", ["USA", {:class=>'bold'}], "Sweden" ], ["USA", "Sweden"])
<add> # options_for_select([ "Denmark", ["USA", {:class => 'bold'}], "Sweden" ], ["USA", "Sweden"])
<ide> # <option value="Denmark">Denmark</option>\n<option value="USA" class="bold" selected="selected">USA</option>\n<option value="Sweden" selected="selected">Sweden</option>
<ide> #
<del> # options_for_select([["Dollar", "$", {:class=>"bold"}], ["Kroner", "DKK", {:onclick => "alert('HI');"}]])
<add> # options_for_select([["Dollar", "$", {:class => "bold"}], ["Kroner", "DKK", {:onclick => "alert('HI');"}]])
<ide> # <option value="$" class="bold">Dollar</option>\n<option value="DKK" onclick="alert('HI');">Kroner</option>
<ide> #
<ide> # If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value
<ide><path>activesupport/lib/active_support/core_ext/hash/slice.rb
<ide> def slice(*keys)
<ide>
<ide> # Replaces the hash with only the given keys.
<ide> # Returns a hash contained the removed key/value pairs
<del> # {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d =>4}
<add> # {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d => 4}
<ide> def slice!(*keys)
<ide> keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key)
<ide> omit = slice(*self.keys - keys) | 5 |
Text | Text | explain use case for `display_value` in docs | eaf61449a85b9563d23b2922425c9ed4a67b7bea | <ide><path>docs/api-guide/relations.md
<ide> to ``True``.
<ide>
<ide> ## The `display_value` method
<ide>
<del>The `__str__` (`__unicode__` on Python 2) method of the model will be called to generate string representations of the objects used to populate the `choices` property. To provide customized representations, override `display_value` of a `RelatedField` subclass. This method will receive a model object, and should return a string suitable for representing it. For example:
<add>The `__str__` (`__unicode__` on Python 2) method of the model will be called to generate string representations of the objects used to populate the `choices` property. These choices are used to populate select HTML inputs in the browsable API. To provide customized representations for such inputs, override `display_value` of a `RelatedField` subclass. This method will receive a model object, and should return a string suitable for representing it. For example:
<ide>
<ide> class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
<ide> def display_value(self, instance): | 1 |
Ruby | Ruby | modify assert conditions not to be affected | 317868d0bd0802d48f29422ce00b8dcddea8ea31 | <ide><path>activerecord/test/cases/relation/merging_test.rb
<ide> def test_relation_merging
<ide> end
<ide>
<ide> def test_relation_to_sql
<del> sql = Post.first.comments.to_sql
<del> assert_no_match(/\?/, sql)
<add> post = Post.first
<add> sql = post.comments.to_sql
<add> assert_match(/.?post_id.? = #{post.id}\Z/i, sql)
<ide> end
<ide>
<ide> def test_relation_merging_with_arel_equalities_keeps_last_equality | 1 |
Text | Text | change object typo to objects | a21b82d15158ea11b1ebd8c680772968836990b3 | <ide><path>docs/docs/ref-09-glossary.md
<ide> In React's terminology, there are five core types that are important to distingu
<ide>
<ide> The primary type in React is the `ReactElement`. It has four properties: `type`, `props`, `key` and `ref`. It has no methods and nothing on the prototype.
<ide>
<del>You can create one of these object through `React.createElement`.
<add>You can create one of these objects through `React.createElement`.
<ide>
<ide> ```javascript
<ide> var root = React.createElement('div'); | 1 |
Java | Java | resolve async model attributes in abstractview | 73b44828e9dba23fec73286829c4583e6342049a | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/AbstractView.java
<ide>
<ide> import java.nio.charset.Charset;
<ide> import java.nio.charset.StandardCharsets;
<del>import java.util.ArrayList;
<del>import java.util.LinkedHashMap;
<del>import java.util.List;
<del>import java.util.Map;
<add>import java.util.*;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<add>import org.springframework.core.ReactiveAdapter;
<add>import org.springframework.core.ReactiveAdapterRegistry;
<add>import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.context.ApplicationContext;
<ide> public abstract class AbstractView implements View, ApplicationContextAware {
<ide> /** Logger that is available to subclasses */
<ide> protected final Log logger = LogFactory.getLog(getClass());
<ide>
<add> private static final Object NO_VALUE = new Object();
<add>
<ide>
<ide> private final List<MediaType> mediaTypes = new ArrayList<>(4);
<ide>
<add> private final ReactiveAdapterRegistry adapterRegistry;
<add>
<ide> private Charset defaultCharset = StandardCharsets.UTF_8;
<ide>
<ide> private String requestContextAttribute;
<ide> public abstract class AbstractView implements View, ApplicationContextAware {
<ide>
<ide>
<ide> public AbstractView() {
<add> this(new ReactiveAdapterRegistry());
<add> }
<add>
<add> public AbstractView(ReactiveAdapterRegistry registry) {
<ide> this.mediaTypes.add(ViewResolverSupport.DEFAULT_CONTENT_TYPE);
<add> this.adapterRegistry = registry;
<ide> }
<ide>
<ide>
<ide> public Mono<Void> render(Map<String, ?> model, MediaType contentType,
<ide> exchange.getResponse().getHeaders().setContentType(contentType);
<ide> }
<ide>
<del> Map<String, Object> mergedModel = getModelAttributes(model, exchange);
<del>
<del> // Expose RequestContext?
<del> if (this.requestContextAttribute != null) {
<del> mergedModel.put(this.requestContextAttribute, createRequestContext(exchange, mergedModel));
<del> }
<del>
<del> return renderInternal(mergedModel, contentType, exchange);
<add> return getModelAttributes(model, exchange).then(mergedModel -> {
<add> // Expose RequestContext?
<add> if (this.requestContextAttribute != null) {
<add> mergedModel.put(this.requestContextAttribute, createRequestContext(exchange, mergedModel));
<add> }
<add> return renderInternal(mergedModel, contentType, exchange);
<add> });
<ide> }
<ide>
<ide> /**
<ide> * Prepare the model to use for rendering.
<ide> * <p>The default implementation creates a combined output Map that includes
<ide> * model as well as static attributes with the former taking precedence.
<ide> */
<del> protected Map<String, Object> getModelAttributes(Map<String, ?> model, ServerWebExchange exchange) {
<add> protected Mono<Map<String, Object>> getModelAttributes(Map<String, ?> model, ServerWebExchange exchange) {
<ide> int size = (model != null ? model.size() : 0);
<ide>
<ide> Map<String, Object> attributes = new LinkedHashMap<>(size);
<ide> if (model != null) {
<ide> attributes.putAll(model);
<ide> }
<ide>
<del> return attributes;
<add> return resolveAsyncAttributes(attributes).then(Mono.just(attributes));
<add> }
<add>
<add> /**
<add> * By default, resolve async attributes supported by the {@link ReactiveAdapterRegistry} to their blocking counterparts.
<add> * <p>View implementations capable of taking advantage of reactive types can override this method if needed.
<add> * @return {@code Mono} to represent when the async attributes have been resolved
<add> */
<add> protected Mono<Void> resolveAsyncAttributes(Map<String, Object> model) {
<add>
<add> List<String> names = new ArrayList<>();
<add> List<Mono<?>> valueMonos = new ArrayList<>();
<add>
<add> for (Map.Entry<String, ?> entry : model.entrySet()) {
<add> Object value = entry.getValue();
<add> if (value == null) {
<add> continue;
<add> }
<add> ReactiveAdapter adapter = this.adapterRegistry.getAdapter(null, value);
<add> if (adapter != null) {
<add> names.add(entry.getKey());
<add> if (adapter.isMultiValue()) {
<add> Flux<Object> fluxValue = Flux.from(adapter.toPublisher(value));
<add> valueMonos.add(fluxValue.collectList().defaultIfEmpty(Collections.emptyList()));
<add> }
<add> else {
<add> Mono<Object> monoValue = Mono.from(adapter.toPublisher(value));
<add> valueMonos.add(monoValue.defaultIfEmpty(NO_VALUE));
<add> }
<add> }
<add> }
<add>
<add> if (names.isEmpty()) {
<add> return Mono.empty();
<add> }
<add>
<add> return Mono.when(valueMonos,
<add> values -> {
<add> for (int i=0; i < values.length; i++) {
<add> if (values[i] != NO_VALUE) {
<add> model.put(names.get(i), values[i]);
<add> }
<add> else {
<add> model.remove(names.get(i));
<add> }
<add> }
<add> return NO_VALUE;
<add> })
<add> .then();
<ide> }
<ide>
<ide> /**
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandler.java
<ide> else if (CharSequence.class.isAssignableFrom(clazz) && !hasModelAnnotation(param
<ide> viewsMono = resolveViews(getDefaultViewName(exchange), locale);
<ide> }
<ide>
<del> return resolveAsyncAttributes(model.asMap())
<del> .doOnSuccess(aVoid -> addBindingResult(result.getBindingContext(), exchange))
<del> .then(viewsMono)
<del> .then(views -> render(views, model.asMap(), exchange));
<add> addBindingResult(result.getBindingContext(), exchange);
<add>
<add> return viewsMono.then(views -> render(views, model.asMap(), exchange));
<ide> });
<ide> }
<ide>
<ide> private String getNameForReturnValue(Class<?> returnValueType, MethodParameter r
<ide> return ClassUtils.getShortNameAsProperty(returnValueType);
<ide> }
<ide>
<del> private Mono<Void> resolveAsyncAttributes(Map<String, Object> model) {
<del>
<del> List<String> names = new ArrayList<>();
<del> List<Mono<?>> valueMonos = new ArrayList<>();
<ide>
<del> for (Map.Entry<String, ?> entry : model.entrySet()) {
<del> ReactiveAdapter adapter = getAdapterRegistry().getAdapter(null, entry.getValue());
<del> if (adapter != null) {
<del> names.add(entry.getKey());
<del> if (adapter.isMultiValue()) {
<del> Flux<Object> value = Flux.from(adapter.toPublisher(entry.getValue()));
<del> valueMonos.add(value.collectList().defaultIfEmpty(Collections.emptyList()));
<del> }
<del> else {
<del> Mono<Object> value = Mono.from(adapter.toPublisher(entry.getValue()));
<del> valueMonos.add(value.defaultIfEmpty(NO_VALUE));
<del> }
<del> }
<del> }
<del>
<del> if (names.isEmpty()) {
<del> return Mono.empty();
<del> }
<del>
<del> return Mono.when(valueMonos,
<del> values -> {
<del> for (int i=0; i < values.length; i++) {
<del> if (values[i] != NO_VALUE) {
<del> model.put(names.get(i), values[i]);
<del> }
<del> else {
<del> model.remove(names.get(i));
<del> }
<del> }
<del> return NO_VALUE;
<del> })
<del> .then();
<del> }
<ide>
<ide> private void addBindingResult(BindingContext context, ServerWebExchange exchange) {
<ide> Map<String, Object> model = context.getModel().asMap();
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/view/AbstractViewTests.java
<add>package org.springframework.web.reactive.result.view;
<add>
<add>import io.reactivex.Observable;
<add>import io.reactivex.Single;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
<add>import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
<add>import org.springframework.tests.sample.beans.TestBean;
<add>import org.springframework.ui.Model;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import reactor.core.publisher.Flux;
<add>import reactor.core.publisher.Mono;
<add>import reactor.test.StepVerifier;
<add>
<add>import java.util.HashMap;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.logging.Level;
<add>
<add>import static org.junit.Assert.assertArrayEquals;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertNull;
<add>
<add>/**
<add> * Unit tests for {@link AbstractView}.
<add> *
<add> * @author Sebastien Deleuze
<add> */
<add>public class AbstractViewTests {
<add>
<add> private MockServerWebExchange exchange;
<add>
<add> @Before
<add> public void setup() {
<add> this.exchange = MockServerHttpRequest.get("/").toExchange();
<add> }
<add>
<add> @Test
<add> public void resolveAsyncAttributes() {
<add>
<add> TestBean testBean1 = new TestBean("Bean1");
<add> TestBean testBean2 = new TestBean("Bean2");
<add> Map<String, Object> attributes = new HashMap();
<add> attributes.put("attr1", Mono.just(testBean1));
<add> attributes.put("attr2", Flux.just(testBean1, testBean2));
<add> attributes.put("attr3", Single.just(testBean2));
<add> attributes.put("attr4", Observable.just(testBean1, testBean2));
<add> attributes.put("attr5", Mono.empty());
<add>
<add> TestView view = new TestView();
<add> StepVerifier.create(view.render(attributes, null, this.exchange)).verifyComplete();
<add>
<add> assertEquals(testBean1, view.attributes.get("attr1"));
<add> assertArrayEquals(new TestBean[] {testBean1, testBean2}, ((List<TestBean>)view.attributes.get("attr2")).toArray());
<add> assertEquals(testBean2, view.attributes.get("attr3"));
<add> assertArrayEquals(new TestBean[] {testBean1, testBean2}, ((List<TestBean>)view.attributes.get("attr4")).toArray());
<add> assertNull(view.attributes.get("attr5"));
<add> }
<add>
<add>
<add> private static class TestView extends AbstractView {
<add>
<add> private Map<String, Object> attributes;
<add>
<add> @Override
<add> protected Mono<Void> renderInternal(Map<String, Object> renderAttributes, MediaType contentType, ServerWebExchange exchange) {
<add> this.attributes = renderAttributes;
<add> return Mono.empty();
<add> }
<add>
<add> public Map<String, Object> getAttributes() {
<add> return this.attributes;
<add> }
<add> }
<add>}
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java
<ide> public void noUrlSet() throws Exception {
<ide> public void defaultStatusCode() {
<ide> String url = "http://url.somewhere.com";
<ide> RedirectView view = new RedirectView(url);
<del> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
<add> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block();
<ide> assertEquals(HttpStatus.SEE_OTHER, this.exchange.getResponse().getStatusCode());
<ide> assertEquals(URI.create(url), this.exchange.getResponse().getHeaders().getLocation());
<ide> }
<ide> public void defaultStatusCode() {
<ide> public void customStatusCode() {
<ide> String url = "http://url.somewhere.com";
<ide> RedirectView view = new RedirectView(url, HttpStatus.FOUND);
<del> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
<add> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block();
<ide> assertEquals(HttpStatus.FOUND, this.exchange.getResponse().getStatusCode());
<ide> assertEquals(URI.create(url), this.exchange.getResponse().getHeaders().getLocation());
<ide> }
<ide> public void customStatusCode() {
<ide> public void contextRelative() {
<ide> String url = "/test.html";
<ide> RedirectView view = new RedirectView(url);
<del> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
<add> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block();
<ide> assertEquals(URI.create("/context/test.html"), this.exchange.getResponse().getHeaders().getLocation());
<ide> }
<ide>
<ide> @Test
<ide> public void contextRelativeQueryParam() {
<ide> String url = "/test.html?id=1";
<ide> RedirectView view = new RedirectView(url);
<del> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
<add> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block();
<ide> assertEquals(URI.create("/context/test.html?id=1"), this.exchange.getResponse().getHeaders().getLocation());
<ide> }
<ide>
<ide> public void expandUriTemplateVariablesFromModel() {
<ide> String url = "http://url.somewhere.com?foo={foo}";
<ide> Map<String, String> model = Collections.singletonMap("foo", "bar");
<ide> RedirectView view = new RedirectView(url);
<del> view.render(model, MediaType.TEXT_HTML, this.exchange);
<add> view.render(model, MediaType.TEXT_HTML, this.exchange).block();
<ide> assertEquals(URI.create("http://url.somewhere.com?foo=bar"), this.exchange.getResponse().getHeaders().getLocation());
<ide> }
<ide>
<ide> public void expandUriTemplateVariablesFromExchangeAttribute() {
<ide> Map<String, String> attributes = Collections.singletonMap("foo", "bar");
<ide> this.exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, attributes);
<ide> RedirectView view = new RedirectView(url);
<del> view.render(new HashMap<>(), MediaType.TEXT_HTML, exchange);
<add> view.render(new HashMap<>(), MediaType.TEXT_HTML, exchange).block();
<ide> assertEquals(URI.create("http://url.somewhere.com?foo=bar"), this.exchange.getResponse().getHeaders().getLocation());
<ide> }
<ide>
<ide> public void propagateQueryParams() throws Exception {
<ide> RedirectView view = new RedirectView("http://url.somewhere.com?foo=bar#bazz");
<ide> view.setPropagateQuery(true);
<ide> this.exchange = MockServerHttpRequest.get("http://url.somewhere.com?a=b&c=d").toExchange();
<del> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
<add> view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block();
<ide> assertEquals(HttpStatus.SEE_OTHER, this.exchange.getResponse().getStatusCode());
<ide> assertEquals(URI.create("http://url.somewhere.com?foo=bar&a=b&c=d#bazz"),
<ide> this.exchange.getResponse().getHeaders().getLocation());
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandlerTests.java
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.test.StepVerifier;
<ide> import rx.Completable;
<del>import rx.Observable;
<ide> import rx.Single;
<ide>
<ide> import org.springframework.core.MethodParameter;
<ide> public void contentNegotiationWith406() throws Exception {
<ide> .verify();
<ide> }
<ide>
<del> @Test
<del> public void modelWithAsyncAttributes() throws Exception {
<del> this.bindingContext.getModel()
<del> .addAttribute("attr1", Mono.just(new TestBean("Bean1")))
<del> .addAttribute("attr2", Flux.just(new TestBean("Bean1"), new TestBean("Bean2")))
<del> .addAttribute("attr3", Single.just(new TestBean("Bean2")))
<del> .addAttribute("attr4", Observable.just(new TestBean("Bean1"), new TestBean("Bean2")))
<del> .addAttribute("attr5", Mono.empty());
<del>
<del> MethodParameter returnType = on(TestController.class).resolveReturnType(void.class);
<del> HandlerResult result = new HandlerResult(new Object(), null, returnType, this.bindingContext);
<del> ViewResolutionResultHandler handler = resultHandler(new TestViewResolver("account"));
<del>
<del> MockServerWebExchange exchange = get("/account").toExchange();
<del>
<del> handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
<del> assertResponseBody(exchange, "account: {" +
<del> "attr1=TestBean[name=Bean1], " +
<del> "attr2=[TestBean[name=Bean1], TestBean[name=Bean2]], " +
<del> "attr3=TestBean[name=Bean2], " +
<del> "attr4=[TestBean[name=Bean1], TestBean[name=Bean2]], " +
<del> "org.springframework.validation.BindingResult.attr1=" +
<del> "org.springframework.validation.BeanPropertyBindingResult: 0 errors, " +
<del> "org.springframework.validation.BindingResult.attr3=" +
<del> "org.springframework.validation.BeanPropertyBindingResult: 0 errors" +
<del> "}");
<del> }
<del>
<ide>
<ide> private ViewResolutionResultHandler resultHandler(ViewResolver... resolvers) {
<ide> return resultHandler(Collections.emptyList(), resolvers); | 5 |
Java | Java | fix method comment for getrequiredproperty(string) | 0dc52a83432ae3e52862bb8f257774bb8c345795 | <ide><path>spring-core/src/main/java/org/springframework/core/env/PropertyResolver.java
<ide> public interface PropertyResolver {
<ide> <T> Class<T> getPropertyAsClass(String key, Class<T> targetType);
<ide>
<ide> /**
<del> * Return the property value associated with the given key, converted to the given
<del> * targetType (never {@code null}).
<add> * Return the property value associated with the given key (never {@code null}).
<ide> * @throws IllegalStateException if the key cannot be resolved
<ide> * @see #getRequiredProperty(String, Class)
<ide> */ | 1 |
Javascript | Javascript | pass safemode and devmode on reopening a project | e6368a566d0dbe89d05d626db13f96ca9af20e89 | <ide><path>src/atom-environment.js
<ide> class AtomEnvironment {
<ide> commands: this.commands,
<ide> history: this.history,
<ide> config: this.config,
<del> open: paths => this.open({ pathsToOpen: paths })
<add> open: paths =>
<add> this.open({
<add> pathsToOpen: paths,
<add> safeMode: this.inSafeMode(),
<add> devMode: this.inDevMode()
<add> })
<ide> });
<ide> this.reopenProjectMenuManager.update();
<ide> });
<ide><path>src/main-process/atom-application.js
<ide> module.exports = class AtomApplication extends EventEmitter {
<ide>
<ide> if (process.platform === 'darwin') {
<ide> this.on('application:reopen-project', ({ paths }) => {
<add> const focusedWindow = this.focusedWindow();
<add> if (focusedWindow) {
<add> const { safeMode, devMode } = focusedWindow;
<add> this.openPaths({ pathsToOpen: paths, safeMode, devMode });
<add> return;
<add> }
<ide> this.openPaths({ pathsToOpen: paths });
<ide> });
<ide> | 2 |
Javascript | Javascript | fix url nitpicks | 39d2f8f7f3fe62d9197a6eb3aaddad94e6d29e52 | <ide><path>lib/NormalModuleFactory.js
<ide> class NormalModuleFactory extends ModuleFactory {
<ide> contextDependencies
<ide> } = data;
<ide> const dependencyType =
<del> dependencies.length > 0 ? dependencies[0].category : undefined;
<add> (dependencies.length > 0 && dependencies[0].category) || "";
<ide> const loaderResolver = this.getResolver("loader");
<ide>
<ide> /** @type {ResourceData | undefined} */
<ide><path>lib/dependencies/RequireContextDependencyParserPlugin.js
<ide> module.exports = class RequireContextDependencyParserPlugin {
<ide> request: requestExpr.string,
<ide> recursive,
<ide> regExp,
<del> mode
<add> mode,
<add> category: "commonjs"
<ide> },
<ide> expr.range
<ide> );
<ide><path>lib/dependencies/URLPlugin.js
<ide> class URLPlugin {
<ide>
<ide> /**
<ide> * @param {JavascriptParser} parser parser
<add> * @param {object} parserOptions options
<ide> */
<del> const parserCallback = parser => {
<add> const parserCallback = (parser, parserOptions) => {
<add> if (parserOptions.url === false) return;
<ide> parser.hooks.canRename.for("URL").tap("URLPlugin", approve);
<ide> parser.hooks.new.for("URL").tap("URLPlugin", _expr => {
<ide> const expr = /** @type {NewExpressionNode} */ (_expr); | 3 |
Ruby | Ruby | add regression test for ipspoofattackerror issue | 228d2b1e935583f0c5bd64227ff157c346cbbb3d | <ide><path>actionpack/test/dispatch/request_test.rb
<ide> def url_for(options = {})
<ide> assert_equal '1.1.1.1', request.remote_ip
<ide> end
<ide>
<add> test "remote ip spoof protection ignores private addresses" do
<add> request = stub_request 'HTTP_X_FORWARDED_FOR' => '172.17.19.51',
<add> 'HTTP_CLIENT_IP' => '172.17.19.51',
<add> 'REMOTE_ADDR' => '1.1.1.1',
<add> 'HTTP_X_BLUECOAT_VIA' => 'de462e07a2db325e'
<add> assert_equal '1.1.1.1', request.remote_ip
<add> end
<add>
<ide> test "remote ip v6" do
<ide> request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334'
<ide> assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip | 1 |
PHP | PHP | fakefor() | f59268ec56b7f157303132a408ba08b257f156d2 | <ide><path>src/Illuminate/Support/Facades/Event.php
<ide> public static function fake($eventsToFake = [])
<ide> *
<ide> * @param callable $callable
<ide> * @param array $eventsToFake
<del> * @return callable
<add> * @return mixed
<ide> */
<ide> public static function fakeFor(callable $callable, array $eventsToFake = [])
<ide> { | 1 |
Python | Python | fix dropout in tfmobilebert | f1679d7c48cc6aac40fd84422734c37950947ab2 | <ide><path>src/transformers/modeling_tf_mobilebert.py
<ide> def call(self, inputs, training=False):
<ide>
<ide> hidden_states = self.dense(hidden_states)
<ide> if not self.use_bottleneck:
<del> hidden_states = self.dropout(hidden_states)
<add> hidden_states = self.dropout(hidden_states, training=training)
<ide> hidden_states = self.LayerNorm(hidden_states + residual_tensor_1)
<ide> else:
<ide> hidden_states = self.LayerNorm(hidden_states + residual_tensor_1) | 1 |
Javascript | Javascript | remove unneeded closure | b0d9a7415cf48e0d1b8185e06056879b0139a596 | <ide><path>src/math/Quaternion.js
<ide> Object.assign( Quaternion.prototype, {
<ide>
<ide> },
<ide>
<del> setFromUnitVectors: function () {
<add> setFromUnitVectors: function ( vFrom, vTo ) {
<ide>
<ide> // assumes direction vectors vFrom and vTo are normalized
<ide>
<del> var r;
<del>
<ide> var EPS = 0.000001;
<ide>
<del> return function setFromUnitVectors( vFrom, vTo ) {
<del>
<del> r = vFrom.dot( vTo ) + 1;
<del>
<del> if ( r < EPS ) {
<del>
<del> r = 0;
<add> var r = vFrom.dot( vTo ) + 1;
<ide>
<del> if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
<add> if ( r < EPS ) {
<ide>
<del> this._x = - vFrom.y;
<del> this._y = vFrom.x;
<del> this._z = 0;
<del> this._w = r;
<add> r = 0;
<ide>
<del> } else {
<add> if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
<ide>
<del> this._x = 0;
<del> this._y = - vFrom.z;
<del> this._z = vFrom.y;
<del> this._w = r;
<del>
<del> }
<add> this._x = - vFrom.y;
<add> this._y = vFrom.x;
<add> this._z = 0;
<add> this._w = r;
<ide>
<ide> } else {
<ide>
<del> // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
<del>
<del> this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
<del> this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
<del> this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
<add> this._x = 0;
<add> this._y = - vFrom.z;
<add> this._z = vFrom.y;
<ide> this._w = r;
<ide>
<ide> }
<ide>
<del> return this.normalize();
<add> } else {
<ide>
<del> };
<add> // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
<ide>
<del> }(),
<add> this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
<add> this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
<add> this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
<add> this._w = r;
<add>
<add> }
<add>
<add> return this.normalize();
<add>
<add> },
<ide>
<ide> angleTo: function ( q ) {
<ide> | 1 |
Text | Text | fix a formatting error in buffer.md | ffe8dffbc4f7e1582e77c4b21e2ca21c54043269 | <ide><path>doc/api/buffer.md
<ide> const buf = Buffer.from(arr.buffer, 0, 16);
<ide> console.log(buf.length);
<ide> ```
<ide>
<del>The `Buffer.from()` and [`TypedArray.from()`] (e.g. `Uint8Array.from()`) have
<del>different signatures and implementations. Specifically, the [`TypedArray`] variants
<del>accept a second argument that is a mapping function that is invoked on every
<del>element of the typed array:
<add>The `Buffer.from()` and [`TypedArray.from()`] have different signatures and
<add>implementations. Specifically, the [`TypedArray`] variants accept a second
<add>argument that is a mapping function that is invoked on every element of the
<add>typed array:
<ide>
<ide> * `TypedArray.from(source[, mapFn[, thisArg]])`
<ide>
<ide> A `TypeError` will be thrown if `size` is not a number.
<ide>
<ide> Note that the `Buffer` module pre-allocates an internal `Buffer` instance of
<ide> size [`Buffer.poolSize`] that is used as a pool for the fast allocation of new
<del>`Buffer` instances created using [`Buffer.allocUnsafe()`] (and the deprecated
<del>`new Buffer(size)` constructor) only when `size` is less than or equal to
<add>`Buffer` instances created using [`Buffer.allocUnsafe()`] and the deprecated
<add>`new Buffer(size)` constructor only when `size` is less than or equal to
<ide> `Buffer.poolSize >> 1` (floor of [`Buffer.poolSize`] divided by two).
<ide>
<ide> Use of this pre-allocated internal memory pool is a key difference between | 1 |
PHP | PHP | remove code that doesn't really need to exist | 9fc56cbab9ef7ebc67db17fd915238e35019e35e | <ide><path>src/Core/Configure.php
<ide> public static function load($key, $config = 'default', $merge = true) {
<ide> $values = $engine->read($key);
<ide>
<ide> if ($merge) {
<del> $keys = array_keys($values);
<del> foreach ($keys as $key) {
<del> $current = Hash::get(static::$_values, $key);
<del> if ($current && is_array($values[$key]) && is_array($current)) {
<del> $values[$key] = Hash::merge($current, $values[$key]);
<del> }
<del> }
<add> $values = Hash::merge(static::$_values, $values);
<ide> }
<ide>
<ide> return static::write($values); | 1 |
Javascript | Javascript | add support for empty catch clause | 8a38c4bd34faf47002b4f087074e6751382f57a0 | <ide><path>lib/Parser.js
<ide> class Parser extends Tapable {
<ide> this.scope.renames.set(param, null);
<ide> this.scope.definitions.add(param);
<ide> });
<del> } else {
<add> } else if(param) {
<ide> this.scope.renames.set(param, null);
<ide> this.scope.definitions.add(param);
<ide> } | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.