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
PHP
PHP
fix cs errors
30152a97234caf1d8218f0ad1bfad504f99b0fcd
<ide><path>src/Error/ErrorHandler.php <ide> protected function _displayException($exception) <ide> $this->_sendResponse($response); <ide> } catch (Throwable $exception) { <ide> $this->_logInternalError($exception); <del> } catch (Exception $exception) { <del> $this->_logInternalError($exception); <ide> } <ide> } <ide> <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php <ide> public function __invoke($request, $response, $next) <ide> return $next($request, $response); <ide> } catch (Throwable $exception) { <ide> return $this->handleException($exception, $request, $response); <del> } catch (Exception $exception) { <del> return $this->handleException($exception, $request, $response); <ide> } <ide> } <ide> <ide> public function handleException($exception, $request, $response) <ide> } catch (Throwable $exception) { <ide> $this->logException($request, $exception); <ide> $response = $this->handleInternalError($response); <del> } catch (Exception $exception) { <del> $this->logException($request, $exception); <del> $response = $this->handleInternalError($response); <ide> } <ide> <ide> return $response; <ide><path>src/Mailer/Email.php <ide> public static function deliver($to = null, $subject = null, $message = null, $co <ide> if (is_array($message)) { <ide> $instance->setViewVars($message); <ide> $message = null; <del> } elseif ($message === null && array_key_exists('message', $config = $instance->getProfile())) { <del> $message = $config['message']; <add> } elseif ($message === null) { <add> $config = $instance->getProfile(); <add> if (array_key_exists('message', $config)) { <add> $message = $config['message']; <add> } <ide> } <ide> <ide> if ($send === true) { <ide><path>src/Mailer/Transport/SmtpTransport.php <ide> protected function _connect() <ide> <ide> $config = $this->_config; <ide> <add> $host = 'localhost'; <ide> if (isset($config['client'])) { <ide> $host = $config['client']; <del> } elseif ($httpHost = env('HTTP_HOST')) { <del> list($host) = explode(':', $httpHost); <ide> } else { <del> $host = 'localhost'; <add> $httpHost = env('HTTP_HOST'); <add> if ($httpHost) { <add> list($host) = explode(':', $httpHost); <add> } <ide> } <ide> <ide> try { <ide><path>src/TestSuite/IntegrationTestTrait.php <ide> use Cake\View\Helper\SecureFieldTokenTrait; <ide> use Exception; <ide> use LogicException; <del>use PHPUnit\Exception as PhpunitException; <add>use PHPUnit\Exception as PhpUnitException; <ide> <ide> /** <ide> * A trait intended to make integration tests of your controllers easier. <ide><path>tests/TestCase/Filesystem/FileTest.php <ide> public function testLastChange() <ide> */ <ide> public function testWrite() <ide> { <del> if (!$tmpFile = $this->_getTmpFile()) { <add> $tmpFile = $this->_getTmpFile(); <add> if (!$tmpFile) { <ide> return false; <ide> } <ide> if (file_exists($tmpFile)) { <ide> public function testWrite() <ide> */ <ide> public function testAppend() <ide> { <del> if (!$tmpFile = $this->_getTmpFile()) { <add> $tmpFile = $this->_getTmpFile(); <add> if (!$tmpFile) { <ide> return false; <ide> } <ide> if (file_exists($tmpFile)) { <ide> public function testAppend() <ide> */ <ide> public function testDelete() <ide> { <del> if (!$tmpFile = $this->_getTmpFile()) { <add> $tmpFile = $this->_getTmpFile(); <add> if (!$tmpFile) { <ide> return false; <ide> } <ide> <ide> public function testDelete() <ide> */ <ide> public function testDeleteAfterRead() <ide> { <del> if (!$tmpFile = $this->_getTmpFile()) { <add> $tmpFile = $this->_getTmpFile(); <add> if (!$tmpFile) { <ide> return false; <ide> } <ide> if (!file_exists($tmpFile)) { <ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function testSaveAssociatedOnlyEntities() <ide> public function testPropertyOption() <ide> { <ide> $config = ['propertyName' => 'thing_placeholder']; <del> $association = new hasMany('Thing', $config); <add> $association = new HasMany('Thing', $config); <ide> $this->assertEquals('thing_placeholder', $association->getProperty()); <ide> } <ide> <ide><path>tests/TestCase/ORM/Association/HasOneTest.php <ide> public function testSaveAssociatedOnlyEntities() <ide> public function testPropertyOption() <ide> { <ide> $config = ['propertyName' => 'thing_placeholder']; <del> $association = new hasOne('Thing', $config); <add> $association = new HasOne('Thing', $config); <ide> $this->assertEquals('thing_placeholder', $association->getProperty()); <ide> } <ide> <ide><path>tests/TestCase/Validation/ValidationTest.php <ide> public function testDateTimeWithMeriadian() <ide> */ <ide> public function testLocalizedTime() <ide> { <del> $locale = I18N::getLocale(); <add> $locale = I18n::getLocale(); <ide> <ide> $this->assertFalse(Validation::localizedTime('', 'date')); <ide> $this->assertFalse(Validation::localizedTime('invalid', 'date')); <ide> <ide> // English (US) <del> I18N::setLocale('en_US'); <add> I18n::setLocale('en_US'); <ide> $this->assertTrue(Validation::localizedTime('12/31/2006', 'date')); <ide> $this->assertTrue(Validation::localizedTime('6.40pm', 'time')); <ide> $this->assertTrue(Validation::localizedTime('12/31/2006 6.40pm', 'datetime')); <ide> public function testLocalizedTime() <ide> $this->assertFalse(Validation::localizedTime('18:40', 'time')); // non-US format <ide> <ide> // German <del> I18N::setLocale('de_DE'); <add> I18n::setLocale('de_DE'); <ide> $this->assertTrue(Validation::localizedTime('31.12.2006', 'date')); <ide> $this->assertTrue(Validation::localizedTime('31. Dezember 2006', 'date')); <ide> $this->assertTrue(Validation::localizedTime('18:40', 'time')); <ide> <ide> $this->assertFalse(Validation::localizedTime('December 31, 2006', 'date')); // non-German format <ide> <ide> // Russian <del> I18N::setLocale('ru_RU'); <add> I18n::setLocale('ru_RU'); <ide> $this->assertTrue(Validation::localizedTime('31 декабря 2006', 'date')); <ide> <ide> $this->assertFalse(Validation::localizedTime('December 31, 2006', 'date')); // non-Russian format <ide> <del> I18N::setLocale($locale); <add> I18n::setLocale($locale); <ide> } <ide> <ide> /**
9
Text
Text
add code of conduct
84fd3a18a3a7f181d1b8c0a7c02b703cc4b8ec3a
<ide><path>CONTRIBUTING.md <ide> We'd love for you to contribute to our source code and to make AngularJS even better than it is <ide> today! Here are the guidelines we'd like you to follow: <ide> <add>## Code of Conduct <add>Help us keep Angular open and inclusive. Please read and follow our [Code of Conduct][coc]. <add> <ide> ## Got a Question or Problem? <ide> <ide> If you have questions about how to use AngularJS, please direct these to the [Google Group][groups] <ide> You can find out more detailed information about contributing in the <ide> [corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html <ide> [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# <ide> [github-pr-helper]: https://chrome.google.com/webstore/detail/github-pr-helper/mokbklfnaddkkbolfldepnkfmanfhpen <add>[coc]: https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md <ide> <ide> [![Analytics](https://ga-beacon.appspot.com/UA-8594346-11/angular.js/CONTRIBUTING.md?pixel)](https://github.com/igrigorik/ga-beacon)
1
Javascript
Javascript
use cache in bannerplugin
12ecab44fccef88e8f00e52e030d2ce395d4cf36
<ide><path>lib/BannerPlugin.js <ide> class BannerPlugin { <ide> undefined, <ide> options <ide> ); <add> const cache = new WeakMap(); <ide> <ide> compiler.hooks.compilation.tap("BannerPlugin", compilation => { <ide> compilation.hooks.processAssets.tap( <ide> class BannerPlugin { <ide> <ide> const comment = compilation.getPath(banner, data); <ide> <del> compilation.updateAsset( <del> file, <del> old => new ConcatSource(comment, "\n", old) <del> ); <add> compilation.updateAsset(file, old => { <add> let cached = cache.get(old); <add> if (!cached || cached.comment !== comment) { <add> const source = new ConcatSource(comment, "\n", old); <add> cache.set(old, { source, comment }); <add> return source; <add> } <add> return cached.source; <add> }); <ide> } <ide> } <ide> } <ide><path>test/BannerPlugin.test.js <add>"use strict"; <add> <add>const path = require("path"); <add>const fs = require("graceful-fs"); <add> <add>const webpack = require(".."); <add> <add>it("should cache assets", done => { <add> const entry1File = path.join(__dirname, "js", "BannerPlugin", "entry1.js"); <add> const entry2File = path.join(__dirname, "js", "BannerPlugin", "entry2.js"); <add> try { <add> fs.mkdirSync(path.join(__dirname, "js", "BannerPlugin"), { <add> recursive: true <add> }); <add> } catch (e) { <add> // empty <add> } <add> const compiler = webpack({ <add> mode: "development", <add> entry: { <add> entry1: entry1File, <add> entry2: entry2File <add> }, <add> output: { <add> path: path.join(__dirname, "js", "BannerPlugin", "output") <add> }, <add> plugins: [new webpack.BannerPlugin("banner is a string")] <add> }); <add> fs.writeFileSync(entry1File, "1", "utf-8"); <add> fs.writeFileSync(entry2File, "1", "utf-8"); <add> compiler.run(err => { <add> if (err) return done(err); <add> fs.writeFileSync(entry2File, "2", "utf-8"); <add> compiler.run((err, stats) => { <add> const { assets } = stats.toJson(); <add> expect(assets.find(as => as.name === "entry1.js").emitted).toBe(false); <add> expect(assets.find(as => as.name === "entry2.js").emitted).toBe(true); <add> done(err); <add> }); <add> }); <add>});
2
PHP
PHP
make association property() exclude plugin names
176717adaadbdc23140325dbffb39b57c662cb0f
<ide><path>src/ORM/Association.php <ide> public function property($name = null) { <ide> $this->_propertyName = $name; <ide> } <ide> if ($name === null && !$this->_propertyName) { <del> $this->_propertyName = Inflector::underscore($this->_name); <add> list($plugin, $name) = pluginSplit($this->_name); <add> $this->_propertyName = Inflector::underscore($name); <ide> } <ide> return $this->_propertyName; <ide> } <ide><path>src/ORM/Association/BelongsTo.php <ide> public function property($name = null) { <ide> return parent::property($name); <ide> } <ide> if ($name === null && !$this->_propertyName) { <del> $this->_propertyName = Inflector::underscore(Inflector::singularize($this->_name)); <add> list($plugin, $name) = pluginSplit($this->_name); <add> $this->_propertyName = Inflector::underscore(Inflector::singularize($name)); <ide> } <ide> return $this->_propertyName; <ide> } <ide><path>src/ORM/Association/HasOne.php <ide> public function property($name = null) { <ide> return parent::property($name); <ide> } <ide> if ($name === null && !$this->_propertyName) { <del> $this->_propertyName = Inflector::underscore(Inflector::singularize($this->_name)); <add> list($plugin, $name) = pluginSplit($this->_name); <add> $this->_propertyName = Inflector::underscore(Inflector::singularize($name)); <ide> } <ide> return $this->_propertyName; <ide> } <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> public function testSaveOnlyEntities() { <ide> $association->save($entity); <ide> } <ide> <add>/** <add> * Test that plugin names are omitted from property() <add> * <add> * @return void <add> */ <add> public function testPropertyNoPlugin() { <add> $mock = $this->getMock('Cake\ORM\Table', [], [], '', false); <add> $config = [ <add> 'sourceTable' => $this->article, <add> 'targetTable' => $mock, <add> ]; <add> $association = new BelongsToMany('Contacts.Tags', $config); <add> $this->assertEquals('tags', $association->property()); <add> } <add> <ide> } <ide><path>tests/TestCase/ORM/Association/BelongsToTest.php <ide> public function testSaveOnlyEntities() { <ide> $this->assertNull($entity->author_id); <ide> } <ide> <add>/** <add> * Test that plugin names are omitted from property() <add> * <add> * @return void <add> */ <add> public function testPropertyNoPlugin() { <add> $mock = $this->getMock('Cake\ORM\Table', [], [], '', false); <add> $config = [ <add> 'sourceTable' => $this->client, <add> 'targetTable' => $mock, <add> ]; <add> $association = new BelongsTo('Contacts.Companies', $config); <add> $this->assertEquals('company', $association->property()); <add> } <add> <ide> } <ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function testSaveOnlyEntities() { <ide> $association = new HasMany('Articles', $config); <ide> $association->save($entity); <ide> } <add> <add>/** <add> * Test that plugin names are omitted from property() <add> * <add> * @return void <add> */ <add> public function testPropertyNoPlugin() { <add> $mock = $this->getMock('Cake\ORM\Table', [], [], '', false); <add> $config = [ <add> 'sourceTable' => $this->author, <add> 'targetTable' => $mock, <add> ]; <add> $association = new HasMany('Contacts.Addresses', $config); <add> $this->assertEquals('addresses', $association->property()); <add> } <add> <ide> } <ide><path>tests/TestCase/ORM/Association/HasOneTest.php <ide> public function testSaveOnlyEntities() { <ide> <ide> $this->assertSame($result, $entity); <ide> } <add> <add>/** <add> * Test that plugin names are omitted from property() <add> * <add> * @return void <add> */ <add> public function testPropertyNoPlugin() { <add> $mock = $this->getMock('Cake\ORM\Table', [], [], '', false); <add> $config = [ <add> 'sourceTable' => $this->user, <add> 'targetTable' => $mock, <add> ]; <add> $association = new HasOne('Contacts.Profiles', $config); <add> $this->assertEquals('profile', $association->property()); <add> } <add> <ide> }
7
Python
Python
fix node build failures in wsl ubuntu
2ea2621ace40921e1bfa56ad0d9a3be0011de738
<ide><path>configure.py <ide> def make_bin_override(): <ide> if bin_override is not None: <ide> gyp_args += ['-Dpython=' + sys.executable] <ide> <del># pass the leftover positional arguments to GYP <del>gyp_args += args <add># pass the leftover non-whitespace positional arguments to GYP <add>gyp_args += [arg for arg in args if not str.isspace(arg)] <ide> <ide> if warn.warned and not options.verbose: <ide> warn('warnings were emitted in the configure phase')
1
Javascript
Javascript
add last chinese cert
c9d919732ad7980c7d1a02340e343327ce8de90a
<ide><path>config/i18n/all-langs.js <ide> const auditedCerts = { <ide> 'quality-assurance', <ide> 'scientific-computing-with-python', <ide> 'data-analysis-with-python', <del> 'information-security' <add> 'information-security', <add> 'machine-learning-with-python' <ide> ], <ide> 'chinese-traditional': [ <ide> 'responsive-web-design', <ide> const auditedCerts = { <ide> 'quality-assurance', <ide> 'scientific-computing-with-python', <ide> 'data-analysis-with-python', <del> 'information-security' <add> 'information-security', <add> 'machine-learning-with-python' <ide> ], <ide> italian: [ <ide> 'responsive-web-design',
1
Python
Python
add document qa pipeline metadata
0b567aa430e9b1b56254de4775db5868104d34e5
<ide><path>utils/update_metadata.py <ide> "AutoModelForAudioFrameClassification", <ide> ), <ide> ("audio-xvector", "MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES", "AutoModelForAudioXVector"), <add> ( <add> "document-question-answering", <add> "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES", <add> "AutoModelForDocumentQuestionAnswering", <add> ), <ide> ] <ide> <ide>
1
Ruby
Ruby
fix typo in docs [ci skip]
99e9630ef83c8fec8aae70467d2cd26ed91e4384
<ide><path>actionpack/lib/action_dispatch/request/session.rb <ide> def delete(key) <ide> @delegate.delete key.to_s <ide> end <ide> <del> # Returns value of given key from the session, or raises +KeyError+ <del> # if can't find given key in case of not setted dafault value. <add> # Returns value of the given key from the session, or raises +KeyError+ <add> # if can't find the given key and no default value is set. <ide> # Returns default value if specified. <ide> # <ide> # session.fetch(:foo)
1
Go
Go
fix some nits in tests
cf31aa0fa0d1b058bd138569d29d570081481c91
<ide><path>distribution/xfer/transfer_test.go <ide> func TestTransfer(t *testing.T) { <ide> } <ide> <ide> func TestConcurrencyLimit(t *testing.T) { <del> concurrencyLimit := 3 <add> const concurrencyLimit = 3 <ide> var runningJobs int32 <ide> <ide> makeXferFunc := func(id string) DoFunc { <ide> func TestConcurrencyLimit(t *testing.T) { <ide> } <ide> <ide> func TestInactiveJobs(t *testing.T) { <del> concurrencyLimit := 3 <add> const concurrencyLimit = 3 <ide> var runningJobs int32 <ide> testDone := make(chan struct{}) <ide> <ide><path>distribution/xfer/upload_test.go <ide> func (u *mockUploadDescriptor) Upload(ctx context.Context, progressOutput progre <ide> <ide> func uploadDescriptors(currentUploads *int32) []UploadDescriptor { <ide> return []UploadDescriptor{ <del> &mockUploadDescriptor{currentUploads, layer.DiffID("sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf"), 0}, <del> &mockUploadDescriptor{currentUploads, layer.DiffID("sha256:1515325234325236634634608943609283523908626098235490238423902343"), 0}, <del> &mockUploadDescriptor{currentUploads, layer.DiffID("sha256:6929356290463485374960346430698374523437683470934634534953453453"), 0}, <del> &mockUploadDescriptor{currentUploads, layer.DiffID("sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf"), 0}, <del> &mockUploadDescriptor{currentUploads, layer.DiffID("sha256:8159352387436803946235346346368745389534789534897538734598734987"), 1}, <del> &mockUploadDescriptor{currentUploads, layer.DiffID("sha256:4637863963478346897346987346987346789346789364879364897364987346"), 0}, <add> &mockUploadDescriptor{currentUploads: currentUploads, diffID: "sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf"}, <add> &mockUploadDescriptor{currentUploads: currentUploads, diffID: "sha256:1515325234325236634634608943609283523908626098235490238423902343"}, <add> &mockUploadDescriptor{currentUploads: currentUploads, diffID: "sha256:6929356290463485374960346430698374523437683470934634534953453453"}, <add> &mockUploadDescriptor{currentUploads: currentUploads, diffID: "sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf"}, <add> &mockUploadDescriptor{currentUploads: currentUploads, diffID: "sha256:8159352387436803946235346346368745389534789534897538734598734987", simulateRetries: 1}, <add> &mockUploadDescriptor{currentUploads: currentUploads, diffID: "sha256:4637863963478346897346987346987346789346789364879364897364987346"}, <ide> } <ide> } <ide>
2
Ruby
Ruby
build expression not(nil) as is not null
a7a5027f4f17e12cf11c310dd807f5c41e798cdb
<ide><path>lib/arel/engines/sql/core_extensions/nil_class.rb <ide> def equality_predicate_sql <ide> 'IS' <ide> end <ide> <add> def not_predicate_sql <add> 'IS NOT' <add> end <add> <ide> NilClass.send(:include, self) <ide> end <ide> end <ide><path>lib/arel/engines/sql/core_extensions/object.rb <ide> def equality_predicate_sql <ide> '=' <ide> end <ide> <add> def not_predicate_sql <add> '!=' <add> end <add> <ide> Object.send(:include, self) <ide> end <ide> end <ide><path>lib/arel/engines/sql/predicates.rb <ide> def predicate_sql <ide> end <ide> <ide> class Not < Binary <del> def predicate_sql; '!=' end <add> def predicate_sql <add> operand2.not_predicate_sql <add> end <ide> end <ide> <ide> class GreaterThanOrEqualTo < Binary <ide><path>lib/arel/engines/sql/primitives.rb <ide> def equality_predicate_sql <ide> value.equality_predicate_sql <ide> end <ide> <add> def not_predicate_sql <add> value.not_predicate_sql <add> end <add> <ide> def to_sql(formatter = Sql::WhereCondition.new(relation)) <ide> formatter.value value <ide> end <ide><path>spec/engines/sql/unit/predicates/not_spec.rb <add>require 'spec_helper' <add> <add>module Arel <add> module Predicates <add> describe Equality do <add> before do <add> @relation1 = Arel::Table.new(:users) <add> @relation2 = Arel::Table.new(:photos) <add> @attribute1 = @relation1[:id] <add> @attribute2 = @relation2[:user_id] <add> end <add> <add> describe '#to_sql' do <add> describe 'when relating to a non-nil value' do <add> it "manufactures a not predicate" do <add> sql = Not.new(@attribute1, @attribute2).to_sql <add> <add> adapter_is :mysql do <add> sql.should be_like(%Q{`users`.`id` != `photos`.`user_id`}) <add> end <add> <add> adapter_is :oracle do <add> sql.should be_like(%Q{"USERS"."ID" != "PHOTOS"."USER_ID"}) <add> end <add> <add> adapter_is_not :mysql, :oracle do <add> sql.should be_like(%Q{"users"."id" != "photos"."user_id"}) <add> end <add> end <add> end <add> <add> describe 'when relation to a nil value' do <add> before do <add> @nil = nil <add> end <add> <add> it "manufactures an is null predicate" do <add> sql = Not.new(@attribute1, @nil).to_sql <add> <add> adapter_is :mysql do <add> sql.should be_like(%Q{`users`.`id` IS NOT NULL}) <add> end <add> <add> adapter_is :oracle do <add> sql.should be_like(%Q{"USERS"."ID" IS NOT NULL}) <add> end <add> <add> adapter_is_not :mysql, :oracle do <add> sql.should be_like(%Q{"users"."id" IS NOT NULL}) <add> end <add> end <add> end <add> <add> describe "when relating to a nil Value" do <add> it "manufactures an IS NULL predicate" do <add> value = nil.bind(@relation1) <add> sql = Not.new(@attribute1, value).to_sql <add> <add> adapter_is :mysql do <add> sql.should be_like(%Q{`users`.`id` IS NOT NULL}) <add> end <add> <add> adapter_is :oracle do <add> sql.should be_like(%Q{"USERS"."ID" IS NOT NULL}) <add> end <add> <add> adapter_is_not :mysql, :oracle do <add> sql.should be_like(%Q{"users"."id" IS NOT NULL}) <add> end <add> end <add> end <add> end <add> end <add> end <add>end
5
PHP
PHP
remove class loader from optimize file
21fddea479015b863f319274ad4187900b64d282
<ide><path>src/Illuminate/Foundation/Console/Optimize/config.php <ide> $basePath = $app['path.base']; <ide> <ide> return array_map('realpath', array( <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/ClassLoader.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Container/Container.php', <ide> $basePath.'/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernelInterface.php', <ide> $basePath.'/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/TerminableInterface.php',
1
Python
Python
fix state handling
35eb2797c5e5dd9cdb6f35705eb522fe4b2357f5
<ide><path>libcloud/container/drivers/rancher.py <ide> def _to_container(self, data): <ide> <ide> """ <ide> rancher_state = data['state'] <add> <add> # A Removed container is purged after x amt of time. <add> # Both of these render the container dead (can't be started later) <add> terminate_condition = ["removed", "purged"] <add> <ide> if 'running' in rancher_state: <ide> state = ContainerState.RUNNING <ide> elif 'stopped' in rancher_state: <ide> def _to_container(self, data): <ide> state = ContainerState.REBOOTING <ide> elif 'error' in rancher_state: <ide> state = ContainerState.ERROR <del> elif 'removed' or 'purged' in rancher_state: <del> # A Removed container is purged after x amt of time. <del> # Both of these render the container dead (can't be started later) <add> elif any(x in rancher_state for x in terminate_condition): <ide> state = ContainerState.TERMINATED <ide> elif data['transitioning'] == 'yes': <ide> # Best we can do for current actions <ide><path>libcloud/test/container/test_rancher.py <ide> def test_start_container(self): <ide> started = container.start() <ide> self.assertEqual(started.id, "1i31") <ide> self.assertEqual(started.name, "newcontainer") <add> self.assertEqual(started.state, "pending") <ide> self.assertEqual(started.extra['state'], "starting") <ide> <ide> def test_stop_container(self): <ide> container = self.driver.get_container("1i31") <ide> stopped = container.stop() <ide> self.assertEqual(stopped.id, "1i31") <ide> self.assertEqual(stopped.name, "newcontainer") <add> self.assertEqual(stopped.state, "pending") <ide> self.assertEqual(stopped.extra['state'], "stopping") <ide> <ide> def test_ex_search_containers(self): <ide> def test_destroy_container(self): <ide> destroyed = container.destroy() <ide> self.assertEqual(destroyed.id, "1i31") <ide> self.assertEqual(destroyed.name, "newcontainer") <add> self.assertEqual(destroyed.state, "pending") <ide> self.assertEqual(destroyed.extra['state'], "stopping") <ide> <ide>
2
Python
Python
use markup for htmlcontent for landing_times
dcf65765e58fb8beba206454075bbd6675b65721
<ide><path>airflow/www/views.py <ide> def landing_times(self, session=None): <ide> return self.render_template( <ide> 'airflow/chart.html', <ide> dag=dag, <del> chart=chart.htmlcontent, <add> chart=Markup(chart.htmlcontent), <ide> height=str(chart_height + 100) + "px", <ide> demo_mode=conf.getboolean('webserver', 'demo_mode'), <ide> root=root,
1
PHP
PHP
apply fixes from styleci
10061f1fb7977bc6b66da690f1d4b34b3a924982
<ide><path>tests/Filesystem/FilesystemAdapterTest.php <ide> public function testGetAllFiles() <ide> <ide> $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); <ide> <del> $this->assertSame($filesystemAdapter->files(),['body.txt','existing.txt','file.txt','file1.txt']); <add> $this->assertSame($filesystemAdapter->files(), ['body.txt', 'existing.txt', 'file.txt', 'file1.txt']); <ide> } <ide> }
1
Text
Text
fix broken link in animations.md
b572a6b874747d89a47102eaacea11b76996f2c0
<ide><path>docs/Animations.md <ide> var App = React.createClass({ <ide> [Run this example](https://rnplay.org/apps/uaQrGQ) <ide> <ide> This example uses a preset value, you can customize the animations as <del>you need, see [LayoutAnimation.js](https://github.com/facebook/react-native/blob/master/Libraries/Animation/LayoutAnimation.js) <add>you need, see [LayoutAnimation.js](https://github.com/facebook/react-native/blob/master/Libraries/LayoutAnimation/LayoutAnimation.js) <ide> for more information. <ide> <ide> ### requestAnimationFrame
1
Javascript
Javascript
forbid haste in jest
575982b96dfd959f72ce8f44bc7d3f3c5e102597
<ide><path>scripts/jest/config.source.js <ide> 'use strict'; <ide> <ide> module.exports = { <add> haste: { <add> hasteImplModulePath: require.resolve('./noHaste.js'), <add> }, <ide> modulePathIgnorePatterns: [ <ide> '<rootDir>/scripts/rollup/shims/', <ide> '<rootDir>/scripts/bench/', <ide><path>scripts/jest/noHaste.js <add>'use strict'; <add> <add>module.exports = { <add> getHasteName() { <add> // We never want Haste. <add> return null; <add> }, <add>};
2
Go
Go
add graceful cancellation endpoint
0bddd4ccfee5b7f4f69cd4757f053214be2ad4cd
<ide><path>api/server/backend/build/backend.go <ide> func (b *Backend) Build(ctx context.Context, config backend.BuildConfig) (string <ide> } <ide> } <ide> <del> stdout := config.ProgressWriter.StdoutFormatter <del> fmt.Fprintf(stdout, "Successfully built %s\n", stringid.TruncateID(imageID)) <add> if !useBuildKit { <add> stdout := config.ProgressWriter.StdoutFormatter <add> fmt.Fprintf(stdout, "Successfully built %s\n", stringid.TruncateID(imageID)) <add> } <ide> err = tagger.TagImages(image.ID(imageID)) <ide> return imageID, err <ide> } <ide> func (b *Backend) PruneCache(ctx context.Context) (*types.BuildCachePruneReport, <ide> return &types.BuildCachePruneReport{SpaceReclaimed: size}, nil <ide> } <ide> <add>func (b *Backend) Cancel(ctx context.Context, id string) error { <add> return b.buildkit.Cancel(ctx, id) <add>} <add> <ide> func squashBuild(build *builder.Result, imageComponent ImageComponent) (string, error) { <ide> var fromID string <ide> if build.FromImage != nil { <ide><path>api/server/router/build/backend.go <ide> type Backend interface { <ide> <ide> // Prune build cache <ide> PruneCache(context.Context) (*types.BuildCachePruneReport, error) <add> <add> Cancel(context.Context, string) error <ide> } <ide> <ide> type experimentalProvider interface { <ide><path>api/server/router/build/build.go <ide> func (r *buildRouter) initRoutes() { <ide> r.routes = []router.Route{ <ide> router.NewPostRoute("/build", r.postBuild, router.WithCancel), <ide> router.NewPostRoute("/build/prune", r.postPrune, router.WithCancel), <add> router.NewPostRoute("/build/cancel", r.postCancel), <ide> } <ide> } <ide><path>api/server/router/build/build_routes.go <ide> func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui <ide> options.CacheFrom = cacheFrom <ide> } <ide> options.SessionID = r.FormValue("session") <add> options.BuildID = r.FormValue("buildid") <ide> <ide> return options, nil <ide> } <ide> func (br *buildRouter) postPrune(ctx context.Context, w http.ResponseWriter, r * <ide> return httputils.WriteJSON(w, http.StatusOK, report) <ide> } <ide> <add>func (br *buildRouter) postCancel(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add> w.Header().Set("Content-Type", "application/json") <add> <add> id := r.FormValue("id") <add> if id == "" { <add> return errors.Errorf("build ID not provided") <add> } <add> <add> return br.backend.Cancel(ctx, id) <add>} <add> <ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> var ( <ide> notVerboseBuffer = bytes.NewBuffer(nil) <ide><path>api/types/client.go <ide> type ImageBuildOptions struct { <ide> Target string <ide> SessionID string <ide> Platform string <add> BuildID string <ide> } <ide> <ide> // ImageBuildResponse holds information <ide><path>builder/builder-next/builder.go <ide> type Opt struct { <ide> type Builder struct { <ide> controller *control.Controller <ide> results *results <add> <add> mu sync.Mutex <add> jobs map[string]func() <ide> } <ide> <ide> func New(opt Opt) (*Builder, error) { <ide> func New(opt Opt) (*Builder, error) { <ide> b := &Builder{ <ide> controller: c, <ide> results: results, <add> jobs: map[string]func(){}, <ide> } <ide> return b, nil <ide> } <ide> <add>func (b *Builder) Cancel(ctx context.Context, id string) error { <add> b.mu.Lock() <add> if cancel, ok := b.jobs[id]; ok { <add> cancel() <add> } <add> b.mu.Unlock() <add> return nil <add>} <add> <ide> func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder.Result, error) { <add> if buildID := opt.Options.BuildID; buildID != "" { <add> b.mu.Lock() <add> ctx, b.jobs[buildID] = context.WithCancel(ctx) <add> b.mu.Unlock() <add> defer func() { <add> delete(b.jobs, buildID) <add> }() <add> } <add> <ide> id := identity.NewID() <ide> <ide> attrs := map[string]string{ <ide><path>client/build_cancel.go <add>package client // import "github.com/docker/docker/client" <add> <add>import ( <add> "net/url" <add> <add> "golang.org/x/net/context" <add>) <add> <add>// BuildCancel requests the daemon to cancel ongoing build request <add>func (cli *Client) BuildCancel(ctx context.Context, id string) error { <add> query := url.Values{} <add> query.Set("id", id) <add> <add> serverResp, err := cli.post(ctx, "/build/cancel", query, nil, nil) <add> if err != nil { <add> return err <add> } <add> defer ensureReaderClosed(serverResp) <add> <add> return nil <add>} <ide><path>client/image_build.go <ide> func (cli *Client) imageBuildOptionsToQuery(options types.ImageBuildOptions) (ur <ide> if options.Platform != "" { <ide> query.Set("platform", strings.ToLower(options.Platform)) <ide> } <add> if options.BuildID != "" { <add> query.Set("buildid", options.BuildID) <add> } <ide> return query, nil <ide> } <ide><path>client/interface.go <ide> type DistributionAPIClient interface { <ide> type ImageAPIClient interface { <ide> ImageBuild(ctx context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) <ide> BuildCachePrune(ctx context.Context) (*types.BuildCachePruneReport, error) <add> BuildCancel(ctx context.Context, id string) error <ide> ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) <ide> ImageHistory(ctx context.Context, image string) ([]image.HistoryResponseItem, error) <ide> ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error)
9
Ruby
Ruby
add timer support for systemd
4cb8afeeef6d9457e8741131dcdc79a69312403b
<ide><path>Library/Homebrew/formula.rb <ide> def systemd_service_path <ide> opt_prefix/"#{service_name}.service" <ide> end <ide> <add> # The generated systemd {.timer} file path. <add> sig { returns(Pathname) } <add> def systemd_timer_path <add> opt_prefix/"#{service_name}.timer" <add> end <add> <ide> # The service specification of the software. <ide> def service <ide> return unless service? <ide><path>Library/Homebrew/formula_installer.rb <ide> def install_service <ide> service_path = formula.systemd_service_path <ide> service_path.atomic_write(formula.service.to_systemd_unit) <ide> service_path.chmod 0644 <add> <add> if formula.service.timed? <add> timer_path = formula.systemd_timer_path <add> timer_path.atomic_write(formula.service.to_systemd_timer) <add> timer_path.chmod 0644 <add> end <ide> end <ide> <ide> service = if formula.service? <ide><path>Library/Homebrew/service.rb <ide> def command <ide> @run.map(&:to_s) <ide> end <ide> <add> # Returns the `String` command to run manually instead of the service. <add> # @return [String] <ide> sig { returns(String) } <ide> def manual_command <ide> instance_eval(&@service_block) <ide> def manual_command <ide> out.join(" ") <ide> end <ide> <add> # Returns a `Boolean` describing if a service is timed. <add> # @return [Boolean] <add> sig { returns(T::Boolean) } <add> def timed? <add> instance_eval(&@service_block) <add> @run_type == RUN_TYPE_CRON || @run_type == RUN_TYPE_INTERVAL <add> end <add> <ide> # Returns a `String` plist. <ide> # @return [String] <ide> sig { returns(String) } <ide> def to_systemd_unit <ide> <ide> unit + options.join("\n") <ide> end <add> <add> # Returns a `String` systemd unit timer. <add> # @return [String] <add> sig { returns(String) } <add> def to_systemd_timer <add> timer = <<~EOS <add> [Unit] <add> Description=Homebrew generated timer for #{@formula.name} <add> <add> [Install] <add> WantedBy=timers.target <add> <add> [Timer] <add> Unit=#{@formula.service_name} <add> EOS <add> <add> instance_eval(&@service_block) <add> options = [] <add> options << "Persistent=true=" if @run_type == RUN_TYPE_CRON <add> options << "OnUnitActiveSec=#{@interval}" if @run_type == RUN_TYPE_INTERVAL <add> <add> timer + options.join("\n") <add> end <ide> end <ide> end <ide><path>Library/Homebrew/test/formula_installer_spec.rb <ide> class #{Formulary.class_s(dep_name)} < Formula <ide> <ide> expect(formula).to receive(:plist).and_return(nil) <ide> expect(formula).to receive(:service?).exactly(3).and_return(true) <del> expect(formula).to receive(:service).twice.and_return(service) <add> expect(formula).to receive(:service).exactly(3).and_return(service) <ide> expect(formula).to receive(:plist_path).and_call_original <ide> expect(formula).to receive(:systemd_service_path).and_call_original <ide> <add> expect(service).to receive(:timed?).and_return(false) <ide> expect(service).to receive(:to_plist).and_return("plist") <ide> expect(service).to receive(:to_systemd_unit).and_return("unit") <ide> <ide> class #{Formulary.class_s(dep_name)} < Formula <ide> expect(service_path).to exist <ide> end <ide> <add> it "works if timed service is set" do <add> formula = Testball.new <add> plist_path = formula.plist_path <add> service_path = formula.systemd_service_path <add> timer_path = formula.systemd_timer_path <add> service = Homebrew::Service.new(formula) <add> formula.opt_prefix.mkpath <add> <add> expect(formula).to receive(:plist).and_return(nil) <add> expect(formula).to receive(:service?).exactly(3).and_return(true) <add> expect(formula).to receive(:service).exactly(4).and_return(service) <add> expect(formula).to receive(:plist_path).and_call_original <add> expect(formula).to receive(:systemd_service_path).and_call_original <add> expect(formula).to receive(:systemd_timer_path).and_call_original <add> <add> expect(service).to receive(:to_plist).and_return("plist") <add> expect(service).to receive(:timed?).and_return(true) <add> expect(service).to receive(:to_systemd_unit).and_return("unit") <add> expect(service).to receive(:to_systemd_timer).and_return("timer") <add> <add> installer = described_class.new(formula) <add> expect { <add> installer.install_service <add> }.not_to output(/Error: Failed to install service files/).to_stderr <add> <add> expect(plist_path).to exist <add> expect(service_path).to exist <add> expect(timer_path).to exist <add> end <add> <ide> it "returns without definition" do <ide> formula = Testball.new <ide> path = formula.plist_path <ide><path>Library/Homebrew/test/formula_spec.rb <ide> expect(f.service_name).to eq("homebrew.formula_name") <ide> expect(f.plist_path).to eq(HOMEBREW_PREFIX/"opt/formula_name/homebrew.mxcl.formula_name.plist") <ide> expect(f.systemd_service_path).to eq(HOMEBREW_PREFIX/"opt/formula_name/homebrew.formula_name.service") <add> expect(f.systemd_timer_path).to eq(HOMEBREW_PREFIX/"opt/formula_name/homebrew.formula_name.timer") <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/service_spec.rb <ide> end <ide> end <ide> <add> describe "#to_systemd_timer" do <add> it "returns valid timer" do <add> f.class.service do <add> run [opt_bin/"beanstalkd", "test"] <add> run_type :interval <add> interval 5 <add> end <add> <add> unit = f.service.to_systemd_timer <add> unit_expect = <<~EOS <add> [Unit] <add> Description=Homebrew generated timer for formula_name <add> <add> [Install] <add> WantedBy=timers.target <add> <add> [Timer] <add> Unit=homebrew.formula_name <add> OnUnitActiveSec=5 <add> EOS <add> expect(unit).to eq(unit_expect.strip) <add> end <add> <add> it "returns valid partial timer" do <add> f.class.service do <add> run opt_bin/"beanstalkd" <add> run_type :immediate <add> end <add> <add> unit = f.service.to_systemd_timer <add> unit_expect = <<~EOS <add> [Unit] <add> Description=Homebrew generated timer for formula_name <add> <add> [Install] <add> WantedBy=timers.target <add> <add> [Timer] <add> Unit=homebrew.formula_name <add> EOS <add> expect(unit).to eq(unit_expect) <add> end <add> end <add> <add> describe "#timed?" do <add> it "returns false for immediate" do <add> f.class.service do <add> run [opt_bin/"beanstalkd", "test"] <add> run_type :immediate <add> end <add> <add> expect(f.service.timed?).to eq(false) <add> end <add> <add> it "returns true for interval" do <add> f.class.service do <add> run [opt_bin/"beanstalkd", "test"] <add> run_type :interval <add> end <add> <add> expect(f.service.timed?).to eq(true) <add> end <add> end <add> <ide> describe "#command" do <ide> it "returns @run data" do <ide> f.class.service do
6
Python
Python
fix a small docstring bug in the csrf decorators
f9fba51164f36519e9b2f7917296ddd83b86ef47
<ide><path>django/views/decorators/csrf.py <ide> def _reject(self, request, reason): <ide> <ide> requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken) <ide> requires_csrf_token.__name__ = 'requires_csrf_token' <del>csrf_protect.__doc__ = """ <add>requires_csrf_token.__doc__ = """ <ide> Use this decorator on views that need a correct csrf_token available to <ide> RequestContext, but without the CSRF protection that csrf_protect <ide> enforces.
1
Ruby
Ruby
fix typos and add nodocs to nullrelation
30bf42b3ef8be104abffba07c3feaa343d882e09
<ide><path>activerecord/lib/active_record/null_relation.rb <ide> <ide> module ActiveRecord <ide> # = Active Record Null Relation <del> module NullRelation <add> module NullRelation # :nodoc: <ide> def exec_queries <ide> @records = [] <ide> end <ide><path>activerecord/lib/active_record/relation.rb <ide> def to_sql <ide> @to_sql ||= klass.connection.to_sql(arel, bind_values.dup) <ide> end <ide> <del> # Returns an hash of where conditions <add> # Returns a hash of where conditions <ide> # <del> # Users.where(name: 'Oscar').to_sql <add> # Users.where(name: 'Oscar').where_values_hash <ide> # # => {:name=>"oscar"} <ide> def where_values_hash <ide> equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node| <ide> def with_default_scope #:nodoc: <ide> end <ide> end <ide> <del> # Returns true if relation is blank> <add> # Returns true if relation is blank. <ide> def blank? <ide> to_a.blank? <ide> end
2
Javascript
Javascript
update view to use import instead of require
50c3dd3860fc092a08efa14e4ae8cd85a74d5e9d
<ide><path>Libraries/Components/View/View.js <ide> <ide> import type {ViewProps} from './ViewPropTypes'; <ide> <del>const React = require('react'); <ide> import ViewNativeComponent from './ViewNativeComponent'; <del>const TextAncestor = require('../../Text/TextAncestor'); <add>import TextAncestor from '../../Text/TextAncestor'; <add>import * as React from 'react'; <ide> <ide> export type Props = ViewProps; <ide>
1
PHP
PHP
fix cs errors
b02d729d3e3305a116ccf9c8efe216dbd2d8797f
<ide><path>src/Http/Response.php <ide> public function withCache($since, $time = '+1 day') <ide> if (!is_int($time)) { <ide> $time = strtotime($time); <ide> if ($time === false) { <del> throw new InvalidArgumentException('Invalid time parameter. Ensure your time value can be parsed by strtotime'); <add> throw new InvalidArgumentException( <add> 'Invalid time parameter. Ensure your time value can be parsed by strtotime' <add> ); <ide> } <ide> } <ide> <ide><path>src/Utility/Security.php <ide> public static function constantEquals($original, $compare): bool <ide> public static function getSalt(): string <ide> { <ide> if (static::$_salt === null) { <del> throw new RuntimeException('Salt not set. Use Security::setSalt() to set one, ideally in `config/bootstrap.php`.'); <add> throw new RuntimeException( <add> 'Salt not set. Use Security::setSalt() to set one, ideally in `config/bootstrap.php`.' <add> ); <ide> } <ide> <ide> return static::$_salt; <ide><path>src/View/Helper/FormHelper.php <ide> protected function _magicOptions(string $fieldName, array $options, bool $allowO <ide> $options['templateVars']['customValidityMessage'] = $message; <ide> <ide> if ($this->getConfig('autoSetCustomValidity')) { <del> $options['oninvalid'] = "this.setCustomValidity(''); if (!this.validity.valid) this.setCustomValidity('$message')"; <add> $options['oninvalid'] = "this.setCustomValidity(''); " <add> . "if (!this.validity.valid) this.setCustomValidity('$message')"; <ide> $options['oninput'] = "this.setCustomValidity('')"; <ide> } <ide> }
3
Javascript
Javascript
fix merge issue
c292e406b4009cb2de1201c096713d068bb8c77b
<ide><path>lib/dependencies/WebAssemblyExportImportedDependency.js <ide> class WebAssemblyExportImportedDependency extends ModuleDependency { <ide> <ide> write(this.exportName); <ide> write(this.name); <add> write(this.valueType); <ide> <ide> super.serialize(context); <ide> } <ide> class WebAssemblyExportImportedDependency extends ModuleDependency { <ide> <ide> this.exportName = read(); <ide> this.name = read(); <add> this.valueType = read(); <ide> <ide> super.deserialize(context); <ide> }
1
Text
Text
add 2.13.4 to changelog.md
2e45c053542f92ed363162b5d27f3da070310c62
<ide><path>CHANGELOG.md <ide> - [#15178](https://github.com/emberjs/ember.js/pull/15178) Refactor route to lookup controller for QPs. <ide> - [#15129](https://github.com/emberjs/ember.js/pull/15129) Fix access to service:-document in ember-engines <ide> <add>### 2.13.4 (July 5, 2017) <add> <add>- [#15321](https://github.com/emberjs/ember.js/pull/15321) [BUGFIX] Improve fastboot debugger/repl experience. <add> <ide> ### 2.13.3 (May 31, 2017) <ide> <ide> - [#15284](https://github.com/emberjs/ember.js/pull/15284) [BUGFIX] remove nested transaction assertion from glimmer.
1
Python
Python
use minor version for compatibility check
9fde2580538967dc16f63d4c3bc55660d031d09e
<ide><path>spacy/cli/download.py <ide> <ide> from ._util import app, Arg, Opt, WHEEL_SUFFIX, SDIST_SUFFIX <ide> from .. import about <del>from ..util import is_package, get_base_version, run_command <add>from ..util import is_package, get_minor_version, run_command <ide> from ..errors import OLD_MODEL_SHORTCUTS <ide> <ide> <ide> def download(model: str, direct: bool = False, sdist: bool = False, *pip_args) - <ide> <ide> <ide> def get_compatibility() -> dict: <del> version = get_base_version(about.__version__) <add> version = get_minor_version(about.__version__) <ide> r = requests.get(about.__compatibility__) <ide> if r.status_code != 200: <ide> msg.fail( <ide><path>spacy/cli/validate.py <ide> import sys <ide> import requests <ide> from wasabi import msg, Printer <add>import warnings <ide> <add>from ..errors import Warnings <ide> from ._util import app <ide> from .. import about <del>from ..util import get_package_version, get_installed_models, get_base_version <add>from ..util import get_package_version, get_installed_models, get_minor_version <ide> from ..util import get_package_path, get_model_meta, is_compatible_version <ide> <ide> <ide> def validate_cli(): <ide> <ide> def validate() -> None: <ide> model_pkgs, compat = get_model_pkgs() <del> spacy_version = get_base_version(about.__version__) <add> spacy_version = get_minor_version(about.__version__) <ide> current_compat = compat.get(spacy_version, {}) <ide> if not current_compat: <ide> msg.warn(f"No compatible packages found for v{spacy_version} of spaCy") <ide> def validate() -> None: <ide> comp = msg.text("", color="green", icon="good", no_print=True) <ide> version = msg.text(data["version"], color="green", no_print=True) <ide> else: <del> version = msg.text(data["version"], color="red", no_print=True) <del> comp = f"--> {compat.get(data['name'], ['n/a'])[0]}" <add> version = msg.text(data["version"], color="yellow", no_print=True) <add> comp = f"--> {current_compat.get(data['name'], ['n/a'])[0]}" <ide> rows.append((data["name"], data["spacy"], version, comp)) <ide> msg.table(rows, header=header) <ide> else: <ide> def get_model_pkgs(silent: bool = False) -> Tuple[dict, dict]: <ide> msg.good("Loaded compatibility table") <ide> compat = r.json()["spacy"] <ide> all_models = set() <del> installed_models = get_installed_models() <add> with warnings.catch_warnings(): <add> warnings.filterwarnings("ignore", message="\\[W09[45]") <add> installed_models = get_installed_models() <ide> for spacy_v, models in dict(compat).items(): <ide> all_models.update(models.keys()) <ide> for model, model_vs in models.items(): <ide> def get_model_pkgs(silent: bool = False) -> Tuple[dict, dict]: <ide> spacy_version = about.__version__ <ide> else: <ide> model_path = get_package_path(package) <del> model_meta = get_model_meta(model_path) <add> with warnings.catch_warnings(): <add> warnings.filterwarnings("ignore", message="\\[W09[45]") <add> model_meta = get_model_meta(model_path) <ide> spacy_version = model_meta.get("spacy_version", "n/a") <ide> is_compat = is_compatible_version(about.__version__, spacy_version) <ide> pkgs[pkg_name] = { <ide><path>spacy/errors.py <ide> class Warnings: <ide> "released, because the model may say it's compatible when it's " <ide> 'not. Consider changing the "spacy_version" in your meta.json to a ' <ide> "version range, with a lower and upper pin. For example: {example}") <del> W095 = ("Model '{model}' ({model_version}) requires spaCy {version} and is " <del> "incompatible with the current version ({current}). This may lead " <del> "to unexpected results or runtime errors. To resolve this, " <del> "download a newer compatible model or retrain your custom model " <del> "with the current spaCy version. For more details and available " <del> "updates, run: python -m spacy validate") <add> W095 = ("Model '{model}' ({model_version}) was trained with spaCy " <add> "{version} and may not be 100% compatible with the current version " <add> "({current}). If you see errors or degraded performance, download " <add> "a newer compatible model or retrain your custom model with the " <add> "current spaCy version. For more details and available updates, " <add> "run: python -m spacy validate") <ide> W096 = ("The method `nlp.disable_pipes` is now deprecated - use " <ide> "`nlp.select_pipes` instead.") <ide> W100 = ("Skipping unsupported morphological feature(s): '{feature}'. " <ide><path>spacy/tests/test_cli.py <ide> from spacy.cli._util import validate_project_commands, parse_config_overrides <ide> from spacy.cli._util import load_project_config, substitute_project_variables <ide> from spacy.cli._util import string_to_list <add>from spacy import about <add>from spacy.util import get_minor_version <add>from spacy.cli.validate import get_model_pkgs <add>from spacy.cli.download import get_compatibility, get_version <ide> from thinc.api import ConfigValidationError, Config <ide> import srsly <ide> import os <ide> def test_project_config_validation2(config, n_errors): <ide> <ide> <ide> @pytest.mark.parametrize( <del> "int_value", [10, pytest.param("10", marks=pytest.mark.xfail)], <add> "int_value", <add> [10, pytest.param("10", marks=pytest.mark.xfail)], <ide> ) <ide> def test_project_config_interpolation(int_value): <ide> variables = {"a": int_value, "b": {"c": "foo", "d": True}} <ide> def test_project_config_interpolation(int_value): <ide> <ide> <ide> @pytest.mark.parametrize( <del> "greeting", [342, "everyone", "tout le monde", pytest.param("42", marks=pytest.mark.xfail)], <add> "greeting", <add> [342, "everyone", "tout le monde", pytest.param("42", marks=pytest.mark.xfail)], <ide> ) <ide> def test_project_config_interpolation_override(greeting): <ide> variables = {"a": "world"} <ide> def test_parse_cli_overrides(): <ide> @pytest.mark.parametrize("pretraining", [True, False]) <ide> def test_init_config(lang, pipeline, optimize, pretraining): <ide> # TODO: add more tests and also check for GPU with transformers <del> config = init_config(lang=lang, pipeline=pipeline, optimize=optimize, pretraining=pretraining, gpu=False) <add> config = init_config( <add> lang=lang, <add> pipeline=pipeline, <add> optimize=optimize, <add> pretraining=pretraining, <add> gpu=False, <add> ) <ide> assert isinstance(config, Config) <ide> if pretraining: <ide> config["paths"]["raw_text"] = "my_data.jsonl" <ide> def test_string_to_list(value): <ide> def test_string_to_list_intify(value): <ide> assert string_to_list(value, intify=False) == ["1", "2", "3"] <ide> assert string_to_list(value, intify=True) == [1, 2, 3] <add> <add> <add>def test_download_compatibility(): <add> model_name = "en_core_web_sm" <add> compatibility = get_compatibility() <add> version = get_version(model_name, compatibility) <add> assert get_minor_version(about.__version__) == get_minor_version(version) <add> <add> <add>def test_validate_compatibility_table(): <add> model_pkgs, compat = get_model_pkgs() <add> spacy_version = get_minor_version(about.__version__) <add> current_compat = compat.get(spacy_version, {}) <add> assert len(current_compat) > 0 <add> assert "en_core_web_sm" in current_compat <ide><path>spacy/util.py <ide> def get_model_version_range(spacy_version: str) -> str: <ide> return f">={spacy_version},<{release[0]}.{release[1] + 1}.0" <ide> <ide> <add>def get_model_lower_version(constraint: str) -> Optional[str]: <add> """From a version range like >=1.2.3,<1.3.0 return the lower pin. <add> """ <add> try: <add> specset = SpecifierSet(constraint) <add> for spec in specset: <add> if spec.operator in (">=", "==", "~="): <add> return spec.version <add> except Exception: <add> pass <add> return None <add> <add> <ide> def get_base_version(version: str) -> str: <ide> """Generate the base version without any prerelease identifiers. <ide> <ide> def load_meta(path: Union[str, Path]) -> Dict[str, Any]: <ide> raise ValueError(Errors.E054.format(setting=setting)) <ide> if "spacy_version" in meta: <ide> if not is_compatible_version(about.__version__, meta["spacy_version"]): <add> lower_version = get_model_lower_version(meta["spacy_version"]) <add> lower_version = get_minor_version(lower_version) <add> if lower_version is not None: <add> lower_version = "v" + lower_version <add> elif "spacy_git_version" in meta: <add> lower_version = "git commit " + meta["spacy_git_version"] <add> else: <add> lower_version = "version unknown" <ide> warn_msg = Warnings.W095.format( <ide> model=f"{meta['lang']}_{meta['name']}", <ide> model_version=meta["version"], <del> version=meta["spacy_version"], <add> version=lower_version, <ide> current=about.__version__, <ide> ) <ide> warnings.warn(warn_msg)
5
Text
Text
fix typos [ci skip]
0ce768168610e97d4a726aa77aae748777e69465
<ide><path>guides/source/action_mailer_basics.md <ide> config.action_mailer.smtp_settings = { <ide> user_name: '<username>', <ide> password: '<password>', <ide> authentication: 'plain', <del> enable_starttls_auto: true } <add> enable_starttls_auto: true } <ide> ``` <ide> Note: As of July 15, 2014, Google increased [its security measures](https://support.google.com/accounts/answer/6010255) and now blocks attempts from apps it deems less secure. <ide> You can change your Gmail settings [here](https://www.google.com/settings/security/lesssecureapps) to allow the attempts. If your Gmail account has 2-factor authentication enabled, <ide><path>guides/source/active_record_validations.md <ide> should happen, an `Array` can be used. Moreover, you can apply both `:if` and <ide> ```ruby <ide> class Computer < ApplicationRecord <ide> validates :mouse, presence: true, <del> if: [Proc.new { |c| c.market.retail? }, :desktop?], <add> if: [Proc.new { |c| c.market.retail? }, :desktop?], <ide> unless: Proc.new { |c| c.trackpad.present? } <ide> end <ide> ``` <ide><path>guides/source/security.md <ide> The common admin interface works like this: it's located at www.example.com/admi <ide> <ide> * Does the admin really have to access the interface from everywhere in the world? Think about _limiting the login to a bunch of source IP addresses_. Examine request.remote_ip to find out about the user's IP address. This is not bullet-proof, but a great barrier. Remember that there might be a proxy in use, though. <ide> <del>* _Put the admin interface to a special sub-domain_ such as admin.application.com and make it a separate application with its own user management. This makes stealing an admin cookie from the usual domain, www.application.com, impossible. This is because of the same origin policy in your browser: An injected (XSS) script on www.application.com may not read the cookie for admin.application.com and vice-versa. <add>* _Put the admin interface to a special subdomain_ such as admin.application.com and make it a separate application with its own user management. This makes stealing an admin cookie from the usual domain, www.application.com, impossible. This is because of the same origin policy in your browser: An injected (XSS) script on www.application.com may not read the cookie for admin.application.com and vice-versa. <ide> <ide> User Management <ide> --------------- <ide><path>guides/source/threading_and_code_execution.md <ide> that promise is to put it as close as possible to the blocking call: <ide> Rails.application.executor.wrap do <ide> th = Thread.new do <ide> Rails.application.executor.wrap do <del> User # inner thread can acquire the load lock, <add> User # inner thread can acquire the 'load' lock, <ide> # load User, and continue <ide> end <ide> end <ide><path>guides/source/working_with_javascript_in_rails.md <ide> Example usage: <ide> ```html <ide> document.body.addEventListener('ajax:success', function(event) { <ide> var detail = event.detail; <del> var data = detail[0], status = detail[1], xhr = detail[2]; <add> var data = detail[0], status = detail[1], xhr = detail[2]; <ide> }) <ide> ``` <ide>
5
Text
Text
add documentation for summary() feature
20ca5befdcdb8759aa7fdb4c452215deaa4f7cbf
<ide><path>docs/sources/models.md <ide> model = keras.models.Sequential() <ide> - __Return__: loss over the data, or tuple `(loss, accuracy)` if `accuracy=True`. <ide> - __save_weights__(fname, overwrite=False): Store the weights of all layers to a HDF5 file. If overwrite==False and the file already exists, an exception will be thrown. <ide> - __load_weights__(fname): Sets the weights of a model, based to weights stored by __save_weights__. You can only __load_weights__ on a savefile from a model with an identical architecture. __load_weights__ can be called either before or after the __compile__ step. <add> - __summary__(): Print out a summary of the model architecture, with parameter count information. <ide> <ide> __Examples__: <ide> <ide> model = keras.models.Graph() <ide> - __Return__: loss over the data. <ide> - __save_weights__(fname, overwrite=False): Store the weights of all layers to a HDF5 file. If `overwrite==False` and the file already exists, an exception will be thrown. <ide> - __load_weights__(fname): Sets the weights of a model, based to weights stored by __save_weights__. You can only __load_weights__ on a savefile from a model with an identical architecture. __load_weights__ can be called either before or after the __compile__ step. <add> - __summary__(): Print out a summary of the model architecture, with parameter count information. <ide> <ide> <ide> __Examples__:
1
Python
Python
remove extra semicolon
26fe4c65390b7a2bfe2722b674943b64820d8442
<ide><path>data_structures/queue/linked_queue.py <ide> class LinkedQueue: <ide> >>> queue.put(5) <ide> >>> queue.put(9) <ide> >>> queue.put('python') <del> >>> queue.is_empty(); <add> >>> queue.is_empty() <ide> False <ide> >>> queue.get() <ide> 5
1
Text
Text
fix typo in roberta-base-squad2-v2 model card
17b1fd804f2ade052e40505a695ec7c9996178a9
<ide><path>model_cards/deepset/roberta-base-squad2-v2/README.md <ide> tokenizer = Tokenizer.load(model_name) <ide> ### In haystack <ide> For doing QA at scale (i.e. many docs instead of single paragraph), you can load the model also in [haystack](https://github.com/deepset-ai/haystack/): <ide> ```python <del>reader = FARMReader(model_name_or_path="deepset/roberta-base-squad2") <add>reader = FARMReader(model_name_or_path="deepset/roberta-base-squad2-v2") <ide> # or <del>reader = TransformersReader(model="deepset/roberta-base-squad2",tokenizer="deepset/roberta-base-squad2") <add>reader = TransformersReader(model_name_or_path="deepset/roberta-base-squad2-v2",tokenizer="deepset/roberta-base-squad2-v2") <ide> ``` <ide> <ide>
1
PHP
PHP
allow 0 limit
1c71e7785655e5084630fdee58ed290245a69f4c
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function limit($value) <ide> { <ide> $property = $this->unions ? 'unionLimit' : 'limit'; <ide> <del> if ($value > 0) { <add> if ($value >= 0) { <ide> $this->$property = $value; <ide> } <ide>
1
Javascript
Javascript
update index.js using es6
e6343a83e240c71b23ed4f292e62fa8c0ab3e181
<ide><path>website/src/react-native/index.js <ide> var index = React.createClass({ <ide> <Prism> <ide> {`// iOS <ide> <del>var React = require('react-native'); <del>var { TabBarIOS, NavigatorIOS } = React; <add>import React, { <add> Component, <add> TabBarIOS, <add> NavigatorIOS <add>} from 'react-native'; <ide> <del>var App = React.createClass({ <del> render: function() { <add>class App extends Component { <add> render() { <ide> return ( <ide> <TabBarIOS> <ide> <TabBarIOS.Item title="React Native" selected={true}> <ide> <NavigatorIOS initialRoute={{ title: 'React Native' }} /> <ide> </TabBarIOS.Item> <ide> </TabBarIOS> <ide> ); <del> }, <del>});`} <add> } <add>}`} <ide> </Prism> <ide> <ide> <Prism> <ide> {`// Android <ide> <del>var React = require('react-native'); <del>var { DrawerLayoutAndroid, ProgressBarAndroid, Text } = React; <add>import React, { <add> Component, <add> DrawerLayoutAndroid, <add> ProgressBarAndroid, <add> Text <add>} from 'react-native'; <ide> <del>var App = React.createClass({ <del> render: function() { <add>class App extends Component { <add> render() { <ide> return ( <ide> <DrawerLayoutAndroid <ide> renderNavigationView={() => <Text>React Native</Text>}> <ide> <ProgressBarAndroid /> <ide> </DrawerLayoutAndroid> <ide> ); <del> }, <del>});`} <add> } <add>}`} <ide> </Prism> <ide> <ide> <h2>Asynchronous Execution</h2> <ide> var App = React.createClass({ <ide> <Prism> <ide> {`// iOS & Android <ide> <del>var React = require('react-native'); <del>var { ScrollView, TouchableHighlight, Text } = React; <add>import React, { <add> Component, <add> ScrollView, <add> TouchableHighlight, <add> Text <add>} from 'react-native'; <ide> <del>var TouchDemo = React.createClass({ <del> render: function() { <add>class TouchDemo extends Component { <add> render() { <ide> return ( <ide> <ScrollView> <ide> <TouchableHighlight onPress={() => console.log('pressed')}> <ide> <Text>Proper Touch Handling</Text> <ide> </TouchableHighlight> <ide> </ScrollView> <ide> ); <del> }, <del>});`} <add> } <add>}`} <ide> </Prism> <ide> <ide> <h2>Flexbox and Styling</h2> <ide> var TouchDemo = React.createClass({ <ide> <Prism> <ide> {`// iOS & Android <ide> <del>var React = require('react-native'); <del>var { Image, StyleSheet, Text, View } = React; <add>var React, { <add> Component, <add> Image, <add> StyleSheet, <add> Text, <add> View <add>} from 'react-native'; <ide> <del>var ReactNative = React.createClass({ <del> render: function() { <add>class ReactNative extends Component { <add> render() { <ide> return ( <ide> <View style={styles.row}> <ide> <Image <ide> var ReactNative = React.createClass({ <ide> </View> <ide> </View> <ide> ); <del> }, <del>}); <add> } <add>} <ide> var styles = StyleSheet.create({ <ide> row: { flexDirection: 'row', margin: 40 }, <ide> image: { width: 40, height: 40, marginRight: 10 }, <ide> var styles = StyleSheet.create({ <ide> React Native is focused on changing the way view code is written. For the rest, we look to the web for universal standards and polyfill those APIs where appropriate. You can use npm to install JavaScript libraries that work on top of the functionality baked into React Native, such as XMLHttpRequest, window.requestAnimationFrame, and navigator.geolocation. We are working on expanding the available APIs, and are excited for the Open Source community to contribute as well. <ide> </p> <ide> <Prism> <del>{`// iOS (Android support for geolocation coming) <add>{`// iOS & Android <ide> <del>var React = require('react-native'); <del>var { Text } = React; <add>import React, { <add> Component, <add> Text <add>} from 'react-native'; <ide> <del>var GeoInfo = React.createClass({ <del> getInitialState: function() { <del> return { position: 'unknown' }; <add>class GeoInfo extends Component { <add> constructor(props) { <add> super(props); <add> this.state = { position: 'unknown' }; <ide> }, <del> componentDidMount: function() { <add> componentDidMount() { <ide> navigator.geolocation.getCurrentPosition( <ide> (position) => this.setState({position}), <ide> (error) => console.error(error) <ide> ); <del> }, <del> render: function() { <add> } <add> render() { <ide> return ( <ide> <Text> <ide> Position: {JSON.stringify(this.state.position)} <ide> </Text> <ide> ); <del> }, <del>});`} <add> } <add>}`} <ide> </Prism> <ide> <ide> <h2>Extensibility</h2> <ide> RCT_EXPORT_METHOD(processString:(NSString *)input callback:(RCTResponseSenderBlo <ide> <Prism> <ide> {`// JavaScript <ide> <del>var React = require('react-native'); <del>var { NativeModules, Text } = React; <add>import React, { <add> Component, <add> NativeModules, <add> Text <add>} from 'react-native'; <ide> <del>var Message = React.createClass({ <del> getInitialState() { <del> return { text: 'Goodbye World.' }; <del> }, <add>class Message extends Component { <add> constructor(props) { <add> super(props); <add> this.state = { text: 'Goodbye World.' }; <add> } <ide> componentDidMount() { <ide> NativeModules.MyCustomModule.processString(this.state.text, (text) => { <ide> this.setState({text}); <ide> }); <del> }, <del> render: function() { <add> } <add> render() { <ide> return ( <ide> <Text>{this.state.text}</Text> <ide> ); <ide> } <del>});`} <add>}`} <ide> </Prism> <ide> <ide> <h3>Creating iOS views</h3> <ide> RCT_EXPORT_VIEW_PROPERTY(myCustomProperty, NSString); <ide> <Prism> <ide> {`// JavaScript <ide> <del>var React = require('react-native'); <del>var { requireNativeComponent } = React; <add>import React, { <add> Component, <add> requireNativeComponent <add>} from 'react-native'; <add> <add>var NativeMyCustomView = requireNativeComponent('MyCustomView', MyCustomView); <ide> <del>class MyCustomView extends React.Component { <add>export default class MyCustomView extends Component { <add> static propTypes = { <add> myCustomProperty: React.PropTypes.oneOf(['a', 'b']), <add> }; <ide> render() { <ide> return <NativeMyCustomView {...this.props} />; <ide> } <ide> } <del>MyCustomView.propTypes = { <del> myCustomProperty: React.PropTypes.oneOf(['a', 'b']), <del>}; <del> <del>var NativeMyCustomView = requireNativeComponent('MyCustomView', MyCustomView); <del>module.exports = MyCustomView;`} <add>`} <ide> </Prism> <ide> <ide> <h3>Creating Android modules</h3> <ide> public class MyCustomModule extends ReactContextBaseJavaModule { <ide> <Prism> <ide> {`// JavaScript <ide> <del>var React = require('react-native'); <del>var { NativeModules, Text } = React; <del>var Message = React.createClass({ <del> getInitialState() { <del> return { text: 'Goodbye World.' }; <add>import React, { <add> Component, <add> NativeModules, <add> Text <add>} from 'react-native'; <add>class Message extends Component { <add> constructor(props) { <add> super(props); <add> this.state = { text: 'Goodbye World.' }; <ide> }, <ide> componentDidMount() { <ide> NativeModules.MyCustomModule.processString(this.state.text, (text) => { <ide> this.setState({text}); <ide> }); <del> }, <del> render: function() { <add> } <add> render() { <ide> return ( <ide> <Text>{this.state.text}</Text> <ide> ); <ide> } <del>}); <add>} <ide> `} <ide> </Prism> <ide> <ide> public class MyCustomViewManager extends SimpleViewManager<MyCustomView> { <ide> <Prism> <ide> {`// JavaScript <ide> <del>var React = require('react-native'); <del>var { requireNativeComponent } = React; <add>import React, { <add> Component, <add> requireNativeComponent <add>} from 'react-native'; <add> <add>var NativeMyCustomView = requireNativeComponent('MyCustomView', MyCustomView); <ide> <del>class MyCustomView extends React.Component { <add>export default class MyCustomView extends Component { <add> static propTypes = { <add> myCustomProperty: React.PropTypes.oneOf(['a', 'b']), <add> }; <ide> render() { <ide> return <NativeMyCustomView {...this.props} />; <ide> } <ide> } <del>MyCustomView.propTypes = { <del> myCustomProperty: React.PropTypes.oneOf(['a', 'b']), <del>}; <del> <del>var NativeMyCustomView = requireNativeComponent('MyCustomView', MyCustomView); <del>module.exports = MyCustomView; <ide> `} <ide> </Prism> <ide> </div>
1
Text
Text
add a changelog entry for [ci skip]
cbca29a959fc0f6667d378953af31f0f0e004f55
<ide><path>railties/CHANGELOG.md <add>* `I18n.load_path` is now reloaded under development so there's no need to <add> restart the server to make new locale files available. Also, I18n will no <add> longer raise for deleted locale files. <add> <add> *Kir Shatrov* <add> <ide> * Add `bin/update` script to update development environment automatically. <ide> <ide> *Mehmet Emin İNAÇ*
1
PHP
PHP
fix most coding standard issues in controller
61aba0f0f88af9be51027e83cfcc75f800b609cc
<ide><path>lib/Cake/Controller/CakeErrorController.php <ide> public function beforeRender() { <ide> } <ide> } <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component.php <ide> public function __get($name) { <ide> * @return void <ide> * @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::initialize <ide> */ <del> public function initialize(Controller $controller) { } <add> public function initialize(Controller $controller) { <add> } <ide> <ide> /** <ide> * Called after the Controller::beforeFilter() and before the controller action <ide> public function initialize(Controller $controller) { } <ide> * @return void <ide> * @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::startup <ide> */ <del> public function startup(Controller $controller) { } <add> public function startup(Controller $controller) { <add> } <ide> <ide> /** <ide> * Called after the Controller::beforeRender(), after the view class is loaded, and before the <ide> public function startup(Controller $controller) { } <ide> * @return void <ide> * @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::beforeRender <ide> */ <del> public function beforeRender(Controller $controller) { } <add> public function beforeRender(Controller $controller) { <add> } <ide> <ide> /** <ide> * Called after Controller::render() and before the output is printed to the browser. <ide> public function beforeRender(Controller $controller) { } <ide> * @return void <ide> * @link @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::shutdown <ide> */ <del> public function shutdown(Controller $controller) { } <add> public function shutdown(Controller $controller) { <add> } <ide> <ide> /** <ide> * Called before Controller::redirect(). Allows you to replace the url that will <ide> public function shutdown(Controller $controller) { } <ide> * @return array|null Either an array or null. <ide> * @link @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::beforeRedirect <ide> */ <del> public function beforeRedirect(Controller $controller, $url, $status = null, $exit = true) {} <add> public function beforeRedirect(Controller $controller, $url, $status = null, $exit = true) { <add> } <ide> <ide> } <ide><path>lib/Cake/Controller/Component/Acl/AclInterface.php <ide> public function inherit($aro, $aco, $action = "*"); <ide> * @param AclComponent $component <ide> */ <ide> public function initialize(Component $component); <add> <ide> } <ide><path>lib/Cake/Controller/Component/Acl/DbAcl.php <ide> public function check($aro, $aco, $action = "*") { <ide> $acoIDs = Set::extract($acoPath, '{n}.' . $this->Aco->alias . '.id'); <ide> <ide> $count = count($aroPath); <del> for ($i = 0 ; $i < $count; $i++) { <add> for ($i = 0; $i < $count; $i++) { <ide> $permAlias = $this->Aro->Permission->alias; <ide> <ide> $perms = $this->Aro->Permission->find('all', array( <ide> protected function _getAcoKeys($keys) { <ide> } <ide> return $newKeys; <ide> } <del>} <ide> <add>} <ide><path>lib/Cake/Controller/Component/Acl/IniAcl.php <ide> class IniAcl extends Object implements AclInterface { <ide> * @return void <ide> */ <ide> public function initialize(Component $component) { <del> <ide> } <ide> <ide> /** <ide> public function initialize(Component $component) { <ide> * @return boolean Success <ide> */ <ide> public function allow($aro, $aco, $action = "*") { <del> <ide> } <ide> <ide> /** <ide> public function allow($aro, $aco, $action = "*") { <ide> * @return boolean Success <ide> */ <ide> public function deny($aro, $aco, $action = "*") { <del> <ide> } <ide> <ide> /** <ide> public function deny($aro, $aco, $action = "*") { <ide> * @return boolean Success <ide> */ <ide> public function inherit($aro, $aco, $action = "*") { <del> <ide> } <ide> <ide> /** <ide> public function inherit($aro, $aco, $action = "*") { <ide> * <ide> * @param string $aro ARO <ide> * @param string $aco ACO <del> * @param string $aco_action Action <add> * @param string $action Action <ide> * @return boolean Success <ide> */ <del> public function check($aro, $aco, $aco_action = null) { <add> public function check($aro, $aco, $action = null) { <ide> if ($this->config == null) { <ide> $this->config = $this->readConfigFile(APP . 'Config' . DS . 'acl.ini.php'); <ide> } <ide> public function check($aro, $aco, $aco_action = null) { <ide> } <ide> <ide> /** <del> * Parses an INI file and returns an array that reflects the INI file's section structure. Double-quote friendly. <add> * Parses an INI file and returns an array that reflects the <add> * INI file's section structure. Double-quote friendly. <ide> * <ide> * @param string $filename File <ide> * @return array INI section structure <ide> public function arrayTrim($array) { <ide> array_unshift($array, ""); <ide> return $array; <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component/Acl/PhpAcl.php <ide> class PhpAcl extends Object implements AclInterface { <ide> */ <ide> public $options = array(); <ide> <del> <ide> /** <ide> * Aro Object <ide> * <ide> class PhpAcl extends Object implements AclInterface { <ide> */ <ide> public $Aco = null; <ide> <del> <add>/** <add> * Constructor <add> * <add> * Sets a few default settings up. <add> */ <ide> public function __construct() { <ide> $this->options = array( <ide> 'policy' => self::DENY, <ide> 'config' => APP . 'Config' . DS . 'acl.php', <ide> ); <ide> } <add> <ide> /** <ide> * Initialize method <ide> * <ide> public function initialize(Component $Component) { <ide> if (!empty($Component->settings['adapter'])) { <ide> $this->options = array_merge($this->options, $Component->settings['adapter']); <ide> } <del> <add> <ide> App::uses('PhpReader', 'Configure'); <ide> $Reader = new PhpReader(dirname($this->options['config']) . DS); <ide> $config = $Reader->read(basename($this->options['config'])); <ide> public function initialize(Component $Component) { <ide> * <ide> * @param array $config configuration array, see docs <ide> * @return void <add> * @throws AclException When required keys are missing. <ide> */ <ide> public function build(array $config) { <ide> if (empty($config['roles'])) { <ide> public function inherit($aro, $aco, $action = "*") { <ide> * <ide> * @param string $aro ARO <ide> * @param string $aco ACO <del> * @param string $aco_action Action <add> * @param string $action Action <ide> * @return boolean true if access is granted, false otherwise <ide> */ <del> public function check($aro, $aco, $aco_action = "*") { <add> public function check($aro, $aco, $action = "*") { <ide> $allow = $this->options['policy']; <ide> $prioritizedAros = $this->Aro->roles($aro); <ide> <del> if ($aco_action && $aco_action != "*") { <del> $aco .= '/' . $aco_action; <add> if ($action && $action != "*") { <add> $aco .= '/' . $action; <ide> } <ide> <del> $path = $this->Aco->path($aco); <del> <add> $path = $this->Aco->path($aco); <add> <ide> if (empty($path)) { <ide> return $allow; <ide> } <ide> public function check($aro, $aco, $aco_action = "*") { <ide> <ide> return $allow; <ide> } <add> <ide> } <ide> <ide> /** <ide> class PhpAco { <ide> * <ide> * @var array <ide> */ <del> protected $tree = array(); <add> protected $_tree = array(); <ide> <ide> /** <ide> * map modifiers for ACO paths to their respective PCRE pattern <ide> public function path($aco) { <ide> $aco = $this->resolve($aco); <ide> $path = array(); <ide> $level = 0; <del> $root = $this->tree; <add> $root = $this->_tree; <ide> $stack = array(array($root, 0)); <del> <add> <ide> while (!empty($stack)) { <ide> list($root, $level) = array_pop($stack); <ide> <ide> public function path($aco) { <ide> } <ide> <ide> foreach ($root as $node => $elements) { <del> $pattern = '/^'.str_replace(array_keys(self::$modifiers), array_values(self::$modifiers), $node).'$/'; <del> <add> $pattern = '/^' . str_replace(array_keys(self::$modifiers), array_values(self::$modifiers), $node) . '$/'; <add> <ide> if ($node == $aco[$level] || preg_match($pattern, $aco[$level])) { <ide> // merge allow/denies with $path of current level <ide> foreach (array('allow', 'deny') as $policy) { <ide> if (!empty($elements[$policy])) { <ide> if (empty($path[$level][$policy])) { <ide> $path[$level][$policy] = array(); <ide> } <del> <ide> $path[$level][$policy] = array_merge($path[$level][$policy], $elements[$policy]); <ide> } <ide> } <ide> public function path($aco) { <ide> if (!empty($elements['children']) && isset($aco[$level + 1])) { <ide> array_push($stack, array($elements['children'], $level + 1)); <ide> } <del> } <add> } <ide> } <ide> } <ide> <ide> return $path; <ide> } <ide> <del> <ide> /** <ide> * allow/deny ARO access to ARO <ide> * <ide> public function path($aco) { <ide> public function access($aro, $aco, $action, $type = 'deny') { <ide> $aco = $this->resolve($aco); <ide> $depth = count($aco); <del> $root = $this->tree; <add> $root = $this->_tree; <ide> $tree = &$root; <ide> <ide> foreach ($aco as $i => $node) { <ide> public function access($aro, $aco, $action, $type = 'deny') { <ide> if (empty($tree[$node][$type])) { <ide> $tree[$node][$type] = array(); <ide> } <del> <add> <ide> $tree[$node][$type] = array_merge(is_array($aro) ? $aro : array($aro), $tree[$node][$type]); <ide> } <ide> } <ide> <del> $this->tree = &$root; <add> $this->_tree = &$root; <ide> } <ide> <ide> /** <ide> public function resolve($aco) { <ide> */ <ide> public function build(array $allow, array $deny = array()) { <ide> $stack = array(); <del> $this->tree = array(); <add> $this->_tree = array(); <ide> $tree = array(); <ide> $root = &$tree; <ide> <ide> public function build(array $allow, array $deny = array()) { <ide> <ide> $this->access($aros, $dotPath, null, 'allow'); <ide> } <del> <add> <ide> foreach ($deny as $dotPath => $aros) { <ide> if (is_string($aros)) { <ide> $aros = array_map('trim', explode(',', $aros)); <ide> public function build(array $allow, array $deny = array()) { <ide> } <ide> } <ide> <del> <ide> } <ide> <ide> /** <ide> class PhpAro { <ide> * <ide> * @var array <ide> */ <del> protected $tree = array(); <add> protected $_tree = array(); <ide> <ide> public function __construct(array $aro = array(), array $map = array(), array $aliases = array()) { <ide> if (!empty($map)) { <ide> public function __construct(array $aro = array(), array $map = array(), array $a <ide> $this->build($aro); <ide> } <ide> <del> <ide> /** <ide> * From the perspective of the given ARO, walk down the tree and <ide> * collect all inherited AROs levelwise such that AROs from different <ide> public function roles($aro) { <ide> list($element, $depth) = array_pop($stack); <ide> $aros[$depth][] = $element; <ide> <del> foreach ($this->tree as $node => $children) { <add> foreach ($this->_tree as $node => $children) { <ide> if (in_array($element, $children)) { <ide> array_push($stack, array($node, $depth + 1)); <ide> } <ide> public function roles($aro) { <ide> return array_reverse($aros); <ide> } <ide> <del> <ide> /** <ide> * resolve an ARO identifier to an internal ARO string using <ide> * the internal mapping information. <ide> public function resolve($aro) { <ide> <ide> if (is_array($aro)) { <ide> if (isset($aro['model']) && isset($aro['foreign_key']) && $aro['model'] == $aroGroup) { <del> $mapped = $aroGroup . '/' . $aro['foreign_key']; <add> $mapped = $aroGroup . '/' . $aro['foreign_key']; <ide> } elseif (isset($aro[$model][$field])) { <ide> $mapped = $aroGroup . '/' . $aro[$model][$field]; <ide> } elseif (isset($aro[$field])) { <ide> public function resolve($aro) { <ide> if (strpos($aro, '/') === false) { <ide> $mapped = $aroGroup . '/' . $aro; <ide> } else { <del> list($aroModel, $aroValue) = explode('/', $aro, 2); <add> list($aroModel, $aroValue) = explode('/', $aro, 2); <ide> <ide> $aroModel = Inflector::camelize($aroModel); <ide> <ide> public function resolve($aro) { <ide> } <ide> } <ide> } <del> <del> if (isset($this->tree[$mapped])) { <add> <add> if (isset($this->_tree[$mapped])) { <ide> return $mapped; <ide> } <del> <add> <ide> // is there a matching alias defined (e.g. Role/1 => Role/admin)? <ide> if (!empty($this->aliases[$mapped])) { <ide> return $this->aliases[$mapped]; <ide> } <del> <ide> } <del> <ide> return self::DEFAULT_ROLE; <ide> } <ide> <del> <ide> /** <ide> * adds a new ARO to the tree <ide> * <ide> public function resolve($aro) { <ide> */ <ide> public function addRole(array $aro) { <ide> foreach ($aro as $role => $inheritedRoles) { <del> if (!isset($this->tree[$role])) { <del> $this->tree[$role] = array(); <add> if (!isset($this->_tree[$role])) { <add> $this->_tree[$role] = array(); <ide> } <ide> <ide> if (!empty($inheritedRoles)) { <ide> if (is_string($inheritedRoles)) { <ide> $inheritedRoles = array_map('trim', explode(',', $inheritedRoles)); <del> } <del> <add> } <add> <ide> foreach ($inheritedRoles as $dependency) { <ide> // detect cycles <ide> $roles = $this->roles($dependency); <del> <add> <ide> if (in_array($role, Set::flatten($roles))) { <ide> $path = ''; <ide> <ide> foreach ($roles as $roleDependencies) { <ide> $path .= implode('|', (array)$roleDependencies) . ' -> '; <ide> } <ide> <del> trigger_error(__d('cake_dev', 'cycle detected when inheriting %s from %s. Path: %s', $role, $dependency, $path.$role)); <add> trigger_error(__d('cake_dev', 'cycle detected when inheriting %s from %s. Path: %s', $role, $dependency, $path . $role)); <ide> continue; <ide> } <del> <del> if (!isset($this->tree[$dependency])) { <del> $this->tree[$dependency] = array(); <add> <add> if (!isset($this->_tree[$dependency])) { <add> $this->_tree[$dependency] = array(); <ide> } <del> <del> $this->tree[$dependency][] = $role; <add> <add> $this->_tree[$dependency][] = $role; <ide> } <ide> } <ide> } <ide> public function addAlias(array $alias) { <ide> * @return void <ide> */ <ide> public function build(array $aros) { <del> $this->tree = array(); <add> $this->_tree = array(); <ide> $this->addRole($aros); <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component/AclComponent.php <ide> public function revoke($aro, $aco, $action = "*") { <ide> trigger_error(__d('cake_dev', 'AclComponent::revoke() is deprecated, use deny() instead'), E_USER_WARNING); <ide> return $this->_Instance->deny($aro, $aco, $action); <ide> } <del>} <del> <ide> <add>} <ide><path>lib/Cake/Controller/Component/Auth/ActionsAuthorize.php <ide> public function authorize($user, CakeRequest $request) { <ide> $user = array($this->settings['userModel'] => $user); <ide> return $Acl->check($user, $this->action($request)); <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component/Auth/BaseAuthenticate.php <ide> abstract public function authenticate(CakeRequest $request, CakeResponse $respon <ide> * @param array $user The user about to be logged out. <ide> * @return void <ide> */ <del> public function logout($user) { } <add> public function logout($user) { <add> } <ide> <ide> /** <ide> * Get a user based on information in the request. Primarily used by stateless authentication <ide> public function logout($user) { } <ide> public function getUser($request) { <ide> return false; <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component/Auth/BaseAuthorize.php <ide> * @see AuthComponent::$authenticate <ide> */ <ide> abstract class BaseAuthorize { <add> <ide> /** <ide> * Controller for the request. <ide> * <ide> public function mapActions($map = array()) { <ide> } <ide> } <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component/Auth/BasicAuthenticate.php <ide> * @since 2.0 <ide> */ <ide> class BasicAuthenticate extends BaseAuthenticate { <add> <ide> /** <ide> * Settings for this object. <ide> * <ide> public function getUser($request) { <ide> public function loginHeaders() { <ide> return sprintf('WWW-Authenticate: Basic realm="%s"', $this->settings['realm']); <ide> } <del>} <ide>\ No newline at end of file <add> <add>} <ide><path>lib/Cake/Controller/Component/Auth/ControllerAuthorize.php <ide> public function controller(Controller $controller = null) { <ide> * @return boolean <ide> */ <ide> public function authorize($user, CakeRequest $request) { <del> return (bool) $this->_Controller->isAuthorized($user); <add> return (bool)$this->_Controller->isAuthorized($user); <ide> } <ide> <del>} <ide>\ No newline at end of file <add>} <ide><path>lib/Cake/Controller/Component/Auth/CrudAuthorize.php <ide> public function authorize($user, CakeRequest $request) { <ide> $this->settings['actionMap'][$request->params['action']] <ide> ); <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component/Auth/DigestAuthenticate.php <ide> * @since 2.0 <ide> */ <ide> class DigestAuthenticate extends BaseAuthenticate { <add> <ide> /** <ide> * Settings for this object. <ide> * <ide> class DigestAuthenticate extends BaseAuthenticate { <ide> * - `realm` The realm authentication is for, Defaults to the servername. <ide> * - `nonce` A nonce used for authentication. Defaults to `uniqid()`. <ide> * - `qop` Defaults to auth, no other values are supported at this time. <del> * - `opaque` A string that must be returned unchanged by clients. Defaults to `md5($settings['realm'])` <add> * - `opaque` A string that must be returned unchanged by clients. <add> * Defaults to `md5($settings['realm'])` <ide> * <ide> * @var array <ide> */ <ide> public function loginHeaders() { <ide> } <ide> return 'WWW-Authenticate: Digest ' . implode(',', $opts); <ide> } <del>} <ide>\ No newline at end of file <add> <add>} <ide><path>lib/Cake/Controller/Component/AuthComponent.php <ide> public function loggedIn() { <ide> public function flash($message) { <ide> $this->Session->setFlash($message, $this->flash['element'], $this->flash['params'], $this->flash['key']); <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component/CookieComponent.php <ide> protected function _encrypt($value) { <ide> <ide> if ($this->_encrypted === true) { <ide> $type = $this->_type; <del> $value = "Q2FrZQ==." .base64_encode(Security::$type($value, $this->key)); <add> $value = "Q2FrZQ==." . base64_encode(Security::$type($value, $this->key)); <ide> } <ide> return $value; <ide> } <ide> protected function _explode($string) { <ide> } <ide> return $array; <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component/PaginatorComponent.php <ide> public function paginate($object = null, $scope = array(), $whitelist = array()) <ide> protected function _getObject($object) { <ide> if (is_string($object)) { <ide> $assoc = null; <del> if (strpos($object, '.') !== false) { <add> if (strpos($object, '.') !== false) { <ide> list($object, $assoc) = pluginSplit($object); <ide> } <ide> <ide> public function validateSort($object, $options, $whitelist = array()) { <ide> * @return array An array of options for pagination <ide> */ <ide> public function checkLimit($options) { <del> $options['limit'] = (int) $options['limit']; <add> $options['limit'] = (int)$options['limit']; <ide> if (empty($options['limit']) || $options['limit'] < 1) { <ide> $options['limit'] = 1; <ide> } <ide> $options['limit'] = min((int)$options['limit'], $options['maxLimit']); <ide> return $options; <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/Component/RequestHandlerComponent.php <ide> public function convertXml($xml) { <ide> return Xml::toArray($xml->data); <ide> } <ide> return Xml::toArray($xml); <del> } catch (XmlException $e) { <add> } catch (XmlException $e) { <ide> return array(); <del> } <add> } <ide> } <ide> <ide> /** <ide><path>lib/Cake/Controller/Component/SecurityComponent.php <ide> protected function _authRequired(Controller $controller) { <ide> $tData = $this->Session->read('_Token'); <ide> <ide> if ( <del> !empty($tData['allowedControllers']) && <del> !in_array($this->request->params['controller'], $tData['allowedControllers']) || <del> !empty($tData['allowedActions']) && <add> !empty($tData['allowedControllers']) && <add> !in_array($this->request->params['controller'], $tData['allowedControllers']) || <add> !empty($tData['allowedActions']) && <ide> !in_array($this->request->params['action'], $tData['allowedActions']) <ide> ) { <ide> if (!$this->blackHole($controller, 'auth')) { <ide> protected function _callback(Controller $controller, $method, $params = array()) <ide> return null; <ide> } <ide> } <add> <ide> } <ide><path>lib/Cake/Controller/ComponentCollection.php <ide> public function implementedEvents() { <ide> 'Controller.shutdown' => array('callable' => 'trigger'), <ide> ); <ide> } <del>} <ide>\ No newline at end of file <add> <add>} <ide><path>lib/Cake/Controller/Controller.php <ide> <?php <ide> /** <del> * Base controller class. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> class Controller extends Object implements CakeEventListener { <ide> */ <ide> public $viewVars = array(); <ide> <del> <ide> /** <ide> * The name of the view file to render. The name specified <ide> * is the filename in /app/View/<SubFolder> without the .ctp extension. <ide> class Controller extends Object implements CakeEventListener { <ide> */ <ide> public function __construct($request = null, $response = null) { <ide> if ($this->name === null) { <del> $this->name = substr(get_class($this), 0, strlen(get_class($this)) -10); <add> $this->name = substr(get_class($this), 0, strlen(get_class($this)) - 10); <ide> } <ide> <ide> if ($this->viewPath == null) { <ide> public function setRequest(CakeRequest $request) { <ide> * <ide> * @param CakeRequest $request <ide> * @return mixed The resulting response. <del> * @throws PrivateActionException, MissingActionException <add> * @throws PrivateActionException When actions are not public or prefixed by _ <add> * @throws MissingActionException When actions are not defined and scaffolding is <add> * not enabled. <ide> */ <ide> public function invokeAction(CakeRequest $request) { <ide> try { <ide> public function constructClasses() { <ide> $this->_mergeControllerVars(); <ide> $this->Components->init($this); <ide> if ($this->uses) { <del> $this->uses = (array) $this->uses; <add> $this->uses = (array)$this->uses; <ide> list(, $this->modelClass) = pluginSplit(current($this->uses)); <ide> } <ide> return true; <ide> public function postConditions($data = array(), $op = null, $bool = 'AND', $excl <ide> } <ide> $fieldOp = strtoupper(trim($fieldOp)); <ide> if ($fieldOp === 'LIKE') { <del> $key = $key.' LIKE'; <add> $key = $key . ' LIKE'; <ide> $value = '%' . $value . '%'; <ide> } elseif ($fieldOp && $fieldOp != '=') { <del> $key = $key.' ' . $fieldOp; <add> $key = $key . ' ' . $fieldOp; <ide> } <ide> $cond[$key] = $value; <ide> } <ide><path>lib/Cake/Controller/Scaffold.php <ide> public function __construct(Controller $controller, CakeRequest $request) { <ide> $this->ScaffoldModel = $this->controller->{$this->modelClass}; <ide> $this->scaffoldTitle = Inflector::humanize(Inflector::underscore($this->viewPath)); <ide> $this->scaffoldActions = $controller->scaffold; <del> $title_for_layout = __d('cake', 'Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle; <add> $title = __d('cake', 'Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle; <ide> $modelClass = $this->controller->modelClass; <ide> $primaryKey = $this->ScaffoldModel->primaryKey; <ide> $displayField = $this->ScaffoldModel->displayField; <ide> public function __construct(Controller $controller, CakeRequest $request) { <ide> 'title_for_layout', 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar', <ide> 'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations' <ide> )); <add> $this->set('title_for_layout', $title); <ide> <ide> if ($this->controller->viewClass) { <ide> $this->controller->viewClass = 'Scaffold'; <ide> protected function _scaffoldSave(CakeRequest $request, $action = 'edit') { <ide> * <ide> * @param CakeRequest $request Request for scaffolding <ide> * @return mixed Success on delete, error if delete fails <del> * @throws MethodNotAllowedException, NotFoundException <add> * @throws MethodNotAllowedException When HTTP method is not a DELETE <add> * @throws NotFoundException When id being deleted does not exist. <ide> */ <ide> protected function _scaffoldDelete(CakeRequest $request) { <ide> if ($this->controller->beforeScaffold('delete')) { <ide> protected function _scaffoldError() { <ide> * <ide> * @param CakeRequest $request Request object for scaffolding <ide> * @return mixed A rendered view of scaffold action, or showing the error <del> * @throws MissingActionException, MissingDatabaseException <add> * @throws MissingActionException When methods are not scaffolded. <add> * @throws MissingDatabaseException When the database connection is undefined. <ide> */ <ide> protected function _scaffold(CakeRequest $request) { <ide> $db = ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig); <ide> protected function _associations() { <ide> } <ide> return $associations; <ide> } <add> <ide> }
22
Javascript
Javascript
fix a comment typo
561d5ddf76013aca18882f795d334db56d0002b7
<ide><path>src/js/component.js <ide> class Component { <ide> * <ide> * @param {Object} [options] <ide> * The key/value store of player options. <del> # <add> * <ide> * @param {Object[]} [options.children] <ide> * An array of children objects to intialize this component with. Children objects have <ide> * a name property that will be used if more than one component of the same type needs to be
1
PHP
PHP
add missing docblock, remove unneeded code
ab7dd99e436d5ce78b5857f7149dc5f030d5b341
<ide><path>lib/Cake/Test/Case/Controller/Component/RequestHandlerComponentTest.php <ide> public function ajax2_layout() { <ide> <ide> } <ide> <del>class CustomJsonView extends JsonView { <del> <ide> /** <del> * Test method for viewClassMap and overriding _serialize() <add> * CustomJsonView class <add> * <add> * @package Cake.Test.Case.Controller.Component <ide> */ <del> protected function _serialize($serialize) { <del> return json_encode(array('return' => 'ok')); <del> } <del>} <add>class CustomJsonView extends JsonView {} <ide> <ide> /** <ide> * RequestHandlerComponentTest class
1
PHP
PHP
remove \ and replace with use
42e77f85eebfdd978d235a031baf3e5f2d4eae16
<ide><path>src/Cache/Engine/MemcachedEngine.php <ide> use Cake\Cache\CacheEngine; <ide> use Cake\Error; <ide> use Cake\Utility\Inflector; <add>use \Memcached; <ide> <ide> /** <ide> * Memcached storage engine for cache. Memcached has some limitations in the amount of <ide> public function init(array $config = []) { <ide> } <ide> <ide> $this->_serializers = [ <del> 'igbinary' => \Memcached::SERIALIZER_IGBINARY, <del> 'json' => \Memcached::SERIALIZER_JSON, <del> 'php' => \Memcached::SERIALIZER_PHP <add> 'igbinary' => Memcached::SERIALIZER_IGBINARY, <add> 'json' => Memcached::SERIALIZER_JSON, <add> 'php' => Memcached::SERIALIZER_PHP <ide> ]; <del> if (defined('Memcached::HAVE_MSGPACK') && \Memcached::HAVE_MSGPACK) { <del> $this->_serializers['msgpack'] = \Memcached::SERIALIZER_MSGPACK; <add> if (defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK) { <add> $this->_serializers['msgpack'] = Memcached::SERIALIZER_MSGPACK; <ide> } <ide> <ide> parent::init($config); <ide> public function init(array $config = []) { <ide> return true; <ide> } <ide> <del> $this->_Memcached = new \Memcached($this->_config['persistent'] ? (string)$this->_config['persistent'] : null); <add> $this->_Memcached = new Memcached($this->_config['persistent'] ? (string)$this->_config['persistent'] : null); <ide> $this->_setOptions(); <ide> <ide> if (count($this->_Memcached->getServerList())) { <ide> public function init(array $config = []) { <ide> * @throws \Cake\Error\Exception when the Memcached extension is not built with the desired serializer engine <ide> */ <ide> protected function _setOptions() { <del> $this->_Memcached->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true); <add> $this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true); <ide> <ide> $serializer = strtolower($this->_config['serialize']); <ide> if (!isset($this->_serializers[$serializer])) { <ide> protected function _setOptions() { <ide> ); <ide> } <ide> <del> $this->_Memcached->setOption(\Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]); <add> $this->_Memcached->setOption(Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]); <ide> <ide> // Check for Amazon ElastiCache instance <ide> if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) { <del> $this->_Memcached->setOption(\Memcached::OPT_CLIENT_MODE, \Memcached::DYNAMIC_CLIENT_MODE); <add> $this->_Memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE); <ide> } <ide> <del> $this->_Memcached->setOption(\Memcached::OPT_COMPRESSION, (bool)$this->_config['compress']); <add> $this->_Memcached->setOption(Memcached::OPT_COMPRESSION, (bool)$this->_config['compress']); <ide> } <ide> <ide> /**
1
PHP
PHP
remove blank line starting control structure
546be6c683277753bcce642ca8e14461b06e35ef
<ide><path>src/Routing/Router.php <ide> public static function routeExists($url = null, $full = false) <ide> <ide> return true; <ide> } catch (MissingRouteException $e) { <del> <ide> return false; <ide> } <ide> }
1
Ruby
Ruby
extract repetitive method
d0bcf51191d71edfddf38ade6ff7a3099ba23a54
<ide><path>activesupport/test/dependencies_test.rb <ide> def with_loading(*from) <ide> ActiveSupport::Dependencies.explicitly_unloadable_constants = [] <ide> end <ide> <add> def with_autoloading_fixtures(&block) <add> with_loading 'autoloading_fixtures', &block <add> end <add> <ide> def test_tracking_loaded_files <ide> require_dependency 'dependencies/service_one' <ide> require_dependency 'dependencies/service_two' <ide> def test_as_load_path <ide> end <ide> <ide> def test_module_loading <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_kind_of Module, A <ide> assert_kind_of Class, A::B <ide> assert_kind_of Class, A::C::D <ide> def test_module_loading <ide> end <ide> <ide> def test_non_existing_const_raises_name_error <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_raise(NameError) { DoesNotExist } <ide> assert_raise(NameError) { NoModule::DoesNotExist } <ide> assert_raise(NameError) { A::DoesNotExist } <ide> def test_non_existing_const_raises_name_error <ide> end <ide> <ide> def test_directories_manifest_as_modules_unless_const_defined <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_kind_of Module, ModuleFolder <ide> Object.__send__ :remove_const, :ModuleFolder <ide> end <ide> end <ide> <ide> def test_module_with_nested_class <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_kind_of Class, ModuleFolder::NestedClass <ide> Object.__send__ :remove_const, :ModuleFolder <ide> end <ide> end <ide> <ide> def test_module_with_nested_inline_class <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_kind_of Class, ModuleFolder::InlineClass <ide> Object.__send__ :remove_const, :ModuleFolder <ide> end <ide> end <ide> <ide> def test_directories_may_manifest_as_nested_classes <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_kind_of Class, ClassFolder <ide> Object.__send__ :remove_const, :ClassFolder <ide> end <ide> end <ide> <ide> def test_class_with_nested_class <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_kind_of Class, ClassFolder::NestedClass <ide> Object.__send__ :remove_const, :ClassFolder <ide> end <ide> end <ide> <ide> def test_class_with_nested_inline_class <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_kind_of Class, ClassFolder::InlineClass <ide> Object.__send__ :remove_const, :ClassFolder <ide> end <ide> end <ide> <ide> def test_class_with_nested_inline_subclass_of_parent <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_kind_of Class, ClassFolder::ClassFolderSubclass <ide> assert_kind_of Class, ClassFolder <ide> assert_equal 'indeed', ClassFolder::ClassFolderSubclass::ConstantInClassFolder <ide> def test_class_with_nested_inline_subclass_of_parent <ide> end <ide> <ide> def test_nested_class_can_access_sibling <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> sibling = ModuleFolder::NestedClass.class_eval "NestedSibling" <ide> assert defined?(ModuleFolder::NestedSibling) <ide> assert_equal ModuleFolder::NestedSibling, sibling <ide> def test_nested_class_can_access_sibling <ide> end <ide> <ide> def failing_test_access_thru_and_upwards_fails <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert ! defined?(ModuleFolder) <ide> assert_raise(NameError) { ModuleFolder::Object } <ide> assert_raise(NameError) { ModuleFolder::NestedClass::Object } <ide> def failing_test_access_thru_and_upwards_fails <ide> end <ide> <ide> def test_non_existing_const_raises_name_error_with_fully_qualified_name <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> begin <ide> A::DoesNotExist.nil? <ide> flunk "No raise!!" <ide> def test_qualified_const_defined_should_not_call_method_missing <ide> end <ide> <ide> def test_autoloaded? <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder") <ide> assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass") <ide> <ide> module A <ide> end <ide> end_eval <ide> <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert_kind_of Integer, ::ModuleWithCustomConstMissing::B <ide> assert_kind_of Module, ::ModuleWithCustomConstMissing::A <ide> assert_kind_of String, ::ModuleWithCustomConstMissing::A::B <ide> module A <ide> <ide> def test_const_missing_should_not_double_load <ide> $counting_loaded_times = 0 <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> require_dependency '././counting_loader' <ide> assert_equal 1, $counting_loaded_times <ide> assert_raise(ArgumentError) { ActiveSupport::Dependencies.load_missing_constant Object, :CountingLoader } <ide> def test_const_missing_within_anonymous_module <ide> m.module_eval "def a() CountingLoader; end" <ide> extend m <ide> kls = nil <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> kls = nil <ide> assert_nothing_raised { kls = a } <ide> assert_equal "CountingLoader", kls.name <ide> def test_nested_load_error_isnt_rescued <ide> end <ide> <ide> def test_load_once_paths_do_not_add_to_autoloaded_constants <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> ActiveSupport::Dependencies.load_once_paths = ActiveSupport::Dependencies.load_paths.dup <ide> <ide> assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder") <ide> def test_load_once_paths_do_not_add_to_autoloaded_constants <ide> end <ide> <ide> def test_application_should_special_case_application_controller <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> require_dependency 'application' <ide> assert_equal 10, ApplicationController <ide> assert ActiveSupport::Dependencies.autoloaded?(:ApplicationController) <ide> end <ide> end <ide> <ide> def test_const_missing_on_kernel_should_fallback_to_object <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> kls = Kernel::E <ide> assert_equal "E", kls.name <ide> assert_equal kls.object_id, Kernel::E.object_id <ide> end <ide> end <ide> <ide> def test_preexisting_constants_are_not_marked_as_autoloaded <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> require_dependency 'e' <ide> assert ActiveSupport::Dependencies.autoloaded?(:E) <ide> ActiveSupport::Dependencies.clear <ide> end <ide> <ide> Object.const_set :E, Class.new <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> require_dependency 'e' <ide> assert ! ActiveSupport::Dependencies.autoloaded?(:E), "E shouldn't be marked autoloaded!" <ide> ActiveSupport::Dependencies.clear <ide> def test_preexisting_constants_are_not_marked_as_autoloaded <ide> end <ide> <ide> def test_unloadable <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> Object.const_set :M, Module.new <ide> M.unloadable <ide> <ide> def test_unloadable <ide> end <ide> <ide> def test_unloadable_should_fail_with_anonymous_modules <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> m = Module.new <ide> assert_raise(ArgumentError) { m.unloadable } <ide> end <ide> end <ide> <ide> def test_unloadable_should_return_change_flag <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> Object.const_set :M, Module.new <ide> assert_equal true, M.unloadable <ide> assert_equal false, M.unloadable <ide> def test_new_constants_in_with_illegal_module_name_raises_correct_error <ide> end <ide> <ide> def test_file_with_multiple_constants_and_require_dependency <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert ! defined?(MultipleConstantFile) <ide> assert ! defined?(SiblingConstant) <ide> <ide> def test_file_with_multiple_constants_and_require_dependency <ide> end <ide> <ide> def test_file_with_multiple_constants_and_auto_loading <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert ! defined?(MultipleConstantFile) <ide> assert ! defined?(SiblingConstant) <ide> <ide> def test_file_with_multiple_constants_and_auto_loading <ide> end <ide> <ide> def test_nested_file_with_multiple_constants_and_require_dependency <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert ! defined?(ClassFolder::NestedClass) <ide> assert ! defined?(ClassFolder::SiblingClass) <ide> <ide> def test_nested_file_with_multiple_constants_and_require_dependency <ide> end <ide> <ide> def test_nested_file_with_multiple_constants_and_auto_loading <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert ! defined?(ClassFolder::NestedClass) <ide> assert ! defined?(ClassFolder::SiblingClass) <ide> <ide> def test_nested_file_with_multiple_constants_and_auto_loading <ide> end <ide> <ide> def test_autoload_doesnt_shadow_no_method_error_with_relative_constant <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it hasn't been referenced yet!" <ide> 2.times do <ide> assert_raise(NoMethodError) { RaisesNoMethodError } <ide> def test_autoload_doesnt_shadow_no_method_error_with_relative_constant <ide> end <ide> <ide> def test_autoload_doesnt_shadow_no_method_error_with_absolute_constant <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it hasn't been referenced yet!" <ide> 2.times do <ide> assert_raise(NoMethodError) { ::RaisesNoMethodError } <ide> def test_autoload_doesnt_shadow_no_method_error_with_absolute_constant <ide> end <ide> <ide> def test_autoload_doesnt_shadow_error_when_mechanism_not_set_to_load <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> ActiveSupport::Dependencies.mechanism = :require <ide> 2.times do <ide> assert_raise(NameError) { assert_equal 123, ::RaisesNameError::FooBarBaz } <ide> def test_autoload_doesnt_shadow_error_when_mechanism_not_set_to_load <ide> end <ide> <ide> def test_autoload_doesnt_shadow_name_error <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> Object.send(:remove_const, :RaisesNameError) if defined?(::RaisesNameError) <ide> 2.times do <ide> begin <ide> def test_remove_constant_handles_double_colon_at_start <ide> end <ide> <ide> def test_load_once_constants_should_not_be_unloaded <del> with_loading 'autoloading_fixtures' do <add> with_autoloading_fixtures do <ide> ActiveSupport::Dependencies.load_once_paths = ActiveSupport::Dependencies.load_paths <ide> ::A.to_s <ide> assert defined?(A)
1
Python
Python
remove repeating prefetch
a3369cd4576a27a9f6613f561d9d8b68b85f7de8
<ide><path>official/core/input_reader.py <ide> def maybe_map_fn(dataset, fn): <ide> service=self._tf_data_service_address, <ide> job_name=self._tf_data_service_job_name)) <ide> <del> dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) <del> <ide> if self._deterministic is not None: <ide> options = tf.data.Options() <ide> options.experimental_deterministic = self._deterministic
1
Python
Python
add template_ext to bigqueryinsertjoboperator
e33f1a12d72ac234e4897f44b326a332acf85901
<ide><path>airflow/providers/google/cloud/operators/bigquery.py <ide> class BigQueryInsertJobOperator(BaseOperator): <ide> """ <ide> <ide> template_fields = ("configuration", "job_id") <add> template_ext = (".json", ) <ide> ui_color = BigQueryUIColors.QUERY.value <ide> <ide> def __init__( <ide> def __init__( <ide> self.gcp_conn_id = gcp_conn_id <ide> self.delegate_to = delegate_to <ide> <add> def prepare_template(self) -> None: <add> # If .json is passed then we have to read the file <add> if isinstance(self.configuration, str) and self.configuration.endswith('.json'): <add> with open(self.configuration, 'r') as file: <add> self.configuration = json.loads(file.read()) <add> <ide> def execute(self, context: Any): <ide> hook = BigQueryHook( <ide> gcp_conn_id=self.gcp_conn_id,
1
Ruby
Ruby
eliminate newlines in basic auth. fixes
f6ced69a11cdff56c2e87b84e775ef09c6d999d1
<ide><path>actionpack/lib/action_controller/metal/http_authentication.rb <ide> def decode_credentials(request) <ide> end <ide> <ide> def encode_credentials(user_name, password) <del> "Basic #{ActiveSupport::Base64.encode64("#{user_name}:#{password}")}" <add> "Basic #{ActiveSupport::Base64.encode64s("#{user_name}:#{password}")}" <ide> end <ide> <ide> def authentication_request(controller, realm) <ide><path>actionpack/test/controller/http_basic_authentication_test.rb <ide> def authenticate_long_credentials <ide> end <ide> end <ide> <add> def test_encode_credentials_has_no_newline <add> username = 'laskjdfhalksdjfhalkjdsfhalksdjfhklsdjhalksdjfhalksdjfhlakdsjfh' <add> password = 'kjfhueyt9485osdfasdkljfh4lkjhakldjfhalkdsjf' <add> result = ActionController::HttpAuthentication::Basic.encode_credentials( <add> username, password) <add> assert_no_match(/\n/, result) <add> end <add> <ide> test "authentication request without credential" do <ide> get :display <ide>
2
Text
Text
replace vague 'may not' with definitive 'will not'
a82ac6eedf925b8922ca2e577d0364a62dea5ad7
<ide><path>doc/api/modules.md <ide> Modules are cached after the first time they are loaded. This means <ide> (among other things) that every call to `require('foo')` will get <ide> exactly the same object returned, if it would resolve to the same file. <ide> <del>Multiple calls to `require('foo')` may not cause the module code to be <del>executed multiple times. This is an important feature. With it, <del>"partially done" objects can be returned, thus allowing transitive <del>dependencies to be loaded even when they would cause cycles. <add>Provided `require.cache` is not modified, multiple calls to <add>`require('foo')` will not cause the module code to be executed multiple times. <add>This is an important feature. With it, "partially done" objects can be returned, <add>thus allowing transitive dependencies to be loaded even when they would cause <add>cycles. <ide> <ide> To have a module execute code multiple times, export a function, and call <ide> that function.
1
Ruby
Ruby
ensure new casks have a description
549cd5b47121e2b7b065c119eec80446b9658439
<ide><path>Library/Homebrew/cask/audit.rb <ide> class Audit <ide> <ide> attr_reader :cask, :commit_range, :download <ide> <del> attr_predicate :appcast? <add> attr_predicate :appcast?, :new_cask?, :strict?, :online? <ide> <ide> def initialize(cask, appcast: false, download: false, quarantine: nil, <ide> token_conflicts: false, online: false, strict: false, <ide> def run! <ide> check_required_stanzas <ide> check_version <ide> check_sha256 <add> check_desc <ide> check_url <ide> check_generic_artifacts <ide> check_token_valid <ide> def check_hosting_with_appcast <ide> end <ide> end <ide> <add> def check_desc <add> return unless new_cask? <add> <add> return if cask.desc.present? <add> <add> add_warning "Cask should have a description. Please add a `desc` stanza." <add> end <add> <ide> def check_url <ide> return unless cask.url <ide> <ide> def check_token_conflicts <ide> end <ide> <ide> def check_token_valid <del> return unless @strict <add> return unless strict? <ide> <ide> add_warning "cask token is not lowercase" if cask.token.downcase! <ide> <ide> def check_token_valid <ide> end <ide> <ide> def check_token_bad_words <del> return unless @strict <add> return unless strict? <ide> <ide> token = cask.token <ide> <ide> def check_bitbucket_repository <ide> end <ide> <ide> def get_repo_data(regex) <del> return unless @online <del> return unless @new_cask <add> return unless online? <add> return unless new_cask? <ide> <ide> _, user, repo = *regex.match(cask.url.to_s) <ide> _, user, repo = *regex.match(cask.homepage) unless user <ide><path>Library/Homebrew/test/cask/audit_spec.rb <ide> def include_msg?(messages, msg) <ide> let(:download) { false } <ide> let(:token_conflicts) { false } <ide> let(:strict) { false } <add> let(:new_cask) { false } <ide> let(:fake_system_command) { class_double(SystemCommand) } <ide> let(:audit) { <ide> described_class.new(cask, download: download, <ide> token_conflicts: token_conflicts, <ide> command: fake_system_command, <del> strict: strict) <add> strict: strict, <add> new_cask: new_cask) <ide> } <ide> <ide> describe "#result" do <ide> def tmp_cask(name, text) <ide> expect(subject).to fail_with(/exception while auditing/) <ide> end <ide> end <add> <add> describe "without description" do <add> let(:cask_token) { "without-description" } <add> let(:cask) do <add> tmp_cask cask_token.to_s, <<~RUBY <add> cask '#{cask_token}' do <add> version '1.0' <add> sha256 '8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a' <add> url "https://brew.sh/" <add> name 'Audit' <add> homepage 'https://brew.sh/' <add> app 'Audit.app' <add> end <add> RUBY <add> end <add> <add> context "when `new_cask` is true" do <add> let(:new_cask) { true } <add> <add> it "warns" do <add> expect(subject).to warn_with(/should have a description/) <add> end <add> end <add> <add> context "when `new_cask` is true" do <add> let(:new_cask) { false } <add> <add> it "does not warn" do <add> expect(subject).not_to warn_with(/should have a description/) <add> end <add> end <add> end <add> <add> context "with description" do <add> let(:cask_token) { "with-description" } <add> let(:cask) do <add> tmp_cask cask_token.to_s, <<~RUBY <add> cask '#{cask_token}' do <add> version '1.0' <add> sha256 '8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a' <add> url "https://brew.sh/" <add> name 'Audit' <add> desc 'Cask Auditor' <add> homepage 'https://brew.sh/' <add> app 'Audit.app' <add> end <add> RUBY <add> end <add> <add> it "does not warn" do <add> expect(subject).not_to warn_with(/should have a description/) <add> end <add> end <ide> end <ide> end
2
Mixed
Java
change time drift error into warning
ed4db631faf0091a92179e9fd629ce06e4704d1e
<ide><path>Libraries/JavaScriptAppEngine/System/JSTimers/JSTimersExecution.js <ide> var performanceNow = require('fbjs/lib/performanceNow'); <ide> var warning = require('fbjs/lib/warning'); <ide> var Systrace = require('Systrace'); <ide> <add>let hasEmittedTimeDriftWarning = false; <add> <ide> /** <ide> * JS implementation of timer functions. Must be completely driven by an <ide> * external clock signal, all that's stored here is timerID, timer type, and <ide> var JSTimersExecution = { <ide> } <ide> }, <ide> <add> /** <add> * Called from native (in development) when environment times are out-of-sync. <add> */ <add> emitTimeDriftWarning: function(warningMessage) { <add> if (hasEmittedTimeDriftWarning) { <add> return; <add> } <add> hasEmittedTimeDriftWarning = true; <add> console.warn(warningMessage); <add> }, <add> <ide> _clearIndex: function(i) { <ide> JSTimersExecution.timerIDs[i] = null; <ide> JSTimersExecution.callbacks[i] = null; <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/core/JSTimersExecution.java <ide> public interface JSTimersExecution extends JavaScriptModule { <ide> <ide> public void callTimers(WritableArray timerIDs); <add> <add> public void emitTimeDriftWarning(String warningMessage); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/core/Timing.java <ide> public void createTimer( <ide> if (mDevSupportManager.getDevSupportEnabled()) { <ide> long driftTime = Math.abs(remoteTime - deviceTime); <ide> if (driftTime > 60000) { <del> throw new RuntimeException( <del> "Debugger and device times have drifted by more than 60s." + <del> "Please correct this by running adb shell " + <del> "\"date `date +%m%d%H%M%Y.%S`\" on your debugger machine." <del> ); <add> getReactApplicationContext().getJSModule(executorToken, JSTimersExecution.class) <add> .emitTimeDriftWarning( <add> "Debugger and device times have drifted by more than 60s. Please correct this by " + <add> "running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine."); <ide> } <ide> } <ide>
3
Python
Python
remove wrong mention of .gz in np.load
6e2a69bb7a42b0b518f5a54cb949eb0f21c43331
<ide><path>numpy/lib/npyio.py <ide> def load(file, mmap_mode=None): <ide> Parameters <ide> ---------- <ide> file : file-like object or string <del> The file to read. Compressed files with the filename extension <del> ``.gz`` are acceptable. File-like objects must support the <add> The file to read. File-like objects must support the <ide> ``seek()`` and ``read()`` methods. Pickled files require that the <ide> file-like object support the ``readline()`` method as well. <ide> mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional
1
Python
Python
use get_primary_cpu_task from tpu_lib
cd85fd8a25fa8cb28f3df814b7a9ce61594b1597
<ide><path>official/bert/model_training_utils.py <ide> import tensorflow as tf <ide> from tensorflow.python.util import object_identity <ide> from official.utils.misc import distribution_utils <add>from official.utils.misc import tpu_lib <ide> <ide> _SUMMARY_TXT = 'training_summary.txt' <ide> _MIN_SUMMARY_STEPS = 10 <ide> <ide> <del>def get_primary_cpu_task(use_remote_tpu=False): <del> """Returns primary CPU task to which input pipeline Ops are put.""" <del> <del> # Remote Eager Borg job configures the TPU worker with job name 'worker'. <del> return '/job:worker' if use_remote_tpu else '' <del> <del> <ide> def _save_checkpoint(checkpoint, model_dir, checkpoint_prefix): <ide> """Saves model to with provided checkpoint prefix.""" <ide> <ide> def run_customized_training_loop( <ide> <ide> # To reduce unnecessary send/receive input pipeline operation, we place input <ide> # pipeline ops in worker task. <del> with tf.device(get_primary_cpu_task(use_remote_tpu)): <add> with tf.device(tpu_lib.get_primary_cpu_task(use_remote_tpu)): <ide> train_iterator = _get_input_iterator(train_input_fn, strategy) <ide> <ide> with distribution_utils.get_strategy_scope(strategy): <ide><path>official/bert/run_classifier.py <ide> def run_bert(strategy, input_meta_data): <ide> run_eagerly=FLAGS.run_eagerly) <ide> <ide> if FLAGS.model_export_path: <del> with tf.device(model_training_utils.get_primary_cpu_task(use_remote_tpu)): <add> with tf.device(tpu_lib.get_primary_cpu_task(use_remote_tpu)): <ide> model_saving_utils.export_bert_model( <ide> FLAGS.model_export_path, model=trained_model) <ide> return trained_model
2
Go
Go
fix network mode for lxc 1.0
0f278940947d74f2b7889ada18808779312f9608
<ide><path>daemon/execdriver/lxc/lxc_template.go <ide> lxc.network.type = veth <ide> lxc.network.link = {{.Network.Interface.Bridge}} <ide> lxc.network.name = eth0 <ide> lxc.network.mtu = {{.Network.Mtu}} <del>{{else if not .Network.HostNetworking}} <add>{{else if .Network.HostNetworking}} <add>lxc.network.type = none <add>{{else}} <ide> # network is disabled (-n=false) <ide> lxc.network.type = empty <ide> lxc.network.flags = up
1
Ruby
Ruby
use arrow character for ui prompts
d0ad829e43ab529b3bfd32a974f824633e6bc67c
<ide><path>Library/Homebrew/cask/artifact/abstract_uninstall.rb <ide> def running_processes(bundle_id) <ide> <ide> sig { returns(String) } <ide> def automation_access_instructions <del> "Enable Automation Access for “Terminal > System Events” in " \ <del> "“System Preferences > Security > Privacy > Automation” if you haven't already." <add> <<~EOS <add> Enable Automation access for "Terminal → System Events" in: <add> System Preferences → Security & Privacy → Privacy → Automation <add> if you haven't already. <add> EOS <ide> end <ide> <ide> # :quit/:signal must come before :kext so the kext will not be in use by a running process <ide><path>Library/Homebrew/cask/cmd/fetch.rb <ide> def run <ide> download = Download.new(cask, **options) <ide> download.clear_cache if args.force? <ide> downloaded_path = download.fetch <del> ohai "Success! Downloaded to -> #{downloaded_path}" <add> ohai "Success! Downloaded to: #{downloaded_path}" <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/cask/dsl/caveats.rb <ide> def eval_caveats(&block) <ide> end <ide> <ide> caveat :unsigned_accessibility do |access = "Accessibility"| <del> # access: the category in System Preferences -> Security & Privacy -> Privacy the app requires. <add> # access: the category in System Preferences > Security & Privacy > Privacy the app requires. <ide> <ide> <<~EOS <ide> #{@cask} is not signed and requires Accessibility access, <ide> so you will need to re-grant Accessibility access every time the app is updated. <ide> <ide> Enable or re-enable it in: <del> System Preferences → Security & Privacy → Privacy -> #{access} <del> To re-enable untick and retick #{@cask}.app. <add> System Preferences → Security & Privacy → Privacy → #{access} <add> To re-enable, untick and retick #{@cask}.app. <ide> EOS <ide> end <ide>
3
Javascript
Javascript
extend unit test for buildstyleinterpolator
3e31038301e9e3bf8a332b97ed869f8d9603d0b6
<ide><path>Libraries/Utilities/__tests__/buildStyleInterpolator-test.js <ide> describe('buildStyleInterpolator', function() { <ide> }); <ide> expect(res).toBe(false); <ide> }); <add> it('should handle identity', function() { <add> var testAnim = { <add> opacity: { <add> type: 'identity', <add> }, <add> }; <add> var interpolator = buildStyleInterpolator(testAnim); <add> var obj = {}; <add> var res = interpolator(obj, 0.5); <add> expect(obj).toEqual({ <add> opacity: 0.5, <add> }); <add> expect(res).toBe(true); <ide> <add> res = interpolator(obj, 0.5); <add> // No change detected <add> expect(obj).toEqual({ <add> opacity: 0.5, <add> }); <add> expect(res).toBe(false); <add> }); <add> it('should translate', function() { <add> var testAnim = { <add> transformTranslate: { <add> from: {x: 1, y: 10, z: 100}, <add> to: {x: 5, y: 50, z: 500}, <add> min: 0, <add> max: 4, <add> type: 'linear', <add> }, <add> }; <add> var interpolator = buildStyleInterpolator(testAnim); <add> var obj = {}; <add> var res = interpolator(obj, 1); <add> expect(obj).toEqual({ <add> transform: [{matrix: [1, 0, 0, 0, <add> 0, 1, 0, 0, <add> 0, 0, 1, 0, <add> 2, 20, 200, 1]}] <add> }); <add> expect(res).toBe(true); <add> }); <add> it('should scale', function() { <add> var testAnim = { <add> transformScale: { <add> from: {x: 1, y: 10, z: 100}, <add> to: {x: 5, y: 50, z: 500}, <add> min: 0, <add> max: 4, <add> type: 'linear', <add> }, <add> }; <add> var interpolator = buildStyleInterpolator(testAnim); <add> var obj = {}; <add> var res = interpolator(obj, 1); <add> expect(obj).toEqual({ <add> transform: [{matrix: [2, 0, 0, 0, <add> 0, 20, 0, 0, <add> 0, 0, 200, 0, <add> 0, 0, 0, 1]}] <add> }); <add> expect(res).toBe(true); <add> }); <add> it('should combine scale and translate', function() { <add> var testAnim = { <add> transformScale: { <add> from: {x: 1, y: 10, z: 100}, <add> to: {x: 5, y: 50, z: 500}, <add> min: 0, <add> max: 4, <add> type: 'linear', <add> }, <add> transformTranslate: { <add> from: {x: 1, y: 10, z: 100}, <add> to: {x: 5, y: 50, z: 500}, <add> min: 0, <add> max: 4, <add> type: 'linear', <add> }, <add> }; <add> var interpolator = buildStyleInterpolator(testAnim); <add> var obj = {}; <add> var res = interpolator(obj, 1); <add> expect(obj).toEqual({ <add> transform: [{matrix: [2, 0, 0, 0, <add> 0, 20, 0, 0, <add> 0, 0, 200, 0, <add> 4, 400, 40000, 1]}] <add> }); <add> expect(res).toBe(true); <add> }); <ide> it('should step', function() { <ide> var testAnim = { <ide> opacity: {
1
Go
Go
prepend hash method to the image checksum
ea3374bcb0b7a78ccbaeb9cd927fbaf259a5cf29
<ide><path>container.go <ide> func (container *Container) RwChecksum() (string, error) { <ide> if _, err := io.Copy(h, rwData); err != nil { <ide> return "", err <ide> } <del> return hex.EncodeToString(h.Sum(nil)), nil <add> return "sha256:"+hex.EncodeToString(h.Sum(nil)), nil <ide> } <ide> <ide> func (container *Container) Export() (Archive, error) {
1
Python
Python
remove unnecessary else statement
501a1cf0c7b31773fb02bc2966f5c1db99311b36
<ide><path>maths/karatsuba.py <ide> def karatsuba(a, b): <ide> """ <ide> if len(str(a)) == 1 or len(str(b)) == 1: <ide> return a * b <del> else: <del> m1 = max(len(str(a)), len(str(b))) <del> m2 = m1 // 2 <ide> <del> a1, a2 = divmod(a, 10**m2) <del> b1, b2 = divmod(b, 10**m2) <add> m1 = max(len(str(a)), len(str(b))) <add> m2 = m1 // 2 <ide> <del> x = karatsuba(a2, b2) <del> y = karatsuba((a1 + a2), (b1 + b2)) <del> z = karatsuba(a1, b1) <add> a1, a2 = divmod(a, 10**m2) <add> b1, b2 = divmod(b, 10**m2) <ide> <del> return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) <add> x = karatsuba(a2, b2) <add> y = karatsuba((a1 + a2), (b1 + b2)) <add> z = karatsuba(a1, b1) <add> <add> return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) <ide> <ide> <ide> def main():
1
Javascript
Javascript
fix coding style in src/display/api.js
a1ee567d60cf87a6d13d928655e0ffc67bd21fac
<ide><path>src/display/api.js <ide> * above this value will not be drawn. Use -1 for no limit. <ide> * @var {number} <ide> */ <del>PDFJS.maxImageSize = PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize; <add>PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? <add> -1 : PDFJS.maxImageSize); <ide> <ide> /** <ide> * The url of where the predefined Adobe CMaps are located. Include trailing <ide> * slash. <ide> * @var {string} <ide> */ <del>PDFJS.cMapUrl = PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl; <add>PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); <ide> <ide> /* <ide> * By default fonts are converted to OpenType fonts and loaded via font face <ide> * rules. If disabled, the font will be rendered using a built in font renderer <ide> * that constructs the glyphs with primitive path commands. <ide> * @var {boolean} <ide> */ <del>PDFJS.disableFontFace = PDFJS.disableFontFace === undefined ? <del> false : PDFJS.disableFontFace; <add>PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? <add> false : PDFJS.disableFontFace); <ide> <ide> /** <ide> * Path for image resources, mainly for annotation icons. Include trailing <ide> * slash. <ide> * @var {string} <ide> */ <del>PDFJS.imageResourcesPath = PDFJS.imageResourcesPath === undefined ? <del> '' : PDFJS.imageResourcesPath; <add>PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? <add> '' : PDFJS.imageResourcesPath); <ide> <ide> /** <ide> * Disable the web worker and run all code on the main thread. This will happen <ide> * automatically if the browser doesn't support workers or sending typed arrays <ide> * to workers. <ide> * @var {boolean} <ide> */ <del>PDFJS.disableWorker = PDFJS.disableWorker === undefined ? <del> false : PDFJS.disableWorker; <add>PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? <add> false : PDFJS.disableWorker); <ide> <ide> /** <ide> * Path and filename of the worker file. Required when the worker is enabled in <ide> * development mode. If unspecified in the production build, the worker will be <ide> * loaded based on the location of the pdf.js file. <ide> * @var {string} <ide> */ <del>PDFJS.workerSrc = PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc; <add>PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); <ide> <ide> /** <ide> * Disable range request loading of PDF files. When enabled and if the server <ide> * supports partial content requests then the PDF will be fetched in chunks. <ide> * Enabled (false) by default. <ide> * @var {boolean} <ide> */ <del>PDFJS.disableRange = PDFJS.disableRange === undefined ? <del> false : PDFJS.disableRange; <add>PDFJS.disableRange = (PDFJS.disableRange === undefined ? <add> false : PDFJS.disableRange); <ide> <ide> /** <ide> * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js <ide> * will automatically keep fetching more data even if it isn't needed to display <ide> * the current page. This default behavior can be disabled. <ide> * @var {boolean} <ide> */ <del>PDFJS.disableAutoFetch = PDFJS.disableAutoFetch === undefined ? <del> false : PDFJS.disableAutoFetch; <add>PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? <add> false : PDFJS.disableAutoFetch); <ide> <ide> /** <ide> * Enables special hooks for debugging PDF.js. <ide> * @var {boolean} <ide> */ <del>PDFJS.pdfBug = PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug; <add>PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); <ide> <ide> /** <ide> * Enables transfer usage in postMessage for ArrayBuffers. <ide> * @var {boolean} <ide> */ <del>PDFJS.postMessageTransfers = PDFJS.postMessageTransfers === undefined ? <del> true : PDFJS.postMessageTransfers; <add>PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? <add> true : PDFJS.postMessageTransfers); <ide> <ide> /** <ide> * Disables URL.createObjectURL usage. <ide> * @var {boolean} <ide> */ <del>PDFJS.disableCreateObjectURL = PDFJS.disableCreateObjectURL === undefined ? <del> false : PDFJS.disableCreateObjectURL; <add>PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? <add> false : PDFJS.disableCreateObjectURL); <ide> <ide> /** <ide> * Controls the logging level. <ide> PDFJS.disableCreateObjectURL = PDFJS.disableCreateObjectURL === undefined ? <ide> * - infos <ide> * @var {number} <ide> */ <del>PDFJS.verbosity = PDFJS.verbosity === undefined ? <del> PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity; <add>PDFJS.verbosity = (PDFJS.verbosity === undefined ? <add> PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity); <ide> <ide> /** <ide> * Document initialization / loading parameters object. <ide> PDFJS.getDocument = function getDocument(source, <ide> 'string or a parameter object'); <ide> } <ide> <del> if (!source.url && !source.data) <add> if (!source.url && !source.data) { <ide> error('Invalid parameter array, need either .data or .url'); <add> } <ide> <ide> // copy/use all keys as is except 'url' -- full path is required <ide> var params = {}; <ide> PDFJS.getDocument = function getDocument(source, <ide> <ide> workerInitializedPromise = new PDFJS.LegacyPromise(); <ide> workerReadyPromise = new PDFJS.LegacyPromise(); <del> transport = new WorkerTransport(workerInitializedPromise, <del> workerReadyPromise, pdfDataRangeTransport, progressCallback); <add> transport = new WorkerTransport(workerInitializedPromise, workerReadyPromise, <add> pdfDataRangeTransport, progressCallback); <ide> workerInitializedPromise.then(function transportInitialized() { <ide> transport.passwordCallback = passwordCallback; <ide> transport.fetchDocument(params); <ide> var PDFDocumentProxy = (function PDFDocumentProxyClosure() { <ide> var metadata = this.pdfInfo.metadata; <ide> promise.resolve({ <ide> info: info, <del> metadata: metadata ? new PDFJS.Metadata(metadata) : null <add> metadata: (metadata ? new PDFJS.Metadata(metadata) : null) <ide> }); <ide> return promise; <ide> }, <ide> var PDFPageProxy = (function PDFPageProxyClosure() { <ide> * with transforms required for rendering. <ide> */ <ide> getViewport: function PDFPageProxy_getViewport(scale, rotate) { <del> if (arguments.length < 2) <add> if (arguments.length < 2) { <ide> rotate = this.rotate; <add> } <ide> return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0); <ide> }, <ide> /** <ide> * @return {Promise} A promise that is resolved with an {Array} of the <ide> * annotation objects. <ide> */ <ide> getAnnotations: function PDFPageProxy_getAnnotations() { <del> if (this.annotationsPromise) <add> if (this.annotationsPromise) { <ide> return this.annotationsPromise; <add> } <ide> <ide> var promise = new PDFJS.LegacyPromise(); <ide> this.annotationsPromise = promise; <ide> var PDFPageProxy = (function PDFPageProxyClosure() { <ide> // this call to render. <ide> this.pendingDestroy = false; <ide> <del> var renderingIntent = 'intent' in params ? <del> (params.intent == 'print' ? 'print' : 'display') : <del> 'display'; <add> var renderingIntent = ('intent' in params ? <add> (params.intent == 'print' ? 'print' : 'display') : 'display'); <ide> <ide> if (!this.intentStates[renderingIntent]) { <ide> this.intentStates[renderingIntent] = {}; <ide> var PDFPageProxy = (function PDFPageProxyClosure() { <ide> } <ide> <ide> var internalRenderTask = new InternalRenderTask(complete, params, <del> this.objs, this.commonObjs, <del> intentState.operatorList, <del> this.pageNumber); <add> this.objs, <add> this.commonObjs, <add> intentState.operatorList, <add> this.pageNumber); <ide> if (!intentState.renderTasks) { <ide> intentState.renderTasks = []; <ide> } <ide> var PDFPageProxy = (function PDFPageProxyClosure() { <ide> if (!this.pendingDestroy || <ide> Object.keys(this.intentStates).some(function(intent) { <ide> var intentState = this.intentStates[intent]; <del> return intentState.renderTasks.length !== 0 || <del> intentState.receivingOperatorList; <add> return (intentState.renderTasks.length !== 0 || <add> intentState.receivingOperatorList); <ide> }, this)) { <ide> return; <ide> } <ide> var PDFPageProxy = (function PDFPageProxyClosure() { <ide> */ <ide> var WorkerTransport = (function WorkerTransportClosure() { <ide> function WorkerTransport(workerInitializedPromise, workerReadyPromise, <del> pdfDataRangeTransport, progressCallback) { <add> pdfDataRangeTransport, progressCallback) { <ide> this.pdfDataRangeTransport = pdfDataRangeTransport; <ide> <ide> this.workerReadyPromise = workerReadyPromise; <ide> var WorkerTransport = (function WorkerTransportClosure() { <ide> messageHandler.on('commonobj', function transportObj(data) { <ide> var id = data[0]; <ide> var type = data[1]; <del> if (this.commonObjs.hasData(id)) <add> if (this.commonObjs.hasData(id)) { <ide> return; <add> } <ide> <ide> switch (type) { <ide> case 'Font': <ide> var WorkerTransport = (function WorkerTransportClosure() { <ide> messageHandler.on('PageError', function transportError(data, intent) { <ide> var page = this.pageCache[data.pageNum - 1]; <ide> var intentState = page.intentStates[intent]; <del> if (intentState.displayReadyPromise) <add> if (intentState.displayReadyPromise) { <ide> intentState.displayReadyPromise.reject(data.error); <del> else <add> } else { <ide> error(data.error); <add> } <ide> }, this); <ide> <ide> messageHandler.on('JpegDecode', function(data, deferred) { <ide> var imageUrl = data[0]; <ide> var components = data[1]; <del> if (components != 3 && components != 1) <add> if (components != 3 && components != 1) { <ide> error('Only 3 component or 1 component can be returned'); <add> } <ide> <ide> var img = new Image(); <ide> img.onload = (function messageHandler_onloadClosure() { <ide> var WorkerTransport = (function WorkerTransportClosure() { <ide> } <ide> <ide> var pageIndex = pageNumber - 1; <del> if (pageIndex in this.pagePromises) <add> if (pageIndex in this.pagePromises) { <ide> return this.pagePromises[pageIndex]; <add> } <ide> var promise = new PDFJS.LegacyPromise(); <ide> this.pagePromises[pageIndex] = promise; <ide> this.messageHandler.send('GetPageRequest', { pageIndex: pageIndex }); <ide> var PDFObjects = (function PDFObjectsClosure() { <ide> * Ensures there is an object defined for `objId`. <ide> */ <ide> ensureObj: function PDFObjects_ensureObj(objId) { <del> if (this.objs[objId]) <add> if (this.objs[objId]) { <ide> return this.objs[objId]; <add> } <ide> <ide> var obj = { <ide> promise: new LegacyPromise(), <ide> var PDFObjects = (function PDFObjectsClosure() { <ide> <ide> // If there isn't an object yet or the object isn't resolved, then the <ide> // data isn't ready yet! <del> if (!obj || !obj.resolved) <add> if (!obj || !obj.resolved) { <ide> error('Requesting object that isn\'t resolved yet ' + objId); <add> } <ide> <ide> return obj.data; <ide> },
1
Javascript
Javascript
modify order of parameters for assertion
7ba83e893e44179abf339c042653334ed71a3f19
<ide><path>test/parallel/test-promises-unhandled-rejections.js <ide> asyncTest( <ide> const e = new Error('error'); <ide> const domainError = new Error('domain error'); <ide> onUnhandledSucceed(done, function(reason, promise) { <del> assert.strictEqual(e, reason); <del> assert.strictEqual(domainError, domainReceivedError); <add> assert.strictEqual(reason, e); <add> assert.strictEqual(domainReceivedError, domainError); <ide> }); <ide> Promise.reject(e); <ide> process.nextTick(function() {
1
Go
Go
rename the variable 'name' to 'destination'
57cec5a777e93486f14151087d178e3569d25d2b
<ide><path>daemon/volumes.go <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> }() <ide> <ide> // 1. Read already configured mount points. <del> for name, point := range container.MountPoints { <del> mountPoints[name] = point <add> for destination, point := range container.MountPoints { <add> mountPoints[destination] = point <ide> } <ide> <ide> // 2. Read volumes from other containers.
1
Go
Go
add a registry package with registry v1/v2 code
4300e5e8818571a55e00d9987bec3ad6ca92dc6f
<ide><path>integration-cli/check_test.go <ide> import ( <ide> cliconfig "github.com/docker/docker/cli/config" <ide> "github.com/docker/docker/integration-cli/daemon" <ide> "github.com/docker/docker/integration-cli/environment" <add> "github.com/docker/docker/integration-cli/registry" <ide> "github.com/docker/docker/pkg/reexec" <ide> "github.com/go-check/check" <ide> ) <ide> func init() { <ide> <ide> type DockerRegistrySuite struct { <ide> ds *DockerSuite <del> reg *testRegistryV2 <add> reg *registry.V2 <ide> d *daemon.Daemon <ide> } <ide> <ide> func (s *DockerRegistrySuite) OnTimeout(c *check.C) { <ide> } <ide> <ide> func (s *DockerRegistrySuite) SetUpTest(c *check.C) { <del> testRequires(c, DaemonIsLinux, RegistryHosting) <add> testRequires(c, DaemonIsLinux, registry.Hosting) <ide> s.reg = setupRegistry(c, false, "", "") <ide> s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ <ide> Experimental: experimentalDaemon, <ide> func init() { <ide> <ide> type DockerSchema1RegistrySuite struct { <ide> ds *DockerSuite <del> reg *testRegistryV2 <add> reg *registry.V2 <ide> d *daemon.Daemon <ide> } <ide> <ide> func (s *DockerSchema1RegistrySuite) OnTimeout(c *check.C) { <ide> } <ide> <ide> func (s *DockerSchema1RegistrySuite) SetUpTest(c *check.C) { <del> testRequires(c, DaemonIsLinux, RegistryHosting, NotArm64) <add> testRequires(c, DaemonIsLinux, registry.Hosting, NotArm64) <ide> s.reg = setupRegistry(c, true, "", "") <ide> s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ <ide> Experimental: experimentalDaemon, <ide> func init() { <ide> <ide> type DockerRegistryAuthHtpasswdSuite struct { <ide> ds *DockerSuite <del> reg *testRegistryV2 <add> reg *registry.V2 <ide> d *daemon.Daemon <ide> } <ide> <ide> func (s *DockerRegistryAuthHtpasswdSuite) OnTimeout(c *check.C) { <ide> } <ide> <ide> func (s *DockerRegistryAuthHtpasswdSuite) SetUpTest(c *check.C) { <del> testRequires(c, DaemonIsLinux, RegistryHosting) <add> testRequires(c, DaemonIsLinux, registry.Hosting) <ide> s.reg = setupRegistry(c, false, "htpasswd", "") <ide> s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ <ide> Experimental: experimentalDaemon, <ide> func init() { <ide> <ide> type DockerRegistryAuthTokenSuite struct { <ide> ds *DockerSuite <del> reg *testRegistryV2 <add> reg *registry.V2 <ide> d *daemon.Daemon <ide> } <ide> <ide> func (s *DockerRegistryAuthTokenSuite) OnTimeout(c *check.C) { <ide> } <ide> <ide> func (s *DockerRegistryAuthTokenSuite) SetUpTest(c *check.C) { <del> testRequires(c, DaemonIsLinux, RegistryHosting) <add> testRequires(c, DaemonIsLinux, registry.Hosting) <ide> s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ <ide> Experimental: experimentalDaemon, <ide> }) <ide> func init() { <ide> <ide> type DockerTrustSuite struct { <ide> ds *DockerSuite <del> reg *testRegistryV2 <add> reg *registry.V2 <ide> not *testNotary <ide> } <ide> <ide> func (s *DockerTrustSuite) SetUpTest(c *check.C) { <del> testRequires(c, RegistryHosting, NotaryServerHosting) <add> testRequires(c, registry.Hosting, NotaryServerHosting) <ide> s.reg = setupRegistry(c, false, "", "") <ide> s.not = setupNotary(c) <ide> } <ide> func init() { <ide> type DockerTrustedSwarmSuite struct { <ide> swarmSuite DockerSwarmSuite <ide> trustSuite DockerTrustSuite <del> reg *testRegistryV2 <add> reg *registry.V2 <ide> not *testNotary <ide> } <ide> <ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildLabelOverwrite(c *check.C) { <ide> } <ide> <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *check.C) { <del> dockerCmd(c, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL) <add> dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) <ide> <ide> baseImage := privateRegistryURL + "/baseimage" <ide> <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *check.C) <ide> err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) <ide> c.Assert(err, checker.IsNil) <ide> <del> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL) <add> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) <ide> <ide> b, err := ioutil.ReadFile(configPath) <ide> c.Assert(err, checker.IsNil) <ide><path>integration-cli/docker_cli_by_digest_test.go <ide> func (s *DockerRegistrySuite) TestPullFailsWithAlteredManifest(c *check.C) { <ide> c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) <ide> <ide> // Load the target manifest blob. <del> manifestBlob := s.reg.readBlobContents(c, manifestDigest) <add> manifestBlob := s.reg.ReadBlobContents(c, manifestDigest) <ide> <ide> var imgManifest schema2.Manifest <ide> err = json.Unmarshal(manifestBlob, &imgManifest) <ide> func (s *DockerRegistrySuite) TestPullFailsWithAlteredManifest(c *check.C) { <ide> <ide> // Move the existing data file aside, so that we can replace it with a <ide> // malicious blob of data. NOTE: we defer the returned undo func. <del> undo := s.reg.tempMoveBlobData(c, manifestDigest) <add> undo := s.reg.TempMoveBlobData(c, manifestDigest) <ide> defer undo() <ide> <ide> alteredManifestBlob, err := json.MarshalIndent(imgManifest, "", " ") <ide> c.Assert(err, checker.IsNil, check.Commentf("unable to encode altered image manifest to JSON")) <ide> <del> s.reg.writeBlobContents(c, manifestDigest, alteredManifestBlob) <add> s.reg.WriteBlobContents(c, manifestDigest, alteredManifestBlob) <ide> <ide> // Now try pulling that image by digest. We should get an error about <ide> // digest verification for the manifest digest. <ide> func (s *DockerSchema1RegistrySuite) TestPullFailsWithAlteredManifest(c *check.C <ide> c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) <ide> <ide> // Load the target manifest blob. <del> manifestBlob := s.reg.readBlobContents(c, manifestDigest) <add> manifestBlob := s.reg.ReadBlobContents(c, manifestDigest) <ide> <ide> var imgManifest schema1.Manifest <ide> err = json.Unmarshal(manifestBlob, &imgManifest) <ide> func (s *DockerSchema1RegistrySuite) TestPullFailsWithAlteredManifest(c *check.C <ide> <ide> // Move the existing data file aside, so that we can replace it with a <ide> // malicious blob of data. NOTE: we defer the returned undo func. <del> undo := s.reg.tempMoveBlobData(c, manifestDigest) <add> undo := s.reg.TempMoveBlobData(c, manifestDigest) <ide> defer undo() <ide> <ide> alteredManifestBlob, err := json.MarshalIndent(imgManifest, "", " ") <ide> c.Assert(err, checker.IsNil, check.Commentf("unable to encode altered image manifest to JSON")) <ide> <del> s.reg.writeBlobContents(c, manifestDigest, alteredManifestBlob) <add> s.reg.WriteBlobContents(c, manifestDigest, alteredManifestBlob) <ide> <ide> // Now try pulling that image by digest. We should get an error about <ide> // digest verification for the manifest digest. <ide> func (s *DockerRegistrySuite) TestPullFailsWithAlteredLayer(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> <ide> // Load the target manifest blob. <del> manifestBlob := s.reg.readBlobContents(c, manifestDigest) <add> manifestBlob := s.reg.ReadBlobContents(c, manifestDigest) <ide> <ide> var imgManifest schema2.Manifest <ide> err = json.Unmarshal(manifestBlob, &imgManifest) <ide> func (s *DockerRegistrySuite) TestPullFailsWithAlteredLayer(c *check.C) { <ide> <ide> // Move the existing data file aside, so that we can replace it with a <ide> // malicious blob of data. NOTE: we defer the returned undo func. <del> undo := s.reg.tempMoveBlobData(c, targetLayerDigest) <add> undo := s.reg.TempMoveBlobData(c, targetLayerDigest) <ide> defer undo() <ide> <ide> // Now make a fake data blob in this directory. <del> s.reg.writeBlobContents(c, targetLayerDigest, []byte("This is not the data you are looking for.")) <add> s.reg.WriteBlobContents(c, targetLayerDigest, []byte("This is not the data you are looking for.")) <ide> <ide> // Now try pulling that image by digest. We should get an error about <ide> // digest verification for the target layer digest. <ide> func (s *DockerSchema1RegistrySuite) TestPullFailsWithAlteredLayer(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> <ide> // Load the target manifest blob. <del> manifestBlob := s.reg.readBlobContents(c, manifestDigest) <add> manifestBlob := s.reg.ReadBlobContents(c, manifestDigest) <ide> <ide> var imgManifest schema1.Manifest <ide> err = json.Unmarshal(manifestBlob, &imgManifest) <ide> func (s *DockerSchema1RegistrySuite) TestPullFailsWithAlteredLayer(c *check.C) { <ide> <ide> // Move the existing data file aside, so that we can replace it with a <ide> // malicious blob of data. NOTE: we defer the returned undo func. <del> undo := s.reg.tempMoveBlobData(c, targetLayerDigest) <add> undo := s.reg.TempMoveBlobData(c, targetLayerDigest) <ide> defer undo() <ide> <ide> // Now make a fake data blob in this directory. <del> s.reg.writeBlobContents(c, targetLayerDigest, []byte("This is not the data you are looking for.")) <add> s.reg.WriteBlobContents(c, targetLayerDigest, []byte("This is not the data you are looking for.")) <ide> <ide> // Now try pulling that image by digest. We should get an error about <ide> // digest verification for the target layer digest. <ide><path>integration-cli/docker_cli_login_test.go <ide> func (s *DockerSuite) TestLoginWithoutTTY(c *check.C) { <ide> <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestLoginToPrivateRegistry(c *check.C) { <ide> // wrong credentials <del> out, _, err := dockerCmdWithError("login", "-u", s.reg.username, "-p", "WRONGPASSWORD", privateRegistryURL) <add> out, _, err := dockerCmdWithError("login", "-u", s.reg.Username(), "-p", "WRONGPASSWORD", privateRegistryURL) <ide> c.Assert(err, checker.NotNil, check.Commentf(out)) <ide> c.Assert(out, checker.Contains, "401 Unauthorized") <ide> <ide> // now it's fine <del> dockerCmd(c, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL) <add> dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) <ide> } <ide><path>integration-cli/docker_cli_logout_test.go <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *check.C) <ide> err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) <ide> c.Assert(err, checker.IsNil) <ide> <del> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL) <add> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) <ide> <ide> b, err := ioutil.ReadFile(configPath) <ide> c.Assert(err, checker.IsNil) <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithWrongHostnamesStored(c * <ide> os.Setenv("PATH", testPath) <ide> <ide> cmd := exec.Command("docker-credential-shell-test", "store") <del> stdin := bytes.NewReader([]byte(fmt.Sprintf(`{"ServerURL": "https://%s", "Username": "%s", "Secret": "%s"}`, privateRegistryURL, s.reg.username, s.reg.password))) <add> stdin := bytes.NewReader([]byte(fmt.Sprintf(`{"ServerURL": "https://%s", "Username": "%s", "Secret": "%s"}`, privateRegistryURL, s.reg.Username(), s.reg.Password()))) <ide> cmd.Stdin = stdin <ide> c.Assert(cmd.Run(), checker.IsNil) <ide> <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithWrongHostnamesStored(c * <ide> err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) <ide> c.Assert(err, checker.IsNil) <ide> <del> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL) <add> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) <ide> <ide> b, err := ioutil.ReadFile(configPath) <ide> c.Assert(err, checker.IsNil) <ide><path>integration-cli/docker_cli_pull_local_test.go <ide> func (s *DockerRegistrySuite) TestPullManifestList(c *check.C) { <ide> manifestListDigest := digest.FromBytes(manifestListJSON) <ide> hexDigest := manifestListDigest.Hex() <ide> <del> registryV2Path := filepath.Join(s.reg.dir, "docker", "registry", "v2") <add> registryV2Path := s.reg.Path() <ide> <ide> // Write manifest list to blob store <ide> blobDir := filepath.Join(registryV2Path, "blobs", "sha256", hexDigest[:2], hexDigest) <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithSchem <ide> err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) <ide> c.Assert(err, checker.IsNil) <ide> <del> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL) <add> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) <ide> <ide> b, err := ioutil.ReadFile(configPath) <ide> c.Assert(err, checker.IsNil) <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithSchem <ide> dockerCmd(c, "--config", tmp, "push", repoName) <ide> <ide> dockerCmd(c, "--config", tmp, "logout", privateRegistryURL) <del> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.username, "-p", s.reg.password, "https://"+privateRegistryURL) <add> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), "https://"+privateRegistryURL) <ide> dockerCmd(c, "--config", tmp, "pull", repoName) <ide> <ide> // likewise push should work <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *check.C) { <ide> err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) <ide> c.Assert(err, checker.IsNil) <ide> <del> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL) <add> dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) <ide> <ide> b, err := ioutil.ReadFile(configPath) <ide> c.Assert(err, checker.IsNil) <ide><path>integration-cli/docker_cli_registry_user_agent_test.go <ide> import ( <ide> "net/http" <ide> "regexp" <ide> <add> "github.com/docker/docker/integration-cli/registry" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func regexpCheckUA(c *check.C, ua string) { <ide> c.Assert(bMatchUpstreamUA, check.Equals, true, check.Commentf("(Upstream) Docker Client User-Agent malformed")) <ide> } <ide> <del>func registerUserAgentHandler(reg *testRegistry, result *string) { <del> reg.registerHandler("/v2/", func(w http.ResponseWriter, r *http.Request) { <add>func registerUserAgentHandler(reg *registry.Mock, result *string) { <add> reg.RegisterHandler("/v2/", func(w http.ResponseWriter, r *http.Request) { <ide> w.WriteHeader(404) <ide> var ua string <ide> for k, v := range r.Header { <ide> func (s *DockerRegistrySuite) TestUserAgentPassThrough(c *check.C) { <ide> loginUA string <ide> ) <ide> <del> buildReg, err := newTestRegistry(c) <add> buildReg, err := registry.NewMock(c) <ide> c.Assert(err, check.IsNil) <ide> registerUserAgentHandler(buildReg, &buildUA) <del> buildRepoName := fmt.Sprintf("%s/busybox", buildReg.hostport) <add> buildRepoName := fmt.Sprintf("%s/busybox", buildReg.URL()) <ide> <del> pullReg, err := newTestRegistry(c) <add> pullReg, err := registry.NewMock(c) <ide> c.Assert(err, check.IsNil) <ide> registerUserAgentHandler(pullReg, &pullUA) <del> pullRepoName := fmt.Sprintf("%s/busybox", pullReg.hostport) <add> pullRepoName := fmt.Sprintf("%s/busybox", pullReg.URL()) <ide> <del> pushReg, err := newTestRegistry(c) <add> pushReg, err := registry.NewMock(c) <ide> c.Assert(err, check.IsNil) <ide> registerUserAgentHandler(pushReg, &pushUA) <del> pushRepoName := fmt.Sprintf("%s/busybox", pushReg.hostport) <add> pushRepoName := fmt.Sprintf("%s/busybox", pushReg.URL()) <ide> <del> loginReg, err := newTestRegistry(c) <add> loginReg, err := registry.NewMock(c) <ide> c.Assert(err, check.IsNil) <ide> registerUserAgentHandler(loginReg, &loginUA) <ide> <ide> s.d.Start(c, <del> "--insecure-registry", buildReg.hostport, <del> "--insecure-registry", pullReg.hostport, <del> "--insecure-registry", pushReg.hostport, <del> "--insecure-registry", loginReg.hostport, <add> "--insecure-registry", buildReg.URL(), <add> "--insecure-registry", pullReg.URL(), <add> "--insecure-registry", pushReg.URL(), <add> "--insecure-registry", loginReg.URL(), <ide> "--disable-legacy-registry=true") <ide> <ide> dockerfileName, cleanup1, err := makefile(fmt.Sprintf("FROM %s", buildRepoName)) <ide> func (s *DockerRegistrySuite) TestUserAgentPassThrough(c *check.C) { <ide> s.d.Cmd("build", "--file", dockerfileName, ".") <ide> regexpCheckUA(c, buildUA) <ide> <del> s.d.Cmd("login", "-u", "richard", "-p", "testtest", loginReg.hostport) <add> s.d.Cmd("login", "-u", "richard", "-p", "testtest", loginReg.URL()) <ide> regexpCheckUA(c, loginUA) <ide> <ide> s.d.Cmd("pull", pullRepoName) <ide><path>integration-cli/docker_cli_v2_only_test.go <ide> import ( <ide> "net/http" <ide> "os" <ide> <add> "github.com/docker/docker/integration-cli/registry" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func makefile(contents string) (string, func(), error) { <ide> // TestV2Only ensures that a daemon in v2-only mode does not <ide> // attempt to contact any v1 registry endpoints. <ide> func (s *DockerRegistrySuite) TestV2Only(c *check.C) { <del> reg, err := newTestRegistry(c) <add> reg, err := registry.NewMock(c) <ide> c.Assert(err, check.IsNil) <ide> <del> reg.registerHandler("/v2/", func(w http.ResponseWriter, r *http.Request) { <add> reg.RegisterHandler("/v2/", func(w http.ResponseWriter, r *http.Request) { <ide> w.WriteHeader(404) <ide> }) <ide> <del> reg.registerHandler("/v1/.*", func(w http.ResponseWriter, r *http.Request) { <add> reg.RegisterHandler("/v1/.*", func(w http.ResponseWriter, r *http.Request) { <ide> c.Fatal("V1 registry contacted") <ide> }) <ide> <del> repoName := fmt.Sprintf("%s/busybox", reg.hostport) <add> repoName := fmt.Sprintf("%s/busybox", reg.URL()) <ide> <del> s.d.Start(c, "--insecure-registry", reg.hostport, "--disable-legacy-registry=true") <add> s.d.Start(c, "--insecure-registry", reg.URL(), "--disable-legacy-registry=true") <ide> <del> dockerfileName, cleanup, err := makefile(fmt.Sprintf("FROM %s/busybox", reg.hostport)) <add> dockerfileName, cleanup, err := makefile(fmt.Sprintf("FROM %s/busybox", reg.URL())) <ide> c.Assert(err, check.IsNil, check.Commentf("Unable to create test dockerfile")) <ide> defer cleanup() <ide> <ide> s.d.Cmd("build", "--file", dockerfileName, ".") <ide> <ide> s.d.Cmd("run", repoName) <del> s.d.Cmd("login", "-u", "richard", "-p", "testtest", "-e", "testuser@testdomain.com", reg.hostport) <add> s.d.Cmd("login", "-u", "richard", "-p", "testtest", "-e", "testuser@testdomain.com", reg.URL()) <ide> s.d.Cmd("tag", "busybox", repoName) <ide> s.d.Cmd("push", repoName) <ide> s.d.Cmd("pull", repoName) <ide> func (s *DockerRegistrySuite) TestV2Only(c *check.C) { <ide> // and ensure v1 endpoints are hit for the following operations: <ide> // login, push, pull, build & run <ide> func (s *DockerRegistrySuite) TestV1(c *check.C) { <del> reg, err := newTestRegistry(c) <add> reg, err := registry.NewMock(c) <ide> c.Assert(err, check.IsNil) <ide> <ide> v2Pings := 0 <del> reg.registerHandler("/v2/", func(w http.ResponseWriter, r *http.Request) { <add> reg.RegisterHandler("/v2/", func(w http.ResponseWriter, r *http.Request) { <ide> v2Pings++ <ide> // V2 ping 404 causes fallback to v1 <ide> w.WriteHeader(404) <ide> }) <ide> <ide> v1Pings := 0 <del> reg.registerHandler("/v1/_ping", func(w http.ResponseWriter, r *http.Request) { <add> reg.RegisterHandler("/v1/_ping", func(w http.ResponseWriter, r *http.Request) { <ide> v1Pings++ <ide> }) <ide> <ide> v1Logins := 0 <del> reg.registerHandler("/v1/users/", func(w http.ResponseWriter, r *http.Request) { <add> reg.RegisterHandler("/v1/users/", func(w http.ResponseWriter, r *http.Request) { <ide> v1Logins++ <ide> }) <ide> <ide> v1Repo := 0 <del> reg.registerHandler("/v1/repositories/busybox/", func(w http.ResponseWriter, r *http.Request) { <add> reg.RegisterHandler("/v1/repositories/busybox/", func(w http.ResponseWriter, r *http.Request) { <ide> v1Repo++ <ide> }) <ide> <del> reg.registerHandler("/v1/repositories/busybox/images", func(w http.ResponseWriter, r *http.Request) { <add> reg.RegisterHandler("/v1/repositories/busybox/images", func(w http.ResponseWriter, r *http.Request) { <ide> v1Repo++ <ide> }) <ide> <del> s.d.Start(c, "--insecure-registry", reg.hostport, "--disable-legacy-registry=false") <add> s.d.Start(c, "--insecure-registry", reg.URL(), "--disable-legacy-registry=false") <ide> <del> dockerfileName, cleanup, err := makefile(fmt.Sprintf("FROM %s/busybox", reg.hostport)) <add> dockerfileName, cleanup, err := makefile(fmt.Sprintf("FROM %s/busybox", reg.URL())) <ide> c.Assert(err, check.IsNil, check.Commentf("Unable to create test dockerfile")) <ide> defer cleanup() <ide> <ide> s.d.Cmd("build", "--file", dockerfileName, ".") <ide> c.Assert(v1Repo, check.Equals, 1, check.Commentf("Expected v1 repository access after build")) <ide> <del> repoName := fmt.Sprintf("%s/busybox", reg.hostport) <add> repoName := fmt.Sprintf("%s/busybox", reg.URL()) <ide> s.d.Cmd("run", repoName) <ide> c.Assert(v1Repo, check.Equals, 2, check.Commentf("Expected v1 repository access after run")) <ide> <del> s.d.Cmd("login", "-u", "richard", "-p", "testtest", reg.hostport) <add> s.d.Cmd("login", "-u", "richard", "-p", "testtest", reg.URL()) <ide> c.Assert(v1Logins, check.Equals, 1, check.Commentf("Expected v1 login attempt")) <ide> <ide> s.d.Cmd("tag", "busybox", repoName) <ide><path>integration-cli/docker_utils_test.go <ide> import ( <ide> "github.com/docker/docker/api/types" <ide> volumetypes "github.com/docker/docker/api/types/volume" <ide> "github.com/docker/docker/integration-cli/daemon" <add> "github.com/docker/docker/integration-cli/registry" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/integration" <ide> "github.com/docker/docker/pkg/integration/checker" <ide> func parseEventTime(t time.Time) string { <ide> return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond())) <ide> } <ide> <del>func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *testRegistryV2 { <del> reg, err := newTestRegistryV2(c, schema1, auth, tokenURL) <add>func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *registry.V2 { <add> reg, err := registry.NewV2(schema1, auth, tokenURL, privateRegistryURL) <ide> c.Assert(err, check.IsNil) <ide> <ide> // Wait for registry to be ready to serve requests. <add><path>integration-cli/registry/registry.go <del><path>integration-cli/registry_test.go <del>package main <add>package registry <ide> <ide> import ( <ide> "fmt" <ide> import ( <ide> "path/filepath" <ide> <ide> "github.com/docker/distribution/digest" <del> "github.com/go-check/check" <ide> ) <ide> <ide> const ( <ide> v2binary = "registry-v2" <ide> v2binarySchema1 = "registry-v2-schema1" <ide> ) <ide> <del>type testRegistryV2 struct { <del> cmd *exec.Cmd <del> dir string <del> auth string <del> username string <del> password string <del> email string <add>type testingT interface { <add> logT <add> Fatal(...interface{}) <add> Fatalf(string, ...interface{}) <ide> } <ide> <del>func newTestRegistryV2(c *check.C, schema1 bool, auth, tokenURL string) (*testRegistryV2, error) { <add>type logT interface { <add> Logf(string, ...interface{}) <add>} <add> <add>// V2 represent a registry version 2 <add>type V2 struct { <add> cmd *exec.Cmd <add> registryURL string <add> dir string <add> auth string <add> username string <add> password string <add> email string <add>} <add> <add>// NewV2 creates a v2 registry server <add>func NewV2(schema1 bool, auth, tokenURL, registryURL string) (*V2, error) { <ide> tmp, err := ioutil.TempDir("", "registry-test-") <ide> if err != nil { <ide> return nil, err <ide> http: <ide> } <ide> defer config.Close() <ide> <del> if _, err := fmt.Fprintf(config, template, tmp, privateRegistryURL, authTemplate); err != nil { <add> if _, err := fmt.Fprintf(config, template, tmp, registryURL, authTemplate); err != nil { <ide> os.RemoveAll(tmp) <ide> return nil, err <ide> } <ide> http: <ide> cmd := exec.Command(binary, confPath) <ide> if err := cmd.Start(); err != nil { <ide> os.RemoveAll(tmp) <del> if os.IsNotExist(err) { <del> c.Skip(err.Error()) <del> } <ide> return nil, err <ide> } <del> return &testRegistryV2{ <del> cmd: cmd, <del> dir: tmp, <del> auth: auth, <del> username: username, <del> password: password, <del> email: email, <add> return &V2{ <add> cmd: cmd, <add> dir: tmp, <add> auth: auth, <add> username: username, <add> password: password, <add> email: email, <add> registryURL: registryURL, <ide> }, nil <ide> } <ide> <del>func (t *testRegistryV2) Ping() error { <add>// Ping sends an http request to the current registry, and fail if it doesn't respond correctly <add>func (r *V2) Ping() error { <ide> // We always ping through HTTP for our test registry. <del> resp, err := http.Get(fmt.Sprintf("http://%s/v2/", privateRegistryURL)) <add> resp, err := http.Get(fmt.Sprintf("http://%s/v2/", r.registryURL)) <ide> if err != nil { <ide> return err <ide> } <ide> resp.Body.Close() <ide> <ide> fail := resp.StatusCode != http.StatusOK <del> if t.auth != "" { <add> if r.auth != "" { <ide> // unauthorized is a _good_ status when pinging v2/ and it needs auth <ide> fail = fail && resp.StatusCode != http.StatusUnauthorized <ide> } <ide> func (t *testRegistryV2) Ping() error { <ide> return nil <ide> } <ide> <del>func (t *testRegistryV2) Close() { <del> t.cmd.Process.Kill() <del> os.RemoveAll(t.dir) <add>// Close kills the registry server <add>func (r *V2) Close() { <add> r.cmd.Process.Kill() <add> os.RemoveAll(r.dir) <ide> } <ide> <del>func (t *testRegistryV2) getBlobFilename(blobDigest digest.Digest) string { <add>func (r *V2) getBlobFilename(blobDigest digest.Digest) string { <ide> // Split the digest into its algorithm and hex components. <ide> dgstAlg, dgstHex := blobDigest.Algorithm(), blobDigest.Hex() <ide> <ide> // The path to the target blob data looks something like: <ide> // baseDir + "docker/registry/v2/blobs/sha256/a3/a3ed...46d4/data" <del> return fmt.Sprintf("%s/docker/registry/v2/blobs/%s/%s/%s/data", t.dir, dgstAlg, dgstHex[:2], dgstHex) <add> return fmt.Sprintf("%s/docker/registry/v2/blobs/%s/%s/%s/data", r.dir, dgstAlg, dgstHex[:2], dgstHex) <ide> } <ide> <del>func (t *testRegistryV2) readBlobContents(c *check.C, blobDigest digest.Digest) []byte { <add>// ReadBlobContents read the file corresponding to the specified digest <add>func (r *V2) ReadBlobContents(t testingT, blobDigest digest.Digest) []byte { <ide> // Load the target manifest blob. <del> manifestBlob, err := ioutil.ReadFile(t.getBlobFilename(blobDigest)) <add> manifestBlob, err := ioutil.ReadFile(r.getBlobFilename(blobDigest)) <ide> if err != nil { <del> c.Fatalf("unable to read blob: %s", err) <add> t.Fatalf("unable to read blob: %s", err) <ide> } <ide> <ide> return manifestBlob <ide> } <ide> <del>func (t *testRegistryV2) writeBlobContents(c *check.C, blobDigest digest.Digest, data []byte) { <del> if err := ioutil.WriteFile(t.getBlobFilename(blobDigest), data, os.FileMode(0644)); err != nil { <del> c.Fatalf("unable to write malicious data blob: %s", err) <add>// WriteBlobContents write the file corresponding to the specified digest with the given content <add>func (r *V2) WriteBlobContents(t testingT, blobDigest digest.Digest, data []byte) { <add> if err := ioutil.WriteFile(r.getBlobFilename(blobDigest), data, os.FileMode(0644)); err != nil { <add> t.Fatalf("unable to write malicious data blob: %s", err) <ide> } <ide> } <ide> <del>func (t *testRegistryV2) tempMoveBlobData(c *check.C, blobDigest digest.Digest) (undo func()) { <add>// TempMoveBlobData moves the existing data file aside, so that we can replace it with a <add>// malicious blob of data for example. <add>func (r *V2) TempMoveBlobData(t testingT, blobDigest digest.Digest) (undo func()) { <ide> tempFile, err := ioutil.TempFile("", "registry-temp-blob-") <ide> if err != nil { <del> c.Fatalf("unable to get temporary blob file: %s", err) <add> t.Fatalf("unable to get temporary blob file: %s", err) <ide> } <ide> tempFile.Close() <ide> <del> blobFilename := t.getBlobFilename(blobDigest) <add> blobFilename := r.getBlobFilename(blobDigest) <ide> <ide> // Move the existing data file aside, so that we can replace it with a <ide> // another blob of data. <ide> if err := os.Rename(blobFilename, tempFile.Name()); err != nil { <ide> os.Remove(tempFile.Name()) <del> c.Fatalf("unable to move data blob: %s", err) <add> t.Fatalf("unable to move data blob: %s", err) <ide> } <ide> <ide> return func() { <ide> os.Rename(tempFile.Name(), blobFilename) <ide> os.Remove(tempFile.Name()) <ide> } <ide> } <add> <add>// Username returns the configured user name of the server <add>func (r *V2) Username() string { <add> return r.username <add>} <add> <add>// Password returns the configured password of the server <add>func (r *V2) Password() string { <add> return r.password <add>} <add> <add>// Path returns the path where the registry write data <add>func (r *V2) Path() string { <add> return filepath.Join(r.dir, "docker", "registry", "v2") <add>} <add><path>integration-cli/registry/registry_mock.go <del><path>integration-cli/registry_mock_test.go <del>package main <add>package registry <ide> <ide> import ( <ide> "net/http" <ide> "net/http/httptest" <ide> "regexp" <ide> "strings" <ide> "sync" <del> <del> "github.com/go-check/check" <ide> ) <ide> <ide> type handlerFunc func(w http.ResponseWriter, r *http.Request) <ide> <del>type testRegistry struct { <add>// Mock represent a registry mock <add>type Mock struct { <ide> server *httptest.Server <ide> hostport string <ide> handlers map[string]handlerFunc <ide> mu sync.Mutex <ide> } <ide> <del>func (tr *testRegistry) registerHandler(path string, h handlerFunc) { <add>// RegisterHandler register the specified handler for the registry mock <add>func (tr *Mock) RegisterHandler(path string, h handlerFunc) { <ide> tr.mu.Lock() <ide> defer tr.mu.Unlock() <ide> tr.handlers[path] = h <ide> } <ide> <del>func newTestRegistry(c *check.C) (*testRegistry, error) { <del> testReg := &testRegistry{handlers: make(map[string]handlerFunc)} <add>// NewMock creates a registry mock <add>func NewMock(t testingT) (*Mock, error) { <add> testReg := &Mock{handlers: make(map[string]handlerFunc)} <ide> <ide> ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <ide> url := r.URL.String() <ide> func newTestRegistry(c *check.C) (*testRegistry, error) { <ide> for re, function := range testReg.handlers { <ide> matched, err = regexp.MatchString(re, url) <ide> if err != nil { <del> c.Fatal("Error with handler regexp") <add> t.Fatal("Error with handler regexp") <ide> } <ide> if matched { <ide> function(w, r) <ide> func newTestRegistry(c *check.C) (*testRegistry, error) { <ide> } <ide> <ide> if !matched { <del> c.Fatalf("Unable to match %s with regexp", url) <add> t.Fatalf("Unable to match %s with regexp", url) <ide> } <ide> })) <ide> <ide> testReg.server = ts <ide> testReg.hostport = strings.Replace(ts.URL, "http://", "", 1) <ide> return testReg, nil <ide> } <add> <add>// URL returns the url of the registry <add>func (tr *Mock) URL() string { <add> return tr.hostport <add>} <ide><path>integration-cli/registry/requirement.go <add>package registry <add> <add>import "os/exec" <add> <add>// Hosting returns wether the host can host a registry (v2) or not <add>func Hosting() bool { <add> // for now registry binary is built only if we're running inside <add> // container through `make test`. Figure that out by testing if <add> // registry binary is in PATH. <add> _, err := exec.LookPath(v2binary) <add> return err == nil <add>} <ide><path>integration-cli/requirements_test.go <ide> func Apparmor() bool { <ide> return err == nil && len(buf) > 1 && buf[0] == 'Y' <ide> } <ide> <del>func RegistryHosting() bool { <del> // for now registry binary is built only if we're running inside <del> // container through `make test`. Figure that out by testing if <del> // registry binary is in PATH. <del> _, err := exec.LookPath(v2binary) <del> return err == nil <del>} <del> <ide> func NotaryHosting() bool { <ide> // for now notary binary is built only if we're running inside <ide> // container through `make test`. Figure that out by testing if
13
Ruby
Ruby
favor composition over inheritance
bca7770e6c05ca2d81302349b02b058ade00d491
<ide><path>railties/lib/rails/paths.rb <ide> module Paths <ide> # root["app/controllers"].existent # => ["/rails/app/controllers"] <ide> # <ide> # Check the <tt>Rails::Paths::Path</tt> documentation for more information. <del> class Root < ::Hash <add> class Root <ide> attr_accessor :path <ide> <ide> def initialize(path) <ide> raise "Argument should be a String of the physical root path" if path.is_a?(Array) <ide> @current = nil <ide> @path = path <del> @root = self <del> super() <add> @root = {} <ide> end <ide> <ide> def []=(path, value) <ide> value = Path.new(self, path, [value].flatten) unless value.is_a?(Path) <del> super(path, value) <add> @root[path] = value <ide> end <ide> <ide> def add(path, options={}) <ide> with = options[:with] || path <del> self[path] = Path.new(self, path, [with].flatten, options) <add> @root[path] = Path.new(self, path, [with].flatten, options) <add> end <add> <add> def [](path) <add> @root[path] <add> end <add> <add> def values <add> @root.values <add> end <add> <add> def keys <add> @root.keys <add> end <add> <add> def values_at(*list) <add> @root.values_at(*list) <ide> end <ide> <ide> def all_paths
1
PHP
PHP
remove unneeded calls to with
36eec89228d87667607ed25aede5b1d25a4f61de
<ide><path>src/Illuminate/Cookie/CookieServiceProvider.php <ide> public function register() <ide> { <ide> $config = $app['config']['session']; <ide> <del> return with(new CookieJar)->setDefaultPathAndDomain($config['path'], $config['domain']); <add> return (new CookieJar)->setDefaultPathAndDomain($config['path'], $config['domain']); <ide> }); <ide> } <ide> } <ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function findOrFail($id, $columns = array('*')) <ide> { <ide> if ( ! is_null($model = $this->find($id, $columns))) return $model; <ide> <del> throw with(new ModelNotFoundException)->setModel(get_class($this->model)); <add> throw (new ModelNotFoundException)->setModel(get_class($this->model)); <ide> } <ide> <ide> /** <ide> public function firstOrFail($columns = array('*')) <ide> { <ide> if ( ! is_null($model = $this->first($columns))) return $model; <ide> <del> throw with(new ModelNotFoundException)->setModel(get_class($this->model)); <add> throw (new ModelNotFoundException)->setModel(get_class($this->model)); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> protected static function firstByAttributes($attributes) <ide> */ <ide> public static function query() <ide> { <del> return with(new static)->newQuery(); <add> return (new static)->newQuery(); <ide> } <ide> <ide> /** <ide> public static function findOrFail($id, $columns = array('*')) <ide> { <ide> if ( ! is_null($model = static::find($id, $columns))) return $model; <ide> <del> throw with(new ModelNotFoundException)->setModel(get_called_class()); <add> throw (new ModelNotFoundException)->setModel(get_called_class()); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Database/Eloquent/SoftDeletingTrait.php <ide> public function trashed() <ide> */ <ide> public static function withTrashed() <ide> { <del> return with(new static)->newQueryWithoutScope(new SoftDeletingScope); <add> return (new static)->newQueryWithoutScope(new SoftDeletingScope); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Encryption/Encrypter.php <ide> protected function getJsonPayload($payload) <ide> */ <ide> protected function validMac(array $payload) <ide> { <del> $bytes = with(new SecureRandom)->nextBytes(16); <add> $bytes = (new SecureRandom)->nextBytes(16); <ide> <ide> $calcMac = hash_hmac('sha256', $this->hash($payload['iv'], $payload['value']), $bytes, true); <ide> <ide><path>src/Illuminate/Foundation/Application.php <ide> public function detectEnvironment($envs) <ide> { <ide> $args = isset($_SERVER['argv']) ? $_SERVER['argv'] : null; <ide> <del> return $this['env'] = with(new EnvironmentDetector())->detect($envs, $args); <add> return $this['env'] = (new EnvironmentDetector())->detect($envs, $args); <ide> } <ide> <ide> /** <ide> protected function getStackedClient() <ide> { <ide> $sessionReject = $this->bound('session.reject') ? $this['session.reject'] : null; <ide> <del> $client = with(new \Stack\Builder) <del> ->push('Illuminate\Cookie\Guard', $this['encrypter']) <del> ->push('Illuminate\Cookie\Queue', $this['cookie']) <del> ->push('Illuminate\Session\Middleware', $this['session'], $sessionReject); <add> $client = (new \Stack\Builder) <add> ->push('Illuminate\Cookie\Guard', $this['encrypter']) <add> ->push('Illuminate\Cookie\Queue', $this['cookie']) <add> ->push('Illuminate\Session\Middleware', $this['session'], $sessionReject); <ide> <ide> $this->mergeCustomMiddlewares($client); <ide> <ide><path>src/Illuminate/Foundation/Composer.php <ide> protected function findComposer() <ide> */ <ide> protected function getProcess() <ide> { <del> return with(new Process('', $this->workingPath))->setTimeout(null); <add> return (new Process('', $this->workingPath))->setTimeout(null); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Http/Request.php <ide> public static function createFromBase(SymfonyRequest $request) <ide> { <ide> if ($request instanceof static) return $request; <ide> <del> return with(new static)->duplicate( <add> return (new static)->duplicate( <ide> <ide> $request->query->all(), $request->request->all(), $request->attributes->all(), <ide> <ide><path>src/Illuminate/Routing/RouteCollection.php <ide> protected function getOtherMethodsRoute($request, array $others) <ide> { <ide> if ($request->method() == 'OPTIONS') <ide> { <del> return with(new Route('OPTIONS', $request->path(), function() use ($others) <add> return (new Route('OPTIONS', $request->path(), function() use ($others) <ide> { <ide> return new Response('', 200, array('Allow' => implode(',', $others))); <ide> <ide><path>src/Illuminate/Routing/Router.php <ide> public function model($key, $class, Closure $callback = null) <ide> // For model binders, we will attempt to retrieve the models using the find <ide> // method on the model instance. If we cannot retrieve the models we'll <ide> // throw a not found exception otherwise we will return the instance. <del> if ($model = with(new $class)->find($value)) <add> if ($model = (new $class)->find($value)) <ide> { <ide> return $model; <ide> } <ide><path>src/Illuminate/Support/ServiceProvider.php <ide> public function package($package, $namespace = null, $path = null) <ide> */ <ide> public function guessPackagePath() <ide> { <del> $path = with(new ReflectionClass($this))->getFileName(); <add> $path = (new ReflectionClass($this))->getFileName(); <ide> <ide> return realpath(dirname($path).'/../../'); <ide> } <ide><path>src/Illuminate/Translation/Translator.php <ide> protected function makeReplacements($line, array $replace) <ide> */ <ide> protected function sortReplacements(array $replace) <ide> { <del> return with(new Collection($replace))->sortBy(function($r) <add> return (new Collection($replace))->sortBy(function($r) <ide> { <ide> return mb_strlen($r) * -1; <ide> });
12
PHP
PHP
fix duplicate values when merging post data
17eb0e4f68ca440b9612e7e7b80b83b8ffdf434f
<ide><path>lib/Cake/Network/CakeRequest.php <ide> protected function _processPost() { <ide> } <ide> unset($this->data['_method']); <ide> } <del> $data = $this->data; <add> <ide> if (isset($this->data['data'])) { <ide> $data = $this->data['data']; <del> } <del> if (count($this->data) <= 1) { <del> $this->data = $data; <del> } else { <del> unset($this->data['data']); <del> $this->data = Set::merge($this->data, $data); <add> if (count($this->data) <= 1) { <add> $this->data = $data; <add> } else { <add> unset($this->data['data']); <add> $this->data = Set::merge($this->data, $data); <add> } <ide> } <ide> } <ide> <ide><path>lib/Cake/Test/Case/Network/CakeRequestTest.php <ide> public function testPostParsing() { <ide> )); <ide> $request = new CakeRequest('some/path'); <ide> $this->assertEquals($_POST['data'], $request->data); <add> <add> $_POST = array( <add> 'a' => array(1, 2), <add> 'b' => array(1, 2) <add> ); <add> $request = new CakeRequest('some/path'); <add> $this->assertEquals($_POST, $request->data); <ide> } <ide> <ide> /**
2
Text
Text
save option in validations
d2a799895b19cabca86a209cf2dac0dc5215ab48
<ide><path>guides/source/active_record_validations.md <ide> class Person < ActiveRecord::Base <ide> validates :age, numericality: true, on: :update <ide> <ide> # the default (validates on both create and update) <del> The following line is in review state and as of now, it is not running in any version of Rails 3.2.x as discussed in this [issue](https://github.com/rails/rails/issues/10248) <add> # The following line is in review state and as of now, it is not running in any version of Rails 3.2.x as discussed in this [issue](https://github.com/rails/rails/issues/10248) <ide> <ide> validates :name, presence: true, on: :save <ide> end
1
Python
Python
mark the subclass transformer as deprecated
487c4b2a13a4b34f3b6b0ac5715b05e275306853
<ide><path>official/nlp/modeling/layers/__init__.py <ide> from official.nlp.modeling.layers.text_layers import FastWordpieceBertTokenizer <ide> from official.nlp.modeling.layers.text_layers import SentencepieceTokenizer <ide> from official.nlp.modeling.layers.tn_transformer_expand_condense import TNTransformerExpandCondense <del>from official.nlp.modeling.layers.transformer import * <add>from official.nlp.modeling.layers.transformer import Transformer <add>from official.nlp.modeling.layers.transformer import TransformerDecoderBlock <ide> from official.nlp.modeling.layers.transformer_encoder_block import TransformerEncoderBlock <ide> from official.nlp.modeling.layers.transformer_scaffold import TransformerScaffold <ide> from official.nlp.modeling.layers.transformer_xl import TransformerXL <ide><path>official/nlp/modeling/layers/transformer.py <ide> """Keras-based transformer block layer.""" <ide> # pylint: disable=g-classes-have-attributes <ide> <add>from absl import logging <ide> import gin <ide> import tensorflow as tf <ide> <ide> class Transformer(transformer_encoder_block.TransformerEncoderBlock): <ide> This layer implements the Transformer from "Attention Is All You Need". <ide> (https://arxiv.org/abs/1706.03762). <ide> <add> **Warning: this layer is deprecated. Please don't use it. Use the <add> `TransformerEncoderBlock` layer instead.** <add> <ide> Args: <ide> num_attention_heads: Number of attention heads. <ide> intermediate_size: Size of the intermediate layer. <ide> def __init__(self, <ide> inner_dropout=intermediate_dropout, <ide> attention_initializer=attention_initializer, <ide> **kwargs) <add> logging.warning("The `Transformer` layer is deprecated. Please directly " <add> "use `TransformerEncoderBlock`.") <ide> <ide> def get_config(self): <ide> return {
2
Text
Text
explain browser support of http/2 without ssl
52a0d97187f92579676dce54e05724606374c2fc
<ide><path>doc/api/http2.md <ide> server.on('stream', (stream, headers) => { <ide> server.listen(80); <ide> ``` <ide> <add>Note that the above example is an HTTP/2 server that does not support SSL. <add>This is significant as most browsers support HTTP/2 only with SSL. <add>To make the above server be able to serve content to browsers, <add>replace `http2.createServer()` with <add>`http2.createSecureServer({key: /* your SSL key */, cert: /* your SSL cert */})`. <add> <ide> The following illustrates an HTTP/2 client: <ide> <ide> ```js
1
PHP
PHP
fix mistake with fixture properties
13ce406a816bf3a52152344d2c2fa070098803fb
<ide><path>lib/Cake/TestSuite/Fixture/FixtureManager.php <ide> public function loadSingle($name, $db = null, $dropTables = true) { <ide> if (isset($this->_fixtureMap[$name])) { <ide> $fixture = $this->_fixtureMap[$name]; <ide> if (!$db) { <del> $db = ConnectionManager::getDataSource($fixture->useDbConfig); <add> $db = ConnectionManager::getDataSource($fixture->connection); <ide> } <ide> $this->_setupTable($fixture, $db, $dropTables); <ide> $fixture->truncate($db);
1
Python
Python
remove unused code in /grid endpoint
2550066e4d105c8c5a030b7ef71dd95a890378b9
<ide><path>airflow/www/views.py <ide> def grid(self, dag_id, session=None): <ide> if num_runs is None: <ide> num_runs = conf.getint('webserver', 'default_dag_run_display_number') <ide> <del> try: <del> base_date = _safe_parse_datetime(request.args["base_date"]) <del> except (KeyError, ValueError): <del> base_date = dag.get_latest_execution_date() or timezone.utcnow() <del> <del> dag_runs = ( <del> session.query(DagRun) <del> .filter(DagRun.dag_id == dag.dag_id, DagRun.execution_date <= base_date) <del> .order_by(DagRun.execution_date.desc()) <del> .limit(num_runs) <del> .all() <del> ) <del> dag_run_dates = {dr.execution_date: alchemy_to_dict(dr) for dr in dag_runs} <del> <del> max_date = max(dag_run_dates, default=None) <del> <del> form = DateTimeWithNumRunsForm( <del> data={ <del> 'base_date': max_date or timezone.utcnow(), <del> 'num_runs': num_runs, <del> } <del> ) <del> <ide> doc_md = wwwutils.wrapped_markdown(getattr(dag, 'doc_md', None)) <ide> <ide> task_log_reader = TaskLogReader() <ide> def grid(self, dag_id, session=None): <ide> <ide> return self.render_template( <ide> 'airflow/grid.html', <del> operators=sorted({op.task_type: op for op in dag.tasks}.values(), key=lambda x: x.task_type), <ide> root=root, <del> form=form, <ide> dag=dag, <ide> doc_md=doc_md, <ide> num_runs=num_runs,
1
PHP
PHP
fix missing deprecation version
ebc3bf8179743e45d2fa4accc27183223e1941c9
<ide><path>src/Datasource/QueryTrait.php <ide> trait QueryTrait <ide> * When called with a Table argument, the default table object will be set <ide> * and this query object will be returned for chaining. <ide> * <add> * Deprecated: 3.6.0 Using Query::repository() as getter is deprecated. Use getRepository() instead. <add> * <ide> * @param \Cake\Datasource\RepositoryInterface|null $table The default table object to use <ide> * @return \Cake\Datasource\RepositoryInterface|$this <ide> */
1
Java
Java
ensure socketutils can be instantiated
08ba53dd0e0206fcfd72658c58371ccbe5a1ffaa
<ide><path>spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class SocketUtilsTests { <ide> @Rule <ide> public final ExpectedException exception = ExpectedException.none(); <ide> <add> @Test <add> public void canBeInstantiated() { <add> // Just making sure somebody doesn't try to make SocketUtils abstract, <add> // since that would be a breaking change due to the intentional public <add> // constructor. <add> new SocketUtils(); <add> } <add> <ide> // TCP <ide> <ide> @Test
1
Python
Python
add an alias to get stats as json
96c6faf4738976b62c9497ec78879ac76610dd66
<ide><path>glances/plugins/glances_plugin.py <ide> def get_stats(self): <ide> """Return the stats object in JSON format.""" <ide> return self._json_dumps(self.stats) <ide> <add> def get_json(self): <add> """Return the stats object in JSON format.""" <add> return self.get_stats() <add> <ide> def get_stats_item(self, item): <ide> """Return the stats object for a specific item in JSON format. <ide>
1
Ruby
Ruby
improve documentation and add test
6116d7bc052839646f448b8403a7287f52b97ed7
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb <ide> module ConnectionAdapters <ide> # * private methods that require being called in a +synchronize+ blocks <ide> # are now explicitly documented <ide> class ConnectionPool <del> # Threadsafe, fair, LIFO queue. Meant to be used by ConnectionPool <del> # with which it shares a Monitor. But could be a generic Queue. <del> # <del> # The Queue in stdlib's 'thread' could replace this class except <del> # stdlib's doesn't support waiting with a timeout. <add> # Threadsafe, fair, FIFO queue. Meant to be used by ConnectionPool <add> # with which it shares a Monitor. <ide> class Queue <ide> def initialize(lock = Monitor.new) <ide> @lock = lock <ide> def num_waiting <ide> # Add +element+ to the queue. Never blocks. <ide> def add(element) <ide> synchronize do <del> @queue.unshift element <add> @queue.push element <ide> @cond.signal <ide> end <ide> end <ide> def can_remove_no_wait? <ide> <ide> # Removes and returns the head of the queue if possible, or +nil+. <ide> def remove <del> @queue.shift <add> @queue.pop <ide> end <ide> <ide> # Remove and return the head the queue if the number of <ide><path>activerecord/test/cases/connection_pool_test.rb <ide> def test_checkout_behaviour <ide> end.join <ide> end <ide> <add> def test_checkout_order_is_fifo <add> conn1 = @pool.checkout <add> conn2 = @pool.checkout <add> @pool.checkin conn1 <add> @pool.checkin conn2 <add> assert_equal [conn2, conn1], 2.times.map { @pool.checkout } <add> end <add> <ide> # The connection pool is "fair" if threads waiting for <ide> # connections receive them in the order in which they began <ide> # waiting. This ensures that we don't timeout one HTTP request
2
Text
Text
fix a typo in changelog_v12
e2d22060ab589b1202caad8499f4080676e1d35e
<ide><path>doc/changelogs/CHANGELOG_V12.md <ide> occur in any future release.” Users should be cautious when using the feature <ide> in production environments. <ide> <ide> Unlike Node.js 14, using ESM will still emit a runtime experimental warning, <del>either when a module is used a the application's entrypoint or the first time <add>either when a module is used at the application's entrypoint or the first time <ide> dynamic `import()` is called. <ide> <ide> Please keep in mind that the implementation of ESM in Node.js differs from the
1
Javascript
Javascript
remove unnecessary comma in bokehshader2
1ff4e4568d3d2623b3e7af45cd3d8a51f5ec2d60
<ide><path>examples/js/shaders/BokehShader2.js <ide> THREE.BokehShader = { <ide> "pentagon": { value: 0 }, <ide> <ide> "shaderFocus": { value: 1 }, <del> "focusCoords": { value: new THREE.Vector2() }, <add> "focusCoords": { value: new THREE.Vector2() } <ide> <ide> <ide> },
1
PHP
PHP
fix bug with retrycommand
bd7aaa8ff0c37907ac66fcccfebc7d6e25a7402c
<ide><path>src/Illuminate/Queue/Console/RetryCommand.php <ide> <ide> namespace Illuminate\Queue\Console; <ide> <add>use DateTimeInterface; <ide> use Illuminate\Console\Command; <ide> use Illuminate\Support\Arr; <ide> <ide> protected function refreshRetryUntil($payload) <ide> $instance = unserialize($payload['data']['command']); <ide> <ide> if (is_object($instance) && method_exists($instance, 'retryUntil')) { <del> $payload['retryUntil'] = $instance->retryUntil()->timestamp; <add> $retryUntil = $instance->retryUntil(); <add> <add> $payload['retryUntil'] = $retryUntil instanceof DateTimeInterface <add> ? $retryUntil->getTimestamp() <add> : $retryUntil; <ide> } <ide> <ide> return json_encode($payload);
1
Python
Python
fix some more tests
4d7ff76cfbaf5fb8a57d8f3232c989e8e2c2f5b5
<ide><path>keras/engine/training.py <ide> def compile(self, optimizer, loss, metrics=[], loss_weights=None, <ide> ''' <ide> self.optimizer = optimizers.get(optimizer) <ide> self.sample_weight_mode = sample_weight_mode <add> self.loss = loss <ide> <ide> # prepare loss weights <ide> if loss_weights is None: <ide><path>keras/legacy/models.py <ide> def build(self, input_shape=None): <ide> <ide> def compile(self, optimizer, loss, <ide> metrics=[], <del> sample_weight_mode=None, <add> sample_weight_modes=None, <ide> loss_weights=None, <ide> **kwargs): <ide> '''Configures the learning process. <ide> def compile(self, optimizer, loss, <ide> self.build() <ide> super(Graph, self).compile(optimizer, loss, <ide> metrics=metrics, <del> sample_weight_mode=sample_weight_mode, <add> sample_weight_mode=sample_weight_modes, <ide> loss_weights=loss_weights, <ide> **kwargs) <ide> <ide><path>keras/models.py <ide> def compile(self, optimizer, loss, <ide> sample_weight_mode=sample_weight_mode, <ide> **kwargs) <ide> self.optimizer = self.model.optimizer <add> self.loss = self.model.loss <add> self.metrics_names = self.model.metrics_names <ide> self.sample_weight_mode = self.model.sample_weight_mode <ide> <ide> def fit(self, x, y, batch_size=32, nb_epoch=10, verbose=1, callbacks=[], <ide><path>keras/wrappers/scikit_learn.py <ide> def fit(self, X, y, **kwargs): <ide> else: <ide> self.model = self.build_fn(**self.filter_sk_params(self.build_fn)) <ide> <del> if self.model.loss.__name__ == 'categorical_crossentropy' and len(y.shape) != 2: <add> loss_name = self.model.loss <add> if hasattr(loss_name, '__name__'): <add> loss_name = loss_name.__name__ <add> if loss_name == 'categorical_crossentropy' and len(y.shape) != 2: <ide> y = to_categorical(y) <ide> <ide> fit_args = copy.deepcopy(self.filter_sk_params(Sequential.fit)) <ide> def score(self, X, y, **kwargs): <ide> Mean accuracy of predictions on X wrt. y. <ide> ''' <ide> kwargs = self.filter_sk_params(Sequential.evaluate, kwargs) <del> kwargs.update({'show_accuracy': True}) <del> loss, accuracy = self.model.evaluate(X, y, **kwargs) <del> return accuracy <add> outputs = self.model.evaluate(X, y, **kwargs) <add> if type(outputs) is not list: <add> outputs = [outputs] <add> for name, output in zip(self.model.metrics_names, outputs): <add> if name == 'acc': <add> return output <add> raise Exception('The model is not configured to compute accuracy. ' <add> 'You should pass `metrics=["accuracy"]` to ' <add> 'the `model.compile()` method.') <ide> <ide> <ide> class KerasRegressor(BaseWrapper): <ide> def predict(self, X, **kwargs): <ide> return self.model.predict(X, **kwargs) <ide> <ide> def score(self, X, y, **kwargs): <del> '''Returns the mean accuracy on the given test data and labels. <add> '''Returns the mean loss on the given test data and labels. <ide> <ide> # Arguments <ide> X: array-like, shape `(n_samples, n_features)` <ide> def score(self, X, y, **kwargs): <ide> Mean accuracy of predictions on X wrt. y. <ide> ''' <ide> kwargs = self.filter_sk_params(Sequential.evaluate, kwargs) <del> kwargs.update({'show_accuracy': False}) <ide> loss = self.model.evaluate(X, y, **kwargs) <add> if type(loss) is list: <add> return loss[0] <ide> return loss <ide><path>tests/keras/test_graph_model.py <ide> def test_siamese_1(): <ide> new_graph = model_from_yaml(yaml_str) <ide> <ide> <del>def test_siamese_2(): <del> graph = Graph() <del> graph.add_input(name='input1', input_shape=(32,)) <del> graph.add_input(name='input2', input_shape=(32,)) <del> <del> graph.add_shared_node(Dense(4), name='shared', <del> inputs=['input1', 'input2'], <del> outputs=['shared_output1', 'shared_output2']) <del> graph.add_node(Dense(4), name='dense1', input='shared_output1') <del> graph.add_node(Dense(4), name='dense2', input='shared_output2') <del> <del> graph.add_output(name='output1', inputs=['dense1', 'dense2'], <del> merge_mode='sum') <del> graph.compile('rmsprop', {'output1': 'mse'}) <del> <del> graph.fit({'input1': X_train_graph, <del> 'input2': X2_train_graph, <del> 'output1': y_train_graph}, <del> nb_epoch=10) <del> out = graph.predict({'input1': X_test_graph, <del> 'input2': X2_test_graph}) <del> assert(type(out == dict)) <del> assert(len(out) == 1) <del> <del> loss = graph.test_on_batch({'input1': X_test_graph, <del> 'input2': X2_test_graph, <del> 'output1': y_test_graph}) <del> loss = graph.train_on_batch({'input1': X_test_graph, <del> 'input2': X2_test_graph, <del> 'output1': y_test_graph}) <del> loss = graph.evaluate({'input1': X_test_graph, <del> 'input2': X2_test_graph, <del> 'output1': y_test_graph}) <del> # test serialization <del> config = graph.get_config() <del> new_graph = Graph.from_config(config) <del> <del> graph.summary() <del> json_str = graph.to_json() <del> new_graph = model_from_json(json_str) <del> <del> yaml_str = graph.to_yaml() <del> new_graph = model_from_yaml(yaml_str) <add>'''Th test below is failing because of a known bug <add>with the serialization of legacy Graph models <add>containing shared nodes with named outputs. <add>This is very low priority (= no plans to fix it), <add>since the Graph model is deprecated. <add>''' <add># def test_siamese_2(): <add># graph = Graph() <add># graph.add_input(name='input1', input_shape=(32,)) <add># graph.add_input(name='input2', input_shape=(32,)) <add> <add># graph.add_shared_node(Dense(4), name='shared', <add># inputs=['input1', 'input2'], <add># outputs=['shared_output1', 'shared_output2']) <add># graph.add_node(Dense(4), name='dense1', input='shared_output1') <add># graph.add_node(Dense(4), name='dense2', input='shared_output2') <add> <add># graph.add_output(name='output1', inputs=['dense1', 'dense2'], <add># merge_mode='sum') <add># graph.compile('rmsprop', {'output1': 'mse'}) <add> <add># graph.fit({'input1': X_train_graph, <add># 'input2': X2_train_graph, <add># 'output1': y_train_graph}, <add># nb_epoch=10) <add># out = graph.predict({'input1': X_test_graph, <add># 'input2': X2_test_graph}) <add># assert(type(out == dict)) <add># assert(len(out) == 1) <add> <add># loss = graph.test_on_batch({'input1': X_test_graph, <add># 'input2': X2_test_graph, <add># 'output1': y_test_graph}) <add># loss = graph.train_on_batch({'input1': X_test_graph, <add># 'input2': X2_test_graph, <add># 'output1': y_test_graph}) <add># loss = graph.evaluate({'input1': X_test_graph, <add># 'input2': X2_test_graph, <add># 'output1': y_test_graph}) <add># # test serialization <add># config = graph.get_config() <add># new_graph = Graph.from_config(config) <add> <add># graph.summary() <add># json_str = graph.to_json() <add># new_graph = model_from_json(json_str) <add> <add># yaml_str = graph.to_yaml() <add># new_graph = model_from_yaml(yaml_str) <ide> <ide> <ide> def test_2o_1i_save_weights(): <ide><path>tests/keras/test_sequential_model.py <ide> def test_merge_sum(): <ide> new_model = model_from_yaml(yaml_str) <ide> <ide> <del>@pytest.mark.skipif(K._BACKEND == 'tensorflow', <del> reason='currently not working with TensorFlow') <ide> def test_merge_dot(): <ide> (X_train, y_train), (X_test, y_test) = _get_test_data() <ide> <ide><path>tests/keras/wrappers/test_scikit_learn.py <ide> def build_fn_clf(hidden_dims=50): <ide> model.add(Dense(nb_class)) <ide> model.add(Activation('softmax')) <ide> model.compile(optimizer='sgd', loss='categorical_crossentropy', <del> class_mode='binary') <add> metrics=['accuracy']) <ide> return model <ide> <ide> <ide> def build_fn_reg(hidden_dims=50): <ide> model.add(Activation('relu')) <ide> model.add(Dense(1)) <ide> model.add(Activation('linear')) <del> model.compile(optimizer='sgd', loss='mean_absolute_error') <add> model.compile(optimizer='sgd', loss='mean_absolute_error', <add> metrics=['accuracy']) <ide> return model <ide> <ide> <ide><path>tests/test_loss_masking.py <ide> import numpy as np <ide> import pytest <ide> <del>from keras.models import Sequential, weighted_objective <add>from keras.models import Sequential <add>from keras.engine.training import weighted_objective <ide> from keras.layers.core import TimeDistributedDense, Masking <ide> from keras import objectives <ide> from keras import backend as K
8
PHP
PHP
add implemented interface
47a9a5bdc818845ef7542527a09c62c603ae3f0a
<ide><path>src/Console/CommandRunner.php <ide> use Cake\Console\Exception\StopException; <ide> use Cake\Console\Shell; <ide> use Cake\Core\ConsoleApplicationInterface; <add>use Cake\Event\EventDispatcherInterface; <ide> use Cake\Event\EventDispatcherTrait; <ide> use Cake\Utility\Inflector; <ide> use RuntimeException; <ide> <ide> /** <ide> * Run CLI commands for the provided application. <ide> */ <del>class CommandRunner <add>class CommandRunner implements EventDispatcherInterface <ide> { <ide> use EventDispatcherTrait; <ide>
1
Text
Text
remove ref to obsolete 'def patches'
159373707b4d8da7f27dbae92585b11674cbd8a2
<ide><path>share/doc/homebrew/Formula-Cookbook.md <ide> Check if the formula you are updating is a dependency for any other formulae by <ide> <ide> Homebrew wants to maintain a consistent Ruby style across all formulae based on [Ruby Style Guide](https://github.com/styleguide/ruby). Other formulae may not have been updated to match this guide yet but all new ones should. Also: <ide> <del>* The order of methods in a formula should be consistent with other formulae (e.g.: `def patches` goes before `def install`) <add>* The order of methods in a formula should be consistent with other formulae (e.g.: `def install` goes before `def post_install`) <ide> * An empty line is required before the `__END__` line <ide> <ide> # Troubleshooting for people writing new formulae
1
Java
Java
add onbackpressurereduce operator
e0122a4c264761ae9eaf969740acf17a0678ad7b
<ide><path>src/main/java/io/reactivex/rxjava3/core/Flowable.java <ide> public final Flowable<T> onBackpressureLatest() { <ide> @SchedulerSupport(SchedulerSupport.NONE) <ide> @NonNull <ide> public final Flowable<T> onBackpressureReduce(@NonNull BiFunction<T, T, T> reducer) { <add> Objects.requireNonNull(reducer, "reducer is null"); <ide> return RxJavaPlugins.onAssembly(new FlowableOnBackpressureReduce<>(this, reducer)); <ide> } <ide> <add> /** <add> * Reduces upstream values into an aggregate value, provided by a supplier and combined via a reducer function, <add> * while the downstream is not ready to receive items, then emits this aggregate value when the downstream becomes ready. <add> * <p> <add> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.onBackpressureReduce.ff.png" alt=""> <add> * <p> <add> * Note that even if the downstream is ready to receive an item, the upstream item will always be aggregated into the output type, <add> * calling both the supplier and the reducer to produce the output value. <add> * <p> <add> * Note that if the current {@code Flowable} does support backpressure, this operator ignores that capability <add> * and doesn't propagate any backpressure requests from downstream. <add> * <p> <add> * Note that due to the nature of how backpressure requests are propagated through subscribeOn/observeOn, <add> * requesting more than 1 from downstream doesn't guarantee a continuous delivery of {@code onNext} events. <add> * <dl> <add> * <dt><b>Backpressure:</b></dt> <add> * <dd>The operator honors backpressure from downstream and consumes the current {@code Flowable} in an unbounded <add> * manner (i.e., not applying backpressure to it).</dd> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code onBackpressureReduce} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param supplier the factory to call to create new item of type R to pass it as the first argument to {@code reducer}. <add> * It is called when previous returned value by {@code reducer} already sent to downstream or the very first update from upstream received. <add> * @param reducer the bi-function to call to reduce excessive updates which downstream is not ready to receive. <add> * The first argument of type R is the object returned by {@code supplier} or result of previous {@code reducer} invocation. <add> * The second argument of type T is the current update from upstream. <add> * @return the new {@code Flowable} instance <add> * @throws NullPointerException if {@code supplier} or {@code reducer} is {@code null} <add> * @see #onBackpressureReduce(BiFunction) <add> * @since 3.0.9 - experimental <add> */ <add> @Experimental <add> @CheckReturnValue <add> @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @NonNull <add> public final <R> Flowable<R> onBackpressureReduce(@NonNull Supplier<R> supplier, @NonNull BiFunction<R, ? super T, R> reducer) { <add> Objects.requireNonNull(supplier, "supplier is null"); <add> Objects.requireNonNull(reducer, "reducer is null"); <add> return RxJavaPlugins.onAssembly(new FlowableOnBackpressureReduceWith<>(this, supplier, reducer)); <add> } <add> <ide> /** <ide> * Returns a {@code Flowable} instance that if the current {@code Flowable} emits an error, it will emit an {@code onComplete} <ide> * and swallow the throwable. <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/AbstractBackpressureThrottlingSubscriber.java <ide> * Abstract base class for operators that throttle excessive updates from upstream in case if <ide> * downstream {@link Subscriber} is not ready to receive updates <ide> * <del> * @param <T> the upstream and downstream value type <add> * @param <T> the upstream value type <add> * @param <R> the downstream value type <ide> */ <del>abstract class AbstractBackpressureThrottlingSubscriber<T> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { <add>abstract class AbstractBackpressureThrottlingSubscriber<T, R> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { <ide> <del> final Subscriber<? super T> downstream; <add> final Subscriber<? super R> downstream; <ide> <ide> Subscription upstream; <ide> <ide> <ide> final AtomicLong requested = new AtomicLong(); <ide> <del> final AtomicReference<T> current = new AtomicReference<>(); <add> final AtomicReference<R> current = new AtomicReference<>(); <ide> <del> AbstractBackpressureThrottlingSubscriber(Subscriber<? super T> downstream) { <add> AbstractBackpressureThrottlingSubscriber(Subscriber<? super R> downstream) { <ide> this.downstream = downstream; <ide> } <ide> <ide> void drain() { <ide> if (getAndIncrement() != 0) { <ide> return; <ide> } <del> final Subscriber<? super T> a = downstream; <add> final Subscriber<? super R> a = downstream; <ide> int missed = 1; <ide> final AtomicLong r = requested; <del> final AtomicReference<T> q = current; <add> final AtomicReference<R> q = current; <ide> <ide> for (;;) { <ide> long e = 0L; <ide> <ide> while (e != r.get()) { <ide> boolean d = done; <del> T v = q.getAndSet(null); <add> R v = q.getAndSet(null); <ide> boolean empty = v == null; <ide> <ide> if (checkTerminated(d, empty, a, q)) { <ide> void drain() { <ide> } <ide> } <ide> <del> boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a, AtomicReference<T> q) { <add> boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a, AtomicReference<R> q) { <ide> if (cancelled) { <ide> q.lazySet(null); <ide> return true; <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureLatest.java <ide> protected void subscribeActual(Subscriber<? super T> s) { <ide> source.subscribe(new BackpressureLatestSubscriber<>(s)); <ide> } <ide> <del> static final class BackpressureLatestSubscriber<T> extends AbstractBackpressureThrottlingSubscriber<T> { <add> static final class BackpressureLatestSubscriber<T> extends AbstractBackpressureThrottlingSubscriber<T, T> { <ide> <ide> private static final long serialVersionUID = 163080509307634843L; <ide> <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureReduce.java <ide> <ide> package io.reactivex.rxjava3.internal.operators.flowable; <ide> <add>import io.reactivex.rxjava3.annotations.NonNull; <ide> import io.reactivex.rxjava3.core.Flowable; <ide> import io.reactivex.rxjava3.exceptions.Exceptions; <ide> import io.reactivex.rxjava3.functions.BiFunction; <ide> <ide> final BiFunction<T, T, T> reducer; <ide> <del> public FlowableOnBackpressureReduce(Flowable<T> source, BiFunction<T, T, T> reducer) { <add> public FlowableOnBackpressureReduce(@NonNull Flowable<T> source, @NonNull BiFunction<T, T, T> reducer) { <ide> super(source); <del> this.reducer = Objects.requireNonNull(reducer, "reducer is null"); <add> this.reducer = reducer; <ide> } <ide> <ide> @Override <del> protected void subscribeActual(Subscriber<? super T> s) { <add> protected void subscribeActual(@NonNull Subscriber<? super T> s) { <ide> source.subscribe(new BackpressureReduceSubscriber<>(s, reducer)); <ide> } <ide> <del> static final class BackpressureReduceSubscriber<T> extends AbstractBackpressureThrottlingSubscriber<T> { <add> static final class BackpressureReduceSubscriber<T> extends AbstractBackpressureThrottlingSubscriber<T, T> { <ide> <ide> private static final long serialVersionUID = 821363947659780367L; <ide> <ide> final BiFunction<T, T, T> reducer; <ide> <del> BackpressureReduceSubscriber(Subscriber<? super T> downstream, BiFunction<T, T, T> reducer) { <add> BackpressureReduceSubscriber(@NonNull Subscriber<? super T> downstream, @NonNull BiFunction<T, T, T> reducer) { <ide> super(downstream); <ide> this.reducer = reducer; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureReduceWith.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <p> <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <p> <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <p> <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import io.reactivex.rxjava3.annotations.NonNull; <add>import io.reactivex.rxjava3.core.Flowable; <add>import io.reactivex.rxjava3.exceptions.Exceptions; <add>import io.reactivex.rxjava3.functions.BiFunction; <add>import io.reactivex.rxjava3.functions.Supplier; <add>import org.reactivestreams.Subscriber; <add> <add>import java.util.Objects; <add> <add>public final class FlowableOnBackpressureReduceWith<T, R> extends AbstractFlowableWithUpstream<T, R> { <add> <add> final BiFunction<R, ? super T, R> reducer; <add> final Supplier<R> supplier; <add> <add> public FlowableOnBackpressureReduceWith(@NonNull Flowable<T> source, <add> @NonNull Supplier<R> supplier, <add> @NonNull BiFunction<R, ? super T, R> reducer) { <add> super(source); <add> this.reducer = reducer; <add> this.supplier = supplier; <add> } <add> <add> @Override <add> protected void subscribeActual(@NonNull Subscriber<? super R> s) { <add> source.subscribe(new BackpressureReduceWithSubscriber<>(s, supplier, reducer)); <add> } <add> <add> static final class BackpressureReduceWithSubscriber<T, R> extends AbstractBackpressureThrottlingSubscriber<T, R> { <add> <add> private static final long serialVersionUID = 8255923705960622424L; <add> <add> final BiFunction<R, ? super T, R> reducer; <add> final Supplier<R> supplier; <add> <add> BackpressureReduceWithSubscriber(@NonNull Subscriber<? super R> downstream, <add> @NonNull Supplier<R> supplier, <add> @NonNull BiFunction<R, ? super T, R> reducer) { <add> super(downstream); <add> this.reducer = reducer; <add> this.supplier = supplier; <add> } <add> <add> @Override <add> public void onNext(T t) { <add> R v = current.get(); <add> try { <add> if (v == null) { <add> current.lazySet(Objects.requireNonNull( <add> reducer.apply(Objects.requireNonNull(supplier.get(), "The supplier returned a null value"), t), <add> "The reducer returned a null value" <add> )); <add> } else if ((v = current.getAndSet(null)) != null) { <add> current.lazySet(Objects.requireNonNull(reducer.apply(v, t), "The reducer returned a null value")); <add> } else { <add> current.lazySet(Objects.requireNonNull( <add> reducer.apply(Objects.requireNonNull(supplier.get(), "The supplier returned a null value"), t), <add> "The reducer returned a null value" <add> )); <add> } <add> } catch (Throwable ex) { <add> Exceptions.throwIfFatal(ex); <add> onError(ex); <add> cancel(); <add> } <add> drain(); <add> } <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureReduceTest.java <ide> import org.junit.Assert; <ide> import org.junit.Test; <ide> <del>import java.io.IOException; <ide> import java.util.Random; <ide> import java.util.concurrent.TimeUnit; <ide> <ide> public void exceptionFromReducer() { <ide> PublishProcessor<Integer> source = PublishProcessor.create(); <ide> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(0); <ide> source.onBackpressureReduce((l, r) -> { <del> throw new IOException("Test exception"); <add> throw new TestException("Test exception"); <ide> }).subscribe(ts); <ide> <ide> source.onNext(1); <ide> source.onNext(2); <ide> <del> TestHelper.assertError(ts.errors(), 0, IOException.class, "Test exception"); <add> TestHelper.assertError(ts.errors(), 0, TestException.class, "Test exception"); <ide> } <ide> <ide> @Test <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureReduceWithTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <p> <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <p> <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <p> <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import io.reactivex.rxjava3.core.Flowable; <add>import io.reactivex.rxjava3.core.RxJavaTest; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.functions.BiFunction; <add>import io.reactivex.rxjava3.functions.Supplier; <add>import io.reactivex.rxjava3.processors.PublishProcessor; <add>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.testsupport.TestHelper; <add>import io.reactivex.rxjava3.testsupport.TestSubscriberEx; <add>import org.junit.Assert; <add>import org.junit.Test; <add> <add>import java.util.*; <add>import java.util.concurrent.TimeUnit; <add> <add>public class FlowableOnBackpressureReduceWithTest extends RxJavaTest { <add> <add> private static <T> BiFunction<List<T>, T, List<T>> createTestReducer() { <add> return (list, number) -> { <add> list.add(number); <add> return list; <add> }; <add> } <add> <add> private static <T> Supplier<List<T>> createTestSupplier() { <add> return ArrayList::new; <add> } <add> <add> @Test <add> public void simple() { <add> TestSubscriberEx<List<Integer>> ts = new TestSubscriberEx<>(); <add> <add> Flowable.range(1, 5).onBackpressureReduce(createTestSupplier(), createTestReducer()).subscribe(ts); <add> <add> ts.assertNoErrors(); <add> ts.assertTerminated(); <add> ts.assertValues( <add> Collections.singletonList(1), <add> Collections.singletonList(2), <add> Collections.singletonList(3), <add> Collections.singletonList(4), <add> Collections.singletonList(5) <add> ); <add> } <add> <add> @Test <add> public void simpleError() { <add> TestSubscriberEx<List<Integer>> ts = new TestSubscriberEx<>(); <add> <add> Flowable.range(1, 5).concatWith(Flowable.error(new TestException())) <add> .onBackpressureReduce(createTestSupplier(), createTestReducer()).subscribe(ts); <add> <add> ts.assertTerminated(); <add> ts.assertError(TestException.class); <add> ts.assertValues( <add> Collections.singletonList(1), <add> Collections.singletonList(2), <add> Collections.singletonList(3), <add> Collections.singletonList(4), <add> Collections.singletonList(5) <add> ); <add> } <add> <add> @Test <add> public void simpleBackpressure() { <add> TestSubscriberEx<List<Integer>> ts = new TestSubscriberEx<>(2L); <add> <add> Flowable.range(1, 5).onBackpressureReduce(createTestSupplier(), createTestReducer()).subscribe(ts); <add> <add> ts.assertNoErrors(); <add> ts.assertValues( <add> Collections.singletonList(1), <add> Collections.singletonList(2) <add> ); <add> ts.assertNotComplete(); <add> } <add> <add> @Test <add> public void synchronousDrop() { <add> PublishProcessor<Integer> source = PublishProcessor.create(); <add> TestSubscriberEx<List<Integer>> ts = new TestSubscriberEx<>(0L); <add> <add> source.onBackpressureReduce(createTestSupplier(), createTestReducer()).subscribe(ts); <add> <add> ts.assertNoValues(); <add> <add> source.onNext(1); <add> ts.request(2); <add> <add> ts.assertValues(Collections.singletonList(1)); <add> <add> source.onNext(2); <add> <add> ts.assertValues( <add> Collections.singletonList(1), <add> Collections.singletonList(2) <add> ); <add> <add> source.onNext(3); <add> source.onNext(4); <add> source.onNext(5); <add> source.onNext(6); <add> <add> ts.request(2); <add> <add> ts.assertValues( <add> Collections.singletonList(1), <add> Collections.singletonList(2), <add> Arrays.asList(3, 4, 5, 6) <add> ); <add> <add> source.onNext(7); <add> <add> ts.assertValues( <add> Collections.singletonList(1), <add> Collections.singletonList(2), <add> Arrays.asList(3, 4, 5, 6), <add> Collections.singletonList(7) <add> ); <add> <add> source.onNext(8); <add> source.onNext(9); <add> source.onComplete(); <add> <add> ts.request(1); <add> <add> ts.assertValues( <add> Collections.singletonList(1), <add> Collections.singletonList(2), <add> Arrays.asList(3, 4, 5, 6), <add> Collections.singletonList(7), <add> Arrays.asList(8, 9) <add> ); <add> ts.assertNoErrors(); <add> ts.assertTerminated(); <add> } <add> <add> private <T> TestSubscriberEx<T> createDelayedSubscriber() { <add> return new TestSubscriberEx<T>(1L) { <add> final Random rnd = new Random(); <add> <add> @Override <add> public void onNext(T t) { <add> super.onNext(t); <add> if (rnd.nextDouble() < 0.001) { <add> try { <add> Thread.sleep(1); <add> } catch (InterruptedException ex) { <add> ex.printStackTrace(); <add> } <add> } <add> request(1); <add> } <add> }; <add> } <add> <add> private <T> void assertValuesDropped(TestSubscriberEx<T> ts, int totalValues) { <add> int n = ts.values().size(); <add> System.out.println("testAsynchronousDrop -> " + n); <add> Assert.assertTrue("All events received?", n < totalValues); <add> } <add> <add> private void assertIncreasingSequence(TestSubscriberEx<Integer> ts) { <add> int previous = 0; <add> for (Integer current : ts.values()) { <add> Assert.assertTrue("The sequence must be increasing [current value=" + previous + <add> ", previous value=" + current + "]", previous <= current); <add> previous = current; <add> } <add> } <add> <add> @Test <add> public void asynchronousDrop() { <add> TestSubscriberEx<Integer> ts = createDelayedSubscriber(); <add> int m = 100000; <add> Flowable.range(1, m) <add> .subscribeOn(Schedulers.computation()) <add> .onBackpressureReduce((Supplier<List<Integer>>) Collections::emptyList, (list, current) -> { <add> //in that case it works like onBackpressureLatest <add> //the output sequence of number must be increasing <add> return Collections.singletonList(current); <add> }) <add> .observeOn(Schedulers.io()) <add> .concatMap(Flowable::fromIterable) <add> .subscribe(ts); <add> <add> ts.awaitDone(2, TimeUnit.SECONDS); <add> ts.assertTerminated(); <add> assertValuesDropped(ts, m); <add> assertIncreasingSequence(ts); <add> } <add> <add> @Test <add> public void asynchronousDrop2() { <add> TestSubscriberEx<Long> ts = createDelayedSubscriber(); <add> int m = 100000; <add> Flowable.rangeLong(1, m) <add> .subscribeOn(Schedulers.computation()) <add> .onBackpressureReduce(createTestSupplier(), createTestReducer()) <add> .observeOn(Schedulers.io()) <add> .concatMap(list -> Flowable.just(list.stream().reduce(Long::sum).orElseThrow(() -> { <add> throw new IllegalArgumentException("No value in list"); <add> }))) <add> .subscribe(ts); <add> <add> ts.awaitDone(2, TimeUnit.SECONDS); <add> ts.assertTerminated(); <add> assertValuesDropped(ts, m); <add> long sum = 0; <add> for (Long i : ts.values()) { <add> sum += i; <add> } <add> //sum = (A1 + An) * n / 2 = 100_001 * 50_000 = 50_000_00000 + 50_000 = 50_000_50_000 <add> Assert.assertEquals("Wrong sum: " + sum, 5000050000L, sum); <add> } <add> <add> @Test <add> public void nullPointerFromReducer() { <add> PublishProcessor<Integer> source = PublishProcessor.create(); <add> TestSubscriberEx<List<Integer>> ts = new TestSubscriberEx<>(0L); <add> source.onBackpressureReduce(createTestSupplier(), (BiFunction<List<Integer>, ? super Integer, List<Integer>>) (list, number) -> null).subscribe(ts); <add> <add> source.onNext(1); <add> source.onNext(2); <add> <add> TestHelper.assertError(ts.errors(), 0, NullPointerException.class, "The reducer returned a null value"); <add> } <add> <add> @Test <add> public void nullPointerFromSupplier() { <add> PublishProcessor<Integer> source = PublishProcessor.create(); <add> TestSubscriberEx<List<Integer>> ts = new TestSubscriberEx<>(0L); <add> source.onBackpressureReduce(() -> null, createTestReducer()).subscribe(ts); <add> <add> source.onNext(1); <add> source.onNext(2); <add> <add> TestHelper.assertError(ts.errors(), 0, NullPointerException.class, "The supplier returned a null value"); <add> } <add> <add> @Test <add> public void exceptionFromReducer() { <add> PublishProcessor<Integer> source = PublishProcessor.create(); <add> TestSubscriberEx<List<Integer>> ts = new TestSubscriberEx<>(0L); <add> source.onBackpressureReduce(createTestSupplier(), (BiFunction<List<Integer>, ? super Integer, List<Integer>>) (l, r) -> { <add> throw new TestException("Test exception"); <add> }).subscribe(ts); <add> <add> source.onNext(1); <add> source.onNext(2); <add> <add> TestHelper.assertError(ts.errors(), 0, TestException.class, "Test exception"); <add> } <add> <add> @Test <add> public void exceptionFromSupplier() { <add> PublishProcessor<Integer> source = PublishProcessor.create(); <add> TestSubscriberEx<List<Integer>> ts = new TestSubscriberEx<>(0L); <add> source.onBackpressureReduce(() -> { <add> throw new TestException("Test exception"); <add> }, createTestReducer()).subscribe(ts); <add> <add> source.onNext(1); <add> source.onNext(2); <add> <add> TestHelper.assertError(ts.errors(), 0, TestException.class, "Test exception"); <add> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(f -> f.onBackpressureReduce(createTestSupplier(), createTestReducer())); <add> } <add> <add> @Test <add> public void take() { <add> Flowable.just(1, 2) <add> .onBackpressureReduce(createTestSupplier(), createTestReducer()) <add> .take(1) <add> .test() <add> .assertResult(Collections.singletonList(1)); <add> } <add> <add> @Test <add> public void dispose() { <add> TestHelper.checkDisposed(Flowable.never().onBackpressureReduce(createTestSupplier(), createTestReducer())); <add> } <add> <add> @Test <add> public void badRequest() { <add> TestHelper.assertBadRequestReported(Flowable.never().onBackpressureReduce(createTestSupplier(), createTestReducer())); <add> } <add>}
7
PHP
PHP
add callback support to "optional"
cb6e308e19754db5a7d5ee42c1334a28001ac5e1
<ide><path>src/Illuminate/Support/helpers.php <ide> function object_get($object, $key, $default = null) <ide> * Provide access to optional objects. <ide> * <ide> * @param mixed $value <add> * @param callable|null $callback <ide> * @return mixed <ide> */ <del> function optional($value = null) <add> function optional($value = null, callable $callback = null) <ide> { <del> return new Optional($value); <add> if (is_null($callback)) { <add> return new Optional($value); <add> } elseif (! is_null($value)) { <add> return $callback($value); <add> } <ide> } <ide> } <ide> <ide><path>tests/Support/SupportHelpersTest.php <ide> public function something() <ide> })->something()); <ide> } <ide> <add> public function testOptionalWithCallback() <add> { <add> $this->assertNull(optional(null, function () { <add> throw new RuntimeException( <add> 'The optional callback should not be called for null' <add> ); <add> })); <add> <add> $this->assertEquals(10, optional(5, function ($number) { <add> return $number * 2; <add> })); <add> } <add> <ide> public function testOptionalWithArray() <ide> { <ide> $this->assertEquals('here', optional(['present' => 'here'])['present']);
2
Text
Text
add new book title for devops
7fe751782a0cd61b50ee5c076a9fe3184df1f3f2
<ide><path>guide/english/book-recommendations/index.md <ide> title: Books to Read for Programmers <ide> - [Amazon Smile](https://smile.amazon.com/Code-Language-Computer-Hardware-Software/dp/0735611319/ref=sr_1_1?s=books&ie=UTF8&qid=1508780869&sr=1-1&keywords=code) <ide> - ISBN-13: 978-0735611313 <ide> <add>*DevOps Handbook:How to Create World-Class Agility, Reliability, and Security in Technology Organizations* by Gene Kim et al <add>- [Amazon Smile](https://www.amazon.com/DevOps-Handbook-World-Class-Reliability-Organizations/dp/1942788002/ref=sr_1_4?s=books&ie=UTF8&qid=1539733859&sr=1-4&keywords=devops+handbook) <add>- ISBN-13: 978-1942788003 <add> <ide> *Don't Make Me Think, Revisited: A Common Sense Approach to Web Usability by Steve Krug* <ide> - [Amazon Smile](https://smile.amazon.com/Dont-Make-Think-Revisited-Usability/dp/0321965515/ref=sr_1_1?ie=UTF8&qid=1538370339&sr=8-1&keywords=dont+make+me+think) <ide> - ISBN-13: 978-0321965516
1
Go
Go
use consts for default registry
ab47fd2f72b4f1d757a4a6cd986c51733535ee2a
<ide><path>registry/config.go <ide> type serviceConfig struct { <ide> registrytypes.ServiceConfig <ide> } <ide> <del>var ( <add>const ( <ide> // DefaultNamespace is the default namespace <ide> DefaultNamespace = "docker.io" <ide> // DefaultRegistryVersionHeader is the name of the default HTTP header <ide> var ( <ide> IndexServer = "https://" + IndexHostname + "/v1/" <ide> // IndexName is the name of the index <ide> IndexName = "docker.io" <add>) <ide> <add>var ( <ide> // DefaultV2Registry is the URI of the default v2 registry <ide> DefaultV2Registry = &url.URL{ <ide> Scheme: "https", <ide> Host: "registry-1.docker.io", <ide> } <del>) <ide> <del>var ( <ide> // ErrInvalidRepositoryName is an error returned if the repository name did <ide> // not have the correct form <ide> ErrInvalidRepositoryName = errors.New("Invalid repository name (ex: \"registry.domain.tld/myrepos\")") <ide> <ide> emptyServiceConfig, _ = newServiceConfig(ServiceOptions{}) <del>) <add> validHostPortRegex = regexp.MustCompile(`^` + reference.DomainRegexp.String() + `$`) <ide> <del>var ( <del> validHostPortRegex = regexp.MustCompile(`^` + reference.DomainRegexp.String() + `$`) <add> // for mocking in unit tests <add> lookupIP = net.LookupIP <ide> ) <ide> <del>// for mocking in unit tests <del>var lookupIP = net.LookupIP <del> <ide> // newServiceConfig returns a new instance of ServiceConfig <ide> func newServiceConfig(options ServiceOptions) (*serviceConfig, error) { <ide> config := &serviceConfig{
1
Text
Text
clarify html safe translations [ci-skip]
0e41b0a87a10205d2b85406ae33e116a5e4cbab3
<ide><path>guides/source/i18n.md <ide> I18n.default_locale = :de <ide> <ide> ### Using Safe HTML Translations <ide> <del>Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. Use them in views without escaping. <add>Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. When you use them in views the HTML will not be escaped. <ide> <ide> ```yaml <ide> # config/locales/en.yml
1
Javascript
Javascript
add a dispose function
b0436ca155722717d7e9888f2b22e7ed313ae875
<ide><path>examples/jsm/csm/CSM.js <ide> export default class CSM { <ide> <ide> } <ide> <add> dispose() { <add> <add> const shaders = this.shaders; <add> shaders.forEach( function ( shader, material ) { <add> <add> delete material.onBeforeCompile; <add> delete material.defines.USE_CSM; <add> delete material.defines.CSM_CASCADES; <add> delete material.defines.CSM_FADE; <add> <add> delete shader.uniforms.CSM_cascades; <add> delete shader.uniforms.cameraNear; <add> delete shader.uniforms.shadowFar; <add> <add> <add> material.needsUpdate = true; <add> <add> } ); <add> shaders.clear(); <add> <add> } <add> <ide> }
1
Javascript
Javascript
remove unused parameters and methods
ff0369883e73fa0f937d2bbb3c86e9267103d7f6
<ide><path>src/ng/parse.js <ide> Lexer.prototype = { <ide> this.text = text; <ide> this.index = 0; <ide> this.ch = undefined; <del> this.lastCh = ':'; // can start regexp <ide> this.tokens = []; <ide> <ide> while (this.index < this.text.length) { <ide> Lexer.prototype = { <ide> this.index++; <ide> } else if (this.isWhitespace(this.ch)) { <ide> this.index++; <del> continue; <ide> } else { <ide> var ch2 = this.ch + this.peek(); <ide> var ch3 = ch2 + this.peek(2); <ide> Lexer.prototype = { <ide> this.throwError('Unexpected next character ', this.index, this.index + 1); <ide> } <ide> } <del> this.lastCh = this.ch; <ide> } <ide> return this.tokens; <ide> }, <ide> Lexer.prototype = { <ide> return chars.indexOf(this.ch) !== -1; <ide> }, <ide> <del> was: function(chars) { <del> return chars.indexOf(this.lastCh) !== -1; <del> }, <del> <ide> peek: function(i) { <ide> var num = i || 1; <ide> return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; <ide> Lexer.prototype = { <ide> return (getter(self, locals)); <ide> }, { <ide> assign: function(self, value) { <del> return setter(self, ident, value, parser.text, parser.options); <add> return setter(self, ident, value, parser.text); <ide> } <ide> }); <ide> } <ide> Parser.prototype = { <ide> return getter(self || object(scope, locals)); <ide> }, { <ide> assign: function(scope, value, locals) { <del> return setter(object(scope, locals), field, value, parser.text, parser.options); <add> return setter(object(scope, locals), field, value, parser.text); <ide> } <ide> }); <ide> }, <ide> Parser.prototype = { <ide> return extend(function(self, locals) { <ide> var o = obj(self, locals), <ide> i = indexFn(self, locals), <del> v, p; <add> v; <ide> <ide> if (!o) return undefined; <ide> v = ensureSafeObject(o[i], parser.text); <ide> Parser.prototype = { <ide> // Parser helper functions <ide> ////////////////////////////////////////////////// <ide> <del>function setter(obj, path, setValue, fullExp, options) { <del> //needed? <del> options = options || {}; <add>function setter(obj, path, setValue, fullExp) { <ide> <ide> var element = path.split('.'), key; <ide> for (var i = 0; element.length > 1; i++) { <ide> var getterFnCache = {}; <ide> * - http://jsperf.com/angularjs-parse-getter/4 <ide> * - http://jsperf.com/path-evaluation-simplified/7 <ide> */ <del>function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) { <add>function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) { <ide> ensureSafeMemberName(key0, fullExp); <ide> ensureSafeMemberName(key1, fullExp); <ide> ensureSafeMemberName(key2, fullExp); <ide> function getterFn(path, options, fullExp) { <ide> fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp); <ide> } else if (options.csp) { <ide> if (pathKeysLength < 6) { <del> fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, <del> options); <add> fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp); <ide> } else { <ide> fn = function(scope, locals) { <ide> var i = 0, val; <ide> do { <ide> val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], <del> pathKeys[i++], fullExp, options)(scope, locals); <add> pathKeys[i++], fullExp)(scope, locals); <ide> <ide> locals = undefined; // clear after first iteration <ide> scope = val; <ide> function $ParseProvider() { <ide> }; <ide> <ide> <del> this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) { <add> this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { <ide> $parseOptions.csp = $sniffer.csp; <ide> <ide> return function(exp) {
1
Ruby
Ruby
remove unneeded merge with default false options
35c5ccb30cf01028970f157894a77fdf54973567
<ide><path>activemodel/lib/active_model/validations/numericality.rb <ide> class NumericalityValidator < EachValidator <ide> <ide> RESERVED_OPTIONS = CHECKS.keys + [:only_integer] <ide> <del> def initialize(options) <del> super(options.reverse_merge(:only_integer => false, :allow_nil => false)) <del> end <del> <ide> def check_validity! <ide> keys = CHECKS.keys - [:odd, :even] <ide> options.slice(*keys).each do |option, value|
1
Javascript
Javascript
update vrmlloader to import vertex colors
96c1f744eef6498e3c9dd15cc41a2235a070da40
<ide><path>examples/js/loaders/VRMLLoader.js <ide> THREE.VRMLLoader.prototype = { <ide> scope.angles = []; <ide> break; <ide> <add> case 'color': <ide> case 'skyColor': <ide> case 'groundColor': <ide> scope.recordingFieldname = fieldName; <ide> THREE.VRMLLoader.prototype = { <ide> scope.points = []; <ide> break; <ide> <add> case 'colorIndex': <ide> case 'coordIndex': <add> case 'normalIndex': <ide> case 'texCoordIndex': <ide> scope.recordingFieldname = fieldName; <ide> scope.isRecordingFaces = true; <ide> THREE.VRMLLoader.prototype = { <ide> case 'transparency': <ide> case 'shininess': <ide> case 'ambientIntensity': <add> case 'creaseAngle': <ide> if ( parts.length !== 2 ) { <ide> <ide> console.warn( 'THREE.VRMLLoader: Invalid single float value specification detected for %s.', fieldName ); <ide> THREE.VRMLLoader.prototype = { <ide> var geometry = new THREE.BufferGeometry(); <ide> <ide> var positions = []; <add> var colors = []; <ide> var normals = []; <ide> var uvs = []; <ide> <del> var position, normal, uv; <add> var position, color, normal, uv; <ide> <ide> var i, il, j, jl; <ide> <ide> THREE.VRMLLoader.prototype = { <ide> <ide> } <ide> <add> // colors <add> <add> if ( child.nodeType === 'Color' ) { <add> <add> if ( child.color ) { <add> <add> for ( j = 0, jl = child.color.length; j < jl; j ++ ) { <add> <add> color = child.color[ j ]; <add> colors.push( color.r, color.g, color.b ); <add> <add> } <add> <add> } <add> <add> } <add> <ide> // positions <ide> <ide> if ( child.nodeType === 'Coordinate' ) { <ide> THREE.VRMLLoader.prototype = { <ide> if ( data.coordIndex ) { <ide> <ide> var newPositions = []; <add> var newColors = []; <ide> var newNormals = []; <ide> var newUvs = []; <ide> <ide> position = new THREE.Vector3(); <add> color = new THREE.Color(); <ide> normal = new THREE.Vector3(); <ide> uv = new THREE.Vector2(); <ide> <ide> THREE.VRMLLoader.prototype = { <ide> position.fromArray( positions, i3 * 3 ); <ide> newPositions.push( position.x, position.y, position.z ); <ide> <add> if ( colors.length > 0 ) { <add> <add> color.fromArray( colors, i1 * 3 ); <add> newColors.push( color.r, color.g, color.b ); <add> color.fromArray( colors, i2 * 3 ); <add> newColors.push( color.r, color.g, color.b ); <add> color.fromArray( colors, i3 * 3 ); <add> newColors.push( color.r, color.g, color.b ); <add> <add> } <add> <ide> if ( uvs.length > 0 ) { <ide> <ide> uv.fromArray( uvs, i1 * 2 ); <ide> THREE.VRMLLoader.prototype = { <ide> } <ide> <ide> positions = newPositions; <add> colors = newColors; <ide> normals = newNormals; <ide> uvs = newUvs; <ide> <ide> THREE.VRMLLoader.prototype = { <ide> <ide> geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) ); <ide> <add> if ( colors.length > 0 ) { <add> <add> geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) ); <add> <add> } <add> <ide> if ( uvs.length > 0 ) { <ide> <ide> geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( uvs, 2 ) );
1
Ruby
Ruby
use method with_active_record_default_timezone
a0f0943d3a8c7f277d1266fce898b128b136bf6a
<ide><path>activerecord/test/cases/quoting_test.rb <ide> def test_quoted_date <ide> end <ide> <ide> def test_quoted_time_utc <del> before = ActiveRecord::Base.default_timezone <del> ActiveRecord::Base.default_timezone = :utc <del> t = Time.now <del> assert_equal t.getutc.to_s(:db), @quoter.quoted_date(t) <del> ensure <del> ActiveRecord::Base.default_timezone = before <add> with_active_record_default_timezone :utc do <add> t = Time.now <add> assert_equal t.getutc.to_s(:db), @quoter.quoted_date(t) <add> end <ide> end <ide> <ide> def test_quoted_time_local <del> before = ActiveRecord::Base.default_timezone <del> ActiveRecord::Base.default_timezone = :local <del> t = Time.now <del> assert_equal t.getlocal.to_s(:db), @quoter.quoted_date(t) <del> ensure <del> ActiveRecord::Base.default_timezone = before <add> with_active_record_default_timezone :local do <add> t = Time.now <add> assert_equal t.getlocal.to_s(:db), @quoter.quoted_date(t) <add> end <ide> end <ide> <ide> def test_quoted_time_crazy <del> before = ActiveRecord::Base.default_timezone <del> ActiveRecord::Base.default_timezone = :asdfasdf <del> t = Time.now <del> assert_equal t.getlocal.to_s(:db), @quoter.quoted_date(t) <del> ensure <del> ActiveRecord::Base.default_timezone = before <add> with_active_record_default_timezone :asdfasdf do <add> t = Time.now <add> assert_equal t.getlocal.to_s(:db), @quoter.quoted_date(t) <add> end <ide> end <ide> <ide> def test_quoted_datetime_utc <del> before = ActiveRecord::Base.default_timezone <del> ActiveRecord::Base.default_timezone = :utc <del> t = DateTime.now <del> assert_equal t.getutc.to_s(:db), @quoter.quoted_date(t) <del> ensure <del> ActiveRecord::Base.default_timezone = before <add> with_active_record_default_timezone :utc do <add> t = DateTime.now <add> assert_equal t.getutc.to_s(:db), @quoter.quoted_date(t) <add> end <ide> end <ide> <ide> ### <ide> # DateTime doesn't define getlocal, so make sure it does nothing <ide> def test_quoted_datetime_local <del> before = ActiveRecord::Base.default_timezone <del> ActiveRecord::Base.default_timezone = :local <del> t = DateTime.now <del> assert_equal t.to_s(:db), @quoter.quoted_date(t) <del> ensure <del> ActiveRecord::Base.default_timezone = before <add> with_active_record_default_timezone :local do <add> t = DateTime.now <add> assert_equal t.to_s(:db), @quoter.quoted_date(t) <add> end <ide> end <ide> <ide> def test_quote_with_quoted_id
1
Ruby
Ruby
allow selective linking at the file level
01994c7be194e3742913e15ad6f1a775de45e03c
<ide><path>Library/Homebrew/cleaner.rb <ide> def clean_dir d <ide> elsif path.extname == '.la' <ide> # *.la files are stupid <ide> path.unlink unless @f.skip_clean? path <del> elsif path == @f.lib+'charset.alias' <del> path.unlink unless @f.skip_clean? path <ide> elsif not path.symlink? <ide> clean_file path <ide> end <ide><path>Library/Homebrew/keg.rb <ide> def initialize path <ide> <ide> # locale-specific directories have the form language[_territory][.codeset][@modifier] <ide> LOCALEDIR_RX = /(locale|man)\/([a-z]{2}|C|POSIX)(_[A-Z]{2})?(\.[a-zA-Z\-0-9]+(@.+)?)?/ <del> INFOFILE_RX = %r[/share/info/[^.].*?\.info$] <add> INFOFILE_RX = %r[info/[^.].*?\.info$] <ide> <ide> # if path is a file in a keg then this will return the containing Keg object <ide> def self.for path <ide> def link <ide> # yeah indeed, you have to force anything you need in the main tree into <ide> # these dirs REMEMBER that *NOT* everything needs to be in the main tree <ide> link_dir('etc') {:mkpath} <del> link_dir('bin') {:skip} <del> link_dir('sbin') {:link} <add> link_dir('bin') { |path| :skip if path.directory? } <add> link_dir('sbin') { |path| :skip if path.directory? } <ide> link_dir('include') {:link} <ide> <ide> link_dir('share') do |path| <del> if path.to_s =~ LOCALEDIR_RX <del> :mkpath <del> elsif share_mkpaths.include? path.to_s <del> :mkpath <add> case path.to_s <add> when 'locale/locale.alias' then :skip <add> when INFOFILE_RX then :info if ENV['HOMEBREW_KEEP_INFO'] <add> when LOCALEDIR_RX then :mkpath <add> when *share_mkpaths then :mkpath <add> else :link <ide> end <ide> end <ide> <ide> link_dir('lib') do |path| <ide> case path.to_s <add> when 'charset.alias' then :skip <ide> # pkg-config database gets explicitly created <ide> when 'pkgconfig' then :mkpath <ide> # lib/language folders also get explicitly created <ide> def link_dir foo <ide> dst.extend ObserverPathnameExtension <ide> <ide> if src.file? <del> # Do the symlink. <del> dst.make_relative_symlink src unless File.basename(src) == '.DS_Store' <del> # Install info file entries in the info directory file <del> dst.install_info if dst.to_s =~ INFOFILE_RX and ENV['HOMEBREW_KEEP_INFO'] <add> Find.prune if File.basename(src) == '.DS_Store' <add> <add> case yield src.relative_path_from(root) <add> when :skip <add> Find.prune <add> when :info <add> dst.make_relative_symlink(src) <add> dst.install_info <add> else <add> dst.make_relative_symlink(src) <add> end <ide> elsif src.directory? <ide> # if the dst dir already exists, then great! walk the rest of the tree tho <ide> next if dst.directory? and not dst.symlink?
2
Javascript
Javascript
fix tooltip title in radar charts
ddee91eb9f7f68d64b1634c103ebbc8421b23c7a
<ide><path>src/controllers/controller.radar.js <ide> module.exports = DatasetController.extend({ <ide> return this.chart.scale.id; <ide> }, <ide> <del> /** <del> * @private <del> */ <del> _getIndexScaleId: function() { <del> return this.chart.scale.id; <del> }, <del> <ide> datasetElementType: elements.Line, <ide> <ide> dataElementType: elements.Point, <ide><path>test/specs/controller.radar.tests.js <ide> describe('Chart.controllers.radar', function() { <ide> expect(meta1.data[0]._model.radius).toBe(20); <ide> }); <ide> <del> it('should return same id for index and value scale', function() { <add> it('should return id for value scale', function() { <ide> var chart = window.acquireChart({ <ide> type: 'radar', <ide> data: { <ide> describe('Chart.controllers.radar', function() { <ide> }); <ide> <ide> var controller = chart.getDatasetMeta(0).controller; <del> expect(controller._getIndexScaleId()).toBe('test'); <ide> expect(controller._getValueScaleId()).toBe('test'); <ide> }); <ide> });
2
Ruby
Ruby
prevent duplicate data-disable-with attributes
3d2645ab138c9158ca4224458de74c723d4441cc
<ide><path>actionview/lib/action_view/helpers/form_tag_helper.rb <ide> def radio_button_tag(name, value, checked = false, options = {}) <ide> # # => <input name='commit' type='submit' value='Save' data-disable-with="Save" data-confirm="Are you sure?" /> <ide> # <ide> def submit_tag(value = "Save changes", options = {}) <del> options = options.stringify_keys <add> options = options.deep_stringify_keys <ide> tag_options = { "type" => "submit", "name" => "commit", "value" => value }.update(options) <del> <del> if ActionView::Base.automatically_disable_submit_tag <del> unless tag_options["data-disable-with"] == false || (tag_options["data"] && tag_options["data"][:disable_with] == false) <del> disable_with_text = tag_options["data-disable-with"] <del> disable_with_text ||= tag_options["data"][:disable_with] if tag_options["data"] <del> disable_with_text ||= value.to_s.clone <del> tag_options.deep_merge!("data" => { "disable_with" => disable_with_text }) <del> else <del> tag_options["data"].delete(:disable_with) if tag_options["data"] <del> end <del> tag_options.delete("data-disable-with") <del> end <del> <add> set_default_disable_with value, tag_options <ide> tag :input, tag_options <ide> end <ide> <ide> def form_tag_with_body(html_options, content) <ide> def sanitize_to_id(name) <ide> name.to_s.delete("]").tr("^-a-zA-Z0-9:.", "_") <ide> end <add> <add> def set_default_disable_with(value, tag_options) <add> return unless ActionView::Base.automatically_disable_submit_tag <add> data = tag_options["data"] <add> <add> unless tag_options["data-disable-with"] == false || (data && data["disable_with"] == false) <add> disable_with_text = tag_options["data-disable-with"] <add> disable_with_text ||= data["disable_with"] if data <add> disable_with_text ||= value.to_s.clone <add> tag_options.deep_merge!("data" => { "disable_with" => disable_with_text }) <add> else <add> data.delete("disable_with") if data <add> end <add> <add> tag_options.delete("data-disable-with") <add> end <ide> end <ide> end <ide> end <ide><path>actionview/test/template/form_tag_helper_test.rb <ide> def test_submit_tag_doesnt_have_data_disable_with_twice <ide> ) <ide> end <ide> <add> def test_submit_tag_doesnt_have_data_disable_with_twice_with_hash <add> assert_equal( <add> %(<input type="submit" name="commit" value="Save" data-disable-with="Processing..." />), <add> submit_tag("Save", data: { disable_with: "Processing..." }) <add> ) <add> end <add> <ide> def test_submit_tag_with_symbol_value <ide> assert_dom_equal( <ide> %(<input data-disable-with="Save" name='commit' type="submit" value="Save" />),
2
Javascript
Javascript
reject control characters in http.request()
4f62acd9c5e6f7d65605dda0ebdcf60e9e848311
<ide><path>lib/_http_client.js <ide> function ClientRequest(options, cb) { <ide> if (self.agent && self.agent.protocol) <ide> expectedProtocol = self.agent.protocol; <ide> <del> if (options.path && / /.test(options.path)) { <add> if (options.path && /[\u0000-\u0020]/.test(options.path)) { <ide> // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/ <ide> // with an additional rule for ignoring percentage-escaped characters <ide> // but that's a) hard to capture in a regular expression that performs <del> // well, and b) possibly too restrictive for real-world usage. That's <del> // why it only scans for spaces because those are guaranteed to create <del> // an invalid request. <add> // well, and b) possibly too restrictive for real-world usage. <add> // Restrict the filter to control characters and spaces. <ide> throw new TypeError('Request path contains unescaped characters'); <ide> } else if (protocol !== expectedProtocol) { <ide> throw new Error('Protocol "' + protocol + '" not supported. ' + <ide><path>test/parallel/test-http-client-unescaped-path.js <ide> 'use strict'; <del>var common = require('../common'); <del>var assert = require('assert'); <del>var http = require('http'); <add>const common = require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <ide> <del>assert.throws(function() { <del> // Path with spaces in it should throw. <del> http.get({ path: 'bad path' }, common.fail); <del>}, /contains unescaped characters/); <add>function* bad() { <add> for (let i = 0; i <= 32; i += 1) <add> yield 'bad' + String.fromCharCode(i) + 'path'; <add>} <add> <add>for (const path of bad()) { <add> assert.throws(() => http.get({ path }, common.fail), <add> /contains unescaped characters/); <add>}
2
Text
Text
add changelog entry for #deliver_later
6e6ebeb03cf0ff58c9ef778bfbdd9b0b9891b17b
<ide><path>actionmailer/CHANGELOG.md <add>* Added #deliver_later in addition to #deliver, which will enqueue a job to render and <add> deliver the mail instead of delivering it right at that moment. The job is enqueued <add> using the new Active Job framework in Rails, and will use whatever queue is configured for Rails. <add> <add> *DHH/Abdelkader Boudih/Cristian Bica* <add> <add> <ide> * Make ActionMailer::Previews methods class methods. Previously they were <ide> instance methods and ActionMailer tries to render a message when they <ide> are called.
1
Python
Python
remove documentation for unused kwarg
08e4ad5eea1d07c5c1287bf365f994acdb1645c7
<ide><path>pytorch_transformers/configuration_openai.py <ide> class OpenAIGPTConfig(PretrainedConfig): <ide> <ide> Args: <ide> vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `OpenAIGPTModel` or a configuration json file. <del> n_special: The number of special tokens to learn during fine-tuning ('[SEP]', '[CLF]', ...) <ide> n_positions: Number of positional embeddings. <ide> n_ctx: Size of the causal mask (usually same as n_positions). <ide> n_embd: Dimensionality of the embeddings and hidden states.
1
Javascript
Javascript
add dropbot to showcase
3357bec8c09f5d546a639575ffc27da6098949d4
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://itunes.apple.com/us/app/reactto36/id989009293?mt=8', <ide> author: 'Jonathan Solichin', <ide> }, <add> { <add> name: 'DropBot', <add> icon: 'http://a2.mzstatic.com/us/r30/Purple69/v4/fb/df/73/fbdf73e0-22d2-c936-3115-1defa195acba/icon175x175.png', <add> link: 'https://itunes.apple.com/us/app/dropbot-phone-replacement/id1000855694?mt=8', <add> author: 'Peach Labs', <add> }, <ide> ]; <ide> <ide> var showcase = React.createClass({
1
Javascript
Javascript
bundle all api documentation in a module
ec6a99d7815a53b3f664d543c204fa5232995d0f
<ide><path>src/display/api.js <ide> /* globals requirejs, __non_webpack_require__ */ <ide> /* eslint no-var: error */ <ide> <add>/** <add> * @module pdfjsLib <add> */ <add> <ide> import { <ide> AbortException, assert, createPromiseCapability, getVerbosityLevel, info, <ide> InvalidPDFException, isArrayBuffer, isSameOrigin, MissingPDFException,
1
Javascript
Javascript
catch localstorage security exceptions. fixes #351
90f975c20e2229c47bb403c70c1f46a3bc0f1fd1
<ide><path>src/js/lib.js <ide> vjs.get = function(url, onSuccess, onError){ <ide> /* Local Storage <ide> ================================================================================ */ <ide> vjs.setLocalStorage = function(key, value){ <del> // IE was throwing errors referencing the var anywhere without this <del> var localStorage = window.localStorage || false; <del> if (!localStorage) { return; } <ide> try { <add> // IE was throwing errors referencing the var anywhere without this <add> var localStorage = window.localStorage || false; <add> if (!localStorage) { return; } <ide> localStorage[key] = value; <ide> } catch(e) { <ide> if (e.code == 22 || e.code == 1014) { // Webkit == 22 / Firefox == 1014 <ide> vjs.log('LocalStorage Full (VideoJS)', e); <ide> } else { <del> vjs.log('LocalStorage Error (VideoJS)', e); <add> if (e.code == 18) { <add> vjs.log('LocalStorage not allowed (VideoJS)', e); <add> } else { <add> vjs.log('LocalStorage Error (VideoJS)', e); <add> } <ide> } <ide> } <ide> };
1
PHP
PHP
fix title handling in html builder
c1e2b9685784db268c3829e77317acd4ef6d8127
<ide><path>src/Illuminate/Html/HtmlBuilder.php <ide> public function link($url, $title = null, $attributes = array(), $secure = null) <ide> { <ide> $url = $this->url->to($url, array(), $secure); <ide> <del> $title = $title ?: $url; <add> if (is_null($title) or $title === false) $title = $uri; <ide> <ide> return '<a href="'.$url.'"'.$this->attributes($attributes).'>'.$this->entities($title).'</a>'; <ide> }
1
Javascript
Javascript
adjust ga value for stripe modal
080154b34fd0cd907fb3d7623c2752b13dfa7ffd
<ide><path>client/src/components/Donation/DonateFormChildViewForHOC.js <ide> class DonateFormChildViewForHOC extends Component { <ide> // change the donation modal button label to close <ide> // or display the close button for the cert donation section <ide> if (this.props.handleProcessing) { <del> this.props.handleProcessing( <del> this.state.donationDuration, <del> Math.round(amount / 100) <del> ); <add> this.props.handleProcessing(duration, amount); <ide> } <ide> <ide> return this.props.postChargeStripe({
1
Text
Text
add instruction of installation docker for centos
56e8e374876dfcf9b561fe7fb2c4877632772573
<ide><path>guide/english/docker/index.md <ide> One of Docker's biggest advantages is that it can be used by a team using differ <ide> <ide> * RedHat: `yum install docker-ce` <ide> <del>* Windows / macOS: [Download](https://www.docker.com/get-started) <add>* Windows: [Download](https://store.docker.com/editions/community/docker-ce-desktop-windows) <ide> <del>* Linux: <add>* MacOS: [Download](https://store.docker.com/editions/community/docker-ce-desktop-mac) <add> <add>* Linux: `sudo apt-get install docker-ce` <add> <add>* CentOS: [Instruction](https://docs.docker.com/install/linux/docker-ce/centos/#uninstall-old-versions) <ide> <ide> ``` <ide> curl -fsSL https://get.docker.com -o get-docker.sh
1
Ruby
Ruby
add mandrill support
3984460424b678d844009319598e2b41c350ca3c
<ide><path>app/controllers/action_mailbox/ingresses/mandrill/inbound_emails_controller.rb <add>class ActionMailbox::Ingresses::Mandrill::InboundEmailsController < ActionMailbox::BaseController <add> before_action :ensure_authenticated <add> <add> def create <add> raw_emails.each { |raw_email| ActionMailbox::InboundEmail.create_and_extract_message_id! raw_email } <add> head :ok <add> rescue JSON::ParserError => error <add> log.error error.message <add> head :unprocessable_entity <add> end <add> <add> private <add> def raw_emails <add> events.lazy. <add> select { |event| event["event"] == "inbound" }. <add> collect { |event| event.dig("msg", "raw_msg") }. <add> collect { |message| StringIO.new message } <add> end <add> <add> def events <add> JSON.parse params.require(:mandrill_events) <add> end <add> <add> <add> def ensure_authenticated <add> head :unauthorized unless authenticated? <add> end <add> <add> def authenticated? <add> Authenticator.new(request).authenticated? <add> end <add> <add> class Authenticator <add> cattr_accessor :key <add> <add> attr_reader :request <add> <add> def initialize(request) <add> @request = request <add> end <add> <add> def authenticated? <add> ActiveSupport::SecurityUtils.secure_compare given_signature, expected_signature <add> end <add> <add> private <add> def given_signature <add> request.headers["X-Mandrill-Signature"] <add> end <add> <add> def expected_signature <add> Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, key, message)).strip <add> end <add> <add> def message <add> [ request.original_url, request.POST.sort ].flatten.join <add> end <add> end <add>end <ide><path>config/routes.rb <ide> post "/amazon/inbound_emails" => "action_mailbox/ingresses/amazon/inbound_emails#create", as: :rails_amazon_inbound_emails <ide> post "/postfix/inbound_emails" => "action_mailbox/ingresses/postfix/inbound_emails#create", as: :rails_postfix_inbound_emails <ide> post "/sendgrid/inbound_emails" => "action_mailbox/ingresses/sendgrid/inbound_emails#create", as: :rails_sendgrid_inbound_emails <add> post "/mandrill/inbound_emails" => "action_mailbox/ingresses/mandrill/inbound_emails#create", as: :rails_mandrill_inbound_emails <ide> <ide> # Mailgun requires that the webhook's URL end in 'mime' for it to receive the raw contents of emails. <ide> post "/mailgun/inbound_emails/mime" => "action_mailbox/ingresses/mailgun/inbound_emails#create", as: :rails_mailgun_inbound_emails <ide><path>test/controllers/ingresses/mandrill/inbound_emails_controller_test.rb <add>require "test_helper" <add> <add>ActionMailbox::Ingresses::Mandrill::InboundEmailsController::Authenticator.key = "1l9Qf7lutEf7h73VXfBwhw" <add> <add>class ActionMailbox::Ingresses::Mandrill::InboundEmailsControllerTest < ActionDispatch::IntegrationTest <add> setup do <add> @events = JSON.generate([{ event: "inbound", msg: { raw_msg: file_fixture("../files/welcome.eml").read } }]) <add> end <add> <add> test "receiving an inbound email from Mandrill" do <add> assert_difference -> { ActionMailbox::InboundEmail.count }, +1 do <add> post rails_mandrill_inbound_emails_url, <add> headers: { "X-Mandrill-Signature" => "gldscd2tAb/G+DmpiLcwukkLrC4=" }, params: { mandrill_events: @events } <add> end <add> <add> assert_response :ok <add> <add> inbound_email = ActionMailbox::InboundEmail.last <add> assert_equal file_fixture("../files/welcome.eml").read, inbound_email.raw_email.download <add> assert_equal "0CB459E0-0336-41DA-BC88-E6E28C697DDB@37signals.com", inbound_email.message_id <add> end <add> <add> test "rejecting a forged inbound email from Mandrill" do <add> assert_no_difference -> { ActionMailbox::InboundEmail.count } do <add> post rails_mandrill_inbound_emails_url, <add> headers: { "X-Mandrill-Signature" => "forged" }, params: { mandrill_events: @events } <add> end <add> <add> assert_response :unauthorized <add> end <add>end
3
Text
Text
update docs to use lists instead of tuples
f0dbf0a264677f2a53faab402ff49f442fc4383a
<ide><path>README.md <ide> Install using `pip`... <ide> <ide> Add `'rest_framework'` to your `INSTALLED_APPS` setting. <ide> <del> INSTALLED_APPS = ( <add> INSTALLED_APPS = [ <ide> ... <ide> 'rest_framework', <del> ) <add> ] <ide> <ide> # Example <ide> <ide> from rest_framework import serializers, viewsets, routers <ide> class UserSerializer(serializers.HyperlinkedModelSerializer): <ide> class Meta: <ide> model = User <del> fields = ('url', 'username', 'email', 'is_staff') <add> fields = ['url', 'username', 'email', 'is_staff'] <ide> <ide> <ide> # ViewSets define the view behavior. <ide> We'd also like to configure a couple of settings for our API. <ide> Add the following to your `settings.py` module: <ide> <ide> ```python <del>INSTALLED_APPS = ( <add>INSTALLED_APPS = [ <ide> ... # Make sure to include the default installed apps here. <ide> 'rest_framework', <del>) <add>] <ide> <ide> REST_FRAMEWORK = { <ide> # Use Django's standard `django.contrib.auth` permissions, <ide><path>docs/api-guide/authentication.md <ide> The value of `request.user` and `request.auth` for unauthenticated requests can <ide> The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_AUTHENTICATION_CLASSES': ( <add> 'DEFAULT_AUTHENTICATION_CLASSES': [ <ide> 'rest_framework.authentication.BasicAuthentication', <ide> 'rest_framework.authentication.SessionAuthentication', <del> ) <add> ] <ide> } <ide> <ide> You can also set the authentication scheme on a per-view or per-viewset basis, <ide> using the `APIView` class-based views. <ide> from rest_framework.views import APIView <ide> <ide> class ExampleView(APIView): <del> authentication_classes = (SessionAuthentication, BasicAuthentication) <del> permission_classes = (IsAuthenticated,) <add> authentication_classes = [SessionAuthentication, BasicAuthentication] <add> permission_classes = [IsAuthenticated] <ide> <ide> def get(self, request, format=None): <ide> content = { <ide> using the `APIView` class-based views. <ide> Or, if you're using the `@api_view` decorator with function based views. <ide> <ide> @api_view(['GET']) <del> @authentication_classes((SessionAuthentication, BasicAuthentication)) <del> @permission_classes((IsAuthenticated,)) <add> @authentication_classes([SessionAuthentication, BasicAuthentication]) <add> @permission_classes([IsAuthenticated]) <ide> def example_view(request, format=None): <ide> content = { <ide> 'user': unicode(request.user), # `django.contrib.auth.User` instance. <ide> This authentication scheme uses a simple token-based HTTP Authentication scheme. <ide> <ide> To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting: <ide> <del> INSTALLED_APPS = ( <add> INSTALLED_APPS = [ <ide> ... <ide> 'rest_framework.authtoken' <del> ) <add> ] <ide> <ide> --- <ide> <ide> It is also possible to create Tokens manually through admin interface. In case y <ide> <ide> from rest_framework.authtoken.admin import TokenAdmin <ide> <del> TokenAdmin.raw_id_fields = ('user',) <add> TokenAdmin.raw_id_fields = ['user'] <ide> <ide> <ide> #### Using Django manage.py command <ide> Install using `pip`. <ide> <ide> Add the package to your `INSTALLED_APPS` and modify your REST framework settings. <ide> <del> INSTALLED_APPS = ( <add> INSTALLED_APPS = [ <ide> ... <ide> 'oauth2_provider', <del> ) <add> ] <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_AUTHENTICATION_CLASSES': ( <add> 'DEFAULT_AUTHENTICATION_CLASSES': [ <ide> 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', <del> ) <add> ] <ide> } <ide> <ide> For more details see the [Django REST framework - Getting started][django-oauth-toolkit-getting-started] documentation. <ide><path>docs/api-guide/fields.md <ide> For example, if `has_expired` was a property on the `Account` model, then the fo <ide> class AccountSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Account <del> fields = ('id', 'account_name', 'has_expired') <add> fields = ['id', 'account_name', 'has_expired'] <ide> <ide> ## HiddenField <ide> <ide><path>docs/api-guide/filtering.md <ide> Generic filters can also present themselves as HTML controls in the browsable AP <ide> The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',) <add> 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] <ide> } <ide> <ide> You can also set the filter backends on a per-view, or per-viewset basis, <ide> using the `GenericAPIView` class-based views. <ide> class UserListView(generics.ListAPIView): <ide> queryset = User.objects.all() <ide> serializer_class = UserSerializer <del> filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) <add> filter_backends = [django_filters.rest_framework.DjangoFilterBackend] <ide> <ide> ## Filtering and object lookups <ide> <ide> To use `DjangoFilterBackend`, first install `django-filter`. Then add `django_fi <ide> You should now either add the filter backend to your settings: <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',) <add> 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] <ide> } <ide> <ide> Or add the filter backend to an individual View or ViewSet. <ide> Or add the filter backend to an individual View or ViewSet. <ide> <ide> class UserListView(generics.ListAPIView): <ide> ... <del> filter_backends = (DjangoFilterBackend,) <add> filter_backends = [DjangoFilterBackend] <ide> <ide> If all you need is simple equality-based filtering, you can set a `filterset_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against. <ide> <ide> class ProductList(generics.ListAPIView): <ide> queryset = Product.objects.all() <ide> serializer_class = ProductSerializer <del> filter_backends = (DjangoFilterBackend,) <del> filterset_fields = ('category', 'in_stock') <add> filter_backends = [DjangoFilterBackend] <add> filterset_fields = ['category', 'in_stock'] <ide> <ide> This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as: <ide> <ide> The `SearchFilter` class will only be applied if the view has a `search_fields` <ide> class UserListView(generics.ListAPIView): <ide> queryset = User.objects.all() <ide> serializer_class = UserSerializer <del> filter_backends = (filters.SearchFilter,) <del> search_fields = ('username', 'email') <add> filter_backends = [filters.SearchFilter] <add> search_fields = ['username', 'email'] <ide> <ide> This will allow the client to filter the items in the list by making queries such as: <ide> <ide> http://example.com/api/users?search=russell <ide> <ide> You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: <ide> <del> search_fields = ('username', 'email', 'profile__profession') <add> search_fields = ['username', 'email', 'profile__profession'] <ide> <ide> By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. <ide> <ide> The search behavior may be restricted by prepending various characters to the `s <ide> <ide> For example: <ide> <del> search_fields = ('=username', '=email') <add> search_fields = ['=username', '=email'] <ide> <ide> By default, the search parameter is named `'search`', but this may be overridden with the `SEARCH_PARAM` setting. <ide> <ide> To dynamically change search fields based on request content, it's possible to s <ide> class CustomSearchFilter(filters.SearchFilter): <ide> def get_search_fields(self, view, request): <ide> if request.query_params.get('title_only'): <del> return ('title',) <add> return ['title'] <ide> return super(CustomSearchFilter, self).get_search_fields(view, request) <ide> <ide> For more details, see the [Django documentation][search-django-admin]. <ide> It's recommended that you explicitly specify which fields the API should allowin <ide> class UserListView(generics.ListAPIView): <ide> queryset = User.objects.all() <ide> serializer_class = UserSerializer <del> filter_backends = (filters.OrderingFilter,) <del> ordering_fields = ('username', 'email') <add> filter_backends = [filters.OrderingFilter] <add> ordering_fields = ['username', 'email'] <ide> <ide> This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data. <ide> <ide> If you are confident that the queryset being used by the view doesn't contain an <ide> class BookingsListView(generics.ListAPIView): <ide> queryset = Booking.objects.all() <ide> serializer_class = BookingSerializer <del> filter_backends = (filters.OrderingFilter,) <add> filter_backends = [filters.OrderingFilter] <ide> ordering_fields = '__all__' <ide> <ide> ### Specifying a default ordering <ide> Typically you'd instead control this by setting `order_by` on the initial querys <ide> class UserListView(generics.ListAPIView): <ide> queryset = User.objects.all() <ide> serializer_class = UserSerializer <del> filter_backends = (filters.OrderingFilter,) <del> ordering_fields = ('username', 'email') <del> ordering = ('username',) <add> filter_backends = [filters.OrderingFilter] <add> ordering_fields = ['username', 'email'] <add> ordering = ['username'] <ide> <ide> The `ordering` attribute may be either a string or a list/tuple of strings. <ide> <ide><path>docs/api-guide/format-suffixes.md <ide> Example: <ide> <ide> When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example: <ide> <del> @api_view(('GET', 'POST')) <add> @api_view(['GET', 'POST']) <ide> def comment_list(request, format=None): <ide> # do stuff... <ide> <ide><path>docs/api-guide/generic-views.md <ide> Typically when using the generic views, you'll override the view, and set severa <ide> class UserList(generics.ListCreateAPIView): <ide> queryset = User.objects.all() <ide> serializer_class = UserSerializer <del> permission_classes = (IsAdminUser,) <add> permission_classes = [IsAdminUser] <ide> <ide> For more complex cases you might also want to override various methods on the view class. For example. <ide> <ide> class UserList(generics.ListCreateAPIView): <ide> queryset = User.objects.all() <ide> serializer_class = UserSerializer <del> permission_classes = (IsAdminUser,) <add> permission_classes = [IsAdminUser] <ide> <ide> def list(self, request): <ide> # Note the use of `get_queryset()` instead of `self.queryset` <ide> Given a queryset, filter it with whichever filter backends are in use, returning <ide> For example: <ide> <ide> def filter_queryset(self, queryset): <del> filter_backends = (CategoryFilter,) <add> filter_backends = [CategoryFilter] <ide> <ide> if 'geo_route' in self.request.query_params: <del> filter_backends = (GeoRouteFilter, CategoryFilter) <add> filter_backends = [GeoRouteFilter, CategoryFilter] <ide> elif 'geo_point' in self.request.query_params: <del> filter_backends = (GeoPointFilter, CategoryFilter) <add> filter_backends = [GeoPointFilter, CategoryFilter] <ide> <ide> for backend in list(filter_backends): <ide> queryset = backend().filter_queryset(self.request, queryset, view=self) <ide> You can then simply apply this mixin to a view or viewset anytime you need to ap <ide> class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView): <ide> queryset = User.objects.all() <ide> serializer_class = UserSerializer <del> lookup_fields = ('account', 'username') <add> lookup_fields = ['account', 'username'] <ide> <ide> Using custom mixins is a good option if you have custom behavior that needs to be used. <ide> <ide><path>docs/api-guide/parsers.md <ide> As an example, if you are sending `json` encoded data using jQuery with the [.aj <ide> The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow only requests with `JSON` content, instead of the default of JSON or form data. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_PARSER_CLASSES': ( <add> 'DEFAULT_PARSER_CLASSES': [ <ide> 'rest_framework.parsers.JSONParser', <del> ) <add> ] <ide> } <ide> <ide> You can also set the parsers used for an individual view, or viewset, <ide> using the `APIView` class-based views. <ide> """ <ide> A view that can accept POST requests with JSON content. <ide> """ <del> parser_classes = (JSONParser,) <add> parser_classes = [JSONParser] <ide> <ide> def post(self, request, format=None): <ide> return Response({'received data': request.data}) <ide> Or, if you're using the `@api_view` decorator with function based views. <ide> from rest_framework.parsers import JSONParser <ide> <ide> @api_view(['POST']) <del> @parser_classes((JSONParser,)) <add> @parser_classes([JSONParser]) <ide> def example_view(request, format=None): <ide> """ <ide> A view that can accept POST requests with JSON content. <ide> If it is called without a `filename` URL keyword argument, then the client must <ide> <ide> # views.py <ide> class FileUploadView(views.APIView): <del> parser_classes = (FileUploadParser,) <add> parser_classes = [FileUploadParser] <ide> <ide> def put(self, request, filename, format=None): <ide> file_obj = request.data['file'] <ide> Install using pip. <ide> Modify your REST framework settings. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_PARSER_CLASSES': ( <add> 'DEFAULT_PARSER_CLASSES': [ <ide> 'rest_framework_yaml.parsers.YAMLParser', <del> ), <del> 'DEFAULT_RENDERER_CLASSES': ( <add> ], <add> 'DEFAULT_RENDERER_CLASSES': [ <ide> 'rest_framework_yaml.renderers.YAMLRenderer', <del> ), <add> ], <ide> } <ide> <ide> ## XML <ide> Install using pip. <ide> Modify your REST framework settings. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_PARSER_CLASSES': ( <add> 'DEFAULT_PARSER_CLASSES': [ <ide> 'rest_framework_xml.parsers.XMLParser', <del> ), <del> 'DEFAULT_RENDERER_CLASSES': ( <add> ], <add> 'DEFAULT_RENDERER_CLASSES': [ <ide> 'rest_framework_xml.renderers.XMLRenderer', <del> ), <add> ], <ide> } <ide> <ide> ## MessagePack <ide><path>docs/api-guide/permissions.md <ide> Often when you're using object level permissions you'll also want to [filter the <ide> The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_PERMISSION_CLASSES': ( <add> 'DEFAULT_PERMISSION_CLASSES': [ <ide> 'rest_framework.permissions.IsAuthenticated', <del> ) <add> ] <ide> } <ide> <ide> If not specified, this setting defaults to allowing unrestricted access: <ide> <del> 'DEFAULT_PERMISSION_CLASSES': ( <add> 'DEFAULT_PERMISSION_CLASSES': [ <ide> 'rest_framework.permissions.AllowAny', <del> ) <add> ] <ide> <ide> You can also set the authentication policy on a per-view, or per-viewset basis, <ide> using the `APIView` class-based views. <ide> using the `APIView` class-based views. <ide> from rest_framework.views import APIView <ide> <ide> class ExampleView(APIView): <del> permission_classes = (IsAuthenticated,) <add> permission_classes = [IsAuthenticated] <ide> <ide> def get(self, request, format=None): <ide> content = { <ide> Or, if you're using the `@api_view` decorator with function based views. <ide> from rest_framework.response import Response <ide> <ide> @api_view(['GET']) <del> @permission_classes((IsAuthenticated, )) <add> @permission_classes([IsAuthenticated]) <ide> def example_view(request, format=None): <ide> content = { <ide> 'status': 'request was permitted' <ide> Provided they inherit from `rest_framework.permissions.BasePermission`, permissi <ide> return request.method in SAFE_METHODS <ide> <ide> class ExampleView(APIView): <del> permission_classes = (IsAuthenticated|ReadOnly,) <add> permission_classes = [IsAuthenticated|ReadOnly] <ide> <ide> def get(self, request, format=None): <ide> content = { <ide><path>docs/api-guide/relations.md <ide> In order to explain the various types of relational fields, we'll use a couple o <ide> duration = models.IntegerField() <ide> <ide> class Meta: <del> unique_together = ('album', 'order') <add> unique_together = ['album', 'order'] <ide> ordering = ['order'] <ide> <ide> def __str__(self): <ide> For example, the following serializer. <ide> <ide> class Meta: <ide> model = Album <del> fields = ('album_name', 'artist', 'tracks') <add> fields = ['album_name', 'artist', 'tracks'] <ide> <ide> Would serialize to the following representation. <ide> <ide> For example, the following serializer: <ide> <ide> class Meta: <ide> model = Album <del> fields = ('album_name', 'artist', 'tracks') <add> fields = ['album_name', 'artist', 'tracks'] <ide> <ide> Would serialize to a representation like this: <ide> <ide> For example, the following serializer: <ide> <ide> class Meta: <ide> model = Album <del> fields = ('album_name', 'artist', 'tracks') <add> fields = ['album_name', 'artist', 'tracks'] <ide> <ide> Would serialize to a representation like this: <ide> <ide> For example, the following serializer: <ide> <ide> class Meta: <ide> model = Album <del> fields = ('album_name', 'artist', 'tracks') <add> fields = ['album_name', 'artist', 'tracks'] <ide> <ide> Would serialize to a representation like this: <ide> <ide> This field can be applied as an identity relationship, such as the `'url'` field <ide> <ide> class Meta: <ide> model = Album <del> fields = ('album_name', 'artist', 'track_listing') <add> fields = ['album_name', 'artist', 'track_listing'] <ide> <ide> Would serialize to a representation like this: <ide> <ide> For example, the following serializer: <ide> class TrackSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Track <del> fields = ('order', 'title', 'duration') <add> fields = ['order', 'title', 'duration'] <ide> <ide> class AlbumSerializer(serializers.ModelSerializer): <ide> tracks = TrackSerializer(many=True, read_only=True) <ide> <ide> class Meta: <ide> model = Album <del> fields = ('album_name', 'artist', 'tracks') <add> fields = ['album_name', 'artist', 'tracks'] <ide> <ide> Would serialize to a nested representation like this: <ide> <ide> By default nested serializers are read-only. If you want to support write-operat <ide> class TrackSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Track <del> fields = ('order', 'title', 'duration') <add> fields = ['order', 'title', 'duration'] <ide> <ide> class AlbumSerializer(serializers.ModelSerializer): <ide> tracks = TrackSerializer(many=True) <ide> <ide> class Meta: <ide> model = Album <del> fields = ('album_name', 'artist', 'tracks') <add> fields = ['album_name', 'artist', 'tracks'] <ide> <ide> def create(self, validated_data): <ide> tracks_data = validated_data.pop('tracks') <ide> For example, we could define a relational field to serialize a track to a custom <ide> <ide> class Meta: <ide> model = Album <del> fields = ('album_name', 'artist', 'tracks') <add> fields = ['album_name', 'artist', 'tracks'] <ide> <ide> This custom field would then serialize to the following representation. <ide> <ide> Note that reverse relationships are not automatically included by the `ModelSeri <ide> <ide> class AlbumSerializer(serializers.ModelSerializer): <ide> class Meta: <del> fields = ('tracks', ...) <add> fields = ['tracks', ...] <ide> <ide> You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example: <ide> <ide> If you have not set a related name for the reverse relationship, you'll need to <ide> <ide> class AlbumSerializer(serializers.ModelSerializer): <ide> class Meta: <del> fields = ('track_set', ...) <add> fields = ['track_set', ...] <ide> <ide> See the Django documentation on [reverse relationships][reverse-relationships] for more details. <ide> <ide><path>docs/api-guide/renderers.md <ide> For more information see the documentation on [content negotiation][conneg]. <ide> The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `JSON` as the main media type and also include the self describing API. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_RENDERER_CLASSES': ( <add> 'DEFAULT_RENDERER_CLASSES': [ <ide> 'rest_framework.renderers.JSONRenderer', <ide> 'rest_framework.renderers.BrowsableAPIRenderer', <del> ) <add> ] <ide> } <ide> <ide> You can also set the renderers used for an individual view, or viewset, <ide> using the `APIView` class-based views. <ide> """ <ide> A view that returns the count of active users in JSON. <ide> """ <del> renderer_classes = (JSONRenderer, ) <add> renderer_classes = [JSONRenderer] <ide> <ide> def get(self, request, format=None): <ide> user_count = User.objects.filter(active=True).count() <ide> using the `APIView` class-based views. <ide> Or, if you're using the `@api_view` decorator with function based views. <ide> <ide> @api_view(['GET']) <del> @renderer_classes((JSONRenderer,)) <add> @renderer_classes([JSONRenderer]) <ide> def user_count_view(request, format=None): <ide> """ <ide> A view that returns the count of active users in JSON. <ide> An example of a view that uses `TemplateHTMLRenderer`: <ide> A view that returns a templated HTML representation of a given user. <ide> """ <ide> queryset = User.objects.all() <del> renderer_classes = (TemplateHTMLRenderer,) <add> renderer_classes = [TemplateHTMLRenderer] <ide> <ide> def get(self, request, *args, **kwargs): <ide> self.object = self.get_object() <ide> A simple renderer that simply returns pre-rendered HTML. Unlike other renderers <ide> <ide> An example of a view that uses `StaticHTMLRenderer`: <ide> <del> @api_view(('GET',)) <del> @renderer_classes((StaticHTMLRenderer,)) <add> @api_view(['GET']) <add> @renderer_classes([StaticHTMLRenderer]) <ide> def simple_html_view(request): <ide> data = '<html><body><h1>Hello, world</h1></body></html>' <ide> return Response(data) <ide> In some cases you might want your view to use different serialization styles dep <ide> <ide> For example: <ide> <del> @api_view(('GET',)) <del> @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) <add> @api_view(['GET']) <add> @renderer_classes([TemplateHTMLRenderer, JSONRenderer]) <ide> def list_users(request): <ide> """ <ide> A view that can return JSON or HTML representations <ide> Install using pip. <ide> Modify your REST framework settings. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_PARSER_CLASSES': ( <add> 'DEFAULT_PARSER_CLASSES': [ <ide> 'rest_framework_yaml.parsers.YAMLParser', <del> ), <del> 'DEFAULT_RENDERER_CLASSES': ( <add> ], <add> 'DEFAULT_RENDERER_CLASSES': [ <ide> 'rest_framework_yaml.renderers.YAMLRenderer', <del> ), <add> ], <ide> } <ide> <ide> ## XML <ide> Install using pip. <ide> Modify your REST framework settings. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_PARSER_CLASSES': ( <add> 'DEFAULT_PARSER_CLASSES': [ <ide> 'rest_framework_xml.parsers.XMLParser', <del> ), <del> 'DEFAULT_RENDERER_CLASSES': ( <add> ], <add> 'DEFAULT_RENDERER_CLASSES': [ <ide> 'rest_framework_xml.renderers.XMLRenderer', <del> ), <add> ], <ide> } <ide> <ide> ## JSONP <ide> Install using pip. <ide> Modify your REST framework settings. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_RENDERER_CLASSES': ( <add> 'DEFAULT_RENDERER_CLASSES': [ <ide> 'rest_framework_jsonp.renderers.JSONPRenderer', <del> ), <add> ], <ide> } <ide> <ide> ## MessagePack <ide> Modify your REST framework settings. <ide> REST_FRAMEWORK = { <ide> ... <ide> <del> 'DEFAULT_RENDERER_CLASSES': ( <add> 'DEFAULT_RENDERER_CLASSES': [ <ide> 'rest_framework.renderers.JSONRenderer', <ide> 'rest_framework.renderers.BrowsableAPIRenderer', <ide> 'drf_renderer_xlsx.renderers.XLSXRenderer', <del> ), <add> ], <ide> } <ide> <ide> To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example: <ide> To avoid having a file streamed without a filename (which the browser will often <ide> class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet): <ide> queryset = MyExampleModel.objects.all() <ide> serializer_class = MyExampleSerializer <del> renderer_classes = (XLSXRenderer,) <add> renderer_classes = [XLSXRenderer] <ide> filename = 'my_export.xlsx' <ide> <ide> ## CSV <ide><path>docs/api-guide/serializers.md <ide> The following example demonstrates how you might handle creating a user with a n <ide> <ide> class Meta: <ide> model = User <del> fields = ('username', 'email', 'profile') <add> fields = ['username', 'email', 'profile'] <ide> <ide> def create(self, validated_data): <ide> profile_data = validated_data.pop('profile') <ide> Declaring a `ModelSerializer` looks like this: <ide> class AccountSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Account <del> fields = ('id', 'account_name', 'users', 'created') <add> fields = ['id', 'account_name', 'users', 'created'] <ide> <ide> By default, all the model fields on the class will be mapped to a corresponding serializer fields. <ide> <ide> For example: <ide> class AccountSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Account <del> fields = ('id', 'account_name', 'users', 'created') <add> fields = ['id', 'account_name', 'users', 'created'] <ide> <ide> You can also set the `fields` attribute to the special value `'__all__'` to indicate that all fields in the model should be used. <ide> <ide> For example: <ide> class AccountSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Account <del> exclude = ('users',) <add> exclude = ['users'] <ide> <ide> In the example above, if the `Account` model had 3 fields `account_name`, `users`, and `created`, this will result in the fields `account_name` and `created` to be serialized. <ide> <ide> The default `ModelSerializer` uses primary keys for relationships, but you can a <ide> class AccountSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Account <del> fields = ('id', 'account_name', 'users', 'created') <add> fields = ['id', 'account_name', 'users', 'created'] <ide> depth = 1 <ide> <ide> The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. <ide> This option should be a list or tuple of field names, and is declared as follows <ide> class AccountSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Account <del> fields = ('id', 'account_name', 'users', 'created') <del> read_only_fields = ('account_name',) <add> fields = ['id', 'account_name', 'users', 'created'] <add> read_only_fields = ['account_name'] <ide> <ide> Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option. <ide> <ide> This option is a dictionary, mapping field names to a dictionary of keyword argu <ide> class CreateUserSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = User <del> fields = ('email', 'username', 'password') <add> fields = ['email', 'username', 'password'] <ide> extra_kwargs = {'password': {'write_only': True}} <ide> <ide> def create(self, validated_data): <ide> You can explicitly include the primary key by adding it to the `fields` option, <ide> class AccountSerializer(serializers.HyperlinkedModelSerializer): <ide> class Meta: <ide> model = Account <del> fields = ('url', 'id', 'account_name', 'users', 'created') <add> fields = ['url', 'id', 'account_name', 'users', 'created'] <ide> <ide> ## Absolute and relative URLs <ide> <ide> You can override a URL field view name and lookup field by using either, or both <ide> class AccountSerializer(serializers.HyperlinkedModelSerializer): <ide> class Meta: <ide> model = Account <del> fields = ('account_url', 'account_name', 'users', 'created') <add> fields = ['account_url', 'account_name', 'users', 'created'] <ide> extra_kwargs = { <ide> 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}, <ide> 'users': {'lookup_field': 'username'} <ide> Alternatively you can set the fields on the serializer explicitly. For example: <ide> <ide> class Meta: <ide> model = Account <del> fields = ('url', 'account_name', 'users', 'created') <add> fields = ['url', 'account_name', 'users', 'created'] <ide> <ide> --- <ide> <ide> This would then allow you to do the following: <ide> >>> class UserSerializer(DynamicFieldsModelSerializer): <ide> >>> class Meta: <ide> >>> model = User <del> >>> fields = ('id', 'username', 'email') <add> >>> fields = ['id', 'username', 'email'] <ide> >>> <ide> >>> print(UserSerializer(user)) <ide> {'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'} <ide><path>docs/api-guide/settings.md <ide> Configuration for REST framework is all namespaced inside a single Django settin <ide> For example your project's `settings.py` file might include something like this: <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_RENDERER_CLASSES': ( <add> 'DEFAULT_RENDERER_CLASSES': [ <ide> 'rest_framework.renderers.JSONRenderer', <del> ), <del> 'DEFAULT_PARSER_CLASSES': ( <add> ], <add> 'DEFAULT_PARSER_CLASSES': [ <ide> 'rest_framework.parsers.JSONParser', <del> ) <add> ] <ide> } <ide> <ide> ## Accessing settings <ide><path>docs/api-guide/testing.md <ide> For example, to add support for using `format='html'` in test requests, you migh <ide> <ide> REST_FRAMEWORK = { <ide> ... <del> 'TEST_REQUEST_RENDERER_CLASSES': ( <add> 'TEST_REQUEST_RENDERER_CLASSES': [ <ide> 'rest_framework.renderers.MultiPartRenderer', <ide> 'rest_framework.renderers.JSONRenderer', <ide> 'rest_framework.renderers.TemplateHTMLRenderer' <del> ) <add> ] <ide> } <ide> <ide> [cite]: https://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper <ide><path>docs/api-guide/throttling.md <ide> If any throttle check fails an `exceptions.Throttled` exception will be raised, <ide> The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_CLASSES` and `DEFAULT_THROTTLE_RATES` settings. For example. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_THROTTLE_CLASSES': ( <add> 'DEFAULT_THROTTLE_CLASSES': [ <ide> 'rest_framework.throttling.AnonRateThrottle', <ide> 'rest_framework.throttling.UserRateThrottle' <del> ), <add> ], <ide> 'DEFAULT_THROTTLE_RATES': { <ide> 'anon': '100/day', <ide> 'user': '1000/day' <ide> using the `APIView` class-based views. <ide> from rest_framework.views import APIView <ide> <ide> class ExampleView(APIView): <del> throttle_classes = (UserRateThrottle,) <add> throttle_classes = [UserRateThrottle] <ide> <ide> def get(self, request, format=None): <ide> content = { <ide> For example, multiple user throttle rates could be implemented by using the foll <ide> ...and the following settings. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_THROTTLE_CLASSES': ( <add> 'DEFAULT_THROTTLE_CLASSES': [ <ide> 'example.throttles.BurstRateThrottle', <ide> 'example.throttles.SustainedRateThrottle' <del> ), <add> ], <ide> 'DEFAULT_THROTTLE_RATES': { <ide> 'burst': '60/min', <ide> 'sustained': '1000/day' <ide> For example, given the following views... <ide> ...and the following settings. <ide> <ide> REST_FRAMEWORK = { <del> 'DEFAULT_THROTTLE_CLASSES': ( <add> 'DEFAULT_THROTTLE_CLASSES': [ <ide> 'rest_framework.throttling.ScopedRateThrottle', <del> ), <add> ], <ide> 'DEFAULT_THROTTLE_RATES': { <ide> 'contacts': '1000/day', <ide> 'uploads': '20/day' <ide><path>docs/api-guide/validators.md <ide> The validator should be applied to *serializer classes*, like so: <ide> validators = [ <ide> UniqueTogetherValidator( <ide> queryset=ToDoItem.objects.all(), <del> fields=('list', 'position') <add> fields=['list', 'position'] <ide> ) <ide> ] <ide> <ide> For example: <ide> # Apply custom validation either here, or in the view. <ide> <ide> class Meta: <del> fields = ('client', 'date', 'amount') <add> fields = ['client', 'date', 'amount'] <ide> extra_kwargs = {'client': {'required': False}} <ide> validators = [] # Remove a default "unique together" constraint. <ide> <ide><path>docs/api-guide/views.md <ide> For example: <ide> * Requires token authentication. <ide> * Only admin users are able to access this view. <ide> """ <del> authentication_classes = (authentication.TokenAuthentication,) <del> permission_classes = (permissions.IsAdminUser,) <add> authentication_classes = [authentication.TokenAuthentication] <add> permission_classes = [permissions.IsAdminUser] <ide> <ide> def get(self, request, format=None): <ide> """ <ide><path>docs/community/3.0-announcement.md <ide> If you try to use a writable nested serializer without writing a custom `create( <ide> >>> class ProfileSerializer(serializers.ModelSerializer): <ide> >>> class Meta: <ide> >>> model = Profile <del> >>> fields = ('address', 'phone') <add> >>> fields = ['address', 'phone'] <ide> >>> <ide> >>> class UserSerializer(serializers.ModelSerializer): <ide> >>> profile = ProfileSerializer() <ide> >>> class Meta: <ide> >>> model = User <del> >>> fields = ('username', 'email', 'profile') <add> >>> fields = ['username', 'email', 'profile'] <ide> >>> <ide> >>> data = { <ide> >>> 'username': 'lizzy', <ide> To use writable nested serialization you'll want to declare a nested field on th <ide> <ide> class Meta: <ide> model = User <del> fields = ('username', 'email', 'profile') <add> fields = ['username', 'email', 'profile'] <ide> <ide> def create(self, validated_data): <ide> profile_data = validated_data.pop('profile') <ide> The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDe <ide> class MySerializer(serializer.ModelSerializer): <ide> class Meta: <ide> model = MyModel <del> fields = ('id', 'email', 'notes', 'is_admin') <add> fields = ['id', 'email', 'notes', 'is_admin'] <ide> extra_kwargs = { <ide> 'is_admin': {'write_only': True} <ide> } <ide> Alternatively, specify the field explicitly on the serializer class: <ide> <ide> class Meta: <ide> model = MyModel <del> fields = ('id', 'email', 'notes', 'is_admin') <add> fields = ['id', 'email', 'notes', 'is_admin'] <ide> <ide> The `read_only_fields` option remains as a convenient shortcut for the more common case. <ide> <ide> The `view_name` and `lookup_field` options have been moved to `PendingDeprecatio <ide> class MySerializer(serializer.HyperlinkedModelSerializer): <ide> class Meta: <ide> model = MyModel <del> fields = ('url', 'email', 'notes', 'is_admin') <add> fields = ['url', 'email', 'notes', 'is_admin'] <ide> extra_kwargs = { <ide> 'url': {'lookup_field': 'uuid'} <ide> } <ide> Alternatively, specify the field explicitly on the serializer class: <ide> <ide> class Meta: <ide> model = MyModel <del> fields = ('url', 'email', 'notes', 'is_admin') <add> fields = ['url', 'email', 'notes', 'is_admin'] <ide> <ide> #### Fields for model methods and properties. <ide> <ide> You can include `expiry_date` as a field option on a `ModelSerializer` class. <ide> class InvitationSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Invitation <del> fields = ('to_email', 'message', 'expiry_date') <add> fields = ['to_email', 'message', 'expiry_date'] <ide> <ide> These fields will be mapped to `serializers.ReadOnlyField()` instances. <ide> <ide> The `UniqueTogetherValidator` should be applied to a serializer, and takes a `qu <ide> class Meta: <ide> validators = [UniqueTogetherValidator( <ide> queryset=RaceResult.objects.all(), <del> fields=('category', 'position') <add> fields=['category', 'position'] <ide> )] <ide> <ide> #### The `UniqueForDateValidator` classes. <ide><path>docs/community/3.1-announcement.md <ide> For example, when using `NamespaceVersioning`, and the following hyperlinked ser <ide> class AccountsSerializer(serializer.HyperlinkedModelSerializer): <ide> class Meta: <ide> model = Accounts <del> fields = ('account_name', 'users') <add> fields = ['account_name', 'users'] <ide> <ide> The output representation would match the version used on the incoming request. Like so: <ide> <ide><path>docs/coreapi/schemas.md <ide> A generic view with sections in the class docstring, using single-line style. <ide> """ <ide> queryset = User.objects.all() <ide> serializer_class = UserSerializer <del> permission_classes = (IsAdminUser,) <add> permission_classes = [IsAdminUser] <ide> <ide> A generic viewset with sections in the class docstring, using multi-line style. <ide> <ide><path>docs/index.md <ide> Install using `pip`, including any optional packages you want... <ide> <ide> Add `'rest_framework'` to your `INSTALLED_APPS` setting. <ide> <del> INSTALLED_APPS = ( <add> INSTALLED_APPS = [ <ide> ... <ide> 'rest_framework', <del> ) <add> ] <ide> <ide> If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file. <ide> <ide> Here's our project's root `urls.py` module: <ide> class UserSerializer(serializers.HyperlinkedModelSerializer): <ide> class Meta: <ide> model = User <del> fields = ('url', 'username', 'email', 'is_staff') <add> fields = ['url', 'username', 'email', 'is_staff'] <ide> <ide> # ViewSets define the view behavior. <ide> class UserViewSet(viewsets.ModelViewSet): <ide><path>docs/topics/writable-nested-serializers.md <ide> Nested data structures are easy enough to work with if they're read-only - simpl <ide> class ToDoItemSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = ToDoItem <del> fields = ('text', 'is_completed') <add> fields = ['text', 'is_completed'] <ide> <ide> class ToDoListSerializer(serializers.ModelSerializer): <ide> items = ToDoItemSerializer(many=True, read_only=True) <ide> <ide> class Meta: <ide> model = ToDoList <del> fields = ('title', 'items') <add> fields = ['title', 'items'] <ide> <ide> Some example output from our serializer. <ide> <ide><path>docs/tutorial/1-serialization.md <ide> Once that's done we can create an app that we'll use to create a simple Web API. <ide> <ide> We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file: <ide> <del> INSTALLED_APPS = ( <add> INSTALLED_APPS = [ <ide> ... <ide> 'rest_framework', <ide> 'snippets.apps.SnippetsConfig', <del> ) <add> ] <ide> <ide> Okay, we're ready to roll. <ide> <ide> For the purposes of this tutorial we're going to start by creating a simple `Sni <ide> style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) <ide> <ide> class Meta: <del> ordering = ('created',) <add> ordering = ['created'] <ide> <ide> We'll also need to create an initial migration for our snippet model, and sync the database for the first time. <ide> <ide> Open the file `snippets/serializers.py` again, and replace the `SnippetSerialize <ide> class SnippetSerializer(serializers.ModelSerializer): <ide> class Meta: <ide> model = Snippet <del> fields = ('id', 'title', 'code', 'linenos', 'language', 'style') <add> fields = ['id', 'title', 'code', 'linenos', 'language', 'style'] <ide> <ide> One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following: <ide> <ide><path>docs/tutorial/4-authentication-and-permissions.md <ide> Now that we've got some users to work with, we'd better add representations of t <ide> <ide> class Meta: <ide> model = User <del> fields = ('id', 'username', 'snippets') <add> fields = ['id', 'username', 'snippets'] <ide> <ide> Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it. <ide> <ide> First add the following import in the views module <ide> <ide> Then, add the following property to **both** the `SnippetList` and `SnippetDetail` view classes. <ide> <del> permission_classes = (permissions.IsAuthenticatedOrReadOnly,) <add> permission_classes = [permissions.IsAuthenticatedOrReadOnly] <ide> <ide> ## Adding login to the Browsable API <ide> <ide> In the snippets app, create a new file, `permissions.py` <ide> <ide> Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class: <ide> <del> permission_classes = (permissions.IsAuthenticatedOrReadOnly, <del> IsOwnerOrReadOnly,) <add> permission_classes = [permissions.IsAuthenticatedOrReadOnly, <add> IsOwnerOrReadOnly] <ide> <ide> Make sure to also import the `IsOwnerOrReadOnly` class. <ide> <ide><path>docs/tutorial/5-relationships-and-hyperlinked-apis.md <ide> Instead of using a concrete generic view, we'll use the base class for represent <ide> <ide> class SnippetHighlight(generics.GenericAPIView): <ide> queryset = Snippet.objects.all() <del> renderer_classes = (renderers.StaticHTMLRenderer,) <add> renderer_classes = [renderers.StaticHTMLRenderer] <ide> <ide> def get(self, request, *args, **kwargs): <ide> snippet = self.get_object() <ide> We can easily re-write our existing serializers to use hyperlinking. In your `sn <ide> <ide> class Meta: <ide> model = Snippet <del> fields = ('url', 'id', 'highlight', 'owner', <del> 'title', 'code', 'linenos', 'language', 'style') <add> fields = ['url', 'id', 'highlight', 'owner', <add> 'title', 'code', 'linenos', 'language', 'style'] <ide> <ide> <ide> class UserSerializer(serializers.HyperlinkedModelSerializer): <ide> snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) <ide> <ide> class Meta: <ide> model = User <del> fields = ('url', 'id', 'username', 'snippets') <add> fields = ['url', 'id', 'username', 'snippets'] <ide> <ide> Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern. <ide> <ide><path>docs/tutorial/6-viewsets-and-routers.md <ide> Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl <ide> """ <ide> queryset = Snippet.objects.all() <ide> serializer_class = SnippetSerializer <del> permission_classes = (permissions.IsAuthenticatedOrReadOnly, <del> IsOwnerOrReadOnly,) <add> permission_classes = [permissions.IsAuthenticatedOrReadOnly, <add> IsOwnerOrReadOnly] <ide> <ide> @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) <ide> def highlight(self, request, *args, **kwargs): <ide><path>docs/tutorial/quickstart.md <ide> First up we're going to define some serializers. Let's create a new module named <ide> class UserSerializer(serializers.HyperlinkedModelSerializer): <ide> class Meta: <ide> model = User <del> fields = ('url', 'username', 'email', 'groups') <add> fields = ['url', 'username', 'email', 'groups'] <ide> <ide> <ide> class GroupSerializer(serializers.HyperlinkedModelSerializer): <ide> class Meta: <ide> model = Group <del> fields = ('url', 'name') <add> fields = ['url', 'name'] <ide> <ide> Notice that we're using hyperlinked relations in this case with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design. <ide> <ide> Pagination allows you to control how many objects per page are returned. To enab <ide> <ide> Add `'rest_framework'` to `INSTALLED_APPS`. The settings module will be in `tutorial/settings.py` <ide> <del> INSTALLED_APPS = ( <add> INSTALLED_APPS = [ <ide> ... <ide> 'rest_framework', <del> ) <add> ] <ide> <ide> Okay, we're done. <ide>
26
Javascript
Javascript
fix mediabox check (regr. of #519)
2ad3a8bd1c3e237a310239de168709d8143d5d9c
<ide><path>pdf.js <ide> var Page = (function pagePage() { <ide> get mediaBox() { <ide> var obj = this.inheritPageProp('MediaBox'); <ide> // Reset invalid media box to letter size. <del> if (!IsArray(obj) || obj.length === 4) <add> if (!IsArray(obj) || obj.length !== 4) <ide> obj = [0, 0, 612, 792]; <ide> return shadow(this, 'mediaBox', obj); <ide> },
1
Ruby
Ruby
pass `debug?` and `verbose?` in `brew style`
5db764f3cb3d8b3e356cc8f209ff4c52c126362e
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit <ide> <ide> only_cops = args.only_cops <ide> except_cops = args.except_cops <del> options = { fix: args.fix? } <add> options = { fix: args.fix?, debug: args.debug?, verbose: args.verbose? } <ide> <ide> if only_cops <ide> options[:only_cops] = only_cops <ide><path>Library/Homebrew/dev-cmd/style.rb <ide> def style <ide> only_cops = args.only_cops <ide> except_cops = args.except_cops <ide> <del> options = { fix: args.fix?, display_cop_names: args.display_cop_names? } <add> options = { <add> fix: args.fix?, display_cop_names: args.display_cop_names?, debug: args.debug?, verbose: args.verbose? <add> } <ide> if only_cops <ide> options[:only_cops] = only_cops <ide> elsif except_cops <ide><path>Library/Homebrew/style.rb <ide> def check_style_json(files, **options) <ide> check_style_impl(files, :json, **options) <ide> end <ide> <del> def check_style_impl(files, output_type, fix: false, except_cops: nil, only_cops: nil, display_cop_names: false) <add> def check_style_impl(files, output_type, <add> fix: false, except_cops: nil, only_cops: nil, display_cop_names: false, <add> debug: false, verbose: false) <ide> Homebrew.install_bundler_gems! <ide> require "rubocop" <ide> require "rubocops" <ide> def check_style_impl(files, output_type, fix: false, except_cops: nil, only_cops <ide> "--parallel" <ide> end <ide> <del> args += ["--extra-details", "--display-cop-names"] if Homebrew.args.verbose? <add> args += ["--extra-details"] if verbose <add> args += ["--display-cop-names"] if display_cop_names || verbose <ide> <ide> if except_cops <ide> except_cops.map! { |cop| RuboCop::Cop::Cop.registry.qualified_cop_name(cop.to_s, "") } <ide> def check_style_impl(files, output_type, fix: false, except_cops: nil, only_cops <ide> <ide> case output_type <ide> when :print <del> args << "--debug" if Homebrew.args.debug? <del> args << "--display-cop-names" if display_cop_names <add> args << "--debug" if debug <ide> args << "--format" << "simple" if files.present? <ide> system(cache_env, "rubocop", *args) <ide> rubocop_success = $CHILD_STATUS.success? <ide> when :json <ide> json, err, status = <del> Open3.capture3(cache_env, "rubocop", <del> "--format", "json", *args) <add> Open3.capture3(cache_env, "rubocop", "--format", "json", *args) <ide> # exit status of 1 just means violations were found; other numbers mean <ide> # execution errors. <ide> # exitstatus can also be nil if RuboCop process crashes, e.g. due to
3
Python
Python
add imports to examples
e58b3ec5df57359cd0bf64e817c397589f655ade
<ide><path>src/transformers/modeling_bart.py <ide> def forward( <ide> <ide> # Mask filling only works for bart-large <ide> from transformers import BartTokenizer, BartForConditionalGeneration <del> tokenizer = AutoTokenizer.from_pretrained('bart-large') <add> tokenizer = BartTokenizer.from_pretrained('bart-large') <ide> TXT = "My friends are <mask> but they eat too many carbs." <ide> model = BartForConditionalGeneration.from_pretrained('bart-large') <ide> input_ids = tokenizer.batch_encode_plus([TXT], return_tensors='pt')['input_ids'] <ide> def generate( <ide> Examples:: <ide> from transformers import BartTokenizer, BartForConditionalGeneration, BartConfig <ide> # see ``examples/summarization/bart/evaluate_cnn.py`` for a longer example <del> config = BartConfig(vocab_size=50264, output_past=True) # no mask_token_id <del> model = BartForConditionalGeneration.from_pretrained('bart-large-cnn', config=config) <add> model = BartForConditionalGeneration.from_pretrained('bart-large-cnn') <ide> tokenizer = BartTokenizer.from_pretrained('bart-large-cnn') <ide> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs." <ide> inputs = tokenizer.batch_encode_plus([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors='pt')
1