content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
move extensions to boot script
8a668860816f1f9b644725dbe72385d45efdc101
<ide><path>common/models/Access-Token.js <del>import { Observable } from 'rx'; <del> <del>module.exports = AccessToken => { <del> // wait for datasource to attach before adding methods <del> // prevents loopback from unnecessarily <del> // adding watchers on startup <del> AccessToken.on('dataSourceAttached', () => { <del> AccessToken.findOne$ = Observable.fromNodeCallback( <del> AccessToken.findOne.bind(AccessToken) <del> ); <del> AccessToken.prototype.validate$ = Observable.fromNodeCallback( <del> AccessToken.prototype.validate <del> ); <del> AccessToken.prototype.destroy$ = Observable.fromNodeCallback( <del> AccessToken.prototype.destroy <del> ); <del> }); <del>}; <ide><path>server/boot/a-extend-built-ins.js <add>import { Observable } from 'rx'; <add> <add>export default function extendEmail(app) { <add> const { AccessToken, Email } = app.models; <add> Email.send$ = Observable.fromNodeCallback(Email.send, Email); <add> AccessToken.findOne$ = Observable.fromNodeCallback( <add> AccessToken.findOne.bind(AccessToken) <add> ); <add> AccessToken.prototype.validate$ = Observable.fromNodeCallback( <add> AccessToken.prototype.validate <add> ); <add> AccessToken.prototype.destroy$ = Observable.fromNodeCallback( <add> AccessToken.prototype.destroy <add> ); <add>} <ide><path>server/boot/a-extendEmail.js <del>import { Observable } from 'rx'; <del> <del>export default function extendEmail(app) { <del> const { Email } = app.models; <del> Email.send$ = Observable.fromNodeCallback(Email.send, Email); <del>}
3
Javascript
Javascript
update node tests to be qunit 2 compatible
b5cfcf55875770c4d917854459e753c134332e5f
<ide><path>tests/node/app-boot-test.js <ide> QUnit.test("App boots and routes to a URL", function(assert) { <ide> assert.ok(this.app); <ide> }); <ide> <del>QUnit.test("nested {{component}}", function() { <add>QUnit.test("nested {{component}}", function(assert) { <ide> this.template('index', "{{root-component}}"); <ide> <ide> this.template('components/root-component', "\ <ide> QUnit.test("nested {{component}}", function() { <ide> "); <ide> <ide> return this.renderToHTML('/').then(function(html) { <del> assertHTMLMatches(html, '<body><div id="EMBER_ID" class="ember-view"><div id="EMBER_ID" class="ember-view"><h1>Hello World</h1><div><div id="EMBER_ID" class="ember-view"><p>The files are *inside* the computer?!</p></div></div></div></div></body>'); <add> assertHTMLMatches(assert, html, '<body><div id="EMBER_ID" class="ember-view"><div id="EMBER_ID" class="ember-view"><h1>Hello World</h1><div><div id="EMBER_ID" class="ember-view"><p>The files are *inside* the computer?!</p></div></div></div></div></body>'); <ide> }); <ide> }); <ide> <del>QUnit.test("{{link-to}}", function() { <add>QUnit.test("{{link-to}}", function(assert) { <ide> this.template('application', "<h1>{{#link-to 'photos'}}Go to photos{{/link-to}}</h1>"); <ide> this.routes(function() { <ide> this.route('photos'); <ide> }); <ide> <ide> return this.renderToHTML('/').then(function(html) { <del> assertHTMLMatches(html, '<body><div id="EMBER_ID" class="ember-view"><h1><a id="EMBER_ID" href="/photos" class="ember-view">Go to photos</a><\/h1></div></body>'); <add> assertHTMLMatches(assert, html, '<body><div id="EMBER_ID" class="ember-view"><h1><a id="EMBER_ID" href="/photos" class="ember-view">Go to photos</a><\/h1></div></body>'); <ide> }); <ide> }); <ide> <del>QUnit.test("non-escaped content", function() { <add>QUnit.test("non-escaped content", function(assert) { <ide> this.routes(function() { <ide> this.route('photos'); <ide> }); <ide> QUnit.test("non-escaped content", function() { <ide> }); <ide> <ide> return this.renderToHTML('/').then(function(html) { <del> assertHTMLMatches(html, '<body><div id="EMBER_ID" class="ember-view"><h1><b>Hello world</b></h1></div></body>'); <add> assertHTMLMatches(assert, html, '<body><div id="EMBER_ID" class="ember-view"><h1><b>Hello world</b></h1></div></body>'); <ide> }); <ide> }); <ide> <del>QUnit.test("outlets", function() { <add>QUnit.test("outlets", function(assert) { <ide> this.routes(function() { <ide> this.route('photos'); <ide> }); <ide> QUnit.test("outlets", function() { <ide> <ide> var promises = []; <ide> promises.push(this.renderToHTML('/').then(function(html) { <del> assertHTMLMatches(html, '<body><div id="EMBER_ID" class="ember-view"><p><span>index</span></p></div></body>'); <add> assertHTMLMatches(assert, html, '<body><div id="EMBER_ID" class="ember-view"><p><span>index</span></p></div></body>'); <ide> })); <ide> <ide> promises.push(this.renderToHTML('/photos').then(function(html) { <del> assertHTMLMatches(html, '<body><div id="EMBER_ID" class="ember-view"><p><em>photos</em></p></div></body>'); <add> assertHTMLMatches(assert, html, '<body><div id="EMBER_ID" class="ember-view"><p><em>photos</em></p></div></body>'); <ide> })); <ide> <ide> return this.all(promises); <ide> QUnit.test("Should not attempt to render element modifiers GH#14220", function(a <ide> <ide> return this.renderToHTML('/') <ide> .then(function(html) { <del> assertHTMLMatches(html, '<body><div id="EMBER_ID" class="ember-view"><div></div></div></body>'); <add> assertHTMLMatches(assert, html, '<body><div id="EMBER_ID" class="ember-view"><div></div></div></body>'); <ide> }); <ide> }); <ide><path>tests/node/helpers/assert-html-matches.js <ide> var htmlDiffer = new HtmlDiffer(diffOptions); <ide> * ignore whitespace and certain attributes values, such as IDs, which Ember <ide> * auto-generates. Attribute ordering is also ignored. <ide> */ <del>function assertHTMLMatches(actual, expected, message) { <add>function assertHTMLMatches(assert, actual, expected, message) { <ide> var isEqual = htmlDiffer.isEqual(actual, expected); <ide> <del> QUnit.push(isEqual, actual, expected, message); <add> assert.pushResult({ <add> result: isEqual, <add> actual, <add> expected, <add> message <add> }); <ide> } <ide> <ide> module.exports = assertHTMLMatches; <ide><path>tests/node/template-compiler-test.js <ide> var test = QUnit.test; <ide> var templateCompiler; <ide> <ide> module('ember-template-compiler.js', { <del> setup: function() { <add> beforeEach: function() { <ide> templateCompiler = require(templateCompilerPath); <ide> }, <ide> <del> teardown: function() { <add> afterEach: function() { <ide> // clear the previously cached version of this module <ide> delete require.cache[templateCompilerPath + '.js']; <ide> }
3
Ruby
Ruby
fix new schema test dependency on hash#to_xml
46b376962f064077734773c7e1eea5881e5d5696
<ide><path>activeresource/test/cases/base/schema_test.rb <ide> require 'abstract_unit' <add>require 'active_support/core_ext/hash/conversions' <ide> require "fixtures/person" <ide> require "fixtures/street_address" <ide>
1
Text
Text
fix example in assert.md
a2d86f6009dd0a33830ecf0677d69e1f181aea26
<ide><path>doc/api/assert.md <ide> assert.throws( <ide> ); <ide> <ide> // Using regular expressions to validate error properties: <del>throws( <add>assert.throws( <ide> () => { <ide> throw err; <ide> }, <ide> throws( <ide> ); <ide> <ide> // Fails due to the different `message` and `name` properties: <del>throws( <add>assert.throws( <ide> () => { <ide> const otherErr = new Error('Not found'); <ide> // Copy all enumerable properties from `err` to `otherErr`. <ide> assert.throws( <ide> ); <ide> <ide> // Using regular expressions to validate error properties: <del>throws( <add>assert.throws( <ide> () => { <ide> throw err; <ide> }, <ide> throws( <ide> ); <ide> <ide> // Fails due to the different `message` and `name` properties: <del>throws( <add>assert.throws( <ide> () => { <ide> const otherErr = new Error('Not found'); <ide> // Copy all enumerable properties from `err` to `otherErr`.
1
Text
Text
fix typo in changelog.md - s/issue/issues
2ee3b482456cd2a09ccbd3a4b0c20f3d0c5a5644
<ide><path>CHANGELOG.md <ide> Fixes and Functionality: <ide> <ide> - Unzip response body only for statuses != 204 ([#1129](https://github.com/axios/axios/pull/1129)) - drawski <del>- Destroy stream on exceeding maxContentLength (fixes [#1098](https://github.com/axios/axios/issue/1098)) ([#1485](https://github.com/axios/axios/pull/1485)) - Gadzhi Gadzhiev <add>- Destroy stream on exceeding maxContentLength (fixes [#1098](https://github.com/axios/axios/issues/1098)) ([#1485](https://github.com/axios/axios/pull/1485)) - Gadzhi Gadzhiev <ide> - Makes Axios error generic to use AxiosResponse ([#1738](https://github.com/axios/axios/pull/1738)) - Suman Lama <ide> - Fixing Mocha tests by locking follow-redirects version to 1.5.10 ([#1993](https://github.com/axios/axios/pull/1993)) - grumblerchester <ide> - Allow uppercase methods in typings. ([#1781](https://github.com/axios/axios/pull/1781)) - Ken Powers
1
Java
Java
fix unset problem for text alignment change
5b4fb89e4ca7edeb5124bcad8cb18815e30d021f
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextShadowNode.java <ide> private static int parseNumericFontWeight(String fontWeightString) { <ide> <ide> protected int mNumberOfLines = UNSET; <ide> protected int mFontSize = UNSET; <del> protected int mTextAlign = UNSET; <add> protected int mTextAlign = Gravity.NO_GRAVITY; <ide> <ide> private float mTextShadowOffsetDx = 0; <ide> private float mTextShadowOffsetDy = 0;
1
Text
Text
fix changelog badge to match style
51c4b30f8e02000ccb53973c70194ab8a76989e2
<ide><path>README.md <ide> It is tiny (2kB) and has no dependencies. <ide> [![npm downloads](https://img.shields.io/npm/dm/redux.svg?style=flat-square)](https://www.npmjs.com/package/redux) <ide> [![redux channel on discord](https://img.shields.io/badge/discord-%23redux%20%40%20reactiflux-61dafb.svg?style=flat-square)](https://discord.gg/0ZcbPKXt5bZ6au5t) <ide> [![#rackt on freenode](https://img.shields.io/badge/irc-%23rackt%20%40%20freenode-61DAFB.svg?style=flat-square)](https://webchat.freenode.net/) <del>[![Changelog #187](https://img.shields.io/badge/changelog-%23187-lightgrey.svg)](https://changelog.com/187) <add>[![Changelog #187](https://img.shields.io/badge/changelog-%23187-lightgrey.svg?style=flat-square)](https://changelog.com/187) <ide> <ide> >**New! Learn Redux from its creator: <ide> >[Getting Started with Redux](https://egghead.io/series/getting-started-with-redux) (30 free videos)**
1
Javascript
Javascript
add transform option to module / module cache
a61ab8795af508669a986e7a60d3f82acf367166
<ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/index.js <ide> class DependencyGraph { <ide> extensions, <ide> mocksPattern, <ide> extractRequires, <add> transformCode, <ide> shouldThrowOnUnresolvedErrors = () => true, <ide> }) { <ide> this._opts = { <ide> class DependencyGraph { <ide> providesModuleNodeModules, <ide> platforms: platforms || [], <ide> preferNativePlatform: preferNativePlatform || false, <del> cache, <ide> extensions: extensions || ['js', 'json'], <ide> mocksPattern, <ide> extractRequires, <ide> shouldThrowOnUnresolvedErrors, <add> transformCode <ide> }; <del> this._cache = this._opts.cache; <add> this._cache = cache; <ide> this._helpers = new DependencyGraphHelpers(this._opts); <ide> this.load().catch((err) => { <ide> // This only happens at initialization. Live errors are easier to recover from. <ide> class DependencyGraph { <ide> <ide> this._fastfs.on('change', this._processFileChange.bind(this)); <ide> <del> this._moduleCache = new ModuleCache( <del> this._fastfs, <del> this._cache, <del> this._opts.extractRequires, <del> this._helpers <del> ); <add> this._moduleCache = new ModuleCache({ <add> fastfs: this._fastfs, <add> cache: this._cache, <add> extractRequires: this._opts.extractRequires, <add> transformCode: this._opts.transformCode, <add> depGraphHelpers: this._helpers, <add> }); <ide> <ide> this._hasteMap = new HasteMap({ <ide> fastfs: this._fastfs, <ide><path>packager/react-packager/src/DependencyResolver/Module.js <ide> const extractRequires = require('./lib/extractRequires'); <ide> <ide> class Module { <ide> <del> constructor({ file, fastfs, moduleCache, cache, extractor, depGraphHelpers }) { <add> constructor({ <add> file, <add> fastfs, <add> moduleCache, <add> cache, <add> extractor = extractRequires, <add> transformCode, <add> depGraphHelpers, <add> }) { <ide> if (!isAbsolutePath(file)) { <ide> throw new Error('Expected file to be absolute path but got ' + file); <ide> } <ide> class Module { <ide> this._moduleCache = moduleCache; <ide> this._cache = cache; <ide> this._extractor = extractor; <add> this._transformCode = transformCode; <ide> this._depGraphHelpers = depGraphHelpers; <ide> } <ide> <ide> class Module { <ide> ); <ide> } <ide> <add> getCode() { <add> return this.read().then(({code}) => code); <add> } <add> <ide> getName() { <ide> return this._cache.get( <ide> this.path, <ide> class Module { <ide> if (this.isJSON() || 'extern' in moduleDocBlock) { <ide> data.dependencies = []; <ide> data.asyncDependencies = []; <add> data.code = content; <add> return data; <ide> } else { <del> var dependencies = (this._extractor || extractRequires)(content).deps; <del> data.dependencies = dependencies.sync; <del> data.asyncDependencies = dependencies.async; <add> const transformCode = this._transformCode; <add> const codePromise = transformCode <add> ? transformCode(this, content) <add> : Promise.resolve({code: content}); <add> <add> return codePromise.then(({code, dependencies, asyncDependencies}) => { <add> const {deps} = this._extractor(code); <add> data.dependencies = dependencies || deps.sync; <add> data.asyncDependencies = asyncDependencies || deps.async; <add> data.code = code; <add> return data; <add> }); <ide> } <del> <del> return data; <ide> }); <ide> } <ide> <ide><path>packager/react-packager/src/DependencyResolver/ModuleCache.js <ide> const path = require('path'); <ide> <ide> class ModuleCache { <ide> <del> constructor(fastfs, cache, extractRequires, depGraphHelpers) { <add> constructor({ <add> fastfs, <add> cache, <add> extractRequires, <add> transformCode, <add> depGraphHelpers, <add> }) { <ide> this._moduleCache = Object.create(null); <ide> this._packageCache = Object.create(null); <ide> this._fastfs = fastfs; <ide> this._cache = cache; <ide> this._extractRequires = extractRequires; <add> this._transformCode = transformCode; <ide> this._depGraphHelpers = depGraphHelpers; <add> <ide> fastfs.on('change', this._processFileChange.bind(this)); <ide> } <ide> <ide> class ModuleCache { <ide> moduleCache: this, <ide> cache: this._cache, <ide> extractor: this._extractRequires, <add> transformCode: this._transformCode, <ide> depGraphHelpers: this._depGraphHelpers, <ide> }); <ide> } <ide><path>packager/react-packager/src/DependencyResolver/__tests__/Module-test.js <ide> const DependencyGraphHelpers = require('../DependencyGraph/DependencyGraphHelper <ide> const Promise = require('promise'); <ide> const fs = require('graceful-fs'); <ide> <add>function mockIndexFile(indexJs) { <add> fs.__setMockFilesystem({'root': {'index.js': indexJs}}); <add>} <add> <ide> describe('Module', () => { <ide> const fileWatcher = { <ide> on: () => this, <ide> isWatchman: () => Promise.resolve(false), <ide> }; <add> const fileName = '/root/index.js'; <add> <add> let cache, fastfs; <add> <add> const createCache = () => ({ <add> get: jest.genMockFn().mockImplementation( <add> (filepath, field, cb) => cb(filepath) <add> ), <add> invalidate: jest.genMockFn(), <add> end: jest.genMockFn(), <add> }); <add> <add> const createModule = (options) => <add> new Module({ <add> cache, <add> fastfs, <add> file: fileName, <add> depGraphHelpers: new DependencyGraphHelpers(), <add> moduleCache: new ModuleCache({fastfs, cache}), <add> ...options, <add> }); <ide> <del> const Cache = jest.genMockFn(); <del> Cache.prototype.get = jest.genMockFn().mockImplementation( <del> (filepath, field, cb) => cb(filepath) <del> ); <del> Cache.prototype.invalidate = jest.genMockFn(); <del> Cache.prototype.end = jest.genMockFn(); <add> beforeEach(function(done) { <add> cache = createCache(); <add> fastfs = new Fastfs( <add> 'test', <add> ['/root'], <add> fileWatcher, <add> {crawling: Promise.resolve([fileName]), ignore: []}, <add> ); <ide> <add> fastfs.build().then(done); <add> }); <ide> <ide> describe('Async Dependencies', () => { <ide> function expectAsyncDependenciesToEqual(expected) { <del> const fastfs = new Fastfs( <del> 'test', <del> ['/root'], <del> fileWatcher, <del> {crawling: Promise.resolve(['/root/index.js']), ignore: []}, <add> const module = createModule(); <add> return module.getAsyncDependencies().then(actual => <add> expect(actual).toEqual(expected) <ide> ); <del> const cache = new Cache(); <del> <del> return fastfs.build().then(() => { <del> const module = new Module({ <del> file: '/root/index.js', <del> fastfs, <del> moduleCache: new ModuleCache(fastfs, cache), <del> cache: cache, <del> depGraphHelpers: new DependencyGraphHelpers(), <del> }); <del> <del> return module.getAsyncDependencies().then(actual => <del> expect(actual).toEqual(expected) <del> ); <del> }); <ide> } <ide> <ide> pit('should recognize single dependency', () => { <del> fs.__setMockFilesystem({ <del> 'root': { <del> 'index.js': 'System.' + 'import("dep1")', <del> }, <del> }); <add> mockIndexFile('System.' + 'import("dep1")'); <ide> <ide> return expectAsyncDependenciesToEqual([['dep1']]); <ide> }); <ide> <ide> pit('should parse single quoted dependencies', () => { <del> fs.__setMockFilesystem({ <del> 'root': { <del> 'index.js': 'System.' + 'import(\'dep1\')', <del> }, <del> }); <add> mockIndexFile('System.' + 'import(\'dep1\')'); <ide> <ide> return expectAsyncDependenciesToEqual([['dep1']]); <ide> }); <ide> <ide> pit('should parse multiple async dependencies on the same module', () => { <del> fs.__setMockFilesystem({ <del> 'root': { <del> 'index.js': [ <del> 'System.' + 'import("dep1")', <del> 'System.' + 'import("dep2")', <del> ].join('\n'), <del> }, <del> }); <add> mockIndexFile([ <add> 'System.' + 'import("dep1")', <add> 'System.' + 'import("dep2")', <add> ].join('\n')); <ide> <ide> return expectAsyncDependenciesToEqual([ <ide> ['dep1'], <ide> describe('Module', () => { <ide> }); <ide> <ide> pit('parse fine new lines', () => { <del> fs.__setMockFilesystem({ <del> 'root': { <del> 'index.js': 'System.' + 'import(\n"dep1"\n)', <del> }, <del> }); <add> mockIndexFile('System.' + 'import(\n"dep1"\n)'); <ide> <ide> return expectAsyncDependenciesToEqual([['dep1']]); <ide> }); <ide> }); <ide> <add> describe('Code', () => { <add> const fileContents = 'arbitrary(code)'; <add> beforeEach(function() { <add> mockIndexFile(fileContents); <add> }); <add> <add> pit('exposes file contents as `code` property on the data exposed by `read()`', () => <add> createModule().read().then(({code}) => <add> expect(code).toBe(fileContents)) <add> ); <add> <add> pit('exposes file contes via the `getCode()` method', () => <add> createModule().getCode().then(code => <add> expect(code).toBe(fileContents)) <add> ); <add> <add> pit('does not save the code in the cache', () => <add> createModule().getCode().then(() => <add> expect(cache.get).not.toBeCalled() <add> ) <add> ); <add> }); <add> <ide> describe('Extrators', () => { <ide> <del> function createModuleWithExtractor(extractor) { <del> const fastfs = new Fastfs( <del> 'test', <del> ['/root'], <del> fileWatcher, <del> {crawling: Promise.resolve(['/root/index.js']), ignore: []}, <del> ); <del> const cache = new Cache(); <del> <del> return fastfs.build().then(() => { <del> return new Module({ <del> file: '/root/index.js', <del> fastfs, <del> moduleCache: new ModuleCache(fastfs, cache), <del> cache, <del> extractor, <del> depGraphHelpers: new DependencyGraphHelpers(), <add> pit('uses custom require extractors if specified', () => { <add> mockIndexFile(''); <add> const module = createModule({ <add> extractor: code => ({deps: {sync: ['foo', 'bar']}}), <add> }); <add> <add> return module.getDependencies().then(actual => <add> expect(actual).toEqual(['foo', 'bar'])); <add> }); <add> }); <add> <add> describe('Custom Code Transform', () => { <add> let transformCode; <add> const fileContents = 'arbitrary(code);'; <add> const exampleCode = ` <add> require('a'); <add> System.import('b'); <add> require('c');`; <add> <add> beforeEach(function() { <add> transformCode = jest.genMockFn(); <add> mockIndexFile(fileContents); <add> transformCode.mockReturnValue(Promise.resolve({code: ''})); <add> }); <add> <add> pit('passes the module and file contents to the transform function when reading', () => { <add> const module = createModule({transformCode}); <add> return module.read() <add> .then(() => { <add> expect(transformCode).toBeCalledWith(module, fileContents); <ide> }); <add> }); <add> <add> pit('uses the code that `transformCode` resolves to to extract dependencies', () => { <add> transformCode.mockReturnValue(Promise.resolve({code: exampleCode})); <add> const module = createModule({transformCode}); <add> <add> return Promise.all([ <add> module.getDependencies(), <add> module.getAsyncDependencies(), <add> ]).then(([dependencies, asyncDependencies]) => { <add> expect(dependencies).toEqual(['a', 'c']); <add> expect(asyncDependencies).toEqual([['b']]); <ide> }); <del> } <add> }); <ide> <del> pit('uses custom require extractors if specified', () => { <del> fs.__setMockFilesystem({ <del> 'root': { <del> 'index.js': '', <del> }, <add> pit('uses dependencies that `transformCode` resolves to, instead of extracting them', () => { <add> const mockedDependencies = ['foo', 'bar']; <add> transformCode.mockReturnValue(Promise.resolve({ <add> code: exampleCode, <add> dependencies: mockedDependencies, <add> })); <add> const module = createModule({transformCode}); <add> <add> return Promise.all([ <add> module.getDependencies(), <add> module.getAsyncDependencies(), <add> ]).then(([dependencies, asyncDependencies]) => { <add> expect(dependencies).toEqual(mockedDependencies); <add> expect(asyncDependencies).toEqual([['b']]); <ide> }); <add> }); <ide> <del> return createModuleWithExtractor( <del> code => ({deps: {sync: ['foo', 'bar']}}) <del> ).then(module => <del> module.getDependencies().then(actual => <del> expect(actual).toEqual(['foo', 'bar']) <del> ) <del> ); <add> pit('uses async dependencies that `transformCode` resolves to, instead of extracting them', () => { <add> const mockedAsyncDependencies = [['foo', 'bar'], ['baz']]; <add> transformCode.mockReturnValue(Promise.resolve({ <add> code: exampleCode, <add> asyncDependencies: mockedAsyncDependencies, <add> })); <add> const module = createModule({transformCode}); <add> <add> return Promise.all([ <add> module.getDependencies(), <add> module.getAsyncDependencies(), <add> ]).then(([dependencies, asyncDependencies]) => { <add> expect(dependencies).toEqual(['a', 'c']); <add> expect(asyncDependencies).toEqual(mockedAsyncDependencies); <add> }); <add> }); <add> <add> pit('exposes the transformed code rather than the raw file contents', () => { <add> transformCode.mockReturnValue(Promise.resolve({code: exampleCode})); <add> const module = createModule({transformCode}); <add> return Promise.all([module.read(), module.getCode()]) <add> .then(([data, code]) => { <add> expect(data.code).toBe(exampleCode); <add> expect(code).toBe(exampleCode); <add> }); <ide> }); <ide> }); <ide> });
4
Ruby
Ruby
increase timeout tolerance
35b8c3d6e2c2cfcddf754989dcc0e5265d4f88f1
<ide><path>Library/Homebrew/test/cask/artifact/shared_examples/uninstall_zap.rb <ide> }.to output(/Application 'my.fancy.package.app' did not quit\./).to_stderr <ide> end <ide> <del> expect(time.real).to be_within(0.5).of(10) <add> expect(time.real).to be_within(3).of(10) <ide> end <ide> end <ide>
1
Java
Java
add perf markers for cold start
ca016e4eb30e4535c42e8e108ea6ff06e2b44b44
<ide><path>ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java <ide> import com.facebook.react.uimanager.ViewManager; <ide> import com.facebook.react.uimanager.debug.DebugComponentOwnershipModule; <ide> import com.facebook.react.uimanager.events.RCTEventEmitter; <add>import com.facebook.systrace.Systrace; <ide> <ide> /** <ide> * Package defining core framework modules (e.g. UIManager). It should be used for modules that <ide> @Override <ide> public List<NativeModule> createNativeModules( <ide> ReactApplicationContext catalystApplicationContext) { <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "createUIManagerModule"); <add> UIManagerModule uiManagerModule; <add> try { <add> uiManagerModule = new UIManagerModule( <add> catalystApplicationContext, <add> mReactInstanceManager.createAllViewManagers(catalystApplicationContext)); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <add> <ide> return Arrays.<NativeModule>asList( <ide> new AnimationsDebugModule( <ide> catalystApplicationContext, <ide> public List<NativeModule> createNativeModules( <ide> new SourceCodeModule( <ide> mReactInstanceManager.getSourceUrl(), <ide> mReactInstanceManager.getDevSupportManager().getSourceMapUrl()), <del> new UIManagerModule( <del> catalystApplicationContext, <del> mReactInstanceManager.createAllViewManagers(catalystApplicationContext)), <add> uiManagerModule, <ide> new DebugComponentOwnershipModule(catalystApplicationContext)); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerImpl.java <ide> import com.facebook.react.uimanager.UIManagerModule; <ide> import com.facebook.react.uimanager.ViewManager; <ide> import com.facebook.soloader.SoLoader; <add>import com.facebook.systrace.Systrace; <ide> <ide> /** <ide> * This class is managing instances of {@link CatalystInstance}. It expose a way to configure <ide> public void detachRootView(ReactRootView rootView) { <ide> @Override <ide> public List<ViewManager> createAllViewManagers( <ide> ReactApplicationContext catalystApplicationContext) { <del> List<ViewManager> allViewManagers = new ArrayList<>(); <del> for (ReactPackage reactPackage : mPackages) { <del> allViewManagers.addAll(reactPackage.createViewManagers(catalystApplicationContext)); <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "createAllViewManagers"); <add> try { <add> List<ViewManager> allViewManagers = new ArrayList<>(); <add> for (ReactPackage reactPackage : mPackages) { <add> allViewManagers.addAll(reactPackage.createViewManagers(catalystApplicationContext)); <add> } <add> return allViewManagers; <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <del> return allViewManagers; <ide> } <ide> <ide> @VisibleForTesting <ide> private ReactApplicationContext createReactContext( <ide> reactContext.setNativeModuleCallExceptionHandler(mDevSupportManager); <ide> } <ide> <del> CoreModulesPackage coreModulesPackage = <del> new CoreModulesPackage(this, mBackBtnHandler); <del> processPackage(coreModulesPackage, reactContext, nativeRegistryBuilder, jsModulesBuilder); <add> Systrace.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "createAndProcessCoreModulesPackage"); <add> try { <add> CoreModulesPackage coreModulesPackage = <add> new CoreModulesPackage(this, mBackBtnHandler); <add> processPackage(coreModulesPackage, reactContext, nativeRegistryBuilder, jsModulesBuilder); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <ide> <ide> // TODO(6818138): Solve use-case of native/js modules overriding <ide> for (ReactPackage reactPackage : mPackages) { <del> processPackage(reactPackage, reactContext, nativeRegistryBuilder, jsModulesBuilder); <add> Systrace.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "createAndProcessCustomReactPackage"); <add> try { <add> processPackage(reactPackage, reactContext, nativeRegistryBuilder, jsModulesBuilder); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <add> } <add> <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "buildNativeModuleRegistry"); <add> NativeModuleRegistry nativeModuleRegistry; <add> try { <add> nativeModuleRegistry = nativeRegistryBuilder.build(); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <add> <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "buildJSModuleConfig"); <add> JavaScriptModulesConfig javaScriptModulesConfig; <add> try { <add> javaScriptModulesConfig = jsModulesBuilder.build(); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> <ide> CatalystInstanceImpl.Builder catalystInstanceBuilder = new CatalystInstanceImpl.Builder() <ide> .setCatalystQueueConfigurationSpec(CatalystQueueConfigurationSpec.createDefault()) <ide> .setJSExecutor(jsExecutor) <del> .setRegistry(nativeRegistryBuilder.build()) <del> .setJSModulesConfig(jsModulesBuilder.build()) <add> .setRegistry(nativeModuleRegistry) <add> .setJSModulesConfig(javaScriptModulesConfig) <ide> .setJSBundleLoader(jsBundleLoader) <ide> .setNativeModuleCallExceptionHandler(mDevSupportManager); <ide> <del> CatalystInstance catalystInstance = catalystInstanceBuilder.build(); <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "createCatalystInstance"); <add> CatalystInstance catalystInstance; <add> try { <add> catalystInstance = catalystInstanceBuilder.build(); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <add> <ide> if (mBridgeIdleDebugListener != null) { <ide> catalystInstance.addBridgeIdleDebugListener(mBridgeIdleDebugListener); <ide> } <ide> <ide> reactContext.initializeWithInstance(catalystInstance); <del> catalystInstance.runJSBundle(); <add> <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "runJSBundle"); <add> try { <add> catalystInstance.runJSBundle(); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <ide> <ide> return reactContext; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java <ide> private CatalystInstanceImpl( <ide> new Runnable() { <ide> @Override <ide> public void run() { <del> initializeBridge(jsExecutor, jsModulesConfig); <del> initLatch.countDown(); <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "initializeBridge"); <add> try { <add> initializeBridge(jsExecutor, jsModulesConfig); <add> initLatch.countDown(); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <ide> } <ide> }); <ide> <ide> private void initializeBridge( <ide> mCatalystQueueConfiguration.getJSQueueThread().assertIsOnThread(); <ide> Assertions.assertCondition(mBridge == null, "initializeBridge should be called once"); <ide> <del> mBridge = new ReactBridge( <del> jsExecutor, <del> new NativeModulesReactCallback(), <del> mCatalystQueueConfiguration.getNativeModulesQueueThread()); <del> mBridge.setGlobalVariable( <del> "__fbBatchedBridgeConfig", <del> buildModulesConfigJSONProperty(mJavaRegistry, jsModulesConfig)); <del> Systrace.registerListener(mTraceListener); <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "ReactBridgeCtor"); <add> try { <add> mBridge = new ReactBridge( <add> jsExecutor, <add> new NativeModulesReactCallback(), <add> mCatalystQueueConfiguration.getNativeModulesQueueThread()); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <add> <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "setBatchedBridgeConfig"); <add> try { <add> mBridge.setGlobalVariable( <add> "__fbBatchedBridgeConfig", <add> buildModulesConfigJSONProperty(mJavaRegistry, jsModulesConfig)); <add> mBridge.setGlobalVariable( <add> "__RCTProfileIsProfiling", <add> Systrace.isTracing(Systrace.TRACE_TAG_REACT_APPS) ? "true" : "false"); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <ide> } <ide> <ide> @Override <ide> public void runJSBundle() { <del> Systrace.beginSection( <del> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <del> "CatalystInstance_runJSBundle"); <del> <ide> try { <ide> final CountDownLatch initLatch = new CountDownLatch(1); <ide> mCatalystQueueConfiguration.getJSQueueThread().runOnQueue( <ide> public void run() { <ide> <ide> incrementPendingJSCalls(); <ide> <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "loadJSScript"); <ide> try { <ide> mJSBundleLoader.loadScript(mBridge); <add> <add> // This is registered after JS starts since it makes a JS call <add> Systrace.registerListener(mTraceListener); <ide> } catch (JSExecutionException e) { <ide> mNativeModuleCallExceptionHandler.handleException(e); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> <ide> initLatch.countDown(); <ide> public void run() { <ide> "Timed out loading JS!"); <ide> } catch (InterruptedException e) { <ide> throw new RuntimeException(e); <del> } finally { <del> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleRegistry.java <ide> import java.io.StringWriter; <ide> import java.util.ArrayList; <ide> import java.util.Collection; <del>import java.util.HashSet; <ide> import java.util.Map; <ide> import java.util.Set; <ide> <ide> public Builder add(NativeModule module) { <ide> } <ide> <ide> public NativeModuleRegistry build() { <del> JsonFactory jsonFactory = new JsonFactory(); <del> StringWriter writer = new StringWriter(); <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateJSON"); <add> String moduleDefinitionJson; <ide> try { <del> JsonGenerator jg = jsonFactory.createGenerator(writer); <del> jg.writeStartObject(); <del> for (ModuleDefinition module : mModuleDefinitions) { <del> jg.writeObjectFieldStart(module.name); <del> jg.writeNumberField("moduleID", module.id); <del> jg.writeObjectFieldStart("methods"); <del> for (int i = 0; i < module.methods.size(); i++) { <del> MethodRegistration method = module.methods.get(i); <del> jg.writeObjectFieldStart(method.name); <del> jg.writeNumberField("methodID", i); <del> jg.writeStringField("type", method.method.getType()); <add> JsonFactory jsonFactory = new JsonFactory(); <add> StringWriter writer = new StringWriter(); <add> try { <add> JsonGenerator jg = jsonFactory.createGenerator(writer); <add> jg.writeStartObject(); <add> for (ModuleDefinition module : mModuleDefinitions) { <add> jg.writeObjectFieldStart(module.name); <add> jg.writeNumberField("moduleID", module.id); <add> jg.writeObjectFieldStart("methods"); <add> for (int i = 0; i < module.methods.size(); i++) { <add> MethodRegistration method = module.methods.get(i); <add> jg.writeObjectFieldStart(method.name); <add> jg.writeNumberField("methodID", i); <add> jg.writeStringField("type", method.method.getType()); <add> jg.writeEndObject(); <add> } <add> jg.writeEndObject(); <add> module.target.writeConstantsField(jg, "constants"); <ide> jg.writeEndObject(); <ide> } <ide> jg.writeEndObject(); <del> module.target.writeConstantsField(jg, "constants"); <del> jg.writeEndObject(); <add> jg.close(); <add> } catch (IOException ioe) { <add> throw new RuntimeException("Unable to serialize Java module configuration", ioe); <ide> } <del> jg.writeEndObject(); <del> jg.close(); <del> } catch (IOException ioe) { <del> throw new RuntimeException("Unable to serialize Java module configuration", ioe); <add> moduleDefinitionJson = writer.getBuffer().toString(); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <del> String moduleDefinitionJson = writer.getBuffer().toString(); <ide> return new NativeModuleRegistry(mModuleDefinitions, mModuleInstances, moduleDefinitionJson); <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java <ide> public UIManagerModule(ReactApplicationContext reactContext, List<ViewManager> v <ide> mShadowNodeRegistry); <ide> DisplayMetrics displayMetrics = reactContext.getResources().getDisplayMetrics(); <ide> DisplayMetricsHolder.setDisplayMetrics(displayMetrics); <del> <del> mModuleConstants = UIManagerModuleConstantsHelper.createConstants( <del> displayMetrics, <del> viewManagerList); <add> mModuleConstants = createConstants(displayMetrics, viewManagerList); <ide> reactContext.addLifecycleEventListener(this); <ide> } <ide> <ide> public void onCatalystInstanceDestroy() { <ide> mEventDispatcher.onCatalystInstanceDestroyed(); <ide> } <ide> <add> private static Map<String, Object> createConstants( <add> DisplayMetrics displayMetrics, <add> List<ViewManager> viewManagerList) { <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateUIManagerConstants"); <add> try { <add> return UIManagerModuleConstantsHelper.createConstants( <add> displayMetrics, <add> viewManagerList); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <add> } <add> <ide> /** <ide> * Registers a new root view. JS can use the returned tag with manageChildren to add/remove <ide> * children to this view.
5
Go
Go
check bad syntax on dockerfile before building
c8dc2b156a079ce03db8f579094b9643632661a8
<ide><path>builder/dockerfile/builder.go <ide> func (b *Builder) build(stdout io.Writer, stderr io.Writer, out io.Writer) (stri <ide> <ide> var shortImgID string <ide> total := len(b.dockerfile.Children) <add> for _, n := range b.dockerfile.Children { <add> if err := b.checkDispatch(n, false); err != nil { <add> return "", err <add> } <add> } <add> <ide> for i, n := range b.dockerfile.Children { <ide> select { <ide> case <-b.clientCtx.Done(): <ide> func (b *Builder) build(stdout io.Writer, stderr io.Writer, out io.Writer) (stri <ide> default: <ide> // Not cancelled yet, keep going... <ide> } <add> <ide> if err := b.dispatch(i, total, n); err != nil { <ide> if b.options.ForceRemove { <ide> b.clearTmp() <ide> func BuildFromConfig(config *container.Config, changes []string) (*container.Con <ide> b.disableCommit = true <ide> <ide> total := len(ast.Children) <add> for _, n := range ast.Children { <add> if err := b.checkDispatch(n, false); err != nil { <add> return nil, err <add> } <add> } <add> <ide> for i, n := range ast.Children { <ide> if err := b.dispatch(i, total, n); err != nil { <ide> return nil, err <ide><path>builder/dockerfile/evaluator.go <ide> func (b *Builder) dispatch(stepN int, stepTotal int, ast *parser.Node) error { <ide> <ide> return fmt.Errorf("Unknown instruction: %s", upperCasedCmd) <ide> } <add> <add>// checkDispatch does a simple check for syntax errors of the Dockerfile. <add>// Because some of the instructions can only be validated through runtime, <add>// arg, env, etc., this syntax check will not be complete and could not replace <add>// the runtime check. Instead, this function is only a helper that allows <add>// user to find out the obvious error in Dockerfile earlier on. <add>// onbuild bool: indicate if instruction XXX is part of `ONBUILD XXX` trigger <add>func (b *Builder) checkDispatch(ast *parser.Node, onbuild bool) error { <add> cmd := ast.Value <add> upperCasedCmd := strings.ToUpper(cmd) <add> <add> // To ensure the user is given a decent error message if the platform <add> // on which the daemon is running does not support a builder command. <add> if err := platformSupports(strings.ToLower(cmd)); err != nil { <add> return err <add> } <add> <add> // The instruction itself is ONBUILD, we will make sure it follows with at <add> // least one argument <add> if upperCasedCmd == "ONBUILD" { <add> if ast.Next == nil { <add> return fmt.Errorf("ONBUILD requires at least one argument") <add> } <add> } <add> <add> // The instruction is part of ONBUILD trigger (not the instruction itself) <add> if onbuild { <add> switch upperCasedCmd { <add> case "ONBUILD": <add> return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") <add> case "MAINTAINER", "FROM": <add> return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", upperCasedCmd) <add> } <add> } <add> <add> if _, ok := evaluateTable[cmd]; ok { <add> return nil <add> } <add> <add> return fmt.Errorf("Unknown instruction: %s", upperCasedCmd) <add>} <ide><path>builder/dockerfile/internals.go <ide> func (b *Builder) processImageFrom(img builder.Image) error { <ide> } <ide> <ide> total := len(ast.Children) <del> for i, n := range ast.Children { <del> switch strings.ToUpper(n.Value) { <del> case "ONBUILD": <del> return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") <del> case "MAINTAINER", "FROM": <del> return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", n.Value) <add> for _, n := range ast.Children { <add> if err := b.checkDispatch(n, true); err != nil { <add> return err <ide> } <del> <add> } <add> for i, n := range ast.Children { <ide> if err := b.dispatch(i, total, n); err != nil { <ide> return err <ide> } <ide><path>cli/command/image/build.go <ide> func runBuild(dockerCli *command.DockerCli, options buildOptions) error { <ide> <ide> response, err := dockerCli.Client().ImageBuild(ctx, body, buildOptions) <ide> if err != nil { <add> if options.quiet { <add> fmt.Fprintf(dockerCli.Err(), "%s", progBuff) <add> } <ide> return err <ide> } <ide> defer response.Body.Close() <ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildStepsWithProgress(c *check.C) { <ide> c.Assert(out, checker.Contains, fmt.Sprintf("Step %d/%d : RUN echo foo", i, 1+totalRun)) <ide> } <ide> } <add> <add>func (s *DockerSuite) TestBuildWithFailure(c *check.C) { <add> name := "testbuildwithfailure" <add> <add> // First test case can only detect `nobody` in runtime so all steps will show up <add> buildCmd := "FROM busybox\nRUN nobody" <add> _, stdout, _, err := buildImageWithStdoutStderr(name, buildCmd, false, "--force-rm", "--rm") <add> c.Assert(err, checker.NotNil) <add> c.Assert(stdout, checker.Contains, "Step 1/2 : FROM busybox") <add> c.Assert(stdout, checker.Contains, "Step 2/2 : RUN nobody") <add> <add> // Second test case `FFOM` should have been detected before build runs so no steps <add> buildCmd = "FFOM nobody\nRUN nobody" <add> _, stdout, _, err = buildImageWithStdoutStderr(name, buildCmd, false, "--force-rm", "--rm") <add> c.Assert(err, checker.NotNil) <add> c.Assert(stdout, checker.Not(checker.Contains), "Step 1/2 : FROM busybox") <add> c.Assert(stdout, checker.Not(checker.Contains), "Step 2/2 : RUN nobody") <add>}
5
Javascript
Javascript
fix hidden control text in progress bar (fixes )
70a71ae81e5026faf38fc0d675521d66847d8411
<ide><path>src/js/control-bar/progress-control/load-progress-bar.js <ide> class LoadProgressBar extends Component { <ide> createEl() { <ide> return super.createEl('div', { <ide> className: 'vjs-load-progress', <del> innerHTML: `<span class="vjs-control-text"><span>${this.localize('Loaded')}</span>: 0%</span>` <add> innerHTML: `<span class="vjs-control-text"><span>${this.localize('Loaded')}</span>: <span class="vjs-control-text-loaded-percentage">0%</span></span>` <ide> }); <ide> } <ide> <ide> class LoadProgressBar extends Component { <ide> const duration = liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration(); <ide> const bufferedEnd = this.player_.bufferedEnd(); <ide> const children = this.partEls_; <add> const controlTextPercentage = this.$('.vjs-control-text-loaded-percentage'); <ide> <ide> // get the percent width of a time compared to the total end <del> const percentify = function(time, end) { <add> const percentify = function(time, end, rounded) { <ide> // no NaN <del> const percent = (time / end) || 0; <add> let percent = (time / end) || 0; <ide> <del> return ((percent >= 1 ? 1 : percent) * 100) + '%'; <add> percent = (percent >= 1 ? 1 : percent) * 100; <add> <add> if (rounded) { <add> percent = percent.toFixed(2); <add> } <add> <add> return percent + '%'; <ide> }; <ide> <ide> // update the width of the progress bar <ide> this.el_.style.width = percentify(bufferedEnd, duration); <ide> <add> // update the control-text <add> Dom.textContent(controlTextPercentage, percentify(bufferedEnd, duration, true)); <add> <ide> // add child elements to represent the individual buffered time ranges <ide> for (let i = 0; i < buffered.length; i++) { <ide> const start = buffered.start(i); <ide><path>src/js/control-bar/progress-control/play-progress-bar.js <ide> class PlayProgressBar extends Component { <ide> */ <ide> createEl() { <ide> return super.createEl('div', { <del> className: 'vjs-play-progress vjs-slider-bar', <del> innerHTML: `<span class="vjs-control-text"><span>${this.localize('Progress')}</span>: 0%</span>` <add> className: 'vjs-play-progress vjs-slider-bar' <add> }, { <add> 'aria-hidden': 'true' <ide> }); <ide> } <ide> <ide><path>src/js/control-bar/progress-control/time-tooltip.js <ide> class TimeTooltip extends Component { <ide> createEl() { <ide> return super.createEl('div', { <ide> className: 'vjs-time-tooltip' <add> }, { <add> 'aria-hidden': 'true' <ide> }); <ide> } <ide>
3
Python
Python
fix function name in airflow/stats.py
c5349fd638cc9c3d3e23406e23186baed150e641
<ide><path>airflow/stats.py <ide> def stat_name_default_handler(stat_name, max_length=250) -> str: <ide> return stat_name <ide> <ide> <del>def get_current_handle_stat_name_func() -> Callable[[str], str]: <add>def get_current_handler_stat_name_func() -> Callable[[str], str]: <ide> """Get Stat Name Handler from airflow.cfg""" <ide> return conf.getimport('scheduler', 'stat_name_handler') or stat_name_default_handler <ide> <ide> def validate_stat(fn): <ide> @wraps(fn) <ide> def wrapper(_self, stat, *args, **kwargs): <ide> try: <del> handle_stat_name_func = get_current_handle_stat_name_func() <del> stat_name = handle_stat_name_func(stat) <add> handler_stat_name_func = get_current_handler_stat_name_func() <add> stat_name = handler_stat_name_func(stat) <ide> return fn(_self, stat_name, *args, **kwargs) <ide> except InvalidStatsNameException: <ide> log.error('Invalid stat name: %s.', stat, exc_info=True)
1
Ruby
Ruby
use parens and silence ambiguous args warnings
88d8ca2ef976ea802657c92a3d27e2737247ee5c
<ide><path>railties/test/generators/plugin_new_generator_test.rb <ide> def test_generating_test_files_in_full_mode <ide> <ide> def test_ensure_that_plugin_options_are_not_passed_to_app_generator <ide> FileUtils.cd(Rails.root) <del> assert_no_match /It works from file!.*It works_from_file/, run_generator([destination_root, "-m", "lib/template.rb"]) <add> assert_no_match(/It works from file!.*It works_from_file/, run_generator([destination_root, "-m", "lib/template.rb"])) <ide> end <ide> <ide> def test_ensure_that_test_dummy_can_be_generated_from_a_template <ide> def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given <ide> def test_ensure_that_skip_active_record_option_is_passed_to_app_generator <ide> run_generator [destination_root, "--skip_active_record"] <ide> assert_no_file "test/dummy/config/database.yml" <del> assert_no_match /ActiveRecord/, File.read(File.join(destination_root, "test/test_helper.rb")) <add> assert_no_match(/ActiveRecord/, File.read(File.join(destination_root, "test/test_helper.rb"))) <ide> end <ide> <ide> def test_ensure_that_database_option_is_passed_to_app_generator <ide> def test_ensure_that_skip_javascript_option_is_passed_to_app_generator <ide> <ide> def test_template_from_dir_pwd <ide> FileUtils.cd(Rails.root) <del> assert_match /It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"]) <add> assert_match(/It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"])) <ide> end <ide> <ide> def test_ensure_that_tests_works <ide> run_generator <ide> FileUtils.cd destination_root <ide> `bundle install` <del> assert_match /1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test` <add> assert_match(/1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`) <ide> end <ide> <ide> def test_ensure_that_tests_works_in_full_mode <ide> run_generator [destination_root, "--full", "--skip_active_record"] <ide> FileUtils.cd destination_root <ide> `bundle install` <del> assert_match /2 tests, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test` <add> assert_match(/2 tests, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test`) <ide> end <ide> <ide> def test_creating_engine_in_full_mode <ide> def test_creating_engine_in_full_mode <ide> end <ide> <ide> def test_being_quiet_while_creating_dummy_application <del> assert_no_match /create\s+config\/application.rb/, run_generator <add> assert_no_match(/create\s+config\/application.rb/, run_generator) <ide> end <ide> <ide> def test_create_mountable_application_with_mountable_option <ide><path>railties/test/generators/shared_generator_tests.rb <ide> def test_plugin_new_generate_pretend <ide> <ide> def test_invalid_database_option_raises_an_error <ide> content = capture(:stderr){ run_generator([destination_root, "-d", "unknown"]) } <del> assert_match /Invalid value for \-\-database option/, content <add> assert_match(/Invalid value for \-\-database option/, content) <ide> end <ide> <ide> def test_test_unit_is_skipped_if_required <ide> def test_test_unit_is_skipped_if_required <ide> <ide> def test_options_before_application_name_raises_an_error <ide> content = capture(:stderr){ run_generator(["--pretend", destination_root]) } <del> assert_match /Options should be given after the \w+ name. For details run: rails( plugin)? --help\n/, content <add> assert_match(/Options should be given after the \w+ name. For details run: rails( plugin)? --help\n/, content) <ide> end <ide> <ide> def test_name_collision_raises_an_error <ide> reserved_words = %w[application destroy plugin runner test] <ide> reserved_words.each do |reserved| <ide> content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] } <del> assert_match /Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words.\n/, content <add> assert_match(/Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words.\n/, content) <ide> end <ide> end <ide> <ide> def test_name_raises_an_error_if_name_already_used_constant <ide> %w{ String Hash Class Module Set Symbol }.each do |ruby_class| <ide> content = capture(:stderr){ run_generator [File.join(destination_root, ruby_class)] } <del> assert_match /Invalid \w+ name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another \w+ name.\n/, content <add> assert_match(/Invalid \w+ name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another \w+ name.\n/, content) <ide> end <ide> end <ide> <ide> def test_shebang_when_is_the_same_as_default_use_env <ide> <ide> def test_template_raises_an_error_with_invalid_path <ide> content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) } <del> assert_match /The template \[.*\] could not be loaded/, content <del> assert_match /non\/existant\/path/, content <add> assert_match(/The template \[.*\] could not be loaded/, content) <add> assert_match(/non\/existant\/path/, content) <ide> end <ide> <ide> def test_template_is_executed_when_supplied <ide> def test_template_is_executed_when_supplied <ide> template.instance_eval "def read; self; end" # Make the string respond to read <ide> <ide> generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) <del> assert_match /It works!/, silence(:stdout){ generator.invoke_all } <add> assert_match(/It works!/, silence(:stdout){ generator.invoke_all }) <ide> end <ide> <ide> def test_dev_option <ide> def test_edge_option <ide> <ide> def test_template_raises_an_error_with_invalid_path <ide> content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) } <del> assert_match /The template \[.*\] could not be loaded/, content <del> assert_match /non\/existant\/path/, content <add> assert_match(/The template \[.*\] could not be loaded/, content) <add> assert_match(/non\/existant\/path/, content) <ide> end <ide> <ide> def test_template_is_executed_when_supplied <ide> def test_template_is_executed_when_supplied <ide> template.instance_eval "def read; self; end" # Make the string respond to read <ide> <ide> generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) <del> assert_match /It works!/, silence(:stdout){ generator.invoke_all } <add> assert_match(/It works!/, silence(:stdout){ generator.invoke_all }) <ide> end <ide> <ide> def test_template_is_executed_when_supplied_an_https_path <ide> def test_template_is_executed_when_supplied_an_https_path <ide> template.instance_eval "def read; self; end" # Make the string respond to read <ide> <ide> generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) <del> assert_match /It works!/, silence(:stdout){ generator.invoke_all } <add> assert_match(/It works!/, silence(:stdout){ generator.invoke_all }) <ide> end <ide> <ide> def test_dev_option <ide> def test_builder_option_with_http <ide> generator([destination_root], :builder => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) <ide> capture(:stdout) { generator.invoke_all } <ide> <del> default_files.each{ |path| assert_no_file path } <add> default_files.each{ |path| assert_no_file(path) } <ide> end <ide> end
2
Python
Python
remove whitespace, useless comment
7f1eb97000d9ad3be1d227078dadd6ce9852193a
<ide><path>keras/layers/convolutional.py <ide> def get_output(self, train=False): <ide> border_mode=border_mode, <ide> subsample=self.subsample) <ide> if self.border_mode == 'same': <del> shift_x = (self.nb_row - 1) // 2 <del> shift_y = (self.nb_col - 1) // 2 <del> conv_out = conv_out[:, :, shift_x:X.shape[2] + shift_x, shift_y:X.shape[3] + shift_y] <add> shift_x = (self.nb_row - 1) // 2 <add> shift_y = (self.nb_col - 1) // 2 <add> conv_out = conv_out[:, :, shift_x:X.shape[2] + shift_x, shift_y:X.shape[3] + shift_y] <ide> <ide> return self.activation(conv_out + self.b.dimshuffle('x', 0, 'x', 'x')) <ide> <ide><path>tests/auto/test_shape_inference.py <ide> def test_Convolution2D(self): <ide> if (subsample[0] > 1 or subsample[1] > 1) and border_mode == 'same': <ide> continue <ide> for input_data_shape in [(2, 1, 3, 3), (2, 1, 4, 4)]: <del> print 'border_mode:', border_mode <del> print 'subsample:', subsample <del> print 'input_data_shape:', input_data_shape <ide> layer = Convolution2D(nb_filter=1, stack_size=1, nb_row=nb_row, nb_col=nb_row, <ide> border_mode=border_mode, subsample=subsample) <ide> input_data = np.random.random(input_data_shape)
2
Javascript
Javascript
pass the priority level along to children
e53f0dc4b44f08b354f24acb2e22ce1349dfc76f
<ide><path>src/renderers/shared/fiber/ReactChildFiber.js <ide> <ide> import type { ReactCoroutine, ReactYield } from 'ReactCoroutine'; <ide> import type { Fiber } from 'ReactFiber'; <add>import type { PriorityLevel } from 'ReactPriorityLevel'; <ide> <ide> import type { ReactNodeList } from 'ReactTypes'; <ide> <ide> var { <ide> var ReactFiber = require('ReactFiber'); <ide> var ReactReifiedYield = require('ReactReifiedYield'); <ide> <del>function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousSibling : Fiber, newChildren) : Fiber { <add>function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousSibling : Fiber, newChildren, priority : PriorityLevel) : Fiber { <ide> if (typeof newChildren !== 'object' || newChildren === null) { <ide> return previousSibling; <ide> } <ide> function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS <ide> element.key === existingChild.key) { <ide> // TODO: This is not sufficient since previous siblings could be new. <ide> // Will fix reconciliation properly later. <del> const clone = ReactFiber.cloneFiber(existingChild); <add> const clone = ReactFiber.cloneFiber(existingChild, priority); <ide> clone.pendingProps = element.props; <ide> clone.child = existingChild.child; <ide> clone.sibling = null; <ide> previousSibling.sibling = clone; <ide> return clone; <ide> } <del> const child = ReactFiber.createFiberFromElement(element); <add> const child = ReactFiber.createFiberFromElement(element, priority); <ide> previousSibling.sibling = child; <ide> child.parent = parent; <ide> return child; <ide> } <ide> <ide> case REACT_COROUTINE_TYPE: { <ide> const coroutine = (newChildren : ReactCoroutine); <del> const child = ReactFiber.createFiberFromCoroutine(coroutine); <add> const child = ReactFiber.createFiberFromCoroutine(coroutine, priority); <ide> previousSibling.sibling = child; <ide> child.parent = parent; <ide> return child; <ide> function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS <ide> case REACT_YIELD_TYPE: { <ide> const yieldNode = (newChildren : ReactYield); <ide> const reifiedYield = ReactReifiedYield.createReifiedYield(yieldNode); <del> const child = ReactFiber.createFiberFromYield(yieldNode); <add> const child = ReactFiber.createFiberFromYield(yieldNode, priority); <ide> child.output = reifiedYield; <ide> previousSibling.sibling = child; <ide> child.parent = parent; <ide> function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS <ide> let prev : Fiber = previousSibling; <ide> let existing : ?Fiber = existingChild; <ide> for (var i = 0; i < newChildren.length; i++) { <del> prev = createSubsequentChild(parent, existing, prev, newChildren[i]); <add> prev = createSubsequentChild(parent, existing, prev, newChildren[i], priority); <ide> if (prev && existing) { <ide> // TODO: This is not correct because there could've been more <ide> // than one sibling consumed but I don't want to return a tuple. <ide> function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS <ide> } <ide> } <ide> <del>function createFirstChild(parent, existingChild, newChildren) { <add>function createFirstChild(parent, existingChild, newChildren, priority) { <ide> if (typeof newChildren !== 'object' || newChildren === null) { <ide> return null; <ide> } <ide> function createFirstChild(parent, existingChild, newChildren) { <ide> element.type === existingChild.type && <ide> element.key === existingChild.key) { <ide> // Get the clone of the existing fiber. <del> const clone = ReactFiber.cloneFiber(existingChild); <add> const clone = ReactFiber.cloneFiber(existingChild, priority); <ide> clone.pendingProps = element.props; <ide> clone.child = existingChild.child; <ide> clone.sibling = null; <ide> return clone; <ide> } <del> const child = ReactFiber.createFiberFromElement(element); <add> const child = ReactFiber.createFiberFromElement(element, priority); <ide> child.parent = parent; <ide> return child; <ide> } <ide> <ide> case REACT_COROUTINE_TYPE: { <ide> const coroutine = (newChildren : ReactCoroutine); <del> const child = ReactFiber.createFiberFromCoroutine(coroutine); <add> const child = ReactFiber.createFiberFromCoroutine(coroutine, priority); <ide> child.parent = parent; <ide> return child; <ide> } <ide> function createFirstChild(parent, existingChild, newChildren) { <ide> // the fragment. <ide> const yieldNode = (newChildren : ReactYield); <ide> const reifiedYield = ReactReifiedYield.createReifiedYield(yieldNode); <del> const child = ReactFiber.createFiberFromYield(yieldNode); <add> const child = ReactFiber.createFiberFromYield(yieldNode, priority); <ide> child.output = reifiedYield; <ide> child.parent = parent; <ide> return child; <ide> function createFirstChild(parent, existingChild, newChildren) { <ide> var existing : ?Fiber = existingChild; <ide> for (var i = 0; i < newChildren.length; i++) { <ide> if (prev == null) { <del> prev = createFirstChild(parent, existing, newChildren[i]); <add> prev = createFirstChild(parent, existing, newChildren[i], priority); <ide> first = prev; <ide> } else { <del> prev = createSubsequentChild(parent, existing, prev, newChildren[i]); <add> prev = createSubsequentChild(parent, existing, prev, newChildren[i], priority); <ide> } <ide> if (prev && existing) { <ide> // TODO: This is not correct because there could've been more <ide> function createFirstChild(parent, existingChild, newChildren) { <ide> <ide> // TODO: This API won't work because we'll need to transfer the side-effects of <ide> // unmounting children to the parent. <del>exports.reconcileChildFibers = function(parent : Fiber, currentFirstChild : ?Fiber, newChildren : ReactNodeList) : ?Fiber { <del> return createFirstChild(parent, currentFirstChild, newChildren); <add>exports.reconcileChildFibers = function(parent : Fiber, currentFirstChild : ?Fiber, newChildren : ReactNodeList, priority : PriorityLevel) : ?Fiber { <add> return createFirstChild(parent, currentFirstChild, newChildren, priority); <ide> }; <ide><path>src/renderers/shared/fiber/ReactFiber.js <ide> function shouldConstruct(Component) { <ide> } <ide> <ide> // This is used to create an alternate fiber to do work on. <del>exports.cloneFiber = function(fiber : Fiber) : Fiber { <add>exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fiber { <ide> // We use a double buffering pooling technique because we know that we'll only <ide> // ever need at most two versions of a tree. We pool the "other" unused node <ide> // that we're free to reuse. This is lazily created to avoid allocating extra <ide> // objects for things that are never updated. It also allow us to reclaim the <ide> // extra memory if needed. <ide> if (fiber.alternate) { <add> fiber.alternate.pendingWorkPriority = priorityLevel; <ide> return fiber.alternate; <ide> } <ide> // This should not have an alternate already <ide> exports.cloneFiber = function(fiber : Fiber) : Fiber { <ide> alt.type = fiber.type; <ide> alt.stateNode = fiber.stateNode; <ide> alt.alternate = fiber; <add> alt.pendingWorkPriority = priorityLevel; <ide> fiber.alternate = alt; <ide> return alt; <ide> }; <ide> <del>exports.createHostContainerFiber = function(containerInfo : ?Object) { <add>exports.createHostContainerFiber = function(containerInfo : ?Object, priorityLevel : PriorityLevel) { <ide> const fiber = createFiber(HostContainer, null); <ide> fiber.stateNode = containerInfo; <add> fiber.pendingWorkPriority = priorityLevel; <ide> return fiber; <ide> }; <ide> <del>exports.createFiberFromElement = function(element : ReactElement) { <add>exports.createFiberFromElement = function(element : ReactElement, priorityLevel : PriorityLevel) { <ide> const fiber = exports.createFiberFromElementType(element.type, element.key); <ide> fiber.pendingProps = element.props; <add> fiber.pendingWorkPriority = priorityLevel; <ide> return fiber; <ide> }; <ide> <ide> exports.createFiberFromElementType = function(type : mixed, key : null | string) <ide> return fiber; <ide> }; <ide> <del>exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine) { <add>exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine, priorityLevel : PriorityLevel) { <ide> const fiber = createFiber(CoroutineComponent, coroutine.key); <ide> fiber.type = coroutine.handler; <ide> fiber.pendingProps = coroutine; <add> fiber.pendingWorkPriority = priorityLevel; <ide> return fiber; <ide> }; <ide> <del>exports.createFiberFromYield = function(yieldNode : ReactYield) { <add>exports.createFiberFromYield = function(yieldNode : ReactYield, priorityLevel : PriorityLevel) { <ide> const fiber = createFiber(YieldComponent, yieldNode.key); <ide> return fiber; <ide> }; <ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js <ide> var { <ide> } = ReactTypeOfWork; <ide> <ide> function reconcileChildren(current, workInProgress, nextChildren) { <add> const priority = workInProgress.pendingWorkPriority; <ide> workInProgress.child = ReactChildFiber.reconcileChildFibers( <ide> workInProgress, <ide> current ? current.child : null, <del> nextChildren <add> nextChildren, <add> priority <ide> ); <ide> } <ide> <ide><path>src/renderers/shared/fiber/ReactFiberCompleteWork.js <ide> function moveCoroutineToHandlerPhase(current : ?Fiber, workInProgress : Fiber) { <ide> var nextChildren = fn(props, yields); <ide> <ide> var currentFirstChild = current ? current.stateNode : null; <add> // Inherit the priority of the parent. <add> const priority = workInProgress.pendingWorkPriority; <ide> workInProgress.stateNode = ReactChildFiber.reconcileChildFibers( <ide> workInProgress, <ide> currentFirstChild, <del> nextChildren <add> nextChildren, <add> priority <ide> ); <ide> return workInProgress.stateNode; <ide> } <ide><path>src/renderers/shared/fiber/ReactFiberReconciler.js <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> return { <ide> <ide> mountContainer(element : ReactElement<any>, containerInfo : ?Object) : OpaqueNode { <del> const container = ReactFiber.createHostContainerFiber(containerInfo); <add> const container = ReactFiber.createHostContainerFiber(containerInfo, LowPriority); <ide> container.alternate = container; <ide> container.pendingProps = element; <del> container.pendingWorkPriority = LowPriority; <ide> <ide> scheduleLowPriWork(container); <ide>
5
Python
Python
fix model deserialization
35d981241f0274ddd132cd87ee9b47932f1a018f
<ide><path>spacy/util.py <ide> def model_from_bytes(model, bytes_data): <ide> for layer in queue: <ide> if hasattr(layer, '_mem'): <ide> params = weights[i] <del> flat_mem = layer._mem._mem.ravel() <add> layer._mem._get_blob(params.size) <add> layer._mem._i -= params.size <add> flat_mem = layer._mem._mem.ravel() <ide> flat_params = params.ravel() <ide> flat_mem[:flat_params.size] = flat_params <ide> layer._mem._offsets.update(metas[i])
1
Ruby
Ruby
clarify deprecation message for #quoted_id
ae73637e35db20d0c4e14959d8c1274e5399278e
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/quoting.rb <ide> def quote(value) <ide> value = id_value_for_database(value) if value.is_a?(Base) <ide> <ide> if value.respond_to?(:quoted_id) <add> at = value.method(:quoted_id).source_location <add> at &&= " at %s:%d" % at <add> <add> owner = value.method(:quoted_id).owner.to_s <add> klass = value.class.to_s <add> klass += "(#{owner})" unless owner == klass <add> <ide> ActiveSupport::Deprecation.warn \ <del> "Using #quoted_id is deprecated and will be removed in Rails 5.2." <add> "Defining #quoted_id is deprecated and will be ignored in Rails 5.2. (defined on #{klass}#{at})" <ide> return value.quoted_id <ide> end <ide> <ide><path>activerecord/test/cases/quoting_test.rb <ide> def test_quoted_datetime_local <ide> end <ide> end <ide> <add> class QuotedOne <add> def quoted_id <add> 1 <add> end <add> end <add> class SubQuotedOne < QuotedOne <add> end <ide> def test_quote_with_quoted_id <del> assert_deprecated { assert_equal 1, @quoter.quote(Struct.new(:quoted_id).new(1)) } <add> assert_deprecated /defined on \S+::QuotedOne at .*quoting_test\.rb:[0-9]/ do <add> assert_equal 1, @quoter.quote(QuotedOne.new) <add> end <add> <add> assert_deprecated /defined on \S+::SubQuotedOne\(\S+::QuotedOne\) at .*quoting_test\.rb:[0-9]/ do <add> assert_equal 1, @quoter.quote(SubQuotedOne.new) <add> end <ide> end <ide> <ide> def test_quote_nil
2
Text
Text
fix typo 'setup/set up'
73baa673c72a49e9cccfde6e844c7dee2e478d8e
<ide><path>docs/sources/articles/networking.md <ide> illustrate the technique. <ide> $ echo 'DOCKER_OPTS="-b=bridge0"' >> /etc/default/docker <ide> $ sudo service docker start <ide> <del> # Confirming new outgoing NAT masquerade is setup <add> # Confirming new outgoing NAT masquerade is set up <ide> <ide> $ sudo iptables -t nat -L -n <ide> ...
1
Text
Text
add conclusion to tutorial
e3427f4c0b25f40e02520dd25f305384fd4ec874
<ide><path>docs/Networking.md <ide> ws.onclose = (e) => { <ide> console.log(e.code, e.reason); <ide> }; <ide> ``` <add> <add>## High Five! <add> <add>If you've gotten here by reading linearly through the tutorial, then you are a pretty impressive human being. Congratulations. Next, you might want to check out [all the cool stuff the community does with React Native](docs/more-resources.html).
1
Javascript
Javascript
remove duplicate test
6217aff4445e16885e5e05debc19e8bd298a82b2
<ide><path>packages/ember-metal/tests/performance_test.js <ide> <ide> module("Computed Properties - Number of times evaluated"); <ide> <del>test("computed properties that depend on multiple properties should run only once per run loop", function() { <del> var obj = {a: 'a', b: 'b', c: 'c'}; <del> var count = 0; <del> Ember.defineProperty(obj, 'abc', Ember.computed(function(key) { <del> count++; <del> return 'computed '+key; <del> }).property('a', 'b', 'c')); <del> <del> Ember.beginPropertyChanges(); <del> Ember.set(obj, 'a', 'aa'); <del> Ember.set(obj, 'b', 'bb'); <del> Ember.set(obj, 'c', 'cc'); <del> Ember.endPropertyChanges(); <del> <del> Ember.get(obj, 'abc'); <del> <del> equal(count, 1, "The computed property is only invoked once"); <del>}); <del> <ide> test("computed properties that depend on multiple properties should run only once per run loop", function() { <ide> var obj = {a: 'a', b: 'b', c: 'c'}; <ide> var cpCount = 0, obsCount = 0;
1
Ruby
Ruby
replace closedtransaction with nulltransaction
057c23715434adcab9b12f987d615979d1f57549
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/transaction.rb <ide> def savepoint_name <ide> end <ide> end <ide> <del> class ClosedTransaction < Transaction #:nodoc: <del> def initialize; super(nil); end <add> class NullTransaction < Transaction #:nodoc: <add> def initialize; end <ide> def closed?; true; end <ide> def open?; false; end <ide> def joinable?; false; end <ide> def open_transactions <ide> end <ide> <ide> def current_transaction <del> @stack.last || closed_transaction <add> @stack.last || NULL_TRANSACTION <ide> end <ide> <ide> private <del> <del> def closed_transaction <del> @closed_transaction ||= ClosedTransaction.new <del> end <add> NULL_TRANSACTION = NullTransaction.new <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> module ConnectionAdapters # :nodoc: <ide> <ide> autoload_at 'active_record/connection_adapters/abstract/transaction' do <ide> autoload :TransactionManager <del> autoload :ClosedTransaction <add> autoload :NullTransaction <ide> autoload :RealTransaction <ide> autoload :SavepointTransaction <ide> autoload :TransactionState
2
PHP
PHP
handle array hosts
0920c23efb9d7042d074729f2f70acbfec629c14
<ide><path>src/Illuminate/Database/Schema/MySqlSchemaState.php <ide> protected function baseDumpCommand() <ide> protected function baseVariables(array $config) <ide> { <ide> return [ <del> 'LARAVEL_LOAD_HOST' => $config['host'], <add> 'LARAVEL_LOAD_HOST' => is_array($config['host']) ? $config['host'][0] : $config['host'], <ide> 'LARAVEL_LOAD_PORT' => $config['port'], <ide> 'LARAVEL_LOAD_USER' => $config['username'], <ide> 'LARAVEL_LOAD_PASSWORD' => $config['password'],
1
Ruby
Ruby
fix buildenvironment initializer
8c4569b7c2af62983cfeb241be15d910b3aa15f4
<ide><path>Library/Homebrew/build_environment.rb <ide> class BuildEnvironment <ide> attr_accessor :proc <ide> <ide> def initialize(*settings) <del> @settings = Set.new(settings) <add> @settings = Set.new(*settings) <ide> end <ide> <ide> def merge(*args)
1
Python
Python
remove todo note, since it hasn't been todone
9f0ead95976c379957faf7d3f02eb52bf80a2e17
<ide><path>rest_framework/views.py <ide> def allowed_methods(self): <ide> <ide> @property <ide> def default_response_headers(self): <del> # TODO: deprecate? <ide> # TODO: Only vary by accept if multiple renderers <ide> return { <ide> 'Allow': ', '.join(self.allowed_methods),
1
Ruby
Ruby
add tests for tighter test audit
7d5f0df71d6f5cdaf2406fca862dfc878253c5bb
<ide><path>Library/Homebrew/test/rubocops/class_cop_spec.rb <ide> class Foo < Formula <ide> end <ide> RUBY <ide> end <add> <add> it "reports an offense when there is an empty test block" do <add> expect_offense(<<~RUBY) <add> class Foo < Formula <add> url 'https://example.com/foo-1.0.tgz' <add> <add> test do <add> ^^^^^^^ `test do` should not be empty <add> end <add> end <add> RUBY <add> end <add> <add> it "reports an offense when test is falsely true" do <add> expect_offense(<<~RUBY) <add> class Foo < Formula <add> url 'https://example.com/foo-1.0.tgz' <add> <add> test do <add> ^^^^^^^ `test do` should contain a real test <add> true <add> end <add> end <add> RUBY <add> end <ide> end
1
Javascript
Javascript
use callback helper on ticks.callback
7d08bab45d57060af5ca84b464b2281da22c8938
<ide><path>src/scales/scale.time.js <ide> import adapters from '../core/core.adapters'; <del>import {isFinite, isNullOrUndef, mergeIf, valueOrDefault} from '../helpers/helpers.core'; <add>import {callback as call, isFinite, isNullOrUndef, mergeIf, valueOrDefault} from '../helpers/helpers.core'; <ide> import {toRadians, isNumber, _limitValue} from '../helpers/helpers.math'; <ide> import Scale from '../core/core.scale'; <ide> import {_arrayUnique, _filterBetween, _lookup} from '../helpers/helpers.collection'; <ide> export default class TimeScale extends Scale { <ide> const major = majorUnit && majorFormat && tick && tick.major; <ide> const label = me._adapter.format(time, format || (major ? majorFormat : minorFormat)); <ide> const formatter = options.ticks.callback; <del> return formatter ? formatter(label, index, ticks) : label; <add> return formatter ? call(formatter, [label, index, ticks], me) : label; <ide> } <ide> <ide> /**
1
Ruby
Ruby
test version interrogation methods
3081e697832e8addd5fa7cfc19b4bc8f3922c256
<ide><path>Library/Homebrew/test/test_versions.rb <ide> def test_macos_version_comparison <ide> assert v == :snow_leopard <ide> assert v < :lion <ide> end <add> <add> def test_version_interrogation <add> v = Version.new("1.1alpha1") <add> assert v.alpha? <add> v = Version.new("1.0beta2") <add> assert v.devel? <add> assert v.beta? <add> v = Version.new("1.0rc-1") <add> assert v.devel? <add> assert v.rc? <add> end <ide> end <ide> <ide> class VersionParsingTests < Test::Unit::TestCase
1
Python
Python
simplify celerykubernetesexecutor tests
10be37513c420515251996602ca9362dfeeb095f
<ide><path>tests/executors/test_celery_kubernetes_executor.py <ide> # under the License. <ide> from unittest import mock <ide> <add>from parameterized import parameterized <add> <add>from airflow.executors.celery_executor import CeleryExecutor <ide> from airflow.executors.celery_kubernetes_executor import CeleryKubernetesExecutor <add>from airflow.executors.kubernetes_executor import KubernetesExecutor <add> <add>KUBERNETES_QUEUE = CeleryKubernetesExecutor.KUBERNETES_QUEUE <ide> <ide> <ide> class TestCeleryKubernetesExecutor: <ide> def test_start(self): <ide> celery_executor_mock.start.assert_called() <ide> k8s_executor_mock.start.assert_called() <ide> <del> def test_queue_command(self): <del> command = ['airflow', 'run', 'dag'] <del> priority = 1 <del> queue = 'default' <del> <del> def when_using_k8s_executor(): <del> celery_executor_mock = mock.MagicMock() <del> k8s_executor_mock = mock.MagicMock() <del> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <del> <del> simple_task_instance = mock.MagicMock() <del> simple_task_instance.queue = CeleryKubernetesExecutor.KUBERNETES_QUEUE <del> <del> cke.queue_command(simple_task_instance, command, priority, queue) <del> <del> k8s_executor_mock.queue_command.assert_called_once_with( <del> simple_task_instance, command, priority, queue <del> ) <del> celery_executor_mock.queue_command.assert_not_called() <del> <del> def when_using_celery_executor(): <del> celery_executor_mock = mock.MagicMock() <del> k8s_executor_mock = mock.MagicMock() <del> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <del> <del> simple_task_instance = mock.MagicMock() <del> simple_task_instance.queue = 'non-kubernetes-queue' <del> <del> cke.queue_command(simple_task_instance, command, priority, queue) <del> <del> celery_executor_mock.queue_command.assert_called_once_with( <del> simple_task_instance, command, priority, queue <del> ) <del> k8s_executor_mock.queue_command.assert_not_called() <del> <del> when_using_k8s_executor() <del> when_using_celery_executor() <del> <del> def test_queue_task_instance(self): <del> mark_success = False <del> pickle_id = None <del> ignore_all_deps = False <del> ignore_depends_on_past = False <del> ignore_task_deps = False <del> ignore_ti_state = False <del> pool = None <del> cfg_path = None <del> <del> def when_using_k8s_executor(): <del> celery_executor_mock = mock.MagicMock() <del> k8s_executor_mock = mock.MagicMock() <del> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <add> @parameterized.expand( <add> [ <add> ('any-other-queue',), <add> (KUBERNETES_QUEUE,), <add> ] <add> ) <add> @mock.patch.object(CeleryExecutor, 'queue_command') <add> @mock.patch.object(KubernetesExecutor, 'queue_command') <add> def test_queue_command(self, test_queue, k8s_queue_cmd, celery_queue_cmd): <add> kwargs = dict( <add> command=['airflow', 'run', 'dag'], <add> priority=1, <add> queue='default', <add> ) <add> kwarg_values = kwargs.values() <add> cke = CeleryKubernetesExecutor(CeleryExecutor(), KubernetesExecutor()) <add> <add> simple_task_instance = mock.MagicMock() <add> simple_task_instance.queue = test_queue <add> <add> cke.queue_command(simple_task_instance, **kwargs) <add> <add> if test_queue == KUBERNETES_QUEUE: <add> k8s_queue_cmd.assert_called_once_with(simple_task_instance, *kwarg_values) <add> celery_queue_cmd.assert_not_called() <add> else: <add> celery_queue_cmd.assert_called_once_with(simple_task_instance, *kwarg_values) <add> k8s_queue_cmd.assert_not_called() <add> <add> @parameterized.expand( <add> [ <add> ('any-other-queue',), <add> (KUBERNETES_QUEUE,), <add> ] <add> ) <add> def test_queue_task_instance(self, test_queue): <add> celery_executor_mock = mock.MagicMock() <add> k8s_executor_mock = mock.MagicMock() <add> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <ide> <del> ti = mock.MagicMock() <del> ti.queue = CeleryKubernetesExecutor.KUBERNETES_QUEUE <del> <del> cke.queue_task_instance( <del> ti, <del> mark_success, <del> pickle_id, <del> ignore_all_deps, <del> ignore_depends_on_past, <del> ignore_task_deps, <del> ignore_ti_state, <del> pool, <del> cfg_path, <del> ) <del> <del> k8s_executor_mock.queue_task_instance.assert_called_once_with( <del> ti, <del> mark_success, <del> pickle_id, <del> ignore_all_deps, <del> ignore_depends_on_past, <del> ignore_task_deps, <del> ignore_ti_state, <del> pool, <del> cfg_path, <del> ) <add> ti = mock.MagicMock() <add> ti.queue = test_queue <add> <add> kwargs = dict( <add> task_instance=ti, <add> mark_success=False, <add> pickle_id=None, <add> ignore_all_deps=False, <add> ignore_depends_on_past=False, <add> ignore_task_deps=False, <add> ignore_ti_state=False, <add> pool=None, <add> cfg_path=None, <add> ) <add> kwarg_values = kwargs.values() <add> cke.queue_task_instance(**kwargs) <add> if test_queue == KUBERNETES_QUEUE: <add> k8s_executor_mock.queue_task_instance.assert_called_once_with(*kwarg_values) <ide> celery_executor_mock.queue_task_instance.assert_not_called() <del> <del> def when_using_celery_executor(): <del> celery_executor_mock = mock.MagicMock() <del> k8s_executor_mock = mock.MagicMock() <del> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <del> <del> ti = mock.MagicMock() <del> ti.queue = 'non-kubernetes-queue' <del> <del> cke.queue_task_instance( <del> ti, <del> mark_success, <del> pickle_id, <del> ignore_all_deps, <del> ignore_depends_on_past, <del> ignore_task_deps, <del> ignore_ti_state, <del> pool, <del> cfg_path, <del> ) <del> <add> else: <add> celery_executor_mock.queue_task_instance.assert_called_once_with(*kwarg_values) <ide> k8s_executor_mock.queue_task_instance.assert_not_called() <del> celery_executor_mock.queue_task_instance.assert_called_once_with( <del> ti, <del> mark_success, <del> pickle_id, <del> ignore_all_deps, <del> ignore_depends_on_past, <del> ignore_task_deps, <del> ignore_ti_state, <del> pool, <del> cfg_path, <del> ) <del> <del> when_using_k8s_executor() <del> when_using_celery_executor() <del> <del> def test_has_tasks(self): <del> ti = mock.MagicMock <del> <del> def when_ti_in_k8s_executor(): <del> celery_executor_mock = mock.MagicMock() <del> k8s_executor_mock = mock.MagicMock() <del> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <del> <del> celery_executor_mock.has_task.return_value = False <del> k8s_executor_mock.has_task.return_value = True <del> <del> assert cke.has_task(ti) <del> celery_executor_mock.has_task.assert_called_once_with(ti) <del> k8s_executor_mock.has_task.assert_called_once_with(ti) <del> <del> def when_ti_in_celery_executor(): <del> celery_executor_mock = mock.MagicMock() <del> k8s_executor_mock = mock.MagicMock() <del> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <del> <del> celery_executor_mock.has_task.return_value = True <del> <del> assert cke.has_task(ti) <del> celery_executor_mock.has_task.assert_called_once_with(ti) <del> <del> when_ti_in_k8s_executor() <del> when_ti_in_celery_executor() <del> <del> def test_adopt_tasks(self): <del> ti = mock.MagicMock <ide> <del> def when_ti_in_k8s_executor(): <del> celery_executor_mock = mock.MagicMock() <del> k8s_executor_mock = mock.MagicMock() <del> ti.queue = "kubernetes" <del> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <del> <del> celery_executor_mock.try_adopt_task_instances.return_value = [] <del> k8s_executor_mock.try_adopt_task_instances.return_value = [] <add> @parameterized.expand( <add> [ <add> (True, True, True), <add> (False, True, True), <add> (True, False, True), <add> (False, False, False), <add> ] <add> ) <add> def test_has_tasks(self, celery_has, k8s_has, cke_has): <add> celery_executor_mock = mock.MagicMock() <add> k8s_executor_mock = mock.MagicMock() <add> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <ide> <del> cke.try_adopt_task_instances([ti]) <del> celery_executor_mock.try_adopt_task_instances.assert_called_once_with([]) <del> k8s_executor_mock.try_adopt_task_instances.assert_called_once_with([ti]) <add> celery_executor_mock.has_task.return_value = celery_has <add> k8s_executor_mock.has_task.return_value = k8s_has <add> ti = mock.MagicMock() <add> assert cke.has_task(ti) == cke_has <add> celery_executor_mock.has_task.assert_called_once_with(ti) <add> if not celery_has: <add> k8s_executor_mock.has_task.assert_called_once_with(ti) <ide> <del> def when_ti_in_celery_executor(): <del> celery_executor_mock = mock.MagicMock() <del> k8s_executor_mock = mock.MagicMock() <del> ti.queue = "default" <del> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <add> @parameterized.expand([(1, 0), (0, 1), (2, 1)]) <add> def test_adopt_tasks(self, num_k8s, num_celery): <add> celery_executor_mock = mock.MagicMock() <add> k8s_executor_mock = mock.MagicMock() <ide> <del> celery_executor_mock.try_adopt_task_instances.return_value = [] <del> k8s_executor_mock.try_adopt_task_instances.return_value = [] <add> def mock_ti(queue): <add> ti = mock.MagicMock() <add> ti.queue = queue <add> return ti <ide> <del> cke.try_adopt_task_instances([ti]) <del> celery_executor_mock.try_adopt_task_instances.assert_called_once_with([ti]) <del> k8s_executor_mock.try_adopt_task_instances.assert_called_once_with([]) <add> celery_tis = [mock_ti('default') for _ in range(num_celery)] <add> k8s_tis = [mock_ti(KUBERNETES_QUEUE) for _ in range(num_k8s)] <ide> <del> when_ti_in_k8s_executor() <del> when_ti_in_celery_executor() <add> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <add> cke.try_adopt_task_instances(celery_tis + k8s_tis) <add> celery_executor_mock.try_adopt_task_instances.assert_called_once_with(celery_tis) <add> k8s_executor_mock.try_adopt_task_instances.assert_called_once_with(k8s_tis) <ide> <ide> def test_get_event_buffer(self): <ide> celery_executor_mock = mock.MagicMock()
1
PHP
PHP
fix incorrect param type
9a9b43e610dbfbcab5b77d584539321f61883097
<ide><path>src/Illuminate/Queue/Listener.php <ide> public function makeProcess($connection, $queue, ListenerOptions $options) <ide> /** <ide> * Add the environment option to the given command. <ide> * <del> * @param string $command <add> * @param array $command <ide> * @param \Illuminate\Queue\ListenerOptions $options <ide> * @return array <ide> */
1
Ruby
Ruby
remove the actual extension file as well [ci skip]
f0129da38572e5cc5b633b7b4cc003808c56ba30
<ide><path>actionpack/lib/action_dispatch/journey/core-ext/hash.rb <del># :stopdoc: <del>if RUBY_VERSION < '1.9' <del>class Hash <del> def keep_if <del> each do |k,v| <del> delete(k) unless yield(k,v) <del> end <del> end <del>end <del>end <del># :startdoc:
1
Python
Python
remove old tf2 bert for squad
3635527dc66cdfe7270e5b3086858db7307df8a3
<ide><path>official/nlp/bert/run_squad.py <ide> 'The maximum length of an answer that can be generated. This is needed ' <ide> 'because the start and end predictions are not conditioned on one another.') <ide> flags.DEFINE_bool( <del> 'use_keras_bert_for_squad', False, 'Whether to use keras BERT for squad ' <del> 'task. Note that when the FLAG "hub_module_url" is specified, ' <del> '"use_keras_bert_for_squad" cannot be True.') <add> 'use_keras_bert_for_squad', True, 'Deprecated and will be removed soon.') <ide> <ide> common_flags.define_common_bert_flags() <ide> <ide> def predict_squad_customized(strategy, input_meta_data, bert_config, <ide> squad_model, _ = bert_models.squad_model( <ide> bert_config, <ide> input_meta_data['max_seq_length'], <del> float_type=tf.float32, <del> use_keras_bert=FLAGS.use_keras_bert_for_squad) <add> float_type=tf.float32) <ide> <ide> checkpoint_path = tf.train.latest_checkpoint(FLAGS.model_dir) <ide> logging.info('Restoring checkpoints from %s', checkpoint_path) <ide> def _get_squad_model(): <ide> bert_config, <ide> max_seq_length, <ide> float_type=tf.float16 if use_float16 else tf.float32, <del> hub_module_url=FLAGS.hub_module_url, <del> use_keras_bert=False <del> if FLAGS.hub_module_url else FLAGS.use_keras_bert_for_squad) <add> hub_module_url=FLAGS.hub_module_url) <ide> squad_model.optimizer = optimization.create_optimizer( <ide> FLAGS.learning_rate, steps_per_epoch * epochs, warmup_steps) <ide> if use_float16: <ide> def export_squad(model_export_path, input_meta_data): <ide> squad_model, _ = bert_models.squad_model( <ide> bert_config, <ide> input_meta_data['max_seq_length'], <del> float_type=tf.float32, <del> use_keras_bert=FLAGS.use_keras_bert_for_squad) <add> float_type=tf.float32) <ide> model_saving_utils.export_bert_model( <ide> model_export_path, model=squad_model, checkpoint_dir=FLAGS.model_dir) <ide> <ide> def main(_): <ide> # Users should always run this script under TF 2.x <ide> assert tf.version.VERSION.startswith('2.') <ide> <add> if not FLAGS.use_keras_bert_for_squad: <add> raise ValueError( <add> 'Old tf2 BERT is no longer supported. Please use keras BERT.') <add> <ide> with tf.io.gfile.GFile(FLAGS.input_meta_data_path, 'rb') as reader: <ide> input_meta_data = json.loads(reader.read().decode('utf-8')) <ide> <ide><path>official/nlp/bert_models.py <ide> def squad_model(bert_config, <ide> max_seq_length, <ide> float_type, <ide> initializer=None, <del> hub_module_url=None, <del> use_keras_bert=False): <add> hub_module_url=None): <ide> """Returns BERT Squad model along with core BERT model to import weights. <ide> <ide> Args: <ide> def squad_model(bert_config, <ide> initializer: Initializer for the final dense layer in the span labeler. <ide> Defaulted to TruncatedNormal initializer. <ide> hub_module_url: TF-Hub path/url to Bert module. <del> use_keras_bert: Whether to use keras BERT. Note that when the above <del> 'hub_module_url' is specified, 'use_keras_bert' cannot be True. <ide> <ide> Returns: <ide> A tuple of (1) keras model that outputs start logits and end logits and <ide> (2) the core BERT transformer encoder. <del> <del> Raises: <del> ValueError: When 'hub_module_url' is specified and 'use_keras_bert' is True. <ide> """ <del> if hub_module_url and use_keras_bert: <del> raise ValueError( <del> 'Cannot use hub_module_url and keras BERT at the same time.') <ide> if initializer is None: <ide> initializer = tf.keras.initializers.TruncatedNormal( <ide> stddev=bert_config.initializer_range) <del> if use_keras_bert: <add> if not hub_module_url: <ide> bert_encoder = _get_transformer_encoder(bert_config, max_seq_length, <ide> float_type) <ide> return bert_span_labeler.BertSpanLabeler( <ide> def squad_model(bert_config, <ide> shape=(max_seq_length,), dtype=tf.int32, name='input_mask') <ide> input_type_ids = tf.keras.layers.Input( <ide> shape=(max_seq_length,), dtype=tf.int32, name='input_type_ids') <del> if hub_module_url: <del> core_model = hub.KerasLayer(hub_module_url, trainable=True) <del> _, sequence_output = core_model( <del> [input_word_ids, input_mask, input_type_ids]) <del> # Sets the shape manually due to a bug in TF shape inference. <del> # TODO(hongkuny): remove this once shape inference is correct. <del> sequence_output.set_shape((None, max_seq_length, bert_config.hidden_size)) <del> else: <del> core_model = modeling.get_bert_model( <del> input_word_ids, <del> input_mask, <del> input_type_ids, <del> config=bert_config, <del> name='bert_model', <del> float_type=float_type) <del> # `BertSquadModel` only uses the sequnce_output which <del> # has dimensionality (batch_size, sequence_length, num_hidden). <del> sequence_output = core_model.outputs[1] <add> core_model = hub.KerasLayer(hub_module_url, trainable=True) <add> _, sequence_output = core_model( <add> [input_word_ids, input_mask, input_type_ids]) <add> # Sets the shape manually due to a bug in TF shape inference. <add> # TODO(hongkuny): remove this once shape inference is correct. <add> sequence_output.set_shape((None, max_seq_length, bert_config.hidden_size)) <ide> <ide> squad_logits_layer = BertSquadLogitsLayer( <ide> initializer=initializer, float_type=float_type, name='squad_logits')
2
Python
Python
add test for deprecated flask.request properties
4d4a639ba46cf72454497bc100b3e811e66af4b2
<ide><path>tests/test_deprecations.py <ide> :copyright: (c) 2014 by Armin Ronacher. <ide> :license: BSD, see LICENSE for more details. <ide> """ <add> <add>import pytest <add> <add>import flask <add> <add> <add>class TestRequestDeprecation(object): <add> <add> def test_request_json(self, catch_deprecation_warnings): <add> """Request.json is deprecated""" <add> app = flask.Flask(__name__) <add> app.testing = True <add> <add> @app.route('/', methods=['POST']) <add> def index(): <add> assert flask.request.json == {'spam': 42} <add> print(flask.request.json) <add> return 'OK' <add> <add> with catch_deprecation_warnings() as captured: <add> c = app.test_client() <add> c.post('/', data='{"spam": 42}', content_type='application/json') <add> <add> assert len(captured) == 1 <add> <add> def test_request_module(self, catch_deprecation_warnings): <add> """Request.module is deprecated""" <add> app = flask.Flask(__name__) <add> app.testing = True <add> <add> @app.route('/') <add> def index(): <add> assert flask.request.module is None <add> return 'OK' <add> <add> with catch_deprecation_warnings() as captured: <add> c = app.test_client() <add> c.get('/') <add> <add> assert len(captured) == 1
1
Python
Python
fix this pr
f0bc684c459df4d75a2bebb2e45a83d2f451b98c
<ide><path>research/object_detection/box_coders/detr_box_coder.py <ide> # limitations under the License. <ide> # ============================================================================== <ide> <del>"""Faster RCNN box coder. <add>"""DETR box coder. <ide> <del>Faster RCNN box coder follows the coding schema described below: <del> ty = (y - ya) / ha <del> tx = (x - xa) / wa <del> th = log(h / ha) <del> tw = log(w / wa) <add>DETR box coder follows the coding schema described below: <add> ty = y <add> tx = x <add> th = h <add> tw = w <ide> where x, y, w, h denote the box's center coordinates, width and height <ide> respectively. Similarly, xa, ya, wa, ha denote the anchor's center <ide> coordinates, width and height. tx, ty, tw and th denote the anchor-encoded <ide> class DETRBoxCoder(box_coder.BoxCoder): <ide> """Faster RCNN box coder.""" <ide> <del> def __init__(self, scale_factors=None): <del> """Constructor for FasterRcnnBoxCoder. <add> def __init__(self): <add> """Constructor for DETRBoxCoder. <ide> <ide> Args: <ide> scale_factors: List of 4 positive scalars to scale ty, tx, th and tw. <ide> If set to None, does not perform scaling. For Faster RCNN, <ide> the open-source implementation recommends using [10.0, 10.0, 5.0, 5.0]. <ide> """ <del> if None: <del> assert len(scale_factors) == 4 <del> for scalar in scale_factors: <del> assert scalar > 0 <del> self._scale_factors = scale_factors <add> pass <ide> <ide> @property <ide> def code_size(self): <ide> def _encode(self, boxes, anchors): <ide> [ty, tx, th, tw]. <ide> """ <ide> # Convert anchors to the center coordinate representation. <del> ycenter, xcenter, h, w = boxes.get_center_coordinates_and_sizes() <del> # Avoid NaN in division and log below. <del> h += EPSILON <del> w += EPSILON <del> <del> tx = xcenter <del> ty = ycenter <del> tw = w #tf.log(w) <del> th = h #tf.log(h) <del> <add> ty, tx, th, tw = boxes.get_center_coordinates_and_sizes() <ide> return tf.transpose(tf.stack([ty, tx, th, tw])) <ide> <ide> def _decode(self, rel_codes, anchors): <ide> def _decode(self, rel_codes, anchors): <ide> boxes: BoxList holding N bounding boxes. <ide> """ <ide> ty, tx, th, tw = tf.unstack(tf.transpose(rel_codes)) <del> <del> w = tw <del> h = th <del> ycenter = ty <del> xcenter = tx <del> ymin = ycenter - h / 2. <del> xmin = xcenter - w / 2. <del> ymax = ycenter + h / 2. <del> xmax = xcenter + w / 2. <add> ymin = ty - th / 2. <add> xmin = tx - tw / 2. <add> ymax = ty + th / 2. <add> xmax = tx + tw / 2. <ide> return box_list.BoxList(tf.transpose(tf.stack([ymin, xmin, ymax, xmax]))) <ide> <ide><path>research/object_detection/core/target_assigner_test.py <ide> def graph_fn(anchor_means, groundtruth_box_corners, <ide> (cls_targets, cls_weights, reg_targets, reg_weights, _) = result <ide> return (cls_targets, cls_weights, reg_targets, reg_weights) <ide> <del> anchor_means = np.array([[0.0, 0.0, 0.4, 0.2], <del> [0.5, 0.5, 1.0, 0.8], <add> anchor_means = np.array([[0.25, 0.25, 0.4, 0.2], <add> [0.5, 0.8, 1.0, 0.8], <ide> [0.9, 0.5, 0.1, 1.0]], dtype=np.float32) <ide> groundtruth_box_corners = np.array([[0.0, 0.0, 0.5, 0.5], <ide> [0.5, 0.5, 0.9, 0.9]], <ide> def graph_fn(anchor_means, groundtruth_box_corners, <ide> groundtruth_labels = np.array([[0.0, 1.0], [0.0, 1.0]], <ide> dtype=np.float32) <ide> <del> exp_cls_targets = [[1], [1], [0]] <del> exp_cls_weights = [[1], [1], [1]] <del> exp_reg_targets = [[0.0, 0.0, 0.5, 0.5], <del> [0.5, 0.5, 0.9, 0.9], <add> exp_cls_targets = [[0, 1], [0, 1], [1, 0]] <add> exp_cls_weights = [[1, 1], [1, 1], [1, 1]] <add> exp_reg_targets = [[0.25, 0.25, 0.5, 0.5], <add> [0.7, 0.7, 0.4, 0.4], <ide> [0, 0, 0, 0]] <ide> exp_reg_weights = [1, 1, 0] <ide> <ide> (cls_targets_out, <ide> cls_weights_out, reg_targets_out, reg_weights_out) = self.execute( <ide> graph_fn, [anchor_means, groundtruth_box_corners, <ide> groundtruth_labels, predicted_labels]) <add> <ide> self.assertAllClose(cls_targets_out, exp_cls_targets) <ide> self.assertAllClose(cls_weights_out, exp_cls_weights) <ide> self.assertAllClose(reg_targets_out, exp_reg_targets)
2
Python
Python
document the blueprint param too
fe1bf3c8213c56e045ead8afa84773f181b3dab6
<ide><path>flask/app.py <ide> def make_null_session(self): <ide> return self.session_interface.make_null_session(self) <ide> <ide> @setupmethod <del> def register_blueprint( <del> self, blueprint, **options <del> ): <add> def register_blueprint(self, blueprint, **options): <ide> """Register a :class:`~flask.Blueprint` on the application. Keyword <ide> arguments passed to this method will override the defaults set on the <ide> blueprint. <ide> <ide> Calls the blueprint's :meth:`~flask.Blueprint.register` method after <ide> recording the blueprint in the application's :attr:`blueprints`. <ide> <add> :param blueprint: The blueprint to register. <ide> :param url_prefix: Blueprint routes will be prefixed with this. <ide> :param subdomain: Blueprint routes will match on this subdomain. <ide> :param url_defaults: Blueprint routes will use these default values for
1
Javascript
Javascript
update apollo example
01cc89845040828c6e1f2bc053ff9c853d1635c5
<ide><path>examples/with-apollo/lib/initClient.js <ide> let apolloClient = null <ide> function createClient (headers) { <ide> return new ApolloClient({ <ide> ssrMode: !process.browser, <del> headers, <ide> dataIdFromObject: result => result.id || null, <ide> networkInterface: createNetworkInterface({ <ide> uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', <ide> opts: { <ide> credentials: 'same-origin' <add> // Pass headers here if your graphql server requires them <ide> } <ide> }) <ide> }) <ide><path>examples/with-apollo/lib/withData.js <ide> export default (Component) => ( <ide> return { <ide> initialState: { <ide> ...state, <del> apollo: { <del> data: state.apollo.data <add> [client.reduxRootKey]: { <add> data: client.getInitialState().data <ide> } <ide> }, <ide> headers,
2
Python
Python
remove references to python 2
e4d1c7781fcd762646c77449690491597c2be82f
<ide><path>numpy/core/code_generators/ufunc_docstrings.py <ide> def add_newdoc(place, name, doc): <ide> <ide> Behavior on division by zero can be changed using ``seterr``. <ide> <del> In Python 2, when both ``x1`` and ``x2`` are of an integer type, <del> ``divide`` will behave like ``floor_divide``. In Python 3, it behaves <del> like ``true_divide``. <add> When both ``x1`` and ``x2`` are of an integer type, equivalent <add> to `numpy.true_divide`. <ide> <ide> Examples <ide> -------- <ide> def add_newdoc(place, name, doc): <ide> [ Inf, 4. , 2.5], <ide> [ Inf, 7. , 4. ]]) <ide> <del> Note the behavior with integer types (Python 2 only): <del> <del> >>> np.divide(2, 4) <del> 0 <del> >>> np.divide(2, 4.) <del> 0.5 <del> <del> Division by zero always yields zero in integer arithmetic (again, <del> Python 2 only), and does not raise an exception or a warning: <del> <del> >>> np.divide(np.array([0, 1], dtype=int), np.array([0, 0], dtype=int)) <del> array([0, 0]) <del> <del> Division by zero can, however, be caught using ``seterr``: <del> <del> >>> old_err_state = np.seterr(divide='raise') <del> >>> np.divide(1, 0) <del> Traceback (most recent call last): <del> File "<stdin>", line 1, in <module> <del> FloatingPointError: divide by zero encountered in divide <del> <ide> >>> ignored_states = np.seterr(**old_err_state) <ide> >>> np.divide(1, 0) <ide> 0 <ide><path>numpy/distutils/ccompiler.py <ide> def CCompiler_compile(self, sources, output_dir=None, macros=None, <ide> If compilation fails. <ide> <ide> """ <del> # This method is effective only with Python >=2.3 distutils. <del> # Any changes here should be applied also to fcompiler.compile <del> # method to support pre Python 2.3 distutils. <ide> global _job_semaphore <ide> <ide> jobs = get_num_build_jobs() <ide><path>numpy/lib/_iotools.py <ide> def _decode_line(line, encoding=None): <ide> <ide> Returns <ide> ------- <del> decoded_line : unicode <del> Unicode in Python 2, a str (unicode) in Python 3. <add> decoded_line : str <ide> <ide> """ <ide> if type(line) is bytes:
3
Ruby
Ruby
handle no /usr/bin/gcc
e526c65566fde66b38b045dabf7fa9c7e28fad20
<ide><path>Library/Homebrew/extend/os/linux/development_tools.rb <ide> def build_system_too_old? <ide> <ide> sig { returns(T::Boolean) } <ide> def system_gcc_too_old? <del> gcc_version("/usr/bin/gcc") < OS::LINUX_GCC_CI_VERSION <add> gcc = "/usr/bin/gcc" <add> return true unless File.exist?(gcc) <add> <add> gcc_version(gcc) < OS::LINUX_GCC_CI_VERSION <ide> end <ide> <ide> sig { returns(T::Hash[String, T.nilable(String)]) }
1
Ruby
Ruby
use rails backtrace in tests
d91bee80beae4e92b2b015599771310cebc3a143
<ide><path>activesupport/lib/active_support/backtrace_cleaner.rb <ide> def clean(backtrace, kind = :silent) <ide> filtered <ide> end <ide> end <add> alias :filter :clean <ide> <ide> # Adds a filter from the block provided. Each line in the backtrace will be <ide> # mapped against this filter. <ide><path>railties/lib/rails/test_help.rb <ide> require 'action_controller/test_case' <ide> require 'action_dispatch/testing/integration' <ide> <add># Config Rails backtrace in tests. <add>require 'rails/backtrace_cleaner' <add>MiniTest.backtrace_filter = Rails.backtrace_cleaner <add> <ide> # Enable turn if it is available <ide> begin <ide> require 'turn'
2
Python
Python
implement ex_open_console for openstack
0cc480ebcc8f6ca75fbae5780e94274b298b7390
<ide><path>libcloud/compute/drivers/openstack.py <ide> def ex_delete_subnet(self, subnet_id): <ide> <ide> return response <ide> <add> def ex_open_console(self, node_id): <add> """ <add> Get remote console URL <add> <add> :param node: node <add> :type node: :class:`Node` <add> <add> :return: Dictionary with the output <add> :rtype: ``dict`` <add> <add> """ <add> microversion = 2.0 # TODO: figure this out dynamically <add> if microversion >= 2.5: <add> data = { <add> "remote_console": { <add> "protocol": "vnc", <add> "type": "novnc" <add> } <add> } <add> uri = '/servers/%s/remote-consoles' <add> else: <add> data = { <add> "os-getVNCConsole": { <add> "type": "novnc" <add> } <add> } <add> uri = '/servers/%s/action' <add> <add> resp = self.connection.request(uri % node_id, <add> method='POST', data=data).object <add> console = resp.get('remote_console') or resp.get('console', {}) <add> return console.get('url') <add> <ide> def ex_get_console_output(self, node, length=None): <ide> """ <ide> Get console output
1
Javascript
Javascript
fix total item counting
f1d23381aaa96e076cf0675f062817c61d24352b
<ide><path>lib/stats/DefaultStatsFactoryPlugin.js <ide> const getTotalSize = children => { <ide> const getTotalItems = children => { <ide> let count = 0; <ide> for (const child of children) { <del> if (child.children) count += getTotalItems(child.children); <del> else if (child.filteredChildren) count += child.filteredChildren; <del> else count++; <add> if (!child.children && !child.filteredChildren) { <add> count++; <add> } else { <add> if (child.children) count += getTotalItems(child.children); <add> if (child.filteredChildren) count += child.filteredChildren; <add> } <ide> } <ide> return count; <ide> };
1
Text
Text
fix typos in docs
57e2a82355c15005875fedc733dc45081af5a2d9
<ide><path>docs/migration.md <ide> instructions that didn’t modify the filesystem. <ide> <ide> Content addressability is the foundation for the new distribution features. The <ide> image pull and push code has been reworked to use a download/upload manager <del>concept that makes pushing and pulling images much more stable and mitigate any <add>concept that makes pushing and pulling images much more stable and mitigates any <ide> parallel request issues. The download manager also brings retries on failed <ide> downloads and better prioritization for concurrent downloads. <ide> <ide><path>docs/security/apparmor.md <ide> Congrats! You just deployed a container secured with a custom apparmor profile! <ide> <ide> ## Debug AppArmor <ide> <del>You can use `demsg` to debug problems and `aa-status` check the loaded profiles. <add>You can use `dmesg` to debug problems and `aa-status` check the loaded profiles. <ide> <ide> ### Use dmesg <ide> <ide><path>docs/security/seccomp.md <ide> CONFIG_SECCOMP=y <ide> <ide> > **Note**: seccomp profiles require seccomp 2.2.1 and are only <ide> > available starting with Debian 9 "Stretch", Ubuntu 15.10 "Wily", <del>> Fedora 22, centos 7 and Oracle Linux 7. To use this feature on Ubuntu 14.04, Debian Wheezy, or <add>> Fedora 22, CentOS 7 and Oracle Linux 7. To use this feature on Ubuntu 14.04, Debian Wheezy, or <ide> > Debian Jessie, you must download the [latest static Docker Linux binary](../installation/binaries.md). <ide> > This feature is currently *not* available on other distributions. <ide>
3
Text
Text
fix a command typo in models.md
7d13fc799b4764ccbc40137792c12f6984980990
<ide><path>website/docs/usage/models.md <ide> the package name or a path to the data directory: <ide> > <ide> > ```diff <ide> > - python -m spacy download en <del>> + python -m spacy dowmload en_core_web_sm <add>> + python -m spacy download en_core_web_sm <ide> > ``` <ide> <ide> ```python
1
Javascript
Javascript
revert a change from the narrow hack
92081af8968ac6123797eab838e0e5bd5e4190a9
<ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> // This is a poor simulation for Arial Narrow while font-stretch <ide> // is not implemented (bug 3512) <ide> if (current.font.narrow) { <del> textHScale += 0.6; <add> textHScale += 0.2; <ide> charSpacing -= (0.09 * current.fontSize); <ide> } <ide>
1
Text
Text
add documentation regarding our api tooling
bf28da8617a9ba37b4aa274b38957ea39a613e48
<ide><path>doc/contributing/api-documentation.md <add># Node.js API Documentation Tooling <add> <add>The Node.js API documentation is generated by an in-house tooling that resides <add>within the [tools/doc](https://github.com/nodejs/node/tree/main/tools/doc) <add>directory. <add> <add>The build process (using `make doc`) uses this tooling to parse the markdown <add>files in [doc/api](https://github.com/nodejs/node/tree/main/doc/api) and <add>generate the following: <add> <add>1. Human-readable HTML in `out/doc/api/*.html` <add>2. A JSON representation in `out/doc/api/*.json` <add> <add>These are published to nodejs.org for multiple versions of Node.js. As an <add>example the latest version of the human-readable HTML is published to <add>[nodejs.org/en/doc](https://nodejs.org/en/docs/), and the latest version <add>of the json documentation is published to <add>[nodejs.org/api/all.json](https://nodejs.org/api/all.json) <add> <add><!-- TODO: Add docs about how the publishing process happens --> <add> <add>**The key things to know about the tooling include:** <add> <add>1. The entry-point is `tools/doc/generate.js`. <add>2. The tooling supports the CLI arguments listed in the table below. <add>3. The tooling processes one file at a time. <add>4. The tooling uses a set of dependencies as described in the dependencies <add> section. <add>5. The tooling parses the input files and does several transformations to the <add> AST (Abstract Syntax Tree). <add>6. The tooling generates a JSON output that contains the metadata and content of <add> the Markdown file. <add>7. The tooling generates a HTML output that contains a human-readable and ready <add> to-view version of the file. <add> <add>This documentation serves the purpose of explaining the existing tooling <add>processes, to allow easier maintenance and evolution of the tooling. It is not <add>meant to be a guide on how to write documentation for Node.js. <add> <add>#### Vocabulary & Good to Know's <add> <add>* AST means "Abstract Syntax Tree" and it is a data structure that represents <add> the structure of a certain data format. In our case, the AST is a "graph" <add> representation of the contents of the Markdown file. <add>* MDN means [Mozilla Developer Network](https://developer.mozilla.org/en-US/) <add> and it is a website that contains documentation for web technologies. We use <add> it as a reference for the structure of the documentation. <add>* The <add> [Stability Index](https://nodejs.org/dist/latest/docs/api/documentation.html#stability-index) <add> is used to community the Stability of a given Node.js module. The Stability <add> levels include: <add> * Stability 0: Deprecated. (This module is Deprecated) <add> * Stability 1: Experimental. (This module is Experimental) <add> * Stability 2: Stable. (This module is Stable) <add> * Stability 3: Legacy. (This module is Legacy) <add>* Within Remark YAML snippets `<!-- something -->` are considered HTML nodes, <add> that's because YAML isn't valid Markdown content. (Doesn't abide by the <add> Markdown spec) <add>* "New Tooling" references to the (written from-scratch) API build tooling <add> introduced in `nodejs/nodejs.dev` that might replace the current one from <add> `nodejs/node` <add> <add>## CLI Arguments <add> <add>The tooling requires a `filename` argument and supports extra arguments (some <add>also required) as shown below: <add> <add>| Argument | Description | Required | Example | <add>| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------- | <add>| `--node-version=` | The version of Node.js that is being documented. It defaults to `process.version` which is supplied by Node.js itself | No | v19.0.0 | <add>| `--output-directory=` | The directory where the output files will be generated. | Yes | `./out/api/` | <add>| `--apilinks=` | This file is used as an index to specify the source file for each module | No | `./out/doc/api/apilinks.json` | <add>| `--versions-file=` | This file is used to specify an index of all previous versions of Node.js. It is used for the Version Navigation on the API docs page. | No | `./out/previous-doc-versions.json` | <add> <add>**Note:** both of the `apilinks` and `versions-file` parameters are generated by <add>the Node.js build process (Makefile). And they're files containing a JSON <add>object. <add> <add>### Basic Usage <add> <add>```bash <add># cd tools/doc <add>npm run node-doc-generator ${filename} <add>``` <add> <add>**OR** <add> <add>```bash <add># nodejs/node root directory <add>make doc <add>``` <add> <add>## Dependencies and how the Tooling works internally <add> <add>The API tooling uses an-AST-alike library called <add>[unified](https://github.com/unifiedjs/unified) for processing the Input file as <add>a Graph that supports easy modification and update of its nodes. <add> <add>In addition to `unified` we also use <add>[Remark](https://github.com/remarkjs/remark) for manipulating the Markdown part, <add>and [Rehype](https://github.com/rehypejs/rehype)to help convert to and from <add>Markdown. <add> <add>### What are the steps of the internal tooling? <add> <add>The tooling uses `unified` pipe-alike engine to pipe each part of the process. <add>(The description below is a simplified version) <add> <add>* Starting from reading the Frontmatter section of the Markdown file with <add> [remark-frontmatter](https://www.npmjs.com/package/remark-frontmatter). <add>* Then the tooling goes to parse the Markdown by using `remark-parse` and adds <add> support to [GitHub Flavoured Markdown](https://github.github.com/gfm/). <add>* The tooling proceeds by parsing some of the Markdown nodes and transforming <add> them to HTML. <add>* The tooling proceeds to generate the JSON output of the file. <add>* Finally it does its final node transformations and generates a stringified <add> HTML. <add>* It then stores the output to a JSON file and adds extra styling to the HTML <add> and then stores the HTML file. <add> <add>### What each file is responsible for? <add> <add>The files listed below are the ones referenced and actually used during the <add>build process of the API docs as we see on <https://nodejs.org/api>. The <add>remaining files from the directory might be used by other steps of the Node.js <add>Makefile or might even be deprecated/remnant of old processes and might need to <add>be revisited/removed. <add> <add>* **`html.mjs`**: Responsible for transforming nodes by decorating them with <add> visual artifacts for the HTML pages; <add> * For example, transforming man or JS doc references to links correctly <add> referring to respective External documentation. <add>* **`json.mjs`**: Responsible for generating the JSON output of the file; <add> * It is mostly responsible for going through the whole Markdown file and <add> generating a JSON object that represent the Metadata of a specific Module. <add> * For example, for the FS module, it will generate an object with all its <add> methods, events, classes and use several regular expressions (ReGeX) for <add> extracting the information needed. <add>* **`generate.mjs`**: Main entry-point of doc generation for a specific file. It <add> does e2e processing of a documentation file; <add>* **`allhtml.mjs`**: A script executed after all files are generated to create a <add> single "all" page containing all the HTML documentation; <add>* **`alljson.mjs`**: A script executed after all files are generated to create a <add> single "all" page containing all the JSON entries; <add>* **`markdown.mjs`**: Contains utility to replace Markdown links to work with <add> the <https://nodejs.org/api/> website. <add>* **`common.mjs`**: Contains a few utility functions that are used by the other <add> files. <add>* **`type-parser.mjs`**: Used to replace "type references" (e.g. "String", or <add> "Buffer") to the correct Internal/External documentation pages (i.e. MDN or <add> other Node.js documentation pages). <add> <add>**Note:** It is important to mention that other files not mentioned here might <add>be used during the process but are not relevant to the generation of the API <add>docs themselves. You will notice that a lot of the logic within the build <add>process is **specific** to the current <https://nodejs.org/api/> infrastructure. <add>Just as adding some JavaScript snippets, styles, transforming certain Markdown <add>elements into HTML, and adding certain HTML classes or such things. <add> <add>**Note:** Regarding the previous **Note** it is important to mention that we're <add>currently working on an API tooling that is generic and independent of the <add>current Nodejs.org Infrastructure. <add>[The new tooling that is functional is available at the nodejs.dev repository](https://github.com/nodejs/nodejs.dev/blob/main/scripts/syncApiDocs.js) <add>and uses plain ReGeX (No AST) and [MDX](https://mdxjs.com/). <add> <add>## The Build Process <add> <add>The build process that happens on `generate.mjs` follows the steps below: <add> <add>* Links within the Markdown are replaced directly within the source Markdown <add> (AST) (`markdown.replaceLinks`) <add> * This happens within `markdown.mjs` and basically it adds suffixes or <add> modifies link references within the Markdown <add> * This is necessary for the `https://nodejs.org` infrastructure as all pages <add> are suffixed with `.html` <add>* Text (and some YAML) Nodes are transformed/modified through <add> `html.preprocessText` <add>* JSON output is generated through `json.jsonAPI` <add>* The title of the page is inferred through `html.firstHeader` <add>* Nodes are transformed into HTML Elements through `html.preprocessElements` <add>* The HTML Table of Contents (ToC) is generated through `html.buildToc` <add> <add>### `html.mjs` <add> <add>This file is responsible for doing node AST transformations that either update <add>Markdown nodes to decorate them with more data or transform them into HTML Nodes <add>that attain a certain visual responsibility; For example, to generate the "Added <add>at" label, or the Source Links or the Stability Index, or the History table. <add> <add>**Note:** Methods not listed below are either not relevant or utility methods <add>for string/array/object manipulation (e.g.: are used by the other methods <add>mentioned below). <add> <add>#### `preprocessText` <add> <add>**New Tooling:** Most of the features within this method are available within <add>the new tooling. <add> <add>This method does two things: <add> <add>* Replaces the Source Link YAML entry `<-- source_link= -->` into a "Source <add> Link" HTML anchor element. <add>* Replaces type references within the Markdown (text) (i.e.: "String", "Buffer") <add> into the correct HTML anchor element that links to the correct documentation <add> page. <add> * The original node then gets mutated from text to HTML. <add> * It also updates references to Linux "MAN" pages to Web versions of them. <add> <add>#### `firstHeader` <add> <add>**New Tooling:** All features within this method are available within the new <add>Tooling. <add> <add>Is used to attempt to extract the first heading of the page (recursively) to <add>define the "title" of the page. <add> <add>**Note:** As all API Markdown files start with a Heading, this could possibly be <add>improved to a reduced complexity. <add> <add>#### `preprocessElements` <add> <add>**New Tooling:** All features within this method are available within the new <add>tooling. <add> <add>This method is responsible for doing multiple transformations within the AST <add>Nodes, in majority, transforming the source node in respective HTML elements <add>with diverse responsibilities, such as: <add> <add>* Updating Markdown `code` blocks by adding Language highlighting <add> * It also adds the "CJS"/"MJS" switch to Nodes that are followed by their <add> CJS/ESM equivalents. <add>* Increasing the Heading level of each Heading <add>* Parses YAML blocks and transforms them into HTML elements (See more at the <add> `parseYAML` method) <add>* Updates BlockQuotes that are prefixed by the "Stability" word into a Stability <add> Index HTML element. <add> <add>#### `parseYAML` <add> <add>**New Tooling:** Most of the features within this method are available within <add>the new tooling. <add> <add>This method is responsible for parsing the `<--YAML snippets -->` and <add>transforming them into HTML elements. <add> <add>It follows a certain kind of "schema" that basically constitues in the following <add>options: <add> <add>| YAML Key | Description | Example | Example Result | Available on new tooling | <add>| ------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | --------------------------- | ------------------------ | <add>| `added` | It's used to reference when a certain "module", "class" or "method" was added on Node.js | `added: v0.1.90` | `Added in: v0.1.90` | Yes | <add>| `deprecated` | It's used to reference when a certain "module", "class" or "method" was deprecated on Node.js | `deprecated: v0.1.90` | `Deprecated since: v0.1.90` | Yes | <add>| `removed` | It's used to reference when a certain "module", "class" or "method" was removed on Node.js | `removed: v0.1.90` | `Removed in: v0.1.90` | No | <add>| `changes` | It's used to describe all the changes (historical ones) that happened within a certain "module", "class" or "method" in Node.js | `[{ version: v0.1.90, pr-url: '', description: '' }]` | -- | Yes | <add>| `napiVersion` | It's used to describe in which version of the N-API this "module", "class" or "method" is available within Node.js | `napiVersion: 1` | `N-API version: 1` | Yes | <add> <add>**Note:** The `changes` field gets prepended with the `added`, `deprecated` and <add>`removed` fields if they exist. The table only gets generated if a `changes` <add>field exists. In the new tooling only "added" is prepended for now. <add> <add>#### `buildToc` <add> <add>**New Tooling:** This feature is natively available within the new tooling <add>through MDX. <add> <add>This method generates the Table of Contents based on all the Headings of the <add>Markdown file. <add> <add>#### `altDocs` <add> <add>**New Tooling:** All features within this method are available within the new <add>tooling. <add> <add>This method generates a version picker for the current page to be shown in older <add>versions of the API docs. <add> <add>### `json.mjs` <add> <add>This file is responsible for generating a JSON object that (supposedly) is used <add>for IDE-Intellisense or for indexing of all the "methods", "classes", "modules", <add>"events", "constants" and "globals" available within a certain Markdown file. <add> <add>It attempts a best effort extraction of the data by using several regular <add>expression patterns (ReGeX). <add> <add>**Note:** JSON output generation is currently not supported by the new tooling, <add>but it is in the pipeline for development. <add> <add>#### `jsonAPI` <add> <add>This method traverses all the AST Nodes by iterating through each one of them <add>and infers the kind of information each node contains through ReGeX. Then it <add>mutate the data and appends it to the final JSON object. <add> <add>For a more in-depth information we recommend to refer to the `json.mjs` file as <add>it contains a lot of comments.
1
Python
Python
add additional tests of lcm and gcd
bf35ddcdc961842628b6aa257609a280ffee9e2c
<ide><path>numpy/core/tests/test_umath.py <ide> def test_mixed(self): <ide> a = np.array([True, True]) <ide> assert_equal(np.choose(c, (a, 1)), np.array([1, 1])) <ide> <add> <ide> class TestRationalFunctions(object): <ide> def test_lcm(self): <ide> self._test_lcm_inner(np.int16) <ide> def test_decimal(self): <ide> assert_equal(np.gcd(a, b), 4*[Decimal('0.04')]) <ide> assert_equal(np.lcm(a, b), 4*[Decimal('0.60')]) <ide> <add> def test_float(self): <add> # not well-defined on float due to rounding errors <add> assert_raises(TypeError, np.gcd, 0.3, 0.4) <add> assert_raises(TypeError, np.lcm, 0.3, 0.4) <add> <add> def test_builtin_long(self): <add> # sanity check that array coercion is alright for builtin longs <add> assert_equal(np.array(2**200).item(), 2**200) <add> <add> # expressed as prime factors <add> a = np.array(2**100 * 3**5) <add> b = np.array([2**100 * 5**7, 2**50 * 3**10]) <add> assert_equal(np.gcd(a, b), [2**100, 2**50 * 3**5]) <add> assert_equal(np.lcm(a, b), [2**100 * 3**5 * 5**7, 2**100 * 3**10]) <add> <add> assert_equal(np.gcd(2**100, 3**100), 1) <add> <ide> <ide> def is_longdouble_finfo_bogus(): <ide> info = np.finfo(np.longcomplex)
1
Text
Text
fix placement of exec driver heading
68efb27e990a52478d9927911757a07910244dc5
<ide><path>docs/reference/commandline/daemon.md <ide> options for `zfs` start with `zfs`. <ide> <ide> $ docker -d --storage-opt dm.blkdiscard=false <ide> <del> <del>## Docker execdriver option <del> <ide> Currently supported options of `zfs`: <ide> <ide> * `zfs.fsname` <ide> Currently supported options of `zfs`: <ide> <ide> $ docker -d -s zfs --storage-opt zfs.fsname=zroot/docker <ide> <add>## Docker execdriver option <add> <ide> The Docker daemon uses a specifically built `libcontainer` execution driver as <ide> its interface to the Linux kernel `namespaces`, `cgroups`, and `SELinux`. <ide>
1
Ruby
Ruby
load 5.2 defaults in ast dummy app
ae7593e7e842ec5efb8d58a7ce005ba55fd4c886
<ide><path>activestorage/test/dummy/config/application.rb <ide> <ide> module Dummy <ide> class Application < Rails::Application <del> config.load_defaults 5.1 <add> config.load_defaults 5.2 <ide> <ide> config.active_storage.service = :local <ide> end
1
PHP
PHP
reduce code duplication
d94003c2dab0643a5e0539de6f7eae7f72f9074d
<ide><path>src/View/Widget/BasicWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> */ <ide> public function secureFields(array $data) <ide> { <add> if (!isset($data['name']) || $data['name'] === '') { <add> return []; <add> } <ide> return [$data['name']]; <ide> } <ide> } <ide><path>src/View/Widget/ButtonWidget.php <ide> namespace Cake\View\Widget; <ide> <ide> use Cake\View\Form\ContextInterface; <del>use Cake\View\Widget\WidgetInterface; <add>use Cake\View\Widget\BasicWidget; <ide> <ide> /** <ide> * Button input class <ide> * If you need to make basic submit inputs with type=submit, <ide> * use the Basic input widget. <ide> */ <del>class ButtonWidget implements WidgetInterface <add>class ButtonWidget extends BasicWidget <ide> { <ide> <del> /** <del> * StringTemplate instance. <del> * <del> * @var \Cake\View\StringTemplate <del> */ <del> protected $_templates; <del> <del> /** <del> * Constructor. <del> * <del> * @param \Cake\View\StringTemplate $templates Templates list. <del> */ <del> public function __construct($templates) <del> { <del> $this->_templates = $templates; <del> } <del> <ide> /** <ide> * Render a button. <ide> * <ide> public function render(array $data, ContextInterface $context) <ide> 'attrs' => $this->_templates->formatAttributes($data, ['text']), <ide> ]); <ide> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function secureFields(array $data) <del> { <del> if (!isset($data['name'])) { <del> return []; <del> } <del> return [$data['name']]; <del> } <ide> } <ide><path>src/View/Widget/CheckboxWidget.php <ide> namespace Cake\View\Widget; <ide> <ide> use Cake\View\Form\ContextInterface; <del>use Cake\View\Widget\WidgetInterface; <add>use Cake\View\Widget\BasicWidget; <ide> <ide> /** <ide> * Input widget for creating checkbox widgets. <ide> */ <del>class CheckboxWidget implements WidgetInterface <add>class CheckboxWidget extends BasicWidget <ide> { <ide> <del> /** <del> * Template instance. <del> * <del> * @var \Cake\View\StringTemplate <del> */ <del> protected $_templates; <del> <del> /** <del> * Constructor <del> * <del> * @param \Cake\View\StringTemplate $templates Templates list. <del> */ <del> public function __construct($templates) <del> { <del> $this->_templates = $templates; <del> } <del> <ide> /** <ide> * Render a checkbox element. <ide> * <ide> protected function _isChecked($data) <ide> } <ide> return false; <ide> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function secureFields(array $data) <del> { <del> return [$data['name']]; <del> } <ide> } <ide><path>src/View/Widget/SelectBoxWidget.php <ide> namespace Cake\View\Widget; <ide> <ide> use Cake\View\Form\ContextInterface; <del>use Cake\View\Widget\WidgetInterface; <add>use Cake\View\Widget\BasicWidget; <ide> use Traversable; <ide> <ide> /** <ide> * This class is intended as an internal implementation detail <ide> * of Cake\View\Helper\FormHelper and is not intended for direct use. <ide> */ <del>class SelectBoxWidget implements WidgetInterface <add>class SelectBoxWidget extends BasicWidget <ide> { <ide> <del> /** <del> * Template instance. <del> * <del> * @var \Cake\View\StringTemplate <del> */ <del> protected $_templates; <del> <del> /** <del> * Constructor <del> * <del> * @param \Cake\View\StringTemplate $templates Templates list. <del> */ <del> public function __construct($templates) <del> { <del> $this->_templates = $templates; <del> } <del> <ide> /** <ide> * Render a select box form input. <ide> * <ide> protected function _isDisabled($key, $disabled) <ide> $strict = !is_numeric($key); <ide> return in_array((string)$key, $disabled, $strict); <ide> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function secureFields(array $data) <del> { <del> return [$data['name']]; <del> } <ide> } <ide><path>src/View/Widget/TextareaWidget.php <ide> namespace Cake\View\Widget; <ide> <ide> use Cake\View\Form\ContextInterface; <del>use Cake\View\Widget\WidgetInterface; <add>use Cake\View\Widget\BasicWidget; <ide> <ide> /** <ide> * Input widget class for generating a textarea control. <ide> * <ide> * This class is intended as an internal implementation detail <ide> * of Cake\View\Helper\FormHelper and is not intended for direct use. <ide> */ <del>class TextareaWidget implements WidgetInterface <add>class TextareaWidget extends BasicWidget <ide> { <del> <del> /** <del> * Constructor <del> * <del> * @param \Cake\View\StringTemplate $templates Templates list. <del> */ <del> public function __construct($templates) <del> { <del> $this->_templates = $templates; <del> } <del> <ide> /** <ide> * Render a text area form widget. <ide> * <ide> public function render(array $data, ContextInterface $context) <ide> ) <ide> ]); <ide> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function secureFields(array $data) <del> { <del> return [$data['name']]; <del> } <ide> }
5
Ruby
Ruby
remove duplicated logic
f9b33e26e077a80e85caa1b2434943ab7b55de60
<ide><path>Library/brew.rb <ide> if ARGV == %w[--version] || ARGV == %w[-v] <ide> puts "Homebrew #{Homebrew.homebrew_version_string}" <ide> exit 0 <del>elsif ARGV.first == "-v" <del> # Shift the -v to the end of the parameter list <del> ARGV << ARGV.shift <ide> end <ide> <ide> if OS.mac? && MacOS.version < "10.6"
1
Text
Text
remove mentions of sorbet/files.yaml
4e9773a650759b5d01c310a99fab00b138443eda
<ide><path>docs/Typechecking.md <ide> file are always passed first (if it exists), followed by arguments provided on t <ide> command line. We use it ignore the `Library/Homebrew/vendor` directory, which <ide> contains gem definitions which we do not wish to type check. <ide> <del>- The `files.yaml` file. It contains a list of every Ruby file in the codebase <del>divided into 3 strictness levels, false, true and strict. The `false` files only <add>- Every Ruby file in the codebase is divided into three strictness levels: false, <add>true and strict. The `false` files only <ide> report errors related to the syntax, constant resolution and correctness of the <ide> method signatures, and not type errors. We use this file to override strictness <ide> on a file-by-file basis. Our longtime goal is to move all `false` files to `true` <ide> out the resulting type errors. Read more about Sorbet's strictness levels <ide> ## Using `brew typecheck` <ide> <ide> When run without any arguments, `brew typecheck`, will run considering the strictness levels <del>set in the `files.yaml` file. However, when typecheck is run on a specific file <del>or directory, more errors may show up since Sorbet can not resolve constants defined <del>outside the scope of the specified file. These problems can be solved with RBI files. <del>Currently `brew typecheck` provides `quiet`, `--file`, `--dir` and `--ignore` options <del>but you can explore more options with `srb tc --help` and passing them with `srb tc`. <add>set in each of the individual Ruby files in the core Homebrew codebase. However, when <add>typecheck is run on a specific file or directory, more errors may show up since Sorbet <add>cannot resolve constants defined outside the scope of the specified file. These <add>problems can be solved with RBI files. Currently `brew typecheck` provides `quiet`, `--file`, <add>`--dir` and `--ignore` options but you can explore more options with `srb tc --help` and <add>passing them with `srb tc`. <ide> <ide> ## Resolving Type Errors <ide>
1
Text
Text
add note about usage docs [ci skip]
bd435fadddfe21d6f3e94a32ed350ca4d49772b3
<ide><path>website/docs/api/entityruler.md <ide> token-based rules or exact phrase matches. It can be combined with the <ide> statistical [`EntityRecognizer`](/api/entityrecognizer) to boost accuracy, or <ide> used on its own to implement a purely rule-based entity recognition system. <ide> After initialization, the component is typically added to the processing <del>pipeline using [`nlp.add_pipe`](/api/language#add_pipe). <add>pipeline using [`nlp.add_pipe`](/api/language#add_pipe). For usage examples, see <add>the docs on <add>[rule-based entity recogntion](/usage/rule-based-matching#entityruler). <ide> <ide> ## EntityRuler.\_\_init\_\_ {#init tag="method"} <ide>
1
Text
Text
add a notice to the readme in models/inception
c2fe833c56ba03b7d013100265934d1f17e29214
<ide><path>inception/README.md <ide> model architecture. <ide> <ide> ## Description of Code <ide> <add>NOTE: For the most part, you will find a newer version of this code at [models/slim](https://github.com/tensorflow/models/tree/master/slim). In particular: <add> <add>* `inception_train.py` and `imagenet_train.py` should no longer be used. The slim editions for running on multiple GPUs are the current best examples. <add>* `inception_distributed_train.py` and `imagenet_distributed_train.py` are still valid examples of distributed training. <add> <ide> The code base provides three core binaries for: <ide> <ide> * Training an Inception v3 network from scratch across multiple GPUs and/or <ide> and `validation-?????-of-00001`, respectively. <ide> you will need to invoke [`build_image_data.py`](inception/data/build_image_data.py) on <ide> your custom data set. Please see the associated options and assumptions behind <ide> this script by reading the comments section of [`build_image_data.py`] <del>(inception/data/build_image_data.py). Also, if your custom data has a different <add>(inception/data/build_image_data.py). Also, if your custom data has a different <ide> number of examples or classes, you need to change the appropriate values in <ide> [`imagenet_data.py`](inception/imagenet_data.py). <ide> <ide> respectively. Generally speaking, we aim for selecting the number of shards such <ide> that roughly 1024 images reside in each shard. Once this data set is built, you <ide> are ready to train or fine-tune an Inception model on this data set. <ide> <del>Note, if you are piggy backing on the flowers retraining scripts, be sure to <del>update `num_classes()` and `num_examples_per_epoch()` in `flowers_data.py` <add>Note, if you are piggy backing on the flowers retraining scripts, be sure to <add>update `num_classes()` and `num_examples_per_epoch()` in `flowers_data.py` <ide> to correspond with your data. <ide> <ide> ## Practical Considerations for Training a Model
1
Text
Text
fix first paragraph of index.html
33fd42e7ed60def8b58b686d9912330445981197
<ide><path>guide/spanish/computer-hardware/power-supply/index.md <ide> localeTitle: Fuente de alimentación <ide> --- <ide> ## Fuente de alimentación <ide> <del>Una unidad de fuente de alimentación (PSU) suministra energía a una computadora. Convierte la alimentación de CA en una alimentación continua de baja tensión de CC para los componentes internos. <add>Una unidad de fuente de alimentación (PSU) suministra energía a una computadora. Convierte la alimentación electrica de Corriente Alterna (CA) en una alimentación electrica continua de baja tensión de Corriente Continua (CC) para los componentes internos. <ide> <ide> Una fuente de alimentación no suele ser reparable por el usuario. Para su seguridad, es aconsejable nunca abrir una unidad de fuente de alimentación. <ide> <ide> #### Más información: <ide> <del>* [Fuente de alimentación](https://en.wikipedia.org/wiki/Power_supply_unit_(computer)) <ide>\ No newline at end of file <add>* [Fuente de alimentación](https://en.wikipedia.org/wiki/Power_supply_unit_(computer))
1
Text
Text
update clojure readme
0da1e888705e9af489cf420ee0ed19c621a8def4
<ide><path>language-adaptors/rxjava-clojure/README.md <del># Clojure Adaptor for RxJava <add>Clojure bindings for RxJava. <ide> <add># Binaries <add> <add>Binaries and dependency information for Maven, Ivy, Gradle and others can be found at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22rxjava-clojure%22). <add> <add>Example for Leiningen: <add> <add>```clojure <add>[com.netflix.rxjava/rxjava-clojure "x.y.z"] <add>``` <add> <add>and for Gradle: <add> <add>```groovy <add>compile 'com.netflix.rx:rxjava-clojure:x.y.z' <add>``` <add> <add>and for Maven: <add> <add>```xml <add><dependency> <add> <groupId>com.netflix.rxjava</groupId> <add> <artifactId>rxjava-clojure</artifactId> <add> <version>x.y.z</version> <add></dependency> <add>``` <add> <add>and for Ivy: <add> <add>```xml <add><dependency org="com.netflix.rxjava" name="rxjava-clojure" rev="x.y.z" /> <add>``` <add> <add># Clojure Bindings <add>This library provides convenient, idiomatic Clojure bindings for RxJava. <add> <add>The bindings try to present an API that will be comfortable and familiar to a Clojure programmer that's familiar with the sequence operations in `clojure.core`. It "fixes" several issues with using RxJava with raw Java interop, for example: <add> <add>* Argument lists are in the "right" order. So in RxJava, the function applied in `Observable.map` is the second argument, while here it's the first argument with one or more Observables as trailing arguments <add>* Operators take normal Clojure functions as arguments, bypassing need for the interop described below <add>* Predicates accomodate Clojure's notion of truth <add>* Operators are generally names as they would be in `clojure.core` rather than the Rx names <add> <add>There is no object wrapping going on. That is, all functions return normal `rx.Observable` objects, so you can always drop back to Java interop for anything that's missing in this wrapper. <add> <add>## Basic Usage <add>Most functionality resides in the `rx.lang.clojure.core` namespace and for the most part looks like normal Clojure sequence manipulation: <add> <add>```clojure <add>(require '[rx.lang.clojure.core :as rx]) <add> <add>(->> my-observable <add> (rx/map (comp clojure.string/lower-case :first-name)) <add> (rx/map clojure.string/lower-case) <add> (rx/filter #{"bob"}) <add> (rx/distinct) <add> (rx/into [])) <add>;=> An Observable that emits a single vector of names <add>``` <add> <add>Blocking operators, which are useful for testing, but should otherwise be avoided, reside in `rx.lang.clojure.blocking`. For example: <add> <add>```clojure <add>(require '[rx.lang.clojure.blocking :as rxb]) <add> <add>(rxb/doseq [{:keys [first-name]} users-observable] <add> (println "Hey," first-name)) <add>;=> nil <add>``` <add> <add>## What's Missing <add>This library is an ongoing work in progress driven primarily by the needs of one team at Netflix. As such some things are currently missing: <add> <add>* Highly-specific operators that we felt cluttered the API and were easily composed from existing operators, especially since we're in not-Java land. For example, `Observable.sumLong()`. <add>* Most everything involving schedulers <add>* Most everything involving time <add>* `Observable.window` and `Observable.buffer`. Who knows which parts of these beasts to wrap? <add> <add>Of course, contributions that cover these cases are welcome. <add> <add># Low-level Interop <ide> This adaptor provides functions and macros to ease Clojure/RxJava interop. In particular, there are functions and macros for turning Clojure functions and code into RxJava `Func*` and `Action*` interfaces without the tedium of manually reifying the interfaces. <ide> <del># Basic Usage <add>## Basic Usage <ide> <del>## Requiring the interop namespace <add>### Requiring the interop namespace <ide> The first thing to do is to require the namespace: <ide> <ide> ```clojure <ide> or, at the REPL: <ide> (require '[rx.lang.clojure.interop :as rx]) <ide> ``` <ide> <del>## Using rx/fn <add>### Using rx/fn <ide> Once the namespace is required, you can use the `rx/fn` macro anywhere RxJava wants a `rx.util.functions.Func` object. The syntax is exactly the same as `clojure.core/fn`: <ide> <ide> ```clojure <ide> If you already have a plain old Clojure function you'd like to use, you can pass <ide> (.reduce (rx/fn* +))) <ide> ``` <ide> <del>## Using rx/action <add>### Using rx/action <ide> The `rx/action` macro is identical to `rx/fn` except that the object returned implements `rx.util.functions.Action` interfaces. It's used in `subscribe` and other side-effect-y contexts: <ide> <ide> ```clojure <ide> The `rx/action` macro is identical to `rx/fn` except that the object returned im <ide> (rx/action [] (println "Sequence complete")))) <ide> ``` <ide> <del>## Using Observable/create <add>### Using Observable/create <ide> As of 0.17, `rx.Observable/create` takes an implementation of `rx.Observable$OnSubscribe` which is basically an alias for `rx.util.functions.Action1` that takes an `rx.Subscriber` as its argument. Thus, you can just use `rx/action` when creating new observables: <ide> <ide> ```clojure <ide> As of 0.17, `rx.Observable/create` takes an implementation of `rx.Observable$OnS <ide> (.onCompleted s))) <ide> ``` <ide> <del># Gotchas <add>## Gotchas <ide> Here are a few things to keep in mind when using this interop: <ide> <ide> * Keep in mind the (mostly empty) distinction between `Func` and `Action` and which is used in which contexts <ide> * If there are multiple Java methods overloaded by `Func` arity, you'll need to use a type hint to let the compiler know which one to choose. <ide> * Methods that take a predicate (like filter) expect the predicate to return a boolean value. A function that returns a non-boolean value will result in a `ClassCastException`. <ide> <del># Binaries <del> <del>Binaries and dependency information for Maven, Ivy, Gradle and others can be found at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22rxjava-clojure%22). <del> <del>Example for Maven: <del> <del>```xml <del><dependency> <del> <groupId>com.netflix.rxjava</groupId> <del> <artifactId>rxjava-clojure</artifactId> <del> <version>x.y.z</version> <del></dependency> <del>``` <del> <del>and for Ivy: <del> <del>```xml <del><dependency org="com.netflix.rxjava" name="rxjava-clojure" rev="x.y.z" /> <del>``` <del> <del>and for Leiningen: <del> <del>```clojure <del>[com.netflix.rxjava/rxjava-clojure "x.y.z"] <del>```
1
Ruby
Ruby
require hash/keys inside active_model/callbacks
80873a49af6f52d48224d9c18c60e67c3f9d4731
<ide><path>activemodel/lib/active_model/callbacks.rb <ide> # frozen_string_literal: true <ide> <ide> require "active_support/core_ext/array/extract_options" <add>require "active_support/core_ext/hash/keys" <ide> <ide> module ActiveModel <ide> # == Active \Model \Callbacks
1
Go
Go
remove accidental debug spew
bff0c4f3dc560109ed2d5dc6cae12453c9bc2747
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) loadMetadata(hash string) *DevInfo { <ide> return nil <ide> } <ide> <del> fmt.Printf("Loaded metadata %v\n", info) <del> <ide> // If the transaction id is larger than the actual one we lost the device due to some crash <ide> if info.TransactionId > devices.TransactionId { <ide> return nil <ide> func (devices *DeviceSet) loadMetadata(hash string) *DevInfo { <ide> <ide> func (devices *DeviceSet) setupBaseImage() error { <ide> oldInfo, _ := devices.lookupDevice("") <del> utils.Debugf("oldInfo: %p", oldInfo) <ide> if oldInfo != nil && oldInfo.Initialized { <ide> return nil <ide> }
1
Ruby
Ruby
set cached values in the env hash
ec760e67fd9be26de165c912dfd0dd0f3f31b4b8
<ide><path>actionpack/lib/action_dispatch/http/mime_negotiation.rb <ide> module MimeNegotiation <ide> # For backward compatibility, the post \format is extracted from the <ide> # X-Post-Data-Format HTTP header if present. <ide> def content_mime_type <del> get_header("action_dispatch.request.content_type") do <del> if get_header('CONTENT_TYPE') =~ /^([^,\;]*)/ <add> get_header("action_dispatch.request.content_type") do |k| <add> v = if get_header('CONTENT_TYPE') =~ /^([^,\;]*)/ <ide> Mime::Type.lookup($1.strip.downcase) <ide> else <ide> nil <ide> end <add> set_header k, v <ide> end <ide> end <ide> <ide> def content_type <ide> <ide> # Returns the accepted MIME type for the request. <ide> def accepts <del> get_header("action_dispatch.request.accepts") do <add> get_header("action_dispatch.request.accepts") do |k| <ide> header = get_header('HTTP_ACCEPT').to_s.strip <ide> <del> if header.empty? <add> v = if header.empty? <ide> [content_mime_type] <ide> else <ide> Mime::Type.parse(header) <ide> end <add> set_header k, v <ide> end <ide> end <ide> <ide> def format(view_path = []) <ide> end <ide> <ide> def formats <del> get_header("action_dispatch.request.formats") do <add> get_header("action_dispatch.request.formats") do |k| <ide> params_readable = begin <ide> parameters[:format] <ide> rescue ActionController::BadRequest <ide> false <ide> end <ide> <del> if params_readable <add> v = if params_readable <ide> Array(Mime[parameters[:format]]) <ide> elsif use_accept_header && valid_accept_header <ide> accepts <ide> def formats <ide> else <ide> [Mime::HTML] <ide> end <add> set_header k, v <ide> end <ide> end <ide>
1
Java
Java
replace "blacklist" with alternative words
972c01cbbd8c99c9c175519dbbae67751c567d86
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CrossOriginAnnotationIntegrationTests.java <ide> protected ApplicationContext initApplicationContext() { <ide> <ide> @Override <ide> protected RestTemplate initRestTemplate() { <del> // JDK default HTTP client blacklist headers like Origin <add> // JDK default HTTP client disallowed headers like Origin <ide> return new RestTemplate(new HttpComponentsClientHttpRequestFactory()); <ide> } <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java <ide> protected ApplicationContext initApplicationContext() { <ide> <ide> @Override <ide> protected RestTemplate initRestTemplate() { <del> // JDK default HTTP client blacklists headers like Origin <add> // JDK default HTTP client disallowed headers like Origin <ide> return new RestTemplate(new HttpComponentsClientHttpRequestFactory()); <ide> } <ide>
2
PHP
PHP
apply fixes from styleci
0740f78a9869f0c96a78781b21ccd4c127ce460f
<ide><path>tests/Support/SupportStrTest.php <ide> public function testStringCanBeLimitedByWordsNonAscii() <ide> $this->assertSame('这是...', Str::words('这是 段中文', 1)); <ide> $this->assertSame('这是___', Str::words('这是 段中文', 1, '___')); <ide> $this->assertSame('这是-段中文', Str::words('这是-段中文', 3, '___')); <del> $this->assertSame('这是___', Str::words('这是 段中文',1, '___')); <add> $this->assertSame('这是___', Str::words('这是 段中文', 1, '___')); <ide> } <ide> <ide> public function testStringTrimmedOnlyWhereNecessary()
1
Javascript
Javascript
flow strict statusbar
6fa997dd634f76b04bcef9bd98c6e57c8069cef0
<ide><path>Libraries/Components/StatusBar/StatusBar.js <ide> * LICENSE file in the root directory of this source tree. <ide> * <ide> * @format <del> * @flow <add> * @flow strict-local <ide> */ <ide> <ide> 'use strict'; <ide> type Props = $ReadOnly<{| <ide> barStyle?: ?('default' | 'light-content' | 'dark-content'), <ide> |}>; <ide> <add>type StackEntryProps = {| <add> /** <add> * The background color of the status bar. <add> * <add> * @platform android <add> */ <add> backgroundColor: {| <add> value: ?string, <add> animated: ?boolean, <add> |}, <add> /** <add> * Sets the color of the status bar text. <add> */ <add> barStyle: {| <add> value: ?string, <add> animated: ?boolean, <add> |}, <add> /** <add> * If the status bar is translucent. <add> * When translucent is set to true, the app will draw under the status bar. <add> * This is useful when using a semi transparent status bar color. <add> */ <add> translucent: ?boolean, <add> /** <add> * <add> */ <add> hidden: {| <add> value: ?boolean, <add> animated: boolean, <add> transition: ?('slide' | 'fade'), <add> |}, <add> /** <add> * If the network activity indicator should be visible. <add> * <add> * @platform ios <add> */ <add> networkActivityIndicatorVisible: ?boolean, <add>|}; <add> <ide> /** <ide> * Merges the prop stack with the default values. <ide> */ <ide> function mergePropsStack( <del> propsStack: Array<Object>, <del> defaultValues: Object, <del>): Object { <add> propsStack: $ReadOnlyArray<StackEntryProps>, <add> defaultValues: StackEntryProps, <add>): StackEntryProps { <add> const init: StackEntryProps = { <add> ...defaultValues, <add> }; <add> <ide> return propsStack.reduce((prev, cur) => { <ide> for (const prop in cur) { <ide> if (cur[prop] != null) { <ide> prev[prop] = cur[prop]; <ide> } <ide> } <ide> return prev; <del> }, Object.assign({}, defaultValues)); <add> }, init); <ide> } <ide> <ide> /** <ide> * Returns an object to insert in the props stack from the props <ide> * and the transition/animation info. <ide> */ <del>function createStackEntry(props: any): any { <add>function createStackEntry(props: Props): StackEntryProps { <ide> return { <del> backgroundColor: <del> props.backgroundColor != null <del> ? { <del> value: props.backgroundColor, <del> animated: props.animated, <del> } <del> : null, <del> barStyle: <del> props.barStyle != null <del> ? { <del> value: props.barStyle, <del> animated: props.animated, <del> } <del> : null, <del> translucent: props.translucent, <del> hidden: <del> props.hidden != null <del> ? { <del> value: props.hidden, <del> animated: props.animated, <del> transition: props.showHideTransition, <del> } <del> : null, <del> networkActivityIndicatorVisible: props.networkActivityIndicatorVisible, <add> backgroundColor: { <add> value: props.backgroundColor, <add> animated: props.animated, <add> }, <add> barStyle: { <add> value: props.barStyle, <add> animated: props.animated, <add> }, <add> translucent: props.translucent || false, <add> hidden: { <add> value: props.hidden, <add> animated: props.animated || false, <add> transition: props.showHideTransition, <add> }, <add> networkActivityIndicatorVisible: <add> props.networkActivityIndicatorVisible || false, <ide> }; <ide> } <ide> <ide> function createStackEntry(props: any): any { <ide> * `currentHeight` (Android only) The height of the status bar. <ide> */ <ide> class StatusBar extends React.Component<Props> { <del> static _propsStack = []; <add> static _propsStack: Array<StackEntryProps> = []; <ide> <del> static _defaultProps = createStackEntry({ <add> static _defaultProps: StackEntryProps = createStackEntry({ <ide> animated: false, <ide> showHideTransition: 'fade', <ide> backgroundColor: 'black', <ide> class StatusBar extends React.Component<Props> { <ide> * changing the status bar hidden property. <ide> */ <ide> static setHidden(hidden: boolean, animation?: StatusBarAnimation) { <del> animation = animation || 'none'; <ide> StatusBar._defaultProps.hidden.value = hidden; <ide> if (Platform.OS === 'ios') { <del> StatusBarManager.setHidden(hidden, animation); <add> StatusBarManager.setHidden(hidden, animation || 'none'); <ide> } else if (Platform.OS === 'android') { <ide> StatusBarManager.setHidden(hidden); <ide> } <ide> class StatusBar extends React.Component<Props> { <ide> * @param animated Animate the style change. <ide> */ <ide> static setBarStyle(style: StatusBarStyle, animated?: boolean) { <del> animated = animated || false; <ide> StatusBar._defaultProps.barStyle.value = style; <ide> if (Platform.OS === 'ios') { <del> StatusBarManager.setStyle(style, animated); <add> StatusBarManager.setStyle(style, animated || false); <ide> } else if (Platform.OS === 'android') { <ide> StatusBarManager.setStyle(style); <ide> } <ide> class StatusBar extends React.Component<Props> { <ide> console.warn('`setBackgroundColor` is only available on Android'); <ide> return; <ide> } <del> animated = animated || false; <ide> StatusBar._defaultProps.backgroundColor.value = color; <del> StatusBarManager.setColor(processColor(color), animated); <add> StatusBarManager.setColor(processColor(color), animated || false); <ide> } <ide> <ide> /**
1
Javascript
Javascript
extract orbitconstraint from orbitcontrols
6a2a28fe34e3ff1ab6b183325ebbc810da2a4195
<ide><path>examples/js/controls/OrbitControls.js <ide> */ <ide> /*global THREE, console */ <ide> <del>// This set of controls performs orbiting, dollying (zooming), and panning. It maintains <del>// the "up" direction as +Y, unlike the TrackballControls. Touch on tablet and phones is <del>// supported. <del>// <del>// Orbit - left mouse / touch: one finger move <del>// Zoom - middle mouse, or mousewheel / touch: two finger spread or squish <del>// Pan - right mouse, or arrow keys / touch: three finter swipe <add>(function () { <ide> <del>THREE.OrbitControls = function ( object, domElement ) { <add> function OrbitConstraint ( object ) { <ide> <del> this.object = object; <del> this.domElement = ( domElement !== undefined ) ? domElement : document; <add> this.object = object; <ide> <del> // API <add> // "target" sets the location of focus, where the object orbits around <add> // and where it pans with respect to. <add> this.target = new THREE.Vector3(); <ide> <del> // Set to false to disable this control <del> this.enabled = true; <add> // Limits to how far you can dolly in and out ( PerspectiveCamera only ) <add> this.minDistance = 0; <add> this.maxDistance = Infinity; <ide> <del> // "target" sets the location of focus, where the control orbits around <del> // and where it pans with respect to. <del> this.target = new THREE.Vector3(); <add> // Limits to how far you can zoom in and out ( OrthographicCamera only ) <add> this.minZoom = 0; <add> this.maxZoom = Infinity; <ide> <del> // center is old, deprecated; use "target" instead <del> this.center = this.target; <add> // How far you can orbit vertically, upper and lower limits. <add> // Range is 0 to Math.PI radians. <add> this.minPolarAngle = 0; // radians <add> this.maxPolarAngle = Math.PI; // radians <ide> <del> // This option actually enables dollying in and out; left as "zoom" for <del> // backwards compatibility <del> this.noZoom = false; <del> this.zoomSpeed = 1.0; <add> // How far you can orbit horizontally, upper and lower limits. <add> // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ]. <add> this.minAzimuthAngle = - Infinity; // radians <add> this.maxAzimuthAngle = Infinity; // radians <ide> <del> // Limits to how far you can dolly in and out ( PerspectiveCamera only ) <del> this.minDistance = 0; <del> this.maxDistance = Infinity; <add> //////////// <add> // internals <ide> <del> // Limits to how far you can zoom in and out ( OrthographicCamera only ) <del> this.minZoom = 0; <del> this.maxZoom = Infinity; <add> var scope = this; <ide> <del> // Set to true to disable this control <del> this.noRotate = false; <del> this.rotateSpeed = 1.0; <add> var EPS = 0.000001; <ide> <del> // Set to true to disable this control <del> this.noPan = false; <del> this.keyPanSpeed = 7.0; // pixels moved per arrow key push <add> // Current position in spherical coordinate system. <add> var theta; <add> var phi; <ide> <del> // Set to true to automatically rotate around the target <del> this.autoRotate = false; <del> this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60 <add> // Pending changes <add> var phiDelta = 0; <add> var thetaDelta = 0; <add> var scale = 1; <add> var panOffset = new THREE.Vector3(); <ide> <del> // How far you can orbit vertically, upper and lower limits. <del> // Range is 0 to Math.PI radians. <del> this.minPolarAngle = 0; // radians <del> this.maxPolarAngle = Math.PI; // radians <add> // events <add> var changeEvent = { type: 'change' }; <ide> <del> // How far you can orbit horizontally, upper and lower limits. <del> // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ]. <del> this.minAzimuthAngle = - Infinity; // radians <del> this.maxAzimuthAngle = Infinity; // radians <add> this.getPolarAngle = function () { <ide> <del> // Set to true to disable use of the keys <del> this.noKeys = false; <add> return phi; <ide> <del> // The four arrow keys <del> this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; <add> }; <ide> <del> // Mouse buttons <del> this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT }; <add> this.getAzimuthalAngle = function () { <ide> <del> //////////// <del> // internals <add> return theta; <ide> <del> var scope = this; <add> }; <ide> <del> var EPS = 0.000001; <add> this.rotateLeft = function ( angle ) { <ide> <del> var rotateStart = new THREE.Vector2(); <del> var rotateEnd = new THREE.Vector2(); <del> var rotateDelta = new THREE.Vector2(); <add> thetaDelta -= angle; <ide> <del> var panStart = new THREE.Vector2(); <del> var panEnd = new THREE.Vector2(); <del> var panDelta = new THREE.Vector2(); <del> var panOffset = new THREE.Vector3(); <add> }; <ide> <del> var offset = new THREE.Vector3(); <add> this.rotateUp = function ( angle ) { <ide> <del> var dollyStart = new THREE.Vector2(); <del> var dollyEnd = new THREE.Vector2(); <del> var dollyDelta = new THREE.Vector2(); <add> phiDelta -= angle; <ide> <del> var theta; <del> var phi; <del> var phiDelta = 0; <del> var thetaDelta = 0; <del> var scale = 1; <del> var pan = new THREE.Vector3(); <add> }; <ide> <del> var lastPosition = new THREE.Vector3(); <del> var lastQuaternion = new THREE.Quaternion(); <add> // pass in distance in world space to move left <add> this.panLeft = function() { <ide> <del> var STATE = { NONE : -1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 }; <add> var v = new THREE.Vector3(); <ide> <del> var state = STATE.NONE; <add> return function panLeft ( distance ) { <ide> <del> // for reset <add> var te = this.object.matrix.elements; <ide> <del> this.target0 = this.target.clone(); <del> this.position0 = this.object.position.clone(); <del> this.zoom0 = this.object.zoom; <add> // get X column of matrix <add> v.set( te[ 0 ], te[ 1 ], te[ 2 ] ); <add> v.multiplyScalar( - distance ); <ide> <del> // so camera.up is the orbit axis <add> panOffset.add( v ); <ide> <del> var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) ); <del> var quatInverse = quat.clone().inverse(); <add> }; <ide> <del> // events <add> }(); <ide> <del> var changeEvent = { type: 'change' }; <del> var startEvent = { type: 'start' }; <del> var endEvent = { type: 'end' }; <add> // pass in distance in world space to move up <add> this.panUp = function() { <ide> <del> this.rotateLeft = function ( angle ) { <add> var v = new THREE.Vector3(); <ide> <del> if ( angle === undefined ) { <add> return function panUp ( distance ) { <ide> <del> angle = getAutoRotationAngle(); <add> var te = this.object.matrix.elements; <ide> <del> } <add> // get Y column of matrix <add> v.set( te[ 4 ], te[ 5 ], te[ 6 ] ); <add> v.multiplyScalar( distance ); <ide> <del> thetaDelta -= angle; <add> panOffset.add( v ); <ide> <del> }; <add> }; <ide> <del> this.rotateUp = function ( angle ) { <add> }(); <ide> <del> if ( angle === undefined ) { <add> // pass in x,y of change desired in pixel space, <add> // right and down are positive <add> this.pan = function ( deltaX, deltaY, screenWidth, screenHeight ) { <ide> <del> angle = getAutoRotationAngle(); <add> if ( scope.object instanceof THREE.PerspectiveCamera ) { <ide> <del> } <add> // perspective <add> var position = scope.object.position; <add> var offset = position.clone().sub( scope.target ); <add> var targetDistance = offset.length(); <ide> <del> phiDelta -= angle; <add> // half of the fov is center to top of screen <add> targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); <ide> <del> }; <add> // we actually don't use screenWidth, since perspective camera is fixed to screen height <add> scope.panLeft( 2 * deltaX * targetDistance / screenHeight ); <add> scope.panUp( 2 * deltaY * targetDistance / screenHeight ); <ide> <del> // pass in distance in world space to move left <del> this.panLeft = function ( distance ) { <add> } else if ( scope.object instanceof THREE.OrthographicCamera ) { <ide> <del> var te = this.object.matrix.elements; <add> // orthographic <add> scope.panLeft( deltaX * ( scope.object.right - scope.object.left ) / screenWidth ); <add> scope.panUp( deltaY * ( scope.object.top - scope.object.bottom ) / screenHeight ); <ide> <del> // get X column of matrix <del> panOffset.set( te[ 0 ], te[ 1 ], te[ 2 ] ); <del> panOffset.multiplyScalar( - distance ); <add> } else { <ide> <del> pan.add( panOffset ); <add> // camera neither orthographic or perspective <add> console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); <ide> <del> }; <add> } <ide> <del> // pass in distance in world space to move up <del> this.panUp = function ( distance ) { <add> }; <ide> <del> var te = this.object.matrix.elements; <add> this.dollyIn = function ( dollyScale ) { <ide> <del> // get Y column of matrix <del> panOffset.set( te[ 4 ], te[ 5 ], te[ 6 ] ); <del> panOffset.multiplyScalar( distance ); <add> if ( scope.object instanceof THREE.PerspectiveCamera ) { <ide> <del> pan.add( panOffset ); <add> scale /= dollyScale; <ide> <del> }; <add> } else if ( scope.object instanceof THREE.OrthographicCamera ) { <ide> <del> // pass in x,y of change desired in pixel space, <del> // right and down are positive <del> this.pan = function ( deltaX, deltaY ) { <add> scope.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom * dollyScale ) ); <add> scope.object.updateProjectionMatrix(); <add> scope.dispatchEvent( changeEvent ); <ide> <del> var element = scope.domElement === document ? scope.domElement.body : scope.domElement; <add> } else { <ide> <del> if ( scope.object instanceof THREE.PerspectiveCamera ) { <add> console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); <ide> <del> // perspective <del> var position = scope.object.position; <del> var offset = position.clone().sub( scope.target ); <del> var targetDistance = offset.length(); <add> } <ide> <del> // half of the fov is center to top of screen <del> targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); <add> }; <ide> <del> // we actually don't use screenWidth, since perspective camera is fixed to screen height <del> scope.panLeft( 2 * deltaX * targetDistance / element.clientHeight ); <del> scope.panUp( 2 * deltaY * targetDistance / element.clientHeight ); <add> this.dollyOut = function ( dollyScale ) { <ide> <del> } else if ( scope.object instanceof THREE.OrthographicCamera ) { <add> if ( scope.object instanceof THREE.PerspectiveCamera ) { <ide> <del> // orthographic <del> scope.panLeft( deltaX * (scope.object.right - scope.object.left) / element.clientWidth ); <del> scope.panUp( deltaY * (scope.object.top - scope.object.bottom) / element.clientHeight ); <add> scale *= dollyScale; <ide> <del> } else { <add> } else if ( scope.object instanceof THREE.OrthographicCamera ) { <ide> <del> // camera neither orthographic or perspective <del> console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); <add> scope.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / dollyScale ) ); <add> scope.object.updateProjectionMatrix(); <add> scope.dispatchEvent( changeEvent ); <ide> <del> } <add> } else { <ide> <del> }; <add> console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); <ide> <del> this.dollyIn = function ( dollyScale ) { <add> } <ide> <del> if ( dollyScale === undefined ) { <add> }; <ide> <del> dollyScale = getZoomScale(); <add> this.update = function() { <ide> <del> } <add> var offset = new THREE.Vector3(); <ide> <del> if ( scope.object instanceof THREE.PerspectiveCamera ) { <add> // so camera.up is the orbit axis <add> var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) ); <add> var quatInverse = quat.clone().inverse(); <ide> <del> scale /= dollyScale; <add> var lastPosition = new THREE.Vector3(); <add> var lastQuaternion = new THREE.Quaternion(); <ide> <del> } else if ( scope.object instanceof THREE.OrthographicCamera ) { <add> return function () { <ide> <del> scope.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom * dollyScale ) ); <del> scope.object.updateProjectionMatrix(); <del> scope.dispatchEvent( changeEvent ); <add> var position = this.object.position; <ide> <del> } else { <add> offset.copy( position ).sub( this.target ); <ide> <del> console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); <add> // rotate offset to "y-axis-is-up" space <add> offset.applyQuaternion( quat ); <ide> <del> } <add> // angle from z-axis around y-axis <ide> <del> }; <add> theta = Math.atan2( offset.x, offset.z ); <ide> <del> this.dollyOut = function ( dollyScale ) { <add> // angle from y-axis <ide> <del> if ( dollyScale === undefined ) { <add> phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y ); <ide> <del> dollyScale = getZoomScale(); <add> theta += thetaDelta; <add> phi += phiDelta; <ide> <del> } <add> // restrict theta to be between desired limits <add> theta = Math.max( this.minAzimuthAngle, Math.min( this.maxAzimuthAngle, theta ) ); <ide> <del> if ( scope.object instanceof THREE.PerspectiveCamera ) { <add> // restrict phi to be between desired limits <add> phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) ); <ide> <del> scale *= dollyScale; <add> // restrict phi to be betwee EPS and PI-EPS <add> phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) ); <ide> <del> } else if ( scope.object instanceof THREE.OrthographicCamera ) { <add> var radius = offset.length() * scale; <ide> <del> scope.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / dollyScale ) ); <del> scope.object.updateProjectionMatrix(); <del> scope.dispatchEvent( changeEvent ); <add> // restrict radius to be between desired limits <add> radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) ); <ide> <del> } else { <add> // move target to panned location <add> this.target.add( panOffset ); <ide> <del> console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); <add> offset.x = radius * Math.sin( phi ) * Math.sin( theta ); <add> offset.y = radius * Math.cos( phi ); <add> offset.z = radius * Math.sin( phi ) * Math.cos( theta ); <ide> <del> } <add> // rotate offset back to "camera-up-vector-is-up" space <add> offset.applyQuaternion( quatInverse ); <ide> <del> }; <add> position.copy( this.target ).add( offset ); <ide> <del> this.update = function () { <add> this.object.lookAt( this.target ); <ide> <del> var position = this.object.position; <add> thetaDelta = 0; <add> phiDelta = 0; <add> scale = 1; <add> panOffset.set( 0, 0, 0 ); <ide> <del> offset.copy( position ).sub( this.target ); <add> // update condition is: <add> // min(camera displacement, camera rotation in radians)^2 > EPS <add> // using small-angle approximation cos(x/2) = 1 - x^2 / 8 <ide> <del> // rotate offset to "y-axis-is-up" space <del> offset.applyQuaternion( quat ); <add> if ( lastPosition.distanceToSquared( this.object.position ) > EPS || <add> 8 * ( 1 - lastQuaternion.dot( this.object.quaternion) ) > EPS ) { <ide> <del> // angle from z-axis around y-axis <add> lastPosition.copy( this.object.position ); <add> lastQuaternion.copy( this.object.quaternion ); <ide> <del> theta = Math.atan2( offset.x, offset.z ); <add> return true; <ide> <del> // angle from y-axis <add> } <ide> <del> phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y ); <add> return false; <ide> <del> if ( this.autoRotate && state === STATE.NONE ) { <add> }; <ide> <del> this.rotateLeft( getAutoRotationAngle() ); <add> }(); <ide> <del> } <add> }; <ide> <del> theta += thetaDelta; <del> phi += phiDelta; <add> OrbitConstraint.prototype = Object.create( THREE.EventDispatcher.prototype ); <add> OrbitConstraint.prototype.constructor = OrbitConstraint; <ide> <del> // restrict theta to be between desired limits <del> theta = Math.max( this.minAzimuthAngle, Math.min( this.maxAzimuthAngle, theta ) ); <ide> <del> // restrict phi to be between desired limits <del> phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) ); <ide> <del> // restrict phi to be betwee EPS and PI-EPS <del> phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) ); <add> // This set of controls performs orbiting, dollying (zooming), and panning. It maintains <add> // the "up" direction as +Y, unlike the TrackballControls. Touch on tablet and phones is <add> // supported. <add> // <add> // Orbit - left mouse / touch: one finger move <add> // Zoom - middle mouse, or mousewheel / touch: two finger spread or squish <add> // Pan - right mouse, or arrow keys / touch: three finter swipe <ide> <del> var radius = offset.length() * scale; <add> THREE.OrbitControls = function ( object, domElement ) { <ide> <del> // restrict radius to be between desired limits <del> radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) ); <add> OrbitConstraint.call( this, object ); <ide> <del> // move target to panned location <del> this.target.add( pan ); <add> this.domElement = ( domElement !== undefined ) ? domElement : document; <ide> <del> offset.x = radius * Math.sin( phi ) * Math.sin( theta ); <del> offset.y = radius * Math.cos( phi ); <del> offset.z = radius * Math.sin( phi ) * Math.cos( theta ); <add> // API <ide> <del> // rotate offset back to "camera-up-vector-is-up" space <del> offset.applyQuaternion( quatInverse ); <add> // Set to false to disable this control <add> this.enabled = true; <ide> <del> position.copy( this.target ).add( offset ); <add> // center is old, deprecated; use "target" instead <add> this.center = this.target; <ide> <del> this.object.lookAt( this.target ); <add> // This option actually enables dollying in and out; left as "zoom" for <add> // backwards compatibility <add> this.noZoom = false; <add> this.zoomSpeed = 1.0; <ide> <del> thetaDelta = 0; <del> phiDelta = 0; <del> scale = 1; <del> pan.set( 0, 0, 0 ); <add> // Set to true to disable this control <add> this.noRotate = false; <add> this.rotateSpeed = 1.0; <ide> <del> // update condition is: <del> // min(camera displacement, camera rotation in radians)^2 > EPS <del> // using small-angle approximation cos(x/2) = 1 - x^2 / 8 <add> // Set to true to disable this control <add> this.noPan = false; <add> this.keyPanSpeed = 7.0; // pixels moved per arrow key push <ide> <del> if ( lastPosition.distanceToSquared( this.object.position ) > EPS <del> || 8 * (1 - lastQuaternion.dot(this.object.quaternion)) > EPS ) { <add> // Set to true to automatically rotate around the target <add> this.autoRotate = false; <add> this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60 <ide> <del> this.dispatchEvent( changeEvent ); <add> // Set to true to disable use of the keys <add> this.noKeys = false; <ide> <del> lastPosition.copy( this.object.position ); <del> lastQuaternion.copy (this.object.quaternion ); <add> // The four arrow keys <add> this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; <ide> <del> } <add> // Mouse buttons <add> this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT }; <ide> <del> }; <add> //////////// <add> // internals <ide> <add> var scope = this; <ide> <del> this.reset = function () { <add> var rotateStart = new THREE.Vector2(); <add> var rotateEnd = new THREE.Vector2(); <add> var rotateDelta = new THREE.Vector2(); <ide> <del> state = STATE.NONE; <add> var panStart = new THREE.Vector2(); <add> var panEnd = new THREE.Vector2(); <add> var panDelta = new THREE.Vector2(); <ide> <del> this.target.copy( this.target0 ); <del> this.object.position.copy( this.position0 ); <del> this.object.zoom = this.zoom0; <add> var dollyStart = new THREE.Vector2(); <add> var dollyEnd = new THREE.Vector2(); <add> var dollyDelta = new THREE.Vector2(); <ide> <del> this.object.updateProjectionMatrix(); <del> this.dispatchEvent( changeEvent ); <add> var STATE = { NONE : -1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 }; <ide> <del> this.update(); <add> var state = STATE.NONE; <ide> <del> }; <add> // for reset <ide> <del> this.getPolarAngle = function () { <add> this.target0 = this.target.clone(); <add> this.position0 = this.object.position.clone(); <add> this.zoom0 = this.object.zoom; <ide> <del> return phi; <add> // events <ide> <del> }; <add> var changeEvent = { type: 'change' }; <add> var startEvent = { type: 'start' }; <add> var endEvent = { type: 'end' }; <ide> <del> this.getAzimuthalAngle = function () { <add> // pass in x,y of change desired in pixel space, <add> // right and down are positive <add> var _pan = this.pan; <add> this.pan = function ( deltaX, deltaY ) { <ide> <del> return theta <add> var element = scope.domElement === document ? scope.domElement.body : scope.domElement; <ide> <del> }; <add> _pan.call( this, deltaX, deltaY, element.clientWidth, element.clientHeight ); <ide> <del> function getAutoRotationAngle() { <add> }; <ide> <del> return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; <add> var _update = this.update; <add> this.update = function() { <ide> <del> } <add> if ( this.autoRotate && state === STATE.NONE ) { <ide> <del> function getZoomScale() { <add> this.rotateLeft( getAutoRotationAngle() ); <ide> <del> return Math.pow( 0.95, scope.zoomSpeed ); <add> } <ide> <del> } <add> if ( _update.call( this ) === true ) { <ide> <del> function onMouseDown( event ) { <add> this.dispatchEvent( changeEvent ); <ide> <del> if ( scope.enabled === false ) return; <del> event.preventDefault(); <add> } <ide> <del> if ( event.button === scope.mouseButtons.ORBIT ) { <del> if ( scope.noRotate === true ) return; <add> }; <ide> <del> state = STATE.ROTATE; <add> this.reset = function () { <ide> <del> rotateStart.set( event.clientX, event.clientY ); <add> state = STATE.NONE; <ide> <del> } else if ( event.button === scope.mouseButtons.ZOOM ) { <del> if ( scope.noZoom === true ) return; <add> this.target.copy( this.target0 ); <add> this.object.position.copy( this.position0 ); <add> this.object.zoom = this.zoom0; <ide> <del> state = STATE.DOLLY; <add> this.object.updateProjectionMatrix(); <add> this.dispatchEvent( changeEvent ); <ide> <del> dollyStart.set( event.clientX, event.clientY ); <add> this.update(); <ide> <del> } else if ( event.button === scope.mouseButtons.PAN ) { <del> if ( scope.noPan === true ) return; <add> }; <ide> <del> state = STATE.PAN; <add> function getAutoRotationAngle() { <ide> <del> panStart.set( event.clientX, event.clientY ); <add> return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; <ide> <ide> } <ide> <del> if ( state !== STATE.NONE ) { <del> document.addEventListener( 'mousemove', onMouseMove, false ); <del> document.addEventListener( 'mouseup', onMouseUp, false ); <del> scope.dispatchEvent( startEvent ); <add> function getZoomScale() { <add> <add> return Math.pow( 0.95, scope.zoomSpeed ); <add> <ide> } <ide> <del> } <add> function onMouseDown( event ) { <ide> <del> function onMouseMove( event ) { <add> if ( scope.enabled === false ) return; <add> event.preventDefault(); <ide> <del> if ( scope.enabled === false ) return; <add> if ( event.button === scope.mouseButtons.ORBIT ) { <add> if ( scope.noRotate === true ) return; <ide> <del> event.preventDefault(); <add> state = STATE.ROTATE; <ide> <del> var element = scope.domElement === document ? scope.domElement.body : scope.domElement; <add> rotateStart.set( event.clientX, event.clientY ); <ide> <del> if ( state === STATE.ROTATE ) { <add> } else if ( event.button === scope.mouseButtons.ZOOM ) { <add> if ( scope.noZoom === true ) return; <ide> <del> if ( scope.noRotate === true ) return; <add> state = STATE.DOLLY; <ide> <del> rotateEnd.set( event.clientX, event.clientY ); <del> rotateDelta.subVectors( rotateEnd, rotateStart ); <add> dollyStart.set( event.clientX, event.clientY ); <ide> <del> // rotating across whole screen goes 360 degrees around <del> scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); <add> } else if ( event.button === scope.mouseButtons.PAN ) { <add> if ( scope.noPan === true ) return; <ide> <del> // rotating up and down along whole screen attempts to go 360, but limited to 180 <del> scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); <add> state = STATE.PAN; <ide> <del> rotateStart.copy( rotateEnd ); <add> panStart.set( event.clientX, event.clientY ); <ide> <del> } else if ( state === STATE.DOLLY ) { <add> } <ide> <del> if ( scope.noZoom === true ) return; <add> if ( state !== STATE.NONE ) { <ide> <del> dollyEnd.set( event.clientX, event.clientY ); <del> dollyDelta.subVectors( dollyEnd, dollyStart ); <add> document.addEventListener( 'mousemove', onMouseMove, false ); <add> document.addEventListener( 'mouseup', onMouseUp, false ); <add> scope.dispatchEvent( startEvent ); <ide> <del> if ( dollyDelta.y > 0 ) { <add> } <ide> <del> scope.dollyIn(); <add> } <ide> <del> } else if ( dollyDelta.y < 0 ) { <add> function onMouseMove( event ) { <ide> <del> scope.dollyOut(); <add> if ( scope.enabled === false ) return; <ide> <del> } <add> event.preventDefault(); <ide> <del> dollyStart.copy( dollyEnd ); <add> var element = scope.domElement === document ? scope.domElement.body : scope.domElement; <ide> <del> } else if ( state === STATE.PAN ) { <add> if ( state === STATE.ROTATE ) { <ide> <del> if ( scope.noPan === true ) return; <add> if ( scope.noRotate === true ) return; <ide> <del> panEnd.set( event.clientX, event.clientY ); <del> panDelta.subVectors( panEnd, panStart ); <add> rotateEnd.set( event.clientX, event.clientY ); <add> rotateDelta.subVectors( rotateEnd, rotateStart ); <ide> <del> scope.pan( panDelta.x, panDelta.y ); <add> // rotating across whole screen goes 360 degrees around <add> scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); <ide> <del> panStart.copy( panEnd ); <add> // rotating up and down along whole screen attempts to go 360, but limited to 180 <add> scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); <ide> <del> } <add> rotateStart.copy( rotateEnd ); <ide> <del> if ( state !== STATE.NONE ) scope.update(); <add> } else if ( state === STATE.DOLLY ) { <ide> <del> } <add> if ( scope.noZoom === true ) return; <ide> <del> function onMouseUp( /* event */ ) { <add> dollyEnd.set( event.clientX, event.clientY ); <add> dollyDelta.subVectors( dollyEnd, dollyStart ); <ide> <del> if ( scope.enabled === false ) return; <add> if ( dollyDelta.y > 0 ) { <ide> <del> document.removeEventListener( 'mousemove', onMouseMove, false ); <del> document.removeEventListener( 'mouseup', onMouseUp, false ); <del> scope.dispatchEvent( endEvent ); <del> state = STATE.NONE; <add> scope.dollyIn( getZoomScale() ); <ide> <del> } <add> } else if ( dollyDelta.y < 0 ) { <ide> <del> function onMouseWheel( event ) { <add> scope.dollyOut( getZoomScale() ); <ide> <del> if ( scope.enabled === false || scope.noZoom === true || state !== STATE.NONE ) return; <add> } <ide> <del> event.preventDefault(); <del> event.stopPropagation(); <add> dollyStart.copy( dollyEnd ); <ide> <del> var delta = 0; <add> } else if ( state === STATE.PAN ) { <ide> <del> if ( event.wheelDelta !== undefined ) { // WebKit / Opera / Explorer 9 <add> if ( scope.noPan === true ) return; <ide> <del> delta = event.wheelDelta; <add> panEnd.set( event.clientX, event.clientY ); <add> panDelta.subVectors( panEnd, panStart ); <ide> <del> } else if ( event.detail !== undefined ) { // Firefox <add> scope.pan( panDelta.x, panDelta.y ); <ide> <del> delta = - event.detail; <add> panStart.copy( panEnd ); <ide> <del> } <add> } <add> <add> if ( state !== STATE.NONE ) scope.update(); <ide> <del> if ( delta > 0 ) { <add> } <ide> <del> scope.dollyOut(); <add> function onMouseUp( /* event */ ) { <ide> <del> } else if ( delta < 0 ) { <add> if ( scope.enabled === false ) return; <ide> <del> scope.dollyIn(); <add> document.removeEventListener( 'mousemove', onMouseMove, false ); <add> document.removeEventListener( 'mouseup', onMouseUp, false ); <add> scope.dispatchEvent( endEvent ); <add> state = STATE.NONE; <ide> <ide> } <ide> <del> scope.update(); <del> scope.dispatchEvent( startEvent ); <del> scope.dispatchEvent( endEvent ); <add> function onMouseWheel( event ) { <ide> <del> } <add> if ( scope.enabled === false || scope.noZoom === true || state !== STATE.NONE ) return; <ide> <del> function onKeyDown( event ) { <add> event.preventDefault(); <add> event.stopPropagation(); <ide> <del> if ( scope.enabled === false || scope.noKeys === true || scope.noPan === true ) return; <add> var delta = 0; <ide> <del> switch ( event.keyCode ) { <add> if ( event.wheelDelta !== undefined ) { // WebKit / Opera / Explorer 9 <ide> <del> case scope.keys.UP: <del> scope.pan( 0, scope.keyPanSpeed ); <del> scope.update(); <del> break; <add> delta = event.wheelDelta; <ide> <del> case scope.keys.BOTTOM: <del> scope.pan( 0, - scope.keyPanSpeed ); <del> scope.update(); <del> break; <add> } else if ( event.detail !== undefined ) { // Firefox <ide> <del> case scope.keys.LEFT: <del> scope.pan( scope.keyPanSpeed, 0 ); <del> scope.update(); <del> break; <add> delta = - event.detail; <ide> <del> case scope.keys.RIGHT: <del> scope.pan( - scope.keyPanSpeed, 0 ); <del> scope.update(); <del> break; <add> } <add> <add> if ( delta > 0 ) { <add> <add> scope.dollyOut( getZoomScale() ); <add> <add> } else if ( delta < 0 ) { <add> <add> scope.dollyIn( getZoomScale() ); <add> <add> } <add> <add> scope.update(); <add> scope.dispatchEvent( startEvent ); <add> scope.dispatchEvent( endEvent ); <ide> <ide> } <ide> <del> } <add> function onKeyDown( event ) { <ide> <del> function touchstart( event ) { <add> if ( scope.enabled === false || scope.noKeys === true || scope.noPan === true ) return; <ide> <del> if ( scope.enabled === false ) return; <add> switch ( event.keyCode ) { <ide> <del> switch ( event.touches.length ) { <add> case scope.keys.UP: <add> scope.pan( 0, scope.keyPanSpeed ); <add> scope.update(); <add> break; <ide> <del> case 1: // one-fingered touch: rotate <add> case scope.keys.BOTTOM: <add> scope.pan( 0, - scope.keyPanSpeed ); <add> scope.update(); <add> break; <ide> <del> if ( scope.noRotate === true ) return; <add> case scope.keys.LEFT: <add> scope.pan( scope.keyPanSpeed, 0 ); <add> scope.update(); <add> break; <ide> <del> state = STATE.TOUCH_ROTATE; <add> case scope.keys.RIGHT: <add> scope.pan( - scope.keyPanSpeed, 0 ); <add> scope.update(); <add> break; <ide> <del> rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); <del> break; <add> } <ide> <del> case 2: // two-fingered touch: dolly <add> } <ide> <del> if ( scope.noZoom === true ) return; <add> function touchstart( event ) { <ide> <del> state = STATE.TOUCH_DOLLY; <add> if ( scope.enabled === false ) return; <ide> <del> var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; <del> var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; <del> var distance = Math.sqrt( dx * dx + dy * dy ); <del> dollyStart.set( 0, distance ); <del> break; <add> switch ( event.touches.length ) { <ide> <del> case 3: // three-fingered touch: pan <add> case 1: // one-fingered touch: rotate <ide> <del> if ( scope.noPan === true ) return; <add> if ( scope.noRotate === true ) return; <ide> <del> state = STATE.TOUCH_PAN; <add> state = STATE.TOUCH_ROTATE; <ide> <del> panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); <del> break; <add> rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); <add> break; <ide> <del> default: <add> case 2: // two-fingered touch: dolly <ide> <del> state = STATE.NONE; <add> if ( scope.noZoom === true ) return; <ide> <del> } <add> state = STATE.TOUCH_DOLLY; <ide> <del> if ( state !== STATE.NONE ) scope.dispatchEvent( startEvent ); <add> var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; <add> var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; <add> var distance = Math.sqrt( dx * dx + dy * dy ); <add> dollyStart.set( 0, distance ); <add> break; <ide> <del> } <add> case 3: // three-fingered touch: pan <ide> <del> function touchmove( event ) { <add> if ( scope.noPan === true ) return; <ide> <del> if ( scope.enabled === false ) return; <add> state = STATE.TOUCH_PAN; <ide> <del> event.preventDefault(); <del> event.stopPropagation(); <add> panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); <add> break; <ide> <del> var element = scope.domElement === document ? scope.domElement.body : scope.domElement; <add> default: <ide> <del> switch ( event.touches.length ) { <add> state = STATE.NONE; <ide> <del> case 1: // one-fingered touch: rotate <add> } <ide> <del> if ( scope.noRotate === true ) return; <del> if ( state !== STATE.TOUCH_ROTATE ) return; <add> if ( state !== STATE.NONE ) scope.dispatchEvent( startEvent ); <ide> <del> rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); <del> rotateDelta.subVectors( rotateEnd, rotateStart ); <add> } <ide> <del> // rotating across whole screen goes 360 degrees around <del> scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); <del> // rotating up and down along whole screen attempts to go 360, but limited to 180 <del> scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); <add> function touchmove( event ) { <ide> <del> rotateStart.copy( rotateEnd ); <add> if ( scope.enabled === false ) return; <ide> <del> scope.update(); <del> break; <add> event.preventDefault(); <add> event.stopPropagation(); <ide> <del> case 2: // two-fingered touch: dolly <add> var element = scope.domElement === document ? scope.domElement.body : scope.domElement; <ide> <del> if ( scope.noZoom === true ) return; <del> if ( state !== STATE.TOUCH_DOLLY ) return; <add> switch ( event.touches.length ) { <ide> <del> var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; <del> var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; <del> var distance = Math.sqrt( dx * dx + dy * dy ); <add> case 1: // one-fingered touch: rotate <ide> <del> dollyEnd.set( 0, distance ); <del> dollyDelta.subVectors( dollyEnd, dollyStart ); <add> if ( scope.noRotate === true ) return; <add> if ( state !== STATE.TOUCH_ROTATE ) return; <ide> <del> if ( dollyDelta.y > 0 ) { <add> rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); <add> rotateDelta.subVectors( rotateEnd, rotateStart ); <ide> <del> scope.dollyOut(); <add> // rotating across whole screen goes 360 degrees around <add> scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); <add> // rotating up and down along whole screen attempts to go 360, but limited to 180 <add> scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); <ide> <del> } else if ( dollyDelta.y < 0 ) { <add> rotateStart.copy( rotateEnd ); <ide> <del> scope.dollyIn(); <add> scope.update(); <add> break; <ide> <del> } <add> case 2: // two-fingered touch: dolly <ide> <del> dollyStart.copy( dollyEnd ); <add> if ( scope.noZoom === true ) return; <add> if ( state !== STATE.TOUCH_DOLLY ) return; <ide> <del> scope.update(); <del> break; <add> var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; <add> var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; <add> var distance = Math.sqrt( dx * dx + dy * dy ); <ide> <del> case 3: // three-fingered touch: pan <add> dollyEnd.set( 0, distance ); <add> dollyDelta.subVectors( dollyEnd, dollyStart ); <ide> <del> if ( scope.noPan === true ) return; <del> if ( state !== STATE.TOUCH_PAN ) return; <add> if ( dollyDelta.y > 0 ) { <ide> <del> panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); <del> panDelta.subVectors( panEnd, panStart ); <add> scope.dollyOut( getZoomScale() ); <ide> <del> scope.pan( panDelta.x, panDelta.y ); <add> } else if ( dollyDelta.y < 0 ) { <ide> <del> panStart.copy( panEnd ); <add> scope.dollyIn( getZoomScale() ); <ide> <del> scope.update(); <del> break; <add> } <ide> <del> default: <add> dollyStart.copy( dollyEnd ); <ide> <del> state = STATE.NONE; <add> scope.update(); <add> break; <add> <add> case 3: // three-fingered touch: pan <add> <add> if ( scope.noPan === true ) return; <add> if ( state !== STATE.TOUCH_PAN ) return; <add> <add> panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); <add> panDelta.subVectors( panEnd, panStart ); <add> <add> scope.pan( panDelta.x, panDelta.y ); <add> <add> panStart.copy( panEnd ); <add> <add> scope.update(); <add> break; <add> <add> default: <add> <add> state = STATE.NONE; <add> <add> } <ide> <ide> } <ide> <del> } <add> function touchend( /* event */ ) { <ide> <del> function touchend( /* event */ ) { <add> if ( scope.enabled === false ) return; <ide> <del> if ( scope.enabled === false ) return; <add> scope.dispatchEvent( endEvent ); <add> state = STATE.NONE; <ide> <del> scope.dispatchEvent( endEvent ); <del> state = STATE.NONE; <add> } <ide> <del> } <add> this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false ); <add> this.domElement.addEventListener( 'mousedown', onMouseDown, false ); <add> this.domElement.addEventListener( 'mousewheel', onMouseWheel, false ); <add> this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox <ide> <del> this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false ); <del> this.domElement.addEventListener( 'mousedown', onMouseDown, false ); <del> this.domElement.addEventListener( 'mousewheel', onMouseWheel, false ); <del> this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox <add> this.domElement.addEventListener( 'touchstart', touchstart, false ); <add> this.domElement.addEventListener( 'touchend', touchend, false ); <add> this.domElement.addEventListener( 'touchmove', touchmove, false ); <ide> <del> this.domElement.addEventListener( 'touchstart', touchstart, false ); <del> this.domElement.addEventListener( 'touchend', touchend, false ); <del> this.domElement.addEventListener( 'touchmove', touchmove, false ); <add> window.addEventListener( 'keydown', onKeyDown, false ); <ide> <del> window.addEventListener( 'keydown', onKeyDown, false ); <add> // force an update at start <add> this.update(); <ide> <del> // force an update at start <del> this.update(); <add> }; <ide> <del>}; <add> THREE.OrbitControls.prototype = Object.create( OrbitConstraint.prototype ); <add> THREE.OrbitControls.prototype.constructor = THREE.OrbitControls; <ide> <del>THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype ); <del>THREE.OrbitControls.prototype.constructor = THREE.OrbitControls; <add>}());
1
PHP
PHP
remove extra code from event list
e2dea14e0573d9b4293d2eef13b03ec038c203ea
<ide><path>src/Illuminate/Foundation/Console/EventListCommand.php <ide> <ide> use Closure; <ide> use Illuminate\Console\Command; <del>use Illuminate\Foundation\Support\Providers\EventServiceProvider; <ide> use Illuminate\Support\Str; <ide> use ReflectionFunction; <ide> <ide> protected function getEvents() <ide> { <ide> $events = []; <ide> <del> foreach ($this->laravel->getProviders(EventServiceProvider::class) as $provider) { <del> $providerEvents = array_merge_recursive($provider->shouldDiscoverEvents() ? $provider->discoverEvents() : [], $provider->listens()); <del> <del> $events = array_merge_recursive($events, $providerEvents); <del> } <del> <ide> $events = $this->addListenersOnDispatcher($events); <ide> <ide> if ($this->filteringByEvent()) {
1
Java
Java
remove unused variable in test
f140464c1289c0d176823e246bfe21dda62e30df
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/MultipartControllerTests.java <ide> <ide> import java.io.IOException; <ide> import java.nio.charset.StandardCharsets; <del>import java.util.Collections; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Optional; <ide> void multipartRequestWrapped() throws Exception { <ide> Filter filter = new RequestWrappingFilter(); <ide> MockMvc mockMvc = standaloneSetup(new MultipartController()).addFilter(filter).build(); <ide> <del> Map<String, String> jsonMap = Collections.singletonMap("name", "yeeeah"); <ide> mockMvc.perform(multipart("/json").file(jsonPart)).andExpect(status().isFound()); <ide> } <ide>
1
Mixed
Go
fix some typos
5c0d2a0932afb1e9c9e26326a22fdbefa1069463
<ide><path>CHANGELOG.md <ide> be found. <ide> * Add `--format` option to `docker node ls` [#30424](https://github.com/docker/docker/pull/30424) <ide> * Add `--prune` option to `docker stack deploy` to remove services that are no longer defined in the docker-compose file [#31302](https://github.com/docker/docker/pull/31302) <ide> * Add `PORTS` column for `docker service ls` when using `ingress` mode [#30813](https://github.com/docker/docker/pull/30813) <del>- Fix unnescessary re-deploying of tasks when environment-variables are used [#32364](https://github.com/docker/docker/pull/32364) <add>- Fix unnecessary re-deploying of tasks when environment-variables are used [#32364](https://github.com/docker/docker/pull/32364) <ide> - Fix `docker stack deploy` not supporting `endpoint_mode` when deploying from a docker compose file [#32333](https://github.com/docker/docker/pull/32333) <ide> - Proceed with startup if cluster component cannot be created to allow recovering from a broken swarm setup [#31631](https://github.com/docker/docker/pull/31631) <ide> <ide><path>api/types/stats.go <ide> type NetworkStats struct { <ide> RxBytes uint64 `json:"rx_bytes"` <ide> // Packets received. Windows and Linux. <ide> RxPackets uint64 `json:"rx_packets"` <del> // Received errors. Not used on Windows. Note that we dont `omitempty` this <add> // Received errors. Not used on Windows. Note that we don't `omitempty` this <ide> // field as it is expected in the >=v1.21 API stats structure. <ide> RxErrors uint64 `json:"rx_errors"` <ide> // Incoming packets dropped. Windows and Linux. <ide><path>cmd/dockerd/daemon.go <ide> func (cli *DaemonCli) start(opts *daemonOptions) (err error) { <ide> <ide> d.StoreHosts(hosts) <ide> <del> // validate after NewDaemon has restored enabled plugins. Dont change order. <add> // validate after NewDaemon has restored enabled plugins. Don't change order. <ide> if err := validateAuthzPlugins(cli.Config.AuthorizationPlugins, pluginStore); err != nil { <ide> return errors.Wrap(err, "failed to validate authorization plugin") <ide> } <ide><path>integration/service/create_test.go <ide> func TestCreateWithDuplicateNetworkNames(t *testing.T) { <ide> network.WithDriver("bridge"), <ide> ) <ide> <del> // Dupliates with name but with different driver <add> // Duplicates with name but with different driver <ide> n3 := network.CreateNoError(t, context.Background(), client, name, <ide> network.WithDriver("overlay"), <ide> )
4
Ruby
Ruby
use models to match the docs
9dc1871acb467abb18ba4e452d2a7c8039799bcd
<ide><path>railties/test/application/current_attributes_integration_test.rb <ide> class CurrentAttributesIntegrationTest < ActiveSupport::TestCase <ide> setup do <ide> build_app <ide> <del> app_file "app/services/current.rb", <<-RUBY <add> app_file "app/models/current.rb", <<-RUBY <ide> class Current < ActiveSupport::CurrentAttributes <ide> attribute :customer <ide>
1
Javascript
Javascript
fix imageobj.imagemask bug from merge
b873c1f4da297c4d4b1bd743d6d28a975fe75c65
<ide><path>pdf.js <ide> var CanvasGraphics = (function canvasGraphics() { <ide> <ide> var tmpCanvas = new this.ScratchCanvas(w, h); <ide> var tmpCtx = tmpCanvas.getContext('2d'); <del> if (imageObj.imageMask) { <del> var fillColor = this.current.fillColor; <del> tmpCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') && <del> fillColor.type === 'Pattern') ? <del> fillColor.getPattern(tmpCtx) : fillColor; <del> tmpCtx.fillRect(0, 0, w, h); <del> } <add> <add> var fillColor = this.current.fillColor; <add> tmpCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') && <add> fillColor.type === 'Pattern') ? <add> fillColor.getPattern(tmpCtx) : fillColor; <add> tmpCtx.fillRect(0, 0, w, h); <add> <ide> var imgData = tmpCtx.getImageData(0, 0, w, h); <ide> var pixels = imgData.data; <ide>
1
Javascript
Javascript
fix no dumping after `maybereadmore`
357f904169c39bbc9c2d8558bbffce2337c83c1b
<ide><path>lib/_http_incoming.js <ide> exports.readStop = readStop; <ide> function IncomingMessage(socket) { <ide> Stream.Readable.call(this); <ide> <add> // Set this to `true` so that stream.Readable won't attempt to read more <add> // data on `IncomingMessage#push` (see `maybeReadMore` in <add> // `_stream_readable.js`). This is important for proper tracking of <add> // `IncomingMessage#_consuming` which is used to dump requests that users <add> // haven't attempted to read. <add> this._readableState.readingMore = true; <add> <ide> this.socket = socket; <ide> this.connection = socket; <ide> <ide> IncomingMessage.prototype.setTimeout = function(msecs, callback) { <ide> <ide> <ide> IncomingMessage.prototype.read = function(n) { <add> if (!this._consuming) <add> this._readableState.readingMore = false; <ide> this._consuming = true; <ide> this.read = Stream.Readable.prototype.read; <ide> return this.read(n); <ide><path>test/parallel/test-http-no-read-no-dump.js <add>'use strict'; <add>const common = require('../common'); <add>const http = require('http'); <add> <add>let onPause = null; <add> <add>const server = http.createServer((req, res) => { <add> if (req.method === 'GET') <add> return res.end(); <add> <add> res.writeHead(200); <add> res.flushHeaders(); <add> <add> req.connection.on('pause', () => { <add> res.end(); <add> onPause(); <add> }); <add>}).listen(common.PORT, common.mustCall(() => { <add> const agent = new http.Agent({ <add> maxSockets: 1, <add> keepAlive: true <add> }); <add> <add> const post = http.request({ <add> agent: agent, <add> method: 'POST', <add> port: common.PORT, <add> }, common.mustCall((res) => { <add> res.resume(); <add> <add> post.write(Buffer.alloc(16 * 1024).fill('X')); <add> onPause = () => { <add> post.end('something'); <add> }; <add> })); <add> <add> /* What happens here is that the server `end`s the response before we send <add> * `something`, and the client thought that this is a green light for sending <add> * next GET request <add> */ <add> post.write('initial'); <add> <add> http.request({ <add> agent: agent, <add> method: 'GET', <add> port: common.PORT, <add> }, common.mustCall((res) => { <add> server.close(); <add> res.connection.end(); <add> })).end(); <add>}));
2
Python
Python
remove misleading documentation
4c12860f7ae61659aed2675498350a386fc4e122
<ide><path>transformers/tokenization_utils.py <ide> def tokenize(self, text, **kwargs): <ide> Take care of added tokens. <ide> <ide> text: The sequence to be encoded. <del> return_tokens_mapped_to_origin: (optional) Set to True to return the index of each token in the initial whitespace tokenization. (default False). <ide> **kwargs: passed to the child `self.tokenize()` method <ide> """ <ide> def lowercase_text(t):
1
Javascript
Javascript
return time from getvalueforpixel
5b0a0b039ce30f40a5a4a6162667f9eaf4c62f0f
<ide><path>src/adapters/adapter.moment.js <ide> adapters._date.override(typeof moment === 'function' ? { <ide> <ide> endOf: function(time, unit) { <ide> return moment(time).endOf(unit).valueOf(); <del> }, <del> <del> // DEPRECATIONS <del> <del> /** <del> * Provided for backward compatibility with scale.getValueForPixel(). <del> * @deprecated since version 2.8.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del> _create: function(time) { <del> return moment(time); <del> }, <add> } <ide> } : {}); <ide><path>src/core/core.adapters.js <ide> helpers.extend(DateAdapter.prototype, /** @lends DateAdapter */ { <ide> * @param {Unit} unit - the unit as string <ide> * @function <ide> */ <del> endOf: abstract, <del> <del> // DEPRECATIONS <del> <del> /** <del> * Provided for backward compatibility for scale.getValueForPixel(), <del> * this method should be overridden only by the moment adapter. <del> * @deprecated since version 2.8.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del> _create: function(value) { <del> return value; <del> } <add> endOf: abstract <ide> }); <ide> <ide> DateAdapter.override = function(members) { <ide><path>src/scales/scale.time.js <ide> module.exports = Scale.extend({ <ide> var me = this; <ide> var offsets = me._offsets; <ide> var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end; <del> var time = interpolate(me._table, 'pos', pos, 'time'); <del> <del> // DEPRECATION, we should return time directly <del> return me._adapter._create(time); <add> return interpolate(me._table, 'pos', pos, 'time'); <ide> }, <ide> <ide> /** <ide><path>test/specs/scale.time.tests.js <ide> describe('Time scale tests', function() { <ide> jasmine.addMatchers({ <ide> toBeCloseToTime: function() { <ide> return { <del> compare: function(actual, expected) { <add> compare: function(time, expected) { <ide> var result = false; <del> <add> var actual = moment(time); <ide> var diff = actual.diff(expected.value, expected.unit, true); <ide> result = Math.abs(diff) < (expected.threshold !== undefined ? expected.threshold : 0.01); <ide>
4
Ruby
Ruby
add missing test for
69f3f81e6ca6ee7ce184f6eafaf4b1e1b78564c3
<ide><path>activemodel/test/cases/validations/confirmation_validation_test.rb <ide> def title_confirmation=(value) <ide> assert_equal "expected title", model.title_confirmation, <ide> "confirmation validation should not override the writer" <ide> end <add> <add> def test_title_confirmation_with_case_sensitive_option_true <add> Topic.validates_confirmation_of(:title, case_sensitive: true) <add> <add> t = Topic.new(title: "title", title_confirmation: "Title") <add> assert t.invalid? <add> end <add> <add> def test_title_confirmation_with_case_sensitive_option_false <add> Topic.validates_confirmation_of(:title, case_sensitive: false) <add> <add> t = Topic.new(title: "title", title_confirmation: "Title") <add> assert t.valid? <add> end <ide> end
1
Javascript
Javascript
fix popover.android to bubble events correctly
eb21b25e2d9f148a33ac9b542aade05f2e197123
<ide><path>Libraries/Modal/Modal.js <ide> class Modal extends React.Component { <ide> transparent={this.props.transparent} <ide> onRequestClose={this.props.onRequestClose} <ide> onShow={this.props.onShow} <del> style={styles.modal}> <add> style={styles.modal} <add> onStartShouldSetResponder={this._shouldSetResponder} <add> > <ide> <View style={[styles.container, containerBackgroundColor]}> <ide> {this.props.children} <ide> </View> <ide> </RCTModalHostView> <ide> ); <ide> } <add> <add> // We don't want any responder events bubbling out of the modal. <add> _shouldSetResponder(): boolean { <add> return true; <add> } <ide> } <ide> <ide> Modal.propTypes = {
1
Text
Text
fix metadata for v11.8.0 doc changes
bbb2134e7b5d2c736b294deee798124ac91fc245
<ide><path>doc/api/cli.md <ide> $ source node_bash_completion <ide> <ide> ### `--diagnostic-report-directory=directory` <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Location at which the report will be generated. <ide> <ide> ### `--diagnostic-report-filename=filename` <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Name of the file to which the report will be written. <ide> <ide> ### `--diagnostic-report-on-fatalerror` <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Enables the report to be triggered on fatal errors (internal errors within <ide> consumption etc. to reason about the fatal error. <ide> <ide> ### `--diagnostic-report-on-signal` <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Enables report to be generated upon receiving the specified (or predefined) <ide> The signal to trigger the report is specified through `--diagnostic-report-signa <ide> <ide> ### `--diagnostic-report-signal=signal` <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Sets or resets the signal for report generation (not supported on Windows). <ide> Default signal is `SIGUSR2`. <ide> <ide> ### `--diagnostic-report-uncaught-exception` <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Enables report to be generated on un-caught exceptions, if <ide> conjunction with native stack and other runtime environment data. <ide> <ide> ### `--diagnostic-report-verbose` <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Flag that enables additional information to be printed during report generation. <ide> Enable experimental ES module support and caching modules. <ide> <ide> ### `--experimental-policy` <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Use the specified file as a security policy. <ide> Enable experimental top-level `await` keyword support in REPL. <ide> <ide> ### `--experimental-report` <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Enable experimental diagnostic report feature. <ide><path>doc/api/policy.md <ide> # Policies <ide> <del><!--introduced_in=v11.7.0--> <add><!--introduced_in=v11.8.0--> <ide> <!-- type=misc --> <ide> <ide> > Stability: 1 - Experimental <ide><path>doc/api/process.md <ide> relied upon to exist. <ide> <ide> ### process.report.getReport([err]) <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> * `err` {Object} <ide> at [report documentation][]. <ide> <ide> ### process.report.setDiagnosticReportOptions([options]); <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> Set the runtime configuration of diagnostic report data capture. Upon invocation <ide> at [report documentation][]. <ide> <ide> ### process.report.triggerReport([filename][, err]) <ide> <!-- YAML <del>added: v11.7.0 <add>added: v11.8.0 <ide> --> <ide> <ide> * `filename` {string} The file to write into. The `filename` should be <ide><path>doc/api/tls.md <ide> being issued by trusted CA (`options.ca`). <ide> <!-- YAML <ide> added: v0.11.3 <ide> changes: <del> - version: v11.7.0 <add> - version: v11.8.0 <ide> pr-url: https://github.com/nodejs/node/pull/25517 <ide> description: The `timeout` option is supported now. <ide> - version: v8.0.0
4
Mixed
Python
add preprocessing.image to autodocs
5216360a3c70b0f4d685966ef449645fa131ade8
<ide><path>docs/autogen.py <ide> preprocessing.sequence.TimeseriesGenerator, <ide> ] <ide> }, <add> { <add> 'page': 'preprocessing/image.md', <add> 'functions': [ <add> preprocessing.image.random_rotation, <add> preprocessing.image.random_shift, <add> preprocessing.image.random_shear, <add> preprocessing.image.random_zoom, <add> preprocessing.image.random_channel_shift, <add> preprocessing.image.random_brightness, <add> ], <add> 'classes': [ <add> preprocessing.image.ImageDataGenerator, <add> ] <add> }, <ide> { <ide> 'page': 'layers/wrappers.md', <ide> 'all_module_classes': [wrappers], <ide><path>docs/templates/preprocessing/image.md <ide> <del>### ImageDataGenerator <add>### Image Preprocessing <ide> <del>```python <del>keras.preprocessing.image.ImageDataGenerator(featurewise_center=False, <del> samplewise_center=False, <del> featurewise_std_normalization=False, <del> samplewise_std_normalization=False, <del> zca_whitening=False, <del> zca_epsilon=1e-6, <del> rotation_range=0., <del> width_shift_range=0., <del> height_shift_range=0., <del> shear_range=0., <del> zoom_range=0., <del> channel_shift_range=0., <del> fill_mode='nearest', <del> cval=0., <del> horizontal_flip=False, <del> vertical_flip=False, <del> rescale=None, <del> preprocessing_function=None, <del> data_format=K.image_data_format()) <del>``` <del> <del>Generate batches of tensor image data with real-time data augmentation. The data will be looped over (in batches) indefinitely. <del> <del>- __Arguments__: <del> - __featurewise_center__: Boolean. Set input mean to 0 over the dataset, feature-wise. <del> - __samplewise_center__: Boolean. Set each sample mean to 0. <del> - __featurewise_std_normalization__: Boolean. Divide inputs by std of the dataset, feature-wise. <del> - __samplewise_std_normalization__: Boolean. Divide each input by its std. <del> - __zca_epsilon__: epsilon for ZCA whitening. Default is 1e-6. <del> - __zca_whitening__: Boolean. Apply ZCA whitening. <del> - __rotation_range__: Int. Degree range for random rotations. <del> - __width_shift_range__: Float (fraction of total width). Range for random horizontal shifts. <del> - __height_shift_range__: Float (fraction of total height). Range for random vertical shifts. <del> - __shear_range__: Float. Shear Intensity (Shear angle in counter-clockwise direction as radians) <del> - __zoom_range__: Float or [lower, upper]. Range for random zoom. If a float, `[lower, upper] = [1-zoom_range, 1+zoom_range]`. <del> - __channel_shift_range__: Float. Range for random channel shifts. <del> - __fill_mode__: One of {"constant", "nearest", "reflect" or "wrap"}. Points outside the boundaries of the input are filled according to the given mode: <del> * "constant": `kkkkkkkk|abcd|kkkkkkkk` (`cval=k`) <del> * "nearest": `aaaaaaaa|abcd|dddddddd` <del> * "reflect": `abcddcba|abcd|dcbaabcd` <del> * "wrap": `abcdabcd|abcd|abcdabcd` <del> - __cval__: Float or Int. Value used for points outside the boundaries when `fill_mode = "constant"`. <del> - __horizontal_flip__: Boolean. Randomly flip inputs horizontally. <del> - __vertical_flip__: Boolean. Randomly flip inputs vertically. <del> - __rescale__: rescaling factor. Defaults to None. If None or 0, no rescaling is applied, <del> otherwise we multiply the data by the value provided (before applying <del> any other transformation). <del> - __preprocessing_function__: function that will be implied on each input. <del> The function will run before any other modification on it. <del> The function should take one argument: <del> one image (Numpy tensor with rank 3), <del> and should output a Numpy tensor with the same shape. <del> - __data_format__: One of {"channels_first", "channels_last"}. <del> "channels_last" mode means that the images should have shape `(samples, height, width, channels)`, <del> "channels_first" mode means that the images should have shape `(samples, channels, height, width)`. <del> It defaults to the `image_data_format` value found in your <del> Keras config file at `~/.keras/keras.json`. <del> If you never set it, then it will be "channels_last". <del> <del>- __Methods__: <del> - __fit(x)__: Compute the internal data stats related to the data-dependent transformations, based on an array of sample data. <del> Only required if featurewise_center or featurewise_std_normalization or zca_whitening. <del> - __Arguments__: <del> - __x__: sample data. Should have rank 4. <del> In case of grayscale data, <del> the channels axis should have value 1, and in case <del> of RGB data, it should have value 3. <del> - __augment__: Boolean (default: False). Whether to fit on randomly augmented samples. <del> - __rounds__: int (default: 1). If augment, how many augmentation passes over the data to use. <del> - __seed__: int (default: None). Random seed. <del> - __flow(x, y)__: Takes numpy data & label arrays, and generates batches of augmented/normalized data. Yields batches indefinitely, in an infinite loop. <del> - __Arguments__: <del> - __x__: data. Should have rank 4. <del> In case of grayscale data, <del> the channels axis should have value 1, and in case <del> of RGB data, it should have value 3. <del> - __y__: labels. <del> - __batch_size__: int (default: 32). <del> - __shuffle__: boolean (default: True). <del> - __seed__: int (default: None). <del> - __save_to_dir__: None or str (default: None). This allows you to optionally specify a directory to which to save the augmented pictures being generated (useful for visualizing what you are doing). <del> - __save_prefix__: str (default: `''`). Prefix to use for filenames of saved pictures (only relevant if `save_to_dir` is set). <del> - __save_format__: one of "png", "jpeg" (only relevant if `save_to_dir` is set). Default: "png". <del> - __yields__: Tuples of `(x, y)` where `x` is a numpy array of image data and `y` is a numpy array of corresponding labels. <del> The generator loops indefinitely. <del> - __flow_from_directory(directory)__: Takes the path to a directory, and generates batches of augmented/normalized data. Yields batches indefinitely, in an infinite loop. <del> - __Arguments__: <del> - __directory__: path to the target directory. It should contain one subdirectory per class. <del> Any PNG, JPG, BMP, PPM or TIF images inside each of the subdirectories directory tree will be included in the generator. <del> See [this script](https://gist.github.com/fchollet/0830affa1f7f19fd47b06d4cf89ed44d) for more details. <del> - __target_size__: tuple of integers `(height, width)`, default: `(256, 256)`. <del> The dimensions to which all images found will be resized. <del> - __color_mode__: one of "grayscale", "rbg". Default: "rgb". Whether the images will be converted to have 1 or 3 color channels. <del> - __classes__: optional list of class subdirectories (e.g. `['dogs', 'cats']`). Default: None. If not provided, the list of classes will be automatically inferred from the subdirectory names/structure under `directory`, where each subdirectory will be treated as a different class (and the order of the classes, which will map to the label indices, will be alphanumeric). The dictionary containing the mapping from class names to class indices can be obtained via the attribute `class_indices`. <del> - __class_mode__: one of "categorical", "binary", "sparse", "input" or None. Default: "categorical". Determines the type of label arrays that are returned: "categorical" will be 2D one-hot encoded labels, "binary" will be 1D binary labels, "sparse" will be 1D integer labels, "input" will be images identical to input images (mainly used to work with autoencoders). If None, no labels are returned (the generator will only yield batches of image data, which is useful to use `model.predict_generator()`, `model.evaluate_generator()`, etc.). Please note that in case of class_mode None, the data still needs to reside in a subdirectory of `directory` for it to work correctly. <del> - __batch_size__: size of the batches of data (default: 32). <del> - __shuffle__: whether to shuffle the data (default: True) <del> - __seed__: optional random seed for shuffling and transformations. <del> - __save_to_dir__: None or str (default: None). This allows you to optionally specify a directory to which to save the augmented pictures being generated (useful for visualizing what you are doing). <del> - __save_prefix__: str. Prefix to use for filenames of saved pictures (only relevant if `save_to_dir` is set). <del> - __save_format__: one of "png", "jpeg" (only relevant if `save_to_dir` is set). Default: "png". <del> - __follow_links__: whether to follow symlinks inside class subdirectories (default: False). <del> <del> <del>- __Examples__: <del> <del>Example of using `.flow(x, y)`: <del> <del>```python <del>(x_train, y_train), (x_test, y_test) = cifar10.load_data() <del>y_train = np_utils.to_categorical(y_train, num_classes) <del>y_test = np_utils.to_categorical(y_test, num_classes) <del> <del>datagen = ImageDataGenerator( <del> featurewise_center=True, <del> featurewise_std_normalization=True, <del> rotation_range=20, <del> width_shift_range=0.2, <del> height_shift_range=0.2, <del> horizontal_flip=True) <del> <del># compute quantities required for featurewise normalization <del># (std, mean, and principal components if ZCA whitening is applied) <del>datagen.fit(x_train) <del> <del># fits the model on batches with real-time data augmentation: <del>model.fit_generator(datagen.flow(x_train, y_train, batch_size=32), <del> steps_per_epoch=len(x_train) / 32, epochs=epochs) <del> <del># here's a more "manual" example <del>for e in range(epochs): <del> print('Epoch', e) <del> batches = 0 <del> for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32): <del> model.fit(x_batch, y_batch) <del> batches += 1 <del> if batches >= len(x_train) / 32: <del> # we need to break the loop by hand because <del> # the generator loops indefinitely <del> break <del>``` <del> <del>Example of using `.flow_from_directory(directory)`: <del> <del>```python <del>train_datagen = ImageDataGenerator( <del> rescale=1./255, <del> shear_range=0.2, <del> zoom_range=0.2, <del> horizontal_flip=True) <del> <del>test_datagen = ImageDataGenerator(rescale=1./255) <del> <del>train_generator = train_datagen.flow_from_directory( <del> 'data/train', <del> target_size=(150, 150), <del> batch_size=32, <del> class_mode='binary') <del> <del>validation_generator = test_datagen.flow_from_directory( <del> 'data/validation', <del> target_size=(150, 150), <del> batch_size=32, <del> class_mode='binary') <del> <del>model.fit_generator( <del> train_generator, <del> steps_per_epoch=2000, <del> epochs=50, <del> validation_data=validation_generator, <del> validation_steps=800) <del>``` <del> <del>Example of transforming images and masks together. <del> <del>```python <del># we create two instances with the same arguments <del>data_gen_args = dict(featurewise_center=True, <del> featurewise_std_normalization=True, <del> rotation_range=90., <del> width_shift_range=0.1, <del> height_shift_range=0.1, <del> zoom_range=0.2) <del>image_datagen = ImageDataGenerator(**data_gen_args) <del>mask_datagen = ImageDataGenerator(**data_gen_args) <del> <del># Provide the same seed and keyword arguments to the fit and flow methods <del>seed = 1 <del>image_datagen.fit(images, augment=True, seed=seed) <del>mask_datagen.fit(masks, augment=True, seed=seed) <del> <del>image_generator = image_datagen.flow_from_directory( <del> 'data/images', <del> class_mode=None, <del> seed=seed) <del> <del>mask_generator = mask_datagen.flow_from_directory( <del> 'data/masks', <del> class_mode=None, <del> seed=seed) <del> <del># combine generators into one which yields image and masks <del>train_generator = zip(image_generator, mask_generator) <del> <del>model.fit_generator( <del> train_generator, <del> steps_per_epoch=2000, <del> epochs=50) <del>``` <add>{{autogenerated}} <ide><path>keras/preprocessing/__init__.py <add>from . import image <add>from . import sequence <add>from . import text <ide><path>keras/preprocessing/image.py <ide> def random_zoom(x, zoom_range, row_axis=1, col_axis=2, channel_axis=0, <ide> <ide> <ide> def random_channel_shift(x, intensity, channel_axis=0): <add> """Perform a random channel shift. <add> <add> # Arguments <add> x: Input tensor. Must be 3D. <add> intensity: Transformation intensity. <add> channel_axis: Index of axis for channels in the input tensor. <add> <add> # Returns <add> Numpy image tensor. <add> <add> """ <ide> x = np.rollaxis(x, channel_axis, 0) <ide> min_x, max_x = np.min(x), np.max(x) <ide> channel_images = [np.clip(x_channel + np.random.uniform(-intensity, intensity), min_x, max_x) <ide> def random_channel_shift(x, intensity, channel_axis=0): <ide> <ide> <ide> def random_brightness(x, brightness_range): <add> """Perform a random brightness shift. <add> <add> # Arguments <add> x: Input tensor. Must be 3D. <add> brightness_range: Tuple of floats; brightness range. <add> channel_axis: Index of axis for channels in the input tensor. <add> <add> # Returns <add> Numpy image tensor. <add> <add> # Raises <add> ValueError if `brightness_range` isn't a tuple. <add> <add> """ <ide> if len(brightness_range) != 2: <ide> raise ValueError('`brightness_range should be tuple or list of two floats. ' <ide> 'Received arg: ', brightness_range) <ide> def list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'): <ide> <ide> <ide> class ImageDataGenerator(object): <del> """Generate minibatches of image data with real-time data augmentation. <add> """Generate batches of tensor image data with real-time data augmentation. <add> The data will be looped over (in batches). <ide> <ide> # Arguments <del> featurewise_center: set input mean to 0 over the dataset. <del> samplewise_center: set each sample mean to 0. <del> featurewise_std_normalization: divide inputs by std of the dataset. <del> samplewise_std_normalization: divide each input by its std. <del> zca_whitening: apply ZCA whitening. <add> featurewise_center: Boolean. Set input mean to 0 over the dataset, feature-wise. <add> samplewise_center: Boolean. Set each sample mean to 0. <add> featurewise_std_normalization: Boolean. Divide inputs by std of the dataset, feature-wise. <add> samplewise_std_normalization: Boolean. Divide each input by its std. <ide> zca_epsilon: epsilon for ZCA whitening. Default is 1e-6. <del> rotation_range: degrees (0 to 180). <del> width_shift_range: fraction of total width, if < 1, or pixels if >= 1. <del> height_shift_range: fraction of total height, if < 1, or pixels if >= 1. <del> brightness_range: the range of brightness to apply <del> shear_range: shear intensity (shear angle in degrees). <del> zoom_range: amount of zoom. if scalar z, zoom will be randomly picked <del> in the range [1-z, 1+z]. A sequence of two can be passed instead <del> to select this range. <del> channel_shift_range: shift range for each channel. <del> fill_mode: points outside the boundaries are filled according to the <del> given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default <del> is 'nearest'. <del> Points outside the boundaries of the input are filled according to the given mode: <del> 'constant': kkkkkkkk|abcd|kkkkkkkk (cval=k) <del> 'nearest': aaaaaaaa|abcd|dddddddd <del> 'reflect': abcddcba|abcd|dcbaabcd <del> 'wrap': abcdabcd|abcd|abcdabcd <del> cval: value used for points outside the boundaries when fill_mode is <del> 'constant'. Default is 0. <del> horizontal_flip: whether to randomly flip images horizontally. <del> vertical_flip: whether to randomly flip images vertically. <del> rescale: rescaling factor. If None or 0, no rescaling is applied, <del> otherwise we multiply the data by the value provided. This is <del> applied after the `preprocessing_function` (if any provided) <del> but before any other transformation. <add> zca_whitening: Boolean. Apply ZCA whitening. <add> rotation_range: Int. Degree range for random rotations. <add> width_shift_range: Float (fraction of total width). Range for random horizontal shifts. <add> height_shift_range: Float (fraction of total height). Range for random vertical shifts. <add> shear_range: Float. Shear Intensity (Shear angle in counter-clockwise direction as radians) <add> zoom_range: Float or [lower, upper]. Range for random zoom. If a float, `[lower, upper] = [1-zoom_range, 1+zoom_range]`. <add> channel_shift_range: Float. Range for random channel shifts. <add> fill_mode: One of {"constant", "nearest", "reflect" or "wrap"}. Default is 'nearest'. <add> Points outside the boundaries of the input are filled according to the given mode: <add> 'constant': kkkkkkkk|abcd|kkkkkkkk (cval=k) <add> 'nearest': aaaaaaaa|abcd|dddddddd <add> 'reflect': abcddcba|abcd|dcbaabcd <add> 'wrap': abcdabcd|abcd|abcdabcd <add> cval: Float or Int. Value used for points outside the boundaries when `fill_mode = "constant"`. <add> horizontal_flip: Boolean. Randomly flip inputs horizontally. <add> vertical_flip: Boolean. Randomly flip inputs vertically. <add> rescale: rescaling factor. Defaults to None. If None or 0, no rescaling is applied, <add> otherwise we multiply the data by the value provided (before applying <add> any other transformation). <ide> preprocessing_function: function that will be implied on each input. <del> The function will run before any other modification on it. <del> The function should take one argument: <del> one image (Numpy tensor with rank 3), <del> and should output a Numpy tensor with the same shape. <del> data_format: 'channels_first' or 'channels_last'. In 'channels_first' mode, the channels dimension <del> (the depth) is at index 1, in 'channels_last' mode it is at index 3. <add> The function will run after the image is resized and augmented. <add> The function should take one argument: <add> one image (Numpy tensor with rank 3), <add> and should output a Numpy tensor with the same shape. <add> data_format: One of {"channels_first", "channels_last"}. <add> "channels_last" mode means that the images should have shape `(samples, height, width, channels)`, <add> "channels_first" mode means that the images should have shape `(samples, channels, height, width)`. <ide> It defaults to the `image_data_format` value found in your <ide> Keras config file at `~/.keras/keras.json`. <ide> If you never set it, then it will be "channels_last". <del> validation_split: fraction of images reserved for validation (strictly between 0 and 1). <add> validation_split: Float. Fraction of images reserved for validation (strictly between 0 and 1). <add> <add> # Examples <add> Example of using `.flow(x, y)`: <add> <add> ```python <add> (x_train, y_train), (x_test, y_test) = cifar10.load_data() <add> y_train = np_utils.to_categorical(y_train, num_classes) <add> y_test = np_utils.to_categorical(y_test, num_classes) <add> <add> datagen = ImageDataGenerator( <add> featurewise_center=True, <add> featurewise_std_normalization=True, <add> rotation_range=20, <add> width_shift_range=0.2, <add> height_shift_range=0.2, <add> horizontal_flip=True) <add> <add> # compute quantities required for featurewise normalization <add> # (std, mean, and principal components if ZCA whitening is applied) <add> datagen.fit(x_train) <add> <add> # fits the model on batches with real-time data augmentation: <add> model.fit_generator(datagen.flow(x_train, y_train, batch_size=32), <add> steps_per_epoch=len(x_train) / 32, epochs=epochs) <add> <add> # here's a more "manual" example <add> for e in range(epochs): <add> print('Epoch', e) <add> batches = 0 <add> for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32): <add> model.fit(x_batch, y_batch) <add> batches += 1 <add> if batches >= len(x_train) / 32: <add> # we need to break the loop by hand because <add> # the generator loops indefinitely <add> break <add> ``` <add> Example of using `.flow_from_directory(directory)`: <add> <add> ```python <add> train_datagen = ImageDataGenerator( <add> rescale=1./255, <add> shear_range=0.2, <add> zoom_range=0.2, <add> horizontal_flip=True) <add> <add> test_datagen = ImageDataGenerator(rescale=1./255) <add> <add> train_generator = train_datagen.flow_from_directory( <add> 'data/train', <add> target_size=(150, 150), <add> batch_size=32, <add> class_mode='binary') <add> <add> validation_generator = test_datagen.flow_from_directory( <add> 'data/validation', <add> target_size=(150, 150), <add> batch_size=32, <add> class_mode='binary') <add> <add> model.fit_generator( <add> train_generator, <add> steps_per_epoch=2000, <add> epochs=50, <add> validation_data=validation_generator, <add> validation_steps=800) <add> ``` <add> <add> Example of transforming images and masks together. <add> <add> ```python <add> # we create two instances with the same arguments <add> data_gen_args = dict(featurewise_center=True, <add> featurewise_std_normalization=True, <add> rotation_range=90., <add> width_shift_range=0.1, <add> height_shift_range=0.1, <add> zoom_range=0.2) <add> image_datagen = ImageDataGenerator(**data_gen_args) <add> mask_datagen = ImageDataGenerator(**data_gen_args) <add> <add> # Provide the same seed and keyword arguments to the fit and flow methods <add> seed = 1 <add> image_datagen.fit(images, augment=True, seed=seed) <add> mask_datagen.fit(masks, augment=True, seed=seed) <add> <add> image_generator = image_datagen.flow_from_directory( <add> 'data/images', <add> class_mode=None, <add> seed=seed) <add> <add> mask_generator = mask_datagen.flow_from_directory( <add> 'data/masks', <add> class_mode=None, <add> seed=seed) <add> <add> # combine generators into one which yields image and masks <add> train_generator = zip(image_generator, mask_generator) <add> <add> model.fit_generator( <add> train_generator, <add> steps_per_epoch=2000, <add> epochs=50) <add> ``` <ide> """ <ide> <ide> def __init__(self, <ide> def __init__(self, <ide> <ide> def flow(self, x, y=None, batch_size=32, shuffle=True, seed=None, <ide> save_to_dir=None, save_prefix='', save_format='png', subset=None): <add> """Takes numpy data & label arrays, and generates batches of <add> augmented/normalized data. <add> <add> # Arguments <add> x: data. Should have rank 4. <add> In case of grayscale data, <add> the channels axis should have value 1, and in case <add> of RGB data, it should have value 3. <add> y: labels. <add> batch_size: int (default: 32). <add> shuffle: boolean (default: True). <add> seed: int (default: None). <add> save_to_dir: None or str (default: None). <add> This allows you to optionally specify a directory <add> to which to save the augmented pictures being generated <add> (useful for visualizing what you are doing). <add> save_prefix: str (default: `''`). Prefix to use for filenames of saved pictures <add> (only relevant if `save_to_dir` is set). <add> save_format: one of "png", "jpeg" (only relevant if `save_to_dir` is set). Default: "png". <add> <add> # Returns <add> An Iterator yielding tuples of `(x, y)` where `x` is a numpy array of image data and <add> `y` is a numpy array of corresponding labels.""" <ide> return NumpyArrayIterator( <ide> x, y, self, <ide> batch_size=batch_size, <ide> def flow_from_directory(self, directory, <ide> follow_links=False, <ide> subset=None, <ide> interpolation='nearest'): <add> """Takes the path to a directory, and generates batches of augmented/normalized data. <add> <add> # Arguments <add> directory: path to the target directory. <add> It should contain one subdirectory per class. <add> Any PNG, JPG, BMP, PPM or TIF images inside each of the subdirectories directory tree will be included in the generator. <add> See [this script](https://gist.github.com/fchollet/0830affa1f7f19fd47b06d4cf89ed44d) for more details. <add> target_size: tuple of integers `(height, width)`, default: `(256, 256)`. <add> The dimensions to which all images found will be resized. <add> color_mode: one of "grayscale", "rbg". Default: "rgb". <add> Whether the images will be converted to have 1 or 3 color channels. <add> classes: optional list of class subdirectories (e.g. `['dogs', 'cats']`). <add> Default: None. If not provided, the list of classes will <add> be automatically inferred from the subdirectory names/structure under `directory`, <add> where each subdirectory will be treated as a different class <add> (and the order of the classes, which will map to the label indices, will be alphanumeric). <add> The dictionary containing the mapping from class names to class <add> indices can be obtained via the attribute `class_indices`. <add> class_mode: one of "categorical", "binary", "sparse", "input" or None. <add> Default: "categorical". Determines the type of label arrays that are <add> returned: "categorical" will be 2D one-hot encoded labels, "binary" will be 1D binary labels, <add> "sparse" will be 1D integer labels, "input" will be images identical to input images (mainly used to work with autoencoders). <add> If None, no labels are returned (the generator will only yield batches of image data, which is useful to use <add> `model.predict_generator()`, `model.evaluate_generator()`, etc.). <add> Please note that in case of class_mode None, <add> the data still needs to reside in a subdirectory of `directory` for it to work correctly. <add> batch_size: size of the batches of data (default: 32). <add> shuffle: whether to shuffle the data (default: True) <add> seed: optional random seed for shuffling and transformations. <add> save_to_dir: None or str (default: None). This allows you to optionally specify a directory to which to save <add> the augmented pictures being generated (useful for visualizing what you are doing). <add> save_prefix: str. Prefix to use for filenames of saved pictures (only relevant if `save_to_dir` is set). <add> save_format: one of "png", "jpeg" (only relevant if `save_to_dir` is set). Default: "png". <add> follow_links: whether to follow symlinks inside class subdirectories (default: False). <add> <add> # Returns <add> A DirectoryIterator yielding tuples of `(x, y)` where `x` is a numpy array of image data and <add> `y` is a numpy array of corresponding labels. <add> """ <ide> return DirectoryIterator( <ide> directory, self, <ide> target_size=target_size, color_mode=color_mode, <ide> def fit(self, x, <ide> augment=False, <ide> rounds=1, <ide> seed=None): <del> """Fits internal statistics to some sample data. <del> <del> Required for featurewise_center, featurewise_std_normalization <del> and zca_whitening. <add> """Compute the internal data stats related to the data-dependent transformations, based on an array of sample data. <add> Only required if featurewise_center or featurewise_std_normalization or zca_whitening. <ide> <ide> # Arguments <del> x: Numpy array, the data to fit on. Should have rank 4. <del> In case of grayscale data, <del> the channels axis should have value 1, and in case <del> of RGB data, it should have value 3. <del> augment: Whether to fit on randomly augmented samples <del> rounds: If `augment`, <del> how many augmentation passes to do over the data <del> seed: random seed. <del> <del> # Raises <del> ValueError: in case of invalid input `x`. <del> """ <add> x: sample data. Should have rank 4. <add> In case of grayscale data, <add> the channels axis should have value 1, and in case <add> of RGB data, it should have value 3. <add> augment: Boolean (default: False). Whether to fit on randomly augmented samples. <add> rounds: int (default: 1). If augment, how many augmentation passes over the data to use. <add> seed: int (default: None). Random seed. <add> """ <ide> x = np.asarray(x, dtype=K.floatx()) <ide> if x.ndim != 4: <ide> raise ValueError('Input to `.fit()` should have rank 4. ' <ide><path>tests/test_documentation.py <ide> <ide> import pytest <ide> <del>modules = ['keras.layers', 'keras.models', 'keras', 'keras.backend.tensorflow_backend'] <add>modules = ['keras.layers', 'keras.models', 'keras', 'keras.backend.tensorflow_backend', 'keras.preprocessing.image'] <ide> accepted_name = ['from_config'] <ide> accepted_module = ['keras.legacy.layers', 'keras.utils.generic_utils'] <ide> <ide> def handle_class(name, member): <ide> <ide> <ide> def handle_function(name, member): <del> if is_accepted(name, member): <add> if is_accepted(name, member) or member_too_small(member): <add> # We don't need to check this one. <ide> return <ide> doc = member.__doc__ <del> if doc is None and not member_too_small(member): <add> if doc is None: <ide> raise ValueError("{} function doesn't have any documentation".format(name), <ide> member.__module__, inspect.getmodule(member).__file__) <add> <ide> args = list(inspect.signature(member).parameters.keys()) <ide> assert_args_presence(args, doc, member, name) <ide> assert_function_style(name, member, doc, args)
5
Ruby
Ruby
add link to rollback in transactions doc
8a3dcf941d9d90c3aee328287a1dd7440ff38f4e
<ide><path>activerecord/lib/active_record/transactions.rb <ide> module Transactions <ide> # be propagated (after triggering the ROLLBACK), so you should be ready to <ide> # catch those in your application code. <ide> # <del> # One exception is the ActiveRecord::Rollback exception, which will trigger <del> # a ROLLBACK when raised, but not be re-raised by the transaction block. <add> # One exception is the {ActiveRecord::Rollback}[rdoc-ref:Rollback] exception, which will trigger <add> # a ROLLBACK when raised, but not be re-raised by the transaction block. Any <add> # other exception will be re-raised. <ide> # <ide> # *Warning*: one should not catch ActiveRecord::StatementInvalid exceptions <ide> # inside a transaction block. ActiveRecord::StatementInvalid exceptions indicate that an
1
Go
Go
use termios via cgo
244af451e9bdff5c87bca84e4c15193fc9eebc64
<ide><path>pkg/term/term.go <ide> func SetWinsize(fd uintptr, ws *Winsize) error { <ide> // IsTerminal returns true if the given file descriptor is a terminal. <ide> func IsTerminal(fd uintptr) bool { <ide> var termios Termios <del> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&termios))) <del> return err == 0 <add> return tcget(fd, &termios) == 0 <ide> } <ide> <ide> // Restore restores the terminal connected to the given file descriptor to a <ide> func RestoreTerminal(fd uintptr, state *State) error { <ide> if state == nil { <ide> return ErrInvalidState <ide> } <del> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&state.termios))) <del> if err != 0 { <add> if err := tcset(fd, &state.termios); err != 0 { <ide> return err <ide> } <ide> return nil <ide> } <ide> <ide> func SaveState(fd uintptr) (*State, error) { <ide> var oldState State <del> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { <add> if err := tcget(fd, &oldState.termios); err != 0 { <ide> return nil, err <ide> } <ide> <ide> func DisableEcho(fd uintptr, state *State) error { <ide> newState := state.termios <ide> newState.Lflag &^= syscall.ECHO <ide> <del> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 { <add> if err := tcset(fd, &newState); err != 0 { <ide> return err <ide> } <ide> handleInterrupt(fd, state) <ide><path>pkg/term/term_cgo.go <add>// +build !windows,cgo <add> <add>package term <add> <add>import ( <add> "syscall" <add> "unsafe" <add>) <add> <add>// #include <termios.h> <add>import "C" <add> <add>type Termios syscall.Termios <add> <add>// MakeRaw put the terminal connected to the given file descriptor into raw <add>// mode and returns the previous state of the terminal so that it can be <add>// restored. <add>func MakeRaw(fd uintptr) (*State, error) { <add> var oldState State <add> if err := tcget(fd, &oldState.termios); err != 0 { <add> return nil, err <add> } <add> <add> newState := oldState.termios <add> <add> C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState))) <add> if err := tcset(fd, &newState); err != 0 { <add> return nil, err <add> } <add> return &oldState, nil <add>} <add> <add>func tcget(fd uintptr, p *Termios) syscall.Errno { <add> ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p))) <add> if ret != 0 { <add> return err.(syscall.Errno) <add> } <add> return 0 <add>} <add> <add>func tcset(fd uintptr, p *Termios) syscall.Errno { <add> ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p))) <add> if ret != 0 { <add> return err.(syscall.Errno) <add> } <add> return 0 <add>} <ide><path>pkg/term/term_nocgo.go <add>// +build !windows,!cgo <add> <add>package term <add> <add>import ( <add> "syscall" <add> "unsafe" <add>) <add> <add>func tcget(fd uintptr, p *Termios) syscall.Errno { <add> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(p))) <add> return err <add>} <add> <add>func tcset(fd uintptr, p *Termios) syscall.Errno { <add> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(p))) <add> return err <add>} <ide><path>pkg/term/termios_darwin.go <add>// +build !cgo <add> <ide> package term <ide> <ide> import ( <ide><path>pkg/term/termios_freebsd.go <add>// +build !cgo <add> <ide> package term <ide> <ide> import ( <ide><path>pkg/term/termios_linux.go <add>// +build !cgo <add> <ide> package term <ide> <ide> import (
6
Go
Go
enhance testing infra
b09cb39fa5cb326bc8c55aa2743a9759b5543a72
<ide><path>libnetwork/cmd/networkdb-test/dbclient/ndbClient.go <ide> package dbclient <ide> <ide> import ( <ide> "context" <add> "fmt" <ide> "io/ioutil" <ide> "log" <ide> "net" <ide> type resultTuple struct { <ide> } <ide> <ide> func httpGetFatalError(ip, port, path string) { <del> // for { <ide> body, err := httpGet(ip, port, path) <ide> if err != nil || !strings.Contains(string(body), "OK") { <del> // if strings.Contains(err.Error(), "EOF") { <del> // logrus.Warnf("Got EOF path:%s err:%s", path, err) <del> // continue <del> // } <ide> log.Fatalf("[%s] error %s %s", path, err, body) <ide> } <del> // break <del> // } <ide> } <ide> <ide> func httpGet(ip, port, path string) ([]byte, error) { <ide> func clusterPeersNumber(ip, port string, doneCh chan resultTuple) { <ide> body, err := httpGet(ip, port, "/clusterpeers") <ide> <ide> if err != nil { <del> logrus.Errorf("clusterPeers %s there was an error: %s\n", ip, err) <add> logrus.Errorf("clusterPeers %s there was an error: %s", ip, err) <ide> doneCh <- resultTuple{id: ip, result: -1} <ide> return <ide> } <ide> func networkPeersNumber(ip, port, networkName string, doneCh chan resultTuple) { <ide> body, err := httpGet(ip, port, "/networkpeers?nid="+networkName) <ide> <ide> if err != nil { <del> logrus.Errorf("networkPeersNumber %s there was an error: %s\n", ip, err) <add> logrus.Errorf("networkPeersNumber %s there was an error: %s", ip, err) <ide> doneCh <- resultTuple{id: ip, result: -1} <ide> return <ide> } <ide> func dbTableEntriesNumber(ip, port, networkName, tableName string, doneCh chan r <ide> body, err := httpGet(ip, port, "/gettable?nid="+networkName+"&tname="+tableName) <ide> <ide> if err != nil { <del> logrus.Errorf("tableEntriesNumber %s there was an error: %s\n", ip, err) <add> logrus.Errorf("tableEntriesNumber %s there was an error: %s", ip, err) <ide> doneCh <- resultTuple{id: ip, result: -1} <ide> return <ide> } <ide> func dbTableEntriesNumber(ip, port, networkName, tableName string, doneCh chan r <ide> doneCh <- resultTuple{id: ip, result: entriesNum} <ide> } <ide> <add>func dbEntriesNumber(ip, port, networkName string, doneCh chan resultTuple) { <add> body, err := httpGet(ip, port, "/networkstats?nid="+networkName) <add> <add> if err != nil { <add> logrus.Errorf("entriesNumber %s there was an error: %s", ip, err) <add> doneCh <- resultTuple{id: ip, result: -1} <add> return <add> } <add> elementsRegexp := regexp.MustCompile(`entries: ([0-9]+)`) <add> entriesNum, _ := strconv.Atoi(elementsRegexp.FindStringSubmatch(string(body))[1]) <add> doneCh <- resultTuple{id: ip, result: entriesNum} <add>} <add> <add>func dbQueueLength(ip, port, networkName string, doneCh chan resultTuple) { <add> body, err := httpGet(ip, port, "/networkstats?nid="+networkName) <add> <add> if err != nil { <add> logrus.Errorf("queueLength %s there was an error: %s", ip, err) <add> doneCh <- resultTuple{id: ip, result: -1} <add> return <add> } <add> elementsRegexp := regexp.MustCompile(`qlen: ([0-9]+)`) <add> entriesNum, _ := strconv.Atoi(elementsRegexp.FindStringSubmatch(string(body))[1]) <add> doneCh <- resultTuple{id: ip, result: entriesNum} <add>} <add> <ide> func clientWatchTable(ip, port, networkName, tableName string, doneCh chan resultTuple) { <ide> httpGetFatalError(ip, port, "/watchtable?nid="+networkName+"&tname="+tableName) <ide> if doneCh != nil { <ide> func clientTableEntriesNumber(ip, port, networkName, tableName string, doneCh ch <ide> body, err := httpGet(ip, port, "/watchedtableentries?nid="+networkName+"&tname="+tableName) <ide> <ide> if err != nil { <del> logrus.Errorf("clientTableEntriesNumber %s there was an error: %s\n", ip, err) <add> logrus.Errorf("clientTableEntriesNumber %s there was an error: %s", ip, err) <ide> doneCh <- resultTuple{id: ip, result: -1} <ide> return <ide> } <ide> func clientTableEntriesNumber(ip, port, networkName, tableName string, doneCh ch <ide> doneCh <- resultTuple{id: ip, result: entriesNum} <ide> } <ide> <add>func writeKeysNumber(ip, port, networkName, tableName, key string, number int, doneCh chan resultTuple) { <add> x := 0 <add> for ; x < number; x++ { <add> k := key + strconv.Itoa(x) <add> // write key <add> writeTableKey(ip, port, networkName, tableName, k) <add> } <add> doneCh <- resultTuple{id: ip, result: x} <add>} <add> <add>func deleteKeysNumber(ip, port, networkName, tableName, key string, number int, doneCh chan resultTuple) { <add> x := 0 <add> for ; x < number; x++ { <add> k := key + strconv.Itoa(x) <add> // write key <add> deleteTableKey(ip, port, networkName, tableName, k) <add> } <add> doneCh <- resultTuple{id: ip, result: x} <add>} <add> <ide> func writeUniqueKeys(ctx context.Context, ip, port, networkName, tableName, key string, doneCh chan resultTuple) { <ide> for x := 0; ; x++ { <ide> select { <ide> func ready(ip, port string, doneCh chan resultTuple) { <ide> doneCh <- resultTuple{id: ip, result: 0} <ide> } <ide> <del>func checkTable(ctx context.Context, ips []string, port, networkName, tableName string, expectedEntries int, fn func(string, string, string, string, chan resultTuple)) { <add>func checkTable(ctx context.Context, ips []string, port, networkName, tableName string, expectedEntries int, fn func(string, string, string, string, chan resultTuple)) (opTime time.Duration) { <ide> startTime := time.Now().UnixNano() <ide> var successTime int64 <ide> <del> // Loop for 2 minutes to guartee that the result is stable <add> // Loop for 2 minutes to guarantee that the result is stable <ide> for { <ide> select { <ide> case <-ctx.Done(): <ide> // Validate test success, if the time is set means that all the tables are empty <ide> if successTime != 0 { <del> logrus.Infof("Check table passed, the cluster converged in %d msec", time.Duration(successTime-startTime)/time.Millisecond) <add> opTime = time.Duration(successTime-startTime) / time.Millisecond <add> logrus.Infof("Check table passed, the cluster converged in %d msec", opTime) <ide> return <ide> } <ide> log.Fatal("Test failed, there is still entries in the tables of the nodes") <ide> func doNetworkPeers(ips []string, args []string) { <ide> close(doneCh) <ide> } <ide> <add>// network-stats-queue networkName <gt/lt> queueSize <add>func doNetworkStatsQueue(ips []string, args []string) { <add> doneCh := make(chan resultTuple, len(ips)) <add> networkName := args[0] <add> comparison := args[1] <add> size, _ := strconv.Atoi(args[2]) <add> <add> // check all the nodes <add> for _, ip := range ips { <add> go dbQueueLength(ip, servicePort, networkName, doneCh) <add> } <add> <add> var avgQueueSize int <add> // wait for the readiness of all nodes <add> for i := len(ips); i > 0; i-- { <add> node := <-doneCh <add> switch comparison { <add> case "lt": <add> if node.result > size { <add> log.Fatalf("Expected queue size from %s to be %d < %d", node.id, node.result, size) <add> } <add> case "gt": <add> if node.result < size { <add> log.Fatalf("Expected queue size from %s to be %d > %d", node.id, node.result, size) <add> } <add> default: <add> log.Fatal("unknown comparison operator") <add> } <add> avgQueueSize += node.result <add> } <add> close(doneCh) <add> avgQueueSize /= len(ips) <add> fmt.Fprintf(os.Stderr, "doNetworkStatsQueue succeeded with avg queue:%d", avgQueueSize) <add>} <add> <add>// write-keys networkName tableName parallelWriters numberOfKeysEach <add>func doWriteKeys(ips []string, args []string) { <add> networkName := args[0] <add> tableName := args[1] <add> parallelWriters, _ := strconv.Atoi(args[2]) <add> numberOfKeys, _ := strconv.Atoi(args[3]) <add> <add> doneCh := make(chan resultTuple, parallelWriters) <add> // Enable watch of tables from clients <add> for i := 0; i < parallelWriters; i++ { <add> go clientWatchTable(ips[i], servicePort, networkName, tableName, doneCh) <add> } <add> waitWriters(parallelWriters, false, doneCh) <add> <add> // Start parallel writers that will create and delete unique keys <add> defer close(doneCh) <add> for i := 0; i < parallelWriters; i++ { <add> key := "key-" + strconv.Itoa(i) + "-" <add> logrus.Infof("Spawn worker: %d on IP:%s", i, ips[i]) <add> go writeKeysNumber(ips[i], servicePort, networkName, tableName, key, numberOfKeys, doneCh) <add> } <add> <add> // Sync with all the writers <add> keyMap := waitWriters(parallelWriters, true, doneCh) <add> logrus.Infof("Written a total of %d keys on the cluster", keyMap[totalWrittenKeys]) <add> <add> // check table entries for 2 minutes <add> ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) <add> opTime := checkTable(ctx, ips, servicePort, networkName, tableName, keyMap[totalWrittenKeys], dbTableEntriesNumber) <add> cancel() <add> fmt.Fprintf(os.Stderr, "doWriteKeys succeeded in %d msec", opTime) <add>} <add> <add>// delete-keys networkName tableName parallelWriters numberOfKeysEach <add>func doDeleteKeys(ips []string, args []string) { <add> networkName := args[0] <add> tableName := args[1] <add> parallelWriters, _ := strconv.Atoi(args[2]) <add> numberOfKeys, _ := strconv.Atoi(args[3]) <add> <add> doneCh := make(chan resultTuple, parallelWriters) <add> // Enable watch of tables from clients <add> for i := 0; i < parallelWriters; i++ { <add> go clientWatchTable(ips[i], servicePort, networkName, tableName, doneCh) <add> } <add> waitWriters(parallelWriters, false, doneCh) <add> <add> // Start parallel writers that will create and delete unique keys <add> defer close(doneCh) <add> for i := 0; i < parallelWriters; i++ { <add> key := "key-" + strconv.Itoa(i) + "-" <add> logrus.Infof("Spawn worker: %d on IP:%s", i, ips[i]) <add> go deleteKeysNumber(ips[i], servicePort, networkName, tableName, key, numberOfKeys, doneCh) <add> } <add> <add> // Sync with all the writers <add> keyMap := waitWriters(parallelWriters, true, doneCh) <add> logrus.Infof("Written a total of %d keys on the cluster", keyMap[totalWrittenKeys]) <add> <add> // check table entries for 2 minutes <add> ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) <add> opTime := checkTable(ctx, ips, servicePort, networkName, tableName, 0, dbTableEntriesNumber) <add> cancel() <add> fmt.Fprintf(os.Stderr, "doDeletekeys succeeded in %d msec", opTime) <add>} <add> <ide> // write-delete-unique-keys networkName tableName numParallelWriters writeTimeSec <ide> func doWriteDeleteUniqueKeys(ips []string, args []string) { <ide> networkName := args[0] <ide> func doWriteDeleteUniqueKeys(ips []string, args []string) { <ide> <ide> // check table entries for 2 minutes <ide> ctx, cancel = context.WithTimeout(context.Background(), 2*time.Minute) <del> checkTable(ctx, ips, servicePort, networkName, tableName, 0, dbTableEntriesNumber) <add> opDBTime := checkTable(ctx, ips, servicePort, networkName, tableName, 0, dbTableEntriesNumber) <ide> cancel() <ide> ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) <del> checkTable(ctx, ips, servicePort, networkName, tableName, 0, clientTableEntriesNumber) <add> opClientTime := checkTable(ctx, ips, servicePort, networkName, tableName, 0, clientTableEntriesNumber) <ide> cancel() <add> fmt.Fprintf(os.Stderr, "doWriteDeleteUniqueKeys succeeded in %d msec and client %d msec", opDBTime, opClientTime) <ide> } <ide> <ide> // write-unique-keys networkName tableName numParallelWriters writeTimeSec <ide> func doWriteUniqueKeys(ips []string, args []string) { <ide> <ide> // check table entries for 2 minutes <ide> ctx, cancel = context.WithTimeout(context.Background(), 2*time.Minute) <del> checkTable(ctx, ips, servicePort, networkName, tableName, keyMap[totalWrittenKeys], dbTableEntriesNumber) <add> opTime := checkTable(ctx, ips, servicePort, networkName, tableName, keyMap[totalWrittenKeys], dbTableEntriesNumber) <ide> cancel() <add> fmt.Fprintf(os.Stderr, "doWriteUniqueKeys succeeded in %d msec", opTime) <ide> } <ide> <ide> // write-delete-leave-join networkName tableName numParallelWriters writeTimeSec <ide> func doWriteDeleteLeaveJoin(ips []string, args []string) { <ide> <ide> // check table entries for 2 minutes <ide> ctx, cancel = context.WithTimeout(context.Background(), 2*time.Minute) <del> checkTable(ctx, ips, servicePort, networkName, tableName, 0, dbTableEntriesNumber) <add> opTime := checkTable(ctx, ips, servicePort, networkName, tableName, 0, dbTableEntriesNumber) <ide> cancel() <add> fmt.Fprintf(os.Stderr, "doWriteDeleteLeaveJoin succeeded in %d msec", opTime) <ide> } <ide> <ide> // write-delete-wait-leave-join networkName tableName numParallelWriters writeTimeSec <ide> func doWriteDeleteWaitLeaveJoin(ips []string, args []string) { <ide> <ide> // check table entries for 2 minutes <ide> ctx, cancel = context.WithTimeout(context.Background(), 2*time.Minute) <del> checkTable(ctx, ips, servicePort, networkName, tableName, 0, dbTableEntriesNumber) <add> opTime := checkTable(ctx, ips, servicePort, networkName, tableName, 0, dbTableEntriesNumber) <ide> cancel() <add> fmt.Fprintf(os.Stderr, "doWriteDeleteWaitLeaveJoin succeeded in %d msec", opTime) <ide> } <ide> <ide> // write-wait-leave networkName tableName numParallelWriters writeTimeSec <ide> func doWriteWaitLeave(ips []string, args []string) { <ide> <ide> // check table entries for 2 minutes <ide> ctx, cancel = context.WithTimeout(context.Background(), 2*time.Minute) <del> checkTable(ctx, ips, servicePort, networkName, tableName, 0, dbTableEntriesNumber) <add> opTime := checkTable(ctx, ips, servicePort, networkName, tableName, 0, dbTableEntriesNumber) <ide> cancel() <add> fmt.Fprintf(os.Stderr, "doWriteLeaveJoin succeeded in %d msec", opTime) <ide> } <ide> <ide> // write-wait-leave-join networkName tableName numParallelWriters writeTimeSec numParallelLeaver <ide> func doWriteWaitLeaveJoin(ips []string, args []string) { <ide> <ide> // check table entries for 2 minutes <ide> ctx, cancel = context.WithTimeout(context.Background(), 2*time.Minute) <del> checkTable(ctx, ips, servicePort, networkName, tableName, keysExpected, dbTableEntriesNumber) <add> opTime := checkTable(ctx, ips, servicePort, networkName, tableName, keysExpected, dbTableEntriesNumber) <ide> cancel() <add> fmt.Fprintf(os.Stderr, "doWriteWaitLeaveJoin succeeded in %d msec", opTime) <ide> } <ide> <ide> var cmdArgChec = map[string]int{ <ide> func Client(args []string) { <ide> // leave-network networkName <ide> doLeaveNetwork(ips, commandArgs) <ide> case "network-peers": <del> // network-peers networkName maxRetry <add> // network-peers networkName expectedNumberPeers maxRetry <ide> doNetworkPeers(ips, commandArgs) <del> <add> // case "network-stats-entries": <add> // // network-stats-entries networkName maxRetry <add> // doNetworkPeers(ips, commandArgs) <add> case "network-stats-queue": <add> // network-stats-queue networkName <lt/gt> queueSize <add> doNetworkStatsQueue(ips, commandArgs) <add> <add> case "write-keys": <add> // write-keys networkName tableName parallelWriters numberOfKeysEach <add> doWriteKeys(ips, commandArgs) <add> case "delete-keys": <add> // delete-keys networkName tableName parallelWriters numberOfKeysEach <add> doDeleteKeys(ips, commandArgs) <ide> case "write-unique-keys": <ide> // write-delete-unique-keys networkName tableName numParallelWriters writeTimeSec <ide> doWriteUniqueKeys(ips, commandArgs) <ide><path>libnetwork/cmd/networkdb-test/testMain.go <ide> import ( <ide> ) <ide> <ide> func main() { <add> formatter := &logrus.TextFormatter{ <add> FullTimestamp: true, <add> } <add> logrus.SetFormatter(formatter) <ide> logrus.Infof("Starting the image with these args: %v", os.Args) <ide> if len(os.Args) < 1 { <ide> log.Fatal("You need at least 1 argument [client/server]") <ide><path>libnetwork/diagnostic/types.go <ide> type TablePeersResult struct { <ide> TableObj <ide> Elements []PeerEntryObj `json:"entries"` <ide> } <add> <add>// NetworkStatsResult network db stats related to entries and queue len for a network <add>type NetworkStatsResult struct { <add> Entries int `json:"entries"` <add> QueueLen int `jsoin:"qlen"` <add>} <add> <add>func (n *NetworkStatsResult) String() string { <add> return fmt.Sprintf("entries: %d, qlen: %d\n", n.Entries, n.QueueLen) <add>} <ide><path>libnetwork/networkdb/networkdbdiagnostic.go <ide> var NetDbPaths2Func = map[string]diagnostic.HTTPHandlerFunc{ <ide> "/deleteentry": dbDeleteEntry, <ide> "/getentry": dbGetEntry, <ide> "/gettable": dbGetTable, <add> "/networkstats": dbNetworkStats, <ide> } <ide> <ide> func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) { <ide> func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) { <ide> } <ide> diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) <ide> } <add> <add>func dbNetworkStats(ctx interface{}, w http.ResponseWriter, r *http.Request) { <add> r.ParseForm() <add> diagnostic.DebugHTTPForm(r) <add> _, json := diagnostic.ParseHTTPFormOptions(r) <add> <add> // audit logs <add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()}) <add> log.Info("network stats") <add> <add> if len(r.Form["nid"]) < 1 { <add> rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=test", r.URL.Path)) <add> log.Error("network stats failed, wrong input") <add> diagnostic.HTTPReply(w, rsp, json) <add> return <add> } <add> <add> nDB, ok := ctx.(*NetworkDB) <add> if ok { <add> nDB.RLock() <add> networks := nDB.networks[nDB.config.NodeID] <add> network, ok := networks[r.Form["nid"][0]] <add> <add> entries := -1 <add> qLen := -1 <add> if ok { <add> entries = network.entriesNumber <add> qLen = network.tableBroadcasts.NumQueued() <add> } <add> nDB.RUnlock() <add> <add> rsp := diagnostic.CommandSucceed(&diagnostic.NetworkStatsResult{Entries: entries, QueueLen: qLen}) <add> log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network stats done") <add> diagnostic.HTTPReply(w, rsp, json) <add> return <add> } <add> diagnostic.HTTPReply(w, diagnostic.FailCommand(fmt.Errorf("%s", dbNotAvailable)), json) <add>}
4
Ruby
Ruby
handle frozen homebrew.args
82e314c4674598552ad7f469377b47772ca64a05
<ide><path>Library/Homebrew/test/messages_spec.rb <ide> end <ide> end <ide> <add> # Homebrew.args OpenStruct usage cannot use verified doubles. <add> # rubocop:disable RSpec/VerifiedDoubles <ide> context "when the --display-times argument is present" do <ide> before do <del> allow(Homebrew.args).to receive(:display_times?).and_return(true) <add> allow(Homebrew).to receive(:args).and_return(double(display_times?: true)) <ide> end <ide> <ide> context "when install_times is empty" do <ide> <ide> context "when the --display-times argument isn't present" do <ide> before do <del> allow(ARGV).to receive(:include?).with("--display-times").and_return(false) <add> allow(Homebrew).to receive(:args).and_return(double(display_times?: false)) <ide> end <ide> <ide> it "doesn't print installation times" do <ide> expect { messages.display_messages }.not_to output.to_stdout <ide> end <ide> end <add> # rubocop:enable RSpec/VerifiedDoubles <ide> end <ide> end
1
Ruby
Ruby
remove redundant begin block
1f5e21bcbce41a5d49998df9ee58c1c875626fd6
<ide><path>activerecord/lib/active_record/middleware/database_selector/resolver.rb <ide> def read_from_replica(&blk) <ide> def write_to_primary(&blk) <ide> ActiveRecord::Base.connected_to(role: :writing) do <ide> instrumenter.instrument("database_selector.active_record.wrote_to_primary") do <del> begin <del> ret = yield <del> ensure <del> resolver.update_last_write_timestamp <del> end <del> ret <add> yield <add> ensure <add> resolver.update_last_write_timestamp <ide> end <ide> end <ide> end
1
Text
Text
add sorbet documentation
cba751a34320a57be5dfec052ffd92783399e2d4
<ide><path>docs/README.md <ide> - [How To Create (And Maintain) A Tap](How-to-Create-and-Maintain-a-Tap.md) <ide> - [Brew Test Bot](Brew-Test-Bot.md) <ide> - [Prose Style Guidelines](Prose-Style-Guidelines.md) <add>- [Type Checking with Sorbet](Typechecking.md) <ide> <ide> ## Maintainers <ide> <ide><path>docs/Typechecking.md <add># Type Checking with Sorbet <add> <add>The majority of the code in Homebrew is written in Ruby which is a dynamic <add>language. To avail the benefits of static type checking, we have set up Sorbet in <add>our codebase which provides the benefits of static type checking to dynamic languages <add>like Ruby. <br> [Sorbet's Documentation](https://sorbet.org/docs/overview) is a <add>good place to get started if you want to dive deeper into Sorbet and it's abilities. <add> <add>## Sorbet elements in the Homebrew Codebase <add> <add>The [`sorbet/`](https://github.com/Homebrew/brew/tree/master/Library/Homebrew/sorbet) <add>directory in `Library/Homebrew` consists of: <add> <add>- The `rbi/` directory. It contains all Ruby Interface files, which help Sorbet to <add>learn about constants, ancestors, and methods defined in ways it doesn’t understand <add>natively. RBI files for all gems are auto-generated using <add>[Tapioca](https://github.com/Shopify/tapioca#tapioca). We can also create a RBI <add>file to help Sorbet understand dynamic definitions. <add>For example: Sorbet assumes that `Kernel` is not necessarily included in our modules <add>and classes, hence we use RBI files to explicitly include the Kernel Module. Here is an <add>[example](https://github.com/Homebrew/brew/blob/72419630b4658da31556a0f6ef1dfa633cf4fe4f/Library/Homebrew/sorbet/rbi/homebrew.rbi#L3-L5) <add>in our codebase. <add> <add>- The `config` file. It is actually a newline-separated list of arguments to pass to <add>`srb tc`, the same as if they’d been passed at the command line. Arguments in the config <add>file are always passed first (if it exists), followed by arguments provided on the <add>command line. We use it ignore the `Library/Homebrew/vendor` directory, which <add>contains gem definitions which we do not wish to type check. <add> <add>- The `files.yaml` file. It contains a list of every Ruby file in the codebase <add>divided into 3 strictness levels, false, true and strict. The `false` files only <add>report errors related to the syntax, constant resolution and correctness of the <add>method signatures, and not type errors. We use this file to override strictness <add>on a file-by-file basis. Our longtime goal is to move all `false` files to `true` <add>and start reporting type errors on those files as well. If you are making changes <add>that require adding a new ruby file, we would urge you to add it to `true` and work <add>out the resulting type errors. Read more about Sorbet's strictness levels <add>[here](https://sorbet.org/docs/static#file-level-granularity-strictness-levels). <add> <add>## Using `brew typecheck` <add> <add>When run without any arguments, `brew typecheck`, will run considering the strictness levels <add>set in the `files.yaml` file. However, when typecheck is run on a specific file <add>or directory, more errors may show up since Sorbet can not resolve constants defined <add>outside the scope of the specified file. These problems can be solved with RBI files. <add>Currently `brew typecheck` provides `quiet`, `--file`, `--dir` and `--ignore` options <add>but you can explore more options with `srb tc --help` and passing them with `srb tc`. <add> <add>## Resolving Type Errors <add> <add>Sorbet reports type errors along with an error reference code, which can be used <add>to look up more information on how to debug the error, or what causes the error in <add>the Sorbet documentation. Here is how we debug some common type errors: <add> <add>* Using `T.reveal_type`. In files which are `true` or higher, if we wrap a variable <add>or method call in `T.reveal_type`, Sorbet will show us what type it thinks that <add>variable has in the output of `srb tc`. This is particularly useful when writing <add>[method signatures](https://sorbet.org/docs/sigs) and debugging. Make sure to <add>remove this line from your code before committing your changes, since this is <add>just a debugging tool. <add> <add>* One of the most frequent errors that we've encountered is: `7003: Method does not exist.` <add>Since Ruby is a very dynamic language, methods can be defined in ways Sorbet cannot <add>see statically. In such cases, check if the method exists at runtime, if not, then <add>Sorbet has caught a future bug! But, it is also possible that even though a method <add>exists at runtime, Sorbet cannot see it. In such cases, we use `*.rbi` files. <add>Read more about RBI files [here](https://sorbet.org/docs/rbi). <add> <add>* Since Sorbet does not automatically assume that Kernel is to be included in Modules, <add>we may encounter many errors while trying to use methods like `puts`, `ohai`, `odebug` et cetera. <add>A simple workaround for this would be to add an extra `include Kernel` line in the <add>respective RBI file. <add> <add>* The tips above are very generic and apply to lots of cases. For some common gotchas <add>when using Sorbet, refer to the [Sorbet Error Reference](https://sorbet.org/docs/error-reference) <add>and [FAQ](https://sorbet.org/docs/faq). <add> <add>## Method Signatures <add> <add>Detailed explanation about why we use Method Signatures and its syntax can be found <add>[here](https://sorbet.org/docs/sigs). The only extra thing to keep in mind is that <add>we add method signatures to RBI files instead of the actual method definition in <add>the code. This way we preserve the original code structure and everything related to <add>Sorbet is kept within the `Library/Homebrew/sorbet` directory.
2
Mixed
Text
remove mips support
9334e45aa0ed815c2745bcc2bb606d91be64998d
<ide><path>configure.py <ide> <ide> valid_os = ('win', 'mac', 'solaris', 'freebsd', 'openbsd', 'linux', <ide> 'android', 'aix', 'cloudabi') <del>valid_arch = ('arm', 'arm64', 'ia32', 'mips', 'mipsel', 'mips64el', 'ppc', <add>valid_arch = ('arm', 'arm64', 'ia32', 'ppc', <ide> 'ppc64', 'x32','x64', 'x86', 'x86_64', 's390', 's390x') <ide> valid_arm_float_abi = ('soft', 'softfp', 'hard') <ide> valid_arm_fpu = ('vfp', 'vfpv3', 'vfpv3-d16', 'neon') <del>valid_mips_arch = ('loongson', 'r1', 'r2', 'r6', 'rx') <del>valid_mips_fpu = ('fp32', 'fp64', 'fpxx') <del>valid_mips_float_abi = ('soft', 'hard') <ide> valid_intl_modes = ('none', 'small-icu', 'full-icu', 'system-icu') <ide> with open ('tools/icu/icu_versions.json') as f: <ide> icu_versions = json.load(f) <ide> help='ARM FPU mode ({0}) [default: %default]'.format( <ide> ', '.join(valid_arm_fpu))) <ide> <del>parser.add_option('--with-mips-arch-variant', <del> action='store', <del> dest='mips_arch_variant', <del> default='r2', <del> choices=valid_mips_arch, <del> help='MIPS arch variant ({0}) [default: %default]'.format( <del> ', '.join(valid_mips_arch))) <del> <del>parser.add_option('--with-mips-fpu-mode', <del> action='store', <del> dest='mips_fpu_mode', <del> default='fp32', <del> choices=valid_mips_fpu, <del> help='MIPS FPU mode ({0}) [default: %default]'.format( <del> ', '.join(valid_mips_fpu))) <del> <del>parser.add_option('--with-mips-float-abi', <del> action='store', <del> dest='mips_float_abi', <del> default='hard', <del> choices=valid_mips_float_abi, <del> help='MIPS floating-point ABI ({0}) [default: %default]'.format( <del> ', '.join(valid_mips_float_abi))) <del> <ide> parser.add_option('--with-dtrace', <ide> action='store_true', <ide> dest='with_dtrace', <ide> def host_arch_cc(): <ide> '__aarch64__' : 'arm64', <ide> '__arm__' : 'arm', <ide> '__i386__' : 'ia32', <del> '__MIPSEL__' : 'mipsel', <del> '__mips__' : 'mips', <ide> '__PPC64__' : 'ppc64', <ide> '__PPC__' : 'ppc64', <ide> '__x86_64__' : 'x64', <ide> def host_arch_cc(): <ide> if rtn != 's390': <ide> break <ide> <del> if rtn == 'mipsel' and '_LP64' in k: <del> rtn = 'mips64el' <del> <ide> return rtn <ide> <ide> <ide> def host_arch_win(): <ide> 'AMD64' : 'x64', <ide> 'x86' : 'ia32', <ide> 'arm' : 'arm', <del> 'mips' : 'mips', <ide> } <ide> <ide> return matchup.get(arch, 'ia32') <ide> def configure_arm(o): <ide> o['variables']['arm_fpu'] = options.arm_fpu or arm_fpu <ide> <ide> <del>def configure_mips(o): <del> can_use_fpu_instructions = (options.mips_float_abi != 'soft') <del> o['variables']['v8_can_use_fpu_instructions'] = b(can_use_fpu_instructions) <del> o['variables']['v8_use_mips_abi_hardfloat'] = b(can_use_fpu_instructions) <del> o['variables']['mips_arch_variant'] = options.mips_arch_variant <del> o['variables']['mips_fpu_mode'] = options.mips_fpu_mode <del> <del> <ide> def gcc_version_ge(version_checked): <ide> for compiler in [(CC, 'c'), (CXX, 'c++')]: <ide> ok, is_clang, clang_version, compiler_version = \ <ide> def configure_node(o): <ide> <ide> if target_arch == 'arm': <ide> configure_arm(o) <del> elif target_arch in ('mips', 'mipsel', 'mips64el'): <del> configure_mips(o) <ide> <ide> if flavor == 'aix': <ide> o['variables']['node_target_type'] = 'static_library' <ide><path>doc/api/process.md <ide> added: v0.5.0 <ide> The `process.arch` property returns a string identifying the operating system <ide> CPU architecture for which the Node.js binary was compiled. <ide> <del>The current possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`, <del>`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. <add>The current possible values are: `'arm'`, `'arm64'`, `'ia32'`, <add>`'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. <ide> <ide> ```js <ide> console.log(`This processor architecture is ${process.arch}`); <ide><path>doc/onboarding-extras.md <ide> need to be attached anymore, as only important bugfixes will be included. <ide> * `macos`, `windows`, `smartos`, `aix` <ide> * No linux, linux is the implied default <ide> * Architecture labels <del> * `arm`, `mips`, `s390`, `ppc` <add> * `arm`, `s390`, `ppc` <ide> * No x86{_64}, since that is the implied default
3
Ruby
Ruby
ignore schema queries on sqlite 3 as well
31ccedd440617edeaa9b11b89219a65ec7225442
<ide><path>activerecord/lib/active_record/test_case.rb <ide> def clear_log; self.log = []; self.log_all = []; end <ide> oracle_ignored = [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im] <ide> mysql_ignored = [/^SHOW TABLES/i, /^SHOW FULL FIELDS/] <ide> postgresql_ignored = [/^\s*select\b.*\bfrom\b.*pg_namespace\b/im, /^\s*select\b.*\battname\b.*\bfrom\b.*\bpg_attribute\b/im, /^SHOW search_path/i] <add> sqlite3_ignored = [/^\s*SELECT name\b.*\bFROM sqlite_master/im] <ide> <del> [oracle_ignored, mysql_ignored, postgresql_ignored].each do |db_ignored_sql| <add> [oracle_ignored, mysql_ignored, postgresql_ignored, sqlite3_ignored].each do |db_ignored_sql| <ide> ignored_sql.concat db_ignored_sql <ide> end <ide>
1
Python
Python
add benchmarks for thread tuning.
54dffe2ef012c5cd241d65b270709d7ddb257f5d
<ide><path>official/resnet/keras/keras_imagenet_benchmark.py <ide> def benchmark_8_gpu(self): <ide> FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu') <ide> FLAGS.dtype = 'fp32' <ide> FLAGS.enable_eager = True <add> # Add some thread tunings to improve performance. <add> FLAGS.datasets_num_private_threads = 14 <ide> self._run_and_report_benchmark() <ide> <del> def benchmark_8_gpu_bfc_allocator(self): <del> """Restricts CPU memory allocation.""" <del> self._setup() <del> FLAGS.num_gpus = 8 <del> FLAGS.data_dir = self.data_dir <del> FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_bfc_allocator') <del> FLAGS.dtype = 'fp32' <del> FLAGS.batch_size = 128 * 8 # 8 GPUs <del> FLAGS.enable_eager = True <del> # Limits CPU memory to work around memory spikes in eager mode. <del> # TODO(yuefengz): get rid of this test once we fix the memory issue. <del> os.environ['TF_CPU_ALLOCATOR_USE_BFC'] = 'true' <del> os.environ['TF_CPU_BFC_MEM_LIMIT_IN_MB'] = '100000' <del> self._run_and_report_benchmark() <del> del os.environ['TF_CPU_ALLOCATOR_USE_BFC'] <del> del os.environ['TF_CPU_BFC_MEM_LIMIT_IN_MB'] <del> <ide> def _run_and_report_benchmark(self): <ide> start_time_sec = time.time() <ide> stats = keras_imagenet_main.run(flags.FLAGS) <ide> def benchmark_8_gpu(self): <ide> FLAGS.batch_size = 128 * 8 # 8 GPUs <ide> self._run_and_report_benchmark() <ide> <add> def benchmark_8_gpu_tweaked(self): <add> self._setup() <add> <add> FLAGS.num_gpus = 8 <add> FLAGS.enable_eager = True <add> FLAGS.distribution_strategy = 'default' <add> FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_tweaked') <add> FLAGS.batch_size = 128 * 8 # 8 GPUs <add> FLAGS.datasets_num_private_threads = 14 <add> self._run_and_report_benchmark() <add> <ide> def benchmark_graph_8_gpu(self): <ide> self._setup() <ide>
1
Go
Go
change push to use manifest builder
f33fa1b8d3befec31fdf1952ea1190012c812dc7
<ide><path>distribution/push.go <ide> import ( <ide> "io" <ide> <ide> "github.com/Sirupsen/logrus" <del> "github.com/docker/distribution/digest" <ide> "github.com/docker/docker/distribution/metadata" <ide> "github.com/docker/docker/distribution/xfer" <ide> "github.com/docker/docker/image" <ide> func NewPusher(ref reference.Named, endpoint registry.APIEndpoint, repoInfo *reg <ide> endpoint: endpoint, <ide> repoInfo: repoInfo, <ide> config: imagePushConfig, <del> layersPushed: pushMap{layersPushed: make(map[digest.Digest]bool)}, <ide> }, nil <ide> case registry.APIVersion1: <ide> return &v1Pusher{ <ide><path>distribution/push_v2.go <ide> package distribution <ide> <ide> import ( <del> "encoding/json" <del> "errors" <ide> "fmt" <ide> "io" <ide> "sync" <del> "time" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution" <ide> "github.com/docker/distribution/digest" <del> "github.com/docker/distribution/manifest" <ide> "github.com/docker/distribution/manifest/schema1" <add> "github.com/docker/distribution/manifest/schema2" <add> "github.com/docker/distribution/registry/client" <ide> "github.com/docker/docker/distribution/metadata" <ide> "github.com/docker/docker/distribution/xfer" <del> "github.com/docker/docker/image" <del> "github.com/docker/docker/image/v1" <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/progress" <ide> type v2Pusher struct { <ide> config *ImagePushConfig <ide> repo distribution.Repository <ide> <del> // confirmedV2 is set to true if we confirm we're talking to a v2 <del> // registry. This is used to limit fallbacks to the v1 protocol. <del> confirmedV2 bool <del> <del> // layersPushed is the set of layers known to exist on the remote side. <del> // This avoids redundant queries when pushing multiple tags that <del> // involve the same layers. <del> layersPushed pushMap <add> // pushState is state built by the Download functions. <add> pushState pushState <ide> } <ide> <del>type pushMap struct { <add>type pushState struct { <ide> sync.Mutex <del> layersPushed map[digest.Digest]bool <add> // remoteLayers is the set of layers known to exist on the remote side. <add> // This avoids redundant queries when pushing multiple tags that <add> // involve the same layers. It is also used to fill in digest and size <add> // information when building the manifest. <add> remoteLayers map[layer.DiffID]distribution.Descriptor <add> // confirmedV2 is set to true if we confirm we're talking to a v2 <add> // registry. This is used to limit fallbacks to the v1 protocol. <add> confirmedV2 bool <ide> } <ide> <ide> func (p *v2Pusher) Push(ctx context.Context) (err error) { <del> p.repo, p.confirmedV2, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "push", "pull") <add> p.pushState.remoteLayers = make(map[layer.DiffID]distribution.Descriptor) <add> <add> p.repo, p.pushState.confirmedV2, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "push", "pull") <ide> if err != nil { <ide> logrus.Debugf("Error getting v2 registry: %v", err) <del> return fallbackError{err: err, confirmedV2: p.confirmedV2} <add> return fallbackError{err: err, confirmedV2: p.pushState.confirmedV2} <ide> } <ide> <ide> if err = p.pushV2Repository(ctx); err != nil { <ide> if registry.ContinueOnError(err) { <del> return fallbackError{err: err, confirmedV2: p.confirmedV2} <add> return fallbackError{err: err, confirmedV2: p.pushState.confirmedV2} <ide> } <ide> } <ide> return err <ide> func (p *v2Pusher) pushV2Tag(ctx context.Context, association reference.Associat <ide> descriptorTemplate := v2PushDescriptor{ <ide> blobSumService: p.blobSumService, <ide> repo: p.repo, <del> layersPushed: &p.layersPushed, <del> confirmedV2: &p.confirmedV2, <del> } <del> <del> // Push empty layer if necessary <del> for _, h := range img.History { <del> if h.EmptyLayer { <del> descriptor := descriptorTemplate <del> descriptor.layer = layer.EmptyLayer <del> descriptors = []xfer.UploadDescriptor{&descriptor} <del> break <del> } <add> pushState: &p.pushState, <ide> } <ide> <ide> // Loop bounds condition is to avoid pushing the base layer on Windows. <ide> func (p *v2Pusher) pushV2Tag(ctx context.Context, association reference.Associat <ide> l = l.Parent() <ide> } <ide> <del> fsLayers, err := p.config.UploadManager.Upload(ctx, descriptors, p.config.ProgressOutput) <del> if err != nil { <add> if err := p.config.UploadManager.Upload(ctx, descriptors, p.config.ProgressOutput); err != nil { <ide> return err <ide> } <ide> <ide> var tag string <ide> if tagged, isTagged := ref.(reference.NamedTagged); isTagged { <ide> tag = tagged.Tag() <ide> } <del> m, err := CreateV2Manifest(p.repo.Name(), tag, img, fsLayers) <del> if err != nil { <del> return err <add> builder := schema1.NewConfigManifestBuilder(p.repo.Blobs(ctx), p.config.TrustKey, p.repo.Name(), tag, img.RawJSON()) <add> <add> // descriptors is in reverse order; iterate backwards to get references <add> // appended in the right order. <add> for i := len(descriptors) - 1; i >= 0; i-- { <add> if err := builder.AppendReference(descriptors[i].(*v2PushDescriptor)); err != nil { <add> return err <add> } <ide> } <ide> <del> logrus.Infof("Signed manifest for %s using daemon's key: %s", ref.String(), p.config.TrustKey.KeyID()) <del> signed, err := schema1.Sign(m, p.config.TrustKey) <add> manifest, err := builder.Build(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> <del> manifestDigest, manifestSize, err := digestFromManifest(signed, ref) <add> manifestDigest, manifestSize, err := digestFromManifest(manifest.(*schema1.SignedManifest), ref) <ide> if err != nil { <ide> return err <ide> } <ide> func (p *v2Pusher) pushV2Tag(ctx context.Context, association reference.Associat <ide> if err != nil { <ide> return err <ide> } <del> _, err = manSvc.Put(ctx, signed) <add> <add> if tagged, isTagged := ref.(reference.NamedTagged); isTagged { <add> _, err = manSvc.Put(ctx, manifest, client.WithTag(tagged.Tag())) <add> } else { <add> _, err = manSvc.Put(ctx, manifest) <add> } <ide> // FIXME create a tag <ide> return err <ide> } <ide> type v2PushDescriptor struct { <ide> layer layer.Layer <ide> blobSumService *metadata.BlobSumService <ide> repo distribution.Repository <del> layersPushed *pushMap <del> confirmedV2 *bool <add> pushState *pushState <ide> } <ide> <ide> func (pd *v2PushDescriptor) Key() string { <ide> func (pd *v2PushDescriptor) DiffID() layer.DiffID { <ide> return pd.layer.DiffID() <ide> } <ide> <del>func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (digest.Digest, error) { <add>func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.Output) error { <ide> diffID := pd.DiffID() <ide> <del> logrus.Debugf("Pushing layer: %s", diffID) <add> pd.pushState.Lock() <add> if _, ok := pd.pushState.remoteLayers[diffID]; ok { <add> // it is already known that the push is not needed and <add> // therefore doing a stat is unnecessary <add> pd.pushState.Unlock() <add> progress.Update(progressOutput, pd.ID(), "Layer already exists") <add> return nil <add> } <add> pd.pushState.Unlock() <ide> <ide> // Do we have any blobsums associated with this layer's DiffID? <ide> possibleBlobsums, err := pd.blobSumService.GetBlobSums(diffID) <ide> if err == nil { <del> dgst, exists, err := blobSumAlreadyExists(ctx, possibleBlobsums, pd.repo, pd.layersPushed) <add> descriptor, exists, err := blobSumAlreadyExists(ctx, possibleBlobsums, pd.repo, pd.pushState) <ide> if err != nil { <ide> progress.Update(progressOutput, pd.ID(), "Image push failed") <del> return "", retryOnError(err) <add> return retryOnError(err) <ide> } <ide> if exists { <ide> progress.Update(progressOutput, pd.ID(), "Layer already exists") <del> return dgst, nil <add> pd.pushState.Lock() <add> pd.pushState.remoteLayers[diffID] = descriptor <add> pd.pushState.Unlock() <add> return nil <ide> } <ide> } <ide> <add> logrus.Debugf("Pushing layer: %s", diffID) <add> <ide> // if digest was empty or not saved, or if blob does not exist on the remote repository, <ide> // then push the blob. <ide> bs := pd.repo.Blobs(ctx) <ide> <ide> // Send the layer <ide> layerUpload, err := bs.Create(ctx) <ide> if err != nil { <del> return "", retryOnError(err) <add> return retryOnError(err) <ide> } <ide> defer layerUpload.Close() <ide> <ide> arch, err := pd.layer.TarStream() <ide> if err != nil { <del> return "", xfer.DoNotRetry{Err: err} <add> return xfer.DoNotRetry{Err: err} <ide> } <ide> <ide> // don't care if this fails; best effort <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> nn, err := layerUpload.ReadFrom(tee) <ide> compressedReader.Close() <ide> if err != nil { <del> return "", retryOnError(err) <add> return retryOnError(err) <ide> } <ide> <ide> pushDigest := digester.Digest() <ide> if _, err := layerUpload.Commit(ctx, distribution.Descriptor{Digest: pushDigest}); err != nil { <del> return "", retryOnError(err) <add> return retryOnError(err) <ide> } <ide> <del> // If Commit succeded, that's an indication that the remote registry <del> // speaks the v2 protocol. <del> *pd.confirmedV2 = true <del> <ide> logrus.Debugf("uploaded layer %s (%s), %d bytes", diffID, pushDigest, nn) <ide> progress.Update(progressOutput, pd.ID(), "Pushed") <ide> <ide> // Cache mapping from this layer's DiffID to the blobsum <ide> if err := pd.blobSumService.Add(diffID, pushDigest); err != nil { <del> return "", xfer.DoNotRetry{Err: err} <add> return xfer.DoNotRetry{Err: err} <ide> } <ide> <del> pd.layersPushed.Lock() <del> pd.layersPushed.layersPushed[pushDigest] = true <del> pd.layersPushed.Unlock() <add> pd.pushState.Lock() <add> <add> // If Commit succeded, that's an indication that the remote registry <add> // speaks the v2 protocol. <add> pd.pushState.confirmedV2 = true <add> <add> pd.pushState.remoteLayers[diffID] = distribution.Descriptor{ <add> Digest: pushDigest, <add> MediaType: schema2.MediaTypeLayer, <add> Size: nn, <add> } <add> <add> pd.pushState.Unlock() <add> <add> return nil <add>} <ide> <del> return pushDigest, nil <add>func (pd *v2PushDescriptor) Descriptor() distribution.Descriptor { <add> // Not necessary to lock pushStatus because this is always <add> // called after all the mutation in pushStatus. <add> // By the time this function is called, every layer will have <add> // an entry in remoteLayers. <add> return pd.pushState.remoteLayers[pd.DiffID()] <ide> } <ide> <ide> // blobSumAlreadyExists checks if the registry already know about any of the <ide> // blobsums passed in the "blobsums" slice. If it finds one that the registry <ide> // knows about, it returns the known digest and "true". <del>func blobSumAlreadyExists(ctx context.Context, blobsums []digest.Digest, repo distribution.Repository, layersPushed *pushMap) (digest.Digest, bool, error) { <del> layersPushed.Lock() <del> for _, dgst := range blobsums { <del> if layersPushed.layersPushed[dgst] { <del> // it is already known that the push is not needed and <del> // therefore doing a stat is unnecessary <del> layersPushed.Unlock() <del> return dgst, true, nil <del> } <del> } <del> layersPushed.Unlock() <del> <add>func blobSumAlreadyExists(ctx context.Context, blobsums []digest.Digest, repo distribution.Repository, pushState *pushState) (distribution.Descriptor, bool, error) { <ide> for _, dgst := range blobsums { <del> _, err := repo.Blobs(ctx).Stat(ctx, dgst) <add> descriptor, err := repo.Blobs(ctx).Stat(ctx, dgst) <ide> switch err { <ide> case nil: <del> return dgst, true, nil <add> descriptor.MediaType = schema2.MediaTypeLayer <add> return descriptor, true, nil <ide> case distribution.ErrBlobUnknown: <ide> // nop <ide> default: <del> return "", false, err <del> } <del> } <del> return "", false, nil <del>} <del> <del>// CreateV2Manifest creates a V2 manifest from an image config and set of <del>// FSLayer digests. <del>// FIXME: This should be moved to the distribution repo, since it will also <del>// be useful for converting new manifests to the old format. <del>func CreateV2Manifest(name, tag string, img *image.Image, fsLayers map[layer.DiffID]digest.Digest) (*schema1.Manifest, error) { <del> if len(img.History) == 0 { <del> return nil, errors.New("empty history when trying to create V2 manifest") <del> } <del> <del> // Generate IDs for each layer <del> // For non-top-level layers, create fake V1Compatibility strings that <del> // fit the format and don't collide with anything else, but don't <del> // result in runnable images on their own. <del> type v1Compatibility struct { <del> ID string `json:"id"` <del> Parent string `json:"parent,omitempty"` <del> Comment string `json:"comment,omitempty"` <del> Created time.Time `json:"created"` <del> ContainerConfig struct { <del> Cmd []string <del> } `json:"container_config,omitempty"` <del> ThrowAway bool `json:"throwaway,omitempty"` <del> } <del> <del> fsLayerList := make([]schema1.FSLayer, len(img.History)) <del> history := make([]schema1.History, len(img.History)) <del> <del> parent := "" <del> layerCounter := 0 <del> for i, h := range img.History { <del> if i == len(img.History)-1 { <del> break <del> } <del> <del> var diffID layer.DiffID <del> if h.EmptyLayer { <del> diffID = layer.EmptyLayer.DiffID() <del> } else { <del> if len(img.RootFS.DiffIDs) <= layerCounter { <del> return nil, errors.New("too many non-empty layers in History section") <del> } <del> diffID = img.RootFS.DiffIDs[layerCounter] <del> layerCounter++ <del> } <del> <del> fsLayer, present := fsLayers[diffID] <del> if !present { <del> return nil, fmt.Errorf("missing layer in CreateV2Manifest: %s", diffID.String()) <del> } <del> dgst := digest.FromBytes([]byte(fsLayer.Hex() + " " + parent)) <del> v1ID := dgst.Hex() <del> <del> v1Compatibility := v1Compatibility{ <del> ID: v1ID, <del> Parent: parent, <del> Comment: h.Comment, <del> Created: h.Created, <add> return distribution.Descriptor{}, false, err <ide> } <del> v1Compatibility.ContainerConfig.Cmd = []string{img.History[i].CreatedBy} <del> if h.EmptyLayer { <del> v1Compatibility.ThrowAway = true <del> } <del> jsonBytes, err := json.Marshal(&v1Compatibility) <del> if err != nil { <del> return nil, err <del> } <del> <del> reversedIndex := len(img.History) - i - 1 <del> history[reversedIndex].V1Compatibility = string(jsonBytes) <del> fsLayerList[reversedIndex] = schema1.FSLayer{BlobSum: fsLayer} <del> <del> parent = v1ID <del> } <del> <del> latestHistory := img.History[len(img.History)-1] <del> <del> var diffID layer.DiffID <del> if latestHistory.EmptyLayer { <del> diffID = layer.EmptyLayer.DiffID() <del> } else { <del> if len(img.RootFS.DiffIDs) <= layerCounter { <del> return nil, errors.New("too many non-empty layers in History section") <del> } <del> diffID = img.RootFS.DiffIDs[layerCounter] <ide> } <del> fsLayer, present := fsLayers[diffID] <del> if !present { <del> return nil, fmt.Errorf("missing layer in CreateV2Manifest: %s", diffID.String()) <del> } <del> <del> fsLayerList[0] = schema1.FSLayer{BlobSum: fsLayer} <del> dgst := digest.FromBytes([]byte(fsLayer.Hex() + " " + parent + " " + string(img.RawJSON()))) <del> <del> // Top-level v1compatibility string should be a modified version of the <del> // image config. <del> transformedConfig, err := v1.MakeV1ConfigFromConfig(img, dgst.Hex(), parent, latestHistory.EmptyLayer) <del> if err != nil { <del> return nil, err <del> } <del> <del> history[0].V1Compatibility = string(transformedConfig) <del> <del> // windows-only baselayer setup <del> if err := setupBaseLayer(history, *img.RootFS); err != nil { <del> return nil, err <del> } <del> <del> return &schema1.Manifest{ <del> Versioned: manifest.Versioned{ <del> SchemaVersion: 1, <del> }, <del> Name: name, <del> Tag: tag, <del> Architecture: img.Architecture, <del> FSLayers: fsLayerList, <del> History: history, <del> }, nil <add> return distribution.Descriptor{}, false, nil <ide> } <ide><path>distribution/push_v2_test.go <del>package distribution <del> <del>import ( <del> "reflect" <del> "testing" <del> <del> "github.com/docker/distribution/digest" <del> "github.com/docker/distribution/manifest/schema1" <del> "github.com/docker/docker/image" <del> "github.com/docker/docker/layer" <del>) <del> <del>func TestCreateV2Manifest(t *testing.T) { <del> imgJSON := `{ <del> "architecture": "amd64", <del> "config": { <del> "AttachStderr": false, <del> "AttachStdin": false, <del> "AttachStdout": false, <del> "Cmd": [ <del> "/bin/sh", <del> "-c", <del> "echo hi" <del> ], <del> "Domainname": "", <del> "Entrypoint": null, <del> "Env": [ <del> "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", <del> "derived=true", <del> "asdf=true" <del> ], <del> "Hostname": "23304fc829f9", <del> "Image": "sha256:4ab15c48b859c2920dd5224f92aabcd39a52794c5b3cf088fb3bbb438756c246", <del> "Labels": {}, <del> "OnBuild": [], <del> "OpenStdin": false, <del> "StdinOnce": false, <del> "Tty": false, <del> "User": "", <del> "Volumes": null, <del> "WorkingDir": "" <del> }, <del> "container": "e91032eb0403a61bfe085ff5a5a48e3659e5a6deae9f4d678daa2ae399d5a001", <del> "container_config": { <del> "AttachStderr": false, <del> "AttachStdin": false, <del> "AttachStdout": false, <del> "Cmd": [ <del> "/bin/sh", <del> "-c", <del> "#(nop) CMD [\"/bin/sh\" \"-c\" \"echo hi\"]" <del> ], <del> "Domainname": "", <del> "Entrypoint": null, <del> "Env": [ <del> "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", <del> "derived=true", <del> "asdf=true" <del> ], <del> "Hostname": "23304fc829f9", <del> "Image": "sha256:4ab15c48b859c2920dd5224f92aabcd39a52794c5b3cf088fb3bbb438756c246", <del> "Labels": {}, <del> "OnBuild": [], <del> "OpenStdin": false, <del> "StdinOnce": false, <del> "Tty": false, <del> "User": "", <del> "Volumes": null, <del> "WorkingDir": "" <del> }, <del> "created": "2015-11-04T23:06:32.365666163Z", <del> "docker_version": "1.9.0-dev", <del> "history": [ <del> { <del> "created": "2015-10-31T22:22:54.690851953Z", <del> "created_by": "/bin/sh -c #(nop) ADD file:a3bc1e842b69636f9df5256c49c5374fb4eef1e281fe3f282c65fb853ee171c5 in /" <del> }, <del> { <del> "created": "2015-10-31T22:22:55.613815829Z", <del> "created_by": "/bin/sh -c #(nop) CMD [\"sh\"]" <del> }, <del> { <del> "created": "2015-11-04T23:06:30.934316144Z", <del> "created_by": "/bin/sh -c #(nop) ENV derived=true", <del> "empty_layer": true <del> }, <del> { <del> "created": "2015-11-04T23:06:31.192097572Z", <del> "created_by": "/bin/sh -c #(nop) ENV asdf=true", <del> "empty_layer": true <del> }, <del> { <del> "created": "2015-11-04T23:06:32.083868454Z", <del> "created_by": "/bin/sh -c dd if=/dev/zero of=/file bs=1024 count=1024" <del> }, <del> { <del> "created": "2015-11-04T23:06:32.365666163Z", <del> "created_by": "/bin/sh -c #(nop) CMD [\"/bin/sh\" \"-c\" \"echo hi\"]", <del> "empty_layer": true <del> } <del> ], <del> "os": "linux", <del> "rootfs": { <del> "diff_ids": [ <del> "sha256:c6f988f4874bb0add23a778f753c65efe992244e148a1d2ec2a8b664fb66bbd1", <del> "sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef", <del> "sha256:13f53e08df5a220ab6d13c58b2bf83a59cbdc2e04d0a3f041ddf4b0ba4112d49" <del> ], <del> "type": "layers" <del> } <del>}` <del> <del> // To fill in rawJSON <del> img, err := image.NewFromJSON([]byte(imgJSON)) <del> if err != nil { <del> t.Fatalf("json decoding failed: %v", err) <del> } <del> <del> fsLayers := map[layer.DiffID]digest.Digest{ <del> layer.DiffID("sha256:c6f988f4874bb0add23a778f753c65efe992244e148a1d2ec2a8b664fb66bbd1"): digest.Digest("sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4"), <del> layer.DiffID("sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef"): digest.Digest("sha256:86e0e091d0da6bde2456dbb48306f3956bbeb2eae1b5b9a43045843f69fe4aaa"), <del> layer.DiffID("sha256:13f53e08df5a220ab6d13c58b2bf83a59cbdc2e04d0a3f041ddf4b0ba4112d49"): digest.Digest("sha256:b4ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4"), <del> } <del> <del> manifest, err := CreateV2Manifest("testrepo", "testtag", img, fsLayers) <del> if err != nil { <del> t.Fatalf("CreateV2Manifest returned error: %v", err) <del> } <del> <del> if manifest.Versioned.SchemaVersion != 1 { <del> t.Fatal("SchemaVersion != 1") <del> } <del> if manifest.Name != "testrepo" { <del> t.Fatal("incorrect name in manifest") <del> } <del> if manifest.Tag != "testtag" { <del> t.Fatal("incorrect tag in manifest") <del> } <del> if manifest.Architecture != "amd64" { <del> t.Fatal("incorrect arch in manifest") <del> } <del> <del> expectedFSLayers := []schema1.FSLayer{ <del> {BlobSum: digest.Digest("sha256:86e0e091d0da6bde2456dbb48306f3956bbeb2eae1b5b9a43045843f69fe4aaa")}, <del> {BlobSum: digest.Digest("sha256:b4ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4")}, <del> {BlobSum: digest.Digest("sha256:86e0e091d0da6bde2456dbb48306f3956bbeb2eae1b5b9a43045843f69fe4aaa")}, <del> {BlobSum: digest.Digest("sha256:86e0e091d0da6bde2456dbb48306f3956bbeb2eae1b5b9a43045843f69fe4aaa")}, <del> {BlobSum: digest.Digest("sha256:86e0e091d0da6bde2456dbb48306f3956bbeb2eae1b5b9a43045843f69fe4aaa")}, <del> {BlobSum: digest.Digest("sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4")}, <del> } <del> <del> if len(manifest.FSLayers) != len(expectedFSLayers) { <del> t.Fatalf("wrong number of FSLayers: %d", len(manifest.FSLayers)) <del> } <del> if !reflect.DeepEqual(manifest.FSLayers, expectedFSLayers) { <del> t.Fatal("wrong FSLayers list") <del> } <del> <del> expectedV1Compatibility := []string{ <del> `{"architecture":"amd64","config":{"AttachStderr":false,"AttachStdin":false,"AttachStdout":false,"Cmd":["/bin/sh","-c","echo hi"],"Domainname":"","Entrypoint":null,"Env":["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","derived=true","asdf=true"],"Hostname":"23304fc829f9","Image":"sha256:4ab15c48b859c2920dd5224f92aabcd39a52794c5b3cf088fb3bbb438756c246","Labels":{},"OnBuild":[],"OpenStdin":false,"StdinOnce":false,"Tty":false,"User":"","Volumes":null,"WorkingDir":""},"container":"e91032eb0403a61bfe085ff5a5a48e3659e5a6deae9f4d678daa2ae399d5a001","container_config":{"AttachStderr":false,"AttachStdin":false,"AttachStdout":false,"Cmd":["/bin/sh","-c","#(nop) CMD [\"/bin/sh\" \"-c\" \"echo hi\"]"],"Domainname":"","Entrypoint":null,"Env":["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","derived=true","asdf=true"],"Hostname":"23304fc829f9","Image":"sha256:4ab15c48b859c2920dd5224f92aabcd39a52794c5b3cf088fb3bbb438756c246","Labels":{},"OnBuild":[],"OpenStdin":false,"StdinOnce":false,"Tty":false,"User":"","Volumes":null,"WorkingDir":""},"created":"2015-11-04T23:06:32.365666163Z","docker_version":"1.9.0-dev","id":"d728140d3fd23dfcac505954af0b2224b3579b177029eded62916579eb19ac64","os":"linux","parent":"0594e66a9830fa5ba73b66349eb221ea4beb6bac8d2148b90a0f371f8d67bcd5","throwaway":true}`, <del> `{"id":"0594e66a9830fa5ba73b66349eb221ea4beb6bac8d2148b90a0f371f8d67bcd5","parent":"39bc0dbed47060dd8952b048e73744ae471fe50354d2c267d308292c53b83ce1","created":"2015-11-04T23:06:32.083868454Z","container_config":{"Cmd":["/bin/sh -c dd if=/dev/zero of=/file bs=1024 count=1024"]}}`, <del> `{"id":"39bc0dbed47060dd8952b048e73744ae471fe50354d2c267d308292c53b83ce1","parent":"875d7f206c023dc979e1677567a01364074f82b61e220c9b83a4610170490381","created":"2015-11-04T23:06:31.192097572Z","container_config":{"Cmd":["/bin/sh -c #(nop) ENV asdf=true"]},"throwaway":true}`, <del> `{"id":"875d7f206c023dc979e1677567a01364074f82b61e220c9b83a4610170490381","parent":"9e3447ca24cb96d86ebd5960cb34d1299b07e0a0e03801d90b9969a2c187dd6e","created":"2015-11-04T23:06:30.934316144Z","container_config":{"Cmd":["/bin/sh -c #(nop) ENV derived=true"]},"throwaway":true}`, <del> `{"id":"9e3447ca24cb96d86ebd5960cb34d1299b07e0a0e03801d90b9969a2c187dd6e","parent":"3690474eb5b4b26fdfbd89c6e159e8cc376ca76ef48032a30fa6aafd56337880","created":"2015-10-31T22:22:55.613815829Z","container_config":{"Cmd":["/bin/sh -c #(nop) CMD [\"sh\"]"]}}`, <del> `{"id":"3690474eb5b4b26fdfbd89c6e159e8cc376ca76ef48032a30fa6aafd56337880","created":"2015-10-31T22:22:54.690851953Z","container_config":{"Cmd":["/bin/sh -c #(nop) ADD file:a3bc1e842b69636f9df5256c49c5374fb4eef1e281fe3f282c65fb853ee171c5 in /"]}}`, <del> } <del> <del> if len(manifest.History) != len(expectedV1Compatibility) { <del> t.Fatalf("wrong number of history entries: %d", len(manifest.History)) <del> } <del> for i := range expectedV1Compatibility { <del> if manifest.History[i].V1Compatibility != expectedV1Compatibility[i] { <del> t.Fatalf("wrong V1Compatibility %d. expected:\n%s\ngot:\n%s", i, expectedV1Compatibility[i], manifest.History[i].V1Compatibility) <del> } <del> } <del>} <ide><path>distribution/push_v2_unix.go <del>// +build !windows <del> <del>package distribution <del> <del>import ( <del> "github.com/docker/distribution/manifest/schema1" <del> "github.com/docker/docker/image" <del>) <del> <del>func setupBaseLayer(history []schema1.History, rootFS image.RootFS) error { <del> return nil <del>} <ide><path>distribution/push_v2_windows.go <del>// +build windows <del> <del>package distribution <del> <del>import ( <del> "encoding/json" <del> <del> "github.com/docker/distribution/manifest/schema1" <del> "github.com/docker/docker/image" <del>) <del> <del>func setupBaseLayer(history []schema1.History, rootFS image.RootFS) error { <del> var v1Config map[string]*json.RawMessage <del> if err := json.Unmarshal([]byte(history[len(history)-1].V1Compatibility), &v1Config); err != nil { <del> return err <del> } <del> baseID, err := json.Marshal(rootFS.BaseLayerID()) <del> if err != nil { <del> return err <del> } <del> v1Config["parent"] = (*json.RawMessage)(&baseID) <del> configJSON, err := json.Marshal(v1Config) <del> if err != nil { <del> return err <del> } <del> history[len(history)-1].V1Compatibility = string(configJSON) <del> return nil <del>} <ide><path>distribution/xfer/upload.go <ide> import ( <ide> "time" <ide> <ide> "github.com/Sirupsen/logrus" <del> "github.com/docker/distribution/digest" <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/progress" <ide> "golang.org/x/net/context" <ide> type uploadTransfer struct { <ide> Transfer <ide> <ide> diffID layer.DiffID <del> digest digest.Digest <ide> err error <ide> } <ide> <ide> type UploadDescriptor interface { <ide> // DiffID should return the DiffID for this layer. <ide> DiffID() layer.DiffID <ide> // Upload is called to perform the Upload. <del> Upload(ctx context.Context, progressOutput progress.Output) (digest.Digest, error) <add> Upload(ctx context.Context, progressOutput progress.Output) error <ide> } <ide> <ide> // Upload is a blocking function which ensures the listed layers are present on <ide> // the remote registry. It uses the string returned by the Key method to <ide> // deduplicate uploads. <del>func (lum *LayerUploadManager) Upload(ctx context.Context, layers []UploadDescriptor, progressOutput progress.Output) (map[layer.DiffID]digest.Digest, error) { <add>func (lum *LayerUploadManager) Upload(ctx context.Context, layers []UploadDescriptor, progressOutput progress.Output) error { <ide> var ( <ide> uploads []*uploadTransfer <del> digests = make(map[layer.DiffID]digest.Digest) <ide> dedupDescriptors = make(map[string]struct{}) <ide> ) <ide> <ide> func (lum *LayerUploadManager) Upload(ctx context.Context, layers []UploadDescri <ide> for _, upload := range uploads { <ide> select { <ide> case <-ctx.Done(): <del> return nil, ctx.Err() <add> return ctx.Err() <ide> case <-upload.Transfer.Done(): <ide> if upload.err != nil { <del> return nil, upload.err <add> return upload.err <ide> } <del> digests[upload.diffID] = upload.digest <ide> } <ide> } <ide> <del> return digests, nil <add> return nil <ide> } <ide> <ide> func (lum *LayerUploadManager) makeUploadFunc(descriptor UploadDescriptor) DoFunc { <ide> func (lum *LayerUploadManager) makeUploadFunc(descriptor UploadDescriptor) DoFun <ide> <ide> retries := 0 <ide> for { <del> digest, err := descriptor.Upload(u.Transfer.Context(), progressOutput) <add> err := descriptor.Upload(u.Transfer.Context(), progressOutput) <ide> if err == nil { <del> u.digest = digest <ide> break <ide> } <ide> <ide><path>distribution/xfer/upload_test.go <ide> func (u *mockUploadDescriptor) DiffID() layer.DiffID { <ide> } <ide> <ide> // Upload is called to perform the upload. <del>func (u *mockUploadDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (digest.Digest, error) { <add>func (u *mockUploadDescriptor) Upload(ctx context.Context, progressOutput progress.Output) error { <ide> if u.currentUploads != nil { <ide> defer atomic.AddInt32(u.currentUploads, -1) <ide> <ide> if atomic.AddInt32(u.currentUploads, 1) > maxUploadConcurrency { <del> return "", errors.New("concurrency limit exceeded") <add> return errors.New("concurrency limit exceeded") <ide> } <ide> } <ide> <ide> // Sleep a bit to simulate a time-consuming upload. <ide> for i := int64(0); i <= 10; i++ { <ide> select { <ide> case <-ctx.Done(): <del> return "", ctx.Err() <add> return ctx.Err() <ide> case <-time.After(10 * time.Millisecond): <ide> progressOutput.WriteProgress(progress.Progress{ID: u.ID(), Current: i, Total: 10}) <ide> } <ide> } <ide> <ide> if u.simulateRetries != 0 { <ide> u.simulateRetries-- <del> return "", errors.New("simulating retry") <add> return errors.New("simulating retry") <ide> } <ide> <del> // For the mock implementation, use SHA256(DiffID) as the returned <del> // digest. <del> return digest.FromBytes([]byte(u.diffID.String())), nil <add> return nil <ide> } <ide> <ide> func uploadDescriptors(currentUploads *int32) []UploadDescriptor { <ide> func TestSuccessfulUpload(t *testing.T) { <ide> var currentUploads int32 <ide> descriptors := uploadDescriptors(&currentUploads) <ide> <del> digests, err := lum.Upload(context.Background(), descriptors, progress.ChanOutput(progressChan)) <add> err := lum.Upload(context.Background(), descriptors, progress.ChanOutput(progressChan)) <ide> if err != nil { <ide> t.Fatalf("upload error: %v", err) <ide> } <ide> <ide> close(progressChan) <ide> <-progressDone <del> <del> if len(digests) != len(expectedDigests) { <del> t.Fatal("wrong number of keys in digests map") <del> } <del> <del> for key, val := range expectedDigests { <del> if digests[key] != val { <del> t.Fatalf("mismatch in digest array for key %v (expected %v, got %v)", key, val, digests[key]) <del> } <del> if receivedProgress[key.String()] != 10 { <del> t.Fatalf("missing or wrong progress output for %v", key) <del> } <del> } <ide> } <ide> <ide> func TestCancelledUpload(t *testing.T) { <ide> func TestCancelledUpload(t *testing.T) { <ide> }() <ide> <ide> descriptors := uploadDescriptors(nil) <del> _, err := lum.Upload(ctx, descriptors, progress.ChanOutput(progressChan)) <add> err := lum.Upload(ctx, descriptors, progress.ChanOutput(progressChan)) <ide> if err != context.Canceled { <ide> t.Fatal("expected upload to be cancelled") <ide> }
7
PHP
PHP
add getter and setter
5a6c10d5fafaf5a19e085b6b1b16d9aff9714d80
<ide><path>src/Illuminate/Validation/Validator.php <ide> public function setCustomMessages(array $messages) <ide> { <ide> $this->customMessages = array_merge($this->customMessages, $messages); <ide> } <add> <add> /** <add> * Get the custom attributes for the validator <add> * <add> * @return array <add> */ <add> public function getCustomAttributes() <add> { <add> return $this->customAttributes; <add> } <add> <add> /** <add> * Set the custom attributes for the validator <add> * <add> * @param array $customAttributes <add> * @return void <add> */ <add> public function setCustomAttributes(array $customAttributes) <add> { <add> $this->customAttributes = array_merge($this->customAttributes, $customAttributes); <add> } <add> <add> /** <add> * Get the custom values for the validator <add> * <add> * @return array <add> */ <add> public function getCustomValues() <add> { <add> return $this->customValues; <add> } <add> <add> /** <add> * Set the custom values for the validator <add> * <add> * @param array $customValues <add> * @return void <add> */ <add> public function setCustomValues(array $customValues) <add> { <add> $this->customValues = array_merge($this->customValues, $customValues); <add> } <ide> <ide> /** <ide> * Get the fallback messages for the validator.
1
Java
Java
add operator for deferred writes
8c89b478d94f5c290c82ede2c302b1740b5d08e4
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/WriteWithOperator.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.http.server.reactive; <add> <add>import org.reactivestreams.Publisher; <add>import org.reactivestreams.Subscriber; <add>import org.reactivestreams.Subscription; <add>import reactor.core.subscriber.SubscriberBarrier; <add>import reactor.core.support.Assert; <add>import reactor.fn.Function; <add> <add> <add>/** <add> * Given a write function that accepts a source {@code Publisher<T>} to write <add> * with and returns {@code Publisher<Void>} for the result, this operator helps <add> * to defer the invocation of the write function, until we know if the source <add> * publisher will begin publishing without an error. If the first emission is <add> * an error, the write function is bypassed, and the error is sent directly <add> * through the result publisher. Otherwise the write function is invoked. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class WriteWithOperator<T> implements Function<Subscriber<? super Void>, Subscriber<? super T>> { <add> <add> private final java.util.function.Function<Publisher<T>, Publisher<Void>> writeFunction; <add> <add> <add> public WriteWithOperator(java.util.function.Function<Publisher<T>, Publisher<Void>> writeFunction) { <add> this.writeFunction = writeFunction; <add> } <add> <add> @Override <add> public Subscriber<? super T> apply(Subscriber<? super Void> subscriber) { <add> return new WriteWithBarrier(subscriber); <add> } <add> <add> <add> private class WriteWithBarrier extends SubscriberBarrier<T, Void> implements Publisher<T> { <add> <add> /** <add> * We've at at least one emission, we've called the write function, the write <add> * subscriber has subscribed and cached signals have been emitted to it. <add> * We're now simply passing data through to the write subscriber. <add> **/ <add> private boolean readyToWrite = false; <add> <add> /** No emission from upstream yet */ <add> private boolean beforeFirstEmission = true; <add> <add> /** Cached signal before readyToWrite */ <add> private T item; <add> <add> /** Cached 1st/2nd signal before readyToWrite */ <add> private Throwable error; <add> <add> /** Cached 1st/2nd signal before readyToWrite */ <add> private boolean completed = false; <add> <add> /** The actual writeSubscriber vs the downstream completion subscriber */ <add> private Subscriber<? super T> writeSubscriber; <add> <add> <add> public WriteWithBarrier(Subscriber<? super Void> subscriber) { <add> super(subscriber); <add> } <add> <add> <add> @Override <add> protected void doOnSubscribe(Subscription subscription) { <add> super.doOnSubscribe(subscription); <add> ((Subscription) super.upstream()).request(1); // bypass doRequest <add> } <add> <add> @Override <add> public void doNext(T item) { <add> if (this.readyToWrite) { <add> this.writeSubscriber.onNext(item); <add> return; <add> } <add> synchronized (this) { <add> if (this.readyToWrite) { <add> this.writeSubscriber.onNext(item); <add> } <add> else if (this.beforeFirstEmission) { <add> this.item = item; <add> this.beforeFirstEmission = false; <add> writeFunction.apply(this).subscribe(downstream()); <add> } <add> else { <add> subscription.cancel(); <add> downstream().onError(new IllegalStateException("Unexpected item.")); <add> } <add> } <add> } <add> <add> @Override <add> public void doError(Throwable ex) { <add> if (this.readyToWrite) { <add> this.writeSubscriber.onError(ex); <add> return; <add> } <add> synchronized (this) { <add> if (this.readyToWrite) { <add> this.writeSubscriber.onError(ex); <add> } <add> else if (this.beforeFirstEmission) { <add> this.beforeFirstEmission = false; <add> downstream().onError(ex); <add> } <add> else { <add> this.error = ex; <add> } <add> } <add> } <add> <add> @Override <add> public void doComplete() { <add> if (this.readyToWrite) { <add> this.writeSubscriber.onComplete(); <add> return; <add> } <add> synchronized (this) { <add> if (this.readyToWrite) { <add> this.writeSubscriber.onComplete(); <add> } <add> else if (this.beforeFirstEmission) { <add> this.completed = true; <add> this.beforeFirstEmission = false; <add> writeFunction.apply(this).subscribe(downstream()); <add> } <add> else { <add> this.completed = true; <add> } <add> } <add> } <add> <add> @Override <add> public void subscribe(Subscriber<? super T> subscriber) { <add> synchronized (this) { <add> Assert.isNull(this.writeSubscriber, "Only one writeSubscriber supported."); <add> this.writeSubscriber = subscriber; <add> <add> if (this.error != null || this.completed) { <add> this.writeSubscriber.onSubscribe(NO_OP_SUBSCRIPTION); <add> emitCachedSignals(); <add> } <add> else { <add> this.writeSubscriber.onSubscribe(this); <add> } <add> } <add> } <add> <add> /** <add> * Emit cached signals to the write subscriber. <add> * @return true if no more signals expected <add> */ <add> private boolean emitCachedSignals() { <add> if (this.item != null) { <add> this.writeSubscriber.onNext(this.item); <add> } <add> if (this.error != null) { <add> this.writeSubscriber.onError(this.error); <add> return true; <add> } <add> if (this.completed) { <add> this.writeSubscriber.onComplete(); <add> return true; <add> } <add> return false; <add> } <add> <add> @Override <add> protected void doRequest(long n) { <add> if (this.readyToWrite) { <add> super.doRequest(n); <add> return; <add> } <add> synchronized (this) { <add> if (this.writeSubscriber != null) { <add> readyToWrite = true; <add> if (emitCachedSignals()) { <add> return; <add> } <add> n--; <add> if (n == 0) { <add> return; <add> } <add> super.doRequest(n); <add> } <add> } <add> } <add> } <add> <add> private final static Subscription NO_OP_SUBSCRIPTION = new Subscription() { <add> <add> @Override <add> public void request(long n) { <add> } <add> <add> @Override <add> public void cancel() { <add> } <add> }; <add> <add>} <ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/reactive/WriteWithOperatorTests.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.http.server.reactive; <add> <add>import java.util.ArrayList; <add>import java.util.Arrays; <add>import java.util.List; <add>import java.util.concurrent.Executors; <add>import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.reactivestreams.Publisher; <add>import org.reactivestreams.Subscriber; <add>import org.reactivestreams.Subscription; <add>import reactor.Publishers; <add>import reactor.core.publisher.PublisherFactory; <add>import reactor.core.subscriber.SubscriberBarrier; <add>import reactor.rx.Streams; <add>import reactor.rx.action.Signal; <add> <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertSame; <add>import static org.junit.Assert.assertTrue; <add> <add>/** <add> * @author Rossen Stoyanchev <add> */ <add>@SuppressWarnings("ThrowableResultOfMethodCallIgnored") <add>public class WriteWithOperatorTests { <add> <add> private OneByOneAsyncWriter writer; <add> <add> private WriteWithOperator<String> operator; <add> <add> <add> @Before <add> public void setUp() throws Exception { <add> this.writer = new OneByOneAsyncWriter(); <add> this.operator = new WriteWithOperator<>(this.writer::writeWith); <add> } <add> <add> @Test <add> public void errorBeforeFirstItem() throws Exception { <add> IllegalStateException error = new IllegalStateException("boo"); <add> Publisher<Void> completion = Publishers.lift(Publishers.error(error), this.operator); <add> List<Signal<Void>> signals = Streams.wrap(completion).materialize().toList().await(5, TimeUnit.SECONDS); <add> <add> assertEquals(1, signals.size()); <add> assertSame("Unexpected signal: " + signals.get(0), error, signals.get(0).getThrowable()); <add> } <add> <add> @Test <add> public void completionBeforeFirstItem() throws Exception { <add> Publisher<Void> completion = Publishers.lift(Publishers.empty(), this.operator); <add> List<Signal<Void>> signals = Streams.wrap(completion).materialize().toList().await(5, TimeUnit.SECONDS); <add> <add> assertEquals(1, signals.size()); <add> assertTrue("Unexpected signal: " + signals.get(0), signals.get(0).isOnComplete()); <add> <add> assertEquals(0, this.writer.items.size()); <add> assertTrue(this.writer.completed); <add> } <add> <add> @Test <add> public void writeOneItem() throws Exception { <add> Publisher<Void> completion = Publishers.lift(Publishers.just("one"), this.operator); <add> List<Signal<Void>> signals = Streams.wrap(completion).materialize().toList().await(5, TimeUnit.SECONDS); <add> <add> assertEquals(1, signals.size()); <add> assertTrue("Unexpected signal: " + signals.get(0), signals.get(0).isOnComplete()); <add> <add> assertEquals(1, this.writer.items.size()); <add> assertEquals("one", this.writer.items.get(0)); <add> assertTrue(this.writer.completed); <add> } <add> <add> <add> @Test <add> public void writeMultipleItems() throws Exception { <add> List<String> items = Arrays.asList("one", "two", "three"); <add> Publisher<Void> completion = Publishers.lift(Publishers.from(items), this.operator); <add> List<Signal<Void>> signals = Streams.wrap(completion).materialize().consumeAsList().await(5, TimeUnit.SECONDS); <add> <add> assertEquals(1, signals.size()); <add> assertTrue("Unexpected signal: " + signals.get(0), signals.get(0).isOnComplete()); <add> <add> assertEquals(3, this.writer.items.size()); <add> assertEquals("one", this.writer.items.get(0)); <add> assertEquals("two", this.writer.items.get(1)); <add> assertEquals("three", this.writer.items.get(2)); <add> assertTrue(this.writer.completed); <add> } <add> <add> @Test <add> public void errorAfterMultipleItems() throws Exception { <add> IllegalStateException error = new IllegalStateException("boo"); <add> Publisher<String> publisher = PublisherFactory.create(subscriber -> { <add> int i = subscriber.context().incrementAndGet(); <add> subscriber.onNext(String.valueOf(i)); <add> if (i == 3) { <add> subscriber.onError(error); <add> } <add> }, subscriber -> new AtomicInteger()); <add> Publisher<Void> completion = Publishers.lift(publisher, this.operator); <add> List<Signal<Void>> signals = Streams.wrap(completion).materialize().toList().await(5, TimeUnit.SECONDS); <add> <add> assertEquals(1, signals.size()); <add> assertSame("Unexpected signal: " + signals.get(0), error, signals.get(0).getThrowable()); <add> <add> assertEquals(3, this.writer.items.size()); <add> assertEquals("1", this.writer.items.get(0)); <add> assertEquals("2", this.writer.items.get(1)); <add> assertEquals("3", this.writer.items.get(2)); <add> assertSame(error, this.writer.error); <add> } <add> <add> <add> private static class OneByOneAsyncWriter { <add> <add> private List<String> items = new ArrayList<>(); <add> <add> private boolean completed = false; <add> <add> private Throwable error; <add> <add> <add> public Publisher<Void> writeWith(Publisher<String> publisher) { <add> return subscriber -> { <add> Executors.newSingleThreadScheduledExecutor().schedule( <add> (Runnable) () -> publisher.subscribe(new WriteSubscriber(subscriber)), <add> 50, TimeUnit.MILLISECONDS); <add> }; <add> } <add> <add> private class WriteSubscriber extends SubscriberBarrier<String, Void> { <add> <add> public WriteSubscriber(Subscriber<? super Void> subscriber) { <add> super(subscriber); <add> } <add> <add> @Override <add> protected void doOnSubscribe(Subscription subscription) { <add> subscription.request(1); <add> } <add> <add> @Override <add> public void doNext(String item) { <add> items.add(item); <add> this.subscription.request(1); <add> } <add> <add> @Override <add> public void doError(Throwable ex) { <add> error = ex; <add> this.subscriber.onError(ex); <add> } <add> <add> @Override <add> public void doComplete() { <add> completed = true; <add> this.subscriber.onComplete(); <add> } <add> } <add> } <add> <add> private final static Subscription NO_OP_SUBSCRIPTION = new Subscription() { <add> <add> @Override <add> public void request(long n) { <add> } <add> <add> @Override <add> public void cancel() { <add> } <add> }; <add> <add>}
2
Ruby
Ruby
switch compilers when no build is specified
cc08d08d74f20d72ba378fed3bbc53390be0b97d
<ide><path>Library/Homebrew/build.rb <ide> def install f <ide> end <ide> end <ide> <del> if f.fails_with? ENV.compiler <del> cs = CompilerSelector.new f <del> cs.select_compiler <del> cs.advise <del> end <add> CompilerSelector.new(f).select_compiler if f.fails_with? ENV.compiler <ide> <ide> f.brew do <ide> if ARGV.flag? '--git' <ide><path>Library/Homebrew/compilers.rb <ide> class CompilerFailure <ide> def initialize compiler, &block <ide> @compiler = compiler <ide> instance_eval(&block) if block_given? <add> @build ||= 9999 <ide> end <ide> <ide> def build val=nil <ide> def select_compiler <ide> # the failing build is >= the currently installed version of foo. <ide> @compilers = @compilers.reject do |cc| <ide> failure = @f.fails_with? cc <del> next unless failure <del> failure.build >= cc.build or not ARGV.homebrew_developer? <add> failure && failure.build >= cc.build <ide> end <ide> <ide> return if @compilers.empty? or @compilers.include? ENV.compiler <ide> def select_compiler <ide> end <ide> end <ide> end <del> <del> def advise <del> failure = @f.fails_with? @old_compiler <del> return unless failure <del> <del> # If we're still using the original ENV.compiler, then the formula did not <del> # declare a specific failing build, so we continue and print some advice. <del> # Otherwise, tell the user that we're switching compilers. <del> if @old_compiler == ENV.compiler <del> cc = Compiler.new(ENV.compiler) <del> subject = "#{@f.name}-#{@f.version}: builds with #{NAMES[cc.name]}-#{cc.build}-#{MACOS_VERSION}" <del> warning = "Using #{NAMES[cc.name]}, but this formula is reported to fail with #{NAMES[cc.name]}." <del> warning += "\n\n#{failure.cause.strip}\n" unless failure.cause.nil? <del> warning += <<-EOS.undent <del> <del> We are continuing anyway so if the build succeeds, please open a ticket with <del> the subject <del> <del> #{subject} <del> <del> so that we can update the formula accordingly. Thanks! <del> EOS <del> <del> viable = @compilers.reject { |c| @f.fails_with? c } <del> unless viable.empty? <del> warning += "\nIf it fails you can use " <del> options = viable.map { |c| "--use-#{c.name}" } <del> warning += "#{options*' or '} to try a different compiler." <del> end <del> <del> opoo warning <del> end <del> end <ide> end <ide><path>Library/Homebrew/formula.rb <ide> def keg_only_reason <ide> def fails_with? cc <ide> return false if self.class.cc_failures.nil? <ide> cc = Compiler.new(cc) unless cc.is_a? Compiler <del> return self.class.cc_failures.find do |failure| <del> next unless failure.compiler == cc.name <del> failure.build.zero? or \ <del> (failure.build >= cc.build or not ARGV.homebrew_developer?) <add> self.class.cc_failures.find do |failure| <add> failure.compiler == cc.name && failure.build >= cc.build <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/test_compilers.rb <ide> def test_even_more_mixed_compiler_failures <ide> <ide> cs.select_compiler <ide> <del> assert_equal case MacOS.clang_build_version <del> when 0..210 then :gcc <del> else :clang <add> assert_equal case MacOS.gcc_42_build_version <add> when nil then :llvm <add> else :gcc <ide> end, ENV.compiler <ide> end <ide> <ide> def test_block_with_no_build_compiler_failures <ide> <ide> cs.select_compiler <ide> <del> assert_equal MacOS.default_compiler, ENV.compiler <add> assert_not_equal :clang, ENV.compiler <ide> end <ide> end
4
Ruby
Ruby
use inheritence to deal with custom methods
b2979117e0adad6f86370074237f57d96cc7c1c7
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def column_exists?(table_name, column_name, type = nil, options = {}) <ide> # <ide> # See also TableDefinition#column for details on how to create columns. <ide> def create_table(table_name, options = {}) <del> table_definition = TableDefinition.new(self) <del> table_definition.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) unless options[:id] == false <add> td = table_definition <add> td.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) unless options[:id] == false <ide> <del> yield table_definition if block_given? <add> yield td if block_given? <ide> <ide> if options[:force] && table_exists?(table_name) <ide> drop_table(table_name, options) <ide> end <ide> <ide> create_sql = "CREATE#{' TEMPORARY' if options[:temporary]} TABLE " <ide> create_sql << "#{quote_table_name(table_name)} (" <del> create_sql << table_definition.to_sql <add> create_sql << td.to_sql <ide> create_sql << ") #{options[:options]}" <ide> execute create_sql <ide> end <ide> def quoted_columns_for_index(column_names, options = {}) <ide> def options_include_default?(options) <ide> options.include?(:default) && !(options[:null] == false && options[:default].nil?) <ide> end <add> <add> private <add> def table_definition <add> TableDefinition.new(self) <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def self.postgresql_connection(config) # :nodoc: <ide> end <ide> <ide> module ConnectionAdapters <del> class TableDefinition <del> def xml(*args) <del> options = args.extract_options! <del> column(args[0], 'xml', options) <del> end <del> end <ide> # PostgreSQL-specific extensions to column definitions in a table. <ide> class PostgreSQLColumn < Column #:nodoc: <ide> # Instantiates a new PostgreSQL column definition in a table. <ide> module ConnectionAdapters <ide> # * <tt>:allow_concurrency</tt> - If true, use async query methods so Ruby threads don't deadlock; <ide> # otherwise, use blocking query methods. <ide> class PostgreSQLAdapter < AbstractAdapter <add> class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition <add> def xml(*args) <add> options = args.extract_options! <add> column(args[0], 'xml', options) <add> end <add> end <add> <ide> ADAPTER_NAME = 'PostgreSQL'.freeze <ide> <ide> NATIVE_DATABASE_TYPES = { <ide> def extract_pg_identifier_from_name(name) <ide> [match_data[1], (rest.length > 0 ? rest : nil)] <ide> end <ide> end <add> <add> def table_definition <add> TableDefinition.new(self) <add> end <ide> end <ide> end <ide> end
2
Python
Python
use contextmanager in _run_doctests
616d27eba33dcb6268ae443e3880300cc82fdc48
<ide><path>tools/refguide_check.py <ide> <ide> $ python refguide_check.py --rst docs <ide> """ <del>import sys <del>import os <del>import re <ide> import copy <del>import inspect <del>import warnings <ide> import doctest <del>import tempfile <add>import glob <add>import inspect <ide> import io <del>import docutils.core <del>from docutils.parsers.rst import directives <add>import os <add>import re <ide> import shutil <del>import glob <del>from doctest import NORMALIZE_WHITESPACE, ELLIPSIS, IGNORE_EXCEPTION_DETAIL <add>import sys <add>import tempfile <add>import warnings <add>import docutils.core <ide> from argparse import ArgumentParser <add>from contextlib import redirect_stderr <add>from doctest import NORMALIZE_WHITESPACE, ELLIPSIS, IGNORE_EXCEPTION_DETAIL <add> <add>from docutils.parsers.rst import directives <ide> from pkg_resources import parse_version <ide> <ide> import sphinx <ide> def flush(self): <ide> sys.stdout.flush() <ide> <ide> # Run tests, trying to restore global state afterward <del> old_printoptions = np.get_printoptions() <del> old_errstate = np.seterr() <del> old_stderr = sys.stderr <del> cwd = os.getcwd() <del> tmpdir = tempfile.mkdtemp() <del> sys.stderr = MyStderr() <del> try: <del> os.chdir(tmpdir) <del> <del> # try to ensure random seed is NOT reproducible <del> np.random.seed(None) <del> <del> ns = {} <del> for t in tests: <del> # We broke the tests up into chunks to try to avoid PSEUDOCODE <del> # This has the unfortunate side effect of restarting the global <del> # namespace for each test chunk, so variables will be "lost" after <del> # a chunk. Chain the globals to avoid this <del> t.globs.update(ns) <del> t.filename = short_path(t.filename, cwd) <del> # Process our options <del> if any([SKIPBLOCK in ex.options for ex in t.examples]): <del> continue <del> fails, successes = runner.run(t, out=out, clear_globs=False) <del> if fails > 0: <del> success = False <del> ns = t.globs <del> finally: <del> sys.stderr = old_stderr <del> os.chdir(cwd) <del> shutil.rmtree(tmpdir) <del> np.set_printoptions(**old_printoptions) <del> np.seterr(**old_errstate) <add> with np.errstate(), np.printoptions(), redirect_stderr(MyStderr()): <add> cwd = os.getcwd() <add> tmpdir = tempfile.mkdtemp() <add> try: <add> os.chdir(tmpdir) <add> <add> # try to ensure random seed is NOT reproducible <add> np.random.seed(None) <add> <add> ns = {} <add> for t in tests: <add> # We broke the tests up into chunks to try to avoid PSEUDOCODE <add> # This has the unfortunate side effect of restarting the global <add> # namespace for each test chunk, so variables will be "lost" after <add> # a chunk. Chain the globals to avoid this <add> t.globs.update(ns) <add> t.filename = short_path(t.filename, cwd) <add> # Process our options <add> if any([SKIPBLOCK in ex.options for ex in t.examples]): <add> continue <add> fails, successes = runner.run(t, out=out, clear_globs=False) <add> if fails > 0: <add> success = False <add> ns = t.globs <add> finally: <add> os.chdir(cwd) <add> shutil.rmtree(tmpdir) <ide> <ide> return success, output <ide>
1
Java
Java
improve dateheaders in mockservletrequest/response
43e36e2dee8e2c7be54ba3715cc355c8a35f9efc
<ide><path>spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java <ide> import java.io.Reader; <ide> import java.io.UnsupportedEncodingException; <ide> import java.security.Principal; <add>import java.text.ParseException; <add>import java.text.SimpleDateFormat; <ide> import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.Date; <ide> import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.Set; <add>import java.util.TimeZone; <add> <ide> import javax.servlet.AsyncContext; <ide> import javax.servlet.DispatcherType; <ide> import javax.servlet.RequestDispatcher; <ide> public class MockHttpServletRequest implements HttpServletRequest { <ide> private static final ServletInputStream EMPTY_SERVLET_INPUT_STREAM = <ide> new DelegatingServletInputStream(new ByteArrayInputStream(new byte[0])); <ide> <add> /** <add> * Date formats as specified in the HTTP RFC <add> * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a> <add> */ <add> private static final String[] DATE_FORMATS = new String[] { <add> "EEE, dd MMM yyyy HH:mm:ss zzz", <add> "EEE, dd-MMM-yy HH:mm:ss zzz", <add> "EEE MMM dd HH:mm:ss yyyy" <add> }; <add> <add> private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); <add> <ide> <ide> private boolean active = true; <ide> <ide> public void setPreferredLocales(List<Locale> locales) { <ide> } <ide> <ide> /** <del> * Returns the first preferred {@linkplain Locale locale} configured <add> * Return the first preferred {@linkplain Locale locale} configured <ide> * in this mock request. <ide> * <p>If no locales have been explicitly configured, the default, <ide> * preferred {@link Locale} for the <em>server</em> mocked by this <ide> public Locale getLocale() { <ide> } <ide> <ide> /** <del> * Returns an {@linkplain Enumeration enumeration} of the preferred <add> * Return an {@linkplain Enumeration enumeration} of the preferred <ide> * {@linkplain Locale locales} configured in this mock request. <ide> * <p>If no locales have been explicitly configured, the default, <ide> * preferred {@link Locale} for the <em>server</em> mocked by this <ide> public void setSecure(boolean secure) { <ide> } <ide> <ide> /** <del> * Returns {@code true} if the {@link #setSecure secure} flag has been set <add> * Return {@code true} if the {@link #setSecure secure} flag has been set <ide> * to {@code true} or if the {@link #getScheme scheme} is {@code https}. <ide> * @see javax.servlet.ServletRequest#isSecure() <ide> */ <ide> public Cookie[] getCookies() { <ide> <ide> /** <ide> * Add a header entry for the given name. <del> * <p>If there was no entry for that header name before, the value will be used <del> * as-is. In case of an existing entry, a String array will be created, <del> * adding the given value (more specifically, its toString representation) <del> * as further element. <del> * <p>Multiple values can only be stored as list of Strings, following the <del> * Servlet spec (see {@code getHeaders} accessor). As alternative to <del> * repeated {@code addHeader} calls for individual elements, you can <del> * use a single call with an entire array or Collection of values as <del> * parameter. <add> * <p>While this method can take any {@code Object} as a parameter, <add> * it is recommended to use the following types: <add> * <ul> <add> * <li>String or any Object to be converted using {@code toString}, see {@link #getHeader} </li> <add> * <li>String, Number or Date for date headers, see {@link #getDateHeader}</li> <add> * <li>String or Number for integer headers, see {@link #getIntHeader}</li> <add> * <li>{@code String[]} and {@code Collection<String>} for multiple values, see {@link #getHeaders}</li> <add> * </ul> <ide> * @see #getHeaderNames <del> * @see #getHeader <ide> * @see #getHeaders <del> * @see #getDateHeader <del> * @see #getIntHeader <ide> */ <ide> public void addHeader(String name, Object value) { <ide> if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) { <ide> else if (value.getClass().isArray()) { <ide> } <ide> } <ide> <add> /** <add> * Return the long timestamp for the date header with the given {@code name}. <add> * <p>If the internal value representation is a String, this method will try <add> * to parse it as a date using the supported date formats: <add> * <ul> <add> * <li>"EEE, dd MMM yyyy HH:mm:ss zzz"</li> <add> * <li>"EEE, dd-MMM-yy HH:mm:ss zzz"</li> <add> * <li>"EEE MMM dd HH:mm:ss yyyy"</li> <add> * </ul> <add> * @param name the header name <add> * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a> <add> */ <ide> @Override <ide> public long getDateHeader(String name) { <ide> HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); <ide> public long getDateHeader(String name) { <ide> else if (value instanceof Number) { <ide> return ((Number) value).longValue(); <ide> } <add> else if (value instanceof String) { <add> return parseDateHeader(name, (String) value); <add> } <ide> else if (value != null) { <ide> throw new IllegalArgumentException( <del> "Value for header '" + name + "' is neither a Date nor a Number: " + value); <add> "Value for header '" + name + "' is not a Date, Number, or String: " + value); <ide> } <ide> else { <ide> return -1L; <ide> } <ide> } <ide> <add> private long parseDateHeader(String name, String value) { <add> for (String dateFormat : DATE_FORMATS) { <add> SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US); <add> simpleDateFormat.setTimeZone(GMT); <add> try { <add> return simpleDateFormat.parse(value).getTime(); <add> } <add> catch (ParseException ex) { <add> // ignore <add> } <add> } <add> throw new IllegalArgumentException("Cannot parse date value '" + value + "' for '" + name + "' header"); <add> } <add> <ide> @Override <ide> public String getHeader(String name) { <ide> HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); <ide> public Part getPart(String name) throws IOException, IllegalStateException, Serv <ide> @Override <ide> public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { <ide> List<Part> result = new LinkedList<Part>(); <del> for(List<Part> list : this.parts.values()) { <add> for (List<Part> list : this.parts.values()) { <ide> result.addAll(list); <ide> } <ide> return result; <ide><path>spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java <ide> import java.io.PrintWriter; <ide> import java.io.UnsupportedEncodingException; <ide> import java.io.Writer; <add>import java.text.SimpleDateFormat; <ide> import java.util.ArrayList; <ide> import java.util.Collection; <ide> import java.util.Collections; <add>import java.util.Date; <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <add>import java.util.TimeZone; <add> <ide> import javax.servlet.ServletOutputStream; <ide> import javax.servlet.http.Cookie; <ide> import javax.servlet.http.HttpServletResponse; <ide> * <ide> * @author Juergen Hoeller <ide> * @author Rod Johnson <add> * @author Brian Clozel <ide> * @since 1.0.2 <ide> */ <ide> public class MockHttpServletResponse implements HttpServletResponse { <ide> public class MockHttpServletResponse implements HttpServletResponse { <ide> <ide> private static final String LOCATION_HEADER = "Location"; <ide> <add> private static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz"; <add> <add> private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); <add> <ide> <ide> //--------------------------------------------------------------------- <ide> // ServletResponse properties <ide> public String getRedirectedUrl() { <ide> <ide> @Override <ide> public void setDateHeader(String name, long value) { <del> setHeaderValue(name, value); <add> setHeaderValue(name, formatDate(value)); <ide> } <ide> <ide> @Override <ide> public void addDateHeader(String name, long value) { <del> addHeaderValue(name, value); <add> addHeaderValue(name, formatDate(value)); <add> } <add> <add> private String formatDate(long date) { <add> SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US); <add> dateFormat.setTimeZone(GMT); <add> return dateFormat.format(new Date(date)); <ide> } <ide> <ide> @Override <ide><path>spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.Collections; <add>import java.util.Date; <ide> import java.util.Enumeration; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> * @author Mark Fisher <ide> * @author Rossen Stoyanchev <ide> * @author Sam Brannen <add> * @author Brian Clozel <add> * @author Jakub Narloch <ide> */ <ide> public class MockHttpServletRequestTests { <ide> <ide> private static final String HOST = "Host"; <ide> <add> private static final String CONTENT_TYPE = "Content-Type"; <add> <add> private static final String IF_MODIFIED_SINCE = "If-Modified-Since"; <add> <ide> private MockHttpServletRequest request = new MockHttpServletRequest(); <ide> <ide> <ide> public void setContentType() { <ide> String contentType = "test/plain"; <ide> request.setContentType(contentType); <ide> assertEquals(contentType, request.getContentType()); <del> assertEquals(contentType, request.getHeader("Content-Type")); <add> assertEquals(contentType, request.getHeader(CONTENT_TYPE)); <ide> assertNull(request.getCharacterEncoding()); <ide> } <ide> <ide> public void setContentTypeUTF8() { <ide> String contentType = "test/plain;charset=UTF-8"; <ide> request.setContentType(contentType); <ide> assertEquals(contentType, request.getContentType()); <del> assertEquals(contentType, request.getHeader("Content-Type")); <add> assertEquals(contentType, request.getHeader(CONTENT_TYPE)); <ide> assertEquals("UTF-8", request.getCharacterEncoding()); <ide> } <ide> <ide> public void contentTypeHeader() { <ide> String contentType = "test/plain"; <ide> request.addHeader("Content-Type", contentType); <ide> assertEquals(contentType, request.getContentType()); <del> assertEquals(contentType, request.getHeader("Content-Type")); <add> assertEquals(contentType, request.getHeader(CONTENT_TYPE)); <ide> assertNull(request.getCharacterEncoding()); <ide> } <ide> <ide> public void contentTypeHeaderUTF8() { <ide> String contentType = "test/plain;charset=UTF-8"; <ide> request.addHeader("Content-Type", contentType); <ide> assertEquals(contentType, request.getContentType()); <del> assertEquals(contentType, request.getHeader("Content-Type")); <add> assertEquals(contentType, request.getHeader(CONTENT_TYPE)); <ide> assertEquals("UTF-8", request.getCharacterEncoding()); <ide> } <ide> <ide> public void setContentTypeHeaderWithMoreComplexCharsetSyntax() { <ide> String contentType = "test/plain;charset=\"utf-8\";foo=\"charset=bar\";foocharset=bar;foo=bar"; <ide> request.addHeader("Content-Type", contentType); <ide> assertEquals(contentType, request.getContentType()); <del> assertEquals(contentType, request.getHeader("Content-Type")); <add> assertEquals(contentType, request.getHeader(CONTENT_TYPE)); <ide> assertEquals("UTF-8", request.getCharacterEncoding()); <ide> } <ide> <ide> public void setContentTypeThenCharacterEncoding() { <ide> request.setContentType("test/plain"); <ide> request.setCharacterEncoding("UTF-8"); <ide> assertEquals("test/plain", request.getContentType()); <del> assertEquals("test/plain;charset=UTF-8", request.getHeader("Content-Type")); <add> assertEquals("test/plain;charset=UTF-8", request.getHeader(CONTENT_TYPE)); <ide> assertEquals("UTF-8", request.getCharacterEncoding()); <ide> } <ide> <ide> public void setCharacterEncodingThenContentType() { <ide> request.setCharacterEncoding("UTF-8"); <ide> request.setContentType("test/plain"); <ide> assertEquals("test/plain", request.getContentType()); <del> assertEquals("test/plain;charset=UTF-8", request.getHeader("Content-Type")); <add> assertEquals("test/plain;charset=UTF-8", request.getHeader(CONTENT_TYPE)); <ide> assertEquals("UTF-8", request.getCharacterEncoding()); <ide> } <ide> <ide> public void isSecureWithHttpsSchemeAndSecureFlagIsTrue() { <ide> assertTrue(request.isSecure()); <ide> } <ide> <add> @Test <add> public void httpHeaderDate() throws Exception { <add> Date date = new Date(); <add> request.addHeader(IF_MODIFIED_SINCE, date); <add> assertEquals(date.getTime(), request.getDateHeader(IF_MODIFIED_SINCE)); <add> } <add> <add> @Test <add> public void httpHeaderTimestamp() throws Exception { <add> long timestamp = new Date().getTime(); <add> request.addHeader(IF_MODIFIED_SINCE, timestamp); <add> assertEquals(timestamp, request.getDateHeader(IF_MODIFIED_SINCE)); <add> } <add> <add> @Test <add> public void httpHeaderRfcFormatedDate() throws Exception { <add> request.addHeader(IF_MODIFIED_SINCE, "Tue, 21 Jul 2015 10:00:00 GMT"); <add> assertEquals(1437472800000L, request.getDateHeader(IF_MODIFIED_SINCE)); <add> } <add> <add> @Test <add> public void httpHeaderFirstVariantFormatedDate() throws Exception { <add> request.addHeader(IF_MODIFIED_SINCE, "Tue, 21-Jul-15 10:00:00 GMT"); <add> assertEquals(1437472800000L, request.getDateHeader(IF_MODIFIED_SINCE)); <add> } <add> <add> @Test <add> public void httpHeaderSecondVariantFormatedDate() throws Exception { <add> request.addHeader(IF_MODIFIED_SINCE, "Tue Jul 21 10:00:00 2015"); <add> assertEquals(1437472800000L, request.getDateHeader(IF_MODIFIED_SINCE)); <add> } <add> <add> @Test(expected = IllegalArgumentException.class) <add> public void httpHeaderFormatedDateError() throws Exception { <add> request.addHeader(IF_MODIFIED_SINCE, "This is not a date"); <add> request.getDateHeader(IF_MODIFIED_SINCE); <add> } <add> <ide> private void assertEqualEnumerations(Enumeration<?> enum1, Enumeration<?> enum2) { <ide> assertNotNull(enum1); <ide> assertNotNull(enum2); <ide><path>spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.io.IOException; <ide> import java.util.Arrays; <ide> import java.util.Collection; <add> <ide> import javax.servlet.http.HttpServletResponse; <ide> <ide> import org.junit.Test; <ide> public void locationHeaderUpdatesGetRedirectedUrl() { <ide> assertEquals(redirectUrl, response.getRedirectedUrl()); <ide> } <ide> <add> @Test <add> public void setDateHeader() { <add> response.setDateHeader("Last-Modified", 1437472800000L); <add> assertEquals("Tue, 21 Jul 2015 10:00:00 GMT", response.getHeader("Last-Modified")); <add> } <add> <add> @Test <add> public void addDateHeader() { <add> response.addDateHeader("Last-Modified", 1437472800000L); <add> response.addDateHeader("Last-Modified", 1437472801000L); <add> assertEquals("Tue, 21 Jul 2015 10:00:00 GMT", response.getHeaders("Last-Modified").get(0)); <add> assertEquals("Tue, 21 Jul 2015 10:00:01 GMT", response.getHeaders("Last-Modified").get(1)); <add> } <add> <ide> /** <ide> * SPR-10414 <ide> */ <ide><path>spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletRequest.java <ide> import java.io.Reader; <ide> import java.io.UnsupportedEncodingException; <ide> import java.security.Principal; <add>import java.text.ParseException; <add>import java.text.SimpleDateFormat; <ide> import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.Date; <ide> import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.Set; <add>import java.util.TimeZone; <add> <ide> import javax.servlet.AsyncContext; <ide> import javax.servlet.DispatcherType; <ide> import javax.servlet.RequestDispatcher; <ide> public class MockHttpServletRequest implements HttpServletRequest { <ide> private static final ServletInputStream EMPTY_SERVLET_INPUT_STREAM = <ide> new DelegatingServletInputStream(new ByteArrayInputStream(new byte[0])); <ide> <add> /** <add> * Date formats as specified in the HTTP RFC <add> * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a> <add> */ <add> private static final String[] DATE_FORMATS = new String[] { <add> "EEE, dd MMM yyyy HH:mm:ss zzz", <add> "EEE, dd-MMM-yy HH:mm:ss zzz", <add> "EEE MMM dd HH:mm:ss yyyy" <add> }; <add> <add> private static TimeZone GMT = TimeZone.getTimeZone("GMT"); <ide> <ide> private boolean active = true; <ide> <ide> public Cookie[] getCookies() { <ide> <ide> /** <ide> * Add a header entry for the given name. <del> * <p>If there was no entry for that header name before, the value will be used <del> * as-is. In case of an existing entry, a String array will be created, <del> * adding the given value (more specifically, its toString representation) <del> * as further element. <del> * <p>Multiple values can only be stored as list of Strings, following the <del> * Servlet spec (see {@code getHeaders} accessor). As alternative to <del> * repeated {@code addHeader} calls for individual elements, you can <del> * use a single call with an entire array or Collection of values as <del> * parameter. <add> * <p>While this method can take any {@code Object} as a parameter, <add> * it is recommended to use the following types: <add> * <ul> <add> * <li>String or any Object to be converted using {@code toString}, see {@link #getHeader}</li> <add> * <li>String, Number or Date for date headers, see {@link #getDateHeader}</li> <add> * <li>String or Number for integer headers, see {@link #getIntHeader}</li> <add> * <li>{@code String[]} and {@code Collection<String>} for multiple values, see {@link #getHeaders}</li> <add> * </ul> <ide> * @see #getHeaderNames <del> * @see #getHeader <ide> * @see #getHeaders <del> * @see #getDateHeader <del> * @see #getIntHeader <ide> */ <ide> public void addHeader(String name, Object value) { <ide> if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) { <ide> else if (value.getClass().isArray()) { <ide> } <ide> } <ide> <add> /** <add> * Return the long timestamp for the date header with the given {@code name}. <add> * <p>If the internal value representation is a String, this method will try <add> * to parse it as a date using the supported date formats: <add> * <ul> <add> * <li>"EEE, dd MMM yyyy HH:mm:ss zzz"</li> <add> * <li>"EEE, dd-MMM-yy HH:mm:ss zzz"</li> <add> * <li>"EEE MMM dd HH:mm:ss yyyy"</li> <add> * </ul> <add> * @param name the header name <add> * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a> <add> */ <ide> @Override <ide> public long getDateHeader(String name) { <ide> HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); <ide> public long getDateHeader(String name) { <ide> else if (value instanceof Number) { <ide> return ((Number) value).longValue(); <ide> } <add> else if (value instanceof String) { <add> return parseDateHeader(name, (String) value); <add> } <ide> else if (value != null) { <ide> throw new IllegalArgumentException( <del> "Value for header '" + name + "' is neither a Date nor a Number: " + value); <add> "Value for header '" + name + "' is not a Date, Number, or String: " + value); <ide> } <ide> else { <ide> return -1L; <ide> } <ide> } <ide> <add> private long parseDateHeader(String name, String value) { <add> for (String dateFormat : DATE_FORMATS) { <add> SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US); <add> simpleDateFormat.setTimeZone(GMT); <add> try { <add> return simpleDateFormat.parse(value).getTime(); <add> } <add> catch (ParseException ex) { <add> // ignore <add> } <add> } <add> throw new IllegalArgumentException("Cannot parse date value '" + value + "' for '" + name + "' header"); <add> } <add> <ide> @Override <ide> public String getHeader(String name) { <ide> HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); <ide> public Part getPart(String name) throws IOException, IllegalStateException, Serv <ide> @Override <ide> public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { <ide> List<Part> result = new LinkedList<Part>(); <del> for(List<Part> list : this.parts.values()) { <add> for (List<Part> list : this.parts.values()) { <ide> result.addAll(list); <ide> } <ide> return result;
5
PHP
PHP
add deletemany() and deletemanyorfail()
8c60a78fdf723711062622124dbcc8ecddf0eca0
<ide><path>src/ORM/Table.php <ide> public function deleteMany(iterable $entities, $options = []) <ide> * @param array|\ArrayAccess $options Options used when calling Table::save() for each entity. <ide> * @return \Cake\Datasource\EntityInterface[]|\Cake\Datasource\ResultSetInterface Entities list. <ide> * @throws \Exception <add> * @throws \Cake\ORM\Exception\PersistenceFailedException <ide> */ <ide> public function deleteManyOrFail(iterable $entities, $options = []) <ide> { <ide> public function deleteManyOrFail(iterable $entities, $options = []) <ide> } <ide> <ide> if ($success === false) { <del> throw new PersistenceFailedException($failed, ['delete']); <add> throw new PersistenceFailedException($failed, ['deleteMany']); <ide> } <ide> <ide> return $success;
1
PHP
PHP
fix docblock on argument type
603ed4a73f926e2a94fb39a01ac1d1dbaf5255d1
<ide><path>src/Illuminate/Contracts/Foundation/Application.php <ide> public function register($provider, $options = [], $force = false); <ide> * Register a deferred provider and service. <ide> * <ide> * @param string $provider <del> * @param string $service <add> * @param string|null $service <ide> * @return void <ide> */ <ide> public function registerDeferredProvider($provider, $service = null); <ide><path>src/Illuminate/Foundation/Application.php <ide> public function loadDeferredProvider($service) <ide> * Register a deferred provider and service. <ide> * <ide> * @param string $provider <del> * @param string $service <add> * @param string|null $service <ide> * @return void <ide> */ <ide> public function registerDeferredProvider($provider, $service = null)
2
Javascript
Javascript
provide support for custom animation events
c53d4c94300c97dd005f9a0cbdbfa387294b9026
<ide><path>src/ng/animator.js <ide> var $AnimatorProvider = function() { <ide> * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden <ide> */ <ide> animator.hide = animateActionFactory('hide', noop, hide); <add> <add> /** <add> * @ngdoc function <add> * @name ng.animator#animate <add> * @methodOf ng.$animator <add> * <add> * @description <add> * Triggers a custom animation event to be executed on the given element <add> * <add> * @param {jQuery/jqLite element} element that will be animated <add> */ <add> animator.animate = function(event, element) { <add> animateActionFactory(event, noop, noop)(element); <add> } <ide> return animator; <ide> <ide> function animateActionFactory(type, beforeFn, afterFn) { <ide><path>test/ng/animatorSpec.js <ide> describe("$animator", function() { <ide> expect(element.hasClass('animation-cancelled')).toBe(true); <ide> })); <ide> <add> <add> it("should properly animate custom animation events", inject(function($animator, $rootScope) { <add> $animator.enabled(true); <add> animator = $animator($rootScope, { <add> ngAnimate : '{custom: \'setup-memo\'}' <add> }); <add> <add> element.text('123'); <add> animator.animate('custom',element); <add> window.setTimeout.expect(1).process(); <add> expect(element.text()).toBe('memento'); <add> })); <ide> }); <ide> <ide> describe("with CSS3", function() { <ide> describe("$animator", function() { <ide> }) <ide> }); <ide> <add> it("should properly animate custom animations for specific animation events", <add> inject(function($animator, $rootScope, $compile, $sniffer) { <add> <add> $animator.enabled(true); <add> var element = $compile(html('<div></div>'))($rootScope); <add> <add> animator = $animator($rootScope, { <add> ngAnimate : '{custom: \'special\'}' <add> }); <add> <add> animator.animate('custom',element); <add> if($sniffer.transitions) { <add> expect(element.hasClass('special')).toBe(true); <add> window.setTimeout.expect(1).process(); <add> expect(element.hasClass('special-active')).toBe(true); <add> } <add> else { <add> expect(window.setTimeout.queue.length).toBe(0); <add> } <add> })); <add> <add> it("should not animate custom animations if not specifically defined", <add> inject(function($animator, $rootScope, $compile) { <add> <add> $animator.enabled(true); <add> var element = $compile(html('<div></div>'))($rootScope); <add> <add> animator = $animator($rootScope, { <add> ngAnimate : '{custom: \'special\'}' <add> }); <add> <add> expect(window.setTimeout.queue.length).toBe(0); <add> animator.animate('custom1',element); <add> expect(element.hasClass('special')).toBe(false); <add> expect(window.setTimeout.queue.length).toBe(0); <add> })); <add> <add> it("should properly animate custom animations for general animation events", <add> inject(function($animator, $rootScope, $compile, $sniffer) { <add> <add> $animator.enabled(true); <add> var element = $compile(html('<div></div>'))($rootScope); <add> <add> animator = $animator($rootScope, { <add> ngAnimate : "'special'" <add> }); <add> <add> animator.animate('custom',element); <add> if($sniffer.transitions) { <add> expect(element.hasClass('special-custom')).toBe(true); <add> window.setTimeout.expect(1).process(); <add> expect(element.hasClass('special-custom-active')).toBe(true); <add> } <add> else { <add> expect(window.setTimeout.queue.length).toBe(0); <add> } <add> })); <add> <ide> describe("Animations", function() { <ide> it("should properly detect and make use of CSS Animations", <ide> inject(function($animator, $rootScope, $compile, $sniffer) {
2
Text
Text
add pronouns for tniessen to readme
54a85d6bb5f8bacec2842caa2172a4fa6864b234
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> * [targos](https://github.com/targos) - <ide> **Michaël Zasso** \<[email protected]> (he/him) <ide> * [tniessen](https://github.com/tniessen) - <del> **Tobias Nießen** \<[email protected]> <add> **Tobias Nießen** \<[email protected]> (he/him) <ide> * [Trott](https://github.com/Trott) - <ide> **Rich Trott** \<[email protected]> (he/him) <ide> <ide> For information about the governance of the Node.js project, see <ide> * [TimothyGu](https://github.com/TimothyGu) - <ide> **Tiancheng "Timothy" Gu** \<[email protected]> (he/him) <ide> * [tniessen](https://github.com/tniessen) - <del> **Tobias Nießen** \<[email protected]> <add> **Tobias Nießen** \<[email protected]> (he/him) <ide> * [trivikr](https://github.com/trivikr) - <ide> **Trivikram Kamat** \<[email protected]> <ide> * [Trott](https://github.com/Trott) -
1
Text
Text
add introductory links from docs in the readme
9b9cf10a98e6c97453f059ccfdf35ffc9874c951
<ide><path>README.md <ide> We have a variety of resources available to help you learn Redux, no matter what <ide> <ide> If you're brand new to Redux and want to understand the basic concepts, see: <ide> <add>- The **[Motivation](https://redux.js.org/introduction/motivation)** behind building Redux, the **[Core Concepts](https://redux.js.org/introduction/coreconcepts)**, and the **[Three Principles](https://redux.js.org/introduction/threeprinciples)**. <ide> - The **[basic tutorial in the Redux docs](https://redux.js.org/basics)** <ide> - Redux creator Dan Abramov's **free ["Getting Started with Redux" video series](https://egghead.io/series/getting-started-with-redux)** on Egghead.io <ide> - Redux co-maintainer Mark Erikson's **["Redux Fundamentals" slideshow](http://blog.isquaredsoftware.com/2018/03/presentation-reactathon-redux-fundamentals/)** and **[list of suggested resources for learning Redux](http://blog.isquaredsoftware.com/2017/12/blogged-answers-learn-redux/)**
1
Javascript
Javascript
remove obsolete domain test
a8526cb5a46df0cd8052ca1a13cab78e0e0c6a4b
<ide><path>test/parallel/test-microtask-queue-run-immediate-domain.js <del>// Copyright Joyent, Inc. and other Node contributors. <del>// <del>// Permission is hereby granted, free of charge, to any person obtaining a <del>// copy of this software and associated documentation files (the <del>// "Software"), to deal in the Software without restriction, including <del>// without limitation the rights to use, copy, modify, merge, publish, <del>// distribute, sublicense, and/or sell copies of the Software, and to permit <del>// persons to whom the Software is furnished to do so, subject to the <del>// following conditions: <del>// <del>// The above copyright notice and this permission notice shall be included <del>// in all copies or substantial portions of the Software. <del>// <del>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <del>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <del>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <del>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <del>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <del>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <del>// USE OR OTHER DEALINGS IN THE SOFTWARE. <del> <del>'use strict'; <del>require('../common'); <del>const assert = require('assert'); <del> <del>// Requiring the domain module here changes the function that is used by node to <del>// call process.nextTick's callbacks to a variant that specifically handles <del>// domains. We want to test this specific variant in this test, and so even if <del>// the domain module is not used, this require call is needed and must not be <del>// removed. <del>require('domain'); <del> <del>function enqueueMicrotask(fn) { <del> Promise.resolve().then(fn); <del>} <del> <del>let done = 0; <del> <del>process.on('exit', function() { <del> assert.strictEqual(done, 2); <del>}); <del> <del>// no nextTick, microtask <del>setImmediate(function() { <del> enqueueMicrotask(function() { <del> done++; <del> }); <del>}); <del> <del> <del>// no nextTick, microtask with nextTick <del>setImmediate(function() { <del> let called = false; <del> <del> enqueueMicrotask(function() { <del> process.nextTick(function() { <del> called = true; <del> }); <del> }); <del> <del> setImmediate(function() { <del> if (called) <del> done++; <del> }); <del> <del>});
1
Ruby
Ruby
remove redundant require of file
52720b46ead63ced84abb0a6efaf54cf72bee70e
<ide><path>activemodel/test/cases/validations/validates_test.rb <ide> require 'models/person' <ide> require 'models/topic' <ide> require 'models/person_with_validator' <del>require 'validators/email_validator' <ide> require 'validators/namespace/email_validator' <ide> <ide> class ValidatesTest < ActiveModel::TestCase
1
Javascript
Javascript
set the iteration state before linking
0c8a2cd2da3a4a9f5d2ee9c25ea8ed56d74a93ab
<ide><path>src/ng/directive/ngRepeat.js <ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { <ide> $animate.move(getBlockElements(block.clone), null, jqLite(previousNode)); <ide> } <ide> previousNode = getBlockEnd(block); <add> updateScope(block.scope, index); <ide> } else { <ide> // new item which we don't know about <ide> $transclude(function(clone, scope) { <ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { <ide> // by a directive with templateUrl when it's template arrives. <ide> block.clone = clone; <ide> nextBlockMap[block.id] = block; <add> updateScope(block.scope, index); <ide> }); <ide> } <del> updateScope(block.scope, index); <ide> } <ide> lastBlockMap = nextBlockMap; <ide> }); <ide><path>test/ng/directive/ngRepeatSpec.js <ide> describe('ngRepeat and transcludes', function() { <ide> }); <ide> }); <ide> <add> <add> it('should set the state before linking', function() { <add> module(function($compileProvider) { <add> $compileProvider.directive('assertA', valueFn(function(scope) { <add> // This linking function asserts that a is set. <add> // If we only test this by asserting binding, it will work even if the value is set later. <add> expect(scope.a).toBeDefined(); <add> })); <add> }); <add> inject(function($compile, $rootScope) { <add> var element = $compile('<div><span ng-repeat="a in [1]"><span assert-a></span></span></div>')($rootScope); <add> $rootScope.$digest(); <add> dealoc(element); <add> }); <add> }); <ide> }); <ide> <ide> describe('ngRepeat animations', function() {
2
Python
Python
add norm exception for ing verbs
288298ead9dc6631172173c92049525315859e85
<ide><path>spacy/lang/en/norm_exceptions.py <ide> "disorganised": "disorganized", <ide> "distil": "distill", <ide> "distils": "distills", <add> "doin": "doing", <add> "doin'": "doing", <ide> "dramatisation": "dramatization", <ide> "dramatisations": "dramatizations", <ide> "dramatise": "dramatize", <ide> "globalises": "globalizes", <ide> "globalising": "globalizing", <ide> "glueing ": "gluing ", <add> "goin": "going", <add> "goin'":"going", <ide> "goitre": "goiter", <ide> "goitres": "goiters", <ide> "gonorrhoea": "gonorrhea", <ide> "harmonised": "harmonized", <ide> "harmonises": "harmonizes", <ide> "harmonising": "harmonizing", <add> "havin": "having", <add> "havin'": "having", <ide> "homoeopath": "homeopath", <ide> "homoeopathic": "homeopathic", <ide> "homoeopaths": "homeopaths", <ide> "localised": "localized", <ide> "localises": "localizes", <ide> "localising": "localizing", <add> "lovin": "loving", <add> "lovin'": "loving", <ide> "louvre": "louver", <ide> "louvred": "louvered", <ide> "louvres": "louvers ",
1
Javascript
Javascript
add assert.deep[strict]equal benchmarks
5e4545e18f707e9ab28a50bd30f29b06320c8234
<ide><path>benchmark/assert/deepequal-buffer.js <add>'use strict'; <add>const common = require('../common.js'); <add>const assert = require('assert'); <add>const bench = common.createBenchmark(main, { <add> n: [1e3], <add> len: [1e2], <add> method: ['strict', 'nonstrict'] <add>}); <add> <add>function main(conf) { <add> const n = +conf.n; <add> const len = +conf.len; <add> var i; <add> <add> const data = Buffer.allocUnsafe(len); <add> const actual = Buffer.alloc(len); <add> const expected = Buffer.alloc(len); <add> data.copy(actual); <add> data.copy(expected); <add> <add> switch (conf.method) { <add> case 'strict': <add> bench.start(); <add> for (i = 0; i < n; ++i) { <add> // eslint-disable-next-line no-restricted-properties <add> assert.deepEqual(actual, expected); <add> } <add> bench.end(n); <add> break; <add> case 'nonstrict': <add> bench.start(); <add> for (i = 0; i < n; ++i) { <add> assert.deepStrictEqual(actual, expected); <add> } <add> bench.end(n); <add> break; <add> default: <add> throw new Error('Unsupported method'); <add> } <add>} <ide><path>benchmark/assert/deepequal-prims-and-objs-big-array.js <ide> 'use strict'; <del>var common = require('../common.js'); <del>var assert = require('assert'); <add>const common = require('../common.js'); <add>const assert = require('assert'); <ide> <ide> const primValues = { <ide> 'null': null, <ide> const primValues = { <ide> 'new-array': new Array([1, 2, 3]) <ide> }; <ide> <del>var bench = common.createBenchmark(main, { <add>const bench = common.createBenchmark(main, { <ide> prim: Object.keys(primValues), <del> n: [25] <add> n: [25], <add> len: [1e5], <add> method: ['strict', 'nonstrict'] <ide> }); <ide> <ide> function main(conf) { <del> var prim = primValues[conf.prim]; <del> var n = +conf.n; <del> var primArray; <del> var primArrayCompare; <del> var x; <add> const prim = primValues[conf.prim]; <add> const n = +conf.n; <add> const len = +conf.len; <add> const actual = []; <add> const expected = []; <add> var i; <ide> <del> primArray = new Array(); <del> primArrayCompare = new Array(); <del> for (x = 0; x < (1e5); x++) { <del> primArray.push(prim); <del> primArrayCompare.push(prim); <add> for (var x = 0; x < len; x++) { <add> actual.push(prim); <add> expected.push(prim); <ide> } <ide> <del> bench.start(); <del> for (x = 0; x < n; x++) { <del> // eslint-disable-next-line no-restricted-properties <del> assert.deepEqual(primArray, primArrayCompare); <add> switch (conf.method) { <add> case 'strict': <add> bench.start(); <add> for (i = 0; i < n; ++i) { <add> // eslint-disable-next-line no-restricted-properties <add> assert.deepEqual(actual, expected); <add> } <add> bench.end(n); <add> break; <add> case 'nonstrict': <add> bench.start(); <add> for (i = 0; i < n; ++i) { <add> assert.deepStrictEqual(actual, expected); <add> } <add> bench.end(n); <add> break; <add> default: <add> throw new Error('Unsupported method'); <ide> } <del> bench.end(n); <ide> } <ide><path>benchmark/assert/deepequal-prims-and-objs-big-loop.js <ide> 'use strict'; <del>var common = require('../common.js'); <del>var assert = require('assert'); <add>const common = require('../common.js'); <add>const assert = require('assert'); <ide> <ide> const primValues = { <ide> 'null': null, <ide> const primValues = { <ide> 'new-array': new Array([1, 2, 3]) <ide> }; <ide> <del>var bench = common.createBenchmark(main, { <add>const bench = common.createBenchmark(main, { <ide> prim: Object.keys(primValues), <del> n: [1e5] <add> n: [1e6], <add> method: ['strict', 'nonstrict'] <ide> }); <ide> <ide> function main(conf) { <del> var prim = primValues[conf.prim]; <del> var n = +conf.n; <del> var x; <add> const prim = primValues[conf.prim]; <add> const n = +conf.n; <add> const actual = prim; <add> const expected = prim; <add> var i; <ide> <del> bench.start(); <del> <del> for (x = 0; x < n; x++) { <del> // eslint-disable-next-line no-restricted-properties <del> assert.deepEqual(new Array([prim]), new Array([prim])); <add> // Creates new array to avoid loop invariant code motion <add> switch (conf.method) { <add> case 'strict': <add> bench.start(); <add> for (i = 0; i < n; ++i) { <add> // eslint-disable-next-line no-restricted-properties <add> assert.deepEqual([actual], [expected]); <add> } <add> bench.end(n); <add> break; <add> case 'nonstrict': <add> bench.start(); <add> for (i = 0; i < n; ++i) { <add> assert.deepStrictEqual([actual], [expected]); <add> } <add> bench.end(n); <add> break; <add> default: <add> throw new Error('Unsupported method'); <ide> } <del> <del> bench.end(n); <ide> } <ide><path>benchmark/assert/deepequal-typedarrays.js <ide> 'use strict'; <del>var common = require('../common.js'); <del>var assert = require('assert'); <del>var bench = common.createBenchmark(main, { <add>const common = require('../common.js'); <add>const assert = require('assert'); <add>const bench = common.createBenchmark(main, { <ide> type: ('Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array ' + <ide> 'Float32Array Float64Array Uint8ClampedArray').split(' '), <del> n: [1] <add> n: [1], <add> method: ['strict', 'nonstrict'], <add> len: [1e6] <ide> }); <ide> <ide> function main(conf) { <del> var type = conf.type; <del> var clazz = global[type]; <del> var n = +conf.n; <add> const type = conf.type; <add> const clazz = global[type]; <add> const n = +conf.n; <add> const len = +conf.len; <ide> <del> bench.start(); <del> var actual = new clazz(n * 1e6); <del> var expected = new clazz(n * 1e6); <add> const actual = new clazz(len); <add> const expected = new clazz(len); <add> var i; <ide> <del> // eslint-disable-next-line no-restricted-properties <del> assert.deepEqual(actual, expected); <del> <del> bench.end(n); <add> switch (conf.method) { <add> case 'strict': <add> bench.start(); <add> for (i = 0; i < n; ++i) { <add> // eslint-disable-next-line no-restricted-properties <add> assert.deepEqual(actual, expected); <add> } <add> bench.end(n); <add> break; <add> case 'nonstrict': <add> bench.start(); <add> for (i = 0; i < n; ++i) { <add> assert.deepStrictEqual(actual, expected); <add> } <add> bench.end(n); <add> break; <add> default: <add> throw new Error('Unsupported method'); <add> } <ide> }
4