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
use fixture files
6fb0e24adddb2c00e6d5a7efd2fb97fac2c34e2f
<ide><path>node-tests/blueprints/route-test-test.js <ide> const chai = require('ember-cli-blueprint-test-helpers/chai'); <ide> const expect = chai.expect; <ide> <ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest'); <add>const fixture = require('../helpers/fixture'); <ide> <ide> describe('Blueprint: route-test', function() { <ide> setupTestHooks(this); <ide> describe('Blueprint: route-test', function() { <ide> it('route-test foo', function() { <ide> return emberGenerateDestroy(['route-test', 'foo'], (_file) => { <ide> expect(_file('tests/unit/routes/foo-test.js')) <del> .to.contain('import { moduleFor, test } from \'ember-qunit\';') <del> .to.contain('moduleFor(\'route:foo\''); <add> .to.equal(fixture('route-test/default.js')); <ide> }); <ide> }); <ide> <ide> describe('Blueprint: route-test', function() { <ide> it('route-test foo', function() { <ide> return emberGenerateDestroy(['route-test', 'foo'], (_file) => { <ide> expect(_file('tests/unit/routes/foo-test.js')) <del> .to.contain('import { describeModule, it } from \'ember-mocha\';') <del> .to.contain('describeModule(\'route:foo\', \'Unit | Route | foo\''); <add> .to.equal(fixture('route-test/mocha.js')); <ide> }); <ide> }); <ide> }); <ide> describe('Blueprint: route-test', function() { <ide> it('route-test foo', function() { <ide> return emberGenerateDestroy(['route-test', 'foo'], (_file) => { <ide> expect(_file('tests/unit/routes/foo-test.js')) <del> .to.contain('import { describe, it } from \'mocha\';') <del> .to.contain('import { setupTest } from \'ember-mocha\';') <del> .to.contain('describe(\'Unit | Route | foo\', function() {') <del> .to.contain('setupTest(\'route:foo\','); <add> .to.equal(fixture('route-test/mocha-0.12.js')); <ide> }); <ide> }); <ide> }); <ide> describe('Blueprint: route-test', function() { <ide> it('route-test foo', function() { <ide> return emberGenerateDestroy(['route-test', 'foo'], (_file) => { <ide> expect(_file('tests/unit/routes/foo-test.js')) <del> .to.contain('import { moduleFor, test } from \'ember-qunit\';') <del> .to.contain('moduleFor(\'route:foo\''); <add> .to.equal(fixture('route-test/default.js')); <ide> }); <ide> }); <ide> }); <ide><path>node-tests/fixtures/route-test/default.js <add>import { moduleFor, test } from 'ember-qunit'; <add> <add>moduleFor('route:foo', 'Unit | Route | foo', { <add> // Specify the other units that are required for this test. <add> // needs: ['controller:foo'] <add>}); <add> <add>test('it exists', function(assert) { <add> let route = this.subject(); <add> assert.ok(route); <add>}); <ide><path>node-tests/fixtures/route-test/mocha-0.12.js <add>import { expect } from 'chai'; <add>import { describe, it } from 'mocha'; <add>import { setupTest } from 'ember-mocha'; <add> <add>describe('Unit | Route | foo', function() { <add> setupTest('route:foo', { <add> // Specify the other units that are required for this test. <add> // needs: ['controller:foo'] <add> }); <add> <add> it('exists', function() { <add> let route = this.subject(); <add> expect(route).to.be.ok; <add> }); <add>}); <ide><path>node-tests/fixtures/route-test/mocha.js <add>import { expect } from 'chai'; <add>import { describeModule, it } from 'ember-mocha'; <add> <add>describeModule('route:foo', 'Unit | Route | foo', <add> { <add> // Specify the other units that are required for this test. <add> // needs: ['controller:foo'] <add> }, <add> function() { <add> it('exists', function() { <add> let route = this.subject(); <add> expect(route).to.be.ok; <add> }); <add> } <add>);
4
Go
Go
replace unreachable returns with panics
22f1cc955dbf25132e69d126f8db0e5498bffbd2
<ide><path>container.go <ide> func (container *Container) WaitTimeout(timeout time.Duration) error { <ide> case <-done: <ide> return nil <ide> } <del> return nil <add> panic("unreachable") <ide> } <ide> <ide> func (container *Container) EnsureMounted() error { <ide><path>network.go <ide> func (alloc *PortAllocator) Release(port int) error { <ide> default: <ide> return errors.New("Too many ports have been released") <ide> } <del> return nil <add> panic("unreachable") <ide> } <ide> <ide> func newPortAllocator(start, end int) (*PortAllocator, error) { <ide><path>utils.go <ide> func (r *bufReader) Read(p []byte) (n int, err error) { <ide> } <ide> r.wait.Wait() <ide> } <del> return <add> panic("unreachable") <ide> } <ide> <ide> func (r *bufReader) Close() error {
3
PHP
PHP
move number to i18n
85c294ab0ae41e247a2fa3ed25d64d4f07c768e4
<ide><path>src/I18n/LocalizedNumber.php <ide> */ <ide> namespace Cake\I18n; <ide> <del>use Cake\Utility\Number; <add>use Cake\I18n\Number; <ide> <ide> /** <ide> * Number helper library. <add><path>src/I18n/Number.php <del><path>src/Utility/Number.php <ide> * @since 0.10.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Utility; <add>namespace Cake\I18n; <ide> <ide> use Cake\Core\Exception\Exception; <ide> use NumberFormatter; <add><path>tests/TestCase/I18n/NumberTest.php <del><path>tests/TestCase/Utility/NumberTest.php <ide> * @since 1.2.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Utility; <add>namespace Cake\Test\TestCase\I18n; <ide> <ide> use Cake\I18n\I18n; <add>use Cake\I18n\Number; <ide> use Cake\TestSuite\TestCase; <del>use Cake\Utility\Number; <ide> <ide> /** <ide> * NumberTest class
3
Python
Python
use m for matrix instead of a for array
b6ba4addafc0782fc3219b73fa67ec8f3f37adaa
<ide><path>numpy/matrixlib/defmatrix.py <ide> def flatten(self, order='C'): <ide> ---------- <ide> order : {'C', 'F', 'A'}, optional <ide> Whether to flatten in C (row-major), Fortran (column-major) order, <del> or preserve the C/Fortran ordering from `a`. <add> or preserve the C/Fortran ordering from `m`. <ide> The default is 'C'. <ide> <ide> Returns <ide> def flatten(self, order='C'): <ide> <ide> Examples <ide> -------- <del> >>> a = np.matrix([[1,2], [3,4]]) <del> >>> a.flatten() <add> >>> m = np.matrix([[1,2], [3,4]]) <add> >>> m.flatten() <ide> matrix([[1, 2, 3, 4]]) <del> >>> a.flatten('F') <add> >>> m.flatten('F') <ide> matrix([[1, 3, 2, 4]]) <ide> <ide> """
1
Ruby
Ruby
enforce uses_from_macos only if core tap
4bd6c343d0906c3ae7c93926ea41fc64f1b05e46
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_deps <ide> "use the canonical name '#{dep.to_formula.full_name}'." <ide> end <ide> <del> if @new_formula && <add> if @core_tap && <add> @new_formula && <ide> dep_f.keg_only? && <ide> dep_f.keg_only_reason.provided_by_macos? && <ide> dep_f.keg_only_reason.applicable? && <ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb <ide> class Foo < Formula <ide> subject { fa } <ide> <ide> let(:fa) do <del> formula_auditor "foo", <<~RUBY, new_formula: true <add> formula_auditor "foo", <<~RUBY, new_formula: true, core_tap: true <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <ide> homepage "https://brew.sh"
2
Text
Text
fix broken link
2dffdf5ddf91d9a2d55b18a887c6bdcb56cec4ed
<ide><path>docs/Brew-Test-Bot.md <ide> by [our Kickstarter in 2013](https://www.kickstarter.com/projects/homebrew/brew- <ide> <ide> It comprises four Mac Minis and three Xserves running in two data centres which host <ide> [a Jenkins instance at https://jenkins.brew.sh](https://jenkins.brew.sh) and run the <del>[`brew-test-bot.rb`](https://github.com/Homebrew/homebrew-test-bot/blob/master/cmd/brew-test-bot.rb) <add>[`test-bot.rb`](https://github.com/Homebrew/homebrew-test-bot/blob/master/cmd/test-bot.rb) <ide> Ruby script to perform automated testing of commits to the master branch, pull <ide> requests and custom builds requested by maintainers. <ide>
1
Javascript
Javascript
add dollar sign back to setsubmitted()
7ef2921caee2be24102e153f22ea79d679f582cb
<ide><path>src/ng/directive/form.js <ide> function FormController(element, attrs, $scope, $animate) { <ide> <ide> /** <ide> * @ngdoc method <del> * @name form.FormController#setSubmitted <add> * @name form.FormController#$setSubmitted <ide> * <ide> * @description <ide> * Sets the form to its submitted state.
1
Javascript
Javascript
add csp support
2b1b2570344cfb55ba93b6f184bd3ee6db324419
<ide><path>lib/nodeserver/server.js <ide> StaticServlet.prototype.sendFile_ = function(req, res, path) { <ide> var self = this; <ide> var file = fs.createReadStream(path); <ide> res.writeHead(200, { <add> // CSP headers, uncomment to enable CSP <add> //"X-WebKit-CSP": "default-src 'self';", <add> //"X-Content-Security-Policy": "default-src 'self'", <ide> 'Content-Type': StaticServlet. <ide> MimeMap[path.split('.').pop()] || 'text/plain' <ide> });
1
Python
Python
revoke tests passing
cbba57c2269f35e1eb16c56444cabc30e70eace1
<ide><path>celery/tests/worker/test_control.py <ide> def test_revoke(self): <ide> def test_revoke_terminate(self): <ide> request = Mock() <ide> request.id = tid = uuid() <del> state.active_requests.add(request) <add> state.reserved_requests.add(request) <ide> try: <ide> r = control.revoke(Mock(), tid, terminate=True) <ide> self.assertIn(tid, revoked) <ide> self.assertTrue(request.terminate.call_count) <del> self.assertIn('terminated', r['ok']) <add> self.assertIn('terminating', r['ok']) <ide> # unknown task id only revokes <ide> r = control.revoke(Mock(), uuid(), terminate=True) <del> self.assertIn('revoked', r['ok']) <add> self.assertIn('not found', r['ok']) <ide> finally: <del> state.active_requests.discard(request) <add> state.reserved_requests.discard(request) <ide> <ide> def test_autoscale(self): <ide> self.panel.state.consumer = Mock()
1
Python
Python
add missing minus sign
9e7f462b0dc386a856ec07c21876b07016c9258b
<ide><path>numpy/doc/basics.py <ide> int8 Byte (-128 to 127) <ide> int16 Integer (-32768 to 32767) <ide> int32 Integer (-2147483648 to 2147483647) <del>int64 Integer (9223372036854775808 to 9223372036854775807) <add>int64 Integer (-9223372036854775808 to 9223372036854775807) <ide> uint8 Unsigned integer (0 to 255) <ide> uint16 Unsigned integer (0 to 65535) <ide> uint32 Unsigned integer (0 to 4294967295)
1
Text
Text
replace the code sample in all the languages
ccfd1ffb30bd806dcc098c5bf60f9e5988e8b951
<ide><path>docs/docs/tutorial.it-IT.md <ide> Ma c'è un problema! I nostri commenti visualizzati appaiono come segue nel brow <ide> <ide> Questo è il risultato della protezione di React da parte di un [attacco XSS](https://en.wikipedia.org/wiki/Cross-site_scripting). C'è una maniera di aggirare questo comportamento, ma il framework ti avvisa di non farlo: <ide> <del>```javascript{4,10} <add>```javascript{3-6,14} <ide> // tutorial7.js <ide> var Comment = React.createClass({ <ide> rawMarkup: function() { <ide><path>docs/docs/tutorial.ja-JP.md <ide> Markdown はインラインでテキストをフォーマットする簡単な <ide> <ide> 次に、Markdown で書かれたコメントを変換して出力してみましょう。 <ide> <del>```javascript{2,10} <add>```javascript{9} <ide> // tutorial6.js <ide> var Comment = React.createClass({ <ide> render: function() { <ide> var Comment = React.createClass({ <ide> <ide> このような現象が起きるのは React が XSS 攻撃に対する防御を行っているからです。これを回避する方法はありますが、それを使うときにはフレームワークが警告をします。 <ide> <del>```javascript{5,11} <add>```javascript{3-6,14} <ide> // tutorial7.js <ide> var Comment = React.createClass({ <del> render: function() { <add> rawMarkup: function() { <ide> var rawMarkup = marked(this.props.children.toString(), {sanitize: true}); <add> return { __html: rawMarkup }; <add> }, <add> <add> render: function() { <ide> return ( <ide> <div className="comment"> <ide> <h2 className="commentAuthor"> <ide> {this.props.author} <ide> </h2> <del> <span dangerouslySetInnerHTML={{"{{"}}__html: rawMarkup}} /> <add> <span dangerouslySetInnerHTML={this.rawMarkup()} /> <ide> </div> <ide> ); <ide> } <ide> var CommentBox = React.createClass({ <ide> #### State の更新 <ide> コンポーネントの作成と同時に、サーバから JSON データを GET で取得し、state を更新して最新のデータを反映させてみましょう。実際のアプリケーションでは動的なエンドポイントになるでしょうが、今回の例では話を簡単にするため、以下の静的な JSON ファイルを使います。 <ide> <del>```javascript <del>// tutorial13.json <add>```json <ide> [ <ide> {"author": "Pete Hunt", "text": "This is one comment"}, <ide> {"author": "Jordan Walke", "text": "This is *another* comment"} <ide><path>docs/docs/tutorial.ko-KR.md <ide> var Comment = React.createClass({ <ide> <ide> React는 이런 식으로 [XSS 공격](https://en.wikipedia.org/wiki/Cross-site_scripting)을 예방합니다. 우회할 방법이 있긴 하지만 프레임워크는 사용하지 않도록 경고하고 있습니다: <ide> <del>```javascript{4,14} <add>```javascript{3-6,14} <ide> // tutorial7.js <ide> var Comment = React.createClass({ <ide> rawMarkup: function() { <ide><path>docs/docs/tutorial.zh-CN.md <ide> var Comment = React.createClass({ <ide> <ide> 那是 React 在保护你免受 [XSS 攻击](https://en.wikipedia.org/wiki/Cross-site_scripting)。有一个方法解决这个问题,但是框架会警告你别使用这种方法: <ide> <del>```javascript{4,10} <add>```javascript{3-6,14} <ide> // tutorial7.js <ide> var Comment = React.createClass({ <ide> rawMarkup: function() {
4
Javascript
Javascript
fix linter error
645252e0c2aabaefcd381f2ed50ddc40170c44ca
<ide><path>src/text-editor.js <ide> class TextEditor { <ide> // coordinates. Useful with {Config::get}. <ide> // <ide> // For example, if called with a position inside the parameter list of an <del> // anonymous CoffeeScript function, this method returns a {ScopeDescriptor} with <add> // anonymous CoffeeScript function, this method returns a {ScopeDescriptor} with <ide> // the following scopes array: <ide> // `["source.coffee", "meta.function.inline.coffee", "meta.parameters.coffee", "variable.parameter.function.coffee"]` <ide> //
1
Text
Text
fix versions html table
34e002d6242181e5e8923bd77597b3fc4b3b6f50
<ide><path>guide/portuguese/html/index.md <ide> p: O elemento define um parágrafo <ide> <ide> Desde os primeiros dias da web, tem havido muitas versões do HTML <ide> <del>Versão | Ano | | --- | --- | | HTML | 1991 | | HTML 2.0 | 1995 | | HTML 3.2 | 1997 | | HTML 4.01 | 1999 | | XHTML | 2000 | | HTML5 | 2014 | <add>|Versão|Ano| <add>|--- |--- | <add>|HTML|1991| <add>|HTML 2.0|1995| <add>|HTML 3.2|1997| <add>|HTML 4.01|1999| <add>|XHTML|2000| <add>|HTML5|2014| <ide> <ide> #### Outros recursos <ide>
1
Text
Text
add `generator_class` parameter to docs
53b3b83b0460e99d22c96cc75625358cdedb96a7
<ide><path>docs/api-guide/schemas.md <ide> to be exposed in the schema: <ide> patterns=schema_url_patterns, <ide> ) <ide> <add>#### `generator_class` <add> <add>May be used to specify a `SchemaGenerator` subclass to be passed to the <add>`SchemaView`. <add> <add> <ide> <ide> ## Using an explicit schema view <ide>
1
Javascript
Javascript
use yargs.parse instead of exitprocess(false)
7a7c8372c3d085b0bc06f17c7e87fd28b2a18a83
<ide><path>bin/config-yargs.js <ide> var OPTIMIZE_GROUP = "Optimizing options:"; <ide> module.exports = function(yargs) { <ide> yargs <ide> .help("help") <del> .exitProcess(false) <ide> .alias("help", "h") <ide> .version() <ide> .alias("version", "v") <ide><path>bin/convert-argv.js <ide> var interpret = require("interpret"); <ide> var prepareOptions = require("../lib/prepareOptions"); <ide> <ide> module.exports = function(yargs, argv, convertOptions) { <del> if(argv["help"] === true || argv["version"] === true) { <del> return { <del> exitByHelpOrVersion: true <del> }; <del> } <del> <ide> var options = []; <ide> <ide> // Shortcuts <ide><path>bin/webpack.js <ide> yargs.options({ <ide> } <ide> }); <ide> <del>var validationErrorOcurred = false; <del>var options = {}; <del>try { <del> var argv = yargs.argv; <add>// yargs will terminate the process early when the user uses help or version. <add>// This causes large help outputs to be cut short (https://github.com/nodejs/node/wiki/API-changes-between-v0.10-and-v4#process). <add>// To prevent this we use the yargs.parse API and exit the process normally <add>yargs.parse(process.argv.slice(2), (err, argv, output) => { <ide> <del> if(argv.verbose) { <del> argv["display"] = "verbose"; <add> // arguments validation failed <add> if(err && output) { <add> console.error(output); <add> process.exitCode = 1; <add> return; <ide> } <ide> <del> options = require("./convert-argv")(yargs, argv); <del>} catch(e) { <del> var YError = require("yargs/lib/yerror"); <del> if(e instanceof YError) { <del> validationErrorOcurred = true; <del> } else { <del> throw e; <del> } <del>} <del> <del>function ifArg(name, fn, init) { <del> if(Array.isArray(argv[name])) { <del> if(init) init(); <del> argv[name].forEach(fn); <del> } else if(typeof argv[name] !== "undefined") { <del> if(init) init(); <del> fn(argv[name], -1); <del> } <del>} <del> <del>function processOptions(options) { <del> // process Promise <del> if(typeof options.then === "function") { <del> options.then(processOptions).catch(function(err) { <del> console.error(err.stack || err); <del> process.exit(1); // eslint-disable-line <del> }); <add> // help or version info <add> if(output) { <add> console.log(output); <ide> return; <ide> } <ide> <del> var firstOptions = [].concat(options)[0]; <del> var statsPresetToOptions = require("../lib/Stats.js").presetToOptions; <add> var options = {}; <ide> <del> var outputOptions = options.stats; <del> if(typeof outputOptions === "boolean" || typeof outputOptions === "string") { <del> outputOptions = statsPresetToOptions(outputOptions); <del> } else if(!outputOptions) { <del> outputOptions = {}; <add> if(argv.verbose) { <add> argv["display"] = "verbose"; <ide> } <ide> <del> ifArg("display", function(preset) { <del> outputOptions = statsPresetToOptions(preset); <del> }); <add> options = require("./convert-argv")(yargs, argv); <ide> <del> outputOptions = Object.create(outputOptions); <del> if(Array.isArray(options) && !outputOptions.children) { <del> outputOptions.children = options.map(o => o.stats); <add> function ifArg(name, fn, init) { <add> if(Array.isArray(argv[name])) { <add> if(init) init(); <add> argv[name].forEach(fn); <add> } else if(typeof argv[name] !== "undefined") { <add> if(init) init(); <add> fn(argv[name], -1); <add> } <ide> } <del> if(typeof outputOptions.context === "undefined") <del> outputOptions.context = firstOptions.context; <ide> <del> ifArg("json", function(bool) { <del> if(bool) <del> outputOptions.json = bool; <del> }); <add> function processOptions(options) { <add> // process Promise <add> if(typeof options.then === "function") { <add> options.then(processOptions).catch(function(err) { <add> console.error(err.stack || err); <add> process.exit(1); // eslint-disable-line <add> }); <add> return; <add> } <ide> <del> if(typeof outputOptions.colors === "undefined") <del> outputOptions.colors = require("supports-color"); <add> var firstOptions = [].concat(options)[0]; <add> var statsPresetToOptions = require("../lib/Stats.js").presetToOptions; <ide> <del> ifArg("sort-modules-by", function(value) { <del> outputOptions.modulesSort = value; <del> }); <add> var outputOptions = options.stats; <add> if(typeof outputOptions === "boolean" || typeof outputOptions === "string") { <add> outputOptions = statsPresetToOptions(outputOptions); <add> } else if(!outputOptions) { <add> outputOptions = {}; <add> } <ide> <del> ifArg("sort-chunks-by", function(value) { <del> outputOptions.chunksSort = value; <del> }); <add> ifArg("display", function(preset) { <add> outputOptions = statsPresetToOptions(preset); <add> }); <ide> <del> ifArg("sort-assets-by", function(value) { <del> outputOptions.assetsSort = value; <del> }); <add> outputOptions = Object.create(outputOptions); <add> if(Array.isArray(options) && !outputOptions.children) { <add> outputOptions.children = options.map(o => o.stats); <add> } <add> if(typeof outputOptions.context === "undefined") <add> outputOptions.context = firstOptions.context; <ide> <del> ifArg("display-exclude", function(value) { <del> outputOptions.exclude = value; <del> }); <add> ifArg("json", function(bool) { <add> if(bool) <add> outputOptions.json = bool; <add> }); <ide> <del> if(!outputOptions.json) { <del> if(typeof outputOptions.cached === "undefined") <del> outputOptions.cached = false; <del> if(typeof outputOptions.cachedAssets === "undefined") <del> outputOptions.cachedAssets = false; <add> if(typeof outputOptions.colors === "undefined") <add> outputOptions.colors = require("supports-color"); <ide> <del> ifArg("display-chunks", function(bool) { <del> if(bool) { <del> outputOptions.modules = false; <del> outputOptions.chunks = true; <del> outputOptions.chunkModules = true; <del> } <add> ifArg("sort-modules-by", function(value) { <add> outputOptions.modulesSort = value; <ide> }); <ide> <del> ifArg("display-entrypoints", function(bool) { <del> if(bool) <del> outputOptions.entrypoints = true; <add> ifArg("sort-chunks-by", function(value) { <add> outputOptions.chunksSort = value; <ide> }); <ide> <del> ifArg("display-reasons", function(bool) { <del> if(bool) <del> outputOptions.reasons = true; <add> ifArg("sort-assets-by", function(value) { <add> outputOptions.assetsSort = value; <ide> }); <ide> <del> ifArg("display-depth", function(bool) { <del> if(bool) <del> outputOptions.depth = true; <add> ifArg("display-exclude", function(value) { <add> outputOptions.exclude = value; <ide> }); <ide> <del> ifArg("display-used-exports", function(bool) { <del> if(bool) <del> outputOptions.usedExports = true; <del> }); <add> if(!outputOptions.json) { <add> if(typeof outputOptions.cached === "undefined") <add> outputOptions.cached = false; <add> if(typeof outputOptions.cachedAssets === "undefined") <add> outputOptions.cachedAssets = false; <add> <add> ifArg("display-chunks", function(bool) { <add> if(bool) { <add> outputOptions.modules = false; <add> outputOptions.chunks = true; <add> outputOptions.chunkModules = true; <add> } <add> }); <ide> <del> ifArg("display-provided-exports", function(bool) { <del> if(bool) <del> outputOptions.providedExports = true; <del> }); <add> ifArg("display-entrypoints", function(bool) { <add> if(bool) <add> outputOptions.entrypoints = true; <add> }); <ide> <del> ifArg("display-optimization-bailout", function(bool) { <del> if(bool) <del> outputOptions.optimizationBailout = bool; <del> }); <add> ifArg("display-reasons", function(bool) { <add> if(bool) <add> outputOptions.reasons = true; <add> }); <ide> <del> ifArg("display-error-details", function(bool) { <del> if(bool) <del> outputOptions.errorDetails = true; <del> }); <add> ifArg("display-depth", function(bool) { <add> if(bool) <add> outputOptions.depth = true; <add> }); <ide> <del> ifArg("display-origins", function(bool) { <del> if(bool) <del> outputOptions.chunkOrigins = true; <del> }); <add> ifArg("display-used-exports", function(bool) { <add> if(bool) <add> outputOptions.usedExports = true; <add> }); <ide> <del> ifArg("display-max-modules", function(value) { <del> outputOptions.maxModules = +value; <del> }); <add> ifArg("display-provided-exports", function(bool) { <add> if(bool) <add> outputOptions.providedExports = true; <add> }); <ide> <del> ifArg("display-cached", function(bool) { <del> if(bool) <del> outputOptions.cached = true; <del> }); <add> ifArg("display-optimization-bailout", function(bool) { <add> if(bool) <add> outputOptions.optimizationBailout = bool; <add> }); <ide> <del> ifArg("display-cached-assets", function(bool) { <del> if(bool) <del> outputOptions.cachedAssets = true; <del> }); <add> ifArg("display-error-details", function(bool) { <add> if(bool) <add> outputOptions.errorDetails = true; <add> }); <ide> <del> if(!outputOptions.exclude) <del> outputOptions.exclude = ["node_modules", "bower_components", "components"]; <add> ifArg("display-origins", function(bool) { <add> if(bool) <add> outputOptions.chunkOrigins = true; <add> }); <ide> <del> if(argv["display-modules"]) { <del> outputOptions.maxModules = Infinity; <del> outputOptions.exclude = undefined; <del> outputOptions.modules = true; <del> } <del> } <add> ifArg("display-max-modules", function(value) { <add> outputOptions.maxModules = +value; <add> }); <ide> <del> ifArg("hide-modules", function(bool) { <del> if(bool) { <del> outputOptions.modules = false; <del> outputOptions.chunkModules = false; <del> } <del> }); <del> <del> var webpack = require("../lib/webpack.js"); <del> <del> Error.stackTraceLimit = 30; <del> var lastHash = null; <del> var compiler; <del> try { <del> compiler = webpack(options); <del> } catch(e) { <del> var WebpackOptionsValidationError = require("../lib/WebpackOptionsValidationError"); <del> if(e instanceof WebpackOptionsValidationError) { <del> if(argv.color) <del> console.error("\u001b[1m\u001b[31m" + e.message + "\u001b[39m\u001b[22m"); <del> else <del> console.error(e.message); <del> process.exit(1); // eslint-disable-line no-process-exit <del> } <del> throw e; <del> } <add> ifArg("display-cached", function(bool) { <add> if(bool) <add> outputOptions.cached = true; <add> }); <ide> <del> if(argv.progress) { <del> var ProgressPlugin = require("../lib/ProgressPlugin"); <del> compiler.apply(new ProgressPlugin({ <del> profile: argv.profile <del> })); <del> } <add> ifArg("display-cached-assets", function(bool) { <add> if(bool) <add> outputOptions.cachedAssets = true; <add> }); <ide> <del> function compilerCallback(err, stats) { <del> if(!options.watch || err) { <del> // Do not keep cache anymore <del> compiler.purgeInputFileSystem(); <del> } <del> if(err) { <del> lastHash = null; <del> console.error(err.stack || err); <del> if(err.details) console.error(err.details); <del> process.exit(1); // eslint-disable-line <add> if(!outputOptions.exclude) <add> outputOptions.exclude = ["node_modules", "bower_components", "components"]; <add> <add> if(argv["display-modules"]) { <add> outputOptions.maxModules = Infinity; <add> outputOptions.exclude = undefined; <add> outputOptions.modules = true; <add> } <ide> } <del> if(outputOptions.json) { <del> process.stdout.write(JSON.stringify(stats.toJson(outputOptions), null, 2) + "\n"); <del> } else if(stats.hash !== lastHash) { <del> lastHash = stats.hash; <del> var statsString = stats.toString(outputOptions); <del> if(statsString) <del> process.stdout.write(statsString + "\n"); <add> <add> ifArg("hide-modules", function(bool) { <add> if(bool) { <add> outputOptions.modules = false; <add> outputOptions.chunkModules = false; <add> } <add> }); <add> <add> var webpack = require("../lib/webpack.js"); <add> <add> Error.stackTraceLimit = 30; <add> var lastHash = null; <add> var compiler; <add> try { <add> compiler = webpack(options); <add> } catch(e) { <add> var WebpackOptionsValidationError = require("../lib/WebpackOptionsValidationError"); <add> if(e instanceof WebpackOptionsValidationError) { <add> if(argv.color) <add> console.error("\u001b[1m\u001b[31m" + e.message + "\u001b[39m\u001b[22m"); <add> else <add> console.error(e.message); <add> process.exit(1); // eslint-disable-line no-process-exit <add> } <add> throw e; <ide> } <del> if(!options.watch && stats.hasErrors()) { <del> process.on("exit", function() { <del> process.exit(2); // eslint-disable-line <del> }); <add> <add> if(argv.progress) { <add> var ProgressPlugin = require("../lib/ProgressPlugin"); <add> compiler.apply(new ProgressPlugin({ <add> profile: argv.profile <add> })); <ide> } <del> } <del> if(firstOptions.watch || options.watch) { <del> var watchOptions = firstOptions.watchOptions || firstOptions.watch || options.watch || {}; <del> if(watchOptions.stdin) { <del> process.stdin.on("end", function() { <del> process.exit(0); // eslint-disable-line <del> }); <del> process.stdin.resume(); <add> <add> function compilerCallback(err, stats) { <add> if(!options.watch || err) { <add> // Do not keep cache anymore <add> compiler.purgeInputFileSystem(); <add> } <add> if(err) { <add> lastHash = null; <add> console.error(err.stack || err); <add> if(err.details) console.error(err.details); <add> process.exit(1); // eslint-disable-line <add> } <add> if(outputOptions.json) { <add> process.stdout.write(JSON.stringify(stats.toJson(outputOptions), null, 2) + "\n"); <add> } else if(stats.hash !== lastHash) { <add> lastHash = stats.hash; <add> var statsString = stats.toString(outputOptions); <add> if(statsString) <add> process.stdout.write(statsString + "\n"); <add> } <add> if(!options.watch && stats.hasErrors()) { <add> process.on("exit", function() { <add> process.exit(2); // eslint-disable-line <add> }); <add> } <ide> } <del> compiler.watch(watchOptions, compilerCallback); <del> console.log("\nWebpack is watching the files…\n"); <del> } else <del> compiler.run(compilerCallback); <add> if(firstOptions.watch || options.watch) { <add> var watchOptions = firstOptions.watchOptions || firstOptions.watch || options.watch || {}; <add> if(watchOptions.stdin) { <add> process.stdin.on("end", function() { <add> process.exit(0); // eslint-disable-line <add> }); <add> process.stdin.resume(); <add> } <add> compiler.watch(watchOptions, compilerCallback); <add> console.log("\nWebpack is watching the files…\n"); <add> } else <add> compiler.run(compilerCallback); <ide> <del>} <add> } <ide> <del>// yargs will terminate the process early when the user uses help or version. <del>// This causes large help outputs to be cut short (https://github.com/nodejs/node/wiki/API-changes-between-v0.10-and-v4#process). <del>// To prevent this we configure yargs with .exitProcess(false). <del>// However, we need to prevent processOptions and convert-argv from causing errorneous results, <del>// so we only parse inputs if help or version was not called. <del>if(!options.exitByHelpOrVersion && !validationErrorOcurred) { <ide> processOptions(options); <del>} <add> <add>});
3
Go
Go
convert testgetimagesjson into several unit tests
627805f5f8895c3a3887c312f7b8f49a89e51732
<ide><path>api/server/server_unit_test.go <ide> import ( <ide> "io" <ide> "net/http" <ide> "net/http/httptest" <add> "reflect" <ide> "strings" <ide> "testing" <ide> <ide> "github.com/dotcloud/docker/api" <ide> "github.com/dotcloud/docker/engine" <add> "github.com/dotcloud/docker/pkg/version" <ide> ) <ide> <ide> func TestGetBoolParam(t *testing.T) { <ide> func TestGetInfo(t *testing.T) { <ide> if v.GetInt("Containers") != 1 { <ide> t.Fatalf("%#v\n", v) <ide> } <del> if r.HeaderMap.Get("Content-Type") != "application/json" { <del> t.Fatalf("%#v\n", r) <add> assertContentType(r, "application/json", t) <add>} <add> <add>func TestGetImagesJSON(t *testing.T) { <add> eng := engine.New() <add> var called bool <add> eng.Register("images", func(job *engine.Job) engine.Status { <add> called = true <add> v := createEnvFromGetImagesJSONStruct(sampleImage) <add> if _, err := v.WriteTo(job.Stdout); err != nil { <add> return job.Error(err) <add> } <add> return engine.StatusOK <add> }) <add> r := serveRequest("GET", "/images/json", nil, eng, t) <add> if !called { <add> t.Fatal("handler was not called") <add> } <add> assertHttpNotError(r, t) <add> assertContentType(r, "application/json", t) <add> var observed getImagesJSONStruct <add> if err := json.Unmarshal(r.Body.Bytes(), &observed); err != nil { <add> t.Fatal(err) <add> } <add> if !reflect.DeepEqual(observed, sampleImage) { <add> t.Errorf("Expected %#v but got %#v", sampleImage, observed) <add> } <add>} <add> <add>func TestGetImagesJSONFilter(t *testing.T) { <add> eng := engine.New() <add> filter := "nothing" <add> eng.Register("images", func(job *engine.Job) engine.Status { <add> filter = job.Getenv("filter") <add> return engine.StatusOK <add> }) <add> serveRequest("GET", "/images/json?filter=aaaa", nil, eng, t) <add> if filter != "aaaa" { <add> t.Errorf("%#v", filter) <add> } <add>} <add> <add>func TestGetImagesJSONFilters(t *testing.T) { <add> eng := engine.New() <add> filter := "nothing" <add> eng.Register("images", func(job *engine.Job) engine.Status { <add> filter = job.Getenv("filters") <add> return engine.StatusOK <add> }) <add> serveRequest("GET", "/images/json?filters=nnnn", nil, eng, t) <add> if filter != "nnnn" { <add> t.Errorf("%#v", filter) <add> } <add>} <add> <add>func TestGetImagesJSONAll(t *testing.T) { <add> eng := engine.New() <add> allFilter := "-1" <add> eng.Register("images", func(job *engine.Job) engine.Status { <add> allFilter = job.Getenv("all") <add> return engine.StatusOK <add> }) <add> serveRequest("GET", "/images/json?all=1", nil, eng, t) <add> if allFilter != "1" { <add> t.Errorf("%#v", allFilter) <add> } <add>} <add> <add>func TestGetImagesJSONLegacyFormat(t *testing.T) { <add> eng := engine.New() <add> var called bool <add> eng.Register("images", func(job *engine.Job) engine.Status { <add> called = true <add> outsLegacy := engine.NewTable("Created", 0) <add> outsLegacy.Add(createEnvFromGetImagesJSONStruct(sampleImage)) <add> if _, err := outsLegacy.WriteListTo(job.Stdout); err != nil { <add> return job.Error(err) <add> } <add> return engine.StatusOK <add> }) <add> r := serveRequestUsingVersion("GET", "/images/json", "1.6", nil, eng, t) <add> if !called { <add> t.Fatal("handler was not called") <add> } <add> assertHttpNotError(r, t) <add> assertContentType(r, "application/json", t) <add> images := engine.NewTable("Created", 0) <add> if _, err := images.ReadListFrom(r.Body.Bytes()); err != nil { <add> t.Fatal(err) <add> } <add> if images.Len() != 1 { <add> t.Fatalf("Expected 1 image, %d found", images.Len()) <add> } <add> image := images.Data[0] <add> if image.Get("Tag") != "test-tag" { <add> t.Errorf("Expected tag 'test-tag', found '%s'", image.Get("Tag")) <add> } <add> if image.Get("Repository") != "test-name" { <add> t.Errorf("Expected repository 'test-name', found '%s'", image.Get("Repository")) <ide> } <ide> } <ide> <ide> func TestGetContainersByName(t *testing.T) { <ide> eng.Register("container_inspect", func(job *engine.Job) engine.Status { <ide> called = true <ide> if job.Args[0] != name { <del> t.Fatalf("name != '%s': %#v", name, job.Args[0]) <add> t.Errorf("name != '%s': %#v", name, job.Args[0]) <ide> } <ide> if api.APIVERSION.LessThan("1.12") && !job.GetenvBool("dirty") { <del> t.Fatal("dirty env variable not set") <add> t.Errorf("dirty env variable not set") <ide> } else if api.APIVERSION.GreaterThanOrEqualTo("1.12") && job.GetenvBool("dirty") { <del> t.Fatal("dirty env variable set when it shouldn't") <add> t.Errorf("dirty env variable set when it shouldn't") <ide> } <ide> v := &engine.Env{} <ide> v.SetBool("dirty", true) <ide> func TestGetContainersByName(t *testing.T) { <ide> if !called { <ide> t.Fatal("handler was not called") <ide> } <del> if r.HeaderMap.Get("Content-Type") != "application/json" { <del> t.Fatalf("%#v\n", r) <del> } <add> assertContentType(r, "application/json", t) <ide> var stdoutJson interface{} <ide> if err := json.Unmarshal(r.Body.Bytes(), &stdoutJson); err != nil { <ide> t.Fatalf("%#v", err) <ide> func TestGetEvents(t *testing.T) { <ide> if !called { <ide> t.Fatal("handler was not called") <ide> } <del> if r.HeaderMap.Get("Content-Type") != "application/json" { <del> t.Fatalf("%#v\n", r) <del> } <add> assertContentType(r, "application/json", t) <ide> var stdout_json struct { <ide> Since int <ide> Until int <ide> } <ide> if err := json.Unmarshal(r.Body.Bytes(), &stdout_json); err != nil { <del> t.Fatalf("%#v", err) <add> t.Fatal(err) <ide> } <ide> if stdout_json.Since != 1 { <del> t.Fatalf("since != 1: %#v", stdout_json.Since) <add> t.Errorf("since != 1: %#v", stdout_json.Since) <ide> } <ide> if stdout_json.Until != 0 { <del> t.Fatalf("until != 0: %#v", stdout_json.Until) <add> t.Errorf("until != 0: %#v", stdout_json.Until) <ide> } <ide> } <ide> <ide> func TestGetImagesByName(t *testing.T) { <ide> } <ide> <ide> func serveRequest(method, target string, body io.Reader, eng *engine.Engine, t *testing.T) *httptest.ResponseRecorder { <add> return serveRequestUsingVersion(method, target, api.APIVERSION, body, eng, t) <add>} <add> <add>func serveRequestUsingVersion(method, target string, version version.Version, body io.Reader, eng *engine.Engine, t *testing.T) *httptest.ResponseRecorder { <ide> r := httptest.NewRecorder() <ide> req, err := http.NewRequest(method, target, body) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> if err := ServeRequest(eng, api.APIVERSION, r, req); err != nil { <add> if err := ServeRequest(eng, version, r, req); err != nil { <ide> t.Fatal(err) <ide> } <ide> return r <ide> func toJson(data interface{}, t *testing.T) io.Reader { <ide> } <ide> return &buf <ide> } <add> <add>func assertContentType(recorder *httptest.ResponseRecorder, content_type string, t *testing.T) { <add> if recorder.HeaderMap.Get("Content-Type") != content_type { <add> t.Fatalf("%#v\n", recorder) <add> } <add>} <add> <add>// XXX: Duplicated from integration/utils_test.go, but maybe that's OK as that <add>// should die as soon as we converted all integration tests? <add>// assertHttpNotError expect the given response to not have an error. <add>// Otherwise the it causes the test to fail. <add>func assertHttpNotError(r *httptest.ResponseRecorder, t *testing.T) { <add> // Non-error http status are [200, 400) <add> if r.Code < http.StatusOK || r.Code >= http.StatusBadRequest { <add> t.Fatal(fmt.Errorf("Unexpected http error: %v", r.Code)) <add> } <add>} <add> <add>func createEnvFromGetImagesJSONStruct(data getImagesJSONStruct) *engine.Env { <add> v := &engine.Env{} <add> v.SetList("RepoTags", data.RepoTags) <add> v.Set("Id", data.Id) <add> v.SetInt64("Created", data.Created) <add> v.SetInt64("Size", data.Size) <add> v.SetInt64("VirtualSize", data.VirtualSize) <add> return v <add>} <add> <add>type getImagesJSONStruct struct { <add> RepoTags []string <add> Id string <add> Created int64 <add> Size int64 <add> VirtualSize int64 <add>} <add> <add>var sampleImage getImagesJSONStruct = getImagesJSONStruct{ <add> RepoTags: []string{"test-name:test-tag"}, <add> Id: "ID", <add> Created: 999, <add> Size: 777, <add> VirtualSize: 666, <add>} <ide><path>integration/api_test.go <ide> import ( <ide> "net" <ide> "net/http" <ide> "net/http/httptest" <del> "strings" <ide> "testing" <ide> "time" <ide> <ide> import ( <ide> "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar" <ide> ) <ide> <del>func TestGetImagesJSON(t *testing.T) { <del> eng := NewTestEngine(t) <del> defer mkDaemonFromEngine(eng, t).Nuke() <del> <del> job := eng.Job("images") <del> initialImages, err := job.Stdout.AddListTable() <del> if err != nil { <del> t.Fatal(err) <del> } <del> if err := job.Run(); err != nil { <del> t.Fatal(err) <del> } <del> <del> req, err := http.NewRequest("GET", "/images/json?all=0", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> r := httptest.NewRecorder() <del> <del> if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil { <del> t.Fatal(err) <del> } <del> assertHttpNotError(r, t) <del> <del> images := engine.NewTable("Created", 0) <del> if _, err := images.ReadListFrom(r.Body.Bytes()); err != nil { <del> t.Fatal(err) <del> } <del> <del> if images.Len() != initialImages.Len() { <del> t.Errorf("Expected %d image, %d found", initialImages.Len(), images.Len()) <del> } <del> <del> found := false <del> for _, img := range images.Data { <del> if strings.Contains(img.GetList("RepoTags")[0], unitTestImageName) { <del> found = true <del> break <del> } <del> } <del> if !found { <del> t.Errorf("Expected image %s, %+v found", unitTestImageName, images) <del> } <del> <del> r2 := httptest.NewRecorder() <del> <del> // all=1 <del> <del> initialImages = getAllImages(eng, t) <del> <del> req2, err := http.NewRequest("GET", "/images/json?all=true", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if err := server.ServeRequest(eng, api.APIVERSION, r2, req2); err != nil { <del> t.Fatal(err) <del> } <del> assertHttpNotError(r2, t) <del> <del> images2 := engine.NewTable("Id", 0) <del> if _, err := images2.ReadListFrom(r2.Body.Bytes()); err != nil { <del> t.Fatal(err) <del> } <del> <del> if images2.Len() != initialImages.Len() { <del> t.Errorf("Expected %d image, %d found", initialImages.Len(), images2.Len()) <del> } <del> <del> found = false <del> for _, img := range images2.Data { <del> if img.Get("Id") == unitTestImageID { <del> found = true <del> break <del> } <del> } <del> if !found { <del> t.Errorf("Retrieved image Id differs, expected %s, received %+v", unitTestImageID, images2) <del> } <del> <del> r3 := httptest.NewRecorder() <del> <del> // filter=a <del> req3, err := http.NewRequest("GET", "/images/json?filter=aaaaaaaaaa", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> if err := server.ServeRequest(eng, api.APIVERSION, r3, req3); err != nil { <del> t.Fatal(err) <del> } <del> assertHttpNotError(r3, t) <del> <del> images3 := engine.NewTable("Id", 0) <del> if _, err := images3.ReadListFrom(r3.Body.Bytes()); err != nil { <del> t.Fatal(err) <del> } <del> <del> if images3.Len() != 0 { <del> t.Errorf("Expected 0 image, %d found", images3.Len()) <del> } <del>} <del> <ide> func TestGetContainersJSON(t *testing.T) { <ide> eng := NewTestEngine(t) <ide> defer mkDaemonFromEngine(eng, t).Nuke()
2
Text
Text
add yaml metadata for process.memoryusage.rss
d2dc3a9bf05bec081f64ff5d8a69c5a964540470
<ide><path>doc/api/process.md <ide> informations about memory usage which can be slow depending on the <ide> program memory allocations. <ide> <ide> ## `process.memoryUsage.rss()` <add><!-- YAML <add>added: REPLACEME <add>--> <ide> <ide> * Returns: {integer} <ide>
1
Text
Text
improve prepositions in buffer.md
617946779c677e0669395cac8fbc2c0dace9da43
<ide><path>doc/api/buffer.md <ide> added: v0.1.90 <ide> <ide> * `target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`] to copy into. <ide> * `targetStart` {integer} The offset within `target` at which to begin <del> copying to. **Default:** `0`. <del>* `sourceStart` {integer} The offset within `buf` at which to begin copying from. <add> writing. **Default:** `0`. <add>* `sourceStart` {integer} The offset within `buf` from which to begin copying. <ide> **Default:** `0`. <ide> * `sourceEnd` {integer} The offset within `buf` at which to stop copying (not <ide> inclusive). **Default:** [`buf.length`].
1
Go
Go
add support to set memoryswap
1a9b640e0d3e6916bff9cd7dd8ab435a70c6a0e8
<ide><path>daemon/create.go <ide> func (daemon *Daemon) ContainerCreate(job *engine.Job) engine.Status { <ide> job.Errorf("Your kernel does not support swap limit capabilities. Limitation discarded.\n") <ide> config.MemorySwap = -1 <ide> } <add> if config.Memory > 0 && config.MemorySwap > 0 && config.MemorySwap < config.Memory { <add> return job.Errorf("Minimum memoryswap limit should larger than memory limit, see usage.\n") <add> } <ide> <ide> var hostConfig *runconfig.HostConfig <ide> if job.EnvExists("HostConfig") { <ide><path>runconfig/parse.go <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> flEntrypoint = cmd.String([]string{"#entrypoint", "-entrypoint"}, "", "Overwrite the default ENTRYPOINT of the image") <ide> flHostname = cmd.String([]string{"h", "-hostname"}, "", "Container host name") <ide> flMemoryString = cmd.String([]string{"m", "-memory"}, "", "Memory limit (format: <number><optional unit>, where unit = b, k, m or g)") <add> flMemorySwap = cmd.String([]string{"-memory-swap"}, "", "Total memory usage (memory + swap), set '-1' to disable swap (format: <number><optional unit>, where unit = b, k, m or g)") <ide> flUser = cmd.String([]string{"u", "-user"}, "", "Username or UID") <ide> flWorkingDir = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container") <ide> flCpuShares = cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)") <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> flMemory = parsedMemory <ide> } <ide> <add> var MemorySwap int64 <add> if *flMemorySwap != "" { <add> parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap) <add> if err != nil { <add> return nil, nil, cmd, err <add> } <add> MemorySwap = parsedMemorySwap <add> } <add> <ide> var binds []string <ide> // add any bind targets to the list of container volumes <ide> for bind := range flVolumes.GetMap() { <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> NetworkDisabled: !*flNetwork, <ide> OpenStdin: *flStdin, <ide> Memory: flMemory, <add> MemorySwap: MemorySwap, <ide> CpuShares: *flCpuShares, <ide> Cpuset: *flCpuset, <ide> AttachStdin: attachStdin,
2
Java
Java
expose primary flag on beandefinitionbuilder
248ad0fa796e2d3e611a166f68357a3d5d608ecf
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java <ide> public BeanDefinitionBuilder addDependsOn(String beanName) { <ide> return this; <ide> } <ide> <add> /** <add> * Set whether this bean is a primary autowire candidate. <add> * @since 5.1.11 <add> */ <add> public BeanDefinitionBuilder setPrimary(boolean primary) { <add> this.beanDefinition.setPrimary(primary); <add> return this; <add> } <add> <ide> /** <ide> * Set the role of this definition. <ide> */
1
Text
Text
add parent option to active job guides [ci-skip]
6f26282780e14f2eefd699df984b87f5a77fdf10
<ide><path>guides/source/active_job_basics.md <ide> end <ide> <ide> Note that you can define `perform` with as many arguments as you want. <ide> <add>If you already have an abstract class and its name differs from `ApplicationJob`, you can pass <add>the `--parent` option to indicate you want a different abstract class: <add> <add>```bash <add>$ bin/rails generate job process_payment --parent=payment_job <add>``` <add> <add>```ruby <add>class ProcessPaymentJob < PaymentJob <add> queue_as :default <add> <add> def perform(*args) <add> # Do something later <add> end <add>end <add>``` <add> <ide> ### Enqueue the Job <ide> <ide> Enqueue a job using [`perform_later`][] and, optionally, [`set`][]. Like so:
1
PHP
PHP
remove duplicate code
010f727c7cab64890273f9acbf5423c1cf9af3bd
<ide><path>src/ORM/Rule/IsUnique.php <ide> public function __invoke(EntityInterface $entity, array $options) <ide> if (isset($options['allowMultipleNulls'])) { <ide> $allowMultipleNulls = $options['allowMultipleNulls'] === true ? true : false; <ide> } <del> <add> <ide> $alias = $options['repository']->alias(); <ide> $conditions = $this->_alias($alias, $entity->extract($this->_fields)); <ide> if ($entity->isNew() === false) { <ide> public function __invoke(EntityInterface $entity, array $options) <ide> } <ide> } <ide> <del> if (!$allowMultipleNulls) { <del> foreach ($conditions as $key => $value) { <del> if ($value === null) { <del> $conditions[$key . ' IS'] = $value; <del> unset($conditions[$key]); <del> } <del> } <del> } <del> <ide> return !$options['repository']->exists($conditions); <ide> } <ide>
1
Go
Go
use strconv.parsebool in getboolparam
da199846d2813467ab8bae629336f3989f285ce9
<ide><path>api.go <ide> func writeJSON(w http.ResponseWriter, b []byte) { <ide> w.Write(b) <ide> } <ide> <del>// FIXME: Use stvconv.ParseBool() instead? <ide> func getBoolParam(value string) (bool, error) { <del> if value == "1" || strings.ToLower(value) == "true" { <del> return true, nil <del> } <del> if value == "" || value == "0" || strings.ToLower(value) == "false" { <add> if value == "" { <ide> return false, nil <ide> } <add> if ret, err := strconv.ParseBool(value); err == nil { <add> return ret, err <add> } <ide> return false, fmt.Errorf("Bad parameter") <ide> } <ide> <ide><path>api_test.go <ide> import ( <ide> "time" <ide> ) <ide> <add>func TestGetBoolParam(t *testing.T) { <add> if ret, err := getBoolParam("true"); err != nil || !ret { <add> t.Fatalf("true -> true, nil | got %b %s", ret, err) <add> } <add> if ret, err := getBoolParam("True"); err != nil || !ret { <add> t.Fatalf("True -> true, nil | got %b %s", ret, err) <add> } <add> if ret, err := getBoolParam("1"); err != nil || !ret { <add> t.Fatalf("1 -> true, nil | got %b %s", ret, err) <add> } <add> if ret, err := getBoolParam(""); err != nil || ret { <add> t.Fatalf("\"\" -> false, nil | got %b %s", ret, err) <add> } <add> if ret, err := getBoolParam("false"); err != nil || ret { <add> t.Fatalf("false -> false, nil | got %b %s", ret, err) <add> } <add> if ret, err := getBoolParam("0"); err != nil || ret { <add> t.Fatalf("0 -> false, nil | got %b %s", ret, err) <add> } <add> if ret, err := getBoolParam("faux"); err == nil || ret { <add> t.Fatalf("faux -> false, err | got %b %s", ret, err) <add> } <add>} <add> <ide> func TestPostAuth(t *testing.T) { <ide> runtime, err := newTestRuntime() <ide> if err != nil {
2
PHP
PHP
fix the parameter namespace
c30bb5d302d9b50dcc241c285913ee8aefd63ea0
<ide><path>src/ORM/Rule/ExistsIn.php <ide> public function __invoke(EntityInterface $entity, array $options) <ide> /** <ide> * Check whether or not the entity fields are nullable and null. <ide> * <del> * @param \Cake\ORM\EntityInterface $entity The entity to check. <add> * @param \Cake\Datasource\EntityInterface $entity The entity to check. <ide> * @param \Cake\ORM\Table $source The table to use schema from. <ide> * @return bool <ide> */
1
Javascript
Javascript
make controlled components and bubbling work in ie
556065937b91a08635799934bee12259cdb439bd
<ide><path>src/eventPlugins/ChangeEventPlugin.js <ide> var EventConstants = require('EventConstants'); <ide> var EventPluginHub = require('EventPluginHub'); <ide> var EventPropagators = require('EventPropagators'); <ide> var ExecutionEnvironment = require('ExecutionEnvironment'); <add>var ReactUpdates = require('ReactUpdates'); <ide> var SyntheticEvent = require('SyntheticEvent'); <ide> <ide> var isEventSupported = require('isEventSupported'); <ide> function manualDispatchChangeEvent(nativeEvent) { <ide> ); <ide> EventPropagators.accumulateTwoPhaseDispatches(event); <ide> <del> // If change bubbled, we'd just bind to it like all the other events <del> // and have it go through ReactEventTopLevelCallback. Since it doesn't, we <del> // manually listen for the change event and so we have to enqueue and <add> // If change and propertychange bubbled, we'd just bind to it like all the <add> // other events and have it go through ReactEventTopLevelCallback. Since it <add> // doesn't, we manually listen for the events and so we have to enqueue and <ide> // process the abstract event manually. <add> // <add> // Batching is necessary here in order to ensure that all event handlers run <add> // before the next rerender (including event handlers attached to ancestor <add> // elements instead of directly on the input). Without this, controlled <add> // components don't work properly in conjunction with event bubbling because <add> // the component is rerendered and the value reverted before all the event <add> // handlers can run. See https://github.com/facebook/react/issues/708. <add> ReactUpdates.batchedUpdates(runEventInBatch, event); <add>} <add> <add>function runEventInBatch(event) { <ide> EventPluginHub.enqueueEvents(event); <ide> EventPluginHub.processEventQueue(); <ide> }
1
Javascript
Javascript
learn layout on mobile
672184d0c30c2b941a8cce69128373f9878839a9
<ide><path>client/src/templates/Challenges/classic/Show.js <ide> class ShowClassic extends Component { <ide> title={`Learn ${this.getBlockNameTitle()} | freeCodeCamp.org`} <ide> /> <ide> <Media maxWidth={MAX_MOBILE_WIDTH}> <del> {matches => <del> matches ? ( <del> <MobileLayout <del> editor={this.renderEditor()} <del> guideUrl={this.getGuideUrl()} <del> hasPreview={this.hasPreview()} <del> instructions={this.renderInstructionsPanel({ <del> showToolPanel: false <del> })} <del> preview={this.renderPreview()} <del> testOutput={this.renderTestOutput()} <del> videoUrl={this.getVideoUrl()} <del> /> <del> ) : ( <del> <DesktopLayout <del> challengeFile={this.getChallengeFile()} <del> editor={this.renderEditor()} <del> hasPreview={this.hasPreview()} <del> instructions={this.renderInstructionsPanel({ <del> showToolPanel: true <del> })} <del> preview={this.renderPreview()} <del> resizeProps={this.resizeProps} <del> testOutput={this.renderTestOutput()} <del> /> <del> ) <del> } <add> <MobileLayout <add> editor={this.renderEditor()} <add> guideUrl={this.getGuideUrl()} <add> hasPreview={this.hasPreview()} <add> instructions={this.renderInstructionsPanel({ <add> showToolPanel: false <add> })} <add> preview={this.renderPreview()} <add> testOutput={this.renderTestOutput()} <add> videoUrl={this.getVideoUrl()} <add> /> <add> </Media> <add> <Media minWidth={MAX_MOBILE_WIDTH + 1}> <add> <DesktopLayout <add> challengeFile={this.getChallengeFile()} <add> editor={this.renderEditor()} <add> hasPreview={this.hasPreview()} <add> instructions={this.renderInstructionsPanel({ <add> showToolPanel: true <add> })} <add> preview={this.renderPreview()} <add> resizeProps={this.resizeProps} <add> testOutput={this.renderTestOutput()} <add> /> <ide> </Media> <ide> <CompletionModal /> <ide> <HelpModal />
1
Ruby
Ruby
fix doc code formatting [ci skip]
5e2774f609315aaaa6208b571721bb6f5d9aa466
<ide><path>activesupport/lib/active_support/deprecation/behaviors.rb <ide> class Deprecation <ide> # constant. Available behaviors are: <ide> # <ide> # [+raise+] Raise <tt>ActiveSupport::DeprecationException</tt>. <del> # [+stderr+] Log all deprecation warnings to +$stderr+. <add> # [+stderr+] Log all deprecation warnings to <tt>$stderr</tt>. <ide> # [+log+] Log all deprecation warnings to +Rails.logger+. <ide> # [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+. <ide> # [+silence+] Do nothing. <ide> def disallowed_behavior <ide> # Available behaviors: <ide> # <ide> # [+raise+] Raise <tt>ActiveSupport::DeprecationException</tt>. <del> # [+stderr+] Log all deprecation warnings to +$stderr+. <add> # [+stderr+] Log all deprecation warnings to <tt>$stderr</tt>. <ide> # [+log+] Log all deprecation warnings to +Rails.logger+. <ide> # [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+. <ide> # [+silence+] Do nothing. <ide><path>activesupport/lib/active_support/deprecation/reporting.rb <ide> def silence(&block) <ide> end <ide> <ide> # Allow previously disallowed deprecation warnings within the block. <del> # <tt>allowed_warnings<tt> can be an array containing strings, symbols, or regular <add> # <tt>allowed_warnings</tt> can be an array containing strings, symbols, or regular <ide> # expressions. (Symbols are treated as strings). These are compared against <ide> # the text of deprecation warning messages generated within the block. <ide> # Matching warnings will be exempt from the rules set by
2
Javascript
Javascript
solve the spaces vs tabs indentation issues
1b4c469ea3f66030f05fa81092fa3ad2e26f7fdb
<ide><path>examples/js/renderers/SoftwareRenderer.js <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> var blockShift = 3; // Normally, it should be 3. At line mode, it has to be 0 <ide> var blockSize = 1 << blockShift; <ide> var maxZVal = (1 << 24); // Note: You want to size this so you don't get overflows. <del> var lineMode = false; <del> var lookVector = new THREE.Vector3( 0, 0, 1 ); <del> var crossVector = new THREE.Vector3(); <del> <add> var lineMode = false; <add> var lookVector = new THREE.Vector3( 0, 0, 1 ); <add> var crossVector = new THREE.Vector3(); <add> <ide> var rectx1 = Infinity, recty1 = Infinity; <ide> var rectx2 = 0, recty2 = 0; <ide> <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> <ide> this.setSize = function ( width, height ) { <ide> <del> setSize( width, height ); <add> setSize( width, height ); <ide> }; <ide> <ide> this.setSize( canvas.width, canvas.height ); <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> <ide> }; <ide> <del> function setSize( width, height ) { <add> function setSize( width, height ) { <ide> <del> canvasWBlocks = Math.floor( width / blockSize ); <add> canvasWBlocks = Math.floor( width / blockSize ); <ide> canvasHBlocks = Math.floor( height / blockSize ); <ide> canvasWidth = canvasWBlocks * blockSize; <ide> canvasHeight = canvasHBlocks * blockSize; <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> } <ide> <ide> cleanColorBuffer(); <del> } <add> } <ide> <ide> function cleanColorBuffer() { <ide> <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> if ( shaders[ id ] === undefined ) { <ide> <ide> if ( material instanceof THREE.MeshBasicMaterial || <del> material instanceof THREE.MeshLambertMaterial || <del> material instanceof THREE.MeshPhongMaterial || <del> material instanceof THREE.SpriteMaterial ) { <add> material instanceof THREE.MeshLambertMaterial || <add> material instanceof THREE.MeshPhongMaterial || <add> material instanceof THREE.SpriteMaterial ) { <ide> <ide> if ( material instanceof THREE.MeshLambertMaterial ) { <ide> // Generate color palette <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> <ide> } else if ( material instanceof THREE.LineBasicMaterial ) { <ide> <del> var string = [ <add> var string = [ <ide> 'var colorOffset = offset * 4;', <ide> 'buffer[ colorOffset ] = material.color.r * (color1.r+color2.r) * 0.5 * 255;', <ide> 'buffer[ colorOffset + 1 ] = material.color.g * (color1.g+color2.g) * 0.5 * 255;', <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> <ide> shader = new Function( 'buffer, depthBuf, offset, depth, color1, color2, material', string ); <ide> <del> } else { <add> } else { <ide> <ide> var string = [ <ide> 'var colorOffset = offset * 4;', <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> <ide> } <ide> <del> // When drawing line, the blockShiftShift has to be zero. In order to clean pixel <del> // Using color1 and color2 to interpolation pixel color <del> // LineWidth is according to material.linewidth <del> function drawLine( v1, v2, color1, color2, shader, material ) { <add> // When drawing line, the blockShiftShift has to be zero. In order to clean pixel <add> // Using color1 and color2 to interpolation pixel color <add> // LineWidth is according to material.linewidth <add> function drawLine( v1, v2, color1, color2, shader, material ) { <ide> <del> // While the line mode is enable, blockSize has to be changed to 0. <del> if ( !lineMode ) { <del> lineMode = true; <del> blockShift = 0; <del> blockSize = 1 << blockShift; <del> <del> setSize( canvas.width, canvas.height ); <del> } <add> // While the line mode is enable, blockSize has to be changed to 0. <add> if ( !lineMode ) { <add> lineMode = true; <add> blockShift = 0; <add> blockSize = 1 << blockShift; <ide> <del> // TODO: Implement per-pixel z-clipping <add> setSize( canvas.width, canvas.height ); <add> } <add> <add> // TODO: Implement per-pixel z-clipping <ide> if ( v1.z < -1 || v1.z > 1 || v2.z < -1 || v2.z > 1 ) return; <del> <del> var halfLineWidth = Math.floor( (material.linewidth-1) * 0.5 ); <add> <add> var halfLineWidth = Math.floor( (material.linewidth-1) * 0.5 ); <ide> <del> // https://gist.github.com/2486101 <add> // https://gist.github.com/2486101 <ide> // explanation: http://pouet.net/topic.php?which=8760&page=1 <ide> <ide> // 28.4 fixed-point coordinates <ide> var x1 = (v1.x * viewportXScale + viewportXOffs) | 0; <del> var x2 = (v2.x * viewportXScale + viewportXOffs) | 0; <add> var x2 = (v2.x * viewportXScale + viewportXOffs) | 0; <ide> <ide> var y1 = (v1.y * viewportYScale + viewportYOffs) | 0; <del> var y2 = (v2.y * viewportYScale + viewportYOffs) | 0; <add> var y2 = (v2.y * viewportYScale + viewportYOffs) | 0; <ide> <ide> var z1 = (v1.z * viewportZScale + viewportZOffs) | 0; <ide> var z2 = (v2.z * viewportZScale + viewportZOffs) | 0; <del> <add> <ide> // Deltas <ide> var dx12 = x1 - x2, dy12 = y1 - y2, dz12 = z1 - z2; <ide> <ide> THREE.SoftwareRenderer = function ( parameters ) { <ide> var maxx = Math.min( ( Math.max( x1, x2 ) + subpixelBias ) >> subpixelBits, canvasWidth ); <ide> var miny = Math.max( ( Math.min( y1, y2 ) + subpixelBias ) >> subpixelBits, 0 ); <ide> var maxy = Math.min( ( Math.max( y1, y2 ) + subpixelBias ) >> subpixelBits, canvasHeight ); <del> var minz = Math.max( ( Math.min( z1, z2 ) + subpixelBias ) >> subpixelBits, 0 ); <del> var maxz = Math.min( ( Math.max( z1, z2 ) + subpixelBias ) >> subpixelBits, 0 ); <del> <add> var minz = Math.max( ( Math.min( z1, z2 ) + subpixelBias ) >> subpixelBits, 0 ); <add> var maxz = Math.min( ( Math.max( z1, z2 ) + subpixelBias ) >> subpixelBits, 0 ); <add> <ide> rectx1 = Math.min( minx, rectx1 ); <ide> rectx2 = Math.max( maxx, rectx2 ); <ide> recty1 = Math.min( miny, recty1 ); <ide> recty2 = Math.max( maxy, recty2 ); <del> <del> // Get the line's unit vector and cross vector <del> var length = Math.sqrt((dy12 * dy12) + (dx12 * dx12)); <del> var unitX = (dx12 / length); <del> var unitY = (dy12 / length); <del> var unitZ = (dz12 / length); <del> var pixelX, pixelY, pixelZ; <del> var pX, pY, pZ; <del> crossVector.set( unitX, unitY, unitZ ); <del> crossVector.cross( lookVector ); <del> crossVector.normalize(); <add> <add> // Get the line's unit vector and cross vector <add> var length = Math.sqrt((dy12 * dy12) + (dx12 * dx12)); <add> var unitX = (dx12 / length); <add> var unitY = (dy12 / length); <add> var unitZ = (dz12 / length); <add> var pixelX, pixelY, pixelZ; <add> var pX, pY, pZ; <add> crossVector.set( unitX, unitY, unitZ ); <add> crossVector.cross( lookVector ); <add> crossVector.normalize(); <ide> <del> while (length > 0) { <add> while (length > 0) { <ide> <del> // Get this pixel. <del> pixelX = (x2 + length * unitX); <del> pixelY = (y2 + length * unitY); <del> pixelZ = (z2 + length * unitZ); <add> // Get this pixel. <add> pixelX = (x2 + length * unitX); <add> pixelY = (y2 + length * unitY); <add> pixelZ = (z2 + length * unitZ); <ide> <del> pixelX = (pixelX + subpixelBias) >> subpixelBits; <del> pixelY = (pixelY + subpixelBias) >> subpixelBits; <del> pZ = (pixelZ + subpixelBias) >> subpixelBits; <add> pixelX = (pixelX + subpixelBias) >> subpixelBits; <add> pixelY = (pixelY + subpixelBias) >> subpixelBits; <add> pZ = (pixelZ + subpixelBias) >> subpixelBits; <ide> <del> // Draw line with line width <del> for ( var i = -halfLineWidth; i <= halfLineWidth; ++i ) { <add> // Draw line with line width <add> for ( var i = -halfLineWidth; i <= halfLineWidth; ++i ) { <ide> <del> // Compute the line pixels. <del> // Get the pixels on the vector that crosses to the line vector <del> pX = Math.floor((pixelX + crossVector.x * i)); <del> pY = Math.floor((pixelY + crossVector.y * i)); <add> // Compute the line pixels. <add> // Get the pixels on the vector that crosses to the line vector <add> pX = Math.floor((pixelX + crossVector.x * i)); <add> pY = Math.floor((pixelY + crossVector.y * i)); <ide> <del> // if pixel is over the rect. Continue <del> if ( rectx1 >= pX || rectx2 <= pX || recty1 >= pY <del> || recty2 <= pY ) <del> continue; <add> // if pixel is over the rect. Continue <add> if ( rectx1 >= pX || rectx2 <= pX || recty1 >= pY <add> || recty2 <= pY ) <add> continue; <ide> <del> // Find this pixel at which block <del> var blockX = pX >> blockShift; <del> var blockY = pY >> blockShift; <del> var blockId = blockX + blockY * canvasWBlocks; <add> // Find this pixel at which block <add> var blockX = pX >> blockShift; <add> var blockY = pY >> blockShift; <add> var blockId = blockX + blockY * canvasWBlocks; <ide> <del> // Compare the pixel depth width z block. <del> if ( blockMaxZ[ blockId ] < minz ) continue; <add> // Compare the pixel depth width z block. <add> if ( blockMaxZ[ blockId ] < minz ) continue; <ide> <del> blockMaxZ[ blockId ] = Math.min( blockMaxZ[ blockId ], maxz ); <add> blockMaxZ[ blockId ] = Math.min( blockMaxZ[ blockId ], maxz ); <ide> <del> var bflags = blockFlags[ blockId ]; <del> if ( bflags & BLOCK_NEEDCLEAR ) clearBlock( blockX, blockY ); <del> blockFlags[ blockId ] = bflags & ~( BLOCK_ISCLEAR | BLOCK_NEEDCLEAR ); <del> <del> // draw pixel <del> var offset = pX + pY * canvasWidth; <del> <del> if ( pZ < zbuffer[ offset ] ) { <del> shader( data, zbuffer, offset, pZ, color1, color2, material ); <del> } <del> } <add> var bflags = blockFlags[ blockId ]; <add> if ( bflags & BLOCK_NEEDCLEAR ) clearBlock( blockX, blockY ); <add> blockFlags[ blockId ] = bflags & ~( BLOCK_ISCLEAR | BLOCK_NEEDCLEAR ); <add> <add> // draw pixel <add> var offset = pX + pY * canvasWidth; <add> <add> if ( pZ < zbuffer[ offset ] ) { <add> shader( data, zbuffer, offset, pZ, color1, color2, material ); <add> } <add> } <ide> <del> --length; <del> } <add> --length; <add> } <ide> <del> } <add> } <ide> <ide> function clearBlock( blockX, blockY ) { <ide>
1
PHP
PHP
fix typo in link to cakephp book documentation
3c46b8a491c29bd0a61eb60b1ebf42bb00872d53
<ide><path>lib/Cake/View/Helper/SessionHelper.php <ide> public function check($name) { <ide> * In your view: `$this->Session->error();` <ide> * <ide> * @return string last error <del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#displaying-notifcations-or-flash-messages <add> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#displaying-notifications-or-flash-messages <ide> */ <ide> public function error() { <ide> return CakeSession::error();
1
Text
Text
explain esm options for package authors
80cc6f52f5a0618477117f87bff5e209711236de
<ide><path>doc/api/esm.md <ide> or when referenced by `import` statements within ES module code: <ide> * Strings passed in as an argument to `--eval` or `--print`, or piped to <ide> `node` via `STDIN`, with the flag `--input-type=commonjs`. <ide> <del>## <code>package.json</code> <code>"type"</code> field <add>### <code>package.json</code> <code>"type"</code> field <ide> <ide> Files ending with `.js` or `.mjs`, or lacking any extension, <ide> will be loaded as ES modules when the nearest parent `package.json` file <ide> if the nearest parent `package.json` contains `"type": "module"`. <ide> import './startup.js'; // Loaded as ES module because of package.json <ide> ``` <ide> <del>## Package Scope and File Extensions <add>Package authors should include the `"type"` field, even in packages where all <add>sources are CommonJS. Being explicit about the `type` of the package will <add>future-proof the package in case the default type of Node.js ever changes, and <add>it will also make things easier for build tools and loaders to determine how the <add>files in the package should be interpreted. <add> <add>### Package Scope and File Extensions <ide> <ide> A folder containing a `package.json` file, and all subfolders below that <ide> folder down until the next folder containing another `package.json`, is <ide> package scope: <ide> extension (since both `.js` and `.cjs` files are treated as CommonJS within a <ide> `"commonjs"` package scope). <ide> <del>## <code>--input-type</code> flag <add>### <code>--input-type</code> flag <ide> <ide> Strings passed in as an argument to `--eval` or `--print` (or `-e` or `-p`), or <ide> piped to `node` via `STDIN`, will be treated as ES modules when the <ide> For completeness there is also `--input-type=commonjs`, for explicitly running <ide> string input as CommonJS. This is the default behavior if `--input-type` is <ide> unspecified. <ide> <del>## Package Entry Points <add>## Packages <add> <add>### Package Entry Points <ide> <ide> The `package.json` `"main"` field defines the entry point for a package, <ide> whether the package is included into CommonJS via `require` or into an ES <ide> be interpreted as CommonJS. <ide> <ide> The `"main"` field can point to exactly one file, regardless of whether the <ide> package is referenced via `require` (in a CommonJS context) or `import` (in an <del>ES module context). Package authors who want to publish a package to be used in <del>both contexts can do so by setting `"main"` to point to the CommonJS entry point <del>and informing the package’s users of the path to the ES module entry point. Such <del>a package would be accessible like `require('pkg')` and `import <del>'pkg/module.mjs'`. Alternatively the package `"main"` could point to the ES <del>module entry point and legacy users could be informed of the CommonJS entry <del>point path, e.g. `require('pkg/commonjs')`. <del> <del>## Package Exports <add>ES module context). <add> <add>#### Compatibility with CommonJS-Only Versions of Node.js <add> <add>Prior to the introduction of support for ES modules in Node.js, it was a common <add>pattern for package authors to include both CommonJS and ES module JavaScript <add>sources in their package, with `package.json` `"main"` specifying the CommonJS <add>entry point and `package.json` `"module"` specifying the ES module entry point. <add>This enabled Node.js to run the CommonJS entry point while build tools such as <add>bundlers used the ES module entry point, since Node.js ignored (and still <add>ignores) `"module"`. <add> <add>Node.js can now run ES module entry points, but it remains impossible for a <add>package to define separate CommonJS and ES module entry points. This is for good <add>reason: the `pkg` variable created from `import pkg from 'pkg'` is not the same <add>singleton as the `pkg` variable created from `const pkg = require('pkg')`, so if <add>both are referenced within the same app (including dependencies), unexpected <add>behavior might occur. <add> <add>There are two general approaches to addressing this limitation while still <add>publishing a package that contains both CommonJS and ES module sources: <add> <add>1. Document a new ES module entry point that’s not the package `"main"`, e.g. <add> `import pkg from 'pkg/module.mjs'` (or `import 'pkg/esm'`, if using [package <add> exports][]). The package `"main"` would still point to a CommonJS file, and <add> thus the package would remain compatible with older versions of Node.js that <add> lack support for ES modules. <add> <add>1. Switch the package `"main"` entry point to an ES module file as part of a <add> breaking change version bump. This version and above would only be usable on <add> ES module-supporting versions of Node.js. If the package still contains a <add> CommonJS version, it would be accessible via a path within the package, e.g. <add> `require('pkg/commonjs')`; this is essentially the inverse of the previous <add> approach. Package consumers who are using CommonJS-only versions of Node.js <add> would need to update their code from `require('pkg')` to e.g. <add> `require('pkg/commonjs')`. <add> <add>Of course, a package could also include only CommonJS or only ES module sources. <add>An existing package could make a semver major bump to an ES module-only version, <add>that would only be supported in ES module-supporting versions of Node.js (and <add>other runtimes). New packages could be published containing only ES module <add>sources, and would be compatible only with ES module-supporting runtimes. <add> <add>### Package Exports <ide> <ide> By default, all subpaths from a package can be imported (`import 'pkg/x.js'`). <ide> Custom subpath aliasing and encapsulation can be provided through the <ide> success! <ide> [`import`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import <ide> [`module.createRequire()`]: modules.html#modules_module_createrequire_filename <ide> [dynamic instantiate hook]: #esm_dynamic_instantiate_hook <add>[package exports]: #esm_package_exports <ide> [special scheme]: https://url.spec.whatwg.org/#special-scheme <ide> [the official standard format]: https://tc39.github.io/ecma262/#sec-modules
1
Javascript
Javascript
remove type cast
8bdc8ad6468c7911f8cbed5aa2c15fd3c1c4bf60
<ide><path>lib/wasm/WebAssemblyParser.js <ide> class WebAssemblyParser extends Tapable { <ide> const exports = (state.module.buildMeta.providedExports = []); <ide> t.traverse(ast, { <ide> ModuleExport({ node }) { <del> const moduleExport = /** @type {t.ModuleExport} */ (node); <del> exports.push(moduleExport.name); <add> exports.push(node.name); <ide> }, <ide> <ide> ModuleImport({ node }) { <del> const moduleImport = /** @type {t.ModuleImport} */ (node); <del> <ide> let onlyDirectImport = false; <ide> <del> if (isMemoryImport(moduleImport) === true) { <add> if (isMemoryImport(node) === true) { <ide> onlyDirectImport = true; <ide> } <ide> <del> if (isTableImport(moduleImport) === true) { <add> if (isTableImport(node) === true) { <ide> onlyDirectImport = true; <ide> } <ide> <ide> const dep = new WebAssemblyImportDependency( <del> moduleImport.module, <del> moduleImport.name, <del> moduleImport.descr, <add> node.module, <add> node.name, <add> node.descr, <ide> onlyDirectImport <ide> ); <ide>
1
Javascript
Javascript
stop unnecessary purging of node cache
10dab495f296fcef5a8b6afb380e91c57c134d59
<ide><path>src/core/ReactDOMIDOperations.js <ide> var ReactDOMIDOperations = { <ide> dangerouslyReplaceNodeWithMarkupByID: function(id, markup) { <ide> var node = ReactID.getNode(id); <ide> DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); <del> ReactID.purgeEntireCache(); <ide> }, <ide> <ide> /** <ide> var ReactDOMIDOperations = { <ide> manageChildrenByParentID: function(parentID, domOperations) { <ide> var parent = ReactID.getNode(parentID); <ide> DOMChildrenOperations.manageChildren(parent, domOperations); <del> ReactID.purgeEntireCache(); <ide> } <ide> <ide> }; <ide><path>src/core/ReactID.js <ide> function purgeID(id) { <ide> delete nodeCache[id]; <ide> } <ide> <del>/** <del> * Clears the entire cache. <del> */ <del>function purgeEntireCache() { <del> nodeCache = {}; <del>} <del> <ide> exports.ATTR_NAME = ATTR_NAME; <ide> exports.getID = getID; <ide> exports.setID = setID; <ide> exports.getNode = getNode; <ide> exports.purgeID = purgeID; <del>exports.purgeEntireCache = purgeEntireCache;
2
Javascript
Javascript
make reducers hot-reloadable
68cdeea6aea5bf2e3a2d86cc298790d63071cf7d
<ide><path>client/src/redux/createStore.js <ide> const sagaMiddleware = createSagaMiddleware(); <ide> export const createStore = () => { <ide> const store = reduxCreateStore(rootReducer, applyMiddleware(sagaMiddleware)); <ide> sagaMiddleware.run(rootSaga); <add> if (module.hot) { <add> // Enable Webpack hot module replacement for reducers <add> module.hot.accept('./rootReducer', () => { <add> const nextRootReducer = require('./rootReducer'); <add> store.replaceReducer(nextRootReducer); <add> }); <add> } <ide> return store; <ide> };
1
Text
Text
add links to subscribe to mailing list
230fc48ccd75b2144cb4561dadc315ef67c44871
<ide><path>README.md <ide> Follow us on twitter: @pdfjs <ide> <ide> http://twitter.com/#!/pdfjs <ide> <del>Join our mailing list: <add>Join our mailing list: <ide> <ide> [email protected] <add> <add>Subscribe either using lists.mozilla.org or Google Groups: <add> <add> https://lists.mozilla.org/listinfo/dev-pdf-js <add> https://groups.google.com/group/mozilla.dev.pdf-js/topics <ide> <ide> Talk to us on IRC: <ide>
1
Ruby
Ruby
display total disk space to be cleared
090b133a01d3918ea6a0d73768b836185a8dce35
<ide><path>Library/Homebrew/cmd/cleanup.rb <ide> require "keg" <ide> require "bottles" <ide> require "thread" <add>require "utils" <ide> <ide> module Homebrew <add> @@disk_cleanup_size = 0 <add> <add> def update_disk_cleanup_size(path_size) <add> @@disk_cleanup_size += path_size <add> end <add> <ide> def cleanup <ide> if ARGV.named.empty? <ide> cleanup_cellar <ide> def cleanup <ide> else <ide> ARGV.resolved_formulae.each { |f| cleanup_formula(f) } <ide> end <add> <add> if @@disk_cleanup_size > 0 <add> disk_space = disk_usage_readable(@@disk_cleanup_size) <add> if ARGV.dry_run? <add> ohai "This operation would free approximately #{disk_space} of disk space." <add> else <add> ohai "This operation has freed approximately #{disk_space} of disk space." <add> end <add> end <ide> end <ide> <ide> def cleanup_logs <ide> def cleanup_path(path) <ide> puts "Removing: #{path}... (#{path.abv})" <ide> yield <ide> end <add> update_disk_cleanup_size(path.disk_usage) <ide> end <ide> <ide> def cleanup_lockfiles
1
Javascript
Javascript
add todo comment
e89acf50a25430c40491529ddb8728800647367b
<ide><path>lib/DependenciesBlock.js <ide> class DependenciesBlock { <ide> this.dependencies = []; <ide> this.blocks = []; <ide> this.variables = []; <add> // TODO remove this line, it's wrong <ide> /** @type {ChunkGroup=} */ <ide> this.chunkGroup = undefined; <ide> }
1
Text
Text
use `buffer.bytelength` for content-length
d06820c624554df89e77cea4afd68a2ca58549a5
<ide><path>doc/api/http.md <ide> Example: <ide> ```js <ide> var body = 'hello world'; <ide> response.writeHead(200, { <del> 'Content-Length': body.length, <add> 'Content-Length': Buffer.byteLength(body), <ide> 'Content-Type': 'text/plain' }); <ide> ``` <ide> <ide> var options = { <ide> method: 'POST', <ide> headers: { <ide> 'Content-Type': 'application/x-www-form-urlencoded', <del> 'Content-Length': postData.length <add> 'Content-Length': Buffer.byteLength(postData) <ide> } <ide> }; <ide>
1
PHP
PHP
skip non-arrays when collapsing
934bb07cdafe0b086740bdb163691f0d7cc9364b
<ide><path>src/Illuminate/Support/Arr.php <ide> public static function collapse($array) <ide> $values = $values->all(); <ide> } <ide> <add> if (! is_array($values)) { <add> continue; <add> } <add> <ide> $results = array_merge($results, $values); <ide> } <ide>
1
Text
Text
fix script to match example
989d08a3583a062f0fe6606a88a417153ea6000e
<ide><path>inception/README.md <ide> bazel-bin/inception/build_image_data \ <ide> --validation_directory="${VALIDATION_DIR}" \ <ide> --output_directory="${OUTPUT_DIRECTORY}" \ <ide> --labels_file="${LABELS_FILE}" \ <del> --train_shards=128 \ <del> --validation_shards=24 \ <add> --train_shards=24 \ <add> --validation_shards=8 \ <ide> --num_threads=8 <ide> ``` <ide>
1
Ruby
Ruby
make remaining migration options to kwargs
817389d1dd4fd531a8df58e4f10d9da71147d193
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb <ide> def initialize( <ide> end <ide> <ide> def add_to(table) <del> columns.each do |column_options| <del> kwargs = column_options.extract_options! <del> table.column(*column_options, **kwargs) <add> columns.each do |name, type, options| <add> table.column(name, type, **options) <ide> end <ide> <ide> if index <ide> def timestamps(**options) <ide> # t.change(:description, :text) <ide> # <ide> # See TableDefinition#column for details of the options you can use. <del> def change(column_name, type, options = {}) <del> @base.change_column(name, column_name, type, options) <add> def change(column_name, type, **options) <add> @base.change_column(name, column_name, type, **options) <ide> end <ide> <ide> # Sets a new default value for a column. <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def remove_column(table_name, column_name, type = nil, **options) <ide> # change_column(:suppliers, :name, :string, limit: 80) <ide> # change_column(:accounts, :description, :text) <ide> # <del> def change_column(table_name, column_name, type, options = {}) <add> def change_column(table_name, column_name, type, **options) <ide> raise NotImplementedError, "change_column is not implemented" <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def rename_table(table_name, new_name) <ide> # Although this command ignores most +options+ and the block if one is given, <ide> # it can be helpful to provide these in a migration's +change+ method so it can be reverted. <ide> # In that case, +options+ and the block will be used by create_table. <del> def drop_table(table_name, options = {}) <add> def drop_table(table_name, **options) <ide> schema_cache.clear_data_source_cache!(table_name.to_s) <ide> execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}" <ide> end <ide> def change_column_comment(table_name, column_name, comment_or_changes) # :nodoc: <ide> change_column table_name, column_name, nil, comment: comment <ide> end <ide> <del> def change_column(table_name, column_name, type, options = {}) #:nodoc: <del> execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_for_alter(table_name, column_name, type, options)}") <add> def change_column(table_name, column_name, type, **options) #:nodoc: <add> execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_for_alter(table_name, column_name, type, **options)}") <ide> end <ide> <ide> def rename_column(table_name, column_name, new_column_name) #:nodoc: <ide> def translate_exception(exception, message:, sql:, binds:) <ide> end <ide> end <ide> <del> def change_column_for_alter(table_name, column_name, type, options = {}) <add> def change_column_for_alter(table_name, column_name, type, **options) <ide> column = column_for(table_name, column_name) <ide> type ||= column.sql_type <ide> <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb <ide> def drop_database(name) #:nodoc: <ide> execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}" <ide> end <ide> <del> def drop_table(table_name, options = {}) # :nodoc: <add> def drop_table(table_name, **options) # :nodoc: <ide> schema_cache.clear_data_source_cache!(table_name.to_s) <ide> execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}" <ide> end <ide> def create_schema(schema_name) <ide> end <ide> <ide> # Drops the schema for the given schema name. <del> def drop_schema(schema_name, options = {}) <add> def drop_schema(schema_name, **options) <ide> execute "DROP SCHEMA#{' IF EXISTS' if options[:if_exists]} #{quote_schema_name(schema_name)} CASCADE" <ide> end <ide> <ide> def add_column(table_name, column_name, type, **options) #:nodoc: <ide> change_column_comment(table_name, column_name, options[:comment]) if options.key?(:comment) <ide> end <ide> <del> def change_column(table_name, column_name, type, options = {}) #:nodoc: <add> def change_column(table_name, column_name, type, **options) #:nodoc: <ide> clear_cache! <del> sqls, procs = Array(change_column_for_alter(table_name, column_name, type, options)).partition { |v| v.is_a?(String) } <add> sqls, procs = Array(change_column_for_alter(table_name, column_name, type, **options)).partition { |v| v.is_a?(String) } <ide> execute "ALTER TABLE #{quote_table_name(table_name)} #{sqls.join(", ")}" <ide> procs.each(&:call) <ide> end <ide> def add_column_for_alter(table_name, column_name, type, **options) <ide> [super, Proc.new { change_column_comment(table_name, column_name, options[:comment]) }] <ide> end <ide> <del> def change_column_for_alter(table_name, column_name, type, options = {}) <add> def change_column_for_alter(table_name, column_name, type, **options) <ide> td = create_table_definition(table_name) <ide> cd = td.new_column_definition(column_name, type, **options) <ide> sqls = [schema_creation.accept(ChangeColumnDefinition.new(cd, column_name))] <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def change_column_null(table_name, column_name, null, default = nil) #:nodoc: <ide> end <ide> end <ide> <del> def change_column(table_name, column_name, type, options = {}) #:nodoc: <add> def change_column(table_name, column_name, type, **options) #:nodoc: <ide> alter_table(table_name) do |definition| <ide> definition[column_name].instance_eval do <del> self.type = type <del> self.limit = options[:limit] if options.include?(:limit) <del> self.default = options[:default] if options.include?(:default) <del> self.null = options[:null] if options.include?(:null) <del> self.precision = options[:precision] if options.include?(:precision) <del> self.scale = options[:scale] if options.include?(:scale) <del> self.collation = options[:collation] if options.include?(:collation) <add> self.type = type <add> self.options.merge!(options) <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/migration/command_recorder.rb <ide> def invert_remove_columns(args) <ide> end <ide> <ide> def invert_rename_index(args) <del> [:rename_index, [args.first] + args.last(2).reverse] <add> table_name, old_name, new_name = args <add> [:rename_index, [table_name, new_name, old_name]] <ide> end <ide> <ide> def invert_rename_column(args) <del> [:rename_column, [args.first] + args.last(2).reverse] <add> table_name, old_name, new_name = args <add> [:rename_column, [table_name, new_name, old_name]] <ide> end <ide> <ide> def invert_remove_index(args) <ide> def invert_remove_index(args) <ide> alias :invert_remove_belongs_to :invert_remove_reference <ide> <ide> def invert_change_column_default(args) <del> table, column, options = *args <add> table, column, options = args <ide> <del> unless options && options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to) <add> unless options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to) <ide> raise ActiveRecord::IrreversibleMigration, "change_column_default is only reversible if given a :from and :to option." <ide> end <ide> <ide> def invert_remove_foreign_key(args) <ide> end <ide> <ide> def invert_change_column_comment(args) <del> table, column, options = *args <add> table, column, options = args <ide> <del> unless options && options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to) <add> unless options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to) <ide> raise ActiveRecord::IrreversibleMigration, "change_column_comment is only reversible if given a :from and :to option." <ide> end <ide> <ide> [:change_column_comment, [table, column, from: options[:to], to: options[:from]]] <ide> end <ide> <ide> def invert_change_table_comment(args) <del> table, options = *args <add> table, options = args <ide> <del> unless options && options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to) <add> unless options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to) <ide> raise ActiveRecord::IrreversibleMigration, "change_table_comment is only reversible if given a :from and :to option." <ide> end <ide> <ide><path>activerecord/lib/active_record/migration/compatibility.rb <ide> def invert_transaction(args, &block) <ide> end <ide> <ide> def invert_change_column_comment(args) <del> table_name, column_name, comment = args <del> [:change_column_comment, [table_name, column_name, from: comment, to: comment]] <add> [:change_column_comment, args] <ide> end <ide> <ide> def invert_change_table_comment(args) <del> table_name, comment = args <del> [:change_table_comment, [table_name, from: comment, to: comment]] <add> [:change_table_comment, args] <ide> end <ide> end <ide> <ide> class << recorder <ide> end <ide> <ide> class V5_1 < V5_2 <del> def change_column(table_name, column_name, type, options = {}) <add> def change_column(table_name, column_name, type, **options) <ide> if connection.adapter_name == "PostgreSQL" <del> super(table_name, column_name, type, options.except(:default, :null, :comment)) <add> super(table_name, column_name, type, **options.except(:default, :null, :comment)) <ide> connection.change_column_default(table_name, column_name, options[:default]) if options.key?(:default) <ide> connection.change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null) <ide> connection.change_column_comment(table_name, column_name, options[:comment]) if options.key?(:comment) <ide><path>activerecord/test/cases/migration/change_table_test.rb <ide> def test_rename_index_renames_index <ide> <ide> def test_change_changes_column <ide> with_change_table do |t| <del> @connection.expect :change_column, nil, [:delete_me, :bar, :string, {}] <add> if RUBY_VERSION < "2.7" <add> @connection.expect :change_column, nil, [:delete_me, :bar, :string, {}] <add> else <add> @connection.expect :change_column, nil, [:delete_me, :bar, :string] <add> end <ide> t.change :bar, :string <ide> end <ide> end
8
Ruby
Ruby
add missing space and newline for clarity
238c77dedf3a9de27f8e902ad3dcfdc3480d95bc
<ide><path>activerecord/lib/active_record/migration.rb <ide> def initialize(env = "production") <ide> class EnvironmentMismatchError < ActiveRecordError <ide> def initialize(current: nil, stored: nil) <ide> msg = "You are attempting to modify a database that was last run in `#{ stored }` environment.\n" <del> msg << "You are running in `#{ current }` environment." <add> msg << "You are running in `#{ current }` environment. " <ide> msg << "If you are sure you want to continue, first set the environment using:\n\n" <ide> msg << "\tbin/rails db:environment:set" <ide> if defined?(Rails.env) <del> super("#{msg} RAILS_ENV=#{::Rails.env}") <add> super("#{msg} RAILS_ENV=#{::Rails.env}\n\n") <ide> else <del> super(msg) <add> super("#{msg}\n\n") <ide> end <ide> end <ide> end
1
Ruby
Ruby
support alias for tap
5f68fff92b8b3389ca023f913f1e6d83282a3eab
<ide><path>Library/Homebrew/formulary.rb <ide> def initialize(tapped_name) <ide> @tap = Tap.new user, repo.sub(/^homebrew-/, "") <ide> name = @tap.formula_renames.fetch(name, name) <ide> path = @tap.formula_files.detect { |file| file.basename(".rb").to_s == name } <del> path ||= @tap.path/"#{name}.rb" <add> <add> unless path <add> if (possible_alias = @tap.path/"Aliases/#{name}").file? <add> path = possible_alias.resolved_path <add> name = path.basename(".rb").to_s <add> else <add> path = @tap.path/"#{name}.rb" <add> end <add> end <ide> <ide> super name, path <ide> end <ide> def self.loader_for(ref) <ide> if possible_tap_formulae.size > 1 <ide> raise TapFormulaAmbiguityError.new(ref, possible_tap_formulae) <ide> elsif possible_tap_formulae.size == 1 <del> return FormulaLoader.new(ref, possible_tap_formulae.first) <add> path = possible_tap_formulae.first.resolved_path <add> name = path.basename(".rb").to_s <add> return FormulaLoader.new(name, path) <ide> end <ide> <ide> if newref = FORMULA_RENAMES[ref] <ide> def self.tap_paths(name, taps = Dir["#{HOMEBREW_LIBRARY}/Taps/*/*/"]) <ide> Pathname.glob([ <ide> "#{tap}Formula/#{name}.rb", <ide> "#{tap}HomebrewFormula/#{name}.rb", <del> "#{tap}#{name}.rb" <add> "#{tap}#{name}.rb", <add> "#{tap}Aliases/#{name}", <ide> ]).detect(&:file?) <ide> end.compact <ide> end
1
Javascript
Javascript
compress http responses from the packager
b838b4617c05fa19a44ec21f1e27961b64efb210
<ide><path>local-cli/server/runServer.js <ide> function runServer(args, config, readyCallback) { <ide> var wsProxy = null; <ide> const app = connect() <ide> .use(loadRawBodyMiddleware) <add> .use(connect.compress()) <ide> .use(getDevToolsMiddleware(args, () => wsProxy && wsProxy.isChromeConnected())) <ide> .use(openStackFrameInEditorMiddleware) <ide> .use(statusPageMiddleware) <ide> function runServer(args, config, readyCallback) { <ide> args.projectRoots.forEach(root => app.use(connect.static(root))); <ide> <ide> app.use(connect.logger()) <del> .use(connect.compress()) <ide> .use(connect.errorHandler()); <ide> <ide> const serverInstance = http.createServer(app).listen(
1
Ruby
Ruby
use respond_to test helpers
0d50cae996c51630361e8514e1f168b0c48957e1
<ide><path>actionmailer/test/base_test.rb <ide> def welcome <ide> test "should respond to action methods" do <ide> assert_respond_to BaseMailer, :welcome <ide> assert_respond_to BaseMailer, :implicit_multipart <del> assert !BaseMailer.respond_to?(:mail) <del> assert !BaseMailer.respond_to?(:headers) <add> assert_not_respond_to BaseMailer, :mail <add> assert_not_respond_to BaseMailer, :headers <ide> end <ide> <ide> test "calling just the action should return the generated mail object" do <ide><path>actionpack/test/controller/parameters/accessors_test.rb <ide> class ParametersAccessorsTest < ActiveSupport::TestCase <ide> else <ide> test "ActionController::Parameters does not respond to #dig on Ruby 2.2" do <ide> assert_not ActionController::Parameters.method_defined?(:dig) <del> assert_not @params.respond_to?(:dig) <add> assert_not_respond_to @params, :dig <ide> end <ide> end <ide> end <ide><path>actionpack/test/controller/runner_test.rb <ide> def hi; end <ide> <ide> def test_respond_to? <ide> runner = MyRunner.new(Class.new { def x; end }.new) <del> assert runner.respond_to?(:hi) <del> assert runner.respond_to?(:x) <add> assert_respond_to runner, :hi <add> assert_respond_to runner, :x <ide> end <ide> end <ide> end <ide><path>actionpack/test/controller/test_case_test.rb <ide> def test_fixture_file_upload_with_binary <ide> <ide> def test_fixture_file_upload_should_be_able_access_to_tempfile <ide> file = fixture_file_upload(FILES_DIR + "/ruby_on_rails.jpg", "image/jpg") <del> assert file.respond_to?(:tempfile), "expected tempfile should respond on fixture file object, got nothing" <add> assert_respond_to file, :tempfile <ide> end <ide> <ide> def test_fixture_file_upload <ide><path>actionpack/test/controller/url_for_test.rb <ide> def test_named_routes <ide> kls = Class.new { include set.url_helpers } <ide> <ide> controller = kls.new <del> assert controller.respond_to?(:home_url) <add> assert_respond_to controller, :home_url <ide> assert_equal "http://www.basecamphq.com/home/sweet/home/again", <ide> controller.send(:home_url, host: "www.basecamphq.com", user: "again") <ide> <ide><path>actionpack/test/dispatch/mime_type_test.rb <ide> class MimeTypeTest < ActiveSupport::TestCase <ide> <ide> types.each do |type| <ide> mime = Mime[type] <del> assert mime.respond_to?("#{type}?"), "#{mime.inspect} does not respond to #{type}?" <add> assert_respond_to mime, "#{type}?" <ide> assert_equal type, mime.symbol, "#{mime.inspect} is not #{type}?" <ide> invalid_types = types - [type] <ide> invalid_types.delete(:html) <ide><path>actionpack/test/dispatch/response_test.rb <ide> def test_only_set_charset_still_defaults_to_text_html <ide> end <ide> <ide> test "respond_to? accepts include_private" do <del> assert_not @response.respond_to?(:method_missing) <add> assert_not_respond_to @response, :method_missing <ide> assert @response.respond_to?(:method_missing, true) <ide> end <ide> <ide><path>actionpack/test/dispatch/uploaded_file_test.rb <ide> def test_delegate_eof_to_tempfile <ide> def test_respond_to? <ide> tf = Class.new { def read; yield end } <ide> uf = Http::UploadedFile.new(tempfile: tf.new) <del> assert uf.respond_to?(:headers), "responds to headers" <del> assert uf.respond_to?(:read), "responds to read" <add> assert_respond_to uf, :headers <add> assert_respond_to uf, :read <ide> end <ide> end <ide> end <ide><path>activemodel/lib/active_model/lint.rb <ide> module Tests <ide> # <tt>to_key</tt> returns an Enumerable of all (primary) key attributes <ide> # of the model, and is used to a generate unique DOM id for the object. <ide> def test_to_key <del> assert model.respond_to?(:to_key), "The model should respond to to_key" <add> assert_respond_to model, :to_key <ide> def model.persisted?() false end <ide> assert model.to_key.nil?, "to_key should return nil when `persisted?` returns false" <ide> end <ide> def model.persisted?() false end <ide> # tests for this behavior in lint because it doesn't make sense to force <ide> # any of the possible implementation strategies on the implementer. <ide> def test_to_param <del> assert model.respond_to?(:to_param), "The model should respond to to_param" <add> assert_respond_to model, :to_param <ide> def model.to_key() [1] end <ide> def model.persisted?() false end <ide> assert model.to_param.nil?, "to_param should return nil when `persisted?` returns false" <ide> def model.persisted?() false end <ide> # <tt>to_partial_path</tt> is used for looking up partials. For example, <ide> # a BlogPost model might return "blog_posts/blog_post". <ide> def test_to_partial_path <del> assert model.respond_to?(:to_partial_path), "The model should respond to to_partial_path" <add> assert_respond_to model, :to_partial_path <ide> assert_kind_of String, model.to_partial_path <ide> end <ide> <ide> def test_to_partial_path <ide> # will route to the create action. If it is persisted, a form for the <ide> # object will route to the update action. <ide> def test_persisted? <del> assert model.respond_to?(:persisted?), "The model should respond to persisted?" <add> assert_respond_to model, :persisted? <ide> assert_boolean model.persisted?, "persisted?" <ide> end <ide> <ide> def test_persisted? <ide> # <ide> # Check ActiveModel::Naming for more information. <ide> def test_model_naming <del> assert model.class.respond_to?(:model_name), "The model class should respond to model_name" <add> assert_respond_to model.class, :model_name <ide> model_name = model.class.model_name <del> assert model_name.respond_to?(:to_str) <del> assert model_name.human.respond_to?(:to_str) <del> assert model_name.singular.respond_to?(:to_str) <del> assert model_name.plural.respond_to?(:to_str) <add> assert_respond_to model_name, :to_str <add> assert_respond_to model_name.human, :to_str <add> assert_respond_to model_name.singular, :to_str <add> assert_respond_to model_name.plural, :to_str <ide> <del> assert model.respond_to?(:model_name), "The model instance should respond to model_name" <add> assert_respond_to model, :model_name <ide> assert_equal model.model_name, model.class.model_name <ide> end <ide> <ide> def test_model_naming <ide> # If localization is used, the strings should be localized for the current <ide> # locale. If no error is present, the method should return an empty array. <ide> def test_errors_aref <del> assert model.respond_to?(:errors), "The model should respond to errors" <add> assert_respond_to model, :errors <ide> assert model.errors[:hello].is_a?(Array), "errors#[] should return an Array" <ide> end <ide> <ide> private <ide> def model <del> assert @model.respond_to?(:to_model), "The object should respond to to_model" <add> assert_respond_to @model, :to_model <ide> @model.to_model <ide> end <ide> <ide><path>activemodel/test/cases/attribute_methods_test.rb <ide> def foo <ide> ModelWithAttributes.define_attribute_methods(:foo) <ide> ModelWithAttributes.undefine_attribute_methods <ide> <del> assert !ModelWithAttributes.new.respond_to?(:foo) <add> assert_not_respond_to ModelWithAttributes.new, :foo <ide> assert_raises(NoMethodError) { ModelWithAttributes.new.foo } <ide> end <ide> <ide> def protected_method <ide> m = ModelWithAttributes2.new <ide> m.attributes = { "private_method" => "<3", "protected_method" => "O_o" } <ide> <del> assert !m.respond_to?(:private_method) <add> assert_not_respond_to m, :private_method <ide> assert m.respond_to?(:private_method, true) <ide> <ide> c = ClassWithProtected.new <ide><path>activemodel/test/cases/callbacks_test.rb <ide> def create <ide> end <ide> <ide> test "only selects which types of callbacks should be created" do <del> assert !ModelCallbacks.respond_to?(:before_initialize) <del> assert !ModelCallbacks.respond_to?(:around_initialize) <add> assert_not_respond_to ModelCallbacks, :before_initialize <add> assert_not_respond_to ModelCallbacks, :around_initialize <ide> assert_respond_to ModelCallbacks, :after_initialize <ide> end <ide> <ide> test "only selects which types of callbacks should be created from an array list" do <ide> assert_respond_to ModelCallbacks, :before_multiple <ide> assert_respond_to ModelCallbacks, :around_multiple <del> assert !ModelCallbacks.respond_to?(:after_multiple) <add> assert_not_respond_to ModelCallbacks, :after_multiple <ide> end <ide> <ide> test "no callbacks should be created" do <del> assert !ModelCallbacks.respond_to?(:before_empty) <del> assert !ModelCallbacks.respond_to?(:around_empty) <del> assert !ModelCallbacks.respond_to?(:after_empty) <add> assert_not_respond_to ModelCallbacks, :before_empty <add> assert_not_respond_to ModelCallbacks, :around_empty <add> assert_not_respond_to ModelCallbacks, :after_empty <ide> end <ide> <ide> class Violin <ide><path>activemodel/test/cases/errors_test.rb <ide> def test_no_key <ide> <ide> test "generate_message works without i18n_scope" do <ide> person = Person.new <del> assert !Person.respond_to?(:i18n_scope) <add> assert_not_respond_to Person, :i18n_scope <ide> assert_nothing_raised { <ide> person.errors.generate_message(:name, :blank) <ide> } <ide><path>activerecord/test/cases/adapters/postgresql/hstore_test.rb <ide> def setup <ide> end <ide> <ide> def test_hstore_included_in_extensions <del> assert @connection.respond_to?(:extensions), "connection should have a list of extensions" <add> assert_respond_to @connection, :extensions <ide> assert_includes @connection.extensions, "hstore", "extension list should include hstore" <ide> end <ide> <ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb <ide> def test_supports_extensions <ide> end <ide> <ide> def test_respond_to_enable_extension <del> assert @conn.respond_to?(:enable_extension) <add> assert_respond_to @conn, :enable_extension <ide> end <ide> <ide> def test_respond_to_disable_extension <del> assert @conn.respond_to?(:disable_extension) <add> assert_respond_to @conn, :disable_extension <ide> end <ide> <ide> def test_statement_closed <ide><path>activerecord/test/cases/associations/left_outer_join_association_test.rb <ide> def test_find_with_sti_join <ide> def test_does_not_override_select <ide> authors = Author.select("authors.name, #{%{(authors.author_address_id || ' ' || authors.author_address_extra_id) as addr_id}}").left_outer_joins(:posts) <ide> assert authors.any? <del> assert authors.first.respond_to?(:addr_id) <add> assert_respond_to authors.first, :addr_id <ide> end <ide> <ide> test "the default scope of the target is applied when joining associations" do <ide><path>activerecord/test/cases/attribute_methods_test.rb <ide> def setup <ide> assert_respond_to topic, :title= <ide> assert_respond_to topic, "author_name" <ide> assert_respond_to topic, "attribute_names" <del> assert !topic.respond_to?("nothingness") <del> assert !topic.respond_to?(:nothingness) <add> assert_not_respond_to topic, "nothingness" <add> assert_not_respond_to topic, :nothingness <ide> end <ide> <ide> test "respond_to? with a custom primary key" do <ide> keyboard = Keyboard.create <ide> assert_not_nil keyboard.key_number <ide> assert_equal keyboard.key_number, keyboard.id <del> assert keyboard.respond_to?("key_number") <del> assert keyboard.respond_to?("id") <add> assert_respond_to keyboard, "key_number" <add> assert_respond_to keyboard, "id" <ide> end <ide> <ide> test "id_before_type_cast with a custom primary key" do <ide> def setup <ide> end <ide> <ide> topic = klass.allocate <del> assert !topic.respond_to?("nothingness") <del> assert !topic.respond_to?(:nothingness) <add> assert_not_respond_to topic, "nothingness" <add> assert_not_respond_to topic, :nothingness <ide> assert_respond_to topic, "title" <ide> assert_respond_to topic, :title <ide> end <ide> def topic.title() "b" end <ide> <ide> test "non-attribute read and write" do <ide> topic = Topic.new <del> assert !topic.respond_to?("mumbo") <add> assert_not_respond_to topic, "mumbo" <ide> assert_raise(NoMethodError) { topic.mumbo } <ide> assert_raise(NoMethodError) { topic.mumbo = 5 } <ide> end <ide> <ide> test "undeclared attribute method does not affect respond_to? and method_missing" do <ide> topic = @target.new(title: "Budget") <del> assert topic.respond_to?("title") <add> assert_respond_to topic, "title" <ide> assert_equal "Budget", topic.title <del> assert !topic.respond_to?("title_hello_world") <add> assert_not_respond_to topic, "title_hello_world" <ide> assert_raise(NoMethodError) { topic.title_hello_world } <ide> end <ide> <ide> def topic.title() "b" end <ide> @target.attribute_method_prefix prefix <ide> <ide> meth = "#{prefix}title" <del> assert topic.respond_to?(meth) <add> assert_respond_to topic, meth <ide> assert_equal ["title"], topic.send(meth) <ide> assert_equal ["title", "a"], topic.send(meth, "a") <ide> assert_equal ["title", 1, 2, 3], topic.send(meth, 1, 2, 3) <ide> def topic.title() "b" end <ide> topic = @target.new(title: "Budget") <ide> <ide> meth = "title#{suffix}" <del> assert topic.respond_to?(meth) <add> assert_respond_to topic, meth <ide> assert_equal ["title"], topic.send(meth) <ide> assert_equal ["title", "a"], topic.send(meth, "a") <ide> assert_equal ["title", 1, 2, 3], topic.send(meth, 1, 2, 3) <ide> def topic.title() "b" end <ide> topic = @target.new(title: "Budget") <ide> <ide> meth = "#{prefix}title#{suffix}" <del> assert topic.respond_to?(meth) <add> assert_respond_to topic, meth <ide> assert_equal ["title"], topic.send(meth) <ide> assert_equal ["title", "a"], topic.send(meth, "a") <ide> assert_equal ["title", 1, 2, 3], topic.send(meth, 1, 2, 3) <ide> def topic.title() "b" end <ide> privatize("title") <ide> <ide> topic = @target.new(title: "The pros and cons of programming naked.") <del> assert !topic.respond_to?(:title) <add> assert_not_respond_to topic, :title <ide> exception = assert_raise(NoMethodError) { topic.title } <ide> assert_includes exception.message, "private method" <ide> assert_equal "I'm private", topic.send(:title) <ide> def topic.title() "b" end <ide> privatize("title=(value)") <ide> <ide> topic = @target.new <del> assert !topic.respond_to?(:title=) <add> assert_not_respond_to topic, :title= <ide> exception = assert_raise(NoMethodError) { topic.title = "Pants" } <ide> assert_includes exception.message, "private method" <ide> topic.send(:title=, "Very large pants") <ide> def topic.title() "b" end <ide> privatize("title?") <ide> <ide> topic = @target.new(title: "Isaac Newton's pants") <del> assert !topic.respond_to?(:title?) <add> assert_not_respond_to topic, :title? <ide> exception = assert_raise(NoMethodError) { topic.title? } <ide> assert_includes exception.message, "private method" <ide> assert topic.send(:title?) <ide><path>activerecord/test/cases/autosave_association_test.rb <ide> def setup <ide> end <ide> <ide> test "should not generate validation methods for has_one associations without :validate => true" do <del> assert [email protected]_to?(:validate_associated_records_for_non_validated_ship) <add> assert_not_respond_to @pirate, :validate_associated_records_for_non_validated_ship <ide> end <ide> <ide> test "should generate validation methods for belongs_to associations with :validate => true" do <ide> assert_respond_to @pirate, :validate_associated_records_for_parrot <ide> end <ide> <ide> test "should not generate validation methods for belongs_to associations without :validate => true" do <del> assert [email protected]_to?(:validate_associated_records_for_non_validated_parrot) <add> assert_not_respond_to @pirate, :validate_associated_records_for_non_validated_parrot <ide> end <ide> <ide> test "should generate validation methods for HABTM associations with :validate => true" do <ide><path>activerecord/test/cases/base_test.rb <ide> def test_default_values_are_deeply_dupped <ide> end <ide> <ide> test "ignored columns have no attribute methods" do <del> refute Developer.new.respond_to?(:first_name) <del> refute Developer.new.respond_to?(:first_name=) <del> refute Developer.new.respond_to?(:first_name?) <del> refute SubDeveloper.new.respond_to?(:first_name) <del> refute SubDeveloper.new.respond_to?(:first_name=) <del> refute SubDeveloper.new.respond_to?(:first_name?) <del> refute SymbolIgnoredDeveloper.new.respond_to?(:first_name) <del> refute SymbolIgnoredDeveloper.new.respond_to?(:first_name=) <del> refute SymbolIgnoredDeveloper.new.respond_to?(:first_name?) <add> assert_not_respond_to Developer.new, :first_name <add> assert_not_respond_to Developer.new, :first_name= <add> assert_not_respond_to Developer.new, :first_name? <add> assert_not_respond_to SubDeveloper.new, :first_name <add> assert_not_respond_to SubDeveloper.new, :first_name= <add> assert_not_respond_to SubDeveloper.new, :first_name? <add> assert_not_respond_to SymbolIgnoredDeveloper.new, :first_name <add> assert_not_respond_to SymbolIgnoredDeveloper.new, :first_name= <add> assert_not_respond_to SymbolIgnoredDeveloper.new, :first_name? <ide> end <ide> <ide> test "ignored columns don't prevent explicit declaration of attribute methods" do <del> assert Developer.new.respond_to?(:last_name) <del> assert Developer.new.respond_to?(:last_name=) <del> assert Developer.new.respond_to?(:last_name?) <del> assert SubDeveloper.new.respond_to?(:last_name) <del> assert SubDeveloper.new.respond_to?(:last_name=) <del> assert SubDeveloper.new.respond_to?(:last_name?) <del> assert SymbolIgnoredDeveloper.new.respond_to?(:last_name) <del> assert SymbolIgnoredDeveloper.new.respond_to?(:last_name=) <del> assert SymbolIgnoredDeveloper.new.respond_to?(:last_name?) <add> assert_respond_to Developer.new, :last_name <add> assert_respond_to Developer.new, :last_name= <add> assert_respond_to Developer.new, :last_name? <add> assert_respond_to SubDeveloper.new, :last_name <add> assert_respond_to SubDeveloper.new, :last_name= <add> assert_respond_to SubDeveloper.new, :last_name? <add> assert_respond_to SymbolIgnoredDeveloper.new, :last_name <add> assert_respond_to SymbolIgnoredDeveloper.new, :last_name= <add> assert_respond_to SymbolIgnoredDeveloper.new, :last_name? <ide> end <ide> <ide> test "ignored columns are stored as an array of string" do <ide> def test_default_values_are_deeply_dupped <ide> <ide> test "when #reload called, ignored columns' attribute methods are not defined" do <ide> developer = Developer.create!(name: "Developer") <del> refute developer.respond_to?(:first_name) <del> refute developer.respond_to?(:first_name=) <add> assert_not_respond_to developer, :first_name <add> assert_not_respond_to developer, :first_name= <ide> <ide> developer.reload <ide> <del> refute developer.respond_to?(:first_name) <del> refute developer.respond_to?(:first_name=) <add> assert_not_respond_to developer, :first_name <add> assert_not_respond_to developer, :first_name= <ide> end <ide> <ide> test "ignored columns not included in SELECT" do <ide><path>activerecord/test/cases/connection_management_test.rb <ide> def test_connections_not_closed_if_exception_inside_transaction <ide> body = Class.new(String) { def to_path; "/path"; end }.new <ide> app = lambda { |_| [200, {}, body] } <ide> response_body = middleware(app).call(@env)[2] <del> assert response_body.respond_to?(:to_path) <add> assert_respond_to response_body, :to_path <ide> assert_equal "/path", response_body.to_path <ide> end <ide> <ide><path>activerecord/test/cases/enum_test.rb <ide> def self.name; "Book"; end <ide> end <ide> <ide> test "enum methods with custom suffix defined" do <del> assert @book.class.respond_to?(:easy_to_read) <del> assert @book.class.respond_to?(:medium_to_read) <del> assert @book.class.respond_to?(:hard_to_read) <add> assert_respond_to @book.class, :easy_to_read <add> assert_respond_to @book.class, :medium_to_read <add> assert_respond_to @book.class, :hard_to_read <ide> <del> assert @book.respond_to?(:easy_to_read?) <del> assert @book.respond_to?(:medium_to_read?) <del> assert @book.respond_to?(:hard_to_read?) <add> assert_respond_to @book, :easy_to_read? <add> assert_respond_to @book, :medium_to_read? <add> assert_respond_to @book, :hard_to_read? <ide> <del> assert @book.respond_to?(:easy_to_read!) <del> assert @book.respond_to?(:medium_to_read!) <del> assert @book.respond_to?(:hard_to_read!) <add> assert_respond_to @book, :easy_to_read! <add> assert_respond_to @book, :medium_to_read! <add> assert_respond_to @book, :hard_to_read! <ide> end <ide> <ide> test "update enum attributes with custom suffix" do <ide><path>activerecord/test/cases/finder_respond_to_test.rb <ide> class FinderRespondToTest < ActiveRecord::TestCase <ide> <ide> def test_should_preserve_normal_respond_to_behaviour_on_base <ide> assert_respond_to ActiveRecord::Base, :new <del> assert !ActiveRecord::Base.respond_to?(:find_by_something) <add> assert_not_respond_to ActiveRecord::Base, :find_by_something <ide> end <ide> <ide> def test_should_preserve_normal_respond_to_behaviour_and_respond_to_newly_added_method <ide> def test_should_respond_to_find_all_by_an_aliased_attribute <ide> end <ide> <ide> def test_should_not_respond_to_find_by_one_missing_attribute <del> assert !Topic.respond_to?(:find_by_undertitle) <add> assert_not_respond_to Topic, :find_by_undertitle <ide> end <ide> <ide> def test_should_not_respond_to_find_by_invalid_method_syntax <del> assert !Topic.respond_to?(:fail_to_find_by_title) <del> assert !Topic.respond_to?(:find_by_title?) <del> assert !Topic.respond_to?(:fail_to_find_or_create_by_title) <del> assert !Topic.respond_to?(:find_or_create_by_title?) <add> assert_not_respond_to Topic, :fail_to_find_by_title <add> assert_not_respond_to Topic, :find_by_title? <add> assert_not_respond_to Topic, :fail_to_find_or_create_by_title <add> assert_not_respond_to Topic, :find_or_create_by_title? <ide> end <ide> <ide> private <ide><path>activerecord/test/cases/json_serialization_test.rb <ide> def test_should_not_call_methods_on_associations_that_dont_respond <ide> def @david.favorite_quote; "Constraints are liberating"; end <ide> json = @david.to_json(include: :posts, methods: :favorite_quote) <ide> <del> assert [email protected]_to?(:favorite_quote) <add> assert_not_respond_to @david.posts.first, :favorite_quote <ide> assert_match %r{"favorite_quote":"Constraints are liberating"}, json <ide> assert_equal 1, %r{"favorite_quote":}.match(json).size <ide> end <ide><path>activerecord/test/cases/migration/command_recorder_test.rb <ide> def test_respond_to_delegates <ide> recorder = CommandRecorder.new(Class.new { <ide> def america; end <ide> }.new) <del> assert recorder.respond_to?(:america) <add> assert_respond_to recorder, :america <ide> end <ide> <ide> def test_send_calls_super <ide> def test_send_delegates_to_record <ide> recorder = CommandRecorder.new(Class.new { <ide> def create_table(name); end <ide> }.new) <del> assert recorder.respond_to?(:create_table), "respond_to? create_table" <add> assert_respond_to recorder, :create_table <ide> recorder.send(:create_table, :horses) <ide> assert_equal [[:create_table, [:horses], nil]], recorder.commands <ide> end <ide><path>activerecord/test/cases/multiparameter_attributes_test.rb <ide> def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes_false <ide> topic = Topic.find(1) <ide> topic.attributes = attributes <ide> assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on <del> assert_equal false, topic.written_on.respond_to?(:time_zone) <add> assert_not_respond_to topic.written_on, :time_zone <ide> end <ide> end <ide> <ide> def test_multiparameter_attributes_on_time_with_skip_time_zone_conversion_for_at <ide> topic = Topic.find(1) <ide> topic.attributes = attributes <ide> assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on <del> assert_equal false, topic.written_on.respond_to?(:time_zone) <add> assert_not_respond_to topic.written_on, :time_zone <ide> end <ide> ensure <ide> Topic.skip_time_zone_conversion_for_attributes = [] <ide><path>activerecord/test/cases/relation_test.rb <ide> def test_merge_raises_with_invalid_argument <ide> <ide> def test_respond_to_for_non_selected_element <ide> post = Post.select(:title).first <del> assert_equal false, post.respond_to?(:body), "post should not respond_to?(:body) since invoking it raises exception" <add> assert_not_respond_to post, :body, "post should not respond_to?(:body) since invoking it raises exception" <ide> <ide> silence_warnings { post = Post.select("'title' as post_title").first } <del> assert_equal false, post.respond_to?(:title), "post should not respond_to?(:body) since invoking it raises exception" <add> assert_not_respond_to post, :title, "post should not respond_to?(:body) since invoking it raises exception" <ide> end <ide> <ide> def test_select_quotes_when_using_from_clause <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_two_scopes_with_includes_should_not_drop_any_include <ide> <ide> def test_dynamic_finder <ide> x = Post.where("author_id = ?", 1) <del> assert x.klass.respond_to?(:find_by_id), "@klass should handle dynamic finders" <add> assert_respond_to x.klass, :find_by_id <ide> end <ide> <ide> def test_multivalue_where <ide> def test_respond_to_dynamic_finders <ide> relation = Topic.all <ide> <ide> ["find_by_title", "find_by_title_and_author_name"].each do |method| <del> assert_respond_to relation, method, "Topic.all should respond to #{method.inspect}" <add> assert_respond_to relation, method <ide> end <ide> end <ide> <ide> def test_respond_to_class_methods_and_scopes <del> assert Topic.all.respond_to?(:by_lifo) <add> assert_respond_to Topic.all, :by_lifo <ide> end <ide> <ide> def test_find_with_readonly_option <ide> def test_preloading_with_associations_and_merges <ide> reader = Reader.create! post_id: post.id, person_id: 1 <ide> comment = Comment.create! post_id: post.id, body: "body" <ide> <del> assert !comment.respond_to?(:readers) <add> assert_not_respond_to comment, :readers <ide> <ide> post_rel = Post.preload(:readers).joins(:readers).where(title: "Uhuu") <ide> result_comment = Comment.joins(:post).merge(post_rel).to_a.first <ide> def test_presence <ide> test "delegations do not leak to other classes" do <ide> Topic.all.by_lifo <ide> assert Topic.all.class.method_defined?(:by_lifo) <del> assert !Post.all.respond_to?(:by_lifo) <add> assert_not_respond_to Post.all, :by_lifo <ide> end <ide> <ide> def test_unscope_with_subquery <ide><path>activerecord/test/cases/scoping/named_scoping_test.rb <ide> def test_method_missing_priority_when_delegating <ide> end <ide> <ide> def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy <del> assert Topic.approved.respond_to?(:limit) <del> assert Topic.approved.respond_to?(:count) <del> assert Topic.approved.respond_to?(:length) <add> assert_respond_to Topic.approved, :limit <add> assert_respond_to Topic.approved, :count <add> assert_respond_to Topic.approved, :length <ide> end <ide> <ide> def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified <ide><path>activesupport/test/concern_test.rb <ide> def test <ide> end <ide> end <ide> @klass.include test_module <del> assert_equal false, Object.respond_to?(:test) <add> assert_not_respond_to Object, :test <ide> Qux.class_eval do <ide> remove_const :ClassMethods <ide> end <ide><path>activesupport/test/configurable_test.rb <ide> class Child < Parent <ide> test "configuration accessors are not available on instance" do <ide> instance = Parent.new <ide> <del> assert !instance.respond_to?(:bar) <del> assert !instance.respond_to?(:bar=) <add> assert_not_respond_to instance, :bar <add> assert_not_respond_to instance, :bar= <ide> <del> assert !instance.respond_to?(:baz) <del> assert !instance.respond_to?(:baz=) <add> assert_not_respond_to instance, :baz <add> assert_not_respond_to instance, :baz= <ide> end <ide> <ide> test "configuration accessors can take a default value" do <ide><path>activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb <ide> def test_should_not_create_instance_writer <ide> assert_respond_to @class, :foo <ide> assert_respond_to @class, :foo= <ide> assert_respond_to @object, :bar <del> assert [email protected]_to?(:bar=) <add> assert_not_respond_to @object, :bar= <ide> end.join <ide> end <ide> <ide> def test_should_not_create_instance_reader <ide> Thread.new do <ide> assert_respond_to @class, :shaq <del> assert [email protected]_to?(:shaq) <add> assert_not_respond_to @object, :shaq <ide> end.join <ide> end <ide> <ide> def test_should_not_create_instance_accessors <ide> Thread.new do <ide> assert_respond_to @class, :camp <del> assert [email protected]_to?(:camp) <del> assert [email protected]_to?(:camp=) <add> assert_not_respond_to @object, :camp <add> assert_not_respond_to @object, :camp= <ide> end.join <ide> end <ide> <ide><path>activesupport/test/core_ext/module/attribute_accessor_test.rb <ide> def test_should_not_create_instance_writer <ide> assert_respond_to @module, :foo <ide> assert_respond_to @module, :foo= <ide> assert_respond_to @object, :bar <del> assert [email protected]_to?(:bar=) <add> assert_not_respond_to @object, :bar= <ide> end <ide> <ide> def test_should_not_create_instance_reader <ide> assert_respond_to @module, :shaq <del> assert [email protected]_to?(:shaq) <add> assert_not_respond_to @object, :shaq <ide> end <ide> <ide> def test_should_not_create_instance_accessors <ide> assert_respond_to @module, :camp <del> assert [email protected]_to?(:camp) <del> assert [email protected]_to?(:camp=) <add> assert_not_respond_to @object, :camp <add> assert_not_respond_to @object, :camp= <ide> end <ide> <ide> def test_should_raise_name_error_if_attribute_name_is_invalid <ide><path>activesupport/test/core_ext/module/concerning_test.rb <ide> def doesnt_clobber; end <ide> end <ide> <ide> def test_using_class_methods_blocks_instead_of_ClassMethods_module <del> assert !Foo.respond_to?(:will_be_orphaned) <del> assert Foo.respond_to?(:hacked_on) <del> assert Foo.respond_to?(:nicer_dsl) <del> assert Foo.respond_to?(:doesnt_clobber) <add> assert_not_respond_to Foo, :will_be_orphaned <add> assert_respond_to Foo, :hacked_on <add> assert_respond_to Foo, :nicer_dsl <add> assert_respond_to Foo, :doesnt_clobber <ide> <ide> # Orphan in Foo::ClassMethods, not Bar::ClassMethods. <ide> assert Foo.const_defined?(:ClassMethods) <ide><path>activesupport/test/core_ext/module/remove_method_test.rb <ide> def test_remove_method_from_an_object <ide> RemoveMethodTests::A.class_eval { <ide> remove_possible_method(:do_something) <ide> } <del> assert !RemoveMethodTests::A.new.respond_to?(:do_something) <add> assert_not_respond_to RemoveMethodTests::A.new, :do_something <ide> end <ide> <ide> def test_remove_singleton_method_from_an_object <ide> RemoveMethodTests::A.class_eval { <ide> remove_possible_singleton_method(:do_something_else) <ide> } <del> assert !RemoveMethodTests::A.respond_to?(:do_something_else) <add> assert_not_respond_to RemoveMethodTests::A, :do_something_else <ide> end <ide> <ide> def test_redefine_method_in_an_object <ide><path>activesupport/test/core_ext/module_test.rb <ide> def test_delegate_missing_to_raises_delegation_error_if_target_nil <ide> end <ide> <ide> def test_delegate_missing_to_affects_respond_to <del> assert DecoratedTester.new(@david).respond_to?(:name) <del> assert_not DecoratedTester.new(@david).respond_to?(:private_name) <del> assert_not DecoratedTester.new(@david).respond_to?(:my_fake_method) <add> assert_respond_to DecoratedTester.new(@david), :name <add> assert_not_respond_to DecoratedTester.new(@david), :private_name <add> assert_not_respond_to DecoratedTester.new(@david), :my_fake_method <ide> <ide> assert DecoratedTester.new(@david).respond_to?(:name, true) <ide> assert_not DecoratedTester.new(@david).respond_to?(:private_name, true) <ide> def initialize(place) <ide> <ide> place = location.new(Somewhere.new("Such street", "Sad city")) <ide> <del> assert_not place.respond_to?(:street) <del> assert_not place.respond_to?(:city) <add> assert_not_respond_to place, :street <add> assert_not_respond_to place, :city <ide> <ide> assert place.respond_to?(:street, true) # Asking for private method <ide> assert place.respond_to?(:city, true) <ide> def initialize(place) <ide> <ide> place = location.new(Somewhere.new("Such street", "Sad city")) <ide> <del> assert_not place.respond_to?(:street) <del> assert_not place.respond_to?(:city) <add> assert_not_respond_to place, :street <add> assert_not_respond_to place, :city <ide> <del> assert_not place.respond_to?(:the_street) <add> assert_not_respond_to place, :the_street <ide> assert place.respond_to?(:the_street, true) <del> assert_not place.respond_to?(:the_city) <add> assert_not_respond_to place, :the_city <ide> assert place.respond_to?(:the_city, true) <ide> end <ide> end <ide><path>activesupport/test/core_ext/object/try_test.rb <ide> def setup <ide> <ide> def test_nonexisting_method <ide> method = :undefined_method <del> assert [email protected]_to?(method) <add> assert_not_respond_to @string, method <ide> assert_nil @string.try(method) <ide> end <ide> <ide> def test_nonexisting_method_with_arguments <ide> method = :undefined_method <del> assert [email protected]_to?(method) <add> assert_not_respond_to @string, method <ide> assert_nil @string.try(method, "llo", "y") <ide> end <ide> <ide> def test_nonexisting_method_bang <ide> method = :undefined_method <del> assert [email protected]_to?(method) <add> assert_not_respond_to @string, method <ide> assert_raise(NoMethodError) { @string.try!(method) } <ide> end <ide> <ide> def test_nonexisting_method_with_arguments_bang <ide> method = :undefined_method <del> assert [email protected]_to?(method) <add> assert_not_respond_to @string, method <ide> assert_raise(NoMethodError) { @string.try!(method, "llo", "y") } <ide> end <ide> <ide><path>activesupport/test/core_ext/time_with_zone_test.rb <ide> def test_in_time_zone <ide> <ide> def test_nil_time_zone <ide> Time.use_zone nil do <del> assert [email protected]_time_zone.respond_to?(:period), "no period method" <del> assert [email protected]_time_zone.respond_to?(:period), "no period method" <add> assert_not_respond_to @t.in_time_zone, :period, "no period method" <add> assert_not_respond_to @dt.in_time_zone, :period, "no period method" <ide> end <ide> end <ide> <ide> def test_in_time_zone <ide> <ide> def test_nil_time_zone <ide> with_tz_default nil do <del> assert [email protected]_time_zone.respond_to?(:period), "no period method" <add> assert_not_respond_to @d.in_time_zone, :period, "no period method" <ide> end <ide> end <ide> <ide> def test_in_time_zone <ide> <ide> def test_nil_time_zone <ide> with_tz_default nil do <del> assert [email protected]_time_zone.respond_to?(:period), "no period method" <del> assert [email protected]_time_zone.respond_to?(:period), "no period method" <del> assert [email protected]_time_zone.respond_to?(:period), "no period method" <add> assert_not_respond_to @s.in_time_zone, :period, "no period method" <add> assert_not_respond_to @u.in_time_zone, :period, "no period method" <add> assert_not_respond_to @z.in_time_zone, :period, "no period method" <ide> end <ide> end <ide> <ide><path>activesupport/test/dependencies_test.rb <ide> def test_unloadable_constants_should_receive_callback <ide> Object.const_set :C, Class.new { def self.before_remove_const; end } <ide> C.unloadable <ide> assert_called(C, :before_remove_const, times: 1) do <del> assert C.respond_to?(:before_remove_const) <add> assert_respond_to C, :before_remove_const <ide> ActiveSupport::Dependencies.clear <ide> assert !defined?(C) <ide> end <ide><path>activesupport/test/multibyte_chars_test.rb <ide> def test_titleize_should_work_on_ascii_characters <ide> end <ide> <ide> def test_respond_to_knows_which_methods_the_proxy_responds_to <del> assert "".mb_chars.respond_to?(:slice) # Defined on Chars <del> assert "".mb_chars.respond_to?(:capitalize!) # Defined on Chars <del> assert "".mb_chars.respond_to?(:gsub) # Defined on String <del> assert !"".mb_chars.respond_to?(:undefined_method) # Not defined <add> assert_respond_to "".mb_chars, :slice # Defined on Chars <add> assert_respond_to "".mb_chars, :capitalize! # Defined on Chars <add> assert_respond_to "".mb_chars, :gsub # Defined on String <add> assert_not_respond_to "".mb_chars, :undefined_method # Not defined <ide> end <ide> <ide> def test_method_works_for_proxyed_methods <ide><path>activesupport/test/ordered_options_test.rb <ide> def test_inheritable_options_inheritable_copy <ide> <ide> def test_introspection <ide> a = ActiveSupport::OrderedOptions.new <del> assert a.respond_to?(:blah) <del> assert a.respond_to?(:blah=) <add> assert_respond_to a, :blah <add> assert_respond_to a, :blah= <ide> assert_equal 42, a.method(:blah=).call(42) <ide> assert_equal 42, a.method(:blah).call <ide> end <ide> <ide> def test_raises_with_bang <ide> a = ActiveSupport::OrderedOptions.new <ide> a[:foo] = :bar <del> assert a.respond_to?(:foo!) <add> assert_respond_to a, :foo! <ide> <ide> assert_nothing_raised { a.foo! } <ide> assert_equal a.foo, a.foo! <ide><path>activesupport/test/tagged_logging_test.rb <ide> def flush(*) <ide> assert_nil logger.formatter <ide> ActiveSupport::TaggedLogging.new(logger) <ide> assert_not_nil logger.formatter <del> assert logger.formatter.respond_to?(:tagged) <add> assert_respond_to logger.formatter, :tagged <ide> end <ide> <ide> test "tagged once" do <ide><path>railties/test/application/configuration/custom_test.rb <ide> def teardown <ide> assert_nil x.i_do_not_exist.zomg <ide> <ide> # test that custom configuration responds to all messages <del> assert_equal true, x.respond_to?(:i_do_not_exist) <add> assert_respond_to x, :i_do_not_exist <ide> assert_kind_of Method, x.method(:i_do_not_exist) <ide> assert_kind_of ActiveSupport::OrderedOptions, x.i_do_not_exist <ide> end <ide><path>railties/test/application/configuration_test.rb <ide> def index <ide> test "respond_to? accepts include_private" do <ide> make_basic_app <ide> <del> assert_not Rails.configuration.respond_to?(:method_missing) <add> assert_not_respond_to Rails.configuration, :method_missing <ide> assert Rails.configuration.respond_to?(:method_missing, true) <ide> end <ide> <ide><path>railties/test/application/console_test.rb <ide> class User <ide> MODEL <ide> <ide> load_environment <del> assert User.new.respond_to?(:name) <add> assert_respond_to User.new, :name <ide> <ide> app_file "app/models/user.rb", <<-MODEL <ide> class User <ide> attr_accessor :name, :age <ide> end <ide> MODEL <ide> <del> assert !User.new.respond_to?(:age) <add> assert_not_respond_to User.new, :age <ide> irb_context.reload!(false) <del> assert User.new.respond_to?(:age) <add> assert_respond_to User.new, :age <ide> end <ide> <ide> def test_access_to_helpers
43
Javascript
Javascript
add error message when nyt api key is missing
f36fa1e0f722526537cba4ad000e2202b32206e8
<ide><path>controllers/api.js <ide> exports.getAviary = function(req, res) { <ide> * New York Times API example. <ide> */ <ide> <del>exports.getNewYorkTimes = function(req, res) { <add>exports.getNewYorkTimes = function(req, res, next) { <ide> var query = querystring.stringify({ 'api-key': secrets.nyt.key, 'list-name': 'young-adult' }); <ide> var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query; <ide> request.get(url, function(error, request, body) { <add> if (request.statusCode === 403) return next(Error('Missing New York Times API Key')); <ide> var bestsellers = JSON.parse(body); <ide> res.render('api/nyt', { <ide> title: 'New York Times API',
1
Text
Text
use test username instead of real
92610f330d6e149f782d9d1cdf106cd629374de4
<ide><path>doc/api/process.md <ide> Use care when dropping privileges: <ide> <ide> ```js <ide> console.log(process.getgroups()); // [ 0 ] <del>process.initgroups('bnoordhuis', 1000); // switch user <add>process.initgroups('nodeuser', 1000); // switch user <ide> console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ] <ide> process.setgid(1000); // drop root gid <ide> console.log(process.getgroups()); // [ 27, 30, 46, 1000 ]
1
Text
Text
add lines 45-57 (infinite loop) to the article
d03e742a85c612d14371b0b6ef11269122e26437
<ide><path>guide/english/c/for/index.md <ide> main () <ide> return 0; <ide> } <ide> ``` <del>## Output: <add> <add>Output: <ide> ```shell <ide> * <ide> *** <ide> ***** <ide> ******* <ide> ********* <add>``` <ide> <del>`` <del> <del> <del> <add>## Syntax of For Infinite loop <ide> <add>An infinite loop occurs when the condition will never be met, due to some inherent characteristic of the loop. An infinite loop also called an endless loop, and it is a piece of coding that lacks a functional exit so that it repeats indefinitely. <ide> <del>## Syntax of For infinite loop <add>### Examples: <ide> <del>```c <add>```C <ide> for ( ; ; ) { <ide> statement(s); <ide> } <ide> ``` <ide> <del>An infinite loop occurs when the condition will never be met, due to some inherent characteristic of the loop. An infinite loop also called an endless loop, and it is a piece of coding that lacks a functional exit so that it repeats indefinitely. <add>```C <add>#include <stdio.h> <ide> <add>int main () { <add> for (int i = 0; i < 5; i--) { <add> printf("%d \n", i); <add> } <add>} <add>``` <ide> <ide> ### Warning! <ide>
1
Javascript
Javascript
reject windowbits=8 when mode=gzip
d8a380e13665ef06ffbfa220cb3a7aaaaa17c9fd
<ide><path>lib/zlib.js <ide> function Zlib(opts, mode) { <ide> mode === UNZIP)) { <ide> windowBits = 0; <ide> } else { <add> // `{ windowBits: 8 }` is valid for deflate but not gzip. <add> const min = Z_MIN_WINDOWBITS + (mode === GZIP ? 1 : 0); <ide> windowBits = checkRangesOrGetDefault( <ide> opts.windowBits, 'options.windowBits', <del> Z_MIN_WINDOWBITS, Z_MAX_WINDOWBITS, Z_DEFAULT_WINDOWBITS); <add> min, Z_MAX_WINDOWBITS, Z_DEFAULT_WINDOWBITS); <ide> } <ide> <ide> level = checkRangesOrGetDefault( <ide><path>test/parallel/test-zlib-failed-init.js <ide> assert.throws( <ide> code: 'ERR_OUT_OF_RANGE', <ide> name: 'RangeError', <ide> message: 'The value of "options.windowBits" is out of range. It must ' + <del> 'be >= 8 and <= 15. Received 0' <add> 'be >= 9 and <= 15. Received 0' <ide> } <ide> ); <ide> <ide><path>test/parallel/test-zlib-zero-windowBits.js <ide> const zlib = require('zlib'); <ide> code: 'ERR_OUT_OF_RANGE', <ide> name: 'RangeError', <ide> message: 'The value of "options.windowBits" is out of range. ' + <del> 'It must be >= 8 and <= 15. Received 0' <add> 'It must be >= 9 and <= 15. Received 0' <ide> }); <ide> } <ide><path>test/parallel/test-zlib.js <ide> const fixtures = require('../common/fixtures'); <ide> <ide> // Should not segfault. <ide> assert.throws(() => zlib.gzipSync(Buffer.alloc(0), { windowBits: 8 }), { <del> code: 'ERR_ZLIB_INITIALIZATION_FAILED', <del> name: 'Error', <del> message: 'Initialization failed', <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError', <add> message: 'The value of "options.windowBits" is out of range. ' + <add> 'It must be >= 9 and <= 15. Received 8', <ide> }); <ide> <ide> let zlibPairs = [
4
Python
Python
use utcfromtimestamp in test
adc0fbd0d321f28443f98de029d53e1357d80e56
<ide><path>t/unit/app/test_beat.py <ide> def test_ticks_microseconds(self): <ide> scheduler = mScheduler(app=self.app) <ide> <ide> now_ts = 1514797200.2 <del> now = datetime.fromtimestamp(now_ts) <add> now = datetime.utcfromtimestamp(now_ts) <ide> schedule_half = schedule(timedelta(seconds=0.5), nowfun=lambda: now) <ide> scheduler.add(name='half_second_schedule', schedule=schedule_half) <ide>
1
PHP
PHP
fix failing test
9a67a7070383abe3d746c9f71e386a10e9548863
<ide><path>lib/Cake/Test/Case/Model/ModelIntegrationTest.php <ide> public function testPkInHabtmLinkModel() { <ide> public function testDynamicBehaviorAttachment() { <ide> $this->loadFixtures('Apple', 'Sample', 'Author'); <ide> $TestModel = new Apple(); <del> $this->assertEquals($TestModel->Behaviors->attached(), array()); <add> $this->assertEquals(array(), $TestModel->Behaviors->attached()); <ide> <ide> $TestModel->Behaviors->attach('Tree', array('left' => 'left_field', 'right' => 'right_field')); <ide> $this->assertTrue(is_object($TestModel->Behaviors->Tree)); <del> $this->assertEquals($TestModel->Behaviors->attached(), array('Tree')); <add> $this->assertEquals(array('Tree'), $TestModel->Behaviors->attached()); <ide> <ide> $expected = array( <ide> 'parent' => 'parent_id', <ide> public function testDynamicBehaviorAttachment() { <ide> '__parentChange' => false, <ide> 'recursive' => -1 <ide> ); <add> $this->assertEquals($expected, $TestModel->Behaviors->Tree->settings['Apple']); <ide> <del> $this->assertEquals($TestModel->Behaviors->Tree->settings['Apple'], $expected); <del> <del> $expected['enabled'] = false; <ide> $TestModel->Behaviors->attach('Tree', array('enabled' => false)); <del> $this->assertEquals($TestModel->Behaviors->Tree->settings['Apple'], $expected); <del> $this->assertEquals($TestModel->Behaviors->attached(), array('Tree')); <add> $this->assertEquals($expected, $TestModel->Behaviors->Tree->settings['Apple']); <add> $this->assertEquals(array('Tree'), $TestModel->Behaviors->attached()); <ide> <ide> $TestModel->Behaviors->detach('Tree'); <del> $this->assertEquals($TestModel->Behaviors->attached(), array()); <add> $this->assertEquals(array(), $TestModel->Behaviors->attached()); <ide> $this->assertFalse(isset($TestModel->Behaviors->Tree)); <ide> } <ide>
1
Python
Python
remove dumbass unneeded test
09e4ee7ae332326e77b23bac1539d31e582419e9
<ide><path>rest_framework/tests/status.py <del>"""Tests for the status module""" <del>from __future__ import unicode_literals <del>from django.test import TestCase <del>from rest_framework import status <del> <del> <del>class TestStatus(TestCase): <del> """Simple sanity test to check the status module""" <del> <del> def test_status(self): <del> """Ensure the status module is present and correct.""" <del> self.assertEqual(200, status.HTTP_200_OK) <del> self.assertEqual(404, status.HTTP_404_NOT_FOUND)
1
PHP
PHP
remove double check of hidden relations
e6dbdfbe35d299447c1a1d01359e568a282c1503
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function relationsToArray() <ide> { <ide> $attributes = []; <ide> <del> $hidden = $this->getHidden(); <del> <ide> foreach ($this->getArrayableRelations() as $key => $value) { <del> if (in_array($key, $hidden)) { <del> continue; <del> } <ide> <ide> // If the values implements the Arrayable interface we can just call this <ide> // toArray method on the instances which will convert both models and
1
Ruby
Ruby
remove safe navigation operator
8b14738a88da598558346ec7de557401622f4ef5
<ide><path>Library/Homebrew/utils/ast.rb <ide> def include_runtime_cpu_detection? <ide> return false if install_node.blank? <ide> <ide> install_node.each_node.any? do |node| <del> node&.receiver&.const_name == "ENV" && node&.method_name == :runtime_cpu_detection <add> node.send_type? && node.receiver.const_name == "ENV" && node.method_name == :runtime_cpu_detection <ide> end <ide> end <ide>
1
Ruby
Ruby
adjust `audit` spec
ffba81f6770769adf139df65bb1985bfdf2e3352
<ide><path>Library/Homebrew/test/cask/audit_spec.rb <ide> def tmp_cask(name, text) <ide> end <ide> end <ide> <del> context "when doing the audit" do <add> context "when doing an offline audit" do <add> let(:online) { false } <add> <add> it "does not evaluate the block" do <add> expect(run).not_to pass <add> end <add> end <add> <add> context "when doing and online audit" do <add> let(:online) { true } <add> <ide> it "evaluates the block" do <ide> expect(run).to fail_with(/Boom/) <ide> end
1
Javascript
Javascript
fix typo in comment
976d6a9ebdf4d3bb6b3f368b65698222911c2586
<ide><path>test/parallel/test-fs-options-immutable.js <ide> if (common.canCreateSymLink()) { <ide> fs.appendFile(fileName, 'ABCD', options, common.mustCall(errHandler)); <ide> } <ide> <del>if (!common.isIBMi) { // IBMi does not suppport fs.watch() <add>if (!common.isIBMi) { // IBMi does not support fs.watch() <ide> const watch = fs.watch(__filename, options, common.mustNotCall()); <ide> watch.close(); <ide> }
1
Python
Python
resolve merge conflicts
4b2537521ef067d919d8faf56dea75855c47e37c
<ide><path>keras/utils/text_dataset_test.py <ide> def _prepare_directory( <ide> for path in class_paths: <ide> os.mkdir(os.path.join(temp_dir, path)) <ide> paths += class_paths <del> <add> <ide> for i in range(count): <ide> path = paths[i % len(paths)] <ide> filename = os.path.join(path, f"text_{i}.txt") <ide> def test_text_dataset_from_directory_standalone(self): <ide> for i in range(3): <ide> filename = f"text_{i}.txt" <ide> with open(os.path.join(directory, filename), "w") as f: <del> text = "".join( <del> [random.choice(string.printable) for _ in range(20)] <del> ) <add> text = "".join([random.choice(string.printable) for _ in range(20)]) <ide> f.write(text) <del> <add> <ide> dataset = text_dataset.text_dataset_from_directory( <ide> directory, batch_size=5, label_mode=None, max_length=10 <ide> )
1
Javascript
Javascript
fix #85 (#97)
e763dc731b054af99e35d2751e71a6569f5ac812
<ide><path>server/build/webpack.js <ide> export default async function createCompiler (dir, { hotReload = false } = {}) { <ide> const nodeModulesDir = join(__dirname, '..', '..', '..', 'node_modules') <ide> <ide> const plugins = [ <add> new webpack.DefinePlugin({ <add> 'process.env.NODE_ENV': JSON.stringify('production') <add> }), <ide> new WriteFilePlugin({ <ide> exitOnErrors: false, <ide> log: false,
1
Java
Java
kill bridge initialization in ondestroy
77ad9459f5ab6eae88f6e0e0e9bf69de7a9be48a
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerImpl.java <ide> /* should only be accessed from main thread (UI thread) */ <ide> private final List<ReactRootView> mAttachedRootViews = new ArrayList<>(); <ide> private LifecycleState mLifecycleState; <del> private boolean mIsContextInitAsyncTaskRunning; <ide> private @Nullable ReactContextInitParams mPendingReactContextInitParams; <add> private @Nullable ReactContextInitAsyncTask mReactContextInitAsyncTask; <ide> <ide> /* accessed from any thread */ <ide> private @Nullable String mJSBundleFile; /* path to JS bundle on file system */ <ide> protected void onPostExecute(Result<ReactApplicationContext> result) { <ide> } catch (Exception e) { <ide> mDevSupportManager.handleException(e); <ide> } finally { <del> mIsContextInitAsyncTaskRunning = false; <add> mReactContextInitAsyncTask = null; <ide> } <ide> <ide> // Handle enqueued request to re-initialize react context. <ide> protected void onPostExecute(Result<ReactApplicationContext> result) { <ide> mPendingReactContextInitParams = null; <ide> } <ide> } <add> <add> @Override <add> protected void onCancelled(Result<ReactApplicationContext> reactApplicationContextResult) { <add> try { <add> mMemoryPressureRouter.destroy(reactApplicationContextResult.get()); <add> } catch (Exception e) { <add> FLog.w(ReactConstants.TAG, "Caught exception after cancelling react context init", e); <add> } finally { <add> mReactContextInitAsyncTask = null; <add> } <add> } <ide> } <ide> <ide> private static class Result<T> { <ide> public void onResume(Activity activity, DefaultHardwareBackBtnHandler defaultBac <ide> public void onDestroy() { <ide> UiThreadUtil.assertOnUiThread(); <ide> <add> if (mReactContextInitAsyncTask != null) { <add> mReactContextInitAsyncTask.cancel(true); <add> } <add> <ide> mMemoryPressureRouter.destroy(mApplicationContext); <ide> if (mUseDeveloperSupport) { <ide> mDevSupportManager.setDevSupportEnabled(false); <ide> public void attachMeasuredRootView(ReactRootView rootView) { <ide> <ide> // If react context is being created in the background, JS application will be started <ide> // automatically when creation completes, as root view is part of the attached root view list. <del> if (!mIsContextInitAsyncTaskRunning && mCurrentReactContext != null) { <add> if (mReactContextInitAsyncTask == null && mCurrentReactContext != null) { <ide> attachMeasuredRootViewToInstance(rootView, mCurrentReactContext.getCatalystInstance()); <ide> } <ide> } <ide> private void recreateReactContextInBackground( <ide> <ide> ReactContextInitParams initParams = <ide> new ReactContextInitParams(jsExecutorFactory, jsBundleLoader); <del> if (!mIsContextInitAsyncTaskRunning) { <add> if (mReactContextInitAsyncTask == null) { <ide> // No background task to create react context is currently running, create and execute one. <del> ReactContextInitAsyncTask initTask = new ReactContextInitAsyncTask(); <del> initTask.execute(initParams); <del> mIsContextInitAsyncTaskRunning = true; <add> mReactContextInitAsyncTask = new ReactContextInitAsyncTask(); <add> mReactContextInitAsyncTask.execute(initParams); <ide> } else { <ide> // Background task is currently running, queue up most recent init params to recreate context <ide> // once task completes.
1
Java
Java
use final keyword in messageheaders
c6c55550342e47454468c5c26ae9777cd687fee4
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java <ide> public final class MessageHeaders implements Map<String, Object>, Serializable { <ide> <ide> private static volatile IdGenerator idGenerator = null; <ide> <del> private static volatile IdGenerator defaultIdGenerator = new AlternativeJdkIdGenerator(); <add> private static final IdGenerator defaultIdGenerator = new AlternativeJdkIdGenerator(); <ide> <ide> /** <ide> * The key for the Message ID. This is an automatically generated UUID and <ide> public final class MessageHeaders implements Map<String, Object>, Serializable { <ide> <ide> public MessageHeaders(Map<String, Object> headers) { <ide> this.headers = (headers != null) ? new HashMap<String, Object>(headers) : new HashMap<String, Object>(); <del> IdGenerator generatorToUse = (idGenerator != null) ? idGenerator : defaultIdGenerator; <del> this.headers.put(ID, generatorToUse.generateId()); <add> this.headers.put(ID, ((idGenerator != null) ? idGenerator : defaultIdGenerator).generateId()); <ide> this.headers.put(TIMESTAMP, new Long(System.currentTimeMillis())); <ide> } <ide>
1
Go
Go
improve error message for invalid ndots number
b3067060623c6774a9936a2a87a3086798bdb250
<ide><path>libnetwork/sandbox_dns_unix.go <ide> dnsOpt: <ide> return fmt.Errorf("invalid ndots option %v", option) <ide> } <ide> if num, err := strconv.Atoi(parts[1]); err != nil { <del> return fmt.Errorf("invalid number for ndots option %v", option) <add> return fmt.Errorf("invalid number for ndots option: %v", parts[1]) <ide> } else if num >= 0 { <ide> // if the user sets ndots, use the user setting <ide> sb.ndotsSet = true <ide><path>libnetwork/service_common_test.go <ide> func TestDNSOptions(t *testing.T) { <ide> dnsOptionsList = resolvconf.GetOptions(currRC.Content) <ide> assert.Equal(t, 1, len(dnsOptionsList)) <ide> assert.Equal(t, "ndots:0", dnsOptionsList[0]) <add> <add> sb2.(*sandbox).config.dnsOptionsList = []string{"ndots:foobar"} <add> err = sb2.(*sandbox).setupDNS() <add> require.NoError(t, err) <add> err = sb2.(*sandbox).rebuildDNS() <add> require.EqualError(t, err, "invalid number for ndots option: foobar") <ide> }
2
Text
Text
fix gradle spec in readme
cf5a20c59ef1533004d205d82cb679fc2f0b63cf
<ide><path>language-adaptors/rxjava-clojure/README.md <ide> Example for Leiningen: <ide> and for Gradle: <ide> <ide> ```groovy <del>compile 'com.netflix.rx:rxjava-clojure:x.y.z' <add>compile 'com.netflix.rxjava:rxjava-clojure:x.y.z' <ide> ``` <ide> <ide> and for Maven:
1
Ruby
Ruby
remove leading whitespace from the xml under test
76bfda8f7291dc73b97fb6d3a0d6f8027169fb75
<ide><path>activesupport/test/xml_mini/xml_mini_engine_test.rb <ide> def test_file_from_xml <ide> <ide> def test_exception_thrown_on_expansion_attack <ide> assert_raise expansion_attack_error do <del> Hash.from_xml(<<-eoxml) <add> Hash.from_xml(<<~eoxml) <ide> <?xml version="1.0" encoding="UTF-8"?> <ide> <!DOCTYPE member [ <ide> <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
1
Python
Python
fix c/p typo from my experiment code
5938f31fa7aa28cdff662f79c7c038cab21bb370
<ide><path>pytorch_pretrained_bert/modeling_gpt2.py <ide> def forward(self, input_ids, position_ids=None, token_type_ids=None, lm_labels=N <ide> if lm_labels is not None: <ide> # Shift so that tokens < n predict n <ide> shift_logits = lm_logits[:, :-1] <del> shift_labels = torch_batch[:, 1:] <add> shift_labels = lm_labels[:, 1:] <ide> <ide> # In tensorflow, it's [batch, d_0, d_1, ..., d_{r-1}, num_classes] <ide> # in pytorch, it's [batch, num_classes, d_0, d_1, ..., d_{r-1}]
1
Ruby
Ruby
handle references to too old macos in formulae
b43f17b2d0503dbec503e5a4d53441ed2eac6add
<ide><path>Library/Homebrew/formula_versions.rb <ide> def bottle_version_map(branch) <ide> versions_seen = (map.keys + [f.pkg_version]).uniq.length <ide> end <ide> return map if versions_seen > MAX_VERSIONS_DEPTH <add> rescue MacOSVersionError => e <add> odebug "#{e} in #{name} at revision #{rev}" if debug? <add> break <ide> end <ide> map <ide> end
1
Javascript
Javascript
correct broken test
f8091004064c22aac811eb890393c919192d07cb
<ide><path>tools/lint/lint.test.js <ide> describe('markdown linter', () => { <ide> function callback() { <ide> const expected = <ide> // eslint-disable-next-line max-len <del> 'fixtures/badYML.md: 19: yaml-linter YAML code blocks must be valid [bad indentation of a mapping entry at line 3, column 17:\n testString: testString\n ^] [Context: "```yml"]'; <add> 'badYML.md: 19: yaml-linter YAML code blocks should be valid [bad indentation of a mapping entry at line 3, column 17:\n testString: testString\n ^] [Context: "```yml"]'; <ide> expect(console.log.mock.calls.length).toBe(1); <ide> expect(console.log.mock.calls[0][0]).toEqual( <ide> expect.stringContaining(expected)
1
Ruby
Ruby
fix compiler selection tests on xcode 4.2+
1fc97a81ec279d7827dcec7eabf6c1c28fe1c6be
<ide><path>Library/Homebrew/test/test_compilers.rb <ide> def test_no_compiler_failures <ide> assert !(f.fails_with? :clang) <ide> assert !(f.fails_with? :llvm) <ide> assert case MacOS.gcc_42_build_version <del> when 0 then f.fails_with? :gcc <add> when nil then f.fails_with? :gcc <ide> else !(f.fails_with? :gcc) <ide> end <ide> <ide> def test_even_more_mixed_compiler_failures <ide> assert f.fails_with? :clang <ide> assert f.fails_with? :llvm <ide> assert case MacOS.gcc_42_build_version <del> when 0 then f.fails_with? :gcc <add> when nil then f.fails_with? :gcc <ide> else !(f.fails_with? :gcc) <ide> end <ide>
1
PHP
PHP
fix string[] types in docblocks
59d4f91809751c413f1301ef0a07a5bded32b239
<ide><path>src/Utility/Hash.php <ide> class Hash <ide> * <ide> * @param array|\ArrayAccess $data Array of data or object implementing <ide> * \ArrayAccess interface to operate on. <del> * @param string|int|array|null $path The path being searched for. Either a dot <add> * @param string|int|string[]|null $path The path being searched for. Either a dot <ide> * separated string, or an array of path segments. <ide> * @param mixed $default The return value when the path does not exist <ide> * @throws \InvalidArgumentException <ide> public static function insert(array $data, string $path, $values = null): array <ide> * <ide> * @param string $op The operation to do. <ide> * @param array $data The data to operate on. <del> * @param array $path The path to work on. <add> * @param string[] $path The path to work on. <ide> * @param mixed $values The values to insert when doing inserts. <ide> * @return array data. <ide> */ <ide> public static function remove(array $data, string $path): array <ide> * following the path specified in `$groupPath`. <ide> * <ide> * @param array $data Array from where to extract keys and values <del> * @param string|array $keyPath A dot-separated string. <del> * @param string|array|null $valuePath A dot-separated string. <add> * @param string|string[] $keyPath A dot-separated string. <add> * @param string|string[]|null $valuePath A dot-separated string. <ide> * @param string|null $groupPath A dot-separated string. <ide> * @return array Combined array <ide> * @link https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::combine <ide> public static function combine(array $data, $keyPath, $valuePath = null, ?string <ide> * The `$format` string can use any format options that `vsprintf()` and `sprintf()` do. <ide> * <ide> * @param array $data Source array from which to extract the data <del> * @param array $paths An array containing one or more Hash::extract()-style key paths <add> * @param string[] $paths An array containing one or more Hash::extract()-style key paths <ide> * @param string $format Format string into which values will be inserted, see sprintf() <ide> * @return string[]|null An array of strings extracted from `$path` and formatted with `$format` <ide> * @link https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::format <ide><path>src/View/Form/EntityContext.php <ide> protected function _schemaDefault(array $parts) <ide> * primary key column is guessed out of the provided $path array <ide> * <ide> * @param mixed $values The list from which to extract primary keys from <del> * @param array $path Each one of the parts in a path for a field name <add> * @param string[] $path Each one of the parts in a path for a field name <ide> * @return array|null <ide> */ <ide> protected function _extractMultiple($values, array $path): ?array
2
Python
Python
improve rewrite state_dict missing _metadata
fd8136fa755a3c59e459e1168014f2bf2fca721a
<ide><path>src/transformers/modeling_utils.py <ide> def save_pretrained( <ide> <ide> # Handle the case where some state_dict keys shouldn't be saved <ide> if self._keys_to_ignore_on_save is not None: <del> state_dict = {k: v for k, v in state_dict.items() if k not in self._keys_to_ignore_on_save} <add> for ignore_key in self._keys_to_ignore_on_save: <add> del state_dict[ignore_key] <ide> <ide> # If we save using the predefined names, we can load using `from_pretrained` <ide> output_model_file = os.path.join(save_directory, WEIGHTS_NAME)
1
Ruby
Ruby
remove old asset_path from rails config
7dba1599d9092a8362956a3fab23b2c60eedea63
<ide><path>actionmailer/lib/action_mailer/railtie.rb <ide> class Railtie < Rails::Railtie # :nodoc: <ide> options.queue ||= app.queue <ide> <ide> # make sure readers methods get compiled <del> options.asset_path ||= app.config.asset_path <ide> options.asset_host ||= app.config.asset_host <ide> options.relative_url_root ||= app.config.relative_url_root <ide> <ide><path>railties/lib/rails/application/configuration.rb <ide> module Rails <ide> class Application <ide> class Configuration < ::Rails::Engine::Configuration <del> attr_accessor :asset_host, :asset_path, :assets, :autoflush_log, <add> attr_accessor :asset_host, :assets, :autoflush_log, <ide> :cache_classes, :cache_store, :consider_all_requests_local, :console, <ide> :eager_load, :exceptions_app, :file_watcher, :filter_parameters, <ide> :force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags, <ide> def initialize(*) <ide> @assets.logger = nil <ide> end <ide> <del> def compiled_asset_path <del> "/" <del> end <del> <ide> def encoding=(value) <ide> @encoding = value <ide> silence_warnings do <ide><path>railties/test/application/configuration_test.rb <ide> def teardown <ide> assert AppTemplate::Application, AppTemplate::Application.config.eager_load_namespaces <ide> end <ide> <del> test "asset_path defaults to nil for application" do <del> require "#{app_path}/config/environment" <del> assert_equal nil, AppTemplate::Application.config.asset_path <del> end <del> <ide> test "the application can be eager loaded even when there are no frameworks" do <ide> FileUtils.rm_rf("#{app_path}/config/environments") <ide> add_to_config <<-RUBY <ide> def index <ide> end <ide> end <ide> <del> test "config.asset_path is not passed through env" do <del> make_basic_app do |app| <del> app.config.asset_path = "/omg%s" <del> end <del> <del> class ::OmgController < ActionController::Base <del> def index <del> render :inline => "<%= image_path('foo.jpg') %>" <del> end <del> end <del> <del> get "/" <del> assert_equal "/omg/images/foo.jpg", last_response.body <del> end <del> <ide> test "config.action_view.cache_template_loading with cache_classes default" do <ide> add_to_config "config.cache_classes = true" <ide> require "#{app_path}/config/environment"
3
Javascript
Javascript
resolve resource in contextreplacementplugin
af0be8de0795e8929234922ef70d86698103822c
<ide><path>lib/ContextReplacementPlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <add>var path = require("path"); <add> <ide> function ContextReplacementPlugin(resourceRegExp, newContentResource, newContentRecursive, newContentRegExp) { <ide> this.resourceRegExp = resourceRegExp; <ide> if(typeof newContentResource !== "string") { <ide> ContextReplacementPlugin.prototype.apply = function(compiler) { <ide> if(!result) return callback(); <ide> if(resourceRegExp.test(result.resource)) { <ide> if(typeof newContentResource !== "undefined") <del> result.resource = newContentResource; <add> result.resource = path.resolve(result.resource, newContentResource); <ide> if(typeof newContentRecursive !== "undefined") <ide> result.recursive = newContentRecursive; <ide> if(typeof newContentRegExp !== "undefined") <ide><path>test/configCases/context-replacement/a/webpack.config.js <ide> var webpack = require("../../../../"); <ide> <ide> module.exports = { <ide> plugins: [ <del> new webpack.ContextReplacementPlugin(/context-replacement.a$/, path.join(__dirname, "new-context"), true, /^replaced$/) <add> new webpack.ContextReplacementPlugin(/context-replacement.a$/, "new-context", true, /^replaced$/) <ide> ] <ide> }; <ide>\ No newline at end of file
2
Javascript
Javascript
fix animated type
851644cfc23728f72fe638b57f03c596803fef7c
<ide><path>Libraries/Animated/src/Animated.js <ide> 'use strict'; <ide> <ide> import Platform from '../../Utilities/Platform'; <del>const View = require('../../Components/View/View'); <del>const React = require('react'); <del>import type {AnimatedComponentType} from './createAnimatedComponent'; <add>import typeof AnimatedFlatList from './components/AnimatedFlatList'; <add>import typeof AnimatedImage from './components/AnimatedImage'; <add>import typeof AnimatedScrollView from './components/AnimatedScrollView'; <add>import typeof AnimatedSectionList from './components/AnimatedSectionList'; <add>import typeof AnimatedText from './components/AnimatedText'; <add>import typeof AnimatedView from './components/AnimatedView'; <ide> <ide> const AnimatedMock = require('./AnimatedMock'); <ide> const AnimatedImplementation = require('./AnimatedImplementation'); <ide> const Animated = ((Platform.isTesting || <ide> : AnimatedImplementation): typeof AnimatedMock); <ide> <ide> module.exports = { <del> get FlatList(): any { <add> get FlatList(): AnimatedFlatList { <ide> return require('./components/AnimatedFlatList'); <ide> }, <del> get Image(): any { <add> get Image(): AnimatedImage { <ide> return require('./components/AnimatedImage'); <ide> }, <del> get ScrollView(): any { <add> get ScrollView(): AnimatedScrollView { <ide> return require('./components/AnimatedScrollView'); <ide> }, <del> get SectionList(): any { <add> get SectionList(): AnimatedSectionList { <ide> return require('./components/AnimatedSectionList'); <ide> }, <del> get Text(): any { <add> get Text(): AnimatedText { <ide> return require('./components/AnimatedText'); <ide> }, <del> get View(): AnimatedComponentType< <del> React.ElementConfig<typeof View>, <del> React.ElementRef<typeof View>, <del> > { <add> get View(): AnimatedView { <ide> return require('./components/AnimatedView'); <ide> }, <ide> ...Animated, <ide><path>RNTester/js/examples/FlatList/FlatListExample.js <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> }; <ide> <ide> _onChangeScrollToIndex = text => { <del> this._listRef <del> .getNode() <del> .scrollToIndex({viewPosition: 0.5, index: Number(text)}); <add> this._listRef.scrollToIndex({viewPosition: 0.5, index: Number(text)}); <ide> }; <ide> <ide> _scrollPos = new Animated.Value(0); <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> ); <ide> <ide> componentDidUpdate() { <del> this._listRef.getNode().recordInteraction(); // e.g. flipping logViewable switch <add> this._listRef.recordInteraction(); // e.g. flipping logViewable switch <ide> } <ide> <ide> render(): React.Node { <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> } <ide> }; <ide> _pressItem = (key: string) => { <del> this._listRef.getNode().recordInteraction(); <add> this._listRef && this._listRef.recordInteraction(); <ide> pressItem(this, key); <ide> }; <ide> _listRef: React.ElementRef<typeof Animated.FlatList>; <ide><path>RNTester/js/examples/SectionList/SectionListExample.js <ide> class SectionListExample extends React.PureComponent<{...}, $FlowFixMeState> { <ide> {useNativeDriver: true}, <ide> ); <ide> <del> _sectionListRef: React.ElementRef<typeof Animated.SectionList>; <add> _sectionListRef: ?React.ElementRef<typeof Animated.SectionList> = null; <ide> _captureRef = ref => { <ide> this._sectionListRef = ref; <ide> }; <ide> <ide> _scrollToLocation(sectionIndex: number, itemIndex: number) { <del> this._sectionListRef.getNode().scrollToLocation({sectionIndex, itemIndex}); <add> this._sectionListRef && <add> this._sectionListRef.scrollToLocation({sectionIndex, itemIndex}); <ide> } <ide> <ide> render(): React.Node {
3
Javascript
Javascript
add length validation to fs.truncate()
751a42a30f35c2d04cfb80ce2b1ebec5d040a7e1
<ide><path>lib/fs.js <ide> const { <ide> const { <ide> isUint32, <ide> validateAndMaskMode, <add> validateInteger, <ide> validateInt32, <ide> validateUint32 <ide> } = require('internal/validators'); <ide> function truncate(path, len, callback) { <ide> len = 0; <ide> } <ide> <add> validateInteger(len, 'len'); <ide> callback = maybeCallback(callback); <ide> fs.open(path, 'r+', function(er, fd) { <ide> if (er) return callback(er); <ide><path>test/parallel/test-fs-truncate.js <ide> function testFtruncate(cb) { <ide> process.on('exit', () => fs.closeSync(fd)); <ide> <ide> ['', false, null, {}, []].forEach((input) => { <add> assert.throws( <add> () => fs.truncate(file5, input, common.mustNotCall()), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> message: 'The "len" argument must be of type number. ' + <add> `Received type ${typeof input}` <add> } <add> ); <add> <ide> assert.throws( <ide> () => fs.ftruncate(fd, input), <ide> { <ide> function testFtruncate(cb) { <ide> }); <ide> <ide> [-1.5, 1.5].forEach((input) => { <add> assert.throws( <add> () => fs.truncate(file5, input), <add> { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "len" is out of range. It must be ' + <add> `an integer. Received ${input}` <add> } <add> ); <add> <ide> assert.throws( <ide> () => fs.ftruncate(fd, input), <ide> {
2
Python
Python
resolve path to be extra sure
6831161bfa776273e0247f6241fea5f05f40623e
<ide><path>spacy/cli/project/assets.py <ide> def project_assets(project_dir: Path) -> None: <ide> msg.warn(f"No assets specified in {PROJECT_FILE}", exits=0) <ide> msg.info(f"Fetching {len(assets)} asset(s)") <ide> for asset in assets: <del> dest = project_dir / asset["dest"] <add> dest = (project_dir / asset["dest"]).resolve() <ide> checksum = asset.get("checksum") <ide> if "git" in asset: <ide> if dest.exists():
1
Ruby
Ruby
add stored procedure test in mysql2
d39b6f77fc75790b1b2b3c5201bb037645d01483
<ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> def disconnect! <ide> # Returns an array of arrays containing the field values. <ide> # Order is the same as that returned by +columns+. <ide> def select_rows(sql, name = nil, binds = []) <del> execute(sql, name).to_a <add> result = execute(sql, name) <add> @connection.next_result while @connection.more_results? <add> result.to_a <ide> end <ide> <ide> # Executes the SQL statement in the context of this connection. <ide> def execute(sql, name = nil) <ide> <ide> def exec_query(sql, name = 'SQL', binds = []) <ide> result = execute(sql, name) <add> @connection.next_result while @connection.more_results? <ide> ActiveRecord::Result.new(result.fields, result.to_a) <ide> end <ide> <ide><path>activerecord/test/cases/adapters/mysql/connection_test.rb <ide> def test_exec_typecasts_bind_vals <ide> end <ide> end <ide> <del> # Test that MySQL allows multiple results for stored procedures <del> if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS) <del> def test_multi_results <del> rows = ActiveRecord::Base.connection.select_rows('CALL ten();') <del> assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" <del> assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'" <del> end <del> end <del> <ide> def test_mysql_connection_collation_is_configured <ide> assert_equal 'utf8_unicode_ci', @connection.show_variable('collation_connection') <ide> assert_equal 'utf8_general_ci', ARUnit2Model.connection.show_variable('collation_connection') <ide><path>activerecord/test/cases/adapters/mysql/sp_test.rb <ide> require "cases/helper" <ide> require 'models/topic' <add>require 'models/reply' <ide> <del>class StoredProcedureTest < ActiveRecord::MysqlTestCase <add>class MysqlStoredProcedureTest < ActiveRecord::MysqlTestCase <ide> fixtures :topics <ide> <add> def setup <add> @connection = ActiveRecord::Base.connection <add> end <add> <ide> # Test that MySQL allows multiple results for stored procedures <del> if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS) <add> # <add> # In MySQL 5.6, CLIENT_MULTI_RESULTS is enabled by default. <add> # http://dev.mysql.com/doc/refman/5.6/en/call.html <add> if ActiveRecord::Base.connection.version >= '5.6.0' || Mysql.const_defined?(:CLIENT_MULTI_RESULTS) <add> def test_multi_results <add> rows = @connection.select_rows('CALL ten();') <add> assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" <add> assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'" <add> end <add> <ide> def test_multi_results_from_find_by_sql <del> topics = Topic.find_by_sql 'CALL topics();' <del> assert_equal 1, topics.size <del> assert ActiveRecord::Base.connection.active?, "Bad connection use by 'MysqlAdapter.select'" <add> topics = Topic.find_by_sql 'CALL topics(3);' <add> assert_equal 3, topics.size <add> assert @connection.active?, "Bad connection use by 'MysqlAdapter.select'" <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/adapters/mysql2/sp_test.rb <add>require "cases/helper" <add>require 'models/topic' <add>require 'models/reply' <add> <add>class Mysql2StoredProcedureTest < ActiveRecord::Mysql2TestCase <add> fixtures :topics <add> <add> def setup <add> @connection = ActiveRecord::Base.connection <add> end <add> <add> # Test that MySQL allows multiple results for stored procedures <add> # <add> # In MySQL 5.6, CLIENT_MULTI_RESULTS is enabled by default. <add> # http://dev.mysql.com/doc/refman/5.6/en/call.html <add> if ActiveRecord::Base.connection.version >= '5.6.0' <add> def test_multi_results <add> rows = @connection.select_rows('CALL ten();') <add> assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" <add> assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select_rows'" <add> end <add> <add> def test_multi_results_from_find_by_sql <add> topics = Topic.find_by_sql 'CALL topics(3);' <add> assert_equal 3, topics.size <add> assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select'" <add> end <add> end <add>end <ide><path>activerecord/test/schema/mysql2_specific_schema.rb <ide> BEGIN <ide> select 10; <ide> END <add>SQL <add> <add> ActiveRecord::Base.connection.execute <<-SQL <add>DROP PROCEDURE IF EXISTS topics; <add>SQL <add> <add> ActiveRecord::Base.connection.execute <<-SQL <add>CREATE PROCEDURE topics(IN num INT) SQL SECURITY INVOKER <add>BEGIN <add> select * from topics limit num; <add>END <ide> SQL <ide> <ide> ActiveRecord::Base.connection.drop_table "enum_tests", if_exists: true <ide><path>activerecord/test/schema/mysql_specific_schema.rb <ide> SQL <ide> <ide> ActiveRecord::Base.connection.execute <<-SQL <del>CREATE PROCEDURE topics() SQL SECURITY INVOKER <add>CREATE PROCEDURE topics(IN num INT) SQL SECURITY INVOKER <ide> BEGIN <del> select * from topics limit 1; <add> select * from topics limit num; <ide> END <ide> SQL <ide>
6
Javascript
Javascript
fix webpack typo
ff35edda1876ab3be5e746d275a28e3ae622a748
<ide><path>scripts/mangleErrors.js <ide> const evalToString = ast => { <ide> * If minify is enabled, we'll replace the error message with just an index that maps to an arrow object lookup. <ide> * <ide> * If minify is disabled, we'll add in a conditional statement to check the process.env.NODE_ENV which will output a <del> * an error number index in production or the actual error message in development. This allows consumers using webpak <add> * an error number index in production or the actual error message in development. This allows consumers using webpack <ide> * or another build tool to have these messages in development but have just the error index in production. <ide> * <ide> * E.g.
1
Java
Java
introduce aop testing utilities
efe3a35da871a7ef34148dfb65d6a96cac1fccb9
<ide><path>spring-test/src/main/java/org/springframework/test/util/AopTestUtils.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.test.util; <add> <add>import org.springframework.aop.framework.Advised; <add>import org.springframework.aop.support.AopUtils; <add> <add>/** <add> * {@code AopTestUtils} is a collection of AOP-related utility methods for <add> * use in unit and integration testing scenarios. <add> * <add> * <p>For Spring's core AOP utilities, see <add> * {@link org.springframework.aop.support.AopUtils AopUtils} and <add> * {@link org.springframework.aop.framework.AopProxyUtils AopProxyUtils}. <add> * <add> * @author Sam Brannen <add> * @since 4.2 <add> * @see org.springframework.aop.support.AopUtils <add> * @see org.springframework.aop.framework.AopProxyUtils <add> */ <add>public class AopTestUtils { <add> <add> /** <add> * Get the <em>target</em> object of the supplied {@code candidate} object. <add> * <p>If the supplied {@code candidate} is a Spring <add> * {@linkplain AopUtils#isAopProxy proxy}, the target of the proxy will <add> * be returned; otherwise, the {@code candidate} will be returned <add> * <em>as is</em>. <add> * <add> * @param candidate the instance to check (potentially a Spring AOP proxy) <add> * @return the target object or the {@code candidate}; never {@code null} <add> * @throws IllegalStateException if an error occurs while unwrapping a proxy <add> * @see Advised#getTargetSource() <add> * @see #getUltimateTargetObject <add> */ <add> @SuppressWarnings("unchecked") <add> public static <T> T getTargetObject(Object candidate) { <add> try { <add> if (AopUtils.isAopProxy(candidate) && (candidate instanceof Advised)) { <add> return (T) ((Advised) candidate).getTargetSource().getTarget(); <add> } <add> } <add> catch (Exception e) { <add> throw new IllegalStateException("Failed to unwrap proxied object.", e); <add> } <add> <add> // else <add> return (T) candidate; <add> } <add> <add> /** <add> * Get the ultimate <em>target</em> object of the supplied {@code candidate} <add> * object, unwrapping not only a top-level proxy but also any number of <add> * nested proxies. <add> * <p>If the supplied {@code candidate} is a Spring <add> * {@linkplain AopUtils#isAopProxy proxy}, the ultimate target of all <add> * nested proxies will be returned; otherwise, the {@code candidate} <add> * will be returned <em>as is</em>. <add> * <add> * @param candidate the instance to check (potentially a Spring AOP proxy) <add> * @return the ultimate target object or the {@code candidate}; never <add> * {@code null} <add> * @throws IllegalStateException if an error occurs while unwrapping a proxy <add> * @see Advised#getTargetSource() <add> * @see org.springframework.aop.framework.AopProxyUtils#ultimateTargetClass <add> */ <add> @SuppressWarnings("unchecked") <add> public static <T> T getUltimateTargetObject(Object candidate) { <add> try { <add> if (AopUtils.isAopProxy(candidate) && (candidate instanceof Advised)) { <add> return (T) getUltimateTargetObject(((Advised) candidate).getTargetSource().getTarget()); <add> } <add> } <add> catch (Exception e) { <add> throw new IllegalStateException("Failed to unwrap proxied object.", e); <add> } <add> <add> // else <add> return (T) candidate; <add> } <add> <add>} <ide><path>spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.test.util; <add> <add>import org.junit.Test; <add> <add>import org.springframework.aop.framework.ProxyFactory; <add>import org.springframework.aop.support.AopUtils; <add> <add>import static org.hamcrest.CoreMatchers.*; <add>import static org.junit.Assert.*; <add>import static org.springframework.test.util.AopTestUtils.*; <add> <add>/** <add> * Unit tests for {@link AopTestUtils}. <add> * <add> * @author Sam Brannen <add> * @since 4.2 <add> */ <add>public class AopTestUtilsTests { <add> <add> private final FooImpl foo = new FooImpl(); <add> <add> <add> @Test <add> public void getTargetObjectForNonProxiedObject() { <add> Foo target = getTargetObject(foo); <add> assertSame(foo, target); <add> } <add> <add> @Test <add> public void getTargetObjectWrappedInSingleJdkDynamicProxy() { <add> Foo target = getTargetObject(jdkProxy(foo)); <add> assertSame(foo, target); <add> } <add> <add> @Test <add> public void getTargetObjectWrappedInSingleCglibProxy() { <add> Foo target = getTargetObject(cglibProxy(foo)); <add> assertSame(foo, target); <add> } <add> <add> @Test <add> public void getTargetObjectWrappedInDoubleJdkDynamicProxy() { <add> Foo target = getTargetObject(jdkProxy(jdkProxy(foo))); <add> assertNotSame(foo, target); <add> } <add> <add> @Test <add> public void getTargetObjectWrappedInDoubleCglibProxy() { <add> Foo target = getTargetObject(cglibProxy(cglibProxy(foo))); <add> assertNotSame(foo, target); <add> } <add> <add> @Test <add> public void getUltimateTargetObjectForNonProxiedObject() { <add> Foo target = getUltimateTargetObject(foo); <add> assertSame(foo, target); <add> } <add> <add> @Test <add> public void getUltimateTargetObjectWrappedInSingleJdkDynamicProxy() { <add> Foo target = getUltimateTargetObject(jdkProxy(foo)); <add> assertSame(foo, target); <add> } <add> <add> @Test <add> public void getUltimateTargetObjectWrappedInSingleCglibProxy() { <add> Foo target = getUltimateTargetObject(cglibProxy(foo)); <add> assertSame(foo, target); <add> } <add> <add> @Test <add> public void getUltimateTargetObjectWrappedInDoubleJdkDynamicProxy() { <add> Foo target = getUltimateTargetObject(jdkProxy(jdkProxy(foo))); <add> assertSame(foo, target); <add> } <add> <add> @Test <add> public void getUltimateTargetObjectWrappedInDoubleCglibProxy() { <add> Foo target = getUltimateTargetObject(cglibProxy(cglibProxy(foo))); <add> assertSame(foo, target); <add> } <add> <add> @Test <add> public void getUltimateTargetObjectWrappedInCglibProxyWrappedInJdkDynamicProxy() { <add> Foo target = getUltimateTargetObject(jdkProxy(cglibProxy(foo))); <add> assertSame(foo, target); <add> } <add> <add> @Test <add> public void getUltimateTargetObjectWrappedInCglibProxyWrappedInDoubleJdkDynamicProxy() { <add> Foo target = getUltimateTargetObject(jdkProxy(jdkProxy(cglibProxy(foo)))); <add> assertSame(foo, target); <add> } <add> <add> private Foo jdkProxy(Foo foo) { <add> ProxyFactory pf = new ProxyFactory(); <add> pf.setTarget(foo); <add> pf.addInterface(Foo.class); <add> Foo proxy = (Foo) pf.getProxy(); <add> assertTrue("Proxy is a JDK dynamic proxy", AopUtils.isJdkDynamicProxy(proxy)); <add> assertThat(proxy, instanceOf(Foo.class)); <add> return proxy; <add> } <add> <add> private Foo cglibProxy(Foo foo) { <add> ProxyFactory pf = new ProxyFactory(); <add> pf.setTarget(foo); <add> pf.setProxyTargetClass(true); <add> Foo proxy = (Foo) pf.getProxy(); <add> assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy)); <add> assertThat(proxy, instanceOf(FooImpl.class)); <add> return proxy; <add> } <add> <add> <add> static interface Foo { <add> } <add> <add> static class FooImpl implements Foo { <add> } <add> <add>}
2
PHP
PHP
fix morphtomany test
b900c41ecc2baafefaad3b545b51807334c52c15
<ide><path>src/Illuminate/Database/Eloquent/Relations/MorphToMany.php <ide> class MorphToMany extends BelongsToMany <ide> * @param bool $inverse <ide> * @return void <ide> */ <del> public function __construct(Builder $query, Model $parent, $name, $table, $foreignKey, $relatedKey, $relationName = null, $inverse = false) <add> public function __construct(Builder $query, Model $parent, $name, $table, $foreignKey, $relatedKey, $localKey, $relationName = null, $inverse = false) <ide> { <ide> $this->inverse = $inverse; <ide> $this->morphType = $name.'_type'; <ide> $this->morphClass = $inverse ? $query->getModel()->getMorphClass() : $parent->getMorphClass(); <ide> <del> parent::__construct($query, $parent, $table, $foreignKey, $relatedKey, $relationName); <add> parent::__construct($query, $parent, $table, $foreignKey, $relatedKey, $localKey, $relationName); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentMorphToManyTest.php <ide> public function getRelation() <ide> { <ide> list($builder, $parent) = $this->getRelationArguments(); <ide> <del> return new MorphToMany($builder, $parent, 'taggable', 'taggables', 'taggable_id', 'tag_id'); <add> return new MorphToMany($builder, $parent, 'taggable', 'taggables', 'taggable_id', 'tag_id', 'id'); <ide> } <ide> <ide> public function getRelationArguments() <ide> public function getRelationArguments() <ide> $builder->shouldReceive('where')->once()->with('taggables.taggable_id', '=', 1); <ide> $builder->shouldReceive('where')->once()->with('taggables.taggable_type', get_class($parent)); <ide> <del> return [$builder, $parent, 'taggable', 'taggables', 'taggable_id', 'tag_id', 'relation_name', false]; <add> return [$builder, $parent, 'taggable', 'taggables', 'taggable_id', 'tag_id', 'id', 'relation_name', false]; <ide> } <ide> } <ide>
2
Ruby
Ruby
fix unexpected behavior of with $,
8040f527c3f75638829809662a52af04d50369f9
<ide><path>actionview/lib/action_view/helpers/output_safety_helper.rb <ide> def to_sentence(array, options = {}) <ide> when 2 <ide> safe_join([array[0], array[1]], options[:two_words_connector]) <ide> else <del> safe_join([safe_join(array[0...-1], options[:words_connector]), options[:last_word_connector], array[-1]]) <add> safe_join([safe_join(array[0...-1], options[:words_connector]), options[:last_word_connector], array[-1]], nil) <ide> end <ide> end <ide> end <ide><path>actionview/test/template/output_safety_helper_test.rb <ide> def setup <ide> assert_equal "one, two three", to_sentence(["one", "two", "three"], last_word_connector: " ") <ide> assert_equal "one, two and three", to_sentence(["one", "two", "three"], last_word_connector: " and ") <ide> end <add> <add> test "to_sentence is not affected by $," do <add> $, = "|" <add> begin <add> assert_equal "one and two", to_sentence(["one", "two"]) <add> assert_equal "one, two, and three", to_sentence(["one", "two", "three"]) <add> ensure <add> $, = nil <add> end <add> end <ide> end
2
Python
Python
allow loading template from iterable
0b3369355dadb39ac1ce9580d95004233031a287
<ide><path>flask/templating.py <ide> def _render(template, context, app): <ide> return rv <ide> <ide> <del>def render_template(template_name, **context): <add>def render_template(template_name_or_list, **context): <ide> """Renders a template from the template folder with the given <ide> context. <ide> <del> :param template_name: the name of the template to be rendered <add> :param template_name_or_list: the name of the template to be <add> rendered, or an iterable with template names <add> the first one existing will be rendered <ide> :param context: the variables that should be available in the <ide> context of the template. <ide> """ <ide> ctx = _request_ctx_stack.top <ide> ctx.app.update_template_context(context) <del> return _render(ctx.app.jinja_env.get_template(template_name), <add> return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), <ide> context, ctx.app) <ide> <ide> <ide><path>flask/testsuite/templating.py <ide> def index(): <ide> self.assert_equal(rv.data, 'Hello Custom World!') <ide> <ide> <add> def test_iterable_loader(self): <add> app = flask.Flask(__name__) <add> @app.context_processor <add> def context_processor(): <add> return {'whiskey': 'Jameson'} <add> @app.route('/') <add> def index(): <add> return flask.render_template( <add> ['no_template.xml', # should skip this one <add> 'simple_template.html', # should render this <add> 'context_template.html'], <add> value=23) <add> <add> rv = app.test_client().get('/') <add> self.assert_equal(rv.data, '<h1>Jameson</h1>') <add> <add> <add> <add> <ide> def suite(): <ide> suite = unittest.TestSuite() <ide> suite.addTest(unittest.makeSuite(TemplatingTestCase))
2
Ruby
Ruby
use safe_system to call brew
21c903c133bffca1204766d108d808f34358bb78
<ide><path>Library/Homebrew/dev-cmd/pr-pull.rb <ide> def pr_pull <ide> upload_args << "--dry-run" if args.dry_run? <ide> upload_args << "--root_url=#{args.root_url}" if args.root_url <ide> upload_args << "--bintray-org=#{bintray_org}" <del> system HOMEBREW_BREW_FILE, *upload_args <add> safe_system HOMEBREW_BREW_FILE, *upload_args <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/dev-cmd/pr-upload.rb <ide> def pr_upload <ide> if args.dry_run? <ide> puts "brew #{bottle_args.join " "}" <ide> else <del> system HOMEBREW_BREW_FILE, *bottle_args <add> safe_system HOMEBREW_BREW_FILE, *bottle_args <ide> end <ide> <ide> if args.dry_run?
2
Javascript
Javascript
add missing test for
07084e1c8bd4efa28b3f02aea353640af0cf37d6
<ide><path>test/auto/injectorSpec.js <ide> describe('injector', function() { <ide> }); <ide> <ide> <add> it('should not corrupt the cache when an object fails to get instantiated', function() { <add> expect(function() { <add> injector.get('idontexist'); <add> }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist"); <add> <add> expect(function() { <add> injector.get('idontexist'); <add> }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist"); <add> }); <add> <add> <ide> it('should provide path to the missing provider', function() { <ide> providers('a', function(idontexist) {return 1;}); <ide> providers('b', function(a) {return 2;});
1
Python
Python
wait option for dagrun operator
af2f2e8c299c40e81dc815bcee84c97f7eb0801d
<ide><path>airflow/operators/dagrun_operator.py <ide> # under the License. <ide> <ide> import datetime <del>from typing import Dict, Optional, Union <add>import time <add>from typing import Dict, List, Optional, Union <ide> <ide> from airflow.api.common.experimental.trigger_dag import trigger_dag <del>from airflow.exceptions import DagNotFound, DagRunAlreadyExists <add>from airflow.exceptions import AirflowException, DagNotFound, DagRunAlreadyExists <ide> from airflow.models import BaseOperator, BaseOperatorLink, DagBag, DagModel, DagRun <ide> from airflow.utils import timezone <ide> from airflow.utils.decorators import apply_defaults <ide> from airflow.utils.helpers import build_airflow_url_with_query <add>from airflow.utils.state import State <ide> from airflow.utils.types import DagRunType <ide> <ide> <ide> class TriggerDagRunOperator(BaseOperator): <ide> When reset_dag_run=False and dag run exists, DagRunAlreadyExists will be raised. <ide> When reset_dag_run=True and dag run exists, existing dag run will be cleared to rerun. <ide> :type reset_dag_run: bool <add> :param wait_for_completion: Whether or not wait for dag run completion. (default: False) <add> :type wait_for_completion: bool <add> :param poke_interval: Poke interval to check dag run status when wait_for_completion=True. <add> (default: 60) <add> :type poke_interval: int <add> :param allowed_states: list of allowed states, default is ``['success']`` <add> :type allowed_states: list <add> :param failed_states: list of failed or dis-allowed states, default is ``None`` <add> :type failed_states: list <ide> """ <ide> <ide> template_fields = ("trigger_dag_id", "execution_date", "conf") <ide> def __init__( <ide> conf: Optional[Dict] = None, <ide> execution_date: Optional[Union[str, datetime.datetime]] = None, <ide> reset_dag_run: bool = False, <add> wait_for_completion: bool = False, <add> poke_interval: int = 60, <add> allowed_states: Optional[List] = None, <add> failed_states: Optional[List] = None, <ide> **kwargs, <ide> ) -> None: <ide> super().__init__(**kwargs) <ide> self.trigger_dag_id = trigger_dag_id <ide> self.conf = conf <ide> self.reset_dag_run = reset_dag_run <add> self.wait_for_completion = wait_for_completion <add> self.poke_interval = poke_interval <add> self.allowed_states = allowed_states or [State.SUCCESS] <add> self.failed_states = failed_states or [State.FAILED] <ide> <ide> if not isinstance(execution_date, (str, datetime.datetime, type(None))): <ide> raise TypeError( <ide> def execute(self, context: Dict): <ide> try: <ide> # Ignore MyPy type for self.execution_date <ide> # because it doesn't pick up the timezone.parse() for strings <del> trigger_dag( <add> dag_run = trigger_dag( <ide> dag_id=self.trigger_dag_id, <ide> run_id=run_id, <ide> conf=self.conf, <ide> def execute(self, context: Dict): <ide> dag.clear(start_date=self.execution_date, end_date=self.execution_date) <ide> else: <ide> raise e <add> <add> if self.wait_for_completion: <add> # wait for dag to complete <add> while True: <add> self.log.info( <add> 'Waiting for %s on %s to become allowed state %s ...', <add> self.trigger_dag_id, <add> dag_run.execution_date, <add> self.allowed_states, <add> ) <add> time.sleep(self.poke_interval) <add> <add> dag_run.refresh_from_db() <add> state = dag_run.state <add> if state in self.failed_states: <add> raise AirflowException(f"{self.trigger_dag_id} failed with failed states {state}") <add> if state in self.allowed_states: <add> self.log.info("%s finished with allowed state %s", self.trigger_dag_id, state) <add> return <ide><path>tests/operators/test_dagrun_operator.py <ide> from datetime import datetime <ide> from unittest import TestCase <ide> <del>from airflow.exceptions import DagRunAlreadyExists <add>from airflow.exceptions import AirflowException, DagRunAlreadyExists <ide> from airflow.models import DAG, DagBag, DagModel, DagRun, Log, TaskInstance <ide> from airflow.models.serialized_dag import SerializedDagModel <ide> from airflow.operators.dagrun_operator import TriggerDagRunOperator <ide> from airflow.utils import timezone <ide> from airflow.utils.session import create_session <add>from airflow.utils.state import State <ide> <ide> DEFAULT_DATE = datetime(2019, 1, 1, tzinfo=timezone.utc) <ide> TEST_DAG_ID = "testdag" <ide> def test_trigger_dagrun_with_reset_dag_run_true(self): <ide> dagruns = session.query(DagRun).filter(DagRun.dag_id == TRIGGERED_DAG_ID).all() <ide> self.assertEqual(len(dagruns), 1) <ide> self.assertTrue(dagruns[0].external_trigger) <add> <add> def test_trigger_dagrun_with_wait_for_completion_true(self): <add> """Test TriggerDagRunOperator with wait_for_completion.""" <add> execution_date = DEFAULT_DATE <add> task = TriggerDagRunOperator( <add> task_id="test_task", <add> trigger_dag_id=TRIGGERED_DAG_ID, <add> execution_date=execution_date, <add> wait_for_completion=True, <add> poke_interval=10, <add> allowed_states=[State.RUNNING], <add> dag=self.dag, <add> ) <add> task.run(start_date=execution_date, end_date=execution_date) <add> <add> with create_session() as session: <add> dagruns = session.query(DagRun).filter(DagRun.dag_id == TRIGGERED_DAG_ID).all() <add> self.assertEqual(len(dagruns), 1) <add> <add> def test_trigger_dagrun_with_wait_for_completion_true_fail(self): <add> """Test TriggerDagRunOperator with wait_for_completion but triggered dag fails.""" <add> execution_date = DEFAULT_DATE <add> task = TriggerDagRunOperator( <add> task_id="test_task", <add> trigger_dag_id=TRIGGERED_DAG_ID, <add> execution_date=execution_date, <add> wait_for_completion=True, <add> poke_interval=10, <add> failed_states=[State.RUNNING], <add> dag=self.dag, <add> ) <add> with self.assertRaises(AirflowException): <add> task.run(start_date=execution_date, end_date=execution_date)
2
Javascript
Javascript
ignore invalid dates
1334b8c8326b93e0ca016c85516627900c7a9fd3
<ide><path>src/ng/filter/filters.js <ide> function dateFilter($locale) { <ide> date = new Date(date); <ide> } <ide> <del> if (!isDate(date)) { <add> if (!isDate(date) || !isFinite(date.getTime())) { <ide> return date; <ide> } <ide> <ide><path>test/ng/filter/filtersSpec.js <ide> describe('filters', function() { <ide> expect(date('')).toEqual(''); <ide> }); <ide> <add> it('should ignore invalid dates', function() { <add> var invalidDate = new Date('abc'); <add> expect(date(invalidDate)).toBe(invalidDate); <add> }); <add> <ide> it('should do basic filter', function() { <ide> expect(date(noon)).toEqual(date(noon, 'mediumDate')); <ide> expect(date(noon, '')).toEqual(date(noon, 'mediumDate'));
2
Text
Text
add kloudless as a new premium sponsor
1c3f796219e7794306bb2db81d4910c0cb7c932a
<ide><path>README.md <ide> The initial aim is to provide a single full-time position on REST framework. <ide> [![][rollbar-img]][rollbar-url] <ide> [![][cadre-img]][cadre-url] <ide> [![][load-impact-img]][load-impact-url] <add>[![][kloudless-img]][kloudless-url] <ide> <del>Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover][rover-url], [Sentry][sentry-url], [Stream][stream-url], [Rollbar][rollbar-url], [Cadre][cadre-url], and [Load Impact][load-impact-url]. <add>Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover][rover-url], [Sentry][sentry-url], [Stream][stream-url], [Rollbar][rollbar-url], [Cadre][cadre-url], [Load Impact][load-impact-url], and [Kloudless][kloudless-url]. <ide> <ide> --- <ide> <ide> Send a description of the issue via email to [rest-framework-security@googlegrou <ide> [rollbar-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rollbar-readme.png <ide> [cadre-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cadre-readme.png <ide> [load-impact-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/load-impact-readme.png <add>[kloudless-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/kloudless-readme.png <ide> <ide> [rover-url]: http://jobs.rover.com/ <ide> [sentry-url]: https://getsentry.com/welcome/ <ide> [stream-url]: https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf <ide> [rollbar-url]: https://rollbar.com/ <ide> [cadre-url]: https://cadre.com/ <ide> [load-impact-url]: https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf <add>[kloudless-url]: https://hubs.ly/H0f30Lf0 <ide> <ide> [oauth1-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth <ide> [oauth2-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit <ide><path>docs/index.md <ide> continued development by **[signing up for a paid plan][funding]**. <ide> <li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li> <ide> <li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li> <ide> <li><a href="https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/load-impact.png)">Load Impact</a></li> <add> <li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless.png)">Kloudless</a></li> <ide> </ul> <ide> <div style="clear: both; padding-bottom: 20px;"></div> <ide> <del>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Rollbar](https://rollbar.com), [Cadre](https://cadre.com), and [Load Impact](https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf).* <add>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Rollbar](https://rollbar.com), [Cadre](https://cadre.com), [Load Impact](https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf), and [Kloudless](https://hubs.ly/H0f30Lf0).* <ide> <ide> --- <ide>
2
Ruby
Ruby
use regex in appcast adjusted_version_stanza
a7b51ebecd35e319a6fe7f8928303dd555449742
<ide><path>Library/Homebrew/cask/audit.rb <ide> def check_appcast_contains_version <ide> "--globoff", "--max-time", "5", appcast_stanza) <ide> version_stanza = cask.version.to_s <ide> adjusted_version_stanza = if cask.appcast.configuration.blank? <del> version_stanza.split(",")[0].split("-")[0].split("_")[0] <add> version_stanza.match(/^[[:alnum:].]+/)[0] <ide> else <ide> cask.appcast.configuration <ide> end
1
PHP
PHP
allow direct closure middleware
fcef04958f22fdf8009486ae6b883572f21cf37a
<ide><path>src/Illuminate/Routing/Router.php <ide> public function resolveMiddlewareClassName($name) <ide> { <ide> $map = $this->middleware; <ide> <del> // If the middleware is the name of a middleware group, we will return the array <del> // of middlewares that belong to the group. This allows developers to group a <del> // set of middleware under single keys that can be conveniently referenced. <del> if (isset($this->middlewareGroups[$name])) { <del> return $this->parseMiddlewareGroup($name); <ide> // When the middleware is simply a Closure, we will return this Closure instance <ide> // directly so that Closures can be registered as middleware inline, which is <ide> // convenient on occasions when the developers are experimenting with them. <add> if ($name instanceof Closure) { <add> return $name; <ide> } elseif (isset($map[$name]) && $map[$name] instanceof Closure) { <ide> return $map[$name]; <add> // If the middleware is the name of a middleware group, we will return the array <add> // of middlewares that belong to the group. This allows developers to group a <add> // set of middleware under single keys that can be conveniently referenced. <add> } elseif (isset($this->middlewareGroups[$name])) { <add> return $this->parseMiddlewareGroup($name); <ide> // Finally, when the middleware is simply a string mapped to a class name the <ide> // middleware name will get parsed into the full class name and parameters <ide> // which may be run using the Pipeline which accepts this string format. <ide><path>tests/Routing/RoutingRouteTest.php <ide> public function testBasicDispatchingOfRoutes() <ide> } <ide> <ide> public function testClosureMiddleware() <add> { <add> $router = $this->getRouter(); <add> $middleware = function ($request, $next) { <add> return 'caught'; <add> }; <add> $router->get('foo/bar', ['middleware' => $middleware, function () { <add> return 'hello'; <add> }]); <add> $this->assertEquals('caught', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); <add> } <add> <add> public function testDefinedClosureMiddleware() <ide> { <ide> $router = $this->getRouter(); <ide> $router->get('foo/bar', ['middleware' => 'foo', function () {
2
Text
Text
add quick contribution note
640c2b559f16a6070805ce26efeb4afe992f2152
<ide><path>readme.md <del>## Laravel Framework (Core) <add>## Laravel Framework (Kernel) <ide> <ide> [![Latest Stable Version](https://poser.pugx.org/laravel/framework/version.png)](https://packagist.org/packages/laravel/framework) [![Total Downloads](https://poser.pugx.org/laravel/framework/d/total.png)](https://packagist.org/packages/laravel/framework) [![Build Status](https://travis-ci.org/laravel/framework.png)](https://travis-ci.org/laravel/framework) [![Dependency Status](https://www.versioneye.com/php/laravel:framework/badge.png)](https://www.versioneye.com/php/laravel:framework) <ide> <del>This repository contains the core code of the Laravel framework. If you want to build an application using Laravel 4, visit the main [Laravel repository](https://github.com/laravel/laravel). <ide>\ No newline at end of file <add>> **Note:** This repository contains the core code of the Laravel framework. If you want to build an application using Laravel 4, visit the main [Laravel repository](https://github.com/laravel/laravel). <add> <add>## Contributing To Laravel <add> <add>Thank you for considering contributing to the Laravel framework. If you are submitting a bug-fix, or an enhancement that is **not** a breaking change, submit your pull request to the branch corresponding to the latest stable release of the framework, such as the `4.1` branch. If you are submitting a breaking change or an entirely new component, submit your pull request to the `master` branch. <ide>\ No newline at end of file
1
Java
Java
add propertynamingstrategy field to objectmapperfb
268657b6cb5ba3153f2d35e37a7e21e8197db6cd
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 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 com.fasterxml.jackson.databind.MapperFeature; <ide> import com.fasterxml.jackson.databind.Module; <ide> import com.fasterxml.jackson.databind.ObjectMapper; <add>import com.fasterxml.jackson.databind.PropertyNamingStrategy; <ide> import com.fasterxml.jackson.databind.SerializationFeature; <ide> import com.fasterxml.jackson.databind.module.SimpleModule; <ide> <ide> public class Jackson2ObjectMapperFactoryBean implements FactoryBean<ObjectMapper <ide> <ide> private boolean findModulesViaServiceLoader; <ide> <add> private PropertyNamingStrategy propertyNamingStrategy; <add> <ide> private ClassLoader beanClassLoader; <ide> <ide> <ide> public void setFindModulesViaServiceLoader(boolean findModules) { <ide> this.findModulesViaServiceLoader = findModules; <ide> } <ide> <add> /** <add> * Specify a {@link com.fasterxml.jackson.databind.PropertyNamingStrategy} to <add> * configure the {@link ObjectMapper} with. <add> * @@since 4.0.2 <add> */ <add> public void setPropertyNamingStrategy(PropertyNamingStrategy propertyNamingStrategy) { <add> this.propertyNamingStrategy = propertyNamingStrategy; <add> } <add> <ide> @Override <ide> public void setBeanClassLoader(ClassLoader beanClassLoader) { <ide> this.beanClassLoader = beanClassLoader; <ide> public void afterPropertiesSet() { <ide> registerWellKnownModulesIfAvailable(); <ide> } <ide> } <add> <add> if (this.propertyNamingStrategy != null) { <add> this.objectMapper.setPropertyNamingStrategy(this.propertyNamingStrategy); <add> } <ide> } <ide> <ide> @SuppressWarnings("unchecked") <ide><path>spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 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 com.fasterxml.jackson.databind.MapperFeature; <ide> import com.fasterxml.jackson.databind.Module; <ide> import com.fasterxml.jackson.databind.ObjectMapper; <add>import com.fasterxml.jackson.databind.PropertyNamingStrategy; <ide> import com.fasterxml.jackson.databind.SerializationFeature; <ide> import com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig; <ide> import com.fasterxml.jackson.databind.cfg.SerializerFactoryConfig; <ide> <ide> import org.springframework.beans.FatalBeanException; <ide> <del>import static org.junit.Assert.*; <add>import static junit.framework.Assert.assertTrue; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.assertNull; <add>import static org.junit.Assert.assertSame; <ide> <ide> /** <ide> * Test cases for {@link Jackson2ObjectMapperFactoryBean} class. <ide> private static DeserializerFactoryConfig getDeserializerFactoryConfig(ObjectMapp <ide> return ((BasicDeserializerFactory) objectMapper.getDeserializationContext().getFactory()).getFactoryConfig(); <ide> } <ide> <add> @Test <add> public void testPropertyNamingStrategy() { <add> PropertyNamingStrategy strategy = new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy(); <add> this.factory.setPropertyNamingStrategy(strategy); <add> this.factory.afterPropertiesSet(); <add> <add> assertSame(strategy, this.factory.getObject().getSerializationConfig().getPropertyNamingStrategy()); <add> assertSame(strategy, this.factory.getObject().getDeserializationConfig().getPropertyNamingStrategy()); <add> } <add> <ide> @Test <ide> public void testCompleteSetup() { <ide> NopAnnotationIntrospector annotationIntrospector = NopAnnotationIntrospector.instance;
2
Text
Text
update rails 5 upgrade guides
3d252a02ae7f17f94401fe206f4ffc1922610d6f
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> Don't forget to review the difference, to see if there were any unexpected chang <ide> Upgrading from Rails 4.2 to Rails 5.0 <ide> ------------------------------------- <ide> <del>### Ruby 2.2.2+ <add>### Ruby 2.2.2+ required <ide> <del>From Ruby on Rails 5.0 onwards, Ruby 2.2.2+ is the only supported version. <del>Make sure you are on Ruby 2.2.2 version or greater, before you proceed. <add>From Ruby on Rails 5.0 onwards, Ruby 2.2.2+ is the only supported Ruby version. <add>Make sure you are on Ruby 2.2.2 version or greater, before you proceed. <ide> <ide> ### Active Record models now inherit from ApplicationRecord by default <ide> <ide> See [#17227](https://github.com/rails/rails/pull/17227) for more details. <ide> <ide> ### ActiveJob jobs now inherit from ApplicationJob by default <ide> <del>In Rails 4.2 an ActiveJob inherits from `ActiveJob::Base`. In Rails 5.0 this <add>In Rails 4.2 an Active Job inherits from `ActiveJob::Base`. In Rails 5.0 this <ide> behavior has changed to now inherit from `ApplicationJob`. <ide> <ide> When upgrading from Rails 4.2 to Rails 5.0 you need to create an <ide> Then make sure that all your job classes inherit from it. <ide> <ide> See [#19034](https://github.com/rails/rails/pull/19034) for more details. <ide> <add>### Rails Controller Testing <add> <add>`assigns` and `assert_template` have been extracted to the `rails-controller-testing` gem. To <add>continue using these methods in your controller tests add `gem 'rails-controller-testing'` to <add>your Gemfile. <add> <add>If you are using Rspec for testing please see the extra configuration required in the gem's <add>documentation. <add> <add>### XML Serialization <add> <add>`ActiveModel::Serializers::Xml` has been extracted from Rails to the `activemodel-serializers-xml` <add>gem. To continue using XML serialization in your application add `gem 'activemodel-serializers-xml'` <add>to your Gemfile. <add> <add>### Removed support for legacy MySQL <add> <add>Rails 5 removes support for the legacy `mysql` database adapter. Most users should be able to <add>use `mysql2` instead. It will be converted to a separate gem when we find someone to maintain <add>it. <add> <add>### Removed support for debugger <add> <add>`debugger` is not supported by Ruby 2.2 which is required by Rails 5. Use `byebug` instead. <add> <add>### Use bin/rails for running tasks and tests <add> <add>Rails 5 adds the ability to run tasks and tests through `bin/rails` instead of rake. Generally <add>these changes are in paralell with rake, but some were ported over altogether. <add> <add>To use the new test runner simply type `bin/rails test`. <add> <add> rake dev:cache` is now `rails dev:cache <add> <add>Run `bin/rails` to see the list of commands available. <add> <add>### `ActionController::Parameters` no longer inherits from `HashWithIndifferentAccess` <add> <add>Calling `params` in your application will now return an object instead of a hash. If your <add>parameters are already permitted you will not need to make any changes. If you are using slice <add>and other methods that depend on being able to read the hash regardless of `permitted?` you will <add>need to ugrade your application to first permit and then convert to a hash. <add> <add> params.permit([:proceed_to, :return_to]).to_h <add> <add>### `protect_from_forgery` now defaults to `prepend: false` <add> <add>`protect_from_forgery` defaults to `prepend: false` which means that it will be inserted into <add>the callback chain at the point in which you call it in your application. If you want <add>`protect_from_forgery` to always run first you should change your application to use <add>`protect_from_forgery prepend: true`. <add> <add>### Default template handler is now RAW <add> <add>Files without a template handler in their extension will be rendered using the raw handler. <add>Previously Rails would render files using the ERB template handler. <add> <add>If you do not want your file to be handled via the raw handler, you should add an extension <add>to your file that can be parsed by the appropriate template handler. <add> <add>### Add wildcard matching for template dependencies <add> <add>You can now use wildcard matching for your template dependencies. For example if you were <add>defining your templates as such: <add> <add>```erb <add><% # Template Dependency: recordings/threads/events/subscribers_changed %> <add><% # Template Dependency: recordings/threads/events/completed %> <add><% # Template Dependency: recordings/threads/events/uncompleted %> <add>``` <add> <add>You can now just call the dependency once with a wildcard. <add> <add>```erb <add><% # Template Dependency: recordings/threads/events/* %> <add>``` <add> <add>### Remove support for `protected_attributes` gem <add> <add>The `protected_attributes` gem is no longer supported in Rails 5. <add> <add>### Remove support for `activerecord-deprecated_finders` gem <add> <add>The `activerecord-deprecated_finders` gem is no longer supported in Rails 5. <add> <add>### `ActiveSupport::TestCase` default test order is now random <add> <add>When tests are run in your application the default order is now `:random` <add>instead of `:sorted`. Use the following config option to set it back to `:sorted`. <add> <add>```ruby <add># config/environments/test.rb <add>Rails.application.configure do <add> config.active_support.test_order = :sorted <add>end <add>``` <add> <add>### New config options <add> <add>## Active Record `belongs_to` Required by Default Option <add> <add>`belongs_to` will now trigger a validation error by default if the association is not present. <add> <add>This can be turned off per-association with `optional: true`. <add> <add>This default will will be automatically configured in new applications. If existing application <add>want to add this feature it will need to be turned on in an initializer. <add> <add> config.active_record.belongs_to_required_by_default = true <add> <add>## Allow configuration of Action Mailer queue name <add> <add>The default mailer queue name is `mailers`. This configuration option allows you to globally change <add>the queue name. Set the following in your config. <add> <add> config.action_mailer.deliver_later_queue_name <add> <add>## Support fragment caching in Action Mailer views <add> <add>Set `config.action_mailer.perform_caching` in your config to determine whether your Action Mailer views <add>should support caching. <add> <add>## Configure the output of `db:structure:dump` <add> <add>If you're using `schema_search_path` or other PostgreSQL extentions, you can control how the schema is <add>dumped. Set to `:all` to generate all dumps, or `:schema_search_path` to generate from schame search path. <add> <add> config.active_record.dump_schemas = :all <add> <ide> Upgrading from Rails 4.1 to Rails 4.2 <ide> ------------------------------------- <ide>
1
Python
Python
use actual range in 'seen' instead of subtree
b509a3e7fcadf84c257c1e5168b6dc926b8b2f3d
<ide><path>spacy/lang/en/syntax_iterators.py <ide> def noun_chunks(obj): <ide> if word.i in seen: <ide> continue <ide> if word.dep in np_deps: <del> if any(w.i in seen for w in word.subtree): <add> if any(j in seen for j in range(word.left_edge.i, word.i + 1)): <ide> continue <ide> seen.update(j for j in range(word.left_edge.i, word.i + 1)) <ide> yield word.left_edge.i, word.i + 1, np_label <ide> def noun_chunks(obj): <ide> head = head.head <ide> # If the head is an NP, and we're coordinated to it, we're an NP <ide> if head.dep in np_deps: <del> if any(w.i in seen for w in word.subtree): <add> if any(j in seen for j in range(word.left_edge.i, word.i + 1)): <ide> continue <ide> seen.update(j for j in range(word.left_edge.i, word.i + 1)) <ide> yield word.left_edge.i, word.i + 1, np_label <ide><path>spacy/language.py <ide> def remove_pipe(self, name): <ide> <ide> def __call__(self, text, disable=[], component_cfg=None): <ide> """Apply the pipeline to some text. The text can span multiple sentences, <del> and can contain arbtrary whitespace. Alignment into the original string <add> and can contain arbitrary whitespace. Alignment into the original string <ide> is preserved. <ide> <ide> text (unicode): The text to be processed.
2
Javascript
Javascript
fix edge cases with adding/removing observers
d884654354a179533fc80132eb85d2fb19dc30f0
<ide><path>packages/ember-metal/lib/events.js <ide> function targetSetFor(obj, eventName) { <ide> // meta system. <ide> var SKIP_PROPERTIES = { __ember_source__: true }; <ide> <del>function iterateSet(obj, eventName, callback, params) { <del> var targetSet = targetSetFor(obj, eventName); <add>function iterateSet(targetSet, callback) { <ide> if (!targetSet) { return false; } <ide> // Iterate through all elements of the target set <ide> for(var targetGuid in targetSet) { <ide> function iterateSet(obj, eventName, callback, params) { <ide> <ide> var action = actionSet[methodGuid]; <ide> if (action) { <del> if (callback(action, params, obj) === true) { <add> if (callback(action) === true) { <ide> return true; <ide> } <ide> } <ide> function invokeAction(action, params, sender) { <ide> } <ide> } <ide> <add>function targetSetUnion(obj, eventName, targetSet) { <add> iterateSet(targetSetFor(obj, eventName), function (action) { <add> var targetGuid = guidFor(action.target), <add> methodGuid = guidFor(action.method), <add> actionSet = targetSet[targetGuid]; <add> if (!actionSet) actionSet = targetSet[targetGuid] = {}; <add> actionSet[methodGuid] = action; <add> }); <add>} <add> <add>function targetSetDiff(obj, eventName, targetSet) { <add> var diffTargetSet = {}; <add> iterateSet(targetSetFor(obj, eventName), function (action) { <add> var targetGuid = guidFor(action.target), <add> methodGuid = guidFor(action.method), <add> actionSet = targetSet[targetGuid], <add> diffActionSet = diffTargetSet[targetGuid]; <add> if (!actionSet) actionSet = targetSet[targetGuid] = {}; <add> if (actionSet[methodGuid]) return; <add> actionSet[methodGuid] = action; <add> if (!diffActionSet) diffActionSet = diffTargetSet[targetGuid] = {}; <add> diffActionSet[methodGuid] = action; <add> }); <add> return diffTargetSet; <add>} <add> <ide> /** <ide> Add an event listener <ide> <ide> function removeListener(obj, eventName, target, method) { <ide> if (method) { <ide> _removeListener(target, method); <ide> } else { <del> iterateSet(obj, eventName, function(action) { <add> iterateSet(targetSetFor(obj, eventName), function(action) { <ide> _removeListener(action.target, action.method); <ide> }); <ide> } <ide> function watchedEvents(obj) { <ide> @param {Array} params <ide> @return true <ide> */ <del>function sendEvent(obj, eventName, params) { <add>function sendEvent(obj, eventName, params, targetSet) { <ide> // first give object a chance to handle it <ide> if (obj !== Ember && 'function' === typeof obj.sendEvent) { <ide> obj.sendEvent(eventName, params); <ide> } <ide> <del> iterateSet(obj, eventName, invokeAction, params); <del> return true; <del>} <add> if (!targetSet) targetSet = targetSetFor(obj, eventName); <ide> <del>/** <del> @private <del> @method deferEvent <del> @for Ember <del> @param obj <del> @param {String} eventName <del> @param {Array} params <del>*/ <del>function deferEvent(obj, eventName, params) { <del> var actions = []; <del> iterateSet(obj, eventName, function (action) { <del> actions.push(action); <add> iterateSet(targetSet, function (action) { <add> invokeAction(action, params, obj); <ide> }); <del> <del> return function() { <del> if (obj.isDestroyed) { return; } <del> <del> if (obj !== Ember && 'function' === typeof obj.sendEvent) { <del> obj.sendEvent(eventName, params); <del> } <del> <del> for (var i=0, len=actions.length; i < len; ++i) { <del> invokeAction(actions[i], params, obj); <del> } <del> }; <add> return true; <ide> } <ide> <ide> /** <ide> function deferEvent(obj, eventName, params) { <ide> @param {String} eventName <ide> */ <ide> function hasListeners(obj, eventName) { <del> if (iterateSet(obj, eventName, function() { return true; })) { <add> if (iterateSet(targetSetFor(obj, eventName), function() { return true; })) { <ide> return true; <ide> } <ide> <ide> function hasListeners(obj, eventName) { <ide> */ <ide> function listenersFor(obj, eventName) { <ide> var ret = []; <del> iterateSet(obj, eventName, function (action) { <add> iterateSet(targetSetFor(obj, eventName), function (action) { <ide> ret.push([action.target, action.method]); <ide> }); <ide> return ret; <ide> Ember.sendEvent = sendEvent; <ide> Ember.hasListeners = hasListeners; <ide> Ember.watchedEvents = watchedEvents; <ide> Ember.listenersFor = listenersFor; <del>Ember.deferEvent = deferEvent; <add>Ember.listenersDiff = targetSetDiff; <add>Ember.listenersUnion = targetSetUnion; <ide>\ No newline at end of file <ide><path>packages/ember-metal/lib/observer.js <ide> require('ember-metal/array'); <ide> <ide> var AFTER_OBSERVERS = ':change'; <ide> var BEFORE_OBSERVERS = ':before'; <add> <ide> var guidFor = Ember.guidFor; <ide> <ide> var deferred = 0; <del>var array_Slice = [].slice; <del> <del>var ObserverSet = function () { <del> this.targetSet = {}; <del>}; <del>ObserverSet.prototype.add = function (target, path) { <del> var targetSet = this.targetSet, <del> targetGuid = Ember.guidFor(target), <del> pathSet = targetSet[targetGuid]; <del> if (!pathSet) { <del> targetSet[targetGuid] = pathSet = {}; <del> } <del> if (pathSet[path]) { <del> return false; <del> } else { <del> return pathSet[path] = true; <del> } <del>}; <del>ObserverSet.prototype.clear = function () { <del> this.targetSet = {}; <del>}; <ide> <del>var DeferredEventQueue = function() { <del> this.targetSet = {}; <del> this.queue = []; <del>}; <add>/* <add> this.observerSet = { <add> [senderGuid]: { // variable name: `keySet` <add> [keyName]: listIndex <add> } <add> }, <add> this.observers = [ <add> { <add> sender: obj, <add> keyName: keyName, <add> eventName: eventName, <add> listeners: { <add> [targetGuid]: { // variable name: `actionSet` <add> [methodGuid]: { // variable name: `action` <add> target: [Object object], <add> method: [Function function] <add> } <add> } <add> } <add> }, <add> ... <add> ] <add>*/ <add>function ObserverSet() { <add> this.clear(); <add>} <ide> <del>DeferredEventQueue.prototype.push = function(target, eventName, keyName) { <del> var targetSet = this.targetSet, <del> queue = this.queue, <del> targetGuid = Ember.guidFor(target), <del> eventNameSet = targetSet[targetGuid], <del> index; <add>ObserverSet.prototype.add = function(sender, keyName, eventName) { <add> var observerSet = this.observerSet, <add> observers = this.observers, <add> senderGuid = Ember.guidFor(sender), <add> keySet = observerSet[senderGuid], <add> index; <ide> <del> if (!eventNameSet) { <del> targetSet[targetGuid] = eventNameSet = {}; <add> if (!keySet) { <add> observerSet[senderGuid] = keySet = {}; <ide> } <del> index = eventNameSet[eventName]; <add> index = keySet[keyName]; <ide> if (index === undefined) { <del> eventNameSet[eventName] = queue.push(Ember.deferEvent(target, eventName, [target, keyName])) - 1; <del> } else { <del> queue[index] = Ember.deferEvent(target, eventName, [target, keyName]); <add> index = observers.push({ <add> sender: sender, <add> keyName: keyName, <add> eventName: eventName, <add> listeners: {} <add> }) - 1; <add> keySet[keyName] = index; <ide> } <add> return observers[index].listeners; <ide> }; <ide> <del>DeferredEventQueue.prototype.flush = function() { <del> var queue = this.queue; <del> this.queue = []; <del> this.targetSet = {}; <del> for (var i=0, len=queue.length; i < len; ++i) { <del> queue[i](); <add>ObserverSet.prototype.flush = function() { <add> var observers = this.observers, i, len, observer, sender; <add> this.clear(); <add> for (i=0, len=observers.length; i < len; ++i) { <add> observer = observers[i]; <add> sender = observer.sender; <add> if (sender.isDestroyed) { continue; } <add> Ember.sendEvent(sender, observer.eventName, [sender, observer.keyName], observer.listeners); <ide> } <ide> }; <ide> <del>var queue = new DeferredEventQueue(), beforeObserverSet = new ObserverSet(); <del> <del>function notifyObservers(obj, eventName, keyName, forceNotification) { <del> if (deferred && !forceNotification) { <del> queue.push(obj, eventName, keyName); <del> } else { <del> Ember.sendEvent(obj, eventName, [obj, keyName]); <del> } <del>} <del> <del>function flushObserverQueue() { <del> beforeObserverSet.clear(); <add>ObserverSet.prototype.clear = function() { <add> this.observerSet = {}; <add> this.observers = []; <add>}; <ide> <del> queue.flush(); <del>} <add>var beforeObserverSet = new ObserverSet(), observerSet = new ObserverSet(); <ide> <ide> /** <ide> @method beginPropertyChanges <ide> @chainable <ide> */ <ide> Ember.beginPropertyChanges = function() { <ide> deferred++; <del> return this; <ide> }; <ide> <ide> /** <ide> @method endPropertyChanges <ide> */ <ide> Ember.endPropertyChanges = function() { <ide> deferred--; <del> if (deferred<=0) flushObserverQueue(); <add> if (deferred<=0) { <add> beforeObserverSet.clear(); <add> observerSet.flush(); <add> } <ide> }; <ide> <ide> /** <ide> Ember.removeBeforeObserver = function(obj, path, target, method) { <ide> return this; <ide> }; <ide> <del>Ember.notifyObservers = function(obj, keyName) { <add>Ember.notifyBeforeObservers = function(obj, keyName) { <ide> if (obj.isDestroying) { return; } <ide> <del> notifyObservers(obj, changeEvent(keyName), keyName); <add> var eventName = beforeEvent(keyName), listeners, listenersDiff; <add> if (deferred) { <add> listeners = beforeObserverSet.add(obj, keyName, eventName); <add> listenersDiff = Ember.listenersDiff(obj, eventName, listeners); <add> Ember.sendEvent(obj, eventName, [obj, keyName], listenersDiff); <add> } else { <add> Ember.sendEvent(obj, eventName, [obj, keyName]); <add> } <ide> }; <ide> <del>Ember.notifyBeforeObservers = function(obj, keyName) { <add>Ember.notifyObservers = function(obj, keyName) { <ide> if (obj.isDestroying) { return; } <ide> <del> var guid, set, forceNotification = false; <del> <add> var eventName = changeEvent(keyName), listeners; <ide> if (deferred) { <del> if (beforeObserverSet.add(obj, keyName)) { <del> forceNotification = true; <del> } else { <del> return; <del> } <add> listeners = observerSet.add(obj, keyName, eventName); <add> Ember.listenersUnion(obj, eventName, listeners); <add> } else { <add> Ember.sendEvent(obj, eventName, [obj, keyName]); <ide> } <del> <del> notifyObservers(obj, beforeEvent(keyName), keyName, forceNotification); <ide> }; <del>
2
PHP
PHP
replace calls to config() with get/setconfig()
888ff743260da06c7431f5d70bd09ffcb115be4a
<ide><path>src/Auth/AbstractPasswordHasher.php <ide> abstract class AbstractPasswordHasher <ide> */ <ide> public function __construct(array $config = []) <ide> { <del> $this->config($config); <add> $this->setConfig($config); <ide> } <ide> <ide> /** <ide><path>src/Auth/BaseAuthenticate.php <ide> abstract class BaseAuthenticate implements EventListenerInterface <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> { <ide> $this->_registry = $registry; <del> $this->config($config); <add> $this->setConfig($config); <ide> } <ide> <ide> /** <ide><path>src/Auth/BaseAuthorize.php <ide> abstract class BaseAuthorize <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> { <ide> $this->_registry = $registry; <del> $this->config($config); <add> $this->setConfig($config); <ide> } <ide> <ide> /** <ide><path>src/Auth/BasicAuthenticate.php <ide> public function unauthenticated(ServerRequest $request, Response $response) <ide> */ <ide> public function loginHeaders(ServerRequest $request) <ide> { <del> $realm = $this->config('realm') ?: $request->env('SERVER_NAME'); <add> $realm = $this->getConfig('realm') ?: $request->env('SERVER_NAME'); <ide> <ide> return sprintf('WWW-Authenticate: Basic realm="%s"', $realm); <ide> } <ide><path>src/Auth/DigestAuthenticate.php <ide> class DigestAuthenticate extends BasicAuthenticate <ide> */ <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> { <del> $this->config([ <add> $this->setConfig([ <ide> 'nonceLifetime' => 300, <ide> 'secret' => Configure::read('Security.salt'), <ide> 'realm' => null, <ide> public function loginHeaders(ServerRequest $request) <ide> */ <ide> protected function generateNonce() <ide> { <del> $expiryTime = microtime(true) + $this->config('nonceLifetime'); <del> $signatureValue = md5($expiryTime . ':' . $this->config('secret')); <add> $expiryTime = microtime(true) + $this->getConfig('nonceLifetime'); <add> $signatureValue = md5($expiryTime . ':' . $this->getConfig('secret')); <ide> $nonceValue = $expiryTime . ':' . $signatureValue; <ide> <ide> return base64_encode($nonceValue); <ide> protected function validNonce($nonce) <ide> return false; <ide> } <ide> <del> return md5($expires . ':' . $this->config('secret')) === $checksum; <add> return md5($expires . ':' . $this->getConfig('secret')) === $checksum; <ide> } <ide> } <ide><path>src/Auth/Storage/SessionStorage.php <ide> class SessionStorage implements StorageInterface <ide> public function __construct(ServerRequest $request, Response $response, array $config = []) <ide> { <ide> $this->_session = $request->session(); <del> $this->config($config); <add> $this->setConfig($config); <ide> } <ide> <ide> /** <ide><path>src/Cache/Cache.php <ide> protected static function _buildEngine($name) <ide> $registry->load($name, $config); <ide> <ide> if ($config['className'] instanceof CacheEngine) { <del> $config = $config['className']->config(); <add> $config = $config['className']->getConfig(); <ide> } <ide> <ide> if (!empty($config['groups'])) { <ide><path>src/Cache/CacheEngine.php <ide> abstract class CacheEngine <ide> */ <ide> public function init(array $config = []) <ide> { <del> $this->config($config); <add> $this->setConfig($config); <ide> <ide> if (!empty($this->_config['groups'])) { <ide> sort($this->_config['groups']); <ide><path>src/Cache/CacheRegistry.php <ide> protected function _create($class, $alias, $config) <ide> ); <ide> } <ide> <del> $config = $instance->config(); <add> $config = $instance->getConfig(); <ide> if ($config['probability'] && time() % $config['probability'] === 0) { <ide> $instance->gc(); <ide> } <ide><path>src/Cache/Engine/MemcachedEngine.php <ide> public function init(array $config = []) <ide> } <ide> <ide> if (isset($config['servers'])) { <del> $this->config('servers', $config['servers'], false); <add> $this->setConfig('servers', $config['servers'], false); <ide> } <ide> <ide> if (!is_array($this->_config['servers'])) { <ide><path>src/Console/Helper.php <ide> abstract class Helper <ide> public function __construct(ConsoleIo $io, array $config = []) <ide> { <ide> $this->_io = $io; <del> $this->config($config); <add> $this->setConfig($config); <ide> } <ide> <ide> /** <ide><path>src/Controller/Component.php <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> $this->response =& $controller->response; <ide> } <ide> <del> $this->config($config); <add> $this->setConfig($config); <ide> <ide> if ($this->components) { <ide> $this->_componentMap = $registry->normalizeArray($this->components); <ide> public function __debugInfo() <ide> return [ <ide> 'components' => $this->components, <ide> 'implementedEvents' => $this->implementedEvents(), <del> '_config' => $this->config(), <add> '_config' => $this->getConfig(), <ide> ]; <ide> } <ide> } <ide><path>src/Controller/Component/AuthComponent.php <ide> class AuthComponent extends Component <ide> * when users are identified. <ide> * <ide> * ``` <del> * $this->Auth->config('authenticate', [ <add> * $this->Auth->setConfig('authenticate', [ <ide> * 'Form' => [ <ide> * 'userModel' => 'Users.Users' <ide> * ] <ide> class AuthComponent extends Component <ide> * config that should be set to all authentications objects using the 'all' key: <ide> * <ide> * ``` <del> * $this->Auth->config('authenticate', [ <add> * $this->Auth->setConfig('authenticate', [ <ide> * AuthComponent::ALL => [ <ide> * 'userModel' => 'Users.Users', <ide> * 'scope' => ['Users.active' => 1] <ide> class AuthComponent extends Component <ide> * when authorization checks are done. <ide> * <ide> * ``` <del> * $this->Auth->config('authorize', [ <add> * $this->Auth->setConfig('authorize', [ <ide> * 'Crud' => [ <ide> * 'actionPath' => 'controllers/' <ide> * ] <ide> class AuthComponent extends Component <ide> * that should be set to all authorization objects using the AuthComponent::ALL key: <ide> * <ide> * ``` <del> * $this->Auth->config('authorize', [ <add> * $this->Auth->setConfig('authorize', [ <ide> * AuthComponent::ALL => [ <ide> * 'actionPath' => 'controllers/' <ide> * ], <ide> protected function _setDefaults() <ide> 'authError' => __d('cake', 'You are not authorized to access that location.') <ide> ]; <ide> <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> foreach ($config as $key => $value) { <ide> if ($value !== null) { <ide> unset($defaults[$key]); <ide> } <ide> } <del> $this->config($defaults); <add> $this->setConfig($defaults); <ide> } <ide> <ide> /** <ide> public function storage(StorageInterface $storage = null) <ide> public function __get($name) <ide> { <ide> if ($name === 'sessionKey') { <del> return $this->storage()->config('key'); <add> return $this->storage()->getConfig('key'); <ide> } <ide> <ide> return parent::__get($name); <ide> public function __set($name, $value) <ide> $this->_storage = null; <ide> <ide> if ($value === false) { <del> $this->config('storage', 'Memory'); <add> $this->setConfig('storage', 'Memory'); <ide> <ide> return; <ide> } <ide> <del> $this->config('storage', 'Session'); <del> $this->storage()->config('key', $value); <add> $this->setConfig('storage', 'Session'); <add> $this->storage()->setConfig('key', $value); <ide> <ide> return; <ide> } <ide><path>src/Controller/Component/CookieComponent.php <ide> class CookieComponent extends Component <ide> public function initialize(array $config) <ide> { <ide> if (!$this->_config['key']) { <del> $this->config('key', Security::salt()); <add> $this->setConfig('key', Security::salt()); <ide> } <ide> <ide> $controller = $this->_registry->getController(); <ide> public function initialize(array $config) <ide> } <ide> <ide> if (empty($this->_config['path'])) { <del> $this->config('path', $this->request->webroot); <add> $this->setConfig('path', $this->request->webroot); <ide> } <ide> } <ide> <ide><path>src/Controller/Component/FlashComponent.php <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> */ <ide> public function set($message, array $options = []) <ide> { <del> $options += $this->config(); <add> $options += $this->getConfig(); <ide> <ide> if ($message instanceof Exception) { <ide> if (!isset($options['params']['code'])) { <ide><path>src/Controller/Component/PaginatorComponent.php <ide> public function getDefaults($alias, $settings) <ide> $settings = $settings[$alias]; <ide> } <ide> <del> $defaults = $this->config(); <add> $defaults = $this->getConfig(); <ide> $maxLimit = isset($settings['maxLimit']) ? $settings['maxLimit'] : $defaults['maxLimit']; <ide> $limit = isset($settings['limit']) ? $settings['limit'] : $defaults['limit']; <ide> <ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> protected function _setExtension($request, $response) <ide> } <ide> <ide> $extensions = array_unique( <del> array_merge(Router::extensions(), array_keys($this->config('viewClassMap'))) <add> array_merge(Router::extensions(), array_keys($this->getConfig('viewClassMap'))) <ide> ); <ide> foreach ($accepts as $types) { <ide> $ext = array_intersect($extensions, $types); <ide> public function startup(Event $event) <ide> return; <ide> } <ide> <del> foreach ($this->config('inputTypeMap') as $type => $handler) { <add> foreach ($this->getConfig('inputTypeMap') as $type => $handler) { <ide> if (!is_callable($handler[0])) { <ide> throw new RuntimeException(sprintf("Invalid callable for '%s' type.", $type)); <ide> } <ide> public function convertXml($xml) <ide> */ <ide> public function beforeRedirect(Event $event, $url, Response $response) <ide> { <del> if (!$this->config('enableBeforeRedirect')) { <add> if (!$this->getConfig('enableBeforeRedirect')) { <ide> return null; <ide> } <ide> $request = $this->request; <ide> public function prefers($type = null) <ide> public function renderAs(Controller $controller, $type, array $options = []) <ide> { <ide> $defaults = ['charset' => 'UTF-8']; <del> $viewClassMap = $this->config('viewClassMap'); <add> $viewClassMap = $this->getConfig('viewClassMap'); <ide> <ide> if (Configure::read('App.encoding') !== null) { <ide> $defaults['charset'] = Configure::read('App.encoding'); <ide> public function mapAlias($alias) <ide> * for the handler. <ide> * @return void <ide> * @throws \Cake\Core\Exception\Exception <del> * @deprecated 3.1.0 Use config('addInputType', ...) instead. <add> * @deprecated 3.1.0 Use setConfig('addInputType', ...) instead. <ide> */ <ide> public function addInputType($type, $handler) <ide> { <ide> trigger_error( <del> 'RequestHandlerComponent::addInputType() is deprecated. Use config("inputTypeMap", ...) instead.', <add> 'RequestHandlerComponent::addInputType() is deprecated. Use setConfig("inputTypeMap", ...) instead.', <ide> E_USER_DEPRECATED <ide> ); <ide> if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) { <ide> throw new Exception('You must give a handler callback.'); <ide> } <del> $this->config('inputTypeMap.' . $type, $handler); <add> $this->setConfig('inputTypeMap.' . $type, $handler); <ide> } <ide> <ide> /** <ide> public function addInputType($type, $handler) <ide> * @param array|string|null $type The type string or array with format `['type' => 'viewClass']` to map one or more <ide> * @param array|null $viewClass The viewClass to be used for the type without `View` appended <ide> * @return array|string Returns viewClass when only string $type is set, else array with viewClassMap <del> * @deprecated 3.1.0 Use config('viewClassMap', ...) instead. <add> * @deprecated 3.1.0 Use setConfig('viewClassMap', ...) instead. <ide> */ <ide> public function viewClassMap($type = null, $viewClass = null) <ide> { <ide> trigger_error( <del> 'RequestHandlerComponent::viewClassMap() is deprecated. Use config("viewClassMap", ...) instead.', <add> 'RequestHandlerComponent::viewClassMap() is deprecated. Use setConfig("viewClassMap", ...) instead.', <ide> E_USER_DEPRECATED <ide> ); <ide> if (!$viewClass && is_string($type)) { <del> return $this->config('viewClassMap.' . $type); <add> return $this->getConfig('viewClassMap.' . $type); <ide> } <ide> if (is_string($type)) { <del> $this->config('viewClassMap.' . $type, $viewClass); <add> $this->setConfig('viewClassMap.' . $type, $viewClass); <ide> } elseif (is_array($type)) { <del> $this->config('viewClassMap', $type, true); <add> $this->setConfig('viewClassMap', $type, true); <ide> } <ide> <del> return $this->config('viewClassMap'); <add> return $this->getConfig('viewClassMap'); <ide> } <ide> } <ide><path>src/Controller/Component/SecurityComponent.php <ide> protected function _requireMethod($method, $actions = []) <ide> if (isset($actions[0]) && is_array($actions[0])) { <ide> $actions = $actions[0]; <ide> } <del> $this->config('require' . $method, (empty($actions)) ? ['*'] : $actions); <add> $this->setConfig('require' . $method, (empty($actions)) ? ['*'] : $actions); <ide> } <ide> <ide> /** <ide> protected function _fieldsList(array $check) <ide> } <ide> <ide> $unlockedFields = array_unique( <del> array_merge((array)$this->config('disabledFields'), (array)$this->_config['unlockedFields'], $unlocked) <add> array_merge((array)$this->getConfig('disabledFields'), (array)$this->_config['unlockedFields'], $unlocked) <ide> ); <ide> <ide> foreach ($fieldList as $i => $key) { <ide><path>src/Core/ObjectRegistry.php <ide> protected function _checkDuplicate($name, $config) <ide> if (empty($config)) { <ide> return; <ide> } <del> $existingConfig = $existing->config(); <add> $existingConfig = $existing->getConfig(); <ide> unset($config['enabled'], $existingConfig['enabled']); <ide> <ide> $fail = false; <ide><path>src/Error/Debugger.php <ide> public static function getInstance($class = null) <ide> public static function configInstance($key = null, $value = null, $merge = true) <ide> { <ide> if (is_array($key) || func_num_args() >= 2) { <del> return static::getInstance()->config($key, $value, $merge); <add> return static::getInstance()->setConfig($key, $value, $merge); <ide> } <ide> <del> return static::getInstance()->config($key); <add> return static::getInstance()->getConfig($key); <ide> } <ide> <ide> /** <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php <ide> public function __construct($exceptionRenderer = null, array $config = []) <ide> } <ide> <ide> $config = $config ?: Configure::read('Error'); <del> $this->config($config); <add> $this->setConfig($config); <ide> } <ide> <ide> /** <ide> public function handleException($exception, $request, $response) <ide> protected function getRenderer($exception) <ide> { <ide> if (!$this->exceptionRenderer) { <del> $this->exceptionRenderer = $this->config('exceptionRenderer') ?: ExceptionRenderer::class; <add> $this->exceptionRenderer = $this->getConfig('exceptionRenderer') ?: ExceptionRenderer::class; <ide> } <ide> <ide> if (is_string($this->exceptionRenderer)) { <ide> protected function getRenderer($exception) <ide> */ <ide> protected function logException($request, $exception) <ide> { <del> if (!$this->config('log')) { <add> if (!$this->getConfig('log')) { <ide> return; <ide> } <ide> <del> $skipLog = $this->config('skipLog'); <add> $skipLog = $this->getConfig('skipLog'); <ide> if ($skipLog) { <ide> foreach ((array)$skipLog as $class) { <ide> if ($exception instanceof $class) { <ide> protected function getMessage($request, $exception) <ide> if ($referer) { <ide> $message .= "\nReferer URL: " . $referer; <ide> } <del> if ($this->config('trace')) { <add> if ($this->getConfig('trace')) { <ide> $message .= "\nStack Trace:\n" . $exception->getTraceAsString() . "\n\n"; <ide> } <ide> <ide><path>src/Http/Client.php <ide> class Client <ide> */ <ide> public function __construct($config = []) <ide> { <del> $this->config($config); <add> $this->setConfig($config); <ide> <ide> $adapter = $this->_config['adapter']; <del> $this->config('adapter', null); <add> $this->setConfig('adapter', null); <ide> if (is_string($adapter)) { <ide> $adapter = new $adapter(); <ide> } <ide> $this->_adapter = $adapter; <ide> <ide> if (!empty($this->_config['cookieJar'])) { <ide> $this->_cookies = $this->_config['cookieJar']; <del> $this->config('cookieJar', null); <add> $this->setConfig('cookieJar', null); <ide> } else { <ide> $this->_cookies = new CookieCollection(); <ide> } <ide><path>src/Log/Engine/BaseLog.php <ide> abstract class BaseLog extends AbstractLogger <ide> */ <ide> public function __construct(array $config = []) <ide> { <del> $this->config($config); <add> $this->setConfig($config); <ide> <ide> if (!is_array($this->_config['scopes']) && $this->_config['scopes'] !== false) { <ide> $this->_config['scopes'] = (array)$this->_config['scopes']; <ide><path>src/Mailer/AbstractTransport.php <ide> abstract public function send(Email $email); <ide> */ <ide> public function __construct($config = []) <ide> { <del> $this->config($config); <add> $this->setConfig($config); <ide> } <ide> <ide> /** <ide><path>src/Network/Socket.php <ide> class Socket <ide> */ <ide> public function __construct(array $config = []) <ide> { <del> $this->config($config); <add> $this->setConfig($config); <ide> } <ide> <ide> /** <ide><path>src/ORM/Behavior.php <ide> public function __construct(Table $table, array $config = []) <ide> $config <ide> ); <ide> $this->_table = $table; <del> $this->config($config); <add> $this->setConfig($config); <ide> $this->initialize($config); <ide> } <ide> <ide> protected function _resolveMethodAliases($key, $defaults, $config) <ide> return $config; <ide> } <ide> if (isset($config[$key]) && $config[$key] === []) { <del> $this->config($key, [], false); <add> $this->setConfig($key, [], false); <ide> unset($config[$key]); <ide> <ide> return $config; <ide> protected function _resolveMethodAliases($key, $defaults, $config) <ide> $indexedCustom[$method] = $alias; <ide> } <ide> } <del> $this->config($key, array_flip($indexedCustom), false); <add> $this->setConfig($key, array_flip($indexedCustom), false); <ide> unset($config[$key]); <ide> <ide> return $config; <ide> public function implementedEvents() <ide> 'Model.beforeRules' => 'beforeRules', <ide> 'Model.afterRules' => 'afterRules', <ide> ]; <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $priority = isset($config['priority']) ? $config['priority'] : null; <ide> $events = []; <ide> <ide> public function implementedEvents() <ide> */ <ide> public function implementedFinders() <ide> { <del> $methods = $this->config('implementedFinders'); <add> $methods = $this->getConfig('implementedFinders'); <ide> if (isset($methods)) { <ide> return $methods; <ide> } <ide> public function implementedFinders() <ide> */ <ide> public function implementedMethods() <ide> { <del> $methods = $this->config('implementedMethods'); <add> $methods = $this->getConfig('implementedMethods'); <ide> if (isset($methods)) { <ide> return $methods; <ide> } <ide><path>src/ORM/Behavior/TimestampBehavior.php <ide> class TimestampBehavior extends Behavior <ide> public function initialize(array $config) <ide> { <ide> if (isset($config['events'])) { <del> $this->config('events', $config['events'], false); <add> $this->setConfig('events', $config['events'], false); <ide> } <ide> } <ide> <ide><path>src/ORM/Behavior/TranslateBehavior.php <ide> public function beforeFind(Event $event, Query $query, $options) <ide> { <ide> $locale = $this->locale(); <ide> <del> if ($locale === $this->config('defaultLocale')) { <add> if ($locale === $this->getConfig('defaultLocale')) { <ide> return; <ide> } <ide> <ide> public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $o <ide> <ide> // No additional translation records need to be saved, <ide> // as the entity is in the default locale. <del> if ($noBundled && $locale === $this->config('defaultLocale')) { <add> if ($noBundled && $locale === $this->getConfig('defaultLocale')) { <ide> return; <ide> } <ide> <ide><path>src/ORM/Behavior/TreeBehavior.php <ide> public function initialize(array $config) <ide> public function beforeSave(Event $event, EntityInterface $entity) <ide> { <ide> $isNew = $entity->isNew(); <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $parent = $entity->get($config['parent']); <ide> $primaryKey = $this->_getPrimaryKey(); <ide> $dirty = $entity->dirty($config['parent']); <ide> public function afterSave(Event $event, EntityInterface $entity) <ide> */ <ide> protected function _setChildrenLevel($entity) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> <ide> if ($entity->get($config['left']) + 1 === $entity->get($config['right'])) { <ide> return; <ide> protected function _setChildrenLevel($entity) <ide> */ <ide> public function beforeDelete(Event $event, EntityInterface $entity) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $this->_ensureFields($entity); <ide> $left = $entity->get($config['left']); <ide> $right = $entity->get($config['right']); <ide> public function beforeDelete(Event $event, EntityInterface $entity) <ide> */ <ide> protected function _setParent($entity, $parent) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $parentNode = $this->_getNode($parent); <ide> $this->_ensureFields($entity); <ide> $parentLeft = $parentNode->get($config['left']); <ide> protected function _setParent($entity, $parent) <ide> */ <ide> protected function _setAsRoot($entity) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $edge = $this->_getMax(); <ide> $this->_ensureFields($entity); <ide> $right = $entity->get($config['right']); <ide> protected function _setAsRoot($entity) <ide> */ <ide> protected function _unmarkInternalTree() <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $this->_table->updateAll( <ide> function ($exp) use ($config) { <ide> $leftInverse = clone $exp; <ide> public function findPath(Query $query, array $options) <ide> throw new InvalidArgumentException("The 'for' key is required for find('path')"); <ide> } <ide> <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> list($left, $right) = array_map( <ide> function ($field) { <ide> return $this->_table->aliasField($field); <ide> function ($field) { <ide> */ <ide> public function childCount(EntityInterface $node, $direct = false) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $parent = $this->_table->aliasField($config['parent']); <ide> <ide> if ($direct) { <ide> public function childCount(EntityInterface $node, $direct = false) <ide> */ <ide> public function findChildren(Query $query, array $options) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $options += ['for' => null, 'direct' => false]; <ide> list($parent, $left, $right) = array_map( <ide> function ($field) { <ide> function ($field) { <ide> */ <ide> public function findTreeList(Query $query, array $options) <ide> { <del> $left = $this->_table->aliasField($this->config('left')); <add> $left = $this->_table->aliasField($this->getConfig('left')); <ide> <ide> $results = $this->_scope($query) <ide> ->find('threaded', [ <del> 'parentField' => $this->config('parent'), <add> 'parentField' => $this->getConfig('parent'), <ide> 'order' => [$left => 'ASC'], <ide> ]); <ide> <ide> public function removeFromTree(EntityInterface $node) <ide> */ <ide> protected function _removeFromTree($node) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $left = $node->get($config['left']); <ide> $right = $node->get($config['right']); <ide> $parent = $node->get($config['parent']); <ide> public function moveUp(EntityInterface $node, $number = 1) <ide> */ <ide> protected function _moveUp($node, $number) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']]; <ide> list($nodeParent, $nodeLeft, $nodeRight) = array_values($node->extract([$parent, $left, $right])); <ide> <ide> public function moveDown(EntityInterface $node, $number = 1) <ide> */ <ide> protected function _moveDown($node, $number) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']]; <ide> list($nodeParent, $nodeLeft, $nodeRight) = array_values($node->extract([$parent, $left, $right])); <ide> <ide> protected function _moveDown($node, $number) <ide> */ <ide> protected function _getNode($id) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']]; <ide> $primaryKey = $this->_getPrimaryKey(); <ide> $fields = [$parent, $left, $right]; <ide> public function recover() <ide> */ <ide> protected function _recoverTree($counter = 0, $parentId = null, $level = -1) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']]; <ide> $primaryKey = $this->_getPrimaryKey(); <ide> $aliasedPrimaryKey = $this->_table->aliasField($primaryKey); <ide> protected function _sync($shift, $dir, $conditions, $mark = false) <ide> */ <ide> protected function _scope($query) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> <ide> if (is_array($config['scope'])) { <ide> return $query->where($config['scope']); <ide> protected function _scope($query) <ide> */ <ide> protected function _ensureFields($entity) <ide> { <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $fields = [$config['left'], $config['right']]; <ide> $values = array_filter($entity->extract($fields)); <ide> if (count($values) === count($fields)) { <ide> public function getLevel($entity) <ide> if ($entity instanceof EntityInterface) { <ide> $id = $entity->get($primaryKey); <ide> } <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $entity = $this->_table->find('all') <ide> ->select([$config['left'], $config['right']]) <ide> ->where([$primaryKey => $id]) <ide><path>src/ORM/LazyEagerLoader.php <ide> protected function _getQuery($objects, $contain, $source) <ide> ->contain($contain); <ide> <ide> foreach ($query->getEagerLoader()->attachableAssociations($source) as $loadable) { <del> $config = $loadable->config(); <add> $config = $loadable->getConfig(); <ide> $config['includeFields'] = true; <del> $loadable->config($config); <add> $loadable->setConfig($config); <ide> } <ide> <ide> return $query; <ide><path>src/Routing/DispatcherFilter.php <ide> public function __construct($config = []) <ide> if (!isset($config['priority'])) { <ide> $config['priority'] = $this->_priority; <ide> } <del> $this->config($config); <add> $this->setConfig($config); <ide> if (isset($config['when']) && !is_callable($config['when'])) { <ide> throw new InvalidArgumentException('"when" conditions must be a callable.'); <ide> } <ide><path>src/Shell/Helper/TableHelper.php <ide> public function output($rows) <ide> return; <ide> } <ide> <del> $config = $this->config(); <add> $config = $this->getConfig(); <ide> $widths = $this->_calculateWidths($rows); <ide> <ide> $this->_rowSeparator($widths); <ide><path>src/View/Helper.php <ide> public function __construct(View $View, array $config = []) <ide> $this->_View = $View; <ide> $this->request = $View->request; <ide> <del> $this->config($config); <add> $this->setConfig($config); <ide> <ide> if (!empty($this->helpers)) { <ide> $this->_helperMap = $View->helpers()->normalizeArray($this->helpers); <ide> public function __debugInfo() <ide> 'fieldset' => $this->fieldset, <ide> 'tags' => $this->tags, <ide> 'implementedEvents' => $this->implementedEvents(), <del> '_config' => $this->config(), <add> '_config' => $this->getConfig(), <ide> ]; <ide> } <ide> } <ide><path>src/View/Helper/FormHelper.php <ide> public function __construct(View $View, array $config = []) <ide> <ide> $this->widgetRegistry($registry, $widgets); <ide> $this->_addDefaultContextProviders(); <del> $this->_idPrefix = $this->config('idPrefix'); <add> $this->_idPrefix = $this->getConfig('idPrefix'); <ide> } <ide> <ide> /** <ide> public function end(array $secureAttributes = []) <ide> $this->requestType = null; <ide> $this->_context = null; <ide> $this->_valueSources = ['context']; <del> $this->_idPrefix = $this->config('idPrefix'); <add> $this->_idPrefix = $this->getConfig('idPrefix'); <ide> <ide> return $out; <ide> } <ide><path>src/View/Helper/PaginatorHelper.php <ide> public function __construct(View $View, array $config = []) <ide> <ide> $query = $this->request->getQueryParams(); <ide> unset($query['page'], $query['limit'], $query['sort'], $query['direction']); <del> $this->config( <add> $this->setConfig( <ide> 'options.url', <ide> array_merge($this->request->getParam('pass'), ['?' => $query]) <ide> ); <ide><path>src/View/Helper/TimeHelper.php <ide> protected function _getTimezone($timezone) <ide> return $timezone; <ide> } <ide> <del> return $this->config('outputTimezone'); <add> return $this->getConfig('outputTimezone'); <ide> } <ide> <ide> /** <ide><path>src/View/StringTemplate.php <ide> public function pop() <ide> */ <ide> public function add(array $templates) <ide> { <del> $this->config($templates); <add> $this->setConfig($templates); <ide> $this->_compileTemplates(array_keys($templates)); <ide> <ide> return $this; <ide> public function load($file) <ide> */ <ide> public function remove($name) <ide> { <del> $this->config($name, null); <add> $this->setConfig($name, null); <ide> unset($this->_compiled[$name]); <ide> } <ide> <ide><path>src/View/StringTemplateTrait.php <ide> public function formatTemplate($name, $data) <ide> public function templater() <ide> { <ide> if ($this->_templater === null) { <del> $class = $this->config('templateClass') ?: 'Cake\View\StringTemplate'; <add> $class = $this->getConfig('templateClass') ?: 'Cake\View\StringTemplate'; <ide> $this->_templater = new $class(); <ide> <del> $templates = $this->config('templates'); <add> $templates = $this->getConfig('templates'); <ide> if ($templates) { <ide> if (is_string($templates)) { <ide> $this->_templater->add($this->_defaultConfig['templates']);
38
Ruby
Ruby
remove duplicated tests
50ec25b506116063d1b7f0da0777d1dbc5380f93
<ide><path>activemodel/test/cases/errors_test.rb <ide> def test_each_when_arity_is_negative <ide> def test_any? <ide> errors = ActiveModel::Errors.new(Person.new) <ide> errors.add(:name) <del> assert_not_deprecated { <del> assert errors.any?, "any? should return true" <del> } <del> assert_not_deprecated { <del> assert errors.any? { |_| true }, "any? should return true" <del> } <add> assert errors.any?, "any? should return true" <add> assert errors.any? { |_| true }, "any? should return true" <ide> end <ide> <ide> def test_first <ide> def test_no_key <ide> assert_equal ["cannot be nil"], person.errors[:name] <ide> end <ide> <del> test "add an error message on a specific attribute (deprecated)" do <del> person = Person.new <del> person.errors.add(:name, "cannot be blank") <del> assert_equal ["cannot be blank"], person.errors[:name] <del> end <del> <del> test "add an error message on a specific attribute with a defined type (deprecated)" do <del> person = Person.new <del> person.errors.add(:name, :blank, message: "cannot be blank") <del> assert_equal ["cannot be blank"], person.errors[:name] <del> end <del> <del> test "add an error with a symbol (deprecated)" do <del> person = Person.new <del> person.errors.add(:name, :blank) <del> message = person.errors.generate_message(:name, :blank) <del> assert_equal [message], person.errors[:name] <del> end <del> <del> test "add an error with a proc (deprecated)" do <del> person = Person.new <del> message = Proc.new { "cannot be blank" } <del> person.errors.add(:name, message) <del> assert_equal ["cannot be blank"], person.errors[:name] <del> end <del> <ide> test "add creates an error object and returns it" do <ide> person = Person.new <ide> error = person.errors.add(:name, :blank) <ide> def test_no_key <ide> assert_equal ["can't be blank"], person.errors[:name] <ide> end <ide> <add> test "add an error message on a specific attribute with a defined type" do <add> person = Person.new <add> person.errors.add(:name, :blank, message: "cannot be blank") <add> assert_equal ["cannot be blank"], person.errors[:name] <add> end <add> <ide> test "initialize options[:message] as Proc, which evaluates to String" do <ide> msg = "custom msg" <ide> type = Proc.new { msg } <ide> def call <ide> assert_empty person.errors.details <ide> end <ide> <del> test "copy errors (deprecated)" do <del> errors = ActiveModel::Errors.new(Person.new) <del> errors.add(:name, :invalid) <del> person = Person.new <del> person.errors.copy!(errors) <del> <del> assert_equal [:name], person.errors.messages.keys <del> assert_equal [:name], person.errors.details.keys <del> end <del> <ide> test "details returns empty array when accessed with non-existent attribute" do <ide> errors = ActiveModel::Errors.new(Person.new) <ide> <ide> def call <ide> end <ide> end <ide> <del> test "merge errors (deprecated)" do <del> errors = ActiveModel::Errors.new(Person.new) <del> errors.add(:name, :invalid) <del> <del> person = Person.new <del> person.errors.add(:name, :blank) <del> person.errors.merge!(errors) <del> <del> assert_equal({ name: ["can't be blank", "is invalid"] }, person.errors.messages) <del> assert_equal({ name: [{ error: :blank }, { error: :invalid }] }, person.errors.details) <del> end <del> <ide> test "merge errors" do <ide> errors = ActiveModel::Errors.new(Person.new) <ide> errors.add(:name, :invalid)
1
Text
Text
add some thoughts from #134
d925a045fdd8dcd39ee3ec6a2387769b49cc3e52
<ide><path>README.md <ide> Atomic Flux with hot reloading. <ide> - [But there are switch statements!](#but-there-are-switch-statements) <ide> - [What about `waitFor`?](#what-about-waitfor) <ide> - [My views aren't updating!](#my-views-arent-updating) <add> - [How do Stores, Actions and Components interact?](#how-do-stores-actions-and-components-interact) <ide> - [Discussion](#discussion) <ide> - [Inspiration and Thanks](#inspiration-and-thanks) <ide> <ide> function (state, action) { <ide> <ide> [Read more](https://github.com/sebmarkbage/ecmascript-rest-spread) about the spread properties ES7 proposal. <ide> <add>### How do Stores, Actions and Components interact? <add> <add>Action creators are just pure functions so they don't interact with anything. Components need to call `dispatch(action)` (or use `bindActionCreators` that wraps it) to dispatch an action *returned* by the action creator. <add> <add>Stores are just pure functions too so they don't need to be “registered” in the traditional sense, and you can't subscribe to them directly. They're just descriptions of how data transforms. So in that sense they don't “interact” with anything either, they just exist, and are used by the dispatcher for computation of the next state. <add> <add>Now, the dispatcher is more interesting. You pass all the Stores to it, and it composes them into a single Store function that it uses for computation. The dispatcher is also a pure function, and it is passed as configuration to `createRedux`, the only stateful thing in Redux. By default, the default dispatcher is used, so if you call `createRedux(stores)`, it is created implicitly. <add> <add>To sum it up: there is a Redux instance at the root of your app. It binds everything together. It accepts a dispatcher (which itself accepts Stores), it holds the state, and it knows how to turn actions into state updates. Everything else (components, for example) subscribes to the Redux instance. If something wants to dispatch an action, they need to do it on the Redux instance. `Connector` is a handy shortcut for subscribing to a slice of the Redux instance's state and injecting `dispatch` into your components, but you don't have to use it. <add> <add>There is no other “interaction” in Redux. <add> <ide> ## Discussion <ide> <ide> Join the **#redux** channel of the [Reactiflux](http://reactiflux.com/) Slack community
1
PHP
PHP
remove input data parsing code from requesthandler
28f843e91fffd35f564ae5206fc7bf5aed0b51b1
<ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <del>use Cake\Utility\Exception\XmlException; <ide> use Cake\Utility\Inflector; <del>use Cake\Utility\Xml; <del>use RuntimeException; <ide> <ide> /** <ide> * Request object handling for alternative HTTP requests. <ide> class RequestHandlerComponent extends Component <ide> * - `checkHttpCache` - Whether to check for HTTP cache. Default `true`. <ide> * - `viewClassMap` - Mapping between type and view classes. If undefined <ide> * json, xml, and ajax will be mapped. Defining any types will omit the defaults. <del> * - `inputTypeMap` - A mapping between types and deserializers for request bodies. <del> * If undefined json & xml will be mapped. Defining any types will omit the defaults. <ide> * <ide> * @var array <ide> */ <ide> protected $_defaultConfig = [ <ide> 'checkHttpCache' => true, <ide> 'viewClassMap' => [], <del> 'inputTypeMap' => [], <ide> ]; <ide> <ide> /** <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> 'xml' => 'Xml', <ide> 'ajax' => 'Ajax', <ide> ], <del> 'inputTypeMap' => [ <del> 'json' => ['json_decode', true], <del> 'xml' => [[$this, 'convertXml']], <del> ], <ide> ]; <ide> parent::__construct($registry, $config); <ide> } <ide> public function startup(EventInterface $event): void <ide> if (!$this->ext && $isAjax) { <ide> $this->ext = 'ajax'; <ide> } <del> <del> if ($request->is(['get', 'head', 'options'])) { <del> return; <del> } <del> <del> if ($request->getParsedBody() !== []) { <del> return; <del> } <del> <del> foreach ($this->getConfig('inputTypeMap') as $type => $handler) { <del> if (!is_callable($handler[0])) { <del> throw new RuntimeException(sprintf("Invalid callable for '%s' type.", $type)); <del> } <del> if ($this->requestedWith($type)) { <del> $input = $request->input(...$handler); <del> $controller->setRequest($request->withParsedBody((array)$input)); <del> } <del> } <del> } <del> <del> /** <del> * Helper method to parse xml input data, due to lack of anonymous functions <del> * this lives here. <del> * <del> * @param string $xml XML string. <del> * @return array Xml array data <del> */ <del> public function convertXml(string $xml): array <del> { <del> try { <del> $xml = Xml::build($xml, ['return' => 'domdocument', 'readFile' => false]); <del> // We might not get child nodes if there are nested inline entities. <del> if ((int)$xml->childNodes->length > 0) { <del> return Xml::toArray($xml); <del> } <del> } catch (XmlException $e) { <del> } <del> <del> return []; <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> use TestApp\Controller\Component\RequestHandlerExtComponent; <ide> use TestApp\Controller\RequestHandlerTestController; <ide> use TestApp\View\AppView; <del>use Zend\Diactoros\Stream; <ide> <ide> /** <ide> * RequestHandlerComponentTest class <ide> */ <ide> class RequestHandlerComponentTest extends TestCase <ide> { <ide> /** <del> * @var RequestHandlerTestController <add> * @var \TestApp\Controller\RequestHandlerTestController <ide> */ <ide> public $Controller; <ide> <ide> class RequestHandlerComponentTest extends TestCase <ide> public $RequestHandler; <ide> <ide> /** <del> * @var ServerRequest <add> * @var \Cake\Http\ServerRequest <ide> */ <ide> public $request; <ide> <ide> public function testUnrecognizedExtensionFailure() <ide> $this->assertSame('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath()); <ide> } <ide> <del> /** <del> * testStartupCallback method <del> * <del> * @return void <del> * @triggers Controller.beforeRender $this->Controller <del> */ <del> public function testStartupCallback(): void <del> { <del> $event = new Event('Controller.beforeRender', $this->Controller); <del> $_SERVER['REQUEST_METHOD'] = 'PUT'; <del> $_SERVER['CONTENT_TYPE'] = 'application/xml'; <del> $this->Controller->setRequest(new ServerRequest()); <del> $this->RequestHandler->beforeRender($event); <del> $this->assertIsArray($this->Controller->getRequest()->getData()); <del> } <del> <del> /** <del> * testStartupCallback with charset. <del> * <del> * @return void <del> * @triggers Controller.startup $this->Controller <del> */ <del> public function testStartupCallbackCharset(): void <del> { <del> $event = new Event('Controller.startup', $this->Controller); <del> $_SERVER['REQUEST_METHOD'] = 'PUT'; <del> $_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8'; <del> $this->Controller->setRequest(new ServerRequest()); <del> $this->RequestHandler->startup($event); <del> $this->assertIsArray($this->Controller->getRequest()->getData()); <del> } <del> <del> /** <del> * Test that processing data results in an array. <del> * <del> * @return void <del> * @triggers Controller.startup $this->Controller <del> */ <del> public function testStartupProcessDataInvalid(): void <del> { <del> $this->Controller->setRequest(new ServerRequest([ <del> 'environment' => [ <del> 'REQUEST_METHOD' => 'POST', <del> 'CONTENT_TYPE' => 'application/json', <del> ], <del> ])); <del> <del> $event = new Event('Controller.startup', $this->Controller); <del> $this->RequestHandler->startup($event); <del> $this->assertEquals([], $this->Controller->getRequest()->getData()); <del> <del> $stream = new Stream('php://memory', 'w'); <del> $stream->write('"invalid"'); <del> $this->Controller->setRequest($this->Controller->getRequest()->withBody($stream)); <del> $this->RequestHandler->startup($event); <del> $this->assertEquals(['invalid'], $this->Controller->getRequest()->getData()); <del> } <del> <del> /** <del> * Test that processing data results in an array. <del> * <del> * @return void <del> * @triggers Controller.startup $this->Controller <del> */ <del> public function testStartupProcessData(): void <del> { <del> $this->Controller->setRequest(new ServerRequest([ <del> 'environment' => [ <del> 'REQUEST_METHOD' => 'POST', <del> 'CONTENT_TYPE' => 'application/json', <del> ], <del> ])); <del> <del> $stream = new Stream('php://memory', 'w'); <del> $stream->write('{"valid":true}'); <del> $this->Controller->setRequest($this->Controller->getRequest()->withBody($stream)); <del> $event = new Event('Controller.startup', $this->Controller); <del> <del> $this->RequestHandler->startup($event); <del> $this->assertEquals(['valid' => true], $this->Controller->getRequest()->getData()); <del> } <del> <del> /** <del> * Test that file handles are ignored as XML data. <del> * <del> * @return void <del> * @triggers Controller.startup $this->Controller <del> */ <del> public function testStartupIgnoreFileAsXml(): void <del> { <del> $this->Controller->setRequest(new ServerRequest([ <del> 'input' => '/dev/random', <del> 'environment' => [ <del> 'REQUEST_METHOD' => 'POST', <del> 'CONTENT_TYPE' => 'application/xml', <del> ], <del> ])); <del> <del> $event = new Event('Controller.startup', $this->Controller); <del> $this->RequestHandler->startup($event); <del> $this->assertEquals([], $this->Controller->getRequest()->getData()); <del> } <del> <del> /** <del> * Test that input xml is parsed <del> * <del> * @return void <del> */ <del> public function testStartupConvertXmlDataWrapper(): void <del> { <del> $xml = <<<XML <del><?xml version="1.0" encoding="utf-8"?> <del><data> <del><article id="1" title="first"></article> <del></data> <del>XML; <del> $this->Controller->setRequest((new ServerRequest(['input' => $xml])) <del> ->withEnv('REQUEST_METHOD', 'POST') <del> ->withEnv('CONTENT_TYPE', 'application/xml')); <del> <del> $event = new Event('Controller.startup', $this->Controller); <del> $this->RequestHandler->startup($event); <del> $expected = [ <del> 'data' => [ <del> 'article' => [ <del> '@id' => 1, <del> '@title' => 'first', <del> ], <del> ], <del> ]; <del> $this->assertEquals($expected, $this->Controller->getRequest()->getData()); <del> } <del> <del> /** <del> * Test that input xml is parsed <del> * <del> * @return void <del> */ <del> public function testStartupConvertXmlElements(): void <del> { <del> $xml = <<<XML <del><?xml version="1.0" encoding="utf-8"?> <del><article> <del> <id>1</id> <del> <title><![CDATA[first]]></title> <del></article> <del>XML; <del> $this->Controller->setRequest((new ServerRequest(['input' => $xml])) <del> ->withEnv('REQUEST_METHOD', 'POST') <del> ->withEnv('CONTENT_TYPE', 'application/xml')); <del> <del> $event = new Event('Controller.startup', $this->Controller); <del> $this->RequestHandler->startup($event); <del> $expected = [ <del> 'article' => [ <del> 'id' => 1, <del> 'title' => 'first', <del> ], <del> ]; <del> $this->assertEquals($expected, $this->Controller->getRequest()->getData()); <del> } <del> <del> /** <del> * Test that input xml is parsed <del> * <del> * @return void <del> */ <del> public function testStartupConvertXmlIgnoreEntities(): void <del> { <del> $xml = <<<XML <del><?xml version="1.0" encoding="UTF-8"?> <del><!DOCTYPE item [ <del> <!ENTITY item "item"> <del> <!ENTITY item1 "&item;&item;&item;&item;&item;&item;"> <del> <!ENTITY item2 "&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;"> <del> <!ENTITY item3 "&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;"> <del> <!ENTITY item4 "&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;"> <del> <!ENTITY item5 "&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;"> <del> <!ENTITY item6 "&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;"> <del> <!ENTITY item7 "&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;"> <del> <!ENTITY item8 "&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;"> <del>]> <del><item> <del> <description>&item8;</description> <del></item> <del>XML; <del> $this->Controller->setRequest((new ServerRequest(['input' => $xml])) <del> ->withEnv('REQUEST_METHOD', 'POST') <del> ->withEnv('CONTENT_TYPE', 'application/xml')); <del> <del> $event = new Event('Controller.startup', $this->Controller); <del> $this->RequestHandler->startup($event); <del> $this->assertEquals([], $this->Controller->getRequest()->getData()); <del> } <del> <del> /** <del> * Test that data isn't processed when parsed data already exists. <del> * <del> * @return void <del> * @triggers Controller.startup $this->Controller <del> */ <del> public function testStartupSkipDataProcess(): void <del> { <del> $this->Controller->setRequest(new ServerRequest([ <del> 'environment' => [ <del> 'REQUEST_METHOD' => 'POST', <del> 'CONTENT_TYPE' => 'application/json', <del> ], <del> ])); <del> <del> $event = new Event('Controller.startup', $this->Controller); <del> $this->RequestHandler->startup($event); <del> $this->assertEquals([], $this->Controller->getRequest()->getData()); <del> <del> $stream = new Stream('php://memory', 'w'); <del> $stream->write('{"new": "data"}'); <del> $this->Controller->setRequest($this->Controller->getRequest() <del> ->withBody($stream) <del> ->withParsedBody(['old' => 'news'])); <del> $this->RequestHandler->startup($event); <del> $this->assertEquals(['old' => 'news'], $this->Controller->getRequest()->getData()); <del> } <del> <ide> /** <ide> * testRenderAs method <ide> * <ide> public function testConstructDefaultOptions(): void <ide> 'ajax' => 'Ajax', <ide> ]; <ide> $this->assertEquals($expected, $viewClass); <del> <del> $inputs = $requestHandler->getConfig('inputTypeMap'); <del> $this->assertArrayHasKey('json', $inputs); <del> $this->assertArrayHasKey('xml', $inputs); <ide> } <ide> <ide> /**
2
Javascript
Javascript
restrict website to 3.0 models until 3.1 release
a13f29bb540ef832f56c364a71ddbd87c7a1c796
<ide><path>website/src/templates/models.js <ide> function isStableVersion(v) { <ide> <ide> function getLatestVersion(modelId, compatibility, prereleases) { <ide> for (let [version, models] of Object.entries(compatibility)) { <del> if (isStableVersion(version) && models[modelId]) { <add> if (version.startsWith('3.0') && isStableVersion(version) && models[modelId]) { <ide> const modelVersions = models[modelId] <ide> for (let modelVersion of modelVersions) { <ide> if (isStableVersion(modelVersion) || prereleases) {
1
Text
Text
add local option to message form [ci skip]
194a93385b08be857172b8eb6287d335c5adf1ea
<ide><path>activestorage/README.md <ide> end <ide> ``` <ide> <ide> ```erb <del><%= form_with model: @message do |form| %> <add><%= form_with model: @message, local: true do |form| %> <ide> <%= form.text_field :title, placeholder: "Title" %><br> <ide> <%= form.text_area :content %><br><br> <ide>
1
Text
Text
add clarification about object data structure
0770e8096649b89e17ea02b58ac87d477239234f
<ide><path>docs/docs/general/data-structures.md <ide> data: [{x:'Sales', y:20}, {x:'Revenue', y:10}] <ide> <ide> This is also the internal format used for parsed data. In this mode, parsing can be disabled by specifying `parsing: false` at chart options or dataset. If parsing is disabled, data must be sorted and in the formats the associated chart type and scales use internally. <ide> <add>The values provided must be parsable by the associated scales or in the internal format of the associated scales. A common mistake would be to provide integers for the `category` scale, which uses integers as an internal format, where each integer represents an index in the labels array. <add> <ide> ## Object[] using custom properties <ide> <ide> ```javascript
1
Java
Java
apply flatshadownode padding to view
312f04d2b782aeb3f9f6bd6c75a4c64e0a0f0b8e
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/AndroidView.java <ide> final ViewManager mViewManager; <ide> private final ReactShadowNode mReactShadowNode; <ide> private final boolean mNeedsCustomLayoutForChildren; <add> private boolean mPaddingChanged = false; <ide> <ide> /* package */ AndroidView(ViewManager viewManager) { <ide> mViewManager = viewManager; <ide> return mNeedsCustomLayoutForChildren; <ide> } <ide> <add> /* package */ boolean isPaddingChanged() { <add> return mPaddingChanged; <add> } <add> <add> /* package */ void resetPaddingChanged() { <add> mPaddingChanged = false; <add> } <add> <ide> @Override <ide> public void setBackgroundColor(int backgroundColor) { <ide> // suppress, this is handled by a ViewManager <ide> public void addChildAt(CSSNode child, int i) { <ide> super.addChildAt(child, i); <ide> ((FlatShadowNode) child).forceMountToView(); <ide> } <add> <add> @Override <add> public void setPadding(int spacingType, float padding) { <add> if (getPadding().set(spacingType, padding)) { <add> mPaddingChanged = true; <add> dirty(); <add> } <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatNativeViewHierarchyManager.java <ide> public void addRootView( <ide> } <ide> } <ide> <add> /* package */ void setPadding( <add> int reactTag, <add> int paddingLeft, <add> int paddingTop, <add> int paddingRight, <add> int paddingBottom) { <add> resolveView(reactTag).setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); <add> } <add> <ide> /* package */ void detachAllChildrenFromViews(int[] viewsToDetachAllChildrenFrom) { <ide> for (int viewTag : viewsToDetachAllChildrenFrom) { <ide> View view = resolveView(viewTag); <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIViewOperationQueue.java <ide> public void execute() { <ide> } <ide> } <ide> <add> private final class SetPadding implements UIOperation { <add> <add> private final int mReactTag; <add> private final int mPaddingLeft; <add> private final int mPaddingTop; <add> private final int mPaddingRight; <add> private final int mPaddingBottom; <add> <add> private SetPadding( <add> int reactTag, <add> int paddingLeft, <add> int paddingTop, <add> int paddingRight, <add> int paddingBottom) { <add> mReactTag = reactTag; <add> mPaddingLeft = paddingLeft; <add> mPaddingTop = paddingTop; <add> mPaddingRight = paddingRight; <add> mPaddingBottom = paddingBottom; <add> } <add> <add> @Override <add> public void execute() { <add> mNativeViewHierarchyManager.setPadding( <add> mReactTag, <add> mPaddingLeft, <add> mPaddingTop, <add> mPaddingRight, <add> mPaddingBottom); <add> } <add> } <add> <ide> public final class DetachAllChildrenFromViews implements UIViewOperationQueue.UIOperation { <ide> private @Nullable int[] mViewsToDetachAllChildrenFrom; <ide> <ide> public void enqueueUpdateViewBounds(int reactTag, int left, int top, int right, <ide> enqueueUIOperation(new UpdateViewBounds(reactTag, left, top, right, bottom)); <ide> } <ide> <add> public void enqueueSetPadding( <add> int reactTag, <add> int paddingLeft, <add> int paddingTop, <add> int paddingRight, <add> int paddingBottom) { <add> enqueueUIOperation( <add> new SetPadding(reactTag, paddingLeft, paddingTop, paddingRight, paddingBottom)); <add> } <add> <ide> public DetachAllChildrenFromViews enqueueDetachAllChildrenFromViews() { <ide> DetachAllChildrenFromViews op = new DetachAllChildrenFromViews(); <ide> enqueueUIOperation(op); <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/StateBuilder.java <ide> <ide> import javax.annotation.Nullable; <ide> <add>import com.facebook.csslayout.Spacing; <ide> import com.facebook.react.uimanager.CatalystStylesDiffMap; <ide> <ide> /** <ide> private void collectStateForMountableNode( <ide> boolean isAndroidView = false; <ide> boolean needsCustomLayoutForChildren = false; <ide> if (node instanceof AndroidView) { <add> AndroidView androidView = (AndroidView) node; <add> updateViewPadding(androidView, tag); <add> <ide> isAndroidView = true; <del> needsCustomLayoutForChildren = ((AndroidView) node).needsCustomLayoutForChildren(); <add> needsCustomLayoutForChildren = androidView.needsCustomLayoutForChildren(); <ide> } <ide> <ide> collectStateRecursively(node, 0, 0, width, height, isAndroidView, needsCustomLayoutForChildren); <ide> private static void updateNodeRegion( <ide> } <ide> } <ide> <add> private void updateViewPadding(AndroidView androidView, int tag) { <add> if (androidView.isPaddingChanged()) { <add> Spacing padding = androidView.getPadding(); <add> mOperationsQueue.enqueueSetPadding( <add> tag, <add> Math.round(padding.get(Spacing.LEFT)), <add> Math.round(padding.get(Spacing.TOP)), <add> Math.round(padding.get(Spacing.RIGHT)), <add> Math.round(padding.get(Spacing.BOTTOM))); <add> androidView.resetPaddingChanged(); <add> } <add> } <add> <ide> private static int[] collectViewTags(ArrayList<FlatShadowNode> views) { <ide> int numViews = views.size(); <ide> if (numViews == 0) {
4
Ruby
Ruby
permit hash on direct upload in active storage
bb148d822cd48688c836fb37ef47c51a150f5e42
<ide><path>activestorage/app/controllers/active_storage/direct_uploads_controller.rb <ide> def create <ide> <ide> private <ide> def blob_args <del> params.require(:blob).permit(:filename, :byte_size, :checksum, :content_type, :metadata).to_h.symbolize_keys <add> params.require(:blob).permit(:filename, :byte_size, :checksum, :content_type, metadata: {}).to_h.symbolize_keys <ide> end <ide> <ide> def direct_upload_json(blob) <ide><path>activestorage/test/controllers/direct_uploads_controller_test.rb <ide> class ActiveStorage::S3DirectUploadsControllerTest < ActionDispatch::Integration <ide> <ide> test "creating new direct upload" do <ide> checksum = Digest::MD5.base64digest("Hello") <add> metadata = { <add> "foo": "bar", <add> "my_key_1": "my_value_1", <add> "my_key_2": "my_value_2", <add> "platform": "my_platform", <add> "library_ID": "12345" <add> } <ide> <ide> post rails_direct_uploads_url, params: { blob: { <del> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain" } } <add> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain", metadata: metadata } } <ide> <ide> response.parsed_body.tap do |details| <ide> assert_equal ActiveStorage::Blob.find(details["id"]), ActiveStorage::Blob.find_signed!(details["signed_id"]) <ide> assert_equal "hello.txt", details["filename"] <ide> assert_equal 6, details["byte_size"] <ide> assert_equal checksum, details["checksum"] <add> assert_equal metadata, details["metadata"].transform_keys(&:to_sym) <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match SERVICE_CONFIGURATIONS[:s3][:bucket], details["direct_upload"]["url"] <ide> assert_match(/s3(-[-a-z0-9]+)?\.(\S+)?amazonaws\.com/, details["direct_upload"]["url"]) <ide> class ActiveStorage::GCSDirectUploadsControllerTest < ActionDispatch::Integratio <ide> <ide> test "creating new direct upload" do <ide> checksum = Digest::MD5.base64digest("Hello") <add> metadata = { <add> "foo": "bar", <add> "my_key_1": "my_value_1", <add> "my_key_2": "my_value_2", <add> "platform": "my_platform", <add> "library_ID": "12345" <add> } <ide> <ide> post rails_direct_uploads_url, params: { blob: { <del> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain" } } <add> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain", metadata: metadata } } <ide> <ide> @response.parsed_body.tap do |details| <ide> assert_equal ActiveStorage::Blob.find(details["id"]), ActiveStorage::Blob.find_signed!(details["signed_id"]) <ide> assert_equal "hello.txt", details["filename"] <ide> assert_equal 6, details["byte_size"] <ide> assert_equal checksum, details["checksum"] <add> assert_equal metadata, details["metadata"].transform_keys(&:to_sym) <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match %r{storage\.googleapis\.com/#{@config[:bucket]}}, details["direct_upload"]["url"] <ide> assert_equal({ "Content-MD5" => checksum, "Content-Disposition" => "inline; filename=\"hello.txt\"; filename*=UTF-8''hello.txt" }, details["direct_upload"]["headers"]) <ide> class ActiveStorage::AzureStorageDirectUploadsControllerTest < ActionDispatch::I <ide> <ide> test "creating new direct upload" do <ide> checksum = Digest::MD5.base64digest("Hello") <add> metadata = { <add> "foo": "bar", <add> "my_key_1": "my_value_1", <add> "my_key_2": "my_value_2", <add> "platform": "my_platform", <add> "library_ID": "12345" <add> } <ide> <ide> post rails_direct_uploads_url, params: { blob: { <del> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain" } } <add> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain", metadata: metadata } } <ide> <ide> @response.parsed_body.tap do |details| <ide> assert_equal ActiveStorage::Blob.find(details["id"]), ActiveStorage::Blob.find_signed!(details["signed_id"]) <ide> assert_equal "hello.txt", details["filename"] <ide> assert_equal 6, details["byte_size"] <ide> assert_equal checksum, details["checksum"] <add> assert_equal metadata, details["metadata"].transform_keys(&:to_sym) <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match %r{#{@config[:storage_account_name]}\.blob\.core\.windows\.net/#{@config[:container]}}, details["direct_upload"]["url"] <ide> assert_equal({ "Content-Type" => "text/plain", "Content-MD5" => checksum, "x-ms-blob-content-disposition" => "inline; filename=\"hello.txt\"; filename*=UTF-8''hello.txt", "x-ms-blob-type" => "BlockBlob" }, details["direct_upload"]["headers"]) <ide> class ActiveStorage::AzureStorageDirectUploadsControllerTest < ActionDispatch::I <ide> class ActiveStorage::DiskDirectUploadsControllerTest < ActionDispatch::IntegrationTest <ide> test "creating new direct upload" do <ide> checksum = Digest::MD5.base64digest("Hello") <add> metadata = { <add> "foo": "bar", <add> "my_key_1": "my_value_1", <add> "my_key_2": "my_value_2", <add> "platform": "my_platform", <add> "library_ID": "12345" <add> } <ide> <ide> post rails_direct_uploads_url, params: { blob: { <del> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain" } } <add> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain", metadata: metadata } } <ide> <ide> @response.parsed_body.tap do |details| <ide> assert_equal ActiveStorage::Blob.find(details["id"]), ActiveStorage::Blob.find_signed!(details["signed_id"]) <ide> assert_equal "hello.txt", details["filename"] <ide> assert_equal 6, details["byte_size"] <ide> assert_equal checksum, details["checksum"] <add> assert_equal metadata, details["metadata"].transform_keys(&:to_sym) <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match(/rails\/active_storage\/disk/, details["direct_upload"]["url"]) <ide> assert_equal({ "Content-Type" => "text/plain" }, details["direct_upload"]["headers"]) <ide> class ActiveStorage::DiskDirectUploadsControllerTest < ActionDispatch::Integrati <ide> <ide> test "creating new direct upload does not include root in json" do <ide> checksum = Digest::MD5.base64digest("Hello") <add> metadata = { <add> "foo": "bar", <add> "my_key_1": "my_value_1", <add> "my_key_2": "my_value_2", <add> "platform": "my_platform", <add> "library_ID": "12345" <add> } <ide> <ide> set_include_root_in_json(true) do <ide> post rails_direct_uploads_url, params: { blob: { <del> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain" } } <add> filename: "hello.txt", byte_size: 6, checksum: checksum, content_type: "text/plain", metadata: metadata } } <ide> end <ide> <ide> @response.parsed_body.tap do |details|
2