content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
render responses when cast as string
338b74c1427d4786f041669b6085266f156153a2
<ide><path>laravel/response.php <ide> public function status($status = null) <ide> } <ide> } <ide> <add> /** <add> * Render the response when cast to string <add> * <add> * @return string <add> */ <add> public function __toString() <add> { <add> return $this->render(); <add> } <add> <ide> } <ide>\ No newline at end of file
1
Text
Text
avoid the phrase "key property"
6541903bc48f4c3c66181d660fab0034b555f938
<ide><path>docs/docs/04-multiple-components.md <ide> React.render( <ide> <ide> ## Ownership <ide> <del>In the above example, instances of `Avatar` *own* instances of `ProfilePic` and `ProfileLink`. In React, **an owner is the component that sets the `props` of other components**. More formally, if a component `X` is created in component `Y`'s `render()` method, it is said that `X` is *owned by* `Y`. As discussed earlier, a component cannot mutate its `props` — they are always consistent with what its owner sets them to. This key property leads to UIs that are guaranteed to be consistent. <add>In the above example, instances of `Avatar` *own* instances of `ProfilePic` and `ProfileLink`. In React, **an owner is the component that sets the `props` of other components**. More formally, if a component `X` is created in component `Y`'s `render()` method, it is said that `X` is *owned by* `Y`. As discussed earlier, a component cannot mutate its `props` — they are always consistent with what its owner sets them to. This fundamental invariant leads to UIs that are guaranteed to be consistent. <ide> <ide> It's important to draw a distinction between the owner-ownee relationship and the parent-child relationship. The owner-ownee relationship is specific to React, while the parent-child relationship is simply the one you know and love from the DOM. In the example above, `Avatar` owns the `div`, `ProfilePic` and `ProfileLink` instances, and `div` is the **parent** (but not owner) of the `ProfilePic` and `ProfileLink` instances. <ide>
1
Text
Text
remove testing block
ac225731d55a6cce8983fc696debee312822de14
<ide><path>README.md <ide> Check out our [documentation on the docs tab](https://github.com/github/atom/doc <ide> 1. `gh-setup atom` <ide> <ide> 2. `cd ~/github/atom && rake install` <del> <del>```coffeescript <del>-> 'hello' <del>```
1
Javascript
Javascript
add isabsoluteurl helper
20a25a278373d2e7c19e3fc5b204cee7e42c4218
<ide><path>lib/helpers/isAbsoluteURL.js <add>'use strict'; <add> <add>/** <add> * Determines whether the specified URL is absolute <add> * <add> * @param {string} url The URL to test <add> * @returns {boolean} True if the specified URL is absolute, otherwise false <add> */ <add>module.exports = function isAbsoluteURL(url) { <add> // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). <add> // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed <add> // by any combination of letters, digits, plus, period, or hyphen. <add> return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); <add>}; <ide><path>test/specs/helpers/isAbsoluteURL.spec.js <add>var isAbsoluteURL = require('../../../lib/helpers/isAbsoluteURL'); <add> <add>describe('helpers::isAbsoluteURL', function () { <add> it('should return true if URL begins with valid scheme name', function () { <add> expect(isAbsoluteURL('https://api.github.com/users')).toBe(true); <add> expect(isAbsoluteURL('custom-scheme-v1.0://example.com/')).toBe(true); <add> expect(isAbsoluteURL('HTTP://example.com/')).toBe(true); <add> }); <add> <add> it('should return false if URL begins with invalid scheme name', function () { <add> expect(isAbsoluteURL('123://example.com/')).toBe(false); <add> expect(isAbsoluteURL('!valid://example.com/')).toBe(false); <add> }); <add> <add> it('should return true if URL is protocol-relative', function () { <add> expect(isAbsoluteURL('//example.com/')).toBe(true); <add> }); <add> <add> it('should return false if URL is relative', function () { <add> expect(isAbsoluteURL('/foo')).toBe(false); <add> expect(isAbsoluteURL('foo')).toBe(false); <add> }); <add>});
2
Javascript
Javascript
remove extend() and tests
1299daf16c27609b0ec7be2efe9a8fe97e75f6c4
<ide><path>src/js/extend.js <del>/** <del> * @file extend.js <del> * @module extend <del> */ <del> <del>import _inherits from '@babel/runtime/helpers/inherits'; <del>import log from './utils/log'; <del> <del>/** <del> * Used to subclass an existing class by emulating ES subclassing using the <del> * `extends` keyword. <del> * <del> * @function <del> * @deprecated <del> * @example <del> * var MyComponent = videojs.extend(videojs.getComponent('Component'), { <del> * myCustomMethod: function() { <del> * // Do things in my method. <del> * } <del> * }); <del> * <del> * @param {Function} superClass <del> * The class to inherit from <del> * <del> * @param {Object} [subClassMethods={}] <del> * Methods of the new class <del> * <del> * @return {Function} <del> * The new class with subClassMethods that inherited superClass. <del> * <del> * @deprecated videojs.extend() is deprecated as of v8; use native ES6 classes instead <del> */ <del>const extend = function(superClass, subClassMethods = {}) { <del> log.warn('The extend() method is deprecated. Please use native ES6 classes instead.'); <del> <del> const isNativeClass = superClass && /^class/.test(superClass.toString()); <del> <del> let subClass = function() { <del> superClass.apply(this, arguments); <del> }; <del> <del> // If the provided super class is a native ES6 class, <del> // make the sub class one as well. <del> if (isNativeClass) { <del> subClass = class SubClass extends superClass {}; <del> } <del> <del> let methods = {}; <del> <del> if (typeof subClassMethods === 'object') { <del> if (subClassMethods.constructor !== Object.prototype.constructor) { <del> subClass = subClassMethods.constructor; <del> } <del> methods = subClassMethods; <del> } else if (typeof subClassMethods === 'function') { <del> subClass = subClassMethods; <del> } <del> <del> if (!isNativeClass) { <del> _inherits(subClass, superClass); <del> } <del> <del> // this is needed for backward-compatibility and node compatibility. <del> if (superClass) { <del> subClass.super_ = superClass; <del> } <del> <del> // Extend subObj's prototype with functions and other properties from props <del> for (const name in methods) { <del> if (methods.hasOwnProperty(name)) { <del> subClass.prototype[name] = methods[name]; <del> } <del> } <del> <del> return subClass; <del>}; <del> <del>export default extend; <ide><path>src/js/video.js <ide> import * as Dom from './utils/dom.js'; <ide> import * as browser from './utils/browser.js'; <ide> import * as Url from './utils/url.js'; <ide> import * as Obj from './utils/obj'; <del>import extend from './extend.js'; <ide> import xhr from '@videojs/xhr'; <ide> <ide> // Include the built-in techs <ide> videojs.browser = browser; <ide> */ <ide> videojs.obj = Obj; <ide> <del>/** <del> * Deprecated reference to the {@link module:extend~extend|extend function} <del> * <del> * @type {Function} <del> * @see {@link module:extend~extend|extend} <del> * @deprecated Deprecated and will be removed in 9.0. Please use native ES6 classes instead. <del> */ <del>videojs.extend = deprecateForMajor(9, 'videojs.extend', 'native ES6 classes', extend); <del> <ide> /** <ide> * Deprecated reference to the {@link module:obj.merge|merge function} <ide> * <ide><path>test/unit/extend.test.js <del>/* eslint-env qunit */ <del>import extend from '../../src/js/extend.js'; <del> <del>QUnit.module('extend.js'); <del> <del>QUnit.test('should add implicit parent constructor call', function(assert) { <del> assert.expect(4); <del> <del> let superCalled = false; <del> <del> [ <del> function() { <del> superCalled = true; <del> }, <del> class Parent { <del> constructor() { <del> superCalled = true; <del> } <del> } <del> ].forEach(Parent => { <del> const Child = extend(Parent, { <del> foo: 'bar' <del> }); <del> const child = new Child(); <del> <del> assert.ok(superCalled, 'super constructor called'); <del> assert.ok(child.foo, 'child properties set'); <del> <del> superCalled = false; <del> }); <del>}); <del> <del>QUnit.test('should have a super_ pointer', function(assert) { <del> assert.expect(4); <del> <del> [function() {}, class Parent {}].forEach(Parent => { <del> const Child = extend(Parent, { <del> foo: 'bar' <del> }); <del> const child = new Child(); <del> <del> assert.ok(child.foo, 'child properties set'); <del> assert.equal(child.constructor.super_, Parent, 'super_ is present and equal to the super class'); <del> }); <del>}); <del> <del>QUnit.test('sub class is an ES6 class if the super class is', function(assert) { <del> class Parent {} <del> <del> const Child = extend(Parent, { <del> foo: 'bar' <del> }); <del> <del> assert.ok(/^class/.test(Child.toString()), 'sub class is native es6 class'); <del>});
3
Text
Text
add a paragraph break
4d89910820e4c0fb62e1e496e5df837b77514f27
<ide><path>docs/reference/run.md <ide> volume mounted on the host). <ide> <ide> The default user within a container is `root` (id = 0), but if the developer <ide> created additional users, those are accessible by name. When passing a numeric <del>ID, the user doesn't have to exist in the container. The developer can set a <del>default user to run the first process with the Dockerfile `USER` instruction, <del>but the operator can override it: <add>ID, the user doesn't have to exist in the container. <add> <add>The developer can set a default user to run the first process with the <add>Dockerfile `USER` instruction, but the operator can override it: <ide> <ide> -u="": Username or UID <ide>
1
Javascript
Javascript
move packager initialization events to reporter
b80e2c8799cc2ef76c77752bbf00be849b0be6b1
<ide><path>local-cli/server/runServer.js <ide> const systraceProfileMiddleware = require('./middleware/systraceProfileMiddlewar <ide> const unless = require('./middleware/unless'); <ide> const webSocketProxy = require('./util/webSocketProxy.js'); <ide> <del>function runServer(args, config, readyCallback) { <add>function runServer(args, config, startedCallback, readyCallback) { <ide> var wsProxy = null; <ide> var ms = null; <ide> const packagerServer = getPackagerServer(args, config); <add> startedCallback(packagerServer._reporter); <add> <ide> const inspectorProxy = new InspectorProxy(); <ide> const app = connect() <ide> .use(loadRawBodyMiddleware) <ide> function runServer(args, config, readyCallback) { <ide> wsProxy = webSocketProxy.attachToServer(serverInstance, '/debugger-proxy'); <ide> ms = messageSocket.attachToServer(serverInstance, '/message'); <ide> inspectorProxy.attachToServer(serverInstance, '/inspector'); <del> readyCallback(); <add> readyCallback(packagerServer._reporter); <ide> } <ide> ); <ide> // Disable any kind of automatic timeout behavior for incoming <ide><path>local-cli/server/server.js <ide> */ <ide> 'use strict'; <ide> <del>const chalk = require('chalk'); <del>const formatBanner = require('./formatBanner'); <ide> const path = require('path'); <ide> const runServer = require('./runServer'); <ide> <ide> const runServer = require('./runServer'); <ide> function server(argv, config, args) { <ide> args.projectRoots = args.projectRoots.concat(args.root); <ide> <del> console.log(formatBanner( <del> 'Running packager on port ' + args.port + '.\n\n' + <del> 'Keep this packager running while developing on any JS projects. ' + <del> 'Feel free to close this tab and run your own packager instance if you ' + <del> 'prefer.\n\n' + <del> 'https://github.com/facebook/react-native', { <del> marginLeft: 1, <del> marginRight: 1, <del> paddingBottom: 1, <del> }) <del> ); <add> const startedCallback = logReporter => { <add> logReporter.update({ <add> type: 'initialize_packager_started', <add> port: args.port, <add> projectRoots: args.projectRoots, <add> }); <ide> <del> console.log( <del> 'Looking for JS files in\n ', <del> chalk.dim(args.projectRoots.join('\n ')), <del> '\n' <del> ); <add> process.on('uncaughtException', error => { <add> logReporter.update({ <add> type: 'initialize_packager_failed', <add> port: args.port, <add> error, <add> }); <ide> <del> process.on('uncaughtException', error => { <del> if (error.code === 'EADDRINUSE') { <del> console.log( <del> chalk.bgRed.bold(' ERROR '), <del> chalk.red('Packager can\'t listen on port', chalk.bold(args.port)) <del> ); <del> console.log('Most likely another process is already using this port'); <del> console.log('Run the following command to find out which process:'); <del> console.log('\n ', chalk.bold('lsof -i :' + args.port), '\n'); <del> console.log('Then, you can either shut down the other process:'); <del> console.log('\n ', chalk.bold('kill -9 <PID>'), '\n'); <del> console.log('or run packager on different port.'); <del> } else { <del> console.log(chalk.bgRed.bold(' ERROR '), chalk.red(error.message)); <del> const errorAttributes = JSON.stringify(error); <del> if (errorAttributes !== '{}') { <del> console.error(chalk.red(errorAttributes)); <del> } <del> console.error(chalk.red(error.stack)); <del> } <del> console.log('\nSee', chalk.underline('http://facebook.github.io/react-native/docs/troubleshooting.html')); <del> console.log('for common problems and solutions.'); <del> process.exit(11); <del> }); <add> process.exit(11); <add> }); <add> }; <add> <add> const readyCallback = logReporter => { <add> logReporter.update({ <add> type: 'initialize_packager_done', <add> }); <add> }; <ide> <del> runServer(args, config, () => console.log('\nReact packager ready.\n')); <add> runServer(args, config, startedCallback, readyCallback); <ide> } <ide> <ide> module.exports = { <ide><path>packager/src/lib/TerminalReporter.js <ide> <ide> 'use strict'; <ide> <add>const chalk = require('chalk'); <ide> const path = require('path'); <ide> const reporting = require('./reporting'); <ide> const terminal = require('./terminal'); <ide> const throttle = require('lodash/throttle'); <ide> const util = require('util'); <add>const formatBanner = require('../../../local-cli/server/formatBanner'); <ide> <ide> import type {ReportableEvent, GlobalCacheDisabledReason} from './reporting'; <ide> <ide> class TerminalReporter { <ide> } <ide> } <ide> <add> <add> _logPackagerInitializing(port: number, projectRoots: Array<string>) { <add> terminal.log( <add> formatBanner( <add> 'Running packager on port ' + <add> port + <add> '.\n\n' + <add> 'Keep this packager running while developing on any JS projects. ' + <add> 'Feel free to close this tab and run your own packager instance if you ' + <add> 'prefer.\n\n' + <add> 'https://github.com/facebook/react-native', <add> { <add> marginLeft: 1, <add> marginRight: 1, <add> paddingBottom: 1, <add> } <add> ) <add> ); <add> <add> terminal.log( <add> 'Looking for JS files in\n ', <add> chalk.dim(projectRoots.join('\n ')), <add> '\n' <add> ); <add> } <add> <add> _logPackagerInitializingFailed(port: number, error: Error) { <add> if (error.code === 'EADDRINUSE') { <add> terminal.log( <add> chalk.bgRed.bold(' ERROR '), <add> chalk.red("Packager can't listen on port", chalk.bold(port)) <add> ); <add> terminal.log('Most likely another process is already using this port'); <add> terminal.log('Run the following command to find out which process:'); <add> terminal.log('\n ', chalk.bold('lsof -i :' + port), '\n'); <add> terminal.log('Then, you can either shut down the other process:'); <add> terminal.log('\n ', chalk.bold('kill -9 <PID>'), '\n'); <add> terminal.log('or run packager on different port.'); <add> } else { <add> terminal.log(chalk.bgRed.bold(' ERROR '), chalk.red(error.message)); <add> const errorAttributes = JSON.stringify(error); <add> if (errorAttributes !== '{}') { <add> terminal.log(chalk.red(errorAttributes)); <add> } <add> terminal.log(chalk.red(error.stack)); <add> } <add> } <add> <add> <ide> /** <ide> * This function is only concerned with logging and should not do state <ide> * or terminal status updates. <ide> */ <ide> _log(event: TerminalReportableEvent): void { <ide> switch (event.type) { <add> case 'initialize_packager_started': <add> this._logPackagerInitializing(event.port, event.projectRoots); <add> break; <add> case 'initialize_packager_done': <add> terminal.log('\nReact packager ready.\n'); <add> break; <add> case 'initialize_packager_failed': <add> this._logPackagerInitializingFailed(event.port, event.error); <add> break; <ide> case 'bundle_build_done': <ide> this._logBundleBuildDone(event.entryFilePath); <ide> break; <ide><path>packager/src/lib/reporting.js <ide> export type GlobalCacheDisabledReason = 'too_many_errors' | 'too_many_misses'; <ide> * report to the tool user. <ide> */ <ide> export type ReportableEvent = { <add> port: number, <add> projectRoots: Array<string>, <add> type: 'initialize_packager_started', <add>} | { <add> type: 'initialize_packager_done', <add>} | { <add> type: 'initialize_packager_failed', <add> port: number, <add> error: Error, <add>} | { <ide> entryFilePath: string, <ide> type: 'bundle_build_done', <ide> } | {
4
Python
Python
increase range in float16 almost equal nulp test
5f84b380f3708e94196582e427356cc38d76b977
<ide><path>numpy/testing/tests/test_utils.py <ide> def test_float32_fail(self): <ide> <ide> def test_float16_pass(self): <ide> nulp = 5 <del> x = np.linspace(-20, 20, 50, dtype=np.float16) <add> x = np.linspace(-4, 4, 10, dtype=np.float16) <add> x = 10**x <ide> x = np.r_[-x, x] <ide> <ide> eps = np.finfo(x.dtype).eps <ide> def test_float16_pass(self): <ide> <ide> def test_float16_fail(self): <ide> nulp = 5 <del> x = np.linspace(-20, 20, 50, dtype=np.float16) <add> x = np.linspace(-4, 4, 10, dtype=np.float16) <add> x = 10**x <ide> x = np.r_[-x, x] <ide> <ide> eps = np.finfo(x.dtype).eps
1
Ruby
Ruby
supply additional data for requirements
5277f849d9dc30c8beac490fe163f3cb7ac7dba1
<ide><path>Library/Homebrew/formula.rb <ide> def to_hash <ide> end <ide> <ide> hsh["requirements"] = requirements.map do |req| <add> req.name.prepend("maximum_") if req.try(:comparator) == "<=" <ide> { <ide> "name" => req.name, <ide> "cask" => req.cask, <ide> "download" => req.download, <add> "version" => req.try(:version), <add> "contexts" => req.tags, <ide> } <ide> end <ide> <ide><path>Library/Homebrew/requirements/java_requirement.rb <ide> require "language/java" <ide> <ide> class JavaRequirement < Requirement <del> attr_reader :java_home <del> <ide> fatal true <ide> <add> attr_reader :java_home, :version <add> <ide> # A strict Java 8 requirement (1.8) should prompt the user to install <ide> # an OpenJDK 1.8 distribution. Versions newer than Java 8 are not <ide> # completely backwards compatible, and contain breaking changes such as <ide><path>Library/Homebrew/requirements/macos_requirement.rb <ide> class MacOSRequirement < Requirement <ide> fatal true <ide> <add> attr_reader :comparator, :version <add> <ide> def initialize(tags = [], comparator: ">=") <ide> if comparator == "==" && tags.first.respond_to?(:map) <ide> @version = tags.shift.map { |s| MacOS::Version.from_symbol(s) } <ide> def message(type: :formula) <ide> end <ide> end <ide> <add> def inspect <add> "#<#{self.class.name}: #{tags.inspect} version#{@comparator}#{@version}>" <add> end <add> <ide> def display_s <ide> return "macOS is required" unless version_specified? <ide> <ide><path>Library/Homebrew/requirements/xcode_requirement.rb <ide> class XcodeRequirement < Requirement <ide> fatal true <ide> <add> attr_reader :version <add> <ide> satisfy(build_env: false) { xcode_installed_version } <ide> <ide> def initialize(tags = [])
4
Javascript
Javascript
update watchmode tests
5e112dbfbe043b9f7a43798b3ef1522155e7317f
<ide><path>test/Compiler.test.js <ide> describe("Compiler", () => { <ide> }); <ide> <ide> compiler.outputFileSystem = new MemoryFs(); <del> compiler.watch({}, err => { <add> <add> const watch = compiler.watch({}, err => { <ide> if (err) return done(err); <ide> expect(compiler.watchMode).toBeTruthy(); <del> done(); <add> watch.close(() => { <add> expect(compiler.watchMode).toBeFalsy(); <add> done(); <add> }); <ide> }); <ide> }); <ide> it("should use cache on second run call", function(done) {
1
Javascript
Javascript
increase coverage of buffer
04796ee97f594186c6aed9ecfeae4cf61dca544d
<ide><path>test/parallel/test-buffer-bytelength.js <ide> assert.throws(() => { Buffer.byteLength({}, 'latin1'); }, <ide> assert.throws(() => { Buffer.byteLength(); }, <ide> /"string" must be a string, Buffer, or ArrayBuffer/); <ide> <add>assert.strictEqual(Buffer.byteLength('', undefined, true), -1); <add> <ide> assert(ArrayBuffer.isView(new Buffer(10))); <ide> assert(ArrayBuffer.isView(new SlowBuffer(10))); <ide> assert(ArrayBuffer.isView(Buffer.alloc(10))); <ide> assert.strictEqual(Buffer.byteLength('ßœ∑≈', 'unkn0wn enc0ding'), 10); <ide> <ide> // base64 <ide> assert.strictEqual(Buffer.byteLength('aGVsbG8gd29ybGQ=', 'base64'), 11); <add>assert.strictEqual(Buffer.byteLength('aGVsbG8gd29ybGQ=', 'BASE64'), 11); <ide> assert.strictEqual(Buffer.byteLength('bm9kZS5qcyByb2NrcyE=', 'base64'), 14); <ide> assert.strictEqual(Buffer.byteLength('aGkk', 'base64'), 3); <ide> assert.strictEqual( <ide> assert.strictEqual(Buffer.byteLength('aaaa==', 'base64'), 3); <ide> <ide> assert.strictEqual(Buffer.byteLength('Il était tué'), 14); <ide> assert.strictEqual(Buffer.byteLength('Il était tué', 'utf8'), 14); <del>assert.strictEqual(Buffer.byteLength('Il était tué', 'ascii'), 12); <del>assert.strictEqual(Buffer.byteLength('Il était tué', 'latin1'), 12); <del>assert.strictEqual(Buffer.byteLength('Il était tué', 'binary'), 12); <del>['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { <del> assert.strictEqual(24, Buffer.byteLength('Il était tué', encoding)); <del>}); <add> <add>['ascii', 'latin1', 'binary'] <add> .reduce((es, e) => es.concat(e, e.toUpperCase()), []) <add> .forEach((encoding) => { <add> assert.strictEqual(Buffer.byteLength('Il était tué', encoding), 12); <add> }); <add> <add>['ucs2', 'ucs-2', 'utf16le', 'utf-16le'] <add> .reduce((es, e) => es.concat(e, e.toUpperCase()), []) <add> .forEach((encoding) => { <add> assert.strictEqual(Buffer.byteLength('Il était tué', encoding), 24); <add> }); <ide> <ide> // Test that ArrayBuffer from a different context is detected correctly <ide> const arrayBuf = vm.runInNewContext('new ArrayBuffer()'); <ide><path>test/parallel/test-buffer-tostring.js <add>'use strict'; <add> <add>require('../common'); <add>const assert = require('assert'); <add> <add>// utf8, ucs2, ascii, latin1, utf16le <add>const encodings = ['utf8', 'ucs2', 'ucs-2', 'ascii', 'latin1', 'binary', <add> 'utf16le', 'utf-16le']; <add> <add>encodings <add> .reduce((es, e) => es.concat(e, e.toUpperCase()), []) <add> .forEach((encoding) => { <add> assert.strictEqual(Buffer.from('foo', encoding).toString(encoding), 'foo'); <add> }); <add> <add>// base64 <add>['base64', 'BASE64'].forEach((encoding) => { <add> assert.strictEqual(Buffer.from('Zm9v', encoding).toString(encoding), 'Zm9v'); <add>}); <add> <add>// hex <add>['hex', 'HEX'].forEach((encoding) => { <add> assert.strictEqual(Buffer.from('666f6f', encoding).toString(encoding), <add> '666f6f'); <add>}); <ide><path>test/parallel/test-buffer-write.js <add>'use strict'; <add> <add>require('../common'); <add>const assert = require('assert'); <add> <add>const outsideBounds = /^RangeError: Attempt to write outside buffer bounds$/; <add> <add>assert.throws(() => Buffer.alloc(9).write('foo', -1), outsideBounds); <add>assert.throws(() => Buffer.alloc(9).write('foo', 10), outsideBounds); <add> <add>const resultMap = new Map([ <add> ['utf8', Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])], <add> ['ucs2', Buffer.from([102, 0, 111, 0, 111, 0, 0, 0, 0])], <add> ['ascii', Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])], <add> ['latin1', Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])], <add> ['binary', Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])], <add> ['utf16le', Buffer.from([102, 0, 111, 0, 111, 0, 0, 0, 0])], <add> ['base64', Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])], <add> ['hex', Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])] <add>]); <add> <add>// utf8, ucs2, ascii, latin1, utf16le <add>const encodings = ['utf8', 'utf-8', 'ucs2', 'ucs-2', 'ascii', 'latin1', <add> 'binary', 'utf16le', 'utf-16le']; <add> <add>encodings <add> .reduce((es, e) => es.concat(e, e.toUpperCase()), []) <add> .forEach((encoding) => { <add> const buf = Buffer.alloc(9); <add> const len = Buffer.byteLength('foo', encoding); <add> assert.strictEqual(buf.write('foo', 0, len, encoding), len); <add> <add> if (encoding.indexOf('-') !== -1) <add> encoding = encoding.replace('-', ''); <add> <add> assert.deepStrictEqual(buf, resultMap.get(encoding.toLowerCase())); <add> }); <add> <add>// base64 <add>['base64', 'BASE64'].forEach((encoding) => { <add> const buf = Buffer.alloc(9); <add> const len = Buffer.byteLength('Zm9v', encoding); <add> <add> assert.strictEqual(buf.write('Zm9v', 0, len, encoding), len); <add> assert.deepStrictEqual(buf, resultMap.get(encoding.toLowerCase())); <add>}); <add> <add>// hex <add>['hex', 'HEX'].forEach((encoding) => { <add> const buf = Buffer.alloc(9); <add> const len = Buffer.byteLength('666f6f', encoding); <add> <add> assert.strictEqual(buf.write('666f6f', 0, len, encoding), len); <add> assert.deepStrictEqual(buf, resultMap.get(encoding.toLowerCase())); <add>});
3
Javascript
Javascript
fix code generation for indexed ram bundles
f91e376515e820ae378e16dc9602a8c4d573a66e
<ide><path>packager/src/ModuleGraph/output/__tests__/indexed-ram-bundle-test.js <ide> declare var jest: any; <ide> jest.disableAutomock(); <ide> <ide> const indexedRamBundle = require('../indexed-ram-bundle'); <add>const {addModuleIdsToModuleWrapper} = require('../util'); <ide> <ide> declare var describe: any; <ide> declare var expect: any; <ide> it('contains the code after the offset table', () => { <ide> table.forEach(([offset, length], i) => { <ide> const moduleCode = <ide> code.slice(codeOffset + offset, codeOffset + offset + length - 1); <del> expect(moduleCode.toString()).toBe(modules[i].file.code); <add> expect(moduleCode.toString()).toBe(expectedCode(modules[i])); <ide> }); <ide> }); <ide> <ide> describe('Startup section optimization', () => { <ide> const startupSection = <ide> code.slice(codeOffset, codeOffset + startupSectionLength - 1); <ide> expect(startupSection.toString()) <del> .toBe(preloaded.concat([requireCall]).map(getCode).join('\n')); <add> .toBe(preloaded.concat([requireCall]).map(expectedCode).join('\n')); <ide> <ide> <ide> preloaded.forEach(m => { <ide> describe('Startup section optimization', () => { <ide> if (offset !== 0 && length !== 0) { <ide> const moduleCode = <ide> code.slice(codeOffset + offset, codeOffset + offset + length - 1); <del> expect(moduleCode.toString()).toBe(modules[i].file.code); <add> expect(moduleCode.toString()).toBe(expectedCode(modules[i])); <ide> } <ide> }); <ide> }); <ide> describe('RAM groups / common sections', () => { <ide> const [offset, length] = groupEntry; <ide> const groupCode = code.slice(codeOffset + offset, codeOffset + offset + length - 1); <ide> expect(groupCode.toString()) <del> .toEqual(group.map(m => m.file.code).join('\n')); <add> .toEqual(group.map(expectedCode).join('\n')); <ide> }); <ide> }); <ide> <ide> function makeDependency(name) { <ide> }; <ide> } <ide> <add>function expectedCode(module) { <add> const {file} = module; <add> return file.type === 'module' <add> ? addModuleIdsToModuleWrapper(module, idForPath) <add> : file.code; <add>} <add> <ide> function getId(path) { <ide> if (path === requireCall.file.path) { <ide> return -1; <ide> function getId(path) { <ide> return id; <ide> } <ide> <del>function getCode(module) { <del> return module.file.code; <del>} <del> <ide> function getPath(module) { <ide> return module.file.path; <ide> } <ide><path>packager/src/ModuleGraph/output/indexed-ram-bundle.js <ide> const nullthrows = require('fbjs/lib/nullthrows'); <ide> <ide> const {createRamBundleGroups} = require('../../Bundler/util'); <ide> const {buildTableAndContents, createModuleGroups} = require('../../shared/output/unbundle/as-indexed-file'); <del>const {concat} = require('./util'); <add>const {addModuleIdsToModuleWrapper, concat} = require('./util'); <ide> <ide> import type {FBIndexMap} from '../../lib/SourceMap.js'; <ide> import type {OutputFn} from '../types.flow'; <ide> function asIndexedRamBundle({ <ide> const moduleGroups = createModuleGroups(ramGroups, deferredModules); <ide> <ide> const tableAndContents = buildTableAndContents( <del> startupModules.map(getModuleCode).join('\n'), <add> startupModules.map(m => getModuleCode(m, idForPath)).join('\n'), <ide> deferredModules, <ide> moduleGroups, <ide> 'utf8', <ide> function asIndexedRamBundle({ <ide> }; <ide> } <ide> <del>function toModuleTransport({dependencies, file}, idForPath) { <add>function toModuleTransport(module, idForPath) { <add> const {dependencies, file} = module; <ide> return { <del> code: file.code, <add> code: getModuleCode(module, idForPath), <ide> dependencies, <ide> id: idForPath(file), <ide> map: file.map, <ide> function toModuleTransport({dependencies, file}, idForPath) { <ide> }; <ide> } <ide> <del>function getModuleCode(module) { <del> return module.file.code; <add>function getModuleCode(module, idForPath) { <add> const {file} = module; <add> return file.type === 'module' <add> ? addModuleIdsToModuleWrapper(module, idForPath) <add> : file.code; <ide> } <ide> <ide> function partition(modules, preloadedModules) {
2
Ruby
Ruby
write tests using cask as argument
049528132582a5587f353a8a015a8f918ecdab44
<ide><path>Library/Homebrew/cmd/--cache.rb <ide> def __cache <ide> puts HOMEBREW_CACHE <ide> else <ide> args.named.each do |name| <add> formula = Formulary.factory name <add> if Fetch.fetch_bottle?(formula) <add> puts formula.bottle.cached_download <add> else <add> puts formula.cached_download <add> end <add> rescue FormulaUnavailableError <ide> begin <del> formula = Formulary.factory name <del> if Fetch.fetch_bottle?(formula) <del> puts formula.bottle.cached_download <del> else <del> puts formula.cached_download <del> end <del> rescue FormulaUnavailableError => e <del> begin <del> cask = Cask::CaskLoader.load name <del> puts "cask: #{Cask::Cmd::Cache.cached_location(cask)}" <del> rescue Cask::CaskUnavailableError <del> ofail "No available formula or cask with the name \"#{name}\"" <del> end <add> cask = Cask::CaskLoader.load name <add> puts "cask: #{Cask::Cmd::Cache.cached_location(cask)}" <add> rescue Cask::CaskUnavailableError <add> ofail "No available formula or cask with the name \"#{name}\"" <ide> end <ide> end <ide> end <ide> end <del> <ide> end <ide><path>Library/Homebrew/cmd/home.rb <ide> def home <ide> if args.no_named? <ide> exec_browser HOMEBREW_WWW <ide> else <del> homepages = args.named.flat_map do |name| <add> homepages = args.named.flat_map do |ref| <add> [Formulary.factory(ref).homepage] <add> rescue FormulaUnavailableError => e <add> puts e.message <ide> begin <del> [Formulary.factory(name).homepage] <del> rescue FormulaUnavailableError => e <add> cask = Cask::CaskLoader.load(ref) <add> puts "Found a cask with ref \"#{ref}\" instead." <add> [cask.homepage] <add> rescue Cask::CaskUnavailableError => e <ide> puts e.message <del> begin <del> cask = Cask::CaskLoader.load(name) <del> puts "Found a cask named \"#{name}\" instead." <del> [cask.homepage] <del> rescue Cask::CaskUnavailableError <del> [] <del> end <add> [] <ide> end <ide> end <del> exec_browser *homepages <add> exec_browser(*homepages) unless homepages.empty? <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/test/cmd/home_spec.rb <ide> # frozen_string_literal: true <ide> <ide> require "cmd/shared_examples/args_parse" <add>require "support/lib/config" <ide> <ide> describe "Homebrew.home_args" do <ide> it_behaves_like "parseable arguments" <ide> end <ide> <ide> describe "brew home", :integration_test do <add> let(:testballhome_homepage) { <add> Formula["testballhome"].homepage <add> } <add> <add> let(:local_caffeine_homepage) { <add> Cask::CaskLoader.load(cask_path("local-caffeine")).homepage <add> } <add> <ide> it "opens the homepage for a given Formula" do <ide> setup_test_formula "testballhome" <ide> <ide> expect { brew "home", "testballhome", "HOMEBREW_BROWSER" => "echo" } <del> .to output("#{Formula["testballhome"].homepage}\n").to_stdout <add> .to output("#{testballhome_homepage}\n").to_stdout <add> .and not_to_output.to_stderr <add> .and be_a_success <add> end <add> <add> it "opens the homepage for a given Cask" do <add> expect { brew "home", cask_path("local-caffeine"), "HOMEBREW_BROWSER" => "echo" } <add> .to output(/Found a cask with ref ".*" instead.\n#{local_caffeine_homepage}/m).to_stdout <add> .and not_to_output.to_stderr <add> .and be_a_success <add> end <add> <add> it "opens the homepages for a given formula and Cask" do <add> setup_test_formula "testballhome" <add> <add> expect { brew "home", "testballhome", cask_path("local-caffeine"), "HOMEBREW_BROWSER" => "echo" } <add> .to output(/Found a cask with ref ".*" instead.\n#{testballhome_homepage} #{local_caffeine_homepage}/m) <add> .to_stdout <ide> .and not_to_output.to_stderr <ide> .and be_a_success <ide> end
3
Text
Text
add djoser to authentication docs
113a28ed8ad65d912180e8be7a92b679251b0249
<ide><path>docs/api-guide/authentication.md <ide> The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let y <ide> <ide> HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] package which provides an easy to use HTTP Signature Authentication mechanism. <ide> <add>## Djoser <add> <add>[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system. <add> <ide> [cite]: http://jacobian.org/writing/rest-worst-practices/ <ide> [http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2 <ide> [http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4 <ide> HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a <ide> [hawk]: https://github.com/hueniverse/hawk <ide> [mohawk]: http://mohawk.readthedocs.org/en/latest/ <ide> [mac]: http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05 <add>[djoser]: https://github.com/sunscrapers/djoser
1
Python
Python
add checkpoint arg to export_inference_graph
599c26f5ecde037763cc6f9d29127489316f44c3
<ide><path>official/vision/serving/export_saved_model_lib.py <ide> def export_inference_graph( <ide> export_checkpoint_subdir: Optional[str] = None, <ide> export_saved_model_subdir: Optional[str] = None, <ide> save_options: Optional[tf.saved_model.SaveOptions] = None, <del> log_model_flops_and_params: bool = False): <add> log_model_flops_and_params: bool = False, <add> checkpoint: Optional[tf.train.Checkpoint] = None): <ide> """Exports inference graph for the model specified in the exp config. <ide> <ide> Saved model is stored at export_dir/saved_model, checkpoint is saved <ide> def export_inference_graph( <ide> save_options: `SaveOptions` for `tf.saved_model.save`. <ide> log_model_flops_and_params: If True, writes model FLOPs to model_flops.txt <ide> and model parameters to model_params.txt. <add> checkpoint: An optional tf.train.Checkpoint. If provided, the export module <add> will use it to read the weights. <ide> """ <ide> <ide> if export_checkpoint_subdir: <ide> def export_inference_graph( <ide> export_module, <ide> function_keys=[input_type], <ide> export_savedmodel_dir=output_saved_model_directory, <add> checkpoint=checkpoint, <ide> checkpoint_path=checkpoint_path, <ide> timestamped=False, <ide> save_options=save_options)
1
Python
Python
set version to 2.1.0a6
5a4737df0993af42550faa14be732dce8425561d
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy-nightly" <del>__version__ = "2.1.0a6.dev1" <add>__version__ = "2.1.0a6" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI" <ide> __email__ = "contact@explosion.ai" <ide> __license__ = "MIT" <del>__release__ = False <add>__release__ = True <ide> <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Text
Text
clarify setservers() methods in dns.md
95205a61251aca0af3f1c8663caaffb03a5f5c3a
<ide><path>doc/api/dns.md <ide> An error will be thrown if an invalid address is provided. <ide> The `dns.setServers()` method must not be called while a DNS query is in <ide> progress. <ide> <add>Note that this method works much like <add>[resolve.conf](http://man7.org/linux/man-pages/man5/resolv.conf.5.html). <add>That is, if attempting to resolve with the first server provided results in a <add>`NOTFOUND` error, the `resolve()` method will *not* attempt to resolve with <add>subsequent servers provided. Fallback DNS servers will only be used if the <add>earlier ones time out or result in some other error. <add> <ide> ## DNS Promises API <ide> <ide> > Stability: 1 - Experimental <ide> An error will be thrown if an invalid address is provided. <ide> The `dnsPromises.setServers()` method must not be called while a DNS query is in <ide> progress. <ide> <add>Note that this method works much like <add>[resolve.conf](http://man7.org/linux/man-pages/man5/resolv.conf.5.html). <add>That is, if attempting to resolve with the first server provided results in a <add>`NOTFOUND` error, the `resolve()` method will *not* attempt to resolve with <add>subsequent servers provided. Fallback DNS servers will only be used if the <add>earlier ones time out or result in some other error. <add> <ide> ## Error codes <ide> <ide> Each DNS query can return one of the following error codes:
1
Go
Go
add /proc/scsi to masked paths
a21ecdf3c8a343a7c94e4c4d01b178c87ca7aaa1
<ide><path>oci/defaults.go <ide> func DefaultLinuxSpec() specs.Spec { <ide> "/proc/timer_list", <ide> "/proc/timer_stats", <ide> "/proc/sched_debug", <add> "/proc/scsi", <ide> }, <ide> ReadonlyPaths: []string{ <ide> "/proc/asound",
1
Go
Go
add configs support to client
102738101a68711c2ca50e36b24d389c35d087df
<ide><path>client/config_create.go <add>package client <add> <add>import ( <add> "encoding/json" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/swarm" <add> "golang.org/x/net/context" <add>) <add> <add>// ConfigCreate creates a new Config. <add>func (cli *Client) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) { <add> var response types.ConfigCreateResponse <add> resp, err := cli.post(ctx, "/configs/create", nil, config, nil) <add> if err != nil { <add> return response, err <add> } <add> <add> err = json.NewDecoder(resp.body).Decode(&response) <add> ensureReaderClosed(resp) <add> return response, err <add>} <ide><path>client/config_create_test.go <add>package client <add> <add>import ( <add> "bytes" <add> "encoding/json" <add> "fmt" <add> "io/ioutil" <add> "net/http" <add> "strings" <add> "testing" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/swarm" <add> "golang.org/x/net/context" <add>) <add> <add>func TestConfigCreateError(t *testing.T) { <add> client := &Client{ <add> client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), <add> } <add> _, err := client.ConfigCreate(context.Background(), swarm.ConfigSpec{}) <add> if err == nil || err.Error() != "Error response from daemon: Server error" { <add> t.Fatalf("expected a Server Error, got %v", err) <add> } <add>} <add> <add>func TestConfigCreate(t *testing.T) { <add> expectedURL := "/configs/create" <add> client := &Client{ <add> client: newMockClient(func(req *http.Request) (*http.Response, error) { <add> if !strings.HasPrefix(req.URL.Path, expectedURL) { <add> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) <add> } <add> if req.Method != "POST" { <add> return nil, fmt.Errorf("expected POST method, got %s", req.Method) <add> } <add> b, err := json.Marshal(types.ConfigCreateResponse{ <add> ID: "test_config", <add> }) <add> if err != nil { <add> return nil, err <add> } <add> return &http.Response{ <add> StatusCode: http.StatusCreated, <add> Body: ioutil.NopCloser(bytes.NewReader(b)), <add> }, nil <add> }), <add> } <add> <add> r, err := client.ConfigCreate(context.Background(), swarm.ConfigSpec{}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if r.ID != "test_config" { <add> t.Fatalf("expected `test_config`, got %s", r.ID) <add> } <add>} <ide><path>client/config_inspect.go <add>package client <add> <add>import ( <add> "bytes" <add> "encoding/json" <add> "io/ioutil" <add> "net/http" <add> <add> "github.com/docker/docker/api/types/swarm" <add> "golang.org/x/net/context" <add>) <add> <add>// ConfigInspectWithRaw returns the config information with raw data <add>func (cli *Client) ConfigInspectWithRaw(ctx context.Context, id string) (swarm.Config, []byte, error) { <add> resp, err := cli.get(ctx, "/configs/"+id, nil, nil) <add> if err != nil { <add> if resp.statusCode == http.StatusNotFound { <add> return swarm.Config{}, nil, configNotFoundError{id} <add> } <add> return swarm.Config{}, nil, err <add> } <add> defer ensureReaderClosed(resp) <add> <add> body, err := ioutil.ReadAll(resp.body) <add> if err != nil { <add> return swarm.Config{}, nil, err <add> } <add> <add> var config swarm.Config <add> rdr := bytes.NewReader(body) <add> err = json.NewDecoder(rdr).Decode(&config) <add> <add> return config, body, err <add>} <ide><path>client/config_inspect_test.go <add>package client <add> <add>import ( <add> "bytes" <add> "encoding/json" <add> "fmt" <add> "io/ioutil" <add> "net/http" <add> "strings" <add> "testing" <add> <add> "github.com/docker/docker/api/types/swarm" <add> "golang.org/x/net/context" <add>) <add> <add>func TestConfigInspectError(t *testing.T) { <add> client := &Client{ <add> client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), <add> } <add> <add> _, _, err := client.ConfigInspectWithRaw(context.Background(), "nothing") <add> if err == nil || err.Error() != "Error response from daemon: Server error" { <add> t.Fatalf("expected a Server Error, got %v", err) <add> } <add>} <add> <add>func TestConfigInspectConfigNotFound(t *testing.T) { <add> client := &Client{ <add> client: newMockClient(errorMock(http.StatusNotFound, "Server error")), <add> } <add> <add> _, _, err := client.ConfigInspectWithRaw(context.Background(), "unknown") <add> if err == nil || !IsErrConfigNotFound(err) { <add> t.Fatalf("expected a configNotFoundError error, got %v", err) <add> } <add>} <add> <add>func TestConfigInspect(t *testing.T) { <add> expectedURL := "/configs/config_id" <add> client := &Client{ <add> client: newMockClient(func(req *http.Request) (*http.Response, error) { <add> if !strings.HasPrefix(req.URL.Path, expectedURL) { <add> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) <add> } <add> content, err := json.Marshal(swarm.Config{ <add> ID: "config_id", <add> }) <add> if err != nil { <add> return nil, err <add> } <add> return &http.Response{ <add> StatusCode: http.StatusOK, <add> Body: ioutil.NopCloser(bytes.NewReader(content)), <add> }, nil <add> }), <add> } <add> <add> configInspect, _, err := client.ConfigInspectWithRaw(context.Background(), "config_id") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if configInspect.ID != "config_id" { <add> t.Fatalf("expected `config_id`, got %s", configInspect.ID) <add> } <add>} <ide><path>client/config_list.go <add>package client <add> <add>import ( <add> "encoding/json" <add> "net/url" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/filters" <add> "github.com/docker/docker/api/types/swarm" <add> "golang.org/x/net/context" <add>) <add> <add>// ConfigList returns the list of configs. <add>func (cli *Client) ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) { <add> query := url.Values{} <add> <add> if options.Filters.Len() > 0 { <add> filterJSON, err := filters.ToParam(options.Filters) <add> if err != nil { <add> return nil, err <add> } <add> <add> query.Set("filters", filterJSON) <add> } <add> <add> resp, err := cli.get(ctx, "/configs", query, nil) <add> if err != nil { <add> return nil, err <add> } <add> <add> var configs []swarm.Config <add> err = json.NewDecoder(resp.body).Decode(&configs) <add> ensureReaderClosed(resp) <add> return configs, err <add>} <ide><path>client/config_list_test.go <add>package client <add> <add>import ( <add> "bytes" <add> "encoding/json" <add> "fmt" <add> "io/ioutil" <add> "net/http" <add> "strings" <add> "testing" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/filters" <add> "github.com/docker/docker/api/types/swarm" <add> "golang.org/x/net/context" <add>) <add> <add>func TestConfigListError(t *testing.T) { <add> client := &Client{ <add> client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), <add> } <add> <add> _, err := client.ConfigList(context.Background(), types.ConfigListOptions{}) <add> if err == nil || err.Error() != "Error response from daemon: Server error" { <add> t.Fatalf("expected a Server Error, got %v", err) <add> } <add>} <add> <add>func TestConfigList(t *testing.T) { <add> expectedURL := "/configs" <add> <add> filters := filters.NewArgs() <add> filters.Add("label", "label1") <add> filters.Add("label", "label2") <add> <add> listCases := []struct { <add> options types.ConfigListOptions <add> expectedQueryParams map[string]string <add> }{ <add> { <add> options: types.ConfigListOptions{}, <add> expectedQueryParams: map[string]string{ <add> "filters": "", <add> }, <add> }, <add> { <add> options: types.ConfigListOptions{ <add> Filters: filters, <add> }, <add> expectedQueryParams: map[string]string{ <add> "filters": `{"label":{"label1":true,"label2":true}}`, <add> }, <add> }, <add> } <add> for _, listCase := range listCases { <add> client := &Client{ <add> client: newMockClient(func(req *http.Request) (*http.Response, error) { <add> if !strings.HasPrefix(req.URL.Path, expectedURL) { <add> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) <add> } <add> query := req.URL.Query() <add> for key, expected := range listCase.expectedQueryParams { <add> actual := query.Get(key) <add> if actual != expected { <add> return nil, fmt.Errorf("%s not set in URL query properly. Expected '%s', got %s", key, expected, actual) <add> } <add> } <add> content, err := json.Marshal([]swarm.Config{ <add> { <add> ID: "config_id1", <add> }, <add> { <add> ID: "config_id2", <add> }, <add> }) <add> if err != nil { <add> return nil, err <add> } <add> return &http.Response{ <add> StatusCode: http.StatusOK, <add> Body: ioutil.NopCloser(bytes.NewReader(content)), <add> }, nil <add> }), <add> } <add> <add> configs, err := client.ConfigList(context.Background(), listCase.options) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if len(configs) != 2 { <add> t.Fatalf("expected 2 configs, got %v", configs) <add> } <add> } <add>} <ide><path>client/config_remove.go <add>package client <add> <add>import "golang.org/x/net/context" <add> <add>// ConfigRemove removes a Config. <add>func (cli *Client) ConfigRemove(ctx context.Context, id string) error { <add> resp, err := cli.delete(ctx, "/configs/"+id, nil, nil) <add> ensureReaderClosed(resp) <add> return err <add>} <ide><path>client/config_remove_test.go <add>package client <add> <add>import ( <add> "bytes" <add> "fmt" <add> "io/ioutil" <add> "net/http" <add> "strings" <add> "testing" <add> <add> "golang.org/x/net/context" <add>) <add> <add>func TestConfigRemoveError(t *testing.T) { <add> client := &Client{ <add> client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), <add> } <add> <add> err := client.ConfigRemove(context.Background(), "config_id") <add> if err == nil || err.Error() != "Error response from daemon: Server error" { <add> t.Fatalf("expected a Server Error, got %v", err) <add> } <add>} <add> <add>func TestConfigRemove(t *testing.T) { <add> expectedURL := "/configs/config_id" <add> <add> client := &Client{ <add> client: newMockClient(func(req *http.Request) (*http.Response, error) { <add> if !strings.HasPrefix(req.URL.Path, expectedURL) { <add> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) <add> } <add> if req.Method != "DELETE" { <add> return nil, fmt.Errorf("expected DELETE method, got %s", req.Method) <add> } <add> return &http.Response{ <add> StatusCode: http.StatusOK, <add> Body: ioutil.NopCloser(bytes.NewReader([]byte("body"))), <add> }, nil <add> }), <add> } <add> <add> err := client.ConfigRemove(context.Background(), "config_id") <add> if err != nil { <add> t.Fatal(err) <add> } <add>} <ide><path>client/config_update.go <add>package client <add> <add>import ( <add> "net/url" <add> "strconv" <add> <add> "github.com/docker/docker/api/types/swarm" <add> "golang.org/x/net/context" <add>) <add> <add>// ConfigUpdate attempts to updates a Config <add>func (cli *Client) ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error { <add> query := url.Values{} <add> query.Set("version", strconv.FormatUint(version.Index, 10)) <add> resp, err := cli.post(ctx, "/configs/"+id+"/update", query, config, nil) <add> ensureReaderClosed(resp) <add> return err <add>} <ide><path>client/config_update_test.go <add>package client <add> <add>import ( <add> "bytes" <add> "fmt" <add> "io/ioutil" <add> "net/http" <add> "strings" <add> "testing" <add> <add> "golang.org/x/net/context" <add> <add> "github.com/docker/docker/api/types/swarm" <add>) <add> <add>func TestConfigUpdateError(t *testing.T) { <add> client := &Client{ <add> client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), <add> } <add> <add> err := client.ConfigUpdate(context.Background(), "config_id", swarm.Version{}, swarm.ConfigSpec{}) <add> if err == nil || err.Error() != "Error response from daemon: Server error" { <add> t.Fatalf("expected a Server Error, got %v", err) <add> } <add>} <add> <add>func TestConfigUpdate(t *testing.T) { <add> expectedURL := "/configs/config_id/update" <add> <add> client := &Client{ <add> client: newMockClient(func(req *http.Request) (*http.Response, error) { <add> if !strings.HasPrefix(req.URL.Path, expectedURL) { <add> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) <add> } <add> if req.Method != "POST" { <add> return nil, fmt.Errorf("expected POST method, got %s", req.Method) <add> } <add> return &http.Response{ <add> StatusCode: http.StatusOK, <add> Body: ioutil.NopCloser(bytes.NewReader([]byte("body"))), <add> }, nil <add> }), <add> } <add> <add> err := client.ConfigUpdate(context.Background(), "config_id", swarm.Version{}, swarm.ConfigSpec{}) <add> if err != nil { <add> t.Fatal(err) <add> } <add>} <ide><path>client/errors.go <ide> func IsErrSecretNotFound(err error) bool { <ide> return ok <ide> } <ide> <add>// configNotFoundError implements an error returned when a config is not found. <add>type configNotFoundError struct { <add> name string <add>} <add> <add>// Error returns a string representation of a configNotFoundError <add>func (e configNotFoundError) Error() string { <add> return fmt.Sprintf("Error: no such config: %s", e.name) <add>} <add> <add>// NotFound indicates that this error type is of NotFound <add>func (e configNotFoundError) NotFound() bool { <add> return true <add>} <add> <add>// IsErrConfigNotFound returns true if the error is caused <add>// when a config is not found. <add>func IsErrConfigNotFound(err error) bool { <add> _, ok := err.(configNotFoundError) <add> return ok <add>} <add> <ide> // pluginNotFoundError implements an error returned when a plugin is not in the docker host. <ide> type pluginNotFoundError struct { <ide> name string <ide><path>client/interface.go <ide> import ( <ide> <ide> // CommonAPIClient is the common methods between stable and experimental versions of APIClient. <ide> type CommonAPIClient interface { <add> ConfigAPIClient <ide> ContainerAPIClient <ide> ImageAPIClient <ide> NodeAPIClient <ide> type SecretAPIClient interface { <ide> SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) <ide> SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error <ide> } <add> <add>// ConfigAPIClient defines API client methods for configs <add>type ConfigAPIClient interface { <add> ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) <add> ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) <add> ConfigRemove(ctx context.Context, id string) error <add> ConfigInspectWithRaw(ctx context.Context, name string) (swarm.Config, []byte, error) <add> ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error <add>}
12
PHP
PHP
add textarea widget and tests
84537f2c1c85f90d0132d84f6b46e5e673c62491
<ide><path>src/View/Input/Textarea.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since CakePHP(tm) v3.0 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\View\Input; <add> <add>use Cake\View\Input\InputInterface; <add> <add>/** <add> * Input widget class for generating a textarea control. <add> * <add> * This class is intended as an internal implementation detail <add> * of Cake\View\Helper\FormHelper and is not intended for direct use. <add> */ <add>class Textarea implements InputInterface { <add> <add>/** <add> * Constructor <add> * <add> * @param Cake\View\StringTemplate $templates <add> */ <add> public function __construct($templates) { <add> $this->_templates = $templates; <add> } <add> <add>/** <add> * Render a text area form widget. <add> * <add> * Data supports the following keys: <add> * <add> * - `name` - Set the input name. <add> * - `val` - A string of the option to mark as selected. <add> * - `escape` - Set to false to disable HTML escaping. <add> * <add> * All other keys will be converted into HTML attributes. <add> * <add> * @param array $data The data to build a textarea with. <add> * @return string HTML elements. <add> */ <add> public function render(array $data) { <add> $data += [ <add> 'val' => '', <add> 'name' => '', <add> 'escape' => true, <add> ]; <add> return $this->_templates->format('textarea', [ <add> 'name' => $data['name'], <add> 'value' => $data['escape'] ? h($data['val']) : $data['val'], <add> 'attrs' => $this->_templates->formatAttributes( <add> $data, ['name', 'val'] <add> ) <add> ]); <add> } <add> <add>} <ide><path>tests/TestCase/View/Input/TextareaTest.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since CakePHP(tm) v3.0 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\TestCase\View\Input; <add> <add>use Cake\TestSuite\TestCase; <add>use Cake\View\Input\Textarea; <add>use Cake\View\StringTemplate; <add> <add>/** <add> * Textarea input test. <add> */ <add>class TextareaTest extends TestCase { <add> <add>/** <add> * setup <add> * <add> * @return void <add> */ <add> public function setUp() { <add> parent::setUp(); <add> $templates = [ <add> 'textarea' => '<textarea name="{{name}}"{{attrs}}>{{value}}</textarea>', <add> ]; <add> $this->templates = new StringTemplate($templates); <add> } <add> <add>/** <add> * Test render in a simple case. <add> * <add> * @return void <add> */ <add> public function testRenderSimple() { <add> $input = new Textarea($this->templates); <add> $result = $input->render(['name' => 'comment']); <add> $expected = [ <add> 'textarea' => ['name' => 'comment'], <add> '/textarea', <add> ]; <add> $this->assertTags($result, $expected); <add> } <add> <add>/** <add> * Test render with a value <add> * <add> * @return void <add> */ <add> public function testRenderWithValue() { <add> $input = new Textarea($this->templates); <add> $data = ['name' => 'comment', 'data-foo' => '<val>', 'val' => 'some <html>']; <add> $result = $input->render($data); <add> $expected = [ <add> 'textarea' => ['name' => 'comment', 'data-foo' => '&lt;val&gt;'], <add> 'some &lt;html&gt;', <add> '/textarea', <add> ]; <add> $this->assertTags($result, $expected); <add> <add> $data['escape'] = false; <add> $result = $input->render($data); <add> $expected = [ <add> 'textarea' => ['name' => 'comment', 'data-foo' => '<val>'], <add> 'some <html>', <add> '/textarea', <add> ]; <add> $this->assertTags($result, $expected); <add> } <add> <add>}
2
Javascript
Javascript
reuse hostname from underlying net.socket
5977cba985a4a1831ab5679a7701026f544d9080
<ide><path>lib/_tls_wrap.js <ide> exports.connect = function(/* [port, host], options, cb */) { <ide> }; <ide> options = util._extend(defaults, options || {}); <ide> <del> var hostname = options.servername || options.host || 'localhost', <add> var hostname = options.servername || <add> options.host || <add> options.socket && options.socket._host || <add> 'localhost', <ide> NPN = {}, <ide> credentials = crypto.createCredentials(options); <ide> tls.convertNPNProtocols(options.NPNProtocols, NPN); <ide><path>lib/net.js <ide> function Socket(options) { <ide> this._connecting = false; <ide> this._hadError = false; <ide> this._handle = null; <add> this._host = null; <ide> <ide> if (util.isNumber(options)) <ide> options = { fd: options }; // Legacy interface. <ide> Socket.prototype.connect = function(options, cb) { <ide> <ide> } else if (!options.host) { <ide> debug('connect: missing host'); <del> connect(self, '127.0.0.1', options.port, 4); <add> self._host = '127.0.0.1'; <add> connect(self, self._host, options.port, 4); <ide> <ide> } else { <ide> var host = options.host; <ide> var family = options.family || 4; <ide> debug('connect: find host ' + host); <add> self._host = host; <ide> require('dns').lookup(host, family, function(err, ip, addressType) { <ide> self.emit('lookup', err, ip, addressType); <ide> <ide><path>test/internet/test-tls-reuse-host-from-socket.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>var tls = require('tls'); <add>var net = require('net'); <add>var connected = false; <add>var secure = false; <add> <add>process.on('exit', function() { <add> assert(connected); <add> assert(secure); <add> console.log('ok'); <add>}); <add> <add>var socket = net.connect(443, 'www.google.com', function() { <add> connected = true; <add> var secureSocket = tls.connect({ socket: socket }, function() { <add> secure = true; <add> secureSocket.destroy(); <add> }); <add>});
3
Text
Text
add graph model to doc
f2c97d817b6f8e886e9bae5975e36f9e77f7ee69
<ide><path>docs/sources/models.md <ide> model = keras.models.Sequential() <ide> ``` <ide> - __Methods__: <ide> - __add__(layer): Add a layer to the model. <del> - __compile__(optimizer, loss, class_mode="categorical"): <del> - __Arguments__: <add> - __compile__(optimizer, loss, class_mode="categorical"): <add> - __Arguments__: <ide> - __optimizer__: str (name of optimizer) or optimizer object. See [optimizers](optimizers.md). <ide> - __loss__: str (name of objective function) or objective function. See [objectives](objectives.md). <del> - __class_mode__: one of "categorical", "binary". This is only used for computing classification accuracy or using the predict_classes method. <add> - __class_mode__: one of "categorical", "binary". This is only used for computing classification accuracy or using the predict_classes method. <ide> - __theano_mode__: A `theano.compile.mode.Mode` ([reference](http://deeplearning.net/software/theano/library/compile/mode.html)) instance controlling specifying compilation options. <ide> - __fit__(X, y, batch_size=128, nb_epoch=100, verbose=1, validation_split=0., validation_data=None, shuffle=True, show_accuracy=False, callbacks=[], class_weight=None, sample_weight=None): Train a model for a fixed number of epochs. <ide> - __Return__: a history dictionary with a record of training loss values at successive epochs, as well as validation loss values (if applicable), accuracy (if applicable), etc. <del> - __Arguments__: <add> - __Arguments__: <ide> - __X__: data. <ide> - __y__: labels. <ide> - __batch_size__: int. Number of samples per gradient update. <del> - __nb_epoch__: int. <add> - __nb_epoch__: int. <ide> - __verbose__: 0 for no logging to stdout, 1 for progress bar logging, 2 for one log line per epoch. <ide> - __callbacks__: `keras.callbacks.Callback` list. List of callbacks to apply during training. See [callbacks](callbacks.md). <ide> - __validation_split__: float (0. < x < 1). Fraction of the data to use as held-out validation data. <ide> model = keras.models.Sequential() <ide> - __class_weight__: dictionary mapping classes to a weight value, used for scaling the loss function (during training only). <ide> - __sample_weight__: list or numpy array with 1:1 mapping to the training samples, used for scaling the loss function (during training only). <ide> - __evaluate__(X, y, batch_size=128, show_accuracy=False, verbose=1): Show performance of the model over some validation data. <del> - __Return__: The loss score over the data. <add> - __Return__: The loss score over the data, or a `(loss, accuracy)` tuple if `show_accuracy=True`. <ide> - __Arguments__: Same meaning as fit method above. verbose is used as a binary flag (progress bar or nothing). <del> - __predict__(X, batch_size=128, verbose=1): <add> - __predict__(X, batch_size=128, verbose=1): <ide> - __Return__: An array of predictions for some test data. <ide> - __Arguments__: Same meaning as fit method above. <ide> - __predict_classes__(X, batch_size=128, verbose=1): Return an array of class predictions for some test data. <ide> - __Return__: An array of labels for some test data. <ide> - __Arguments__: Same meaning as fit method above. verbose is used as a binary flag (progress bar or nothing). <del> - __train__(X, y, accuracy=False): Single gradient update on one batch. if accuracy==False, return tuple (loss_on_batch, accuracy_on_batch). Else, return loss_on_batch. <add> - __train_on_batch__(X, y, accuracy=False): Single gradient update on one batch. <ide> - __Return__: loss over the data, or tuple `(loss, accuracy)` if `accuracy=True`. <del> - __test__(X, y, accuracy=False): Single performance evaluation on one batch. if accuracy==False, return tuple (loss_on_batch, accuracy_on_batch). Else, return loss_on_batch. <add> - __test_on_batch__(X, y, accuracy=False): Single performance evaluation on one batch. <ide> - __Return__: loss over the data, or tuple `(loss, accuracy)` if `accuracy=True`. <ide> - __save_weights__(fname, overwrite=False): Store the weights of all layers to a HDF5 file. If overwrite==False and the file already exists, an exception will be thrown. <del> - __load_weights__(fname): Sets the weights of a model, based to weights stored by __save__weights__. You can only __load__weights__ on a savefile from a model with an identical architecture. __load_weights__ can be called either before or after the __compile__ step. <add> - __load_weights__(fname): Sets the weights of a model, based to weights stored by __save_weights__. You can only __load_weights__ on a savefile from a model with an identical architecture. __load_weights__ can be called either before or after the __compile__ step. <ide> <ide> __Examples__: <ide> <ide> Epoch 2 <ide> 10960/37800 [=======>......................] - ETA: 4s - loss: 0.0109 - acc.: 0.9420 <ide> ''' <ide> ``` <add> <add>--- <add> <add>## Graph <add> <add>Arbitrary connection graph. It can have any number of inputs and outputs, with each output trained with its own loss function. The quantity being optimized by a Graph model is the sum of all loss functions over the different outputs. <add> <add>```python <add>model = keras.models.Graph() <add>``` <add>- __Methods__: <add> - __add_input__(ndim=2): Add an input with shape dimensionality `ndim`. Use `ndim=2` for vector input (`(samples, features)`), ndim=3 for temporal input (`(samples, time, features)`), ndim=4 for image input (`(samples, channels, height, width)`). <add> - __add_output__(name, input=None, inputs=[], merge_mode='concat'): Add an output connect to `input` or `inputs`. <add> - __Arguments__: <add> - __name__: str. unique identifier of the output. <add> - __input__: str name of the node that the output is connected to. Only specify *one* of either `input` or `inputs`. <add> - __inputs__: list of str names of the node that the output is connected to. <add> - __merge_mode__: "sum" or "concat". Only applicable if `inputs` list is specified. Merge mode for the different inputs. <add> - __add_node__(layer, name, input=None, inputs=[], merge_mode='concat'): Add an output connect to `input` or `inputs`. <add> - __Arguments__: <add> - __layer__: Layer instance. <add> - __name__: str. unique identifier of the node. <add> - __input__: str name of the node/input that the node is connected to. Only specify *one* of either `input` or `inputs`. <add> - __inputs__: list of str names of the node that the node is connected to. <add> - __merge_mode__: "sum" or "concat". Only applicable if `inputs` list is specified. Merge mode for the different inputs. <add> - __compile__(optimizer, loss): <add> - __Arguments__: <add> - __optimizer__: str (name of optimizer) or optimizer object. See [optimizers](optimizers.md). <add> - __loss__: dictionary mapping the name(s) of the output(s) to a loss function (string name of objective function or objective function. See [objectives](objectives.md)). <add> - __fit__(data, batch_size=128, nb_epoch=100, verbose=1, validation_split=0., validation_data=None, shuffle=True, callbacks=[]): Train a model for a fixed number of epochs. <add> - __Return__: a history dictionary with a record of training loss values at successive epochs, as well as validation loss values (if applicable). <add> - __Arguments__: <add> - __data__:dictionary mapping input names out outputs names to appropriate numpy arrays. All arrays should contain the same number of samples. <add> - __batch_size__: int. Number of samples per gradient update. <add> - __nb_epoch__: int. <add> - __verbose__: 0 for no logging to stdout, 1 for progress bar logging, 2 for one log line per epoch. <add> - __callbacks__: `keras.callbacks.Callback` list. List of callbacks to apply during training. See [callbacks](callbacks.md). <add> - __validation_split__: float (0. < x < 1). Fraction of the data to use as held-out validation data. <add> - __validation_data__: tuple (X, y) to be used as held-out validation data. Will override validation_split. <add> - __shuffle__: boolean. Whether to shuffle the samples at each epoch. <add> - __evaluate__(data, batch_size=128, verbose=1): Show performance of the model over some validation data. <add> - __Return__: The loss score over the data. <add> - __Arguments__: Same meaning as fit method above. verbose is used as a binary flag (progress bar or nothing). <add> - __predict__(data, batch_size=128, verbose=1): <add> - __Return__: A dictionary mapping output names to arrays of predictions over the data. <add> - __Arguments__: Same meaning as fit method above. Only inputs need to be specified in `data`. <add> - __train_on_batch__(data): Single gradient update on one batch. <add> - __Return__: loss over the data. <add> - __test_on_batch__(data): Single performance evaluation on one batch. <add> - __Return__: loss over the data. <add> - __save_weights__(fname, overwrite=False): Store the weights of all layers to a HDF5 file. If `overwrite==False` and the file already exists, an exception will be thrown. <add> - __load_weights__(fname): Sets the weights of a model, based to weights stored by __save_weights__. You can only __load_weights__ on a savefile from a model with an identical architecture. __load_weights__ can be called either before or after the __compile__ step. <add> <add> <add>__Examples__: <add> <add>```python <add># graph model with one input and two outputs <add>graph = Graph() <add>graph.add_input(name='input', ndim=2) <add>graph.add_node(Dense(32, 16), name='dense1', input='input') <add>graph.add_node(Dense(32, 4), name='dense2', input='input') <add>graph.add_node(Dense(16, 4), name='dense3', input='dense1') <add>graph.add_output(name='output1', input='dense2') <add>graph.add_output(name='output2', input='dense3') <add> <add>graph.compile('rmsprop', {'output1':'mse', 'output2':'mse'}) <add>history = graph.fit({'input':X_train, 'output1':y_train, 'output2':y2_train}, nb_epoch=10) <add> <add>``` <add> <add>```python <add># graph model with two inputs and one output <add>graph = Graph() <add>graph.add_input(name='input1', ndim=2) <add>graph.add_input(name='input2', ndim=2) <add>graph.add_node(Dense(32, 16), name='dense1', input='input1') <add>graph.add_node(Dense(32, 4), name='dense2', input='input2') <add>graph.add_node(Dense(16, 4), name='dense3', input='dense1') <add>graph.add_output(name='output', inputs=['dense2', 'dense3'], merge_mode='sum') <add>graph.compile('rmsprop', {'output':'mse'}) <add> <add>history = graph.fit({'input1':X_train, 'input2':X2_train, 'output':y_train}, nb_epoch=10) <add>predictions = graph.predict({'input1':X_test, 'input2':X2_test}) # {'output':...} <add> <add>``` <ide>\ No newline at end of file
1
Ruby
Ruby
remove intermediate method
74ad97ce7f3325fc0a16c5ec3262e191a92667cd
<ide><path>Library/Homebrew/cmd/config.rb <ide> def dump_build_config(f) <ide> f.puts "X11: #{describe_x11}" <ide> end <ide> <del> def write_build_config(f) <del> Homebrew.dump_build_config(f) <del> end <del> <ide> def dump_verbose_config(f) <ide> f.puts "HOMEBREW_VERSION: #{HOMEBREW_VERSION}" <ide> f.puts "ORIGIN: #{origin}" <ide><path>Library/Homebrew/formula.rb <ide> def system cmd, *args <ide> Kernel.system "/usr/bin/tail", "-n", "5", logfn unless ARGV.verbose? <ide> f.puts <ide> require 'cmd/config' <del> Homebrew.write_build_config(f) <add> Homebrew.dump_build_config(f) <ide> raise BuildError.new(self, cmd, args) <ide> end <ide> end
2
Javascript
Javascript
add meridiem translation and correct quotemark
315abe846d9333cc4cea2d7781365d12ca3da347
<ide><path>src/locale/br.js <ide> function softMutation(text) { <ide> return mutationTable[text.charAt(0)] + text.substring(1); <ide> } <ide> <add>var monthsParse = [ <add> /^gen/i, <add> /^c[ʼ\']hwe/i, <add> /^meu/i, <add> /^ebr/i, <add> /^mae/i, <add> /^(mez|eve)/i, <add> /^gou/i, <add> /^eos/i, <add> /^gwe/i, <add> /^her/i, <add> /^du/i, <add> /^ker/i, <add> ], <add> monthsRegex = /^(genver|c[ʼ\']hwevrer|meurzh|ebrel|mae|mezheven|gouere|eost|gwengolo|here|du|kerzu|gen|c[ʼ\']hwe|meu|ebr|mae|eve|gou|eos|gwe|her|du|ker)/i, <add> monthsStrictRegex = /^(genver|c[ʼ\']hwevrer|meurzh|ebrel|mae|mezheven|gouere|eost|gwengolo|here|du|kerzu)/i, <add> monthsShortStrictRegex = /^(gen|c[ʼ\']hwe|meu|ebr|mae|eve|gou|eos|gwe|her|du|ker)/i, <add> fullWeekdaysParse = [ <add> /^sul/i, <add> /^lun/i, <add> /^meurzh/i, <add> /^merc[ʼ\']her/i, <add> /^yaou/i, <add> /^gwener/i, <add> /^sadorn/i, <add> ], <add> shortWeekdaysParse = [ <add> /^Sul/i, <add> /^Lun/i, <add> /^Meu/i, <add> /^Mer/i, <add> /^Yao/i, <add> /^Gwe/i, <add> /^Sad/i, <add> ], <add> minWeekdaysParse = [ <add> /^Su/i, <add> /^Lu/i, <add> /^Me([^r]|$)/i, <add> /^Mer/i, <add> /^Ya/i, <add> /^Gw/i, <add> /^Sa/i, <add> ]; <add> <ide> export default moment.defineLocale('br', { <del> months: "Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split( <add> months: 'Genver_Cʼhwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split( <ide> '_' <ide> ), <del> monthsShort: "Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split('_'), <del> weekdays: "Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split('_'), <add> monthsShort: 'Gen_Cʼhwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'), <add> weekdays: 'Sul_Lun_Meurzh_Mercʼher_Yaou_Gwener_Sadorn'.split('_'), <ide> weekdaysShort: 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'), <ide> weekdaysMin: 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'), <del> weekdaysParseExact: true, <add> weekdaysParse: minWeekdaysParse, <add> fullWeekdaysParse: fullWeekdaysParse, <add> shortWeekdaysParse: shortWeekdaysParse, <add> minWeekdaysParse: minWeekdaysParse, <add> <add> monthsRegex: monthsRegex, <add> monthsShortRegex: monthsRegex, <add> monthsStrictRegex: monthsStrictRegex, <add> monthsShortStrictRegex: monthsShortStrictRegex, <add> monthsParse: monthsParse, <add> longMonthsParse: monthsParse, <add> shortMonthsParse: monthsParse, <add> <ide> longDateFormat: { <ide> LT: 'HH:mm', <ide> LTS: 'HH:mm:ss', <ide> export default moment.defineLocale('br', { <ide> }, <ide> calendar: { <ide> sameDay: '[Hiziv da] LT', <del> nextDay: "[Warc'hoazh da] LT", <add> nextDay: '[Warcʼhoazh da] LT', <ide> nextWeek: 'dddd [da] LT', <del> lastDay: "[Dec'h da] LT", <add> lastDay: '[Decʼh da] LT', <ide> lastWeek: 'dddd [paset da] LT', <ide> sameElse: 'L', <ide> }, <ide> relativeTime: { <ide> future: 'a-benn %s', <del> past: "%s 'zo", <add> past: '%s ʼzo', <ide> s: 'un nebeud segondennoù', <ide> ss: '%d eilenn', <ide> m: 'ur vunutenn', <ide> export default moment.defineLocale('br', { <ide> dow: 1, // Monday is the first day of the week. <ide> doy: 4, // The week that contains Jan 4th is the first week of the year. <ide> }, <add> meridiemParse: /a.m.|g.m./, // goude merenn | a-raok merenn <add> isPM: function (token) { <add> return token === 'g.m.'; <add> }, <add> meridiem: function (hour, minute, isLower) { <add> return hour < 12 ? 'a.m.' : 'g.m.'; <add> }, <ide> }); <ide><path>src/test/locale/br.js <ide> import moment from '../../moment'; <ide> localeModule('br'); <ide> <ide> test('parse', function (assert) { <del> var tests = "Genver Gen_C'hwevrer C'hwe_Meurzh Meu_Ebrel Ebr_Mae Mae_Mezheven Eve_Gouere Gou_Eost Eos_Gwengolo Gwe_Here Her_Du Du_Kerzu Ker".split( <add> var tests = 'Genver Gen_Cʼhwevrer Cʼhwe_Meurzh Meu_Ebrel Ebr_Mae Mae_Mezheven Eve_Gouere Gou_Eost Eos_Gwengolo Gwe_Here Her_Du Du_Kerzu Ker'.split( <ide> '_' <ide> ), <del> i; <add> i, <add> monthsWithRegularQuoteMark = ["C'hwevrer", "C'hwe"]; <add> <ide> function equalTest(input, mmm, i) { <ide> assert.equal( <ide> moment(input, mmm).month(), <ide> test('parse', function (assert) { <ide> equalTestStrict(tests[i][0].toLocaleLowerCase(), 'MMMM', i); <ide> equalTestStrict(tests[i][0].toLocaleUpperCase(), 'MMMM', i); <ide> } <add> <add> // check with regular quote mark <add> equalTest(monthsWithRegularQuoteMark[0], 'MMM', 1); <add> equalTest(monthsWithRegularQuoteMark[1], 'MMM', 1); <add> equalTest(monthsWithRegularQuoteMark[0], 'MMMM', 1); <add> equalTest(monthsWithRegularQuoteMark[1], 'MMMM', 1); <add> equalTest(monthsWithRegularQuoteMark[0].toLocaleLowerCase(), 'MMM', 1); <add> equalTest(monthsWithRegularQuoteMark[1].toLocaleLowerCase(), 'MMM', 1); <add> equalTest(monthsWithRegularQuoteMark[0].toLocaleUpperCase(), 'MMMM', 1); <add> equalTest(monthsWithRegularQuoteMark[1].toLocaleUpperCase(), 'MMMM', 1); <add> <add> assert.notEqual( <add> moment(monthsWithRegularQuoteMark[0], 'MMM', true).month(), <add> 1 <add> ); <add> equalTestStrict(monthsWithRegularQuoteMark[1], 'MMM', 1); <add> equalTest(monthsWithRegularQuoteMark[0], 'MMMM', 1); <add> assert.notEqual( <add> moment(monthsWithRegularQuoteMark[1], 'MMMM', true).month(), <add> 1 <add> ); <add> equalTest(monthsWithRegularQuoteMark[1].toLocaleLowerCase(), 'MMM', 1); <add> equalTest(monthsWithRegularQuoteMark[0].toLocaleUpperCase(), 'MMMM', 1); <add> <add> // check weekday with regular quote mark <add> assert.equal( <add> moment("merc'her", 'dddd', true).day(), <add> 3, <add> "merc'her (regular quote)" <add> ); <add> assert.equal( <add> moment('mercʼher', 'dddd', true).day(), <add> 3, <add> 'mercʼher (special quote)' <add> ); <ide> }); <ide> <ide> test('format', function (assert) { <ide> moment.locale('br'); <ide> var a = [ <ide> [ <ide> 'dddd, MMMM Do YYYY, h:mm:ss a', <del> "Sul, C'hwevrer 14vet 2010, 3:25:50 pm", <add> 'Sul, Cʼhwevrer 14vet 2010, 3:25:50 g.m.', <ide> ], <del> ['ddd, h A', 'Sul, 3 PM'], <del> ['M Mo MM MMMM MMM', "2 2vet 02 C'hwevrer C'hwe"], <add> ['ddd, h A', 'Sul, 3 g.m.'], <add> ['M Mo MM MMMM MMM', '2 2vet 02 Cʼhwevrer Cʼhwe'], <ide> ['YYYY YY', '2010 10'], <ide> ['D Do DD', '14 14vet 14'], <ide> ['d do dddd ddd dd', '0 0vet Sul Sul Su'], <ide> test('format', function (assert) { <ide> ['s ss', '50 50'], <ide> ['DDDo [devezh] [ar] [vloaz]', '45vet devezh ar vloaz'], <ide> ['L', '14/02/2010'], <del> ['LL', "14 a viz C'hwevrer 2010"], <del> ['LLL', "14 a viz C'hwevrer 2010 15:25"], <del> ['LLLL', "Sul, 14 a viz C'hwevrer 2010 15:25"], <add> ['LL', '14 a viz Cʼhwevrer 2010'], <add> ['LLL', '14 a viz Cʼhwevrer 2010 15:25'], <add> ['LLLL', 'Sul, 14 a viz Cʼhwevrer 2010 15:25'], <ide> ], <ide> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <ide> i; <ide> test('format ordinal', function (assert) { <ide> <ide> test('format month', function (assert) { <ide> moment.locale('br'); <del> var expected = "Genver Gen_C'hwevrer C'hwe_Meurzh Meu_Ebrel Ebr_Mae Mae_Mezheven Eve_Gouere Gou_Eost Eos_Gwengolo Gwe_Here Her_Du Du_Kerzu Ker".split( <add> var expected = 'Genver Gen_Cʼhwevrer Cʼhwe_Meurzh Meu_Ebrel Ebr_Mae Mae_Mezheven Eve_Gouere Gou_Eost Eos_Gwengolo Gwe_Here Her_Du Du_Kerzu Ker'.split( <ide> '_' <ide> ), <ide> i; <ide> test('format month', function (assert) { <ide> <ide> test('format week', function (assert) { <ide> moment.locale('br'); <del> var expected = "Sul Sul Su_Lun Lun Lu_Meurzh Meu Me_Merc'her Mer Mer_Yaou Yao Ya_Gwener Gwe Gw_Sadorn Sad Sa".split( <add> var expected = 'Sul Sul Su_Lun Lun Lu_Meurzh Meu Me_Mercʼher Mer Mer_Yaou Yao Ya_Gwener Gwe Gw_Sadorn Sad Sa'.split( <ide> '_' <ide> ), <ide> i; <ide> test('suffix', function (assert) { <ide> 'a-benn un nebeud segondennoù', <ide> 'prefix' <ide> ); <del> assert.equal(moment(0).from(30000), "un nebeud segondennoù 'zo", 'suffix'); <add> assert.equal(moment(0).from(30000), 'un nebeud segondennoù ʼzo', 'suffix'); <ide> }); <ide> <ide> test('now from now', function (assert) { <ide> moment.locale('br'); <ide> assert.equal( <ide> moment().fromNow(), <del> "un nebeud segondennoù 'zo", <add> 'un nebeud segondennoù ʼzo', <ide> 'now from now should display as in the past' <ide> ); <ide> }); <ide> test('calendar day', function (assert) { <ide> ); <ide> assert.equal( <ide> moment(a).add({ d: 1 }).calendar(), <del> "Warc'hoazh da 12:00", <add> 'Warcʼhoazh da 12:00', <ide> 'tomorrow at the same time' <ide> ); <ide> assert.equal( <ide> moment(a).subtract({ d: 1 }).calendar(), <del> "Dec'h da 12:00", <add> 'Decʼh da 12:00', <ide> 'yesterday at the same time' <ide> ); <ide> });
2
Mixed
Javascript
delay animations until attached
cfb5fba527cd93b596329fb05079e320b6586701
<ide><path>docs/docs/getting-started/v3-migration.md <ide> options: { <ide> <ide> Animation system was completely rewritten in Chart.js v3. Each property can now be animated separately. Please see [animations](../configuration/animations.md) docs for details. <ide> <del> <ide> #### Customizability <ide> <ide> * `custom` attribute of elements was removed. Please use scriptable options <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> While the end-user migration for Chart.js 3 is fairly straight-forward, the developer migration can be more complicated. Please reach out for help in the #dev [Slack](https://chartjs-slack.herokuapp.com/) channel if tips on migrating would be helpful. <ide> <ide> Some of the biggest things that have changed: <add> <ide> * There is a completely rewritten and more performant animation system. <ide> * `Element._model` and `Element._view` are no longer used and properties are now set directly on the elements. You will have to use the method `getProps` to access these properties inside most methods such as `inXRange`/`inYRange` and `getCenterPoint`. Please take a look at [the Chart.js-provided elements](https://github.com/chartjs/Chart.js/tree/master/src/elements) for examples. <ide> * When building the elements in a controller, it's now suggested to call `updateElement` to provide the element properties. There are also methods such as `getSharedOptions` and `includeOptions` that have been added to skip redundant computation. Please take a look at [the Chart.js-provided controllers](https://github.com/chartjs/Chart.js/tree/master/src/controllers) for examples. <ide> A few changes were made to controllers that are more straight-forward, but will <ide> The following properties and methods were removed: <ide> <ide> #### Chart <add> <ide> * `Chart.borderWidth` <ide> * `Chart.chart.chart` <ide> * `Chart.Bar`. New charts are created via `new Chart` and providing the appropriate `type` parameter <ide> The APIs listed in this section have changed in signature or behaviour from vers <ide> * `Chart.platform` is no longer the platform object used by charts. Every chart instance now has a separate platform instance. <ide> * `Chart.platforms` is an object that contains two usable platform classes, `BasicPlatform` and `DomPlatform`. It also contains `BasePlatform`, a class that all platforms must extend from. <ide> * If the canvas passed in is an instance of `OffscreenCanvas`, the `BasicPlatform` is automatically used. <add>* `isAttached` method was added to platform. <ide><path>src/core/core.controller.js <ide> export default class Chart { <ide> this.active = undefined; <ide> this.lastActive = []; <ide> this._lastEvent = undefined; <del> /** @type {{resize?: function}} */ <add> /** @type {{attach?: function, detach?: function, resize?: function}} */ <ide> this._listeners = {}; <ide> this._sortedMetasets = []; <ide> this._updating = false; <ide> export default class Chart { <ide> this.$plugins = undefined; <ide> this.$proxies = {}; <ide> this._hiddenIndices = {}; <add> this.attached = true; <ide> <ide> // Add the chart instance to the global namespace <ide> Chart.instances[me.id] = me; <ide> export default class Chart { <ide> Animator.listen(me, 'progress', onAnimationProgress); <ide> <ide> me._initialize(); <del> me.update(); <add> if (me.attached) { <add> me.update(); <add> } <ide> } <ide> <ide> /** <ide> export default class Chart { <ide> options.onResize(me, newSize); <ide> } <ide> <del> me.update('resize'); <add> // Only apply 'resize' mode if we are attached, else do a regular update. <add> me.update(me.attached && 'resize'); <ide> } <ide> } <ide> <ide> export default class Chart { <ide> }; <ide> <ide> if (Animator.has(me)) { <del> if (!Animator.running(me)) { <add> if (me.attached && !Animator.running(me)) { <ide> Animator.start(me); <ide> } <ide> } else { <ide> export default class Chart { <ide> bindEvents() { <ide> const me = this; <ide> const listeners = me._listeners; <add> const platform = me.platform; <add> <add> const _add = (type, listener) => { <add> platform.addEventListener(me, type, listener); <add> listeners[type] = listener; <add> }; <add> const _remove = (type, listener) => { <add> if (listeners[type]) { <add> platform.removeEventListener(me, type, listener); <add> delete listeners[type]; <add> } <add> }; <add> <ide> let listener = function(e) { <ide> me._eventHandler(e); <ide> }; <ide> <del> helpers.each(me.options.events, (type) => { <del> me.platform.addEventListener(me, type, listener); <del> listeners[type] = listener; <del> }); <add> helpers.each(me.options.events, (type) => _add(type, listener)); <ide> <ide> if (me.options.responsive) { <del> listener = function(width, height) { <add> listener = (width, height) => { <ide> if (me.canvas) { <ide> me.resize(false, width, height); <ide> } <ide> }; <ide> <del> me.platform.addEventListener(me, 'resize', listener); <del> listeners.resize = listener; <add> let detached; // eslint-disable-line prefer-const <add> const attached = () => { <add> _remove('attach', attached); <add> <add> me.resize(); <add> me.attached = true; <add> <add> _add('resize', listener); <add> _add('detach', detached); <add> }; <add> <add> detached = () => { <add> me.attached = false; <add> <add> _remove('resize', listener); <add> _add('attach', attached); <add> }; <add> <add> if (platform.isAttached(me.canvas)) { <add> attached(); <add> } else { <add> detached(); <add> } <add> } else { <add> me.attached = true; <ide> } <ide> } <ide> <ide><path>src/helpers/helpers.dom.js <ide> export function getRelativePosition(evt, chart) { <ide> }; <ide> } <ide> <add>function fallbackIfNotValid(measure, fallback) { <add> return typeof measure === 'number' ? measure : fallback; <add>} <add> <ide> export function getMaximumWidth(domNode) { <ide> const container = _getParentNode(domNode); <ide> if (!container) { <del> if (typeof domNode.clientWidth === 'number') { <del> return domNode.clientWidth; <del> } <del> return domNode.width; <add> return fallbackIfNotValid(domNode.clientWidth, domNode.width); <ide> } <ide> <ide> const clientWidth = container.clientWidth; <ide> export function getMaximumWidth(domNode) { <ide> export function getMaximumHeight(domNode) { <ide> const container = _getParentNode(domNode); <ide> if (!container) { <del> if (typeof domNode.clientHeight === 'number') { <del> return domNode.clientHeight; <del> } <del> return domNode.height; <add> return fallbackIfNotValid(domNode.clientHeight, domNode.height); <ide> } <ide> <ide> const clientHeight = container.clientHeight; <ide><path>src/platform/platform.base.js <ide> export default class BasePlatform { <ide> getDevicePixelRatio() { <ide> return 1; <ide> } <add> <add> /** <add> * @param {HTMLCanvasElement} canvas <add> * @returns {boolean} true if the canvas is attached to the platform, false if not. <add> */ <add> isAttached(canvas) { // eslint-disable-line no-unused-vars <add> return true; <add> } <ide> } <ide> <ide> /** <ide><path>src/platform/platform.dom.js <ide> function throttled(fn, thisArg) { <ide> }; <ide> } <ide> <del>/** <del> * Watch for resize of `element`. <del> * Calling `fn` is limited to once per animation frame <del> * @param {Element} element - The element to monitor <del> * @param {function} fn - Callback function to call when resized <del> */ <del>function watchForResize(element, fn) { <del> const resize = throttled((width, height) => { <del> const w = element.clientWidth; <del> fn(width, height); <del> if (w < element.clientWidth) { <del> // If the container size shrank during chart resize, let's assume <del> // scrollbar appeared. So we resize again with the scrollbar visible - <del> // effectively making chart smaller and the scrollbar hidden again. <del> // Because we are inside `throttled`, and currently `ticking`, scroll <del> // events are ignored during this whole 2 resize process. <del> // If we assumed wrong and something else happened, we are resizing <del> // twice in a frame (potential performance issue) <del> fn(); <del> } <del> }, window); <del> <del> // @ts-ignore until https://github.com/Microsoft/TypeScript/issues/28502 implemented <del> const observer = new ResizeObserver(entries => { <del> const entry = entries[0]; <del> resize(entry.contentRect.width, entry.contentRect.height); <del> }); <del> observer.observe(element); <del> return observer; <del>} <del> <del>/** <del> * Detect attachment of `element` or its direct `parent` to DOM <del> * @param {Element} element - The element to watch for <del> * @param {function} fn - Callback function to call when attachment is detected <del> * @return {MutationObserver} <del> */ <del>function watchForAttachment(element, fn) { <add>function createAttachObserver(chart, type, listener) { <add> const canvas = chart.canvas; <add> const container = canvas && _getParentNode(canvas); <add> const element = container || canvas; <ide> const observer = new MutationObserver(entries => { <ide> const parent = _getParentNode(element); <ide> entries.forEach(entry => { <ide> for (let i = 0; i < entry.addedNodes.length; i++) { <ide> const added = entry.addedNodes[i]; <ide> if (added === element || added === parent) { <del> fn(entry.target); <add> listener(entry.target); <ide> } <ide> } <ide> }); <ide> function watchForAttachment(element, fn) { <ide> return observer; <ide> } <ide> <del>/** <del> * Watch for detachment of `element` from its direct `parent`. <del> * @param {Element} element - The element to watch <del> * @param {function} fn - Callback function to call when detached. <del> * @return {MutationObserver=} <del> */ <del>function watchForDetachment(element, fn) { <del> const parent = _getParentNode(element); <del> if (!parent) { <add>function createDetachObserver(chart, type, listener) { <add> const canvas = chart.canvas; <add> const container = canvas && _getParentNode(canvas); <add> if (!container) { <ide> return; <ide> } <ide> const observer = new MutationObserver(entries => { <ide> entries.forEach(entry => { <ide> for (let i = 0; i < entry.removedNodes.length; i++) { <del> if (entry.removedNodes[i] === element) { <del> fn(); <add> if (entry.removedNodes[i] === canvas) { <add> listener(); <ide> break; <ide> } <ide> } <ide> }); <ide> }); <del> observer.observe(parent, {childList: true}); <add> observer.observe(container, {childList: true}); <ide> return observer; <ide> } <ide> <del>/** <del> * @param {{ [x: string]: any; resize?: any; detach?: MutationObserver; attach?: MutationObserver; }} proxies <del> * @param {string} type <del> */ <del>function removeObserver(proxies, type) { <del> const observer = proxies[type]; <add>function createResizeObserver(chart, type, listener) { <add> const canvas = chart.canvas; <add> const container = canvas && _getParentNode(canvas); <add> if (!container) { <add> return; <add> } <add> const resize = throttled((width, height) => { <add> const w = container.clientWidth; <add> listener(width, height); <add> if (w < container.clientWidth) { <add> // If the container size shrank during chart resize, let's assume <add> // scrollbar appeared. So we resize again with the scrollbar visible - <add> // effectively making chart smaller and the scrollbar hidden again. <add> // Because we are inside `throttled`, and currently `ticking`, scroll <add> // events are ignored during this whole 2 resize process. <add> // If we assumed wrong and something else happened, we are resizing <add> // twice in a frame (potential performance issue) <add> listener(); <add> } <add> }, window); <add> <add> // @ts-ignore until https://github.com/microsoft/TypeScript/issues/37861 implemented <add> const observer = new ResizeObserver(entries => { <add> const entry = entries[0]; <add> resize(entry.contentRect.width, entry.contentRect.height); <add> }); <add> observer.observe(container); <add> return observer; <add>} <add> <add>function releaseObserver(canvas, type, observer) { <ide> if (observer) { <ide> observer.disconnect(); <del> proxies[type] = undefined; <ide> } <ide> } <ide> <del>/** <del> * @param {{ resize?: any; detach?: MutationObserver; attach?: MutationObserver; }} proxies <del> */ <del>function unlistenForResize(proxies) { <del> removeObserver(proxies, 'attach'); <del> removeObserver(proxies, 'detach'); <del> removeObserver(proxies, 'resize'); <del>} <add>function createProxyAndListen(chart, type, listener) { <add> const canvas = chart.canvas; <add> const proxy = throttled((event) => { <add> // This case can occur if the chart is destroyed while waiting <add> // for the throttled function to occur. We prevent crashes by checking <add> // for a destroyed chart <add> if (chart.ctx !== null) { <add> listener(fromNativeEvent(event, chart)); <add> } <add> }, chart); <ide> <del>/** <del> * @param {HTMLCanvasElement} canvas <del> * @param {{ resize?: any; detach?: MutationObserver; attach?: MutationObserver; }} proxies <del> * @param {function} listener <del> */ <del>function listenForResize(canvas, proxies, listener) { <del> // Helper for recursing when canvas is detached from it's parent <del> const detached = () => listenForResize(canvas, proxies, listener); <del> <del> // First make sure all observers are removed <del> unlistenForResize(proxies); <del> // Then check if we are attached <del> const container = _getParentNode(canvas); <del> if (container) { <del> // The canvas is attached (or was immediately re-attached when called through `detached`) <del> proxies.resize = watchForResize(container, listener); <del> proxies.detach = watchForDetachment(canvas, detached); <del> } else { <del> // The canvas is detached <del> proxies.attach = watchForAttachment(canvas, () => { <del> // The canvas was attached. <del> removeObserver(proxies, 'attach'); <del> const parent = _getParentNode(canvas); <del> proxies.resize = watchForResize(parent, listener); <del> proxies.detach = watchForDetachment(canvas, detached); <del> }); <del> } <add> addListener(canvas, type, proxy); <add> <add> return proxy; <ide> } <ide> <ide> /** <ide> export default class DomPlatform extends BasePlatform { <ide> // Can have only one listener per type, so make sure previous is removed <ide> this.removeEventListener(chart, type); <ide> <del> const canvas = chart.canvas; <ide> const proxies = chart.$proxies || (chart.$proxies = {}); <del> if (type === 'resize') { <del> return listenForResize(canvas, proxies, listener); <del> } <del> <del> const proxy = proxies[type] = throttled((event) => { <del> // This case can occur if the chart is destroyed while waiting <del> // for the throttled function to occur. We prevent crashes by checking <del> // for a destroyed chart <del> if (chart.ctx !== null) { <del> listener(fromNativeEvent(event, chart)); <del> } <del> }, chart); <del> <del> addListener(canvas, type, proxy); <add> const handlers = { <add> attach: createAttachObserver, <add> detach: createDetachObserver, <add> resize: createResizeObserver <add> }; <add> const handler = handlers[type] || createProxyAndListen; <add> proxies[type] = handler(chart, type, listener); <ide> } <ide> <ide> <ide> export default class DomPlatform extends BasePlatform { <ide> removeEventListener(chart, type) { <ide> const canvas = chart.canvas; <ide> const proxies = chart.$proxies || (chart.$proxies = {}); <del> <del> if (type === 'resize') { <del> return unlistenForResize(proxies); <del> } <del> <ide> const proxy = proxies[type]; <add> <ide> if (!proxy) { <ide> return; <ide> } <ide> <del> removeListener(canvas, type, proxy); <add> const handlers = { <add> attach: releaseObserver, <add> detach: releaseObserver, <add> resize: releaseObserver <add> }; <add> const handler = handlers[type] || removeListener; <add> handler(canvas, type, proxy); <ide> proxies[type] = undefined; <ide> } <ide> <ide> getDevicePixelRatio() { <ide> return window.devicePixelRatio; <ide> } <add> <add> <add> /** <add> * @param {HTMLCanvasElement} canvas <add> */ <add> isAttached(canvas) { <add> const container = _getParentNode(canvas); <add> return !!(container && _getParentNode(container)); <add> } <ide> } <ide><path>test/specs/platform.dom.tests.js <add>import {DomPlatform} from '../../src/platform/platforms'; <add> <ide> describe('Platform.dom', function() { <ide> <ide> describe('context acquisition', function() { <ide> describe('Platform.dom', function() { <ide> }); <ide> }); <ide> }); <add> <add> describe('isAttached', function() { <add> it('should detect detached when canvas is attached to DOM', function() { <add> var platform = new DomPlatform(); <add> var canvas = document.createElement('canvas'); <add> var div = document.createElement('div'); <add> <add> expect(platform.isAttached(canvas)).toEqual(false); <add> div.appendChild(canvas); <add> expect(platform.isAttached(canvas)).toEqual(false); <add> document.body.appendChild(div); <add> <add> expect(platform.isAttached(canvas)).toEqual(true); <add> <add> div.removeChild(canvas); <add> expect(platform.isAttached(canvas)).toEqual(false); <add> document.body.removeChild(div); <add> expect(platform.isAttached(canvas)).toEqual(false); <add> }); <add> }); <ide> });
6
Javascript
Javascript
improve console logging to metro
76e10c4e8bc3e31eecf80b15bde29d133caaca1e
<ide><path>Libraries/Core/Devtools/logToConsole.js <ide> const getDevServer = require('./getDevServer'); <ide> let ID = 0; <ide> <ide> function logToConsole( <del> level: 'trace' | 'info' | 'warn' | 'log', <add> level: <add> | 'trace' <add> | 'info' <add> | 'warn' <add> | 'log' <add> | 'group' <add> | 'groupCollapsed' <add> | 'groupEnd' <add> | 'debug', <ide> data: Array<mixed>, <ide> ) { <ide> let body; <ide><path>Libraries/Core/setUpDeveloperTools.js <ide> if (__DEV__) { <ide> <ide> if (!Platform.isTesting) { <ide> const logToConsole = require('./Devtools/logToConsole'); <del> ['log', 'warn', 'info', 'trace'].forEach(level => { <add> [ <add> 'trace', <add> 'info', <add> 'warn', <add> 'log', <add> 'group', <add> 'groupCollapsed', <add> 'groupEnd', <add> 'debug', <add> ].forEach(level => { <ide> const originalFunction = console[level]; <ide> // $FlowFixMe Overwrite console methods <ide> console[level] = function(...args) {
2
Python
Python
remove unused function
7c42a178f67676467ca6e71d0628954a22396271
<ide><path>slim/train_image_classifier.py <ide> def _configure_optimizer(learning_rate): <ide> raise ValueError('Optimizer [%s] was not recognized', FLAGS.optimizer) <ide> return optimizer <ide> <del> <del>def _add_variables_summaries(learning_rate): <del> summaries = [] <del> for variable in slim.get_model_variables(): <del> summaries.append(tf.summary.histogram(variable.op.name, variable)) <del> summaries.append(tf.summary.scalar('training/Learning Rate', learning_rate)) <del> return summaries <del> <del> <ide> def _get_init_fn(): <ide> """Returns a function run by the chief worker to warm-start the training. <ide>
1
PHP
PHP
fix typo in docblock
4fe16c2997cfee9b46dea810dc04016c93002625
<ide><path>src/Illuminate/View/Component.php <ide> abstract class Component <ide> protected static $methodCache = []; <ide> <ide> /** <del> * That properties / methods that should not be exposed to the component. <add> * The properties / methods that should not be exposed to the component. <ide> * <ide> * @var array <ide> */
1
Java
Java
fix intermittent test failure in asynctests
38cf91922c0423fa8ffd541e9cc7f1d2cae87529
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/DefaultMvcResult.java <ide> <ide> import org.springframework.mock.web.MockHttpServletRequest; <ide> import org.springframework.mock.web.MockHttpServletResponse; <del>import org.springframework.web.context.request.async.WebAsyncManager; <del>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> import org.springframework.web.servlet.FlashMap; <ide> import org.springframework.web.servlet.HandlerInterceptor; <ide> import org.springframework.web.servlet.ModelAndView; <ide> class DefaultMvcResult implements MvcResult { <ide> <ide> private Exception resolvedException; <ide> <add> private Object asyncResult; <add> <ide> private CountDownLatch asyncResultLatch; <ide> <ide> <ide> public FlashMap getFlashMap() { <ide> return RequestContextUtils.getOutputFlashMap(mockRequest); <ide> } <ide> <del> public void setAsyncResultLatch(CountDownLatch asyncResultLatch) { <del> this.asyncResultLatch = asyncResultLatch; <add> public void setAsyncResult(Object asyncResult) { <add> this.asyncResult = asyncResult; <ide> } <ide> <ide> public Object getAsyncResult() { <ide> HttpServletRequest request = this.mockRequest; <ide> if (request.isAsyncStarted()) { <del> <del> long timeout = request.getAsyncContext().getTimeout(); <del> if (!awaitAsyncResult(timeout)) { <add> if (!awaitAsyncResult(request)) { <ide> throw new IllegalStateException( <del> "Gave up waiting on async result from [" + this.handler + "] to complete"); <del> } <del> <del> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.mockRequest); <del> if (asyncManager.hasConcurrentResult()) { <del> return asyncManager.getConcurrentResult(); <add> "Gave up waiting on async result from handler [" + this.handler + "] to complete"); <ide> } <ide> } <del> return null; <add> return this.asyncResult; <ide> } <ide> <del> private boolean awaitAsyncResult(long timeout) { <add> private boolean awaitAsyncResult(HttpServletRequest request) { <add> long timeout = request.getAsyncContext().getTimeout(); <ide> if (this.asyncResultLatch != null) { <ide> try { <ide> return this.asyncResultLatch.await(timeout, TimeUnit.MILLISECONDS); <ide> private boolean awaitAsyncResult(long timeout) { <ide> return true; <ide> } <ide> <add> public void setAsyncResultLatch(CountDownLatch asyncResultLatch) { <add> this.asyncResultLatch = asyncResultLatch; <add> } <add> <ide> } <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/TestDispatcherServlet.java <ide> protected void service(HttpServletRequest request, HttpServletResponse response) <ide> super.service(request, response); <ide> } <ide> <del> private CountDownLatch registerAsyncInterceptors(HttpServletRequest request) { <add> private CountDownLatch registerAsyncInterceptors(final HttpServletRequest servletRequest) { <ide> <ide> final CountDownLatch asyncResultLatch = new CountDownLatch(1); <ide> <del> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <add> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(servletRequest); <ide> <ide> asyncManager.registerCallableInterceptor(KEY, new CallableProcessingInterceptorAdapter() { <ide> public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object value) throws Exception { <add> getMvcResult(servletRequest).setAsyncResult(value); <ide> asyncResultLatch.countDown(); <ide> } <ide> }); <ide> asyncManager.registerDeferredResultInterceptor(KEY, new DeferredResultProcessingInterceptorAdapter() { <ide> public <T> void postProcess(NativeWebRequest request, DeferredResult<T> result, Object value) throws Exception { <add> getMvcResult(servletRequest).setAsyncResult(value); <ide> asyncResultLatch.countDown(); <ide> } <ide> });
2
PHP
PHP
fix closing div tag
51a013fbbf4d834216909d532d40dc4067a6810f
<ide><path>app/views/hello.php <ide> <div class="welcome"> <ide> <a href="http://laravel.com" title="Laravel PHP Framework"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIcAAACHCAYAAAA850oKAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoyNUVCMTdGOUJBNkExMUUyOTY3MkMyQjZGOTYyREVGMiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyNUVCMTdGQUJBNkExMUUyOTY3MkMyQjZGOTYyREVGMiI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjI1RUIxN0Y3QkE2QTExRTI5NjcyQzJCNkY5NjJERUYyIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjI1RUIxN0Y4QkE2QTExRTI5NjcyQzJCNkY5NjJERUYyIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+g6J7EAAAEL1JREFUeNrsXQmUFcUVrT8MKqJGjIKirIIQdlBcEISgIbhEjEYlLohGwYwL0eMSUKMeEsyBiCJBIrgcILjhwsG4YGIcHRCJggtuIAiKiYKKUeMumHvp96X9zPyu+tPV2697zjs9Z6Z//+p6d169evXqVU4Z4qtj+uyLy08hfSAdIS0g2yiHpOFryFrIq5CnIQ9vM/epJSYPyGkSohEuIyDnQNq7fk8tVkKmQKaBKJ/Vmxwgxmm4/BGyu+vbzOBdyGjIDJDkW2NygBS74DILcoTry8ziIcgwEOQDbXKAGO1weRTSxvVf5rEaMggEWRlIDiHGAkgz129lNcz0B0FW1EkOGUqedRajbC1Ib/8QU1FwwwxHjLIF9T4LBiK3FTnwy2G4HOX6qOywCfK5/Hw45NTvDSsSx1gF2cP1VWZBArwGeQnyik9WYyjZCA60xs9nQk6CdMPv/lcpHzzLESPTJODPa6DwTXV9CH9bg8vlIMlsOqeQB/OWg16qi3yWAQlMUClrJY4YycWnkBU2SVAnORgAcf2fGBJwkexlkVfk+maxELdtcuzj9FLeJChGjgmQU+RnBztkuAvyiPICjGuSRoK6kHdISZCLnB5DRw3kOJDhvSQ0Bnr+AS49OFWFdJefu8qfr4OM9hM3by3GivVwy/Lh4uw4iAESMLjZ1keAPBlaFfnYpWLlxn7PcsgDT8blr06foaIryPGSZSLsJP/93UTy1qBxCY/j7OcItHl+ITn4czXkEKfT0MCMq5EhkYBWvoMovquPEK1CbvMGSC+0+83CVdkuuDwPaeD0Ggo4fh+Kjn7ckAh7FZCA0gnSMKJ203HuW1s+x0RcLnB6DQ1vK2+t4sMAQjDeNEZ8g50T0O6bKmr55VXKS/5wCAe0AlM17ttbeWsaOyek3SO3IgcY/jEuFzudhooTYRlODbjnZsjSJDW6oo7fc2VuodNpqJgiy+K1Av+U3GcyVKaTySWHBEK4R2Wj02lo2JGhAhCkQRGCvI5LVdItBxv6Ai43Op2GioMhvy12A/p9pkpIvKki4O9XQNY7nYaKq2A9egfcQ+uxKtHkAIs/cs5p6GAwazYI0rhIv38i/sfXSbYcxCznnIYOJldNDPjHZCBqTKLJIc7pucqLuzuEhxGwHkcH3HMtZH6SLQcJwpD6X5w+Q8ctIMjuAf+Y3DKyLhZyoHF9NO+9HPKe02eo2BVym38jUS0EWS8E+TYOy3GDrP8HWY8Pg6ZhDiVhsPJiSsX6npvaJ8RBDmafn655/23KqxLjEC4m4B+0k4bl/lccPsc4SRrRcU6rnHMaOraT6e22Rfqe01ruRvskanI0VV7AS8c5fc45p1bADK6xAX3PwNjIqMlBjAJzdbcpkEgfOH2Gjouggx8HEOQOGd4jJQezjCZqWg+mko12ugwdnLXMBEGaBNx3vvJ2wUUa5zgSDRusO0eP2kEqEwQmB3EHvPLC619FSQ7iOhCkoYb12CRTsG+dPkNHYHKQ+H4XR02OjkHzbl8DGf+f5nRpBUWTgwSTIQ9GSQ6Cy8q7aT5jjHNOrWBHmd42CAgtDIe8EyU5uG3u9wbO6RinSyvoE+T4o//fV95uxU1RkYM4E6ztofkcJscucbq0giuhh/0DCPJP5VWZjowcm9ddNK2Hc07tgclBzD3dIYhEkEVRkYPoh0adqEmQxTK9dQgfOslB3ygvvP5RVOQgxku1QR1wfPzQ6dIKzoIehgQQZI3yiv9FRo6WkEs0rcf7zjm1iptBkD0CdDAHl+lRkYO4FI1qoXnvNOecWgOTg24tlhwk+I3ySktFQg4OK+MNnNNznR6tYXBQ/8pBOwyvfxkFOYihYGxfTYIwIeg2p0drCEwOgg5exOVCw+eukkkFQ/ctc/gSk+kn4/n76dS/xHOZI7JcJWfXeNbAHYkHQBdfBuhhLi51ObLUD49PqabgWW8XzqFN0BNyhvKCXkHWYz0axtS2Pzs9WgHreDCKHbT4Rn3RiuwpZKj2kaFoqQ1Ty0EwG3of2Q0XZD24LsDFuR5Ol1ZA3R0mEdJiemDxuM+CyFAfnyMPDhe/0/Q9uEu/yunQGrSSg6CHN0yJUSo5iPPQoA6aBFnknFMrYEyJ/gQjp41tfEGpVYuZDMSipronRzJyehxkJ6fTkvGW8ore0oF8AvKa7UrIpfgcfrBm5cM6N+J7mPc4yelYG8uFBCREDUs/Rj5m1ZMcTHLtInsqgshBK8XIaTen962wScIEJMKTtA5xlsSWgyAH1rcYPrcynKc0sta5aogvPUc6oNzB2MRi3zCxQJKG4yLDNrgcpLzjVX6ivF2QFfW1HASrD7aXDb86DWFZo1PLjAzso0W+YeKZoOBVBITgLjuG4rmKOwCyfVgOqR87STBmhOb9DNoMybhzuj7vK8gw8aJM6+MkA2c0rHXaVq7MUd1BLEVDGz6HPxizr6TL6zR0FC7XZ4gMa4QENTJEvBZ3g8THaylEoNRVB4RWo79NcijpmP460ytpOAvCdE4pGV72WYWawjWJmMhQIc7+YaJwVi7kpmseBBRU25RHhu5pkxzEUHTUXZovQ7ZWp4AIG2WWVeObVm5IQsNkb/OhItxju0stt3EKPEMVz+/lMsdw5e22s0aOtZCOkk+g83KslHxSwsjwucwk8sPEIrzPpwkhw15ChIFy3VPzo9XiDBdDE/EbtwvTIfWD2WJMKbxK834eHfYzcY7iwn+VVy0xP0wsARm+SggZfigWIW8dSj3ilVZ6tfKirHWBub8PQI63ZTmILyAd0MFvaXYAE1KujbDP3/VZBcoy2+ezGpCBs4dDxDIcJj5ELqTHU/nT1ZZz6/2Wcq041dQZc4B/bcNyKDFLrF91oub93BtzhkXndFWB87gyKeOXBJ/6CBkoByh7p3Ry2GCQa7aQIE+Gdf5JhPyzsk3dbViO70wZvvRJzU6id/14CN/Jd1nmswpPlLJUbZEMdPx6ilU4VGYUjSJuRhX6ZGpAOzl8LbVJjucl9rFJs+PuNLA2eXwtMwk6WwxDLww6ESkGQnT2OZBJOGyHkdne6KdlAe0eapMcxEg0YppmJ9LzZvCo2LY/zhqe9g0Ti3VnRhGSobVvakkL0SyB03Oegs1c4M+L3WSbHFxZbK+TUigdy9D6+AInqsYnS2TbX5LI0NTnQJIQbVU6EHhype0jylnjgxt8dVPkGVJvo7yEWA4TLyftaG851bm/b6jootIJ1l5/FP17b1yWg2CEcVBQEmxSIauXfX0zCp6VUqGyAcZ4utcVdqiMoAH00MdBDkwJGSqFAPlIJKd126psgs7xHVzKqG24tk0OloN6g9NLrgOgASsSSAYGmbr5HEgGoXZU5YM+MvRfYXNY4ZT1XQmsULjg459J8G83JcGHwDu381kGyq6qvEHd8eTs6rAsB8Pki8VxpHQPCOgwn6CrOJtRk6G5z4HktaVy8IM+FKsH0f/4oBTLwenoQt+08hn/AhWeQ9N8bMAzuNQ9xXZWlCTI9ldbFqw6Ov1rgQtvQ/LWvZjlMF2gWiZOZ/Mi91BpvUiskMmwvdqyYDVQviPndG0MrpCzvMPkQsuxUn0/1W1lCUpqrbykkWJglvUN9VkWlwWr/cWBHCikbOh0GwoYXufu/RdIDq7f14S1QIXnMXkn6PSFx/B9NQbP5JjYQ22JRPZTtWRLO4QGLmPsF7rphSLp+Vep4oEiOrOTgmL7vmc2Ecu2i9NbZLgl9EifFI0LqgmWjzrqPpNrLJc7fUWKX9kKA3MJPcin6A+LYLJiOV2cXocI57ehQ7b2LSj4NR3GtuIzcJcV09EmGTyT4d1RTmXRwdp0Twrbcvm9s5CCmdOFJwBwpsTEkyUGz71HeeUcHCyjMkQykGjdfbGGASq4qAg/8yflrWvogjkfRypfCr1DAi2HrFHkYw1UcKlrFEfDejxg8L3cm3uZU1+CyOFbo8gTokVI7WChki66WV6yKZgrvM2dCmMiR8RrFOeAHDcaEJXBttlOhRGRQ9Yo+qktq5c9VXRZT8w3bQeCfGzg43Ah8CCnRkvkkJLVeTIcpOJdo7gG5BhjYD32U97xpW6RzRI5kpTAy7A6M8bWGhDkVlxOd6oMH0lLlOX0dJzhZ1jG8hOnyuyTgzhZhgstwMqsw2WsU2V5kIP+g+mue4bhX3fqzD45iEOCzjMrsB5c5LvQqbM8yEGMlz0kugT5Gy7znUrLgxzMJjvb8DMXQL5xas0+OYgrZW+qrvXgoXfu8J8yIceuKuAs91pwtfKirQ4ZJwcxCtajlYH14ObgK5xqy4McDIz9wfAzTCl8zqk3++QgTANj3Hx1nlNvyaBT/0ia6kwYBcZAEK7Y3uH0rI2NEgpgqetm6L/Dk7bwFoSfo9FzdW+WOmNMCnIboGoHLWw1ZA7kvsJjUdJGDobIO+ucDOUjyJgSfJYsg/qmVb2bImtTtaIyZS/G+pgMjE02+MxEMZVtypwUi2WYnQNC/EfnA2mzHATrR7STKauu9TgGl/vLkBCsZnCXEOIt0w9XpvCFWSyeQ8UlBs7pXBDk78o7lSjrWCo+BAmxqj4PSqPl2GwMlHd0x2oD69FJeVWFGmSQEC/5fIjlYT20MqWdwfoc3E13vIH1eAUE4bpLVrZULhdC3G7r2LC0Wo48+qFjFhhYj51lartbSt+XlRlvFwthfVN52snBPba9TSoU4n05c5meMkLkfYglUX5xpUo3eDguz6idafAZZqvzsJleCX6vtXlCKK/4fyz/wLQcrBXaKMUE4Zy9vcnpCXhnFmZdmLD3eAdyr8QiFsVZr1V2Og6plM7dO8XkaK7MzpWjc/oUOmCWiv9kbOad3COEWBjncWJS453VBE+GHAFZQ8vB3e1HpXx4odXgZqh/G3RGM3FOoz4ZmyWs7hNCVMd5UrUU4uNe6FMgvyjoiwcqxbymnRxcWLsGMszAeqxD5zApaFIE7eP+33ky0/iHydqQJVJ0FwvBzeh1HT+6iJaDTt2zGZj3c4zeHx3/rEEnVcqMp5uF9vBUKWbEM3z9ENr1ZcyEaCFkICm6anykZ04+yCBKhwwQhON2X8NO4/01IX0/9/o+JLOMeXEfMSbJ2ccLITh86G44X4G2d8iTg1HD61U2cAJebI5hJ86sh3O6OWtKedHKebpHllkkBM+GOVwIcbTyosmmOB/vMTlPjkYSbNk9A+TgeksnvNwXFp1TzioekyHj/rjPtpdaJX3FsaSlaBJGaCDn+wI+eFZGrMdleLlxhh3MqstTAnwaOu+sJrRV1lRMpOgkhKAv0Sqkx56Gd9scVMwVsG9eBmYu+aktj0x/2/C/b6Z0th9MkuGZt3frJslYJgTjOkOlnT1DfvyDeMfv9F9Y9omRMSaItM0AQe7Ei/7SsOO5nH+uOG+sGHR7KUkyFgjBY8WOFUKwApONxPBVMtvbUCs5pCHtxHw2zQBBtI9MTxqgB5bfGiSOMisO2Ky7yuDhgMJjVHJ1NIwEmZ8BC/KC8o5M35gSQlAfB4qFOEFFc/YcLcbg2s7XyRVpKIeYGRnwQarw4lMTTop9ZOpJiXKdi0G64f5z3bTI4WMyGzwhxdPcDTI125AwQjT1OZa9I/56rgCPRp/MKHZTTvNFGAcZobw8iDRGUqeiI6oSQAhWXj5GCMFk56jzWRnLYarkreiPT4NuzpXwgvvKix0M+ZHylsyTng/CoFUvnlsWAyEaSH+dIsRoHNFXfyGO5qsyweC59UtNHvB/AQYAJxSvvrFB3mUAAAAASUVORK5CYII="></a> <ide> <h1>You have arrived.</h1> <del> <div> <add> </div> <ide> </body> <ide> </html>
1
Python
Python
use our own improperlyconfigured exception
384df480059d91d5319ded7d6fc52c23eb12a0c9
<ide><path>celery/backends/mongodb.py <ide> """MongoDB backend for celery.""" <ide> from datetime import datetime <ide> <del>from django.core.exceptions import ImproperlyConfigured <ide> from billiard.serialization import pickle <ide> try: <ide> import pymongo <ide> <ide> from celery import conf <ide> from celery import states <del>from celery.backends.base import BaseDictBackend <ide> from celery.loaders import load_settings <add>from celery.backends.base import BaseDictBackend <add>from celery.exceptions import ImproperlyConfigured <ide> <ide> <ide> class Bunch: <ide> class MongoBackend(BaseDictBackend): <ide> def __init__(self, *args, **kwargs): <ide> """Initialize MongoDB backend instance. <ide> <del> :raises django.core.exceptions.ImproperlyConfigured: if <add> :raises celery.exceptions.ImproperlyConfigured: if <ide> module :mod:`pymongo` is not available. <ide> <ide> """ <ide><path>celery/backends/pyredis.py <ide> import warnings <ide> <del>from django.core.exceptions import ImproperlyConfigured <ide> <del>from celery.backends.base import KeyValueStoreBackend <ide> from celery.loaders import load_settings <add>from celery.backends.base import KeyValueStoreBackend <add>from celery.exceptions import ImproperlyConfigured <ide> <ide> try: <ide> import redis <ide> class RedisBackend(KeyValueStoreBackend): <ide> <ide> The port to the Redis server. <ide> <del> Raises :class:`django.core.exceptions.ImproperlyConfigured` if <add> Raises :class:`celery.exceptions.ImproperlyConfigured` if <ide> :setting:`REDIS_HOST` or :setting:`REDIS_PORT` is not set. <ide> <ide> """ <ide><path>celery/backends/tyrant.py <ide> """celery.backends.tyrant""" <del>from django.core.exceptions import ImproperlyConfigured <ide> try: <ide> import pytyrant <ide> except ImportError: <ide> pytyrant = None <ide> <del>from celery.backends.base import KeyValueStoreBackend <ide> from celery.loaders import load_settings <add>from celery.backends.base import KeyValueStoreBackend <add>from celery.exceptions import ImproperlyConfigured <ide> <ide> <ide> class TyrantBackend(KeyValueStoreBackend): <ide> class TyrantBackend(KeyValueStoreBackend): <ide> def __init__(self, tyrant_host=None, tyrant_port=None): <ide> """Initialize Tokyo Tyrant backend instance. <ide> <del> Raises :class:`django.core.exceptions.ImproperlyConfigured` if <add> Raises :class:`celery.exceptions.ImproperlyConfigured` if <ide> :setting:`TT_HOST` or :setting:`TT_PORT` is not set. <ide> <ide> """ <ide><path>celery/exceptions.py <ide> """.strip() <ide> <ide> <add>class ImproperlyConfigured(Exception): <add> """Celery is somehow improperly configured.""" <add> <add> <ide> class NotRegistered(KeyError): <ide> """The task is not registered.""" <ide> <ide> def __init__(self, message, *args, **kwargs): <ide> <ide> class AlreadyRegistered(Exception): <ide> """The task is already registered.""" <add> pass <ide> <ide> <ide> class TimeoutError(Exception): <ide><path>celery/tests/test_backends/test_amqp.py <ide> import errno <ide> import unittest <ide> <del>from django.core.exceptions import ImproperlyConfigured <add>from celery.exceptions import ImproperlyConfigured <ide> <ide> from celery import states <ide> from celery.utils import gen_unique_id <ide><path>celery/tests/test_backends/test_redis.py <ide> import socket <ide> import unittest <ide> <del>from django.core.exceptions import ImproperlyConfigured <add>from celery.exceptions import ImproperlyConfigured <ide> <ide> from celery import states <ide> from celery.utils import gen_unique_id <ide><path>celery/tests/test_backends/test_tyrant.py <ide> import socket <ide> import unittest <ide> <del>from django.core.exceptions import ImproperlyConfigured <add>from celery.exceptions import ImproperlyConfigured <ide> <ide> from celery import states <ide> from celery.utils import gen_unique_id <ide><path>celery/tests/test_celery.py <ide> class TestInitFile(unittest.TestCase): <ide> <ide> def test_version(self): <ide> self.assertTrue(celery.VERSION) <del> self.assertEqual(len(celery.VERSION), 3) <add> self.assertTrue(len(celery.VERSION) >= 3) <ide> celery.VERSION = (0, 3, 0) <ide> self.assertFalse(celery.is_stable_release()) <ide> self.assertEqual(celery.__version__.count("."), 2)
8
Python
Python
add spacy.blank() loading function
7c7fac93372eb30445d2e36fa21631ce4937f046
<ide><path>spacy/__init__.py <ide> def load(name, **overrides): <ide> return util.load_model(name, **overrides) <ide> <ide> <add>def blank(name, **kwargs): <add> LangClass = util.get_lang_class(name) <add> return LangClass(**kwargs) <add> <add> <ide> def info(model=None, markdown=False): <ide> return cli_info(None, model, markdown)
1
Python
Python
fix naming conventions issue
f851ff39dfc2fb4729e7e96bcb462c0ec1c7deed
<ide><path>glances/glances.py <ide> def __update__(self): <ide> self.network.append(netstat) <ide> self.network_old = self.network_new <ide> <del> # DISK IO <add> # DISK I/O <ide> self.diskio = [] <ide> try: <ide> self.diskio_old <ide> def getProcessList(self, sortedby='auto'): <ide> sortedby = 'proc_size' <ide> # Auto selection <ide> # If global Mem > 70% sort by process size <del> # Else sort by cpu comsoption <add> # Else sort by CPU comsoption <ide> try: <ide> memtotal = (self.mem['used'] - self.mem['cache']) * \ <ide> 100 / self.mem['total'] <ide> class glancesScreen(): <ide> """ <ide> <ide> # By default the process list is automatically sorted <del> # If global CPU > WANRING => Sorted by process Cpu consomption <add> # If global CPU > WANRING => Sorted by process CPU consomption <ide> # If global used MEM > WARINING => Sorted by process size <ide> __process_sortedby = 'auto' <ide> <ide> def __catchKey(self): <ide> # 'a' > Sort process list automatically <ide> self.setProcessSortedBy('auto') <ide> elif ((self.pressedkey == 99) and psutil_get_cpu_percent_tag): <del> # 'c' > Sort process list by Cpu usage <add> # 'c' > Sort process list by CPU usage <ide> self.setProcessSortedBy('cpu_percent') <ide> elif ((self.pressedkey == 100) and psutil_disk_io_tag): <del> # 'n' > Enable/Disable diskio stats <add> # 'n' > Enable/Disable disk I/O stats <ide> self.diskio_tag = not self.diskio_tag <ide> elif ((self.pressedkey == 102) and psutil_fs_usage_tag): <ide> # 'n' > Enable/Disable fs stats <ide> def displayCpu(self, cpu): <ide> screen_y = self.screen.getmaxyx()[0] <ide> if ((screen_y > self.cpu_y + 5) <ide> and (screen_x > self.cpu_x + 18)): <del> self.term_window.addnstr(self.cpu_y, self.cpu_x, _("Cpu"), 8, \ <add> self.term_window.addnstr(self.cpu_y, self.cpu_x, _("CPU"), 8, \ <ide> self.title_color if self.hascolors else curses.A_UNDERLINE) <ide> <ide> if (not cpu): <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> and (screen_x > process_x + 49)): <ide> # Processes detail <ide> self.term_window.addnstr(self.process_y + 3, process_x, \ <del> _("Cpu %"), 5, \ <add> _("CPU %"), 5, \ <ide> curses.A_UNDERLINE \ <ide> if (self.getProcessSortedBy() == 'cpu_percent') else 0) <ide> self.term_window.addnstr(self.process_y + 3, process_x + 7, \ <ide> def displayHelp(self): <ide> self.term_window.addnstr(self.help_y + 10, self.help_x, \ <ide> _("p") + "\t" + _("Sort process list by name"), 79) <ide> self.term_window.addnstr(self.help_y + 11, self.help_x, \ <del> _("d") + "\t" + _("Enable/Disable disk IO stats \ <add> _("d") + "\t" + _("Enable/Disable disk I/O stats \ <ide> (need PsUtil v0.4.0 or higher)"), \ <ide> 79, \ <ide> self.ifCRITICAL_color2 if not psutil_disk_io_tag else 0) <ide> def printVersion(): <ide> <ide> def printSyntax(): <ide> printVersion() <del> print _("Usage: glances.py [-f file] [-o output] [-t sec] [-h] [-v]") <add> print _("Usage: glances [-f file] [-o output] [-t sec] [-h] [-v]") <ide> print "" <ide> print _("\t-f file:\t\tSet the output folder (HTML) or file (CSV)") <ide> print _("\t-h:\t\tDisplay the syntax and exit") <ide> def printSyntax(): <ide> print _("'a' to set the automatic mode. \ <ide> The processes are sorted automatically") <ide> print _("'c' to sort the processes list by CPU consumption") <del> print _("'d' to disable or enable the disk IO stats") <add> print _("'d' to disable or enable the disk I/O stats") <ide> print _("'f' to disable or enable the file system stats") <ide> print _("'h' to hide or show the help message") <ide> print _("'l' to hide or show the logs messages")
1
Javascript
Javascript
remove excessive license boilerplate
683e09603e3418ed13333bac05876cb7d52453f5
<ide><path>lib/process.js <del>// Copyright io.js 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> <ide> 'use strict'; <ide> <ide> // Re-export process as a native module
1
Javascript
Javascript
fix unit tests
57e3a67f628719487317db8564a9c71742f936de
<ide><path>test/unit/router.test.js <ide> /* global describe, it, expect */ <ide> import Router from '../../dist/lib/router/router' <ide> <add>class PageLoader { <add> constructor (options = {}) { <add> this.options = options <add> this.loaded = {} <add> } <add> <add> loadPage (route) { <add> this.loaded[route] = true <add> <add> if (this.options.delay) { <add> return new Promise((resolve) => setTimeout(resolve, this.options.delay)) <add> } <add> } <add>} <add> <ide> describe('Router', () => { <ide> const request = { clone: () => null } <ide> describe('.prefetch()', () => { <ide> it('should prefetch a given page', async () => { <del> const router = new Router('/', {}) <del> const promise = Promise.resolve(request) <del> const route = 'routex' <del> router.doFetchRoute = (r) => { <del> expect(r).toBe(route) <del> return promise <del> } <add> const pageLoader = new PageLoader() <add> const router = new Router('/', {}, '/', { pageLoader }) <add> const route = '/routex' <ide> await router.prefetch(route) <ide> <del> expect(router.fetchingRoutes[route]).toBe(promise) <del> }) <del> <del> it('should stop if it\'s prefetching already', async () => { <del> const router = new Router('/', {}) <del> const route = 'routex' <del> router.fetchingRoutes[route] = Promise.resolve(request) <del> router.doFetchRoute = () => { throw new Error('Should not happen') } <del> await router.prefetch(route) <add> expect(pageLoader.loaded['/routex']).toBeTruthy() <ide> }) <ide> <ide> it('should only run two jobs at a time', async () => { <del> const router = new Router('/', {}) <del> let count = 0 <del> <del> router.doFetchRoute = () => { <del> count++ <del> return new Promise((resolve) => {}) <del> } <add> // delay loading pages for an hour <add> const pageLoader = new PageLoader({ delay: 1000 * 3600 }) <add> const router = new Router('/', {}, '/', { pageLoader }) <ide> <ide> router.prefetch('route1') <ide> router.prefetch('route2') <ide> router.prefetch('route3') <ide> router.prefetch('route4') <ide> <add> // Wait for a bit <ide> await new Promise((resolve) => setTimeout(resolve, 50)) <ide> <del> expect(count).toBe(2) <del> expect(Object.keys(router.fetchingRoutes)).toEqual(['route1', 'route2']) <add> expect(Object.keys(pageLoader.loaded).length).toBe(2) <add> expect(Object.keys(pageLoader.loaded)).toEqual(['route1', 'route2']) <ide> }) <ide> <ide> it('should run all the jobs', async () => { <del> const router = new Router('/', {}) <add> const pageLoader = new PageLoader() <add> const router = new Router('/', {}, '/', { pageLoader }) <ide> const routes = ['route1', 'route2', 'route3', 'route4'] <ide> <ide> router.doFetchRoute = () => Promise.resolve(request) <ide> describe('Router', () => { <ide> await router.prefetch(routes[2]) <ide> await router.prefetch(routes[3]) <ide> <del> expect(Object.keys(router.fetchingRoutes)).toEqual(routes) <add> expect(Object.keys(pageLoader.loaded)).toEqual(routes) <ide> }) <ide> }) <ide> })
1
Text
Text
add devdocs link for offline documentation
8afd770a1abe06aabda3e6b44cad2755c8076ab7
<ide><path>README.md <ide> If you enjoyed my course, consider supporting Egghead by [buying a subscription] <ide> <ide> For PDF, ePub, and MOBI exports for offline reading, and instructions on how to create them, please see: [paulkogel/redux-offline-docs](https://github.com/paulkogel/redux-offline-docs). <ide> <add>For Offline docs, please see: [devdocs](http://devdocs.io/redux/) <add> <ide> ### Examples <ide> <ide> * [Counter Vanilla](http://redux.js.org/docs/introduction/Examples.html#counter-vanilla) ([source](https://github.com/reactjs/redux/tree/master/examples/counter-vanilla))
1
Javascript
Javascript
use addgroup for adding draw calls in test
6d5d6f8b74a23f3deffb25b0d014b495d6b36b13
<ide><path>test/unit/geometry/EdgesGeometry.js <ide> function addDrawCalls ( geometry ) { <ide> var start = i * 3; <ide> var count = 3; <ide> <del> geometry.addDrawCall ( start, count, offset ); <del> <add> geometry.addGroup( start, count ); <ide> } <ide> <ide> return geometry;
1
Go
Go
fix race in set running
77936ba1a1ff404b75ae8a34c6d4e280c23d9144
<ide><path>container.go <ide> func (container *Container) Start() (err error) { <ide> return err <ide> } <ide> container.waitLock = make(chan struct{}) <add> container.State.SetRunning(0) <ide> go container.monitor() <ide> <ide> if container.Config.Tty { <ide> func (container *Container) Start() (err error) { <ide> return err <ide> } <ide> <del> container.State.SetRunning(container.process.Pid()) <add> // TODO: @crosbymichael @creack <add> // find a way to update this <add> // container.State.SetRunning(container.process.Pid()) <ide> container.ToDisk() <ide> return nil <ide> } <ide> func (container *Container) monitor() { <ide> exitCode := container.process.GetExitCode() <ide> container.State.SetStopped(exitCode) <ide> <add> close(container.waitLock) <add> <ide> if err := container.ToDisk(); err != nil { <ide> // FIXME: there is a race condition here which causes this to fail during the unit tests. <ide> // If another goroutine was waiting for Wait() to return before removing the container's root <ide> func (container *Container) monitor() { <ide> // FIXME: why are we serializing running state to disk in the first place? <ide> //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err) <ide> } <del> close(container.waitLock) <ide> } <ide> <ide> func (container *Container) cleanup() { <ide><path>execdriver/lxc/driver.go <ide> func (d *driver) Wait(id string, duration time.Duration) error { <ide> func (d *driver) kill(c *execdriver.Process, sig int) error { <ide> output, err := exec.Command("lxc-kill", "-n", c.ID, strconv.Itoa(sig)).CombinedOutput() <ide> if err != nil { <del> fmt.Printf("--->%s\n", output) <ide> return fmt.Errorf("Err: %s Output: %s", err, output) <ide> } <ide> return nil
2
Ruby
Ruby
avoid call to array#first
dd4e81df86a119a32d52396c4ef856c856b7965a
<ide><path>activesupport/lib/active_support/notifications/fanout.rb <ide> def initialize(pattern, delegate) <ide> @delegate = delegate <ide> end <ide> <del> def publish(*args) <del> return unless subscribed_to?(args.first) <del> @delegate.call(*args) <add> def publish(message, *args) <add> return unless subscribed_to?(message) <add> @delegate.call(message, *args) <ide> true <ide> end <ide>
1
Text
Text
update url for issue
6fcae83036970dd2aad73127da6cbd0d2becb333
<ide><path>CONTRIBUTING.md <ide> A great way to contribute to the project is to send a detailed report when you <ide> encounter an issue. We always appreciate a well-written, thorough bug report, <ide> and will thank you for it! <ide> <del>Check that [our issue database](https://github.com/docker/docker/issues) <add>Check that [our issue database](https://github.com/moby/moby/issues) <ide> doesn't already include that problem or suggestion before submitting an issue. <ide> If you find a match, you can use the "subscribe" button to get notified on <ide> updates. Do *not* leave random "+1" or "I have this too" comments, as they <ide> This section gives the experienced contributor some tips and guidelines. <ide> <ide> Not sure if that typo is worth a pull request? Found a bug and know how to fix <ide> it? Do it! We will appreciate it. Any significant improvement should be <del>documented as [a GitHub issue](https://github.com/docker/docker/issues) before <add>documented as [a GitHub issue](https://github.com/moby/moby/issues) before <ide> anybody starts working on it. <ide> <ide> We are always thrilled to receive pull requests. We do our best to process them
1
Mixed
Ruby
stringify database configurations
63c4e9765b53ae1f8b4674c45012295f873a40be
<ide><path>activerecord/CHANGELOG.md <add>* Allow `ActiveRecord::Base.configurations=` to be set with a symbolized hash. <add> <add> *Gannon McGibbon* <add> <ide> * Don't update counter cache unless the record is actually saved. <ide> <ide> Fixes #31493, #33113, #33117. <ide><path>activerecord/lib/active_record/database_configurations.rb <ide> def build_configs(configs) <ide> return configs.configurations if configs.is_a?(DatabaseConfigurations) <ide> <ide> build_db_config = configs.each_pair.flat_map do |env_name, config| <del> walk_configs(env_name, "primary", config) <add> walk_configs(env_name.to_s, "primary", config) <ide> end.compact <ide> <ide> if url = ENV["DATABASE_URL"] <ide> def walk_configs(env_name, spec_name, config) <ide> when String <ide> build_db_config_from_string(env_name, spec_name, config) <ide> when Hash <del> build_db_config_from_hash(env_name, spec_name, config) <add> build_db_config_from_hash(env_name, spec_name, config.stringify_keys) <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/connection_adapters/connection_handler_test.rb <ide> def test_establish_connection_using_top_level_key_in_two_level_config <ide> ActiveRecord::Base.configurations = @prev_configs <ide> end <ide> <add> def test_symbolized_configurations_assignment <add> @prev_configs = ActiveRecord::Base.configurations <add> config = { <add> development: { <add> primary: { <add> adapter: "sqlite3", <add> database: "db/development.sqlite3", <add> }, <add> }, <add> test: { <add> primary: { <add> adapter: "sqlite3", <add> database: "db/test.sqlite3", <add> }, <add> }, <add> } <add> ActiveRecord::Base.configurations = config <add> ActiveRecord::Base.configurations.configs_for.each do |config| <add> assert_instance_of ActiveRecord::DatabaseConfigurations::HashConfig, config <add> end <add> ensure <add> ActiveRecord::Base.configurations = @prev_configs <add> end <add> <ide> def test_retrieve_connection <ide> assert @handler.retrieve_connection(@spec_name) <ide> end
3
Text
Text
add f3n67u to collaborators
dffcfdde34189a257692c2b80d9b03ee71486deb
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Evan Lucas** <<evanlucas@me.com>> (he/him) <ide> * [fhinkel](https://github.com/fhinkel) - <ide> **Franziska Hinkelmann** <<franziska.hinkelmann@gmail.com>> (she/her) <add>* [F3n67u](https://github.com/F3n67u) - <add> **Feng Yu** <<F3n67u@outlook.com>> (he/him) <ide> * [Flarna](https://github.com/Flarna) - <ide> **Gerhard Stöbich** <<deb2001-github@yahoo.de>> (he/they) <ide> * [gabrielschulhof](https://github.com/gabrielschulhof) -
1
Go
Go
switch node management tests to api types
22b34d64496c9b6ebae5e2b4a98ecd9a172cc557
<ide><path>integration-cli/check_test.go <ide> import ( <ide> <ide> "github.com/docker/docker/cliconfig" <ide> "github.com/docker/docker/pkg/reexec" <add> "github.com/docker/engine-api/types/swarm" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func (s *DockerSwarmSuite) AddDaemon(c *check.C, joinSwarm, manager bool) *Swarm <ide> <ide> if joinSwarm == true { <ide> if len(s.daemons) > 0 { <del> c.Assert(d.Join(s.daemons[0].listenAddr, "", "", manager), check.IsNil) <add> c.Assert(d.Join(swarm.JoinRequest{ <add> RemoteAddrs: []string{s.daemons[0].listenAddr}, <add> Manager: manager}), check.IsNil) <ide> } else { <del> aa := make(map[string]bool) <del> aa["worker"] = true <del> aa["manager"] = true <del> c.Assert(d.Init(aa, ""), check.IsNil) <add> c.Assert(d.Init(swarm.InitRequest{ <add> Spec: swarm.Spec{ <add> AcceptancePolicy: autoAcceptPolicy, <add> }, <add> }), check.IsNil) <ide> } <ide> } <ide> <ide><path>integration-cli/daemon_swarm.go <ide> type SwarmDaemon struct { <ide> listenAddr string <ide> } <ide> <del>// Init initializes a new swarm cluster. <del>func (d *SwarmDaemon) Init(autoAccept map[string]bool, secret string) error { <del> req := swarm.InitRequest{ <del> ListenAddr: d.listenAddr, <del> } <del> for _, role := range []swarm.NodeRole{swarm.NodeRoleManager, swarm.NodeRoleWorker} { <del> policy := swarm.Policy{ <del> Role: role, <del> Autoaccept: autoAccept[strings.ToLower(string(role))], <del> } <del> <del> if secret != "" { <del> policy.Secret = &secret <del> } <add>// default policy in tests is allow-all <add>var autoAcceptPolicy = swarm.AcceptancePolicy{ <add> Policies: []swarm.Policy{ <add> {Role: swarm.NodeRoleWorker, Autoaccept: true}, <add> {Role: swarm.NodeRoleManager, Autoaccept: true}, <add> }, <add>} <ide> <del> req.Spec.AcceptancePolicy.Policies = append(req.Spec.AcceptancePolicy.Policies, policy) <add>// Init initializes a new swarm cluster. <add>func (d *SwarmDaemon) Init(req swarm.InitRequest) error { <add> if req.ListenAddr == "" { <add> req.ListenAddr = d.listenAddr <ide> } <ide> status, out, err := d.SockRequest("POST", "/swarm/init", req) <ide> if status != http.StatusOK { <ide> func (d *SwarmDaemon) Init(autoAccept map[string]bool, secret string) error { <ide> return nil <ide> } <ide> <del>// Join joins a current daemon with existing cluster. <del>func (d *SwarmDaemon) Join(remoteAddr, secret, cahash string, manager bool) error { <del> req := swarm.JoinRequest{ <del> ListenAddr: d.listenAddr, <del> RemoteAddrs: []string{remoteAddr}, <del> Manager: manager, <del> CACertHash: cahash, <del> } <del> <del> if secret != "" { <del> req.Secret = secret <add>// Join joins a daemon to an existing cluster. <add>func (d *SwarmDaemon) Join(req swarm.JoinRequest) error { <add> if req.ListenAddr == "" { <add> req.ListenAddr = d.listenAddr <ide> } <ide> status, out, err := d.SockRequest("POST", "/swarm/join", req) <ide> if status != http.StatusOK { <ide><path>integration-cli/docker_api_swarm_test.go <ide> func (s *DockerSwarmSuite) TestApiSwarmInit(c *check.C) { <ide> c.Assert(info.ControlAvailable, checker.Equals, false) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) <ide> <del> c.Assert(d2.Join(d1.listenAddr, "", "", false), checker.IsNil) <add> c.Assert(d2.Join(swarm.JoinRequest{RemoteAddrs: []string{d1.listenAddr}}), checker.IsNil) <ide> <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <ide> func (s *DockerSwarmSuite) TestApiSwarmManualAcceptanceSecret(c *check.C) { <ide> <ide> func (s *DockerSwarmSuite) testAPISwarmManualAcceptance(c *check.C, secret string) { <ide> d1 := s.AddDaemon(c, false, false) <del> c.Assert(d1.Init(map[string]bool{}, secret), checker.IsNil) <add> c.Assert(d1.Init(swarm.InitRequest{ <add> Spec: swarm.Spec{ <add> AcceptancePolicy: swarm.AcceptancePolicy{ <add> Policies: []swarm.Policy{ <add> {Role: swarm.NodeRoleWorker, Secret: &secret}, <add> {Role: swarm.NodeRoleManager, Secret: &secret}, <add> }, <add> }, <add> }, <add> }), checker.IsNil) <ide> <ide> d2 := s.AddDaemon(c, false, false) <del> err := d2.Join(d1.listenAddr, "", "", false) <add> err := d2.Join(swarm.JoinRequest{RemoteAddrs: []string{d1.listenAddr}}) <ide> c.Assert(err, checker.NotNil) <ide> if secret == "" { <ide> c.Assert(err.Error(), checker.Contains, "needs to be accepted") <ide> func (s *DockerSwarmSuite) testAPISwarmManualAcceptance(c *check.C, secret strin <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) <ide> } <ide> d3 := s.AddDaemon(c, false, false) <del> c.Assert(d3.Join(d1.listenAddr, secret, "", false), checker.NotNil) <add> c.Assert(d3.Join(swarm.JoinRequest{Secret: secret, RemoteAddrs: []string{d1.listenAddr}}), checker.NotNil) <ide> info, err := d3.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStatePending) <ide> func (s *DockerSwarmSuite) testAPISwarmManualAcceptance(c *check.C, secret strin <ide> <ide> func (s *DockerSwarmSuite) TestApiSwarmSecretAcceptance(c *check.C) { <ide> d1 := s.AddDaemon(c, false, false) <del> aa := make(map[string]bool) <del> aa["worker"] = true <del> c.Assert(d1.Init(aa, "foobar"), checker.IsNil) <add> secret := "foobar" <add> c.Assert(d1.Init(swarm.InitRequest{ <add> Spec: swarm.Spec{ <add> AcceptancePolicy: swarm.AcceptancePolicy{ <add> Policies: []swarm.Policy{ <add> {Role: swarm.NodeRoleWorker, Autoaccept: true, Secret: &secret}, <add> {Role: swarm.NodeRoleManager, Secret: &secret}, <add> }, <add> }, <add> }, <add> }), checker.IsNil) <ide> <ide> d2 := s.AddDaemon(c, false, false) <del> err := d2.Join(d1.listenAddr, "", "", false) <add> err := d2.Join(swarm.JoinRequest{RemoteAddrs: []string{d1.listenAddr}}) <ide> c.Assert(err, checker.NotNil) <ide> c.Assert(err.Error(), checker.Contains, "secret token is necessary") <ide> info, err := d2.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) <ide> <del> err = d2.Join(d1.listenAddr, "foobaz", "", false) <add> err = d2.Join(swarm.JoinRequest{Secret: "foobaz", RemoteAddrs: []string{d1.listenAddr}}) <ide> c.Assert(err, checker.NotNil) <ide> c.Assert(err.Error(), checker.Contains, "secret token is necessary") <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) <ide> <del> c.Assert(d2.Join(d1.listenAddr, "foobar", "", false), checker.IsNil) <add> c.Assert(d2.Join(swarm.JoinRequest{Secret: "foobar", RemoteAddrs: []string{d1.listenAddr}}), checker.IsNil) <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> func (s *DockerSwarmSuite) TestApiSwarmSecretAcceptance(c *check.C) { <ide> } <ide> }) <ide> <del> err = d2.Join(d1.listenAddr, "foobar", "", false) <add> err = d2.Join(swarm.JoinRequest{Secret: "foobar", RemoteAddrs: []string{d1.listenAddr}}) <ide> c.Assert(err, checker.NotNil) <ide> c.Assert(err.Error(), checker.Contains, "secret token is necessary") <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) <ide> <del> c.Assert(d2.Join(d1.listenAddr, "foobaz", "", false), checker.IsNil) <add> c.Assert(d2.Join(swarm.JoinRequest{Secret: "foobaz", RemoteAddrs: []string{d1.listenAddr}}), checker.IsNil) <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> func (s *DockerSwarmSuite) TestApiSwarmSecretAcceptance(c *check.C) { <ide> } <ide> }) <ide> <del> err = d2.Join(d1.listenAddr, "", "", false) <add> err = d2.Join(swarm.JoinRequest{RemoteAddrs: []string{d1.listenAddr}}) <ide> c.Assert(err, checker.NotNil) <ide> c.Assert(err.Error(), checker.Contains, "secret token is necessary") <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) <ide> <del> c.Assert(d2.Join(d1.listenAddr, "foobaz", "", false), checker.IsNil) <add> c.Assert(d2.Join(swarm.JoinRequest{Secret: "foobaz", RemoteAddrs: []string{d1.listenAddr}}), checker.IsNil) <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> func (s *DockerSwarmSuite) TestApiSwarmSecretAcceptance(c *check.C) { <ide> } <ide> }) <ide> <del> c.Assert(d2.Join(d1.listenAddr, "", "", false), checker.IsNil) <add> c.Assert(d2.Join(swarm.JoinRequest{RemoteAddrs: []string{d1.listenAddr}}), checker.IsNil) <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> func (s *DockerSwarmSuite) TestApiSwarmSecretAcceptance(c *check.C) { <ide> func (s *DockerSwarmSuite) TestApiSwarmCAHash(c *check.C) { <ide> d1 := s.AddDaemon(c, true, true) <ide> d2 := s.AddDaemon(c, false, false) <del> err := d2.Join(d1.listenAddr, "", "foobar", false) <add> err := d2.Join(swarm.JoinRequest{CACertHash: "foobar", RemoteAddrs: []string{d1.listenAddr}}) <ide> c.Assert(err, checker.NotNil) <ide> c.Assert(err.Error(), checker.Contains, "invalid checksum digest format") <ide> <ide> c.Assert(len(d1.CACertHash), checker.GreaterThan, 0) <del> c.Assert(d2.Join(d1.listenAddr, "", d1.CACertHash, false), checker.IsNil) <add> c.Assert(d2.Join(swarm.JoinRequest{CACertHash: d1.CACertHash, RemoteAddrs: []string{d1.listenAddr}}), checker.IsNil) <ide> } <ide> <ide> func (s *DockerSwarmSuite) TestApiSwarmPromoteDemote(c *check.C) { <ide> d1 := s.AddDaemon(c, false, false) <del> c.Assert(d1.Init(map[string]bool{"worker": true}, ""), checker.IsNil) <add> c.Assert(d1.Init(swarm.InitRequest{ <add> Spec: swarm.Spec{ <add> AcceptancePolicy: swarm.AcceptancePolicy{ <add> Policies: []swarm.Policy{ <add> {Role: swarm.NodeRoleWorker, Autoaccept: true}, <add> {Role: swarm.NodeRoleManager}, <add> }, <add> }, <add> }, <add> }), checker.IsNil) <ide> d2 := s.AddDaemon(c, true, false) <ide> <ide> info, err := d2.info() <ide> func (s *DockerSwarmSuite) TestApiSwarmLeaveOnPendingJoin(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> id = strings.TrimSpace(id) <ide> <del> go d2.Join("nosuchhost:1234", "", "", false) // will block on pending state <add> go d2.Join(swarm.JoinRequest{ <add> RemoteAddrs: []string{"nosuchhost:1234"}, <add> }) // will block on pending state <ide> <ide> for i := 0; ; i++ { <ide> info, err := d2.info() <ide> func (s *DockerSwarmSuite) TestApiSwarmLeaveOnPendingJoin(c *check.C) { <ide> // #23705 <ide> func (s *DockerSwarmSuite) TestApiSwarmRestoreOnPendingJoin(c *check.C) { <ide> d := s.AddDaemon(c, false, false) <del> go d.Join("nosuchhost:1234", "", "", false) // will block on pending state <add> go d.Join(swarm.JoinRequest{ <add> RemoteAddrs: []string{"nosuchhost:1234"}, <add> }) // will block on pending state <ide> <ide> for i := 0; ; i++ { <ide> info, err := d.info()
3
Text
Text
use rails instead of rake
33e202d3ae8dfa3aa978a09944030622832e6e15
<ide><path>actionpack/CHANGELOG.md <ide> <ide> ## Rails 5.0.0.beta2 (February 01, 2016) ## <ide> <del>* Add `-g` and `-c` options to `bin/rake routes`. These options return the url `name`, `verb` and <add>* Add `-g` and `-c` options to `bin/rails routes`. These options return the url `name`, `verb` and <ide> `path` field that match the pattern or match a specific controller. <ide> <del> Deprecate `CONTROLLER` env variable in `bin/rake routes`. <add> Deprecate `CONTROLLER` env variable in `bin/rails routes`. <ide> <ide> See #18902. <ide> <ide><path>activerecord/CHANGELOG.md <ide> <ide> *Ben Murphy*, *Matthew Draper* <ide> <del>* `bin/rake db:migrate` uses <add>* `bin/rails db:migrate` uses <ide> `ActiveRecord::Tasks::DatabaseTasks.migrations_paths` instead of <ide> `Migrator.migrations_paths`. <ide>
2
PHP
PHP
remove unused property
6838dd332d9232278bf5731b080cd36bb5cac0d5
<ide><path>src/Utility/Inflector.php <ide> class Inflector <ide> 'pokemon', 'proceedings', 'research', 'sea[- ]bass', 'series', 'species', 'weather', <ide> ]; <ide> <del> /** <del> * Default map of accented and special characters to ASCII characters <del> * <del> * @var array <del> */ <del> protected static $_transliteration = [ <del> 'ä' => 'ae', <del> 'æ' => 'ae', <del> 'ǽ' => 'ae', <del> 'ö' => 'oe', <del> 'œ' => 'oe', <del> 'ü' => 'ue', <del> 'Ä' => 'Ae', <del> 'Ü' => 'Ue', <del> 'Ö' => 'Oe', <del> 'À' => 'A', <del> 'Á' => 'A', <del> 'Â' => 'A', <del> 'Ã' => 'A', <del> 'Å' => 'A', <del> 'Ǻ' => 'A', <del> 'Ā' => 'A', <del> 'Ă' => 'A', <del> 'Ą' => 'A', <del> 'Ǎ' => 'A', <del> 'à' => 'a', <del> 'á' => 'a', <del> 'â' => 'a', <del> 'ã' => 'a', <del> 'å' => 'a', <del> 'ǻ' => 'a', <del> 'ā' => 'a', <del> 'ă' => 'a', <del> 'ą' => 'a', <del> 'ǎ' => 'a', <del> 'ª' => 'a', <del> 'Ç' => 'C', <del> 'Ć' => 'C', <del> 'Ĉ' => 'C', <del> 'Ċ' => 'C', <del> 'Č' => 'C', <del> 'ç' => 'c', <del> 'ć' => 'c', <del> 'ĉ' => 'c', <del> 'ċ' => 'c', <del> 'č' => 'c', <del> 'Ð' => 'D', <del> 'Ď' => 'D', <del> 'Đ' => 'D', <del> 'ð' => 'd', <del> 'ď' => 'd', <del> 'đ' => 'd', <del> 'È' => 'E', <del> 'É' => 'E', <del> 'Ê' => 'E', <del> 'Ë' => 'E', <del> 'Ē' => 'E', <del> 'Ĕ' => 'E', <del> 'Ė' => 'E', <del> 'Ę' => 'E', <del> 'Ě' => 'E', <del> 'è' => 'e', <del> 'é' => 'e', <del> 'ê' => 'e', <del> 'ë' => 'e', <del> 'ē' => 'e', <del> 'ĕ' => 'e', <del> 'ė' => 'e', <del> 'ę' => 'e', <del> 'ě' => 'e', <del> 'Ĝ' => 'G', <del> 'Ğ' => 'G', <del> 'Ġ' => 'G', <del> 'Ģ' => 'G', <del> 'Ґ' => 'G', <del> 'ĝ' => 'g', <del> 'ğ' => 'g', <del> 'ġ' => 'g', <del> 'ģ' => 'g', <del> 'ґ' => 'g', <del> 'Ĥ' => 'H', <del> 'Ħ' => 'H', <del> 'ĥ' => 'h', <del> 'ħ' => 'h', <del> 'І' => 'I', <del> 'Ì' => 'I', <del> 'Í' => 'I', <del> 'Î' => 'I', <del> 'Ї' => 'Yi', <del> 'Ï' => 'I', <del> 'Ĩ' => 'I', <del> 'Ī' => 'I', <del> 'Ĭ' => 'I', <del> 'Ǐ' => 'I', <del> 'Į' => 'I', <del> 'İ' => 'I', <del> 'і' => 'i', <del> 'ì' => 'i', <del> 'í' => 'i', <del> 'î' => 'i', <del> 'ï' => 'i', <del> 'ї' => 'yi', <del> 'ĩ' => 'i', <del> 'ī' => 'i', <del> 'ĭ' => 'i', <del> 'ǐ' => 'i', <del> 'į' => 'i', <del> 'ı' => 'i', <del> 'Ĵ' => 'J', <del> 'ĵ' => 'j', <del> 'Ķ' => 'K', <del> 'ķ' => 'k', <del> 'Ĺ' => 'L', <del> 'Ļ' => 'L', <del> 'Ľ' => 'L', <del> 'Ŀ' => 'L', <del> 'Ł' => 'L', <del> 'ĺ' => 'l', <del> 'ļ' => 'l', <del> 'ľ' => 'l', <del> 'ŀ' => 'l', <del> 'ł' => 'l', <del> 'Ñ' => 'N', <del> 'Ń' => 'N', <del> 'Ņ' => 'N', <del> 'Ň' => 'N', <del> 'ñ' => 'n', <del> 'ń' => 'n', <del> 'ņ' => 'n', <del> 'ň' => 'n', <del> 'ʼn' => 'n', <del> 'Ò' => 'O', <del> 'Ó' => 'O', <del> 'Ô' => 'O', <del> 'Õ' => 'O', <del> 'Ō' => 'O', <del> 'Ŏ' => 'O', <del> 'Ǒ' => 'O', <del> 'Ő' => 'O', <del> 'Ơ' => 'O', <del> 'Ø' => 'O', <del> 'Ǿ' => 'O', <del> 'ò' => 'o', <del> 'ó' => 'o', <del> 'ô' => 'o', <del> 'õ' => 'o', <del> 'ō' => 'o', <del> 'ŏ' => 'o', <del> 'ǒ' => 'o', <del> 'ő' => 'o', <del> 'ơ' => 'o', <del> 'ø' => 'o', <del> 'ǿ' => 'o', <del> 'º' => 'o', <del> 'Ŕ' => 'R', <del> 'Ŗ' => 'R', <del> 'Ř' => 'R', <del> 'ŕ' => 'r', <del> 'ŗ' => 'r', <del> 'ř' => 'r', <del> 'Ś' => 'S', <del> 'Ŝ' => 'S', <del> 'Ş' => 'S', <del> 'Ș' => 'S', <del> 'Š' => 'S', <del> 'ẞ' => 'SS', <del> 'ś' => 's', <del> 'ŝ' => 's', <del> 'ş' => 's', <del> 'ș' => 's', <del> 'š' => 's', <del> 'ſ' => 's', <del> 'Ţ' => 'T', <del> 'Ț' => 'T', <del> 'Ť' => 'T', <del> 'Ŧ' => 'T', <del> 'ţ' => 't', <del> 'ț' => 't', <del> 'ť' => 't', <del> 'ŧ' => 't', <del> 'Ù' => 'U', <del> 'Ú' => 'U', <del> 'Û' => 'U', <del> 'Ũ' => 'U', <del> 'Ū' => 'U', <del> 'Ŭ' => 'U', <del> 'Ů' => 'U', <del> 'Ű' => 'U', <del> 'Ų' => 'U', <del> 'Ư' => 'U', <del> 'Ǔ' => 'U', <del> 'Ǖ' => 'U', <del> 'Ǘ' => 'U', <del> 'Ǚ' => 'U', <del> 'Ǜ' => 'U', <del> 'ù' => 'u', <del> 'ú' => 'u', <del> 'û' => 'u', <del> 'ũ' => 'u', <del> 'ū' => 'u', <del> 'ŭ' => 'u', <del> 'ů' => 'u', <del> 'ű' => 'u', <del> 'ų' => 'u', <del> 'ư' => 'u', <del> 'ǔ' => 'u', <del> 'ǖ' => 'u', <del> 'ǘ' => 'u', <del> 'ǚ' => 'u', <del> 'ǜ' => 'u', <del> 'Ý' => 'Y', <del> 'Ÿ' => 'Y', <del> 'Ŷ' => 'Y', <del> 'ý' => 'y', <del> 'ÿ' => 'y', <del> 'ŷ' => 'y', <del> 'Ŵ' => 'W', <del> 'ŵ' => 'w', <del> 'Ź' => 'Z', <del> 'Ż' => 'Z', <del> 'Ž' => 'Z', <del> 'ź' => 'z', <del> 'ż' => 'z', <del> 'ž' => 'z', <del> 'Æ' => 'AE', <del> 'Ǽ' => 'AE', <del> 'ß' => 'ss', <del> 'IJ' => 'IJ', <del> 'ij' => 'ij', <del> 'Œ' => 'OE', <del> 'ƒ' => 'f', <del> 'Þ' => 'TH', <del> 'þ' => 'th', <del> 'Є' => 'Ye', <del> 'є' => 'ye', <del> ]; <del> <ide> /** <ide> * Method cache array. <ide> *
1
Python
Python
fix support for builds in dirs with whitespace
50bf6df95bdb5e4254719b0a6061cd1cdece2b7c
<ide><path>numpy/distutils/fcompiler/__init__.py <ide> from numpy.distutils.ccompiler import CCompiler, gen_lib_options <ide> from numpy.distutils import log <ide> from numpy.distutils.misc_util import is_string, all_strings, is_sequence, \ <del> make_temp_file, get_shared_lib_extension <add> make_temp_file, get_shared_lib_extension, quote <ide> from numpy.distutils.environment import EnvironmentConfig <ide> from numpy.distutils.exec_command import find_executable <ide> from numpy.distutils.compat import get_exception <ide> def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): <ide> % (self.__class__.__name__, src)) <ide> extra_compile_args = self.extra_f90_compile_args or [] <ide> if self.object_switch[-1]==' ': <del> o_args = [self.object_switch.strip(), obj] <add> o_args = [self.object_switch.strip(), quote(obj)] <ide> else: <del> o_args = [self.object_switch.strip()+obj] <add> o_args = [self.object_switch.strip() + quote(obj)] <ide> <ide> assert self.compile_switch.strip() <del> s_args = [self.compile_switch, src] <add> s_args = [self.compile_switch, quote(src)] <ide> <ide> if extra_compile_args: <ide> log.info('extra %s options: %r' \ <ide> def link(self, target_desc, objects, <ide> else: <ide> ld_args = objects + self.objects <ide> ld_args = ld_args + lib_opts + o_args <add> ld_args = [quote(ld_arg) for ld_arg in ld_args] <ide> if debug: <ide> ld_args[:0] = ['-g'] <ide> if extra_preargs: <ide> def get_f77flags(src): <ide> <ide> if __name__ == '__main__': <ide> show_fcompilers() <add> <ide><path>numpy/distutils/misc_util.py <ide> import distutils <ide> from distutils.errors import DistutilsError <ide> <add>try: <add> from pipes import quote <add>except ImportError: <add> from shlex import quote <add> <ide> try: <ide> set <ide> except NameError: <ide> 'get_script_files', 'get_lib_source_files', 'get_data_files', <ide> 'dot_join', 'get_frame', 'minrelpath', 'njoin', <ide> 'is_sequence', 'is_string', 'as_list', 'gpaths', 'get_language', <del> 'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info'] <add> 'quote_args', 'quote', 'get_build_architecture', 'get_info', <add> 'get_pkg_info'] <ide> <ide> class InstallableLib(object): <ide> """ <ide><path>numpy/distutils/npy_pkg_config.py <ide> else: <ide> from configparser import ConfigParser, SafeConfigParser, NoOptionError <ide> <add>from numpy.distutils.misc_util import quote <add> <ide> __all__ = ['FormatError', 'PkgNotFound', 'LibraryInfo', 'VariableSet', <ide> 'read_config', 'parse_flags'] <ide> <ide> def parse_flags(line): <ide> * 'ignored' <ide> <ide> """ <del> lexer = shlex.shlex(line) <add> lexer = shlex.shlex(line, posix=True) <ide> lexer.whitespace_split = True <ide> <ide> d = {'include_dirs': [], 'library_dirs': [], 'libraries': [], <ide> def next_token(t): <ide> <ide> return d <ide> <del>def _escape_backslash(val): <del> return val.replace('\\', '\\\\') <ide> <ide> class LibraryInfo(object): <ide> """ <ide> def sections(self): <ide> <ide> def cflags(self, section="default"): <ide> val = self.vars.interpolate(self._sections[section]['cflags']) <del> return _escape_backslash(val) <add> return quote(val) <ide> <ide> def libs(self, section="default"): <ide> val = self.vars.interpolate(self._sections[section]['libs']) <del> return _escape_backslash(val) <add> return quote(val) <ide> <ide> def __str__(self): <ide> m = ['Name: %s' % self.name] <ide> def parse_config(filename, dirs=None): <ide> vars = {} <ide> if config.has_section('variables'): <ide> for name, value in config.items("variables"): <del> vars[name] = _escape_backslash(value) <add> vars[name] = quote(value) <ide> <ide> # Parse "normal" sections <ide> secs = [s for s in config.sections() if not s in ['meta', 'variables']] <ide> def _read_config(f): <ide> (pkgname, meta["name"])) <ide> <ide> mod = sys.modules[pkgname] <del> vars["pkgdir"] = _escape_backslash(os.path.dirname(mod.__file__)) <add> vars["pkgdir"] = quote(os.path.dirname(mod.__file__)) <ide> <ide> return LibraryInfo(name=meta["name"], description=meta["description"], <ide> version=meta["version"], sections=sections, vars=VariableSet(vars)) <ide><path>numpy/distutils/tests/test_npy_pkg_config.py <ide> from __future__ import division, absolute_import, print_function <ide> <ide> import os <add>import shlex <ide> from tempfile import mkstemp <ide> <ide> from numpy.testing import * <ide> 'version': '0.1', 'name': 'foo'} <ide> <ide> class TestLibraryInfo(TestCase): <add> <add> def assertLexEqual(self, str1, str2): <add> # Use shlex.split for comparison because it is above quotes <add> # eg: shlex.split("'abc'") == shlex.split("abc") <add> return shlex.split(str1) == shlex.split(str2) <add> <ide> def test_simple(self): <ide> fd, filename = mkstemp('foo.ini') <ide> try: <ide> def test_simple(self): <ide> os.close(fd) <ide> <ide> out = read_config(pkg) <del> self.assertTrue(out.cflags() == simple_d['cflags']) <del> self.assertTrue(out.libs() == simple_d['libflags']) <del> self.assertTrue(out.name == simple_d['name']) <del> self.assertTrue(out.version == simple_d['version']) <add> self.assertLexEqual(out.cflags(), simple_d['cflags']) <add> self.assertLexEqual(out.libs(), simple_d['libflags']) <add> self.assertEqual(out.name, simple_d['name']) <add> self.assertEqual(out.version, simple_d['version']) <ide> finally: <ide> os.remove(filename) <ide> <ide> def test_simple_variable(self): <ide> os.close(fd) <ide> <ide> out = read_config(pkg) <del> self.assertTrue(out.cflags() == simple_variable_d['cflags']) <del> self.assertTrue(out.libs() == simple_variable_d['libflags']) <del> self.assertTrue(out.name == simple_variable_d['name']) <del> self.assertTrue(out.version == simple_variable_d['version']) <add> self.assertLexEqual(out.cflags(), simple_variable_d['cflags']) <add> self.assertLexEqual(out.libs(), simple_variable_d['libflags']) <add> self.assertEqual(out.name, simple_variable_d['name']) <add> self.assertEqual(out.version, simple_variable_d['version']) <ide> <ide> out.vars['prefix'] = '/Users/david' <del> self.assertTrue(out.cflags() == '-I/Users/david/include') <add> self.assertLexEqual(out.cflags(), '-I/Users/david/include') <ide> finally: <ide> os.remove(filename) <ide> <ide> def test_simple_cflags(self): <ide> self.assertTrue(d['include_dirs'] == ['/usr/include']) <ide> self.assertTrue(d['macros'] == ['FOO']) <ide> <add> def test_quotes_cflags(self): <add> d = parse_flags("-I'/usr/foo bar/include' -DFOO") <add> self.assertTrue(d['include_dirs'] == ['/usr/foo bar/include']) <add> self.assertTrue(d['macros'] == ['FOO']) <add> <add> d = parse_flags("-I/usr/'foo bar'/include -DFOO") <add> self.assertTrue(d['include_dirs'] == ['/usr/foo bar/include']) <add> self.assertTrue(d['macros'] == ['FOO']) <add> <add> d = parse_flags("'-I/usr/foo bar'/include -DFOO") <add> self.assertTrue(d['include_dirs'] == ['/usr/foo bar/include']) <add> self.assertTrue(d['macros'] == ['FOO']) <add> <add> def test_escaping_cflags(self): <add> d = parse_flags("-I/usr/foo\\ bar/include -DFOO") <add> self.assertTrue(d['include_dirs'] == ['/usr/foo bar/include']) <add> self.assertTrue(d['macros'] == ['FOO']) <add> <add> d = parse_flags(r"-I/usr/foo\ bar/include -DFOO") <add> self.assertTrue(d['include_dirs'] == ['/usr/foo bar/include']) <add> self.assertTrue(d['macros'] == ['FOO']) <add> <ide> def test_simple_lflags(self): <ide> d = parse_flags("-L/usr/lib -lfoo -L/usr/lib -lbar") <ide> self.assertTrue(d['library_dirs'] == ['/usr/lib', '/usr/lib']) <ide> def test_simple_lflags(self): <ide> d = parse_flags("-L /usr/lib -lfoo -L/usr/lib -lbar") <ide> self.assertTrue(d['library_dirs'] == ['/usr/lib', '/usr/lib']) <ide> self.assertTrue(d['libraries'] == ['foo', 'bar']) <add> <add> def test_quotes_lflags(self): <add> d = parse_flags("-L'/usr/foo bar' -lfoo -L/usr/lib -lbar") <add> self.assertTrue(d['library_dirs'] == ['/usr/foo bar', '/usr/lib']) <add> <add> d = parse_flags("-L/usr/'foo bar' -lfoo -L/usr/lib -lbar") <add> self.assertTrue(d['library_dirs'] == ['/usr/foo bar', '/usr/lib']) <add> <add> d = parse_flags("\"-L/usr/foo bar\" -lfoo -L/usr/lib -lbar") <add> self.assertTrue(d['library_dirs'] == ['/usr/foo bar', '/usr/lib']) <add> <add> d = parse_flags("\"-L/usr/foo bar/baz buz\" -lfoo -L/usr/lib -lbar") <add> self.assertTrue(d['library_dirs'] == ['/usr/foo bar/baz buz', '/usr/lib']) <add> <add> def test_escaping_lflags(self): <add> d = parse_flags("-L/usr/foo\\ bar -lfoo -L/usr/lib -lbar") <add> self.assertTrue(d['library_dirs'] == ['/usr/foo bar', '/usr/lib']) <add> <add> d = parse_flags(r"-L/usr/foo\ bar -lfoo -L/usr/lib -lbar") <add> self.assertTrue(d['library_dirs'] == ['/usr/foo bar', '/usr/lib']) <add> <add> def test_odd_characters_lflags(self): <add> # tab in directory name <add> d = parse_flags('-L/usr/"foo\tbar" -lfoo -L/usr/lib -lbar') <add> self.assertTrue(d['library_dirs'] == ['/usr/foo\tbar', '/usr/lib']) <add> <add> d = parse_flags("-L/usr/foo\\\tbar -lfoo -L/usr/lib -lbar") <add> self.assertTrue(d['library_dirs'] == ['/usr/foo\tbar', '/usr/lib']) <ide><path>numpy/distutils/unixccompiler.py <ide> from distutils.unixccompiler import * <ide> from numpy.distutils.ccompiler import replace_method <ide> from numpy.distutils.compat import get_exception <add>from numpy.distutils.misc_util import quote_args, quote <ide> <ide> if sys.version_info[0] < 3: <ide> from . import log <ide> def UnixCCompiler_create_static_lib(self, objects, output_libname, <ide> display = '%s: adding %d object files to %s' % ( <ide> os.path.basename(self.archiver[0]), <ide> len(objects), output_filename) <del> self.spawn(self.archiver + [output_filename] + objects, <del> display = display) <add> command = self.archiver + [quote(output_filename)] + quote_args(objects) <add> self.spawn(command, display = display) <ide> <ide> # Not many Unices required ranlib anymore -- SunOS 4.x is, I <ide> # think the only major Unix that does. Maybe we need some
5
Text
Text
use canonical docs url
2ef91b1c783b1f9d415c9bd2f4aba8ba9f958182
<ide><path>README.md <ide> <ide> ## Documentation <ide> <del>You can find documentation at [chartjs.org/docs](http://www.chartjs.org/docs). The markdown files that build the site are available under `/docs`. Please note - in some of the json examples of configuration you might notice some liquid tags - this is just for the generating the site html, please disregard. <add>You can find documentation at [chartjs.org/docs](http://www.chartjs.org/docs/). The markdown files that build the site are available under `/docs`. Please note - in some of the json examples of configuration you might notice some liquid tags - this is just for the generating the site html, please disregard. <ide> <ide> ## License <ide>
1
Text
Text
change html-scanner to rails-html-sanitizer
4c3afea7dfb380f6357c9ebceac973bfa20151f6
<ide><path>guides/source/action_view_overview.md <ide> strip_links('Blog: <a href="http://myblog.com/">Visit</a>.') <ide> #### strip_tags(html) <ide> <ide> Strips all HTML tags from the html, including comments. <del>This uses the html-scanner tokenizer and so its HTML parsing ability is limited by that of html-scanner. <add>This functionality is powered by the rails-html-sanitizer gem. <ide> <ide> ```ruby <ide> strip_tags("Strip <i>these</i> tags!")
1
Javascript
Javascript
fix minor typo
6ca5272f94f095b864682f438e4cd916aae073ad
<ide><path>src/ng/directive/ngClass.js <ide> function classDirective(name, selector) { <ide> * @name ng.directive:ngClass <ide> * <ide> * @description <del> * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an <del> * expression that represents all classes to be added. <add> * The `ngClass` allows you to set CSS classes on HTML an element, dynamically, by databinding <add> * an expression that represents all classes to be added. <ide> * <ide> * The directive won't add duplicate classes if a particular class was already set. <ide> *
1
Text
Text
use h1 for packages and features sections
cecec376e3049abc4a0a22648334999c4988ae6e
<ide><path>docs/features.md <del>## Features <add># Features <ide><path>docs/packages/intro.md <del>## Packages <add># Packages <ide> <ide> ### Package Layout <ide>
2
Javascript
Javascript
treat \ the same as /
9520adeb37f5ebe02a68669ec97770f4869705bb
<ide><path>lib/url.js <ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { <ide> throw new TypeError("Parameter 'url' must be a string, not " + typeof url); <ide> } <ide> <add> // Copy chrome, IE, opera backslash-handling behavior. <add> // See: https://code.google.com/p/chromium/issues/detail?id=25916 <add> var hashSplit = url.split('#'); <add> hashSplit[0] = hashSplit[0].replace(/\\/g, '/'); <add> url = hashSplit.join('#'); <add> <ide> var rest = url; <ide> <ide> // trim before proceeding. <ide><path>test/simple/test-url.js <ide> var parseTests = { <ide> 'path': '//some_path' <ide> }, <ide> <add> 'http:\\\\evil-phisher\\foo.html#h\\a\\s\\h': { <add> protocol: 'http:', <add> slashes: true, <add> host: 'evil-phisher', <add> hostname: 'evil-phisher', <add> pathname: '/foo.html', <add> path: '/foo.html', <add> hash: '#h\\a\\s\\h', <add> href: 'http://evil-phisher/foo.html#h\\a\\s\\h' <add> }, <add> <add> <add> 'http:\\\\evil-phisher\\foo.html': { <add> protocol: 'http:', <add> slashes: true, <add> host: 'evil-phisher', <add> hostname: 'evil-phisher', <add> pathname: '/foo.html', <add> path: '/foo.html', <add> href: 'http://evil-phisher/foo.html' <add> }, <add> <ide> 'HTTP://www.example.com/' : { <ide> 'href': 'http://www.example.com/', <ide> 'protocol': 'http:', <ide> relativeTests2.forEach(function(relativeTest) { <ide> 'format(' + relativeTest[1] + ') == ' + expected + <ide> '\nactual:' + actual); <ide> }); <add> <add>// backslashes should be like forward slashes <add>var res = url.resolve('http://example.com/x', '\\\\foo.com\\bar'); <add>assert.equal(res, 'http://foo.com/bar');
2
Javascript
Javascript
add help button toggle
fc97bc826620a3c90fa88eaff7c67ba6395afd25
<ide><path>client/main.js <ide> main = (function(main) { <ide> }); <ide> <ide> $(helpChatBtnClass).on('click', function() { <del> main.chat.helpChat.toggleChat(true); <add> // is button already pressed? <add> // no? open chat <add> // yes? close chat <add> var shouldChatBeOpen = !$(this).hasClass('active'); <add> main.chat.helpChat.toggleChat(shouldChatBeOpen); <add> if (shouldChatBeOpen) { <add> $(helpChatBtnClass).addClass('active'); <add> } <add> }); <add> <add> $('#chat-embed-help').on('gitter-chat-toggle', function(e) { <add> var shouldButtonBePressed = !!e.originalEvent.detail.state; <add> if (shouldButtonBePressed) { <add> return $(helpChatBtnClass).addClass('active'); <add> } <add> return $(helpChatBtnClass).removeClass('active'); <ide> }); <ide> }; <ide>
1
Javascript
Javascript
increase coverage for repl
5934a445c344309f735c3f1b79ae5777d75f4ca7
<ide><path>test/parallel/test-repl-envvars.js <ide> const stream = require('stream'); <ide> const REPL = require('internal/repl'); <ide> const assert = require('assert'); <ide> const inspect = require('util').inspect; <add>const { REPL_MODE_SLOPPY, REPL_MODE_STRICT } = require('repl'); <ide> <ide> const tests = [ <ide> { <ide> const tests = [ <ide> env: { NODE_NO_READLINE: '0' }, <ide> expected: { terminal: true, useColors: true } <ide> }, <add> { <add> env: { NODE_REPL_MODE: 'sloppy' }, <add> expected: { terminal: true, useColors: true, replMode: REPL_MODE_SLOPPY } <add> }, <add> { <add> env: { NODE_REPL_MODE: 'strict' }, <add> expected: { terminal: true, useColors: true, replMode: REPL_MODE_STRICT } <add> }, <ide> ]; <ide> <ide> function run(test) { <ide> function run(test) { <ide> `Expected ${inspect(expected)} with ${inspect(env)}`); <ide> assert.strictEqual(repl.useColors, expected.useColors, <ide> `Expected ${inspect(expected)} with ${inspect(env)}`); <add> assert.strictEqual(repl.replMode, expected.replMode || REPL_MODE_SLOPPY, <add> `Expected ${inspect(expected)} with ${inspect(env)}`); <ide> for (const key of Object.keys(env)) { <ide> delete process.env[key]; <ide> }
1
Python
Python
add test for weighted histogram mismatch
0033161ec65311c600dffc6d7af8daf4116b760f
<ide><path>numpy/lib/tests/test_histograms.py <ide> def test_outliers(self): <ide> h, b = histogram(a, bins=8, range=[1, 9], weights=w) <ide> assert_equal(h, w[1:-1]) <ide> <add> def test_arr_weights_mismatch(self): <add> a = np.arange(10) + .5 <add> w = np.arange(11) + .5 <add> with assert_raises_regex(ValueError, "same shape as"): <add> h, b = histogram(a, range=[1, 9], weights=w, density=True) <add> <add> <ide> def test_type(self): <ide> # Check the type of the returned histogram <ide> a = np.arange(10) + .5
1
PHP
PHP
add bc test for
dc7b8cbb89c92dc46777abcad90fdfb50e704515
<ide><path>lib/Cake/Test/Case/Model/ModelValidationTest.php <ide> public function testIsUniqueValidator() { <ide> $this->assertFalse($Article->validates(), 'Should fail, conditions are combined with or'); <ide> } <ide> <add>/** <add> * Test backward compatibility of the isUnique method when used as a validator for multiple fields. <add> * <add> * @return void <add> */ <add> public function testBackwardCompatIsUniqueValidator() { <add> $this->loadFixtures('Article'); <add> $Article = ClassRegistry::init('Article'); <add> $Article->validate = array( <add> 'title' => array( <add> 'duplicate' => array( <add> 'rule' => 'isUnique', <add> 'message' => 'Title must be unique', <add> ), <add> 'minLength' => array( <add> 'rule' => array('minLength', 1), <add> 'message' => 'Title cannot be empty', <add> ), <add> ) <add> ); <add> $data = array( <add> 'title' => 'First Article', <add> ); <add> $data = $Article->create($data); <add> $this->assertFalse($Article->validates(), 'Contains a dupe'); <add> } <add> <ide> } <ide> <ide> /**
1
Javascript
Javascript
fix lint for moved reactnative
744548ad143b7350e7e1d7d39e72bf2f4108fee6
<ide><path>src/renderers/native/ReactIOS/IOSDefaultEventPluginOrder.js <ide> <ide> var IOSDefaultEventPluginOrder = [ <ide> 'ResponderEventPlugin', <del> 'IOSNativeBridgeEventPlugin' <add> 'IOSNativeBridgeEventPlugin', <ide> ]; <ide> <ide> module.exports = IOSDefaultEventPluginOrder; <ide><path>src/renderers/native/ReactIOS/IOSNativeBridgeEventPlugin.js <ide> var IOSNativeBridgeEventPlugin = { <ide> return null; <ide> } <ide> return event; <del> } <add> }, <ide> }; <ide> <ide> module.exports = IOSNativeBridgeEventPlugin; <ide><path>src/renderers/native/ReactIOS/NativeMethodsMixin.js <ide> var NativeMethodsMixin = { <ide> */ <ide> blur: function() { <ide> TextInputState.blurTextInput(findNodeHandle(this)); <del> } <add> }, <ide> }; <ide> <ide> function throwOnStylesProp(component, props) { <ide> if (__DEV__) { <ide> !NativeMethodsMixin_DEV.componentWillReceiveProps, <ide> 'Do not override existing functions.' <ide> ); <del> NativeMethodsMixin_DEV.componentWillMount = function () { <add> NativeMethodsMixin_DEV.componentWillMount = function() { <ide> throwOnStylesProp(this, this.props); <ide> }; <del> NativeMethodsMixin_DEV.componentWillReceiveProps = function (newProps) { <add> NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { <ide> throwOnStylesProp(this, newProps); <ide> }; <ide> } <ide> if (__DEV__) { <ide> var mountSafeCallback = function(context: ReactComponent, callback: ?Function): any { <ide> return function() { <ide> if (!callback || (context.isMounted && !context.isMounted())) { <del> return; <add> return undefined; <ide> } <ide> return callback.apply(context, arguments); <ide> }; <ide><path>src/renderers/native/ReactNative/ReactNative.js <ide> var ReactNativeComponentTree = require('ReactNativeComponentTree'); <ide> var ReactNativeDefaultInjection = require('ReactNativeDefaultInjection'); <ide> <del>var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> var ReactElement = require('ReactElement'); <del>var ReactInstanceHandles = require('ReactInstanceHandles'); <ide> var ReactNativeMount = require('ReactNativeMount'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> <ide> var ReactNative = { <ide> /* eslint-enable camelcase */ <ide> <ide> unmountComponentAtNodeAndRemoveContainer: ReactNativeMount.unmountComponentAtNodeAndRemoveContainer, <del> <del> // Deprecations (remove for 0.13) <del> renderComponent: function( <del> element: ReactElement, <del> mountInto: number, <del> callback?: ?(() => void) <del> ): ?ReactComponent { <del> warning('Use React.render instead of React.renderComponent'); <del> return ReactNative.render(element, mountInto, callback); <del> }, <ide> }; <ide> <ide> // Inject the runtime into a devtools global hook regardless of browser. <ide><path>src/renderers/native/ReactNative/ReactNativeAttributePayload.js <ide> function diffProperties( <ide> defaultDiffer(prevProp, nextProp) <ide> ); <ide> if (shouldUpdate) { <del> var nextValue = typeof attributeConfig.process === 'function' ? <del> attributeConfig.process(nextProp) : <del> nextProp; <add> nextValue = typeof attributeConfig.process === 'function' ? <add> attributeConfig.process(nextProp) : <add> nextProp; <ide> (updatePayload || (updatePayload = {}))[altKey] = nextValue; <ide> } <ide> } else { <ide> function diffProperties( <ide> // Also iterate through all the previous props to catch any that have been <ide> // removed and make sure native gets the signal so it can reset them to the <ide> // default. <del> for (var propKey in prevProps) { <add> for (propKey in prevProps) { <ide> if (nextProps[propKey] !== undefined) { <ide> continue; // we've already covered this key in the previous pass <ide> } <ide> var ReactNativeAttributePayload = { <ide> nextProps, <ide> validAttributes <ide> ); <del> } <add> }, <ide> <ide> }; <ide> <ide><path>src/renderers/native/ReactNative/ReactNativeBaseComponent.js <ide> var ReactMultiChild = require('ReactMultiChild'); <ide> var UIManager = require('UIManager'); <ide> <ide> var deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev'); <del>var invariant = require('invariant'); <del>var warning = require('warning'); <ide> <ide> var registrationNames = ReactNativeEventEmitter.registrationNames; <ide> var putListener = ReactNativeEventEmitter.putListener; <ide> ReactNativeBaseComponent.Mixin = { <ide> context <ide> ); <ide> return tag; <del> } <add> }, <ide> }; <ide> <ide> /** <ide><path>src/renderers/native/ReactNative/ReactNativeContainerInfo.js <ide> <ide> function ReactNativeContainerInfo(tag) { <ide> var info = { <del> _tag: tag <add> _tag: tag, <ide> }; <ide> return info; <ide> } <ide><path>src/renderers/native/ReactNative/ReactNativeDOMIDOperations.js <ide> 'use strict'; <ide> <ide> var ReactNativeComponentTree = require('ReactNativeComponentTree'); <del>var ReactNativeTagHandles = require('ReactNativeTagHandles'); <ide> var ReactMultiChildUpdateTypes = require('ReactMultiChildUpdateTypes'); <ide> var ReactPerf = require('ReactPerf'); <ide> var UIManager = require('UIManager'); <ide><path>src/renderers/native/ReactNative/ReactNativeDefaultInjection.js <ide> function inject() { <ide> */ <ide> EventPluginHub.injection.injectEventPluginsByName({ <ide> 'ResponderEventPlugin': ResponderEventPlugin, <del> 'IOSNativeBridgeEventPlugin': IOSNativeBridgeEventPlugin <add> 'IOSNativeBridgeEventPlugin': IOSNativeBridgeEventPlugin, <ide> }); <ide> <ide> ReactUpdates.injection.injectReconcileTransaction( <ide> function inject() { <ide> return new ReactSimpleEmptyComponent( <ide> ReactElement.createElement(View, { <ide> collapsable: true, <del> style: { position: 'absolute' } <add> style: { position: 'absolute' }, <ide> }), <ide> instantiate <ide> ); <ide><path>src/renderers/native/ReactNative/ReactNativeEventEmitter.js <ide> var ReactNativeEventEmitter = merge(ReactEventEmitterMixin, { <ide> nativeEvent <ide> ); <ide> } <del> } <add> }, <ide> }); <ide> <ide> module.exports = ReactNativeEventEmitter; <ide><path>src/renderers/native/ReactNative/ReactNativeGlobalInteractionHandler.js <ide> var ReactNativeGlobalInteractionHandler = { <ide> } else if (!interactionHandle) { <ide> interactionHandle = InteractionManager.createInteractionHandle(); <ide> } <del> } <add> }, <ide> }; <ide> <ide> module.exports = ReactNativeGlobalInteractionHandler; <ide><path>src/renderers/native/ReactNative/ReactNativeGlobalResponderHandler.js <ide> */ <ide> 'use strict'; <ide> <del>var ReactNativeTagHandles = require('ReactNativeTagHandles'); <ide> var UIManager = require('UIManager'); <ide> <ide> var ReactNativeGlobalResponderHandler = { <ide> var ReactNativeGlobalResponderHandler = { <ide> } else { <ide> UIManager.clearJSResponder(); <ide> } <del> } <add> }, <ide> }; <ide> <ide> module.exports = ReactNativeGlobalResponderHandler; <ide><path>src/renderers/native/ReactNative/ReactNativeMount.js <ide> var ReactNativeMount = { <ide> <ide> if (!ReactNativeTagHandles.reactTagIsNativeTopRootID(containerTag)) { <ide> console.error('You cannot render into anything but a top root'); <del> return; <add> return null; <ide> } <ide> <ide> ReactNativeTagHandles.assertRootTag(containerTag); <ide> var ReactNativeMount = { <ide> // Call back into native to remove all of the subviews from this container <ide> ReactReconciler.unmountComponent(instance); <ide> UIManager.removeSubviewsFromContainerWithID(containerID); <del> } <add> }, <ide> <ide> }; <ide> <ide><path>src/renderers/native/ReactNative/ReactNativeReconcileTransaction.js <ide> var ON_DOM_READY_QUEUEING = { <ide> */ <ide> close: function() { <ide> this.reactMountReady.notifyAll(); <del> } <add> }, <ide> }; <ide> <ide> /** <ide> var Mixin = { <ide> destructor: function() { <ide> CallbackQueue.release(this.reactMountReady); <ide> this.reactMountReady = null; <del> } <add> }, <ide> }; <ide> <ide> Object.assign( <ide><path>src/renderers/native/ReactNative/ReactNativeTagHandles.js <ide> 'use strict'; <ide> <ide> var invariant = require('invariant'); <del>var warning = require('warning'); <ide> <ide> /** <ide> * Keeps track of allocating and associating native "tags" which are numeric, <ide> var warning = require('warning'); <ide> * unmount a component with a `rootNodeID`, then mount a new one in its place, <ide> */ <ide> var INITIAL_TAG_COUNT = 1; <del>var NATIVE_TOP_ROOT_ID_SEPARATOR = '{TOP_LEVEL}'; <ide> var ReactNativeTagHandles = { <ide> tagsStartAt: INITIAL_TAG_COUNT, <ide> tagCount: INITIAL_TAG_COUNT, <ide> var ReactNativeTagHandles = { <ide> assertRootTag: function(tag: number): void { <ide> invariant( <ide> this.reactTagIsNativeTopRootID(tag), <del> 'Expect a native root tag, instead got ', tag <add> 'Expect a native root tag, instead got %s', tag <ide> ); <ide> }, <ide> <ide> reactTagIsNativeTopRootID: function(reactTag: number): bool { <ide> // We reserve all tags that are 1 mod 10 for native root views <ide> return reactTag % 10 === 1; <del> } <add> }, <ide> }; <ide> <ide> module.exports = ReactNativeTagHandles; <ide><path>src/renderers/native/ReactNative/ReactNativeTextComponent.js <ide> Object.assign(ReactNativeTextComponent.prototype, { <ide> // TODO: nativeParent should have this context already. Stop abusing context. <ide> invariant( <ide> context.isInAParentText, <del> 'RawText "' + this._stringText + '" must be wrapped in an explicit ' + <del> '<Text> component.' <add> 'RawText "%s" must be wrapped in an explicit <Text> component.', <add> this._stringText <ide> ); <ide> this._nativeParent = nativeParent; <ide> var tag = ReactNativeTagHandles.allocateTag(); <ide> Object.assign(ReactNativeTextComponent.prototype, { <ide> this._currentElement = null; <ide> this._stringText = null; <ide> this._rootNodeID = null; <del> } <add> }, <ide> <ide> }); <ide> <ide><path>src/renderers/native/ReactNative/__tests__/ReactNativeAttributePayload-test.js <ide> describe('ReactNativeAttributePayload', function() { <ide> <ide> it('should do deep diffs of Objects by default', () => { <ide> expect(diff( <del> {a: [1], b: {k: [3,4]}, c: {k: [4,4]} }, <del> {a: [2], b: {k: [3,4]}, c: {k: [4,5]} }, <add> {a: [1], b: {k: [3, 4]}, c: {k: [4, 4]} }, <add> {a: [2], b: {k: [3, 4]}, c: {k: [4, 5]} }, <ide> {a: true, b: true, c: true} <del> )).toEqual({a: [2], c: {k: [4,5]}}); <add> )).toEqual({a: [2], c: {k: [4, 5]}}); <ide> }); <ide> <ide> it('should work with undefined styles', () => { <ide> describe('ReactNativeAttributePayload', function() { <ide> // Note that if the property changes from one function to another, we don't <ide> // need to send an update. <ide> expect(diff( <del> {a: function() { return 1; }, b: function() { return 2; }, c: 3}, <del> {b: function() { return 9; }, c: function() { return 3; }, }, <add> { <add> a: function() { <add> return 1; <add> }, <add> b: function() { <add> return 2; <add> }, <add> c: 3, <add> }, <add> { <add> b: function() { <add> return 9; <add> }, <add> c: function() { <add> return 3; <add> }, <add> }, <ide> {a: true, b: true, c: true} <ide> )).toEqual({a: null, c: true}); <ide> }); <ide> <del> }); <add>}); <ide><path>src/renderers/native/ReactNative/findNodeHandle.js <ide> <ide> var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> var ReactInstanceMap = require('ReactInstanceMap'); <del>var ReactNativeTagHandles = require('ReactNativeTagHandles'); <ide> <ide> var invariant = require('invariant'); <ide> var warning = require('warning'); <ide><path>src/renderers/shared/event/eventPlugins/PanResponder.js <ide> * @providesModule PanResponder <ide> */ <ide> <del>"use strict"; <add>'use strict'; <ide> <ide> var TouchHistoryMath = require('TouchHistoryMath'); <ide> <ide> var PanResponder = { <ide> gestureState.y0 = currentCentroidY(e.touchHistory); <ide> gestureState.dx = 0; <ide> gestureState.dy = 0; <del> config.onPanResponderGrant && config.onPanResponderGrant(e, gestureState); <add> if (config.onPanResponderGrant) config.onPanResponderGrant(e, gestureState); <ide> // TODO: t7467124 investigate if this can be removed <ide> return config.onShouldBlockNativeResponder === undefined ? true : <ide> config.onShouldBlockNativeResponder(); <ide> }, <ide> <ide> onResponderReject: function(e) { <del> config.onPanResponderReject && config.onPanResponderReject(e, gestureState); <add> if (config.onPanResponderReject) config.onPanResponderReject(e, gestureState); <ide> }, <ide> <ide> onResponderRelease: function(e) { <del> config.onPanResponderRelease && config.onPanResponderRelease(e, gestureState); <add> if (config.onPanResponderRelease) config.onPanResponderRelease(e, gestureState); <ide> PanResponder._initializeGestureState(gestureState); <ide> }, <ide> <ide> onResponderStart: function(e) { <ide> var touchHistory = e.touchHistory; <ide> gestureState.numberActiveTouches = touchHistory.numberActiveTouches; <del> config.onPanResponderStart && config.onPanResponderStart(e, gestureState); <add> if (config.onPanResponderStart) config.onPanResponderStart(e, gestureState); <ide> }, <ide> <ide> onResponderMove: function(e) { <ide> var PanResponder = { <ide> // Filter out any touch moves past the first one - we would have <ide> // already processed multi-touch geometry during the first event. <ide> PanResponder._updateGestureStateOnMove(gestureState, touchHistory); <del> config.onPanResponderMove && config.onPanResponderMove(e, gestureState); <add> if (config.onPanResponderMove) config.onPanResponderMove(e, gestureState); <ide> }, <ide> <ide> onResponderEnd: function(e) { <ide> var touchHistory = e.touchHistory; <ide> gestureState.numberActiveTouches = touchHistory.numberActiveTouches; <del> config.onPanResponderEnd && config.onPanResponderEnd(e, gestureState); <add> if (config.onPanResponderEnd) config.onPanResponderEnd(e, gestureState); <ide> }, <ide> <ide> onResponderTerminate: function(e) { <del> config.onPanResponderTerminate && <add> if (config.onPanResponderTerminate) { <ide> config.onPanResponderTerminate(e, gestureState); <add> } <ide> PanResponder._initializeGestureState(gestureState); <ide> }, <ide> <ide><path>src/renderers/shared/event/eventPlugins/TouchHistoryMath.js <ide> * @providesModule TouchHistoryMath <ide> */ <ide> <del>"use strict"; <add>'use strict'; <ide> <ide> var TouchHistoryMath = { <ide> /**
20
Text
Text
consolidate node.js instructions
dab119f2be22534980261fc14fdf442293eb7b69
<ide><path>docs/how-to-setup-freecodecamp-locally.md <ide> Software required for both Docker and Local builds: <ide> | [Node.js](http://nodejs.org) | `12.x` | [LTS Schedule](https://github.com/nodejs/Release#release-schedule) | <ide> | npm (comes bundled with Node) | `6.x` | Does not have LTS releases, we use the version bundled with Node LTS | <ide> <add>If Node.js is already installed on your machine, run the following commands to validate the versions: <add> <add>```sh <add>node -v <add>npm -v <add>``` <add> <add>> [!DANGER] <add>> If you have a different version, please install the recommended version. We can only support installation issues for recommended versions. See [troubleshooting](#troubleshooting) for details. <add> <ide> **Docker Build additional prerequisite:** <ide> <ide> | Prerequisite | Version | Notes | <ide> Software required for both Docker and Local builds: <ide> > [!TIP] <ide> > We highly recommend updating to the latest stable releases of the software listed above, also known as Long Term Support (LTS) releases. <ide> <del>If Node.js is already installed on your machine, run the following commands to validate the versions: <del> <del>```sh <del>node -v <del>npm -v <del>``` <del> <del>> [!DANGER] <del>> If you have a different version, please install the recommended version. We can only support installation issues for recommended versions. See [troubleshooting](#troubleshooting) for details. <del> <ide> ### Configuring dependencies <ide> <ide> #### Step 1: Set up the environment variable file
1
Ruby
Ruby
rescue the assertion exception
0579f303ec0968e66a0e17bc494b06d0996aaffd
<ide><path>activesupport/test/test_test.rb <ide> def test_array_of_expressions <ide> end <ide> <ide> def test_array_of_expressions_identify_failure <del> assert_difference ['@object.num', '1 + 1'] do <del> @object.increment <add> assert_raises(MiniTest::Assertion) do <add> assert_difference ['@object.num', '1 + 1'] do <add> @object.increment <add> end <ide> end <del> fail 'should not get to here' <del> rescue Exception => e <del> assert_match(/didn't change by/, e.message) <del> assert_match(/expected but was/, e.message) <ide> end <ide> <ide> def test_array_of_expressions_identify_failure_when_message_provided <del> assert_difference ['@object.num', '1 + 1'], 1, 'something went wrong' do <del> @object.increment <add> assert_raises(MiniTest::Assertion) do <add> assert_difference ['@object.num', '1 + 1'], 1, 'something went wrong' do <add> @object.increment <add> end <ide> end <del> fail 'should not get to here' <del> rescue Exception => e <del> assert_match(/something went wrong/, e.message) <del> assert_match(/didn't change by/, e.message) <del> assert_match(/expected but was/, e.message) <ide> end <ide> else <ide> def default_test; end
1
Text
Text
fix incorrect heading level
d4d6dfdb9412419ede5059e72a407cdbbde8a4dd
<ide><path>doc/api/dns.md <ide> Here is an example of the result object: <ide> minttl: 60 } ] <ide> ``` <ide> <del>## `dnsPromises.resolveCaa(hostname)` <add>### `dnsPromises.resolveCaa(hostname)` <ide> <!-- YAML <ide> added: v15.0.0 <ide> -->
1
Text
Text
add stub linux and windows requirements
bb2527bbb81287ce1a660ab6a4eeb7c09dc5e84a
<ide><path>README.md <ide> Atom will automatically update when a new release is available. <ide> * [node.js](http://nodejs.org/) <ide> * Command Line Tools for [Xcode](https://developer.apple.com/xcode/downloads/) <ide> <add>**Linux Requirements** <add> * [node.js](http://nodejs.org/) <add> <add>**Windows Requirements** <add> * [node.js](http://nodejs.org/) <add> <ide> ```sh <ide> git clone git@github.com:atom/atom.git <ide> cd atom
1
Javascript
Javascript
upgrade externalsplugin to es6
994bc7a7018c259a6affcf2a25a3bdc82537c3ab
<ide><path>lib/ExternalsPlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <add>"use strict"; <add> <ide> var ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); <ide> <del>function ExternalsPlugin(type, externals) { <del> this.type = type; <del> this.externals = externals; <add>class ExternalsPlugin { <add> constructor(type, externals) { <add> this.type = type; <add> this.externals = externals; <add> } <add> apply(compiler) { <add> compiler.plugin("compile", (params) => { <add> params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(this.type, this.externals)); <add> }); <add> } <ide> } <add> <ide> module.exports = ExternalsPlugin; <del>ExternalsPlugin.prototype.apply = function(compiler) { <del> compiler.plugin("compile", function(params) { <del> params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(this.type, this.externals)); <del> }.bind(this)); <del>};
1
Text
Text
simplify recommendation in webcrypto.md
c9bb345b05307688bc6b727580121a9bf2819108
<ide><path>doc/api/webcrypto.md <ide> added: v15.0.0 <ide> * Type: {ArrayBuffer|TypedArray|DataView|Buffer} <ide> <ide> The initialization vector must be unique for every encryption operation <del>using a given key. It is recommended by the AES-GCM specification that <add>using a given key. The AES-GCM specification recommends that <ide> this contain at least 12 random bytes. <ide> <ide> #### `aesGcmParams.name`
1
Ruby
Ruby
permit glibc 2.35
1ac5fc05bd4c46c5f5812428790f465f531dec4e
<ide><path>Library/Homebrew/formula_auditor.rb <ide> def audit_postgresql <ide> <ide> def audit_glibc <ide> return unless @core_tap <del> return if formula.name != "glibc" || formula.version.to_s == OS::CI_GLIBC_VERSION <add> return if formula.name != "glibc" || [OS::CI_GLIBC_VERSION, "2.35"].include?(formula.version.to_s) <ide> <ide> problem "The glibc version must be #{OS::CI_GLIBC_VERSION}, as this is the version used by our CI on Linux. " \ <ide> "Glibc is for users who have a system Glibc with a lower version, " \
1
Ruby
Ruby
unify heredoc style
50fee143583b129a86a56bdc21d1f4ff4b9f5812
<ide><path>Library/Homebrew/cask/lib/hbc/cli.rb <ide> def self.parser <ide> end <ide> <ide> opts.on("--binarydir=PATH") do <del> opoo <<-EOF.undent <add> opoo <<-EOS.undent <ide> Option --binarydir is obsolete! <ide> Homebrew-Cask now uses the same location as your Homebrew installation for executable links. <del> EOF <add> EOS <ide> end <ide> <ide> FLAGS.each do |flag, method| <ide> def run(*args) <ide> end <ide> <ide> def purpose <del> puts <<-PURPOSE.undent <add> puts <<-EOS.undent <ide> brew-cask provides a friendly homebrew-style CLI workflow for the <ide> administration of macOS applications distributed as binaries. <ide> <del> PURPOSE <add> EOS <ide> end <ide> <ide> def usage <ide><path>Library/Homebrew/cask/lib/hbc/cli/uninstall.rb <ide> def self.run(*args) <ide> <ide> single = versions.count == 1 <ide> <del> puts <<-EOF.undent <add> puts <<-EOS.undent <ide> #{cask_token} #{versions.join(', ')} #{single ? 'is' : 'are'} still installed. <ide> Remove #{single ? 'it' : 'them all'} with `brew cask uninstall --force #{cask_token}`. <del> EOF <add> EOS <ide> end <ide> end <ide> <ide><path>Library/Homebrew/cask/lib/hbc/container/air.rb <ide> def self.me?(criteria) <ide> <ide> def self.installer_cmd <ide> return @installer_cmd ||= INSTALLER_PATHNAME if installer_exist? <del> raise Hbc::CaskError, <<-ERRMSG.undent <add> raise Hbc::CaskError, <<-EOS.undent <ide> Adobe AIR runtime not present, try installing it via <ide> <ide> brew cask install adobe-air <ide> <del> ERRMSG <add> EOS <ide> end <ide> <ide> def self.installer_exist? <ide><path>Library/Homebrew/cask/lib/hbc/system_command.rb <ide> def self._parse_plist(command, output) <ide> _warn_plist_garbage(command, Regexp.last_match[2]) <ide> xml = Plist.parse_xml(output) <ide> unless xml.respond_to?(:keys) && !xml.keys.empty? <del> raise Hbc::CaskError, <<-ERRMSG <add> raise Hbc::CaskError, <<-EOS <ide> Empty result parsing plist output from command. <ide> command was: <ide> #{command.utf8_inspect} <ide> output we attempted to parse: <ide> #{output} <del> ERRMSG <add> EOS <ide> end <ide> xml <ide> rescue Plist::ParseError => e <del> raise Hbc::CaskError, <<-ERRMSG <add> raise Hbc::CaskError, <<-EOS <ide> Error parsing plist output from command. <ide> command was: <ide> #{command.utf8_inspect} <ide> error was: <ide> #{e} <ide> output we attempted to parse: <ide> #{output} <del> ERRMSG <add> EOS <ide> end <ide> end <ide><path>Library/Homebrew/cask/spec/cask/cli/cleanup_spec.rb <ide> <ide> expect { <ide> subject.cleanup! <del> }.to output(<<-OUTPUT.undent).to_stdout <add> }.to output(<<-EOS.undent).to_stdout <ide> ==> Removing cached downloads <ide> #{cached_download} <ide> ==> This operation has freed approximately #{disk_usage_readable(cleanup_size)} of disk space. <del> OUTPUT <add> EOS <ide> <ide> expect(cached_download.exist?).to eq(false) <ide> end <ide> <ide> expect { <ide> subject.cleanup! <del> }.to output(<<-OUTPUT.undent).to_stdout <add> }.to output(<<-EOS.undent).to_stdout <ide> ==> Removing cached downloads <ide> skipping: #{cached_download} is locked <ide> ==> This operation has freed approximately #{disk_usage_readable(cleanup_size)} of disk space. <del> OUTPUT <add> EOS <ide> <ide> expect(cached_download.exist?).to eq(true) <ide> end <ide> <ide> expect { <ide> subject.cleanup! <del> }.to output(<<-OUTPUT.undent).to_stdout <add> }.to output(<<-EOS.undent).to_stdout <ide> ==> Removing cached downloads older than 10 days old <ide> Nothing to do <del> OUTPUT <add> EOS <ide> <ide> expect(cached_download.exist?).to eq(true) <ide> end <ide><path>Library/Homebrew/cask/test/cask/artifact/uninstall_test.rb <ide> let(:launchctl_remove_cmd) { %w[/bin/launchctl remove my.fancy.package.service] } <ide> let(:unknown_response) { "launchctl list returned unknown response\n" } <ide> let(:service_info) { <del> <<-PLIST.undent <add> <<-EOS.undent <ide> { <ide> "LimitLoadToSessionType" = "Aqua"; <ide> "Label" = "my.fancy.package.service"; <ide> "argument"; <ide> ); <ide> }; <del> PLIST <add> EOS <ide> } <ide> <ide> describe "when launchctl job is owned by user" do <ide> ] <ide> } <ide> let(:pkg_info_plist) { <del> <<-PLIST.undent <add> <<-EOS.undent <ide> <?xml version="1.0" encoding="UTF-8"?> <ide> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <ide> <plist version="1.0"> <ide> <string>/</string> <ide> </dict> <ide> </plist> <del> PLIST <add> EOS <ide> } <ide> <ide> it "can uninstall" do <ide><path>Library/Homebrew/cask/test/cask/artifact/zap_test.rb <ide> let(:launchctl_remove_cmd) { %w[/bin/launchctl remove my.fancy.package.service] } <ide> let(:unknown_response) { "launchctl list returned unknown response\n" } <ide> let(:service_info) { <del> <<-PLIST.undent <add> <<-EOS.undent <ide> { <ide> "LimitLoadToSessionType" = "Aqua"; <ide> "Label" = "my.fancy.package.service"; <ide> "argument"; <ide> ); <ide> }; <del> PLIST <add> EOS <ide> } <ide> <ide> describe "when launchctl job is owned by user" do <ide> ] <ide> } <ide> let(:pkg_info_plist) { <del> <<-PLIST.undent <add> <<-EOS.undent <ide> <?xml version="1.0" encoding="UTF-8"?> <ide> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <ide> <plist version="1.0"> <ide> <string>/</string> <ide> </dict> <ide> </plist> <del> PLIST <add> EOS <ide> } <ide> <ide> it "can zap" do <ide><path>Library/Homebrew/cask/test/cask/cli/cat_test.rb <ide> describe Hbc::CLI::Cat do <ide> describe "given a basic Cask" do <ide> before do <del> @expected_output = <<-CLIOUTPUT.undent <add> @expected_output = <<-EOS.undent <ide> test_cask 'basic-cask' do <ide> version '1.2.3' <ide> sha256 '8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b' <ide> <ide> app 'TestCask.app' <ide> end <del> CLIOUTPUT <add> EOS <ide> end <ide> <ide> it "displays the Cask file content about the specified Cask" do <ide><path>Library/Homebrew/cask/test/cask/cli/create_test.rb <ide> def self.editor_commands <ide> it "drops a template down for the specified Cask" do <ide> Hbc::CLI::Create.run("new-cask") <ide> template = File.read(Hbc.path("new-cask")) <del> template.must_equal <<-TEMPLATE.undent <add> template.must_equal <<-EOS.undent <ide> cask 'new-cask' do <ide> version '' <ide> sha256 '' <ide> def self.editor_commands <ide> <ide> app '' <ide> end <del> TEMPLATE <add> EOS <ide> end <ide> <ide> it "throws away additional Cask arguments and uses the first" do <ide><path>Library/Homebrew/cask/test/cask/cli/search_test.rb <ide> it "lists the available Casks that match the search term" do <ide> lambda { <ide> Hbc::CLI::Search.run("photoshop") <del> }.must_output <<-OUTPUT.gsub(%r{^ *}, "") <add> }.must_output <<-EOS.undent <ide> ==> Partial matches <ide> adobe-photoshop-cc <ide> adobe-photoshop-lightroom <del> OUTPUT <add> EOS <ide> end <ide> <ide> it "shows that there are no Casks matching a search term that did not result in anything" do <ide><path>Library/Homebrew/cask/test/cask/cli/uninstall_test.rb <ide> timestamped_versions.each do |timestamped_version| <ide> caskroom_path.join(".metadata", *timestamped_version, "Casks").tap(&:mkpath) <ide> .join("#{token}.rb").open("w") do |caskfile| <del> caskfile.puts <<-EOF.undent <add> caskfile.puts <<-EOS.undent <ide> cask '#{token}' do <ide> version '#{timestamped_version[0]}' <ide> end <del> EOF <add> EOS <ide> end <ide> caskroom_path.join(timestamped_version[0]).mkpath <ide> end <ide> <ide> saved_caskfile.dirname.mkpath <ide> <del> IO.write saved_caskfile, <<-EOF.undent <add> IO.write saved_caskfile, <<-EOS.undent <ide> cask 'ive-been-renamed' do <ide> version :latest <ide> <ide> app 'ive-been-renamed.app' <ide> end <del> EOF <add> EOS <ide> end <ide> <ide> after do <ide><path>Library/Homebrew/cask/test/cask/dsl_test.rb <ide> end <ide> <ide> it "prints a warning that it has encountered an unexpected method" do <del> expected = Regexp.compile(<<-EOREGEX.undent.lines.map(&:chomp).join("")) <add> expected = Regexp.compile(<<-EOS.undent.lines.map(&:chomp).join("")) <ide> (?m) <ide> Warning: <ide> .* <ide> brew update; brew cleanup; brew cask cleanup <ide> .* <ide> https://github.com/caskroom/homebrew-cask#reporting-bugs <del> EOREGEX <add> EOS <ide> <ide> TestHelper.must_output(self, attempt_unknown_method, expected) <ide> end <ide><path>Library/Homebrew/cask/test/cask/url_checker_test.rb <ide> end <ide> <ide> it "properly populates the response code and headers from an http response" do <del> TestHelper.fake_response_for(TestHelper.test_cask.url, <<-RESPONSE.gsub(%r{^ *}, "")) <add> TestHelper.fake_response_for(TestHelper.test_cask.url, <<-EOS.undent) <ide> HTTP/1.1 200 OK <ide> Content-Type: application/x-apple-diskimage <ide> ETag: "b4208f3e84967be4b078ecaa03fba941" <ide> Content-Length: 23726161 <ide> Last-Modified: Sun, 12 Aug 2012 21:17:21 GMT <del> RESPONSE <add> EOS <ide> <ide> checker = Hbc::UrlChecker.new(TestHelper.test_cask, TestHelper.fake_fetcher) <ide> checker.run
13
Python
Python
support sentinel with ssl
18a0963ed36f87b8fb884ad27cfc2b7f1ca9f53c
<ide><path>celery/backends/redis.py <ide> class RedisBackend(BaseKeyValueStoreBackend, AsyncBackendMixin): <ide> <ide> #: :pypi:`redis` client module. <ide> redis = redis <add> connection_class_ssl = redis.SSLConnection if redis else None <ide> <ide> #: Maximum number of connections in the pool. <ide> max_connections = None <ide> def __init__(self, host=None, port=None, db=None, password=None, <ide> ssl = _get('redis_backend_use_ssl') <ide> if ssl: <ide> self.connparams.update(ssl) <del> self.connparams['connection_class'] = redis.SSLConnection <add> self.connparams['connection_class'] = self.connection_class_ssl <ide> <ide> if url: <ide> self.connparams = self._params_from_url(url, self.connparams) <ide> def __init__(self, host=None, port=None, db=None, password=None, <ide> # redis_backend_use_ssl dict, check ssl_cert_reqs is valid. If set <ide> # via query string ssl_cert_reqs will be a string so convert it here <ide> if ('connection_class' in self.connparams and <del> self.connparams['connection_class'] is redis.SSLConnection): <add> issubclass(self.connparams['connection_class'], redis.SSLConnection)): <ide> ssl_cert_reqs_missing = 'MISSING' <ide> ssl_string_to_constant = {'CERT_REQUIRED': CERT_REQUIRED, <ide> 'CERT_OPTIONAL': CERT_OPTIONAL, <ide> def __reduce__(self, args=(), kwargs=None): <ide> ) <ide> <ide> <add>if getattr(redis, "sentinel", None): <add> class SentinelManagedSSLConnection( <add> redis.sentinel.SentinelManagedConnection, <add> redis.SSLConnection): <add> """Connect to a Redis server using Sentinel + TLS. <add> <add> Use Sentinel to identify which Redis server is the current master <add> to connect to and when connecting to the Master server, use an <add> SSL Connection. <add> """ <add> <add> pass <add> <add> <ide> class SentinelBackend(RedisBackend): <ide> """Redis sentinel task result store.""" <ide> <ide> sentinel = getattr(redis, "sentinel", None) <add> connection_class_ssl = SentinelManagedSSLConnection if sentinel else None <ide> <ide> def __init__(self, *args, **kwargs): <ide> if self.sentinel is None: <ide><path>t/unit/backends/test_redis.py <ide> def test_get_pool(self): <ide> ) <ide> pool = x._get_pool(**x.connparams) <ide> assert pool <add> <add> def test_backend_ssl(self): <add> pytest.importorskip('redis') <add> <add> from celery.backends.redis import SentinelBackend <add> self.app.conf.redis_backend_use_ssl = { <add> 'ssl_cert_reqs': "CERT_REQUIRED", <add> 'ssl_ca_certs': '/path/to/ca.crt', <add> 'ssl_certfile': '/path/to/client.crt', <add> 'ssl_keyfile': '/path/to/client.key', <add> } <add> self.app.conf.redis_socket_timeout = 30.0 <add> self.app.conf.redis_socket_connect_timeout = 100.0 <add> x = SentinelBackend( <add> 'sentinel://:bosco@vandelay.com:123//1', app=self.app, <add> ) <add> assert x.connparams <add> assert len(x.connparams['hosts']) == 1 <add> assert x.connparams['hosts'][0]['host'] == 'vandelay.com' <add> assert x.connparams['hosts'][0]['db'] == 1 <add> assert x.connparams['hosts'][0]['port'] == 123 <add> assert x.connparams['hosts'][0]['password'] == 'bosco' <add> assert x.connparams['socket_timeout'] == 30.0 <add> assert x.connparams['socket_connect_timeout'] == 100.0 <add> assert x.connparams['ssl_cert_reqs'] == ssl.CERT_REQUIRED <add> assert x.connparams['ssl_ca_certs'] == '/path/to/ca.crt' <add> assert x.connparams['ssl_certfile'] == '/path/to/client.crt' <add> assert x.connparams['ssl_keyfile'] == '/path/to/client.key' <add> <add> from celery.backends.redis import SentinelManagedSSLConnection <add> assert x.connparams['connection_class'] is SentinelManagedSSLConnection
2
Python
Python
fix typo in docstring
af36d77d01866d310b0258f69d11a23d829dc231
<ide><path>spacy/tests/regression/test_issue4501-5000.py <ide> def test_issue4590(en_vocab): <ide> <ide> <ide> def test_issue4651_with_phrase_matcher_attr(): <del> """Test that the EntityRuler PhraseMatcher is deserialize correctly using <add> """Test that the EntityRuler PhraseMatcher is deserialized correctly using <ide> the method from_disk when the EntityRuler argument phrase_matcher_attr is <ide> specified. <ide> """ <ide> def test_issue4651_with_phrase_matcher_attr(): <ide> <ide> <ide> def test_issue4651_without_phrase_matcher_attr(): <del> """Test that the EntityRuler PhraseMatcher is deserialize correctly using <add> """Test that the EntityRuler PhraseMatcher is deserialized correctly using <ide> the method from_disk when the EntityRuler argument phrase_matcher_attr is <ide> not specified. <ide> """
1
Javascript
Javascript
use content-range instead of content-length
c02b2cb37c6c82a65b8877b5671122b6c23ae6b7
<ide><path>src/core/worker.js <ide> var WorkerMessageHandler = PDFJS.WorkerMessageHandler = { <ide> <ide> var length = fullRequestXhr.getResponseHeader('Content-Length'); <ide> length = parseInt(length, 10); <add>//#if (GENERIC || CHROME) <add> if (fullRequestXhr.status === 206) { <add> // Since Chrome 39, there exists a bug where cached responses are <add> // served with status code 206 for non-range requests. <add> // Content-Length does not specify the total size of the resource <add> // when the status code is 206 (see RFC 2616, section 14.16). <add> // In this case, extract the file size from the Content-Range <add> // header, which is defined to be "bytes start-end/length" for <add> // byte range requests. <add> // See https://github.com/mozilla/pdf.js/issues/5512 and <add> // https://code.google.com/p/chromium/issues/detail?id=442318 <add> length = fullRequestXhr.getResponseHeader('Content-Range'); <add> length = length && /bytes \d+-\d+\/(\d+)/.exec(length); <add> length = length && parseInt(length[1], 10); <add> } <add>//#endif <ide> if (!isInt(length)) { <ide> return; <ide> }
1
PHP
PHP
use the getattributes method on insert
c5401623dcb8eb3b7511c821c60d97427579cac5
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> protected function performInsert(Builder $query) <ide> // If the model has an incrementing key, we can use the "insertGetId" method on <ide> // the query builder, which will give us back the final inserted ID for this <ide> // table from the database. Not all tables have to be incrementing though. <del> $attributes = $this->attributes; <add> $attributes = $this->getAttributes(); <ide> <ide> if ($this->getIncrementing()) { <ide> $this->insertAndSetId($query, $attributes);
1
Ruby
Ruby
remove resolver autoload
d1e8912cff88ca93ed63120e75d74aee9e5ef76e
<ide><path>activerecord/lib/active_record/connection_adapters.rb <ide> module ConnectionAdapters <ide> autoload :Column <ide> autoload :PoolConfig <ide> autoload :PoolManager <del> autoload :Resolver <ide> <ide> autoload_at "active_record/connection_adapters/abstract/schema_definitions" do <ide> autoload :IndexDefinition
1
Javascript
Javascript
remove unused svelte spike code..
2861674ec08fe3c5342af5a084d8ae55e09a20e7
<ide><path>broccoli/deprecated-features.js <ide> function handleExportedDeclaration(d, map) { <ide> } <ide> <ide> module.exports = DEPRECATED_FEATURES; <del> <del>// TODO: remove this, it is primarily just for testing if svelte is working... <del>function svelte(infile, outfile) { <del> console.log(DEPRECATED_FEATURES); // eslint-disable-line no-console <del> const babel = require('babel-core'); // eslint-disable-line node/no-extraneous-require <del> <del> let { code } = babel.transformFileSync(infile, { <del> plugins: [ <del> [ <del> 'debug-macros', <del> { <del> debugTools: { <del> source: '@ember/debug', <del> assertPredicateIndex: 1, <del> isDebug: false, <del> }, <del> svelte: { <del> 'ember-source': '3.3.0', <del> }, <del> flags: [ <del> { <del> source: '@glimmer/env', <del> flags: { DEBUG: false }, <del> }, <del> { <del> name: 'ember-source', <del> source: '@ember/deprecated-features', <del> flags: DEPRECATED_FEATURES, <del> }, <del> { <del> source: '@ember/canary-features', <del> flags: { <del> EMBER_METAL_TRACKED_PROPERTIES: true, <del> }, <del> }, <del> ], <del> }, <del> ], <del> ], <del> }); <del> <del> fs.writeFileSync(outfile, code); <del>} <del> <del>if (process.env.SVELTE_TEST) { <del> svelte('dist/es/@ember/-internals/metal/lib/property_get.js', 'property_get.svelte.js'); <del> svelte('dist/es/@ember/-internals/metal/lib/property_set.js', 'property_set.svelte.js'); <del>}
1
Ruby
Ruby
remove unnecessary array allocations
dc79f803b1a5b0436a3375999bc10403c3edb513
<ide><path>Library/Homebrew/dependencies.rb <ide> class Dependencies <ide> include Enumerable <ide> <del> def initialize(*args) <del> @deps = Array.new(*args) <add> def initialize <add> @deps = [] <ide> end <ide> <ide> def each(*args, &block) <ide> def inspect <ide> class Requirements <ide> include Enumerable <ide> <del> def initialize(*args) <del> @reqs = Set.new(*args) <add> def initialize <add> @reqs = Set.new <ide> end <ide> <ide> def each(*args, &block)
1
PHP
PHP
fix doc string
d4f4f261d62e383ba6f38c856d644a9627c84a5c
<ide><path>src/Http/Response.php <ide> protected function _createStream(): void <ide> * Formats the Content-Type header based on the configured contentType and charset <ide> * the charset will only be set in the header if the response is of type text/* <ide> * <del> * @param string|null $type The type to set. <add> * @param string $type The type to set. <ide> * @return void <ide> */ <ide> protected function _setContentType(string $type): void
1
Text
Text
fix extraneous markup in changelog
dc0bea7a52d4646f46ced75828a5b92908af3374
<ide><path>CHANGELOG.md <ide> <ide> ### Major changes <ide> <del>- **Initial render now uses `document.createElement` instead of generating HTML.** Previously we would generate a large string of HTML and then set `node.innerHTML`. At the time, this was decided to be faster than using `document.createElement` for the majority of cases and browsers that we supported. Browsers have continued to improve and so overwhelmingly this is no longer true. By using `createElement` we can make other parts of React faster. (<small>[@spicyj](https://github.com/spicyj) in [#5205](https://github.com/facebook/react/pull/5205)) <del>- **`data-reactid` is no longer on every node.** As a result of using `document.createElement`, we can prime the node cache as we create DOM nodes, allowing us to skip a potential lookup (which used the `data-reactid` attribute). Root nodes will have a `data-reactroot` attribute and server generated markup will still contain `data-reactid`. (<small>[@spicyj](https://github.com/spicyj) in [#5205](https://github.com/facebook/react/pull/5205)) <add>- **Initial render now uses `document.createElement` instead of generating HTML.** Previously we would generate a large string of HTML and then set `node.innerHTML`. At the time, this was decided to be faster than using `document.createElement` for the majority of cases and browsers that we supported. Browsers have continued to improve and so overwhelmingly this is no longer true. By using `createElement` we can make other parts of React faster. ([@spicyj](https://github.com/spicyj) in [#5205](https://github.com/facebook/react/pull/5205)) <add>- **`data-reactid` is no longer on every node.** As a result of using `document.createElement`, we can prime the node cache as we create DOM nodes, allowing us to skip a potential lookup (which used the `data-reactid` attribute). Root nodes will have a `data-reactroot` attribute and server generated markup will still contain `data-reactid`. ([@spicyj](https://github.com/spicyj) in [#5205](https://github.com/facebook/react/pull/5205)) <ide> - **No more extra `<span>`s.** ReactDOM will now render plain text nodes interspersed with comment nodes that are used for demarcation. This gives us the same ability to update individual pieces of text, without creating extra nested nodes. If you were targeting these `<span>`s in your CSS, you will need to adjust accordingly. You can always render them explicitly in your components. ([@mwiencek](https://github.com/mwiencek) in [#5753](https://github.com/facebook/react/pull/5753)) <ide> - **Rendering `null` now uses comment nodes.** Previously `null` would render to `<noscript>` elements. We now use comment nodes. This may cause issues if making use of `:nth-child` CSS selectors. While we consider this rendering behavior an implementation detail of React, it's worth noting the potential problem. ([@spicyj](https://github.com/spicyj) in [#5451](https://github.com/facebook/react/pull/5451)) <ide> - **Functional components can now return `null`.** We added support for [defining stateless components as functions](/react/blog/2015/09/10/react-v0.14-rc1.html#stateless-function-components) in React 0.14. However, React 0.14 still allowed you to define a class component without extending `React.Component` or using `React.createClass()`, so [we couldn’t reliably tell if your component is a function or a class](https://github.com/facebook/react/issues/5355), and did not allow returning `null` from it. This issue is solved in React 15, and you can now return `null` from any component, whether it is a class or a function. ([@jimfb](https://github.com/jimfb) in [#5884](https://github.com/facebook/react/pull/5884))
1
Python
Python
allow lowercase log levels.
08fb1d06cff06397f365c546032479b8d9925931
<ide><path>celery/bin/base.py <ide> def __init__(self): <ide> super().__init__(('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'FATAL')) <ide> <ide> def convert(self, value, param, ctx): <add> value = value.upper() <ide> value = super().convert(value, param, ctx) <ide> return mlevel(value) <ide>
1
Javascript
Javascript
update example to use a module
474251928ecba842610ea0aee3b0f51f317e0dc9
<ide><path>src/ng/directive/ngSwitch.js <ide> * <ide> * <ide> * @example <del> <example module="ngAnimate" deps="angular-animate.js" animations="true"> <add> <example module="switchExample" deps="angular-animate.js" animations="true"> <ide> <file name="index.html"> <del> <div ng-controller="Ctrl"> <add> <div ng-controller="ExampleController"> <ide> <select ng-model="selection" ng-options="item for item in items"> <ide> </select> <ide> <tt>selection={{selection}}</tt> <ide> </div> <ide> </file> <ide> <file name="script.js"> <del> function Ctrl($scope) { <del> $scope.items = ['settings', 'home', 'other']; <del> $scope.selection = $scope.items[0]; <del> } <add> angular.module('switchExample', ['ngAnimate']) <add> .controller('ExampleController', ['$scope', function($scope) { <add> $scope.items = ['settings', 'home', 'other']; <add> $scope.selection = $scope.items[0]; <add> }]); <ide> </file> <ide> <file name="animations.css"> <ide> .animate-switch-container {
1
Javascript
Javascript
catch only chunk loading errors
d900e7df0b5c65d6c81b8c66660d0c34c3fe963d
<ide><path>lib/dependencies/DepBlockHelpers.js <ide> var DepBlockHelpers = exports; <ide> DepBlockHelpers.getLoadDepBlockWrapper = function(depBlock, outputOptions, requestShortener, name) { <ide> var promiseCode = DepBlockHelpers.getDepBlockPromise(depBlock, outputOptions, requestShortener, name); <ide> return [ <del> promiseCode + ".then(", <del> ").catch(function(err) { __webpack_require__.oe(err); })" <add> promiseCode + ".catch(function(err) { __webpack_require__.oe(err); }).then(", <add> ")" <ide> ]; <ide> }; <ide>
1
Java
Java
use volatile for subscriber in base publishers
06b2ab39088f128d3aa5ca355d0bc0f2c7b36ab3
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerReadPublisher.java <ide> <ide> private volatile long demand; <ide> <del> private volatile boolean completionBeforeDemand; <del> <del> @Nullable <del> private volatile Throwable errorBeforeDemand; <del> <ide> @SuppressWarnings("rawtypes") <ide> private static final AtomicLongFieldUpdater<AbstractListenerReadPublisher> DEMAND_FIELD_UPDATER = <ide> AtomicLongFieldUpdater.newUpdater(AbstractListenerReadPublisher.class, "demand"); <ide> <ide> @Nullable <del> private Subscriber<? super T> subscriber; <add> private volatile Subscriber<? super T> subscriber; <add> <add> private volatile boolean completionBeforeDemand; <add> <add> @Nullable <add> private volatile Throwable errorBeforeDemand; <ide> <ide> <ide> // Publisher implementation... <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/WriteResultPublisher.java <ide> class WriteResultPublisher implements Publisher<Void> { <ide> private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED); <ide> <ide> @Nullable <del> private Subscriber<? super Void> subscriber; <add> private volatile Subscriber<? super Void> subscriber; <ide> <ide> private volatile boolean completedBeforeSubscribed; <ide>
2
Mixed
Python
make filtering optional, and pluggable
47b534a13e42d498629bf9522225633122c563d5
<ide><path>docs/api-guide/filtering.md <add># Filtering <add> <add>> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. <add>> <add>> &mdash; [Django documentation][cite] <add> <add>The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset. <add> <add>The simplest way to filter the queryset of any view that subclasses `MultipleObjectAPIView` is to override the `.get_queryset()` method. <add> <add>Overriding this method allows you to customize the queryset returned by the view in a number of different ways. <add> <add>## Filtering against the current user <add> <add>You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned. <add> <add>You can do so by filtering based on the value of `request.user`. <add> <add>For example: <add> <add> class PurchaseList(generics.ListAPIView) <add> model = Purchase <add> serializer_class = PurchaseSerializer <add> <add> def get_queryset(self): <add> """ <add> This view should return a list of all the purchases <add> for the currently authenticated user. <add> """ <add> user = self.request.user <add> return Purchase.objects.filter(purchaser=user) <add> <add> <add>## Filtering against the URL <add> <add>Another style of filtering might involve restricting the queryset based on some part of the URL. <add> <add>For example if your URL config contained an entry like this: <add> <add> url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()), <add> <add>You could then write a view that returned a purchase queryset filtered by the username portion of the URL: <add> <add> class PurchaseList(generics.ListAPIView) <add> model = Purchase <add> serializer_class = PurchaseSerializer <add> <add> def get_queryset(self): <add> """ <add> This view should return a list of all the purchases for <add> the user as determined by the username portion of the URL. <add> """ <add> username = self.kwargs['username'] <add> return Purchase.objects.filter(purchaser__username=username) <add> <add>## Filtering against query parameters <add> <add>A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url. <add> <add>We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL: <add> <add> class PurchaseList(generics.ListAPIView) <add> model = Purchase <add> serializer_class = PurchaseSerializer <add> <add> def get_queryset(self): <add> """ <add> Optionally restricts the returned purchases to a given user, <add> by filtering against a `username` query parameter in the URL. <add> """ <add> queryset = Purchase.objects.all() <add> username = self.request.QUERY_PARAMS.get('username', None): <add> if username is not None: <add> queryset = queryset.filter(purchaser__username=username) <add> return queryset <add> <add># Generic Filtering <add> <add>As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters. <add> <add>REST framework supports pluggable backends to implement filtering, and includes a default implementation which uses the [django-filter] package. <add> <add>To use REST framework's default filtering backend, first install `django-filter`. <add> <add> pip install -e git+https://github.com/alex/django-filter.git#egg=django-filter <add> <add>**Note**: The currently supported version of `django-filter` is the `master` branch. A PyPI release is expected to be coming soon. <add> <add>## Specifying filter fields <add> <add>**TODO**: Document setting `.filter_fields` on the view. <add> <add>## Specifying a FilterSet <add> <add>**TODO**: Document setting `.filter_class` on the view. <add> <add>**TODO**: Note support for `lookup_type`, double underscore relationship spanning, and ordering. <add> <add># Custom generic filtering <add> <add>You can also provide your own generic filtering backend, or write an installable app for other developers to use. <add> <add>To do so overide `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. <add> <add>To install the filter, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class. <add> <add>For example: <add> <add> REST_FRAMEWORK = { <add> 'FILTER_BACKEND': 'custom_filters.CustomFilterBackend' <add> } <add> <add>[cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters <add>[django-filter]: https://github.com/alex/django-filter <ide>\ No newline at end of file <ide><path>rest_framework/compat.py <ide> # flake8: noqa <ide> import django <ide> <add># django-filter is optional <add>try: <add> import django_filters <add>except: <add> django_filters = None <add> <add> <ide> # cStringIO only if it's available, otherwise StringIO <ide> try: <ide> import cStringIO as StringIO <ide> def apply_markdown(text): <ide> yaml = None <ide> <ide> <del>import unittest <del>try: <del> import unittest.skip <del>except ImportError: # python < 2.7 <del> from unittest import TestCase <del> import functools <del> <del> def skip(reason): <del> # Pasted from py27/lib/unittest/case.py <del> """ <del> Unconditionally skip a test. <del> """ <del> def decorator(test_item): <del> if not (isinstance(test_item, type) and issubclass(test_item, TestCase)): <del> @functools.wraps(test_item) <del> def skip_wrapper(*args, **kwargs): <del> pass <del> test_item = skip_wrapper <del> <del> test_item.__unittest_skip__ = True <del> test_item.__unittest_skip_why__ = reason <del> return test_item <del> return decorator <del> <del> unittest.skip = skip <del> <del> <ide> # xml.etree.parse only throws ParseError for python >= 2.7 <ide> try: <ide> from xml.etree import ParseError as ETParseError <ide><path>rest_framework/filters.py <add>from rest_framework.compat import django_filters <add> <add> <add>class BaseFilterBackend(object): <add> """ <add> A base class from which all filter backend classes should inherit. <add> """ <add> <add> def filter_queryset(self, request, queryset, view): <add> """ <add> Return a filtered queryset. <add> """ <add> raise NotImplementedError(".filter_queryset() must be overridden.") <add> <add> <add>class DjangoFilterBackend(BaseFilterBackend): <add> """ <add> A filter backend that uses django-filter. <add> """ <add> <add> def get_filter_class(self, view): <add> """ <add> Return the django-filters `FilterSet` used to filter the queryset. <add> """ <add> filter_class = getattr(view, 'filter_class', None) <add> filter_fields = getattr(view, 'filter_fields', None) <add> filter_model = getattr(view, 'model', None) <add> <add> if filter_class or filter_fields: <add> assert django_filters, 'django-filter is not installed' <add> <add> if filter_class: <add> assert issubclass(filter_class.Meta.model, filter_model), \ <add> '%s is not a subclass of %s' % (filter_class.Meta.model, filter_model) <add> return filter_class <add> <add> if filter_fields: <add> class AutoFilterSet(django_filters.FilterSet): <add> class Meta: <add> model = filter_model <add> fields = filter_fields <add> return AutoFilterSet <add> <add> return None <add> <add> def filter_queryset(self, request, queryset, view): <add> filter_class = self.get_filter_class(view) <add> <add> if filter_class: <add> return filter_class(request.GET, queryset=queryset) <add> <add> return queryset <ide><path>rest_framework/generics.py <ide> from rest_framework.settings import api_settings <ide> from django.views.generic.detail import SingleObjectMixin <ide> from django.views.generic.list import MultipleObjectMixin <del>import django_filters <add> <ide> <ide> ### Base classes for the generic views ### <ide> <ide> class MultipleObjectAPIView(MultipleObjectMixin, GenericAPIView): <ide> <ide> pagination_serializer_class = api_settings.DEFAULT_PAGINATION_SERIALIZER_CLASS <ide> paginate_by = api_settings.PAGINATE_BY <del> filter_class = None <del> filter_fields = None <del> <del> def get_filter_class(self): <del> """ <del> Return the django-filters `FilterSet` used to filter the queryset. <del> """ <del> if self.filter_class: <del> return self.filter_class <del> <del> if self.filter_fields: <del> class AutoFilterSet(django_filters.FilterSet): <del> class Meta: <del> model = self.model <del> fields = self.filter_fields <del> return AutoFilterSet <del> <del> return None <add> filter_backend = api_settings.FILTER_BACKEND <ide> <ide> def filter_queryset(self, queryset): <del> filter_class = self.get_filter_class() <del> <del> if filter_class: <del> assert issubclass(filter_class.Meta.model, self.model), \ <del> "%s is not a subclass of %s" % (filter_class.Meta.model, self.model) <del> return filter_class(self.request.GET, queryset=queryset) <del> <del> return queryset <add> if not self.filter_backend: <add> return queryset <add> backend = self.filter_backend() <add> return backend.filter_queryset(self.request, queryset, self) <ide> <ide> def get_filtered_queryset(self): <ide> return self.filter_queryset(self.get_queryset()) <ide><path>rest_framework/pagination.py <ide> from rest_framework import serializers <add>from rest_framework.templatetags.rest_framework import replace_query_param <ide> <ide> # TODO: Support URLconf kwarg-style paging <ide> <ide> def to_native(self, value): <ide> return None <ide> page = value.next_page_number() <ide> request = self.context.get('request') <del> relative_url = '?%s=%d' % (self.page_field, page) <del> if request: <del> for field, value in request.QUERY_PARAMS.iteritems(): <del> if field != self.page_field: <del> relative_url += '&%s=%s' % (field, value) <del> return request.build_absolute_uri(relative_url) <del> return relative_url <add> url = request and request.get_full_path() or '' <add> return replace_query_param(url, self.page_field, page) <ide> <ide> <ide> class PreviousPageField(PageField): <ide> def to_native(self, value): <ide> return None <ide> page = value.previous_page_number() <ide> request = self.context.get('request') <del> relative_url = '?%s=%d' % (self.page_field, page) <del> if request: <del> for field, value in request.QUERY_PARAMS.iteritems(): <del> if field != self.page_field: <del> relative_url += '&%s=%s' % (field, value) <del> return request.build_absolute_uri(relative_url) <del> return relative_url <add> url = request and request.get_full_path() or '' <add> return replace_query_param(url, self.page_field, page) <ide> <ide> <ide> class PaginationSerializerOptions(serializers.SerializerOptions): <ide><path>rest_framework/settings.py <ide> 'anon': None, <ide> }, <ide> 'PAGINATE_BY': None, <add> 'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend', <ide> <ide> 'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser', <ide> 'UNAUTHENTICATED_TOKEN': None, <ide> 'DEFAULT_CONTENT_NEGOTIATION_CLASS', <ide> 'DEFAULT_MODEL_SERIALIZER_CLASS', <ide> 'DEFAULT_PAGINATION_SERIALIZER_CLASS', <add> 'FILTER_BACKEND', <ide> 'UNAUTHENTICATED_USER', <ide> 'UNAUTHENTICATED_TOKEN', <ide> ) <ide><path>rest_framework/templatetags/rest_framework.py <ide> from django import template <ide> from django.core.urlresolvers import reverse <del>from django.http import QueryDict <ide> from django.utils.encoding import force_unicode <ide> from django.utils.html import escape <ide> from django.utils.safestring import SafeData, mark_safe <add>from django.http import QueryDict <ide> from urlparse import urlsplit, urlunsplit <ide> import re <ide> import string <ide> <ide> register = template.Library() <ide> <ide> <add>def replace_query_param(url, key, val): <add> """ <add> Given a URL and a key/val pair, set or replace an item in the query <add> parameters of the URL, and return the new URL. <add> """ <add> (scheme, netloc, path, query, fragment) = urlsplit(url) <add> query_dict = QueryDict(query).copy() <add> query_dict[key] = val <add> query = query_dict.urlencode() <add> return urlunsplit((scheme, netloc, path, query, fragment)) <add> <add> <ide> # Regex for adding classes to html snippets <ide> class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])') <ide> <ide> trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z') <ide> <ide> <del># Helper function for 'add_query_param' <del>def replace_query_param(url, key, val): <del> """ <del> Given a URL and a key/val pair, set or replace an item in the query <del> parameters of the URL, and return the new URL. <del> """ <del> (scheme, netloc, path, query, fragment) = urlsplit(url) <del> query_dict = QueryDict(query).copy() <del> query_dict[key] = val <del> query = query_dict.urlencode() <del> return urlunsplit((scheme, netloc, path, query, fragment)) <del> <del> <ide> # And the template tags themselves... <ide> <ide> @register.simple_tag <ide><path>rest_framework/tests/filterset.py <ide> from decimal import Decimal <ide> from django.test import TestCase <ide> from django.test.client import RequestFactory <add>from django.utils import unittest <ide> from rest_framework import generics, status <add>from rest_framework.compat import django_filters <ide> from rest_framework.tests.models import FilterableItem, BasicModel <del>import django_filters <ide> <ide> factory = RequestFactory() <ide> <del># Basic filter on a list view. <del>class FilterFieldsRootView(generics.ListCreateAPIView): <del> model = FilterableItem <del> filter_fields = ['decimal', 'date'] <ide> <del> <del># These class are used to test a filter class. <del>class SeveralFieldsFilter(django_filters.FilterSet): <del> text = django_filters.CharFilter(lookup_type='icontains') <del> decimal = django_filters.NumberFilter(lookup_type='lt') <del> date = django_filters.DateFilter(lookup_type='gt') <del> class Meta: <add>if django_filters: <add> # Basic filter on a list view. <add> class FilterFieldsRootView(generics.ListCreateAPIView): <ide> model = FilterableItem <del> fields = ['text', 'decimal', 'date'] <add> filter_fields = ['decimal', 'date'] <ide> <add> # These class are used to test a filter class. <add> class SeveralFieldsFilter(django_filters.FilterSet): <add> text = django_filters.CharFilter(lookup_type='icontains') <add> decimal = django_filters.NumberFilter(lookup_type='lt') <add> date = django_filters.DateFilter(lookup_type='gt') <ide> <del>class FilterClassRootView(generics.ListCreateAPIView): <del> model = FilterableItem <del> filter_class = SeveralFieldsFilter <add> class Meta: <add> model = FilterableItem <add> fields = ['text', 'decimal', 'date'] <ide> <add> class FilterClassRootView(generics.ListCreateAPIView): <add> model = FilterableItem <add> filter_class = SeveralFieldsFilter <ide> <del># These classes are used to test a misconfigured filter class. <del>class MisconfiguredFilter(django_filters.FilterSet): <del> text = django_filters.CharFilter(lookup_type='icontains') <del> class Meta: <del> model = BasicModel <del> fields = ['text'] <add> # These classes are used to test a misconfigured filter class. <add> class MisconfiguredFilter(django_filters.FilterSet): <add> text = django_filters.CharFilter(lookup_type='icontains') <ide> <add> class Meta: <add> model = BasicModel <add> fields = ['text'] <ide> <del>class IncorrectlyConfiguredRootView(generics.ListCreateAPIView): <del> model = FilterableItem <del> filter_class = MisconfiguredFilter <add> class IncorrectlyConfiguredRootView(generics.ListCreateAPIView): <add> model = FilterableItem <add> filter_class = MisconfiguredFilter <ide> <ide> <ide> class IntegrationTestFiltering(TestCase): <ide> def setUp(self): <ide> for obj in self.objects.all() <ide> ] <ide> <add> @unittest.skipUnless(django_filters, 'django-filters not installed') <ide> def test_get_filtered_fields_root_view(self): <ide> """ <ide> GET requests to paginated ListCreateAPIView should return paginated results. <ide> def test_get_filtered_fields_root_view(self): <ide> request = factory.get('/?decimal=%s' % search_decimal) <ide> response = view(request).render() <ide> self.assertEquals(response.status_code, status.HTTP_200_OK) <del> expected_data = [ f for f in self.data if f['decimal'] == search_decimal ] <add> expected_data = [f for f in self.data if f['decimal'] == search_decimal] <ide> self.assertEquals(response.data, expected_data) <ide> <ide> # Tests that the date filter works. <ide> search_date = datetime.date(2012, 9, 22) <ide> request = factory.get('/?date=%s' % search_date) # search_date str: '2012-09-22' <ide> response = view(request).render() <ide> self.assertEquals(response.status_code, status.HTTP_200_OK) <del> expected_data = [ f for f in self.data if f['date'] == search_date ] <add> expected_data = [f for f in self.data if f['date'] == search_date] <ide> self.assertEquals(response.data, expected_data) <ide> <add> @unittest.skipUnless(django_filters, 'django-filters not installed') <ide> def test_get_filtered_class_root_view(self): <ide> """ <ide> GET requests to filtered ListCreateAPIView that have a filter_class set <ide> def test_get_filtered_class_root_view(self): <ide> request = factory.get('/?decimal=%s' % search_decimal) <ide> response = view(request).render() <ide> self.assertEquals(response.status_code, status.HTTP_200_OK) <del> expected_data = [ f for f in self.data if f['decimal'] < search_decimal ] <add> expected_data = [f for f in self.data if f['decimal'] < search_decimal] <ide> self.assertEquals(response.data, expected_data) <ide> <ide> # Tests that the date filter set with 'gt' in the filter class works. <ide> search_date = datetime.date(2012, 10, 2) <ide> request = factory.get('/?date=%s' % search_date) # search_date str: '2012-10-02' <ide> response = view(request).render() <ide> self.assertEquals(response.status_code, status.HTTP_200_OK) <del> expected_data = [ f for f in self.data if f['date'] > search_date ] <add> expected_data = [f for f in self.data if f['date'] > search_date] <ide> self.assertEquals(response.data, expected_data) <ide> <ide> # Tests that the text filter set with 'icontains' in the filter class works. <ide> search_text = 'ff' <ide> request = factory.get('/?text=%s' % search_text) <ide> response = view(request).render() <ide> self.assertEquals(response.status_code, status.HTTP_200_OK) <del> expected_data = [ f for f in self.data if search_text in f['text'].lower() ] <add> expected_data = [f for f in self.data if search_text in f['text'].lower()] <ide> self.assertEquals(response.data, expected_data) <ide> <ide> # Tests that multiple filters works. <ide> def test_get_filtered_class_root_view(self): <ide> request = factory.get('/?decimal=%s&date=%s' % (search_decimal, search_date)) <ide> response = view(request).render() <ide> self.assertEquals(response.status_code, status.HTTP_200_OK) <del> expected_data = [ f for f in self.data if f['date'] > search_date and <del> f['decimal'] < search_decimal ] <add> expected_data = [f for f in self.data if f['date'] > search_date and <add> f['decimal'] < search_decimal] <ide> self.assertEquals(response.data, expected_data) <ide> <add> @unittest.skipUnless(django_filters, 'django-filters not installed') <ide> def test_incorrectly_configured_filter(self): <ide> """ <ide> An error should be displayed when the filter class is misconfigured. <ide> def test_incorrectly_configured_filter(self): <ide> request = factory.get('/') <ide> self.assertRaises(AssertionError, view, request) <ide> <add> @unittest.skipUnless(django_filters, 'django-filters not installed') <ide> def test_unknown_filter(self): <ide> """ <ide> GET requests with filters that aren't configured should return 200. <ide> def test_unknown_filter(self): <ide> search_integer = 10 <ide> request = factory.get('/?integer=%s' % search_integer) <ide> response = view(request).render() <del> self.assertEquals(response.status_code, status.HTTP_200_OK) <ide>\ No newline at end of file <add> self.assertEquals(response.status_code, status.HTTP_200_OK) <ide><path>rest_framework/tests/pagination.py <ide> from django.core.paginator import Paginator <ide> from django.test import TestCase <ide> from django.test.client import RequestFactory <add>from django.utils import unittest <ide> from rest_framework import generics, status, pagination <add>from rest_framework.compat import django_filters <ide> from rest_framework.tests.models import BasicModel, FilterableItem <del>import django_filters <ide> <ide> factory = RequestFactory() <ide> <ide> class RootView(generics.ListCreateAPIView): <ide> paginate_by = 10 <ide> <ide> <del>class DecimalFilter(django_filters.FilterSet): <del> decimal = django_filters.NumberFilter(lookup_type='lt') <del> class Meta: <del> model = FilterableItem <del> fields = ['text', 'decimal', 'date'] <add>if django_filters: <add> class DecimalFilter(django_filters.FilterSet): <add> decimal = django_filters.NumberFilter(lookup_type='lt') <ide> <add> class Meta: <add> model = FilterableItem <add> fields = ['text', 'decimal', 'date'] <ide> <del>class FilterFieldsRootView(generics.ListCreateAPIView): <del> model = FilterableItem <del> paginate_by = 10 <del> filter_class = DecimalFilter <add> class FilterFieldsRootView(generics.ListCreateAPIView): <add> model = FilterableItem <add> paginate_by = 10 <add> filter_class = DecimalFilter <ide> <ide> <ide> class IntegrationTestPagination(TestCase): <ide> def setUp(self): <ide> ] <ide> self.view = FilterFieldsRootView.as_view() <ide> <add> @unittest.skipUnless(django_filters, 'django-filters not installed') <ide> def test_get_paginated_filtered_root_view(self): <ide> """ <ide> GET requests to paginated filtered ListCreateAPIView should return <ide><path>rest_framework/tests/response.py <ide> def test_specified_renderer_serializes_content_on_accept_query(self): <ide> self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT)) <ide> self.assertEquals(resp.status_code, DUMMYSTATUS) <ide> <del> @unittest.skip('can\'t pass because view is a simple Django view and response is an ImmediateResponse') <del> def test_unsatisfiable_accept_header_on_request_returns_406_status(self): <del> """If the Accept header is unsatisfiable we should return a 406 Not Acceptable response.""" <del> resp = self.client.get('/', HTTP_ACCEPT='foo/bar') <del> self.assertEquals(resp.status_code, status.HTTP_406_NOT_ACCEPTABLE) <del> <ide> def test_specified_renderer_serializes_content_on_format_query(self): <ide> """If a 'format' query is specified, the renderer with the matching <ide> format attribute should serialize the response.""" <ide><path>rest_framework/utils/__init__.py <ide> from django.utils.encoding import smart_unicode <ide> from django.utils.xmlutils import SimplerXMLGenerator <ide> from rest_framework.compat import StringIO <del> <ide> import re <ide> import xml.etree.ElementTree as ET <ide>
11
Javascript
Javascript
use const or let and assert.strictequal
8a3c7d76b38c848d33acbf963e11d2b6be1a44ec
<ide><path>test/parallel/test-fs-read-file-sync.js <ide> 'use strict'; <del>var common = require('../common'); <del>var assert = require('assert'); <del>var path = require('path'); <del>var fs = require('fs'); <add>const common = require('../common'); <add>const assert = require('assert'); <add>const path = require('path'); <add>const fs = require('fs'); <ide> <del>var fn = path.join(common.fixturesDir, 'elipses.txt'); <add>const fn = path.join(common.fixturesDir, 'elipses.txt'); <ide> <del>var s = fs.readFileSync(fn, 'utf8'); <del>for (var i = 0; i < s.length; i++) { <del> assert.equal('\u2026', s[i]); <add>const s = fs.readFileSync(fn, 'utf8'); <add>for (let i = 0; i < s.length; i++) { <add> assert.strictEqual('\u2026', s[i]); <ide> } <del>assert.equal(10000, s.length); <add>assert.strictEqual(10000, s.length);
1
Javascript
Javascript
convert the page view to es6 syntax
6dfdff2f03d764f1c2d177586ffd5998d1f4edfc
<ide><path>web/pdf_page_view.js <ide> import { <ide> import { getGlobalEventBus } from './dom_events'; <ide> import { RenderingStates } from './pdf_rendering_queue'; <ide> <del>var TEXT_LAYER_RENDER_DELAY = 200; // ms <add>const TEXT_LAYER_RENDER_DELAY = 200; // ms <ide> <ide> /** <ide> * @typedef {Object} PDFPageViewOptions <ide> var TEXT_LAYER_RENDER_DELAY = 200; // ms <ide> */ <ide> <ide> /** <del> * @class <ide> * @implements {IRenderableView} <ide> */ <del>var PDFPageView = (function PDFPageViewClosure() { <add>class PDFPageView { <ide> /** <del> * @constructs PDFPageView <ide> * @param {PDFPageViewOptions} options <ide> */ <del> function PDFPageView(options) { <del> var container = options.container; <del> var id = options.id; <del> var scale = options.scale; <del> var defaultViewport = options.defaultViewport; <del> var renderingQueue = options.renderingQueue; <del> var textLayerFactory = options.textLayerFactory; <del> var annotationLayerFactory = options.annotationLayerFactory; <del> var enhanceTextSelection = options.enhanceTextSelection || false; <del> var renderInteractiveForms = options.renderInteractiveForms || false; <del> <del> this.id = id; <del> this.renderingId = 'page' + id; <del> this.pageLabel = null; <add> constructor(options) { <add> let container = options.container; <add> let defaultViewport = options.defaultViewport; <add> <add> this.id = options.id; <add> this.renderingId = 'page' + this.id; <ide> <add> this.pageLabel = null; <ide> this.rotation = 0; <del> this.scale = scale || DEFAULT_SCALE; <add> this.scale = options.scale || DEFAULT_SCALE; <ide> this.viewport = defaultViewport; <ide> this.pdfPageRotate = defaultViewport.rotation; <ide> this.hasRestrictedScaling = false; <del> this.enhanceTextSelection = enhanceTextSelection; <del> this.renderInteractiveForms = renderInteractiveForms; <add> this.enhanceTextSelection = options.enhanceTextSelection || false; <add> this.renderInteractiveForms = options.renderInteractiveForms || false; <ide> <ide> this.eventBus = options.eventBus || getGlobalEventBus(); <del> this.renderingQueue = renderingQueue; <del> this.textLayerFactory = textLayerFactory; <del> this.annotationLayerFactory = annotationLayerFactory; <add> this.renderingQueue = options.renderingQueue; <add> this.textLayerFactory = options.textLayerFactory; <add> this.annotationLayerFactory = options.annotationLayerFactory; <ide> this.renderer = options.renderer || RendererType.CANVAS; <ide> <ide> this.paintTask = null; <ide> var PDFPageView = (function PDFPageViewClosure() { <ide> this.onBeforeDraw = null; <ide> this.onAfterDraw = null; <ide> <add> this.annotationLayer = null; <ide> this.textLayer = null; <del> <ide> this.zoomLayer = null; <ide> <del> this.annotationLayer = null; <del> <del> var div = document.createElement('div'); <add> let div = document.createElement('div'); <ide> div.className = 'page'; <ide> div.style.width = Math.floor(this.viewport.width) + 'px'; <ide> div.style.height = Math.floor(this.viewport.height) + 'px'; <ide> var PDFPageView = (function PDFPageViewClosure() { <ide> container.appendChild(div); <ide> } <ide> <del> PDFPageView.prototype = { <del> setPdfPage: function PDFPageView_setPdfPage(pdfPage) { <del> this.pdfPage = pdfPage; <del> this.pdfPageRotate = pdfPage.rotate; <del> var totalRotation = (this.rotation + this.pdfPageRotate) % 360; <del> this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, <del> totalRotation); <del> this.stats = pdfPage.stats; <del> this.reset(); <del> }, <add> setPdfPage(pdfPage) { <add> this.pdfPage = pdfPage; <add> this.pdfPageRotate = pdfPage.rotate; <ide> <del> destroy: function PDFPageView_destroy() { <del> this.reset(); <del> if (this.pdfPage) { <del> this.pdfPage.cleanup(); <del> } <del> }, <del> <del> /** <del> * @private <del> */ <del> _resetZoomLayer(removeFromDOM = false) { <del> if (!this.zoomLayer) { <del> return; <del> } <del> var zoomLayerCanvas = this.zoomLayer.firstChild; <del> this.paintedViewportMap.delete(zoomLayerCanvas); <del> // Zeroing the width and height causes Firefox to release graphics <del> // resources immediately, which can greatly reduce memory consumption. <del> zoomLayerCanvas.width = 0; <del> zoomLayerCanvas.height = 0; <del> <del> if (removeFromDOM) { <del> // Note: ChildNode.remove doesn't throw if the parentNode is undefined. <del> this.zoomLayer.remove(); <del> } <del> this.zoomLayer = null; <del> }, <del> <del> reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) { <del> this.cancelRendering(); <del> <del> var div = this.div; <del> div.style.width = Math.floor(this.viewport.width) + 'px'; <del> div.style.height = Math.floor(this.viewport.height) + 'px'; <del> <del> var childNodes = div.childNodes; <del> var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null; <del> var currentAnnotationNode = (keepAnnotations && this.annotationLayer && <del> this.annotationLayer.div) || null; <del> for (var i = childNodes.length - 1; i >= 0; i--) { <del> var node = childNodes[i]; <del> if (currentZoomLayerNode === node || currentAnnotationNode === node) { <del> continue; <del> } <del> div.removeChild(node); <del> } <del> div.removeAttribute('data-loaded'); <add> let totalRotation = (this.rotation + this.pdfPageRotate) % 360; <add> this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, <add> totalRotation); <add> this.stats = pdfPage.stats; <add> this.reset(); <add> } <ide> <del> if (currentAnnotationNode) { <del> // Hide annotationLayer until all elements are resized <del> // so they are not displayed on the already-resized page <del> this.annotationLayer.hide(); <del> } else { <del> this.annotationLayer = null; <del> } <add> destroy() { <add> this.reset(); <add> if (this.pdfPage) { <add> this.pdfPage.cleanup(); <add> } <add> } <ide> <del> if (!currentZoomLayerNode) { <del> if (this.canvas) { <del> this.paintedViewportMap.delete(this.canvas); <del> // Zeroing the width and height causes Firefox to release graphics <del> // resources immediately, which can greatly reduce memory consumption. <del> this.canvas.width = 0; <del> this.canvas.height = 0; <del> delete this.canvas; <del> } <del> this._resetZoomLayer(); <del> } <del> if (this.svg) { <del> this.paintedViewportMap.delete(this.svg); <del> delete this.svg; <del> } <add> /** <add> * @private <add> */ <add> _resetZoomLayer(removeFromDOM = false) { <add> if (!this.zoomLayer) { <add> return; <add> } <add> let zoomLayerCanvas = this.zoomLayer.firstChild; <add> this.paintedViewportMap.delete(zoomLayerCanvas); <add> // Zeroing the width and height causes Firefox to release graphics <add> // resources immediately, which can greatly reduce memory consumption. <add> zoomLayerCanvas.width = 0; <add> zoomLayerCanvas.height = 0; <add> <add> if (removeFromDOM) { <add> // Note: `ChildNode.remove` doesn't throw if the parent node is undefined. <add> this.zoomLayer.remove(); <add> } <add> this.zoomLayer = null; <add> } <ide> <del> this.loadingIconDiv = document.createElement('div'); <del> this.loadingIconDiv.className = 'loadingIcon'; <del> div.appendChild(this.loadingIconDiv); <del> }, <add> reset(keepZoomLayer = false, keepAnnotations = false) { <add> this.cancelRendering(); <ide> <del> update: function PDFPageView_update(scale, rotation) { <del> this.scale = scale || this.scale; <add> let div = this.div; <add> div.style.width = Math.floor(this.viewport.width) + 'px'; <add> div.style.height = Math.floor(this.viewport.height) + 'px'; <ide> <del> if (typeof rotation !== 'undefined') { <del> this.rotation = rotation; <add> let childNodes = div.childNodes; <add> let currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null; <add> let currentAnnotationNode = (keepAnnotations && this.annotationLayer && <add> this.annotationLayer.div) || null; <add> for (let i = childNodes.length - 1; i >= 0; i--) { <add> let node = childNodes[i]; <add> if (currentZoomLayerNode === node || currentAnnotationNode === node) { <add> continue; <add> } <add> div.removeChild(node); <add> } <add> div.removeAttribute('data-loaded'); <add> <add> if (currentAnnotationNode) { <add> // Hide the annotation layer until all elements are resized <add> // so they are not displayed on the already resized page. <add> this.annotationLayer.hide(); <add> } else { <add> this.annotationLayer = null; <add> } <add> <add> if (!currentZoomLayerNode) { <add> if (this.canvas) { <add> this.paintedViewportMap.delete(this.canvas); <add> // Zeroing the width and height causes Firefox to release graphics <add> // resources immediately, which can greatly reduce memory consumption. <add> this.canvas.width = 0; <add> this.canvas.height = 0; <add> delete this.canvas; <ide> } <add> this._resetZoomLayer(); <add> } <add> if (this.svg) { <add> this.paintedViewportMap.delete(this.svg); <add> delete this.svg; <add> } <add> <add> this.loadingIconDiv = document.createElement('div'); <add> this.loadingIconDiv.className = 'loadingIcon'; <add> div.appendChild(this.loadingIconDiv); <add> } <ide> <del> var totalRotation = (this.rotation + this.pdfPageRotate) % 360; <del> this.viewport = this.viewport.clone({ <del> scale: this.scale * CSS_UNITS, <del> rotation: totalRotation <add> update(scale, rotation) { <add> this.scale = scale || this.scale; <add> if (typeof rotation !== 'undefined') { // The rotation may be zero. <add> this.rotation = rotation; <add> } <add> <add> let totalRotation = (this.rotation + this.pdfPageRotate) % 360; <add> this.viewport = this.viewport.clone({ <add> scale: this.scale * CSS_UNITS, <add> rotation: totalRotation, <add> }); <add> <add> if (this.svg) { <add> this.cssTransform(this.svg, true); <add> <add> this.eventBus.dispatch('pagerendered', { <add> source: this, <add> pageNumber: this.id, <add> cssTransform: true, <ide> }); <add> return; <add> } <add> <add> let isScalingRestricted = false; <add> if (this.canvas && PDFJS.maxCanvasPixels > 0) { <add> let outputScale = this.outputScale; <add> if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) * <add> ((Math.floor(this.viewport.height) * outputScale.sy) | 0) > <add> PDFJS.maxCanvasPixels) { <add> isScalingRestricted = true; <add> } <add> } <ide> <del> if (this.svg) { <del> this.cssTransform(this.svg, true); <add> if (this.canvas) { <add> if (PDFJS.useOnlyCssZoom || <add> (this.hasRestrictedScaling && isScalingRestricted)) { <add> this.cssTransform(this.canvas, true); <ide> <ide> this.eventBus.dispatch('pagerendered', { <ide> source: this, <ide> var PDFPageView = (function PDFPageViewClosure() { <ide> }); <ide> return; <ide> } <del> <del> var isScalingRestricted = false; <del> if (this.canvas && PDFJS.maxCanvasPixels > 0) { <del> var outputScale = this.outputScale; <del> if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) * <del> ((Math.floor(this.viewport.height) * outputScale.sy) | 0) > <del> PDFJS.maxCanvasPixels) { <del> isScalingRestricted = true; <del> } <add> if (!this.zoomLayer) { <add> this.zoomLayer = this.canvas.parentNode; <add> this.zoomLayer.style.position = 'absolute'; <ide> } <add> } <add> if (this.zoomLayer) { <add> this.cssTransform(this.zoomLayer.firstChild); <add> } <add> this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true); <add> } <ide> <del> if (this.canvas) { <del> if (PDFJS.useOnlyCssZoom || <del> (this.hasRestrictedScaling && isScalingRestricted)) { <del> this.cssTransform(this.canvas, true); <del> <del> this.eventBus.dispatch('pagerendered', { <del> source: this, <del> pageNumber: this.id, <del> cssTransform: true, <del> }); <del> return; <del> } <del> if (!this.zoomLayer) { <del> this.zoomLayer = this.canvas.parentNode; <del> this.zoomLayer.style.position = 'absolute'; <del> } <del> } <del> if (this.zoomLayer) { <del> this.cssTransform(this.zoomLayer.firstChild); <del> } <del> this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true); <del> }, <add> cancelRendering() { <add> if (this.paintTask) { <add> this.paintTask.cancel(); <add> this.paintTask = null; <add> } <add> this.renderingState = RenderingStates.INITIAL; <add> this.resume = null; <ide> <del> cancelRendering: function PDFPageView_cancelRendering() { <del> if (this.paintTask) { <del> this.paintTask.cancel(); <del> this.paintTask = null; <del> } <del> this.renderingState = RenderingStates.INITIAL; <del> this.resume = null; <add> if (this.textLayer) { <add> this.textLayer.cancel(); <add> this.textLayer = null; <add> } <add> } <ide> <del> if (this.textLayer) { <del> this.textLayer.cancel(); <del> this.textLayer = null; <del> } <del> }, <del> <del> /** <del> * Called when moved in the parent's container. <del> */ <del> updatePosition: function PDFPageView_updatePosition() { <del> if (this.textLayer) { <del> this.textLayer.render(TEXT_LAYER_RENDER_DELAY); <del> } <del> }, <del> <del> cssTransform: function PDFPageView_transform(target, redrawAnnotations) { <del> // Scale target (canvas or svg), its wrapper, and page container. <del> var width = this.viewport.width; <del> var height = this.viewport.height; <del> var div = this.div; <del> target.style.width = target.parentNode.style.width = div.style.width = <del> Math.floor(width) + 'px'; <del> target.style.height = target.parentNode.style.height = div.style.height = <del> Math.floor(height) + 'px'; <del> // The canvas may have been originally rotated, rotate relative to that. <del> var relativeRotation = this.viewport.rotation - <del> this.paintedViewportMap.get(target).rotation; <del> var absRotation = Math.abs(relativeRotation); <del> var scaleX = 1, scaleY = 1; <del> if (absRotation === 90 || absRotation === 270) { <del> // Scale x and y because of the rotation. <del> scaleX = height / width; <del> scaleY = width / height; <del> } <del> var cssTransform = 'rotate(' + relativeRotation + 'deg) ' + <del> 'scale(' + scaleX + ',' + scaleY + ')'; <del> CustomStyle.setProp('transform', target, cssTransform); <del> <del> if (this.textLayer) { <del> // Rotating the text layer is more complicated since the divs inside the <del> // the text layer are rotated. <del> // TODO: This could probably be simplified by drawing the text layer in <del> // one orientation then rotating overall. <del> var textLayerViewport = this.textLayer.viewport; <del> var textRelativeRotation = this.viewport.rotation - <del> textLayerViewport.rotation; <del> var textAbsRotation = Math.abs(textRelativeRotation); <del> var scale = width / textLayerViewport.width; <del> if (textAbsRotation === 90 || textAbsRotation === 270) { <del> scale = width / textLayerViewport.height; <del> } <del> var textLayerDiv = this.textLayer.textLayerDiv; <del> var transX, transY; <del> switch (textAbsRotation) { <del> case 0: <del> transX = transY = 0; <del> break; <del> case 90: <del> transX = 0; <del> transY = '-' + textLayerDiv.style.height; <del> break; <del> case 180: <del> transX = '-' + textLayerDiv.style.width; <del> transY = '-' + textLayerDiv.style.height; <del> break; <del> case 270: <del> transX = '-' + textLayerDiv.style.width; <del> transY = 0; <del> break; <del> default: <del> console.error('Bad rotation value.'); <del> break; <del> } <del> CustomStyle.setProp('transform', textLayerDiv, <del> 'rotate(' + textAbsRotation + 'deg) ' + <del> 'scale(' + scale + ', ' + scale + ') ' + <del> 'translate(' + transX + ', ' + transY + ')'); <del> CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%'); <del> } <add> /** <add> * Called when moved in the parent's container. <add> */ <add> updatePosition() { <add> if (this.textLayer) { <add> this.textLayer.render(TEXT_LAYER_RENDER_DELAY); <add> } <add> } <ide> <del> if (redrawAnnotations && this.annotationLayer) { <del> this.annotationLayer.render(this.viewport, 'display'); <add> cssTransform(target, redrawAnnotations = false) { <add> // Scale target (canvas or svg), its wrapper and page container. <add> let width = this.viewport.width; <add> let height = this.viewport.height; <add> let div = this.div; <add> target.style.width = target.parentNode.style.width = div.style.width = <add> Math.floor(width) + 'px'; <add> target.style.height = target.parentNode.style.height = div.style.height = <add> Math.floor(height) + 'px'; <add> // The canvas may have been originally rotated; rotate relative to that. <add> let relativeRotation = this.viewport.rotation - <add> this.paintedViewportMap.get(target).rotation; <add> let absRotation = Math.abs(relativeRotation); <add> let scaleX = 1, scaleY = 1; <add> if (absRotation === 90 || absRotation === 270) { <add> // Scale x and y because of the rotation. <add> scaleX = height / width; <add> scaleY = width / height; <add> } <add> let cssTransform = 'rotate(' + relativeRotation + 'deg) ' + <add> 'scale(' + scaleX + ',' + scaleY + ')'; <add> CustomStyle.setProp('transform', target, cssTransform); <add> <add> if (this.textLayer) { <add> // Rotating the text layer is more complicated since the divs inside the <add> // the text layer are rotated. <add> // TODO: This could probably be simplified by drawing the text layer in <add> // one orientation and then rotating overall. <add> let textLayerViewport = this.textLayer.viewport; <add> let textRelativeRotation = this.viewport.rotation - <add> textLayerViewport.rotation; <add> let textAbsRotation = Math.abs(textRelativeRotation); <add> let scale = width / textLayerViewport.width; <add> if (textAbsRotation === 90 || textAbsRotation === 270) { <add> scale = width / textLayerViewport.height; <ide> } <del> }, <del> <del> get width() { <del> return this.viewport.width; <del> }, <del> <del> get height() { <del> return this.viewport.height; <del> }, <del> <del> getPagePoint: function PDFPageView_getPagePoint(x, y) { <del> return this.viewport.convertToPdfPoint(x, y); <del> }, <del> <del> draw() { <del> if (this.renderingState !== RenderingStates.INITIAL) { <del> console.error('Must be in new state before drawing'); <del> this.reset(); // Ensure that we reset all state to prevent issues. <add> let textLayerDiv = this.textLayer.textLayerDiv; <add> let transX, transY; <add> switch (textAbsRotation) { <add> case 0: <add> transX = transY = 0; <add> break; <add> case 90: <add> transX = 0; <add> transY = '-' + textLayerDiv.style.height; <add> break; <add> case 180: <add> transX = '-' + textLayerDiv.style.width; <add> transY = '-' + textLayerDiv.style.height; <add> break; <add> case 270: <add> transX = '-' + textLayerDiv.style.width; <add> transY = 0; <add> break; <add> default: <add> console.error('Bad rotation value.'); <add> break; <ide> } <add> CustomStyle.setProp('transform', textLayerDiv, <add> 'rotate(' + textAbsRotation + 'deg) ' + <add> 'scale(' + scale + ', ' + scale + ') ' + <add> 'translate(' + transX + ', ' + transY + ')'); <add> CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%'); <add> } <add> <add> if (redrawAnnotations && this.annotationLayer) { <add> this.annotationLayer.render(this.viewport, 'display'); <add> } <add> } <ide> <del> this.renderingState = RenderingStates.RUNNING; <add> get width() { <add> return this.viewport.width; <add> } <add> <add> get height() { <add> return this.viewport.height; <add> } <ide> <del> let pdfPage = this.pdfPage; <del> let div = this.div; <del> // Wrap the canvas so if it has a css transform for highdpi the overflow <del> // will be hidden in FF. <del> let canvasWrapper = document.createElement('div'); <del> canvasWrapper.style.width = div.style.width; <del> canvasWrapper.style.height = div.style.height; <del> canvasWrapper.classList.add('canvasWrapper'); <add> getPagePoint(x, y) { <add> return this.viewport.convertToPdfPoint(x, y); <add> } <ide> <add> draw() { <add> if (this.renderingState !== RenderingStates.INITIAL) { <add> console.error('Must be in new state before drawing'); <add> this.reset(); // Ensure that we reset all state to prevent issues. <add> } <add> <add> this.renderingState = RenderingStates.RUNNING; <add> <add> let pdfPage = this.pdfPage; <add> let div = this.div; <add> // Wrap the canvas so that if it has a CSS transform for high DPI the <add> // overflow will be hidden in Firefox. <add> let canvasWrapper = document.createElement('div'); <add> canvasWrapper.style.width = div.style.width; <add> canvasWrapper.style.height = div.style.height; <add> canvasWrapper.classList.add('canvasWrapper'); <add> <add> if (this.annotationLayer && this.annotationLayer.div) { <add> // The annotation layer needs to stay on top. <add> div.insertBefore(canvasWrapper, this.annotationLayer.div); <add> } else { <add> div.appendChild(canvasWrapper); <add> } <add> <add> let textLayer = null; <add> if (this.textLayerFactory) { <add> let textLayerDiv = document.createElement('div'); <add> textLayerDiv.className = 'textLayer'; <add> textLayerDiv.style.width = canvasWrapper.style.width; <add> textLayerDiv.style.height = canvasWrapper.style.height; <ide> if (this.annotationLayer && this.annotationLayer.div) { <del> // annotationLayer needs to stay on top <del> div.insertBefore(canvasWrapper, this.annotationLayer.div); <add> // The annotation layer needs to stay on top. <add> div.insertBefore(textLayerDiv, this.annotationLayer.div); <ide> } else { <del> div.appendChild(canvasWrapper); <add> div.appendChild(textLayerDiv); <ide> } <ide> <del> let textLayer = null; <del> if (this.textLayerFactory) { <del> let textLayerDiv = document.createElement('div'); <del> textLayerDiv.className = 'textLayer'; <del> textLayerDiv.style.width = canvasWrapper.style.width; <del> textLayerDiv.style.height = canvasWrapper.style.height; <del> if (this.annotationLayer && this.annotationLayer.div) { <del> // annotationLayer needs to stay on top <del> div.insertBefore(textLayerDiv, this.annotationLayer.div); <del> } else { <del> div.appendChild(textLayerDiv); <add> textLayer = this.textLayerFactory. <add> createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, <add> this.enhanceTextSelection); <add> } <add> this.textLayer = textLayer; <add> <add> let renderContinueCallback = null; <add> if (this.renderingQueue) { <add> renderContinueCallback = (cont) => { <add> if (!this.renderingQueue.isHighestPriority(this)) { <add> this.renderingState = RenderingStates.PAUSED; <add> this.resume = () => { <add> this.renderingState = RenderingStates.RUNNING; <add> cont(); <add> }; <add> return; <ide> } <add> cont(); <add> }; <add> } <ide> <del> textLayer = this.textLayerFactory. <del> createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, <del> this.enhanceTextSelection); <del> } <del> this.textLayer = textLayer; <del> <del> let renderContinueCallback = null; <del> if (this.renderingQueue) { <del> renderContinueCallback = (cont) => { <del> if (!this.renderingQueue.isHighestPriority(this)) { <del> this.renderingState = RenderingStates.PAUSED; <del> this.resume = () => { <del> this.renderingState = RenderingStates.RUNNING; <del> cont(); <del> }; <del> return; <del> } <del> cont(); <del> }; <add> let finishPaintTask = (error) => { <add> // The paintTask may have been replaced by a new one, so only remove <add> // the reference to the paintTask if it matches the one that is <add> // triggering this callback. <add> if (paintTask === this.paintTask) { <add> this.paintTask = null; <ide> } <ide> <del> let finishPaintTask = (error) => { <del> // The paintTask may have been replaced by a new one, so only remove <del> // the reference to the paintTask if it matches the one that is <del> // triggering this callback. <del> if (paintTask === this.paintTask) { <del> this.paintTask = null; <del> } <del> <del> if (((typeof PDFJSDev === 'undefined' || <del> !PDFJSDev.test('PDFJS_NEXT')) && error === 'cancelled') || <del> error instanceof RenderingCancelledException) { <del> this.error = null; <del> return Promise.resolve(undefined); <del> } <del> <del> this.renderingState = RenderingStates.FINISHED; <del> <del> if (this.loadingIconDiv) { <del> div.removeChild(this.loadingIconDiv); <del> delete this.loadingIconDiv; <del> } <del> this._resetZoomLayer(/* removeFromDOM = */ true); <del> <del> this.error = error; <del> this.stats = pdfPage.stats; <del> if (this.onAfterDraw) { <del> this.onAfterDraw(); <del> } <del> this.eventBus.dispatch('pagerendered', { <del> source: this, <del> pageNumber: this.id, <del> cssTransform: false, <del> }); <del> <del> if (error) { <del> return Promise.reject(error); <del> } <add> if (((typeof PDFJSDev === 'undefined' || <add> !PDFJSDev.test('PDFJS_NEXT')) && error === 'cancelled') || <add> error instanceof RenderingCancelledException) { <add> this.error = null; <ide> return Promise.resolve(undefined); <del> }; <add> } <ide> <del> let paintTask = this.renderer === RendererType.SVG ? <del> this.paintOnSvg(canvasWrapper) : <del> this.paintOnCanvas(canvasWrapper); <del> paintTask.onRenderContinue = renderContinueCallback; <del> this.paintTask = paintTask; <del> <del> let resultPromise = paintTask.promise.then(function() { <del> return finishPaintTask(null).then(function () { <del> if (textLayer) { <del> pdfPage.getTextContent({ <del> normalizeWhitespace: true, <del> }).then(function textContentResolved(textContent) { <del> textLayer.setTextContent(textContent); <del> textLayer.render(TEXT_LAYER_RENDER_DELAY); <del> }); <del> } <del> }); <del> }, function(reason) { <del> return finishPaintTask(reason); <del> }); <add> this.renderingState = RenderingStates.FINISHED; <ide> <del> if (this.annotationLayerFactory) { <del> if (!this.annotationLayer) { <del> this.annotationLayer = this.annotationLayerFactory. <del> createAnnotationLayerBuilder(div, pdfPage, <del> this.renderInteractiveForms); <del> } <del> this.annotationLayer.render(this.viewport, 'display'); <add> if (this.loadingIconDiv) { <add> div.removeChild(this.loadingIconDiv); <add> delete this.loadingIconDiv; <ide> } <del> div.setAttribute('data-loaded', true); <add> this._resetZoomLayer(/* removeFromDOM = */ true); <ide> <del> if (this.onBeforeDraw) { <del> this.onBeforeDraw(); <add> this.error = error; <add> this.stats = pdfPage.stats; <add> if (this.onAfterDraw) { <add> this.onAfterDraw(); <ide> } <del> return resultPromise; <del> }, <del> <del> paintOnCanvas(canvasWrapper) { <del> var renderCapability = createPromiseCapability(); <del> <del> var result = { <del> promise: renderCapability.promise, <del> onRenderContinue(cont) { <del> cont(); <del> }, <del> cancel() { <del> renderTask.cancel(); <del> } <del> }; <add> this.eventBus.dispatch('pagerendered', { <add> source: this, <add> pageNumber: this.id, <add> cssTransform: false, <add> }); <ide> <del> var viewport = this.viewport; <del> var canvas = document.createElement('canvas'); <del> canvas.id = 'page' + this.id; <del> // Keep the canvas hidden until the first draw callback, or until drawing <del> // is complete when `!this.renderingQueue`, to prevent black flickering. <del> canvas.setAttribute('hidden', 'hidden'); <del> var isCanvasHidden = true; <del> var showCanvas = function () { <del> if (isCanvasHidden) { <del> canvas.removeAttribute('hidden'); <del> isCanvasHidden = false; <add> if (error) { <add> return Promise.reject(error); <add> } <add> return Promise.resolve(undefined); <add> }; <add> <add> let paintTask = this.renderer === RendererType.SVG ? <add> this.paintOnSvg(canvasWrapper) : <add> this.paintOnCanvas(canvasWrapper); <add> paintTask.onRenderContinue = renderContinueCallback; <add> this.paintTask = paintTask; <add> <add> let resultPromise = paintTask.promise.then(function() { <add> return finishPaintTask(null).then(function () { <add> if (textLayer) { <add> pdfPage.getTextContent({ <add> normalizeWhitespace: true, <add> }).then(function textContentResolved(textContent) { <add> textLayer.setTextContent(textContent); <add> textLayer.render(TEXT_LAYER_RENDER_DELAY); <add> }); <ide> } <del> }; <del> <del> canvasWrapper.appendChild(canvas); <del> this.canvas = canvas; <del> <del> if (typeof PDFJSDev === 'undefined' || <del> PDFJSDev.test('MOZCENTRAL || FIREFOX || GENERIC')) { <del> canvas.mozOpaque = true; <add> }); <add> }, function(reason) { <add> return finishPaintTask(reason); <add> }); <add> <add> if (this.annotationLayerFactory) { <add> if (!this.annotationLayer) { <add> this.annotationLayer = this.annotationLayerFactory. <add> createAnnotationLayerBuilder(div, pdfPage, <add> this.renderInteractiveForms); <ide> } <add> this.annotationLayer.render(this.viewport, 'display'); <add> } <add> div.setAttribute('data-loaded', true); <add> <add> if (this.onBeforeDraw) { <add> this.onBeforeDraw(); <add> } <add> return resultPromise; <add> } <ide> <del> var ctx = canvas.getContext('2d', {alpha: false}); <del> var outputScale = getOutputScale(ctx); <del> this.outputScale = outputScale; <del> <del> if (PDFJS.useOnlyCssZoom) { <del> var actualSizeViewport = viewport.clone({scale: CSS_UNITS}); <del> // Use a scale that will make the canvas be the original intended size <del> // of the page. <del> outputScale.sx *= actualSizeViewport.width / viewport.width; <del> outputScale.sy *= actualSizeViewport.height / viewport.height; <add> paintOnCanvas(canvasWrapper) { <add> let renderCapability = createPromiseCapability(); <add> let result = { <add> promise: renderCapability.promise, <add> onRenderContinue(cont) { <add> cont(); <add> }, <add> cancel() { <add> renderTask.cancel(); <add> }, <add> }; <add> <add> let viewport = this.viewport; <add> let canvas = document.createElement('canvas'); <add> canvas.id = this.renderingId; <add> <add> // Keep the canvas hidden until the first draw callback, or until drawing <add> // is complete when `!this.renderingQueue`, to prevent black flickering. <add> canvas.setAttribute('hidden', 'hidden'); <add> let isCanvasHidden = true; <add> let showCanvas = function () { <add> if (isCanvasHidden) { <add> canvas.removeAttribute('hidden'); <add> isCanvasHidden = false; <add> } <add> }; <add> <add> canvasWrapper.appendChild(canvas); <add> this.canvas = canvas; <add> <add> if (typeof PDFJSDev === 'undefined' || <add> PDFJSDev.test('MOZCENTRAL || FIREFOX || GENERIC')) { <add> canvas.mozOpaque = true; <add> } <add> <add> let ctx = canvas.getContext('2d', { alpha: false, }); <add> let outputScale = getOutputScale(ctx); <add> this.outputScale = outputScale; <add> <add> if (PDFJS.useOnlyCssZoom) { <add> let actualSizeViewport = viewport.clone({ scale: CSS_UNITS, }); <add> // Use a scale that makes the canvas have the originally intended size <add> // of the page. <add> outputScale.sx *= actualSizeViewport.width / viewport.width; <add> outputScale.sy *= actualSizeViewport.height / viewport.height; <add> outputScale.scaled = true; <add> } <add> <add> if (PDFJS.maxCanvasPixels > 0) { <add> let pixelsInViewport = viewport.width * viewport.height; <add> let maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport); <add> if (outputScale.sx > maxScale || outputScale.sy > maxScale) { <add> outputScale.sx = maxScale; <add> outputScale.sy = maxScale; <ide> outputScale.scaled = true; <add> this.hasRestrictedScaling = true; <add> } else { <add> this.hasRestrictedScaling = false; <ide> } <del> <del> if (PDFJS.maxCanvasPixels > 0) { <del> var pixelsInViewport = viewport.width * viewport.height; <del> var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport); <del> if (outputScale.sx > maxScale || outputScale.sy > maxScale) { <del> outputScale.sx = maxScale; <del> outputScale.sy = maxScale; <del> outputScale.scaled = true; <del> this.hasRestrictedScaling = true; <del> } else { <del> this.hasRestrictedScaling = false; <del> } <add> } <add> <add> let sfx = approximateFraction(outputScale.sx); <add> let sfy = approximateFraction(outputScale.sy); <add> canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]); <add> canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]); <add> canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px'; <add> canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px'; <add> // Add the viewport so it's known what it was originally drawn with. <add> this.paintedViewportMap.set(canvas, viewport); <add> <add> // Rendering area <add> let transform = !outputScale.scaled ? null : <add> [outputScale.sx, 0, 0, outputScale.sy, 0, 0]; <add> let renderContext = { <add> canvasContext: ctx, <add> transform, <add> viewport: this.viewport, <add> renderInteractiveForms: this.renderInteractiveForms, <add> }; <add> let renderTask = this.pdfPage.render(renderContext); <add> renderTask.onContinue = function (cont) { <add> showCanvas(); <add> if (result.onRenderContinue) { <add> result.onRenderContinue(cont); <add> } else { <add> cont(); <ide> } <add> }; <add> <add> renderTask.promise.then(function() { <add> showCanvas(); <add> renderCapability.resolve(undefined); <add> }, function(error) { <add> showCanvas(); <add> renderCapability.reject(error); <add> }); <add> return result; <add> } <ide> <del> var sfx = approximateFraction(outputScale.sx); <del> var sfy = approximateFraction(outputScale.sy); <del> canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]); <del> canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]); <del> canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px'; <del> canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px'; <del> // Add the viewport so it's known what it was originally drawn with. <del> this.paintedViewportMap.set(canvas, viewport); <del> <del> // Rendering area <del> var transform = !outputScale.scaled ? null : <del> [outputScale.sx, 0, 0, outputScale.sy, 0, 0]; <del> var renderContext = { <del> canvasContext: ctx, <del> transform, <del> viewport: this.viewport, <del> renderInteractiveForms: this.renderInteractiveForms, <del> // intent: 'default', // === 'display' <add> paintOnSvg(wrapper) { <add> if (typeof PDFJSDev !== 'undefined' && <add> PDFJSDev.test('FIREFOX || MOZCENTRAL || CHROME')) { <add> // Return a mock object, to prevent errors such as e.g. <add> // "TypeError: paintTask.promise is undefined". <add> return { <add> promise: Promise.reject(new Error('SVG rendering is not supported.')), <add> onRenderContinue(cont) { }, <add> cancel() { }, <ide> }; <del> var renderTask = this.pdfPage.render(renderContext); <del> renderTask.onContinue = function (cont) { <del> showCanvas(); <del> if (result.onRenderContinue) { <del> result.onRenderContinue(cont); <add> } <add> <add> let cancelled = false; <add> let ensureNotCancelled = () => { <add> if (cancelled) { <add> if ((typeof PDFJSDev !== 'undefined' && <add> PDFJSDev.test('PDFJS_NEXT')) || PDFJS.pdfjsNext) { <add> throw new RenderingCancelledException( <add> 'Rendering cancelled, page ' + this.id, 'svg'); <ide> } else { <del> cont(); <add> throw 'cancelled'; // eslint-disable-line no-throw-literal <ide> } <del> }; <del> <del> renderTask.promise.then(function() { <del> showCanvas(); <del> renderCapability.resolve(undefined); <del> }, function(error) { <del> showCanvas(); <del> renderCapability.reject(error); <del> }); <del> return result; <del> }, <del> <del> paintOnSvg(wrapper) { <del> if (typeof PDFJSDev !== 'undefined' && <del> PDFJSDev.test('FIREFOX || MOZCENTRAL || CHROME')) { <del> // Return a mock object, to prevent errors such as e.g. <del> // "TypeError: paintTask.promise is undefined". <del> return { <del> promise: Promise.reject(new Error('SVG rendering is not supported.')), <del> onRenderContinue(cont) { }, <del> cancel() { }, <del> }; <ide> } <del> <del> let cancelled = false; <del> let ensureNotCancelled = () => { <del> if (cancelled) { <del> if ((typeof PDFJSDev !== 'undefined' && <del> PDFJSDev.test('PDFJS_NEXT')) || PDFJS.pdfjsNext) { <del> throw new RenderingCancelledException( <del> 'Rendering cancelled, page ' + this.id, 'svg'); <del> } else { <del> throw 'cancelled'; // eslint-disable-line no-throw-literal <del> } <del> } <del> }; <del> <del> let pdfPage = this.pdfPage; <del> let actualSizeViewport = this.viewport.clone({ scale: CSS_UNITS, }); <del> let promise = pdfPage.getOperatorList().then((opList) => { <add> }; <add> <add> let pdfPage = this.pdfPage; <add> let actualSizeViewport = this.viewport.clone({ scale: CSS_UNITS, }); <add> let promise = pdfPage.getOperatorList().then((opList) => { <add> ensureNotCancelled(); <add> let svgGfx = new SVGGraphics(pdfPage.commonObjs, pdfPage.objs); <add> return svgGfx.getSVG(opList, actualSizeViewport).then((svg) => { <ide> ensureNotCancelled(); <del> var svgGfx = new SVGGraphics(pdfPage.commonObjs, pdfPage.objs); <del> return svgGfx.getSVG(opList, actualSizeViewport).then((svg) => { <del> ensureNotCancelled(); <del> this.svg = svg; <del> this.paintedViewportMap.set(svg, actualSizeViewport); <del> <del> svg.style.width = wrapper.style.width; <del> svg.style.height = wrapper.style.height; <del> this.renderingState = RenderingStates.FINISHED; <del> wrapper.appendChild(svg); <del> }); <del> }); <del> <del> return { <del> promise, <del> onRenderContinue(cont) { <del> cont(); <del> }, <del> cancel() { <del> cancelled = true; <del> } <del> }; <del> }, <del> <del> /** <del> * @param {string|null} label <del> */ <del> setPageLabel: function PDFView_setPageLabel(label) { <del> this.pageLabel = (typeof label === 'string' ? label : null); <add> this.svg = svg; <add> this.paintedViewportMap.set(svg, actualSizeViewport); <ide> <del> if (this.pageLabel !== null) { <del> this.div.setAttribute('data-page-label', this.pageLabel); <del> } else { <del> this.div.removeAttribute('data-page-label'); <del> } <del> }, <del> }; <add> svg.style.width = wrapper.style.width; <add> svg.style.height = wrapper.style.height; <add> this.renderingState = RenderingStates.FINISHED; <add> wrapper.appendChild(svg); <add> }); <add> }); <add> <add> return { <add> promise, <add> onRenderContinue(cont) { <add> cont(); <add> }, <add> cancel() { <add> cancelled = true; <add> }, <add> }; <add> } <ide> <del> return PDFPageView; <del>})(); <add> /** <add> * @param {string|null} label <add> */ <add> setPageLabel(label) { <add> this.pageLabel = (typeof label === 'string' ? label : null); <add> <add> if (this.pageLabel !== null) { <add> this.div.setAttribute('data-page-label', this.pageLabel); <add> } else { <add> this.div.removeAttribute('data-page-label'); <add> } <add> } <add>} <ide> <ide> export { <ide> PDFPageView,
1
Text
Text
add changelog entry for
2a41b6ea98cdf227b93cc483e9a3f3640db54a05
<ide><path>actionview/CHANGELOG.md <add>* Add `config.action_view.image_loading` to configure the default value of <add> the `image_tag` `:loading` option. <add> <add> By setting `config.action_view.image_loading = "lazy"`, an application can opt in to <add> lazy loading images sitewide, without changing view code. <add> <add> *Jonathan Hefner* <add> <ide> * `ActionView::Helpers::FormBuilder#id` returns the value <ide> of the `<form>` element's `id` attribute. With a `method` argument, returns <ide> the `id` attribute for a form field with that name.
1
Javascript
Javascript
add sendflash to send a flash message json
b8f8ea80cf10f9df66a37fb5cd6f7f25bd2a1137
<ide><path>server/middlewares/express-extensions.js <ide> export default function() { <ide> res.renderWithoutFlash = res.render; <ide> // render to observable stream using build in render <ide> res.render$ = Observable.fromNodeCallback(res.render, res); <add> res.sendFlash = (type, message) => { <add> if (type && message) { <add> req.flash(type, message); <add> } <add> return res.json(req.flash()); <add> }; <ide> next(); <ide> }; <ide> }
1
PHP
PHP
remove superfluous whitespace in doc blocks
05305555a38008b238c544a2c9a57d007806f2e0
<ide><path>src/Auth/AbstractPasswordHasher.php <ide> <ide> /** <ide> * Abstract password hashing class <del> * <ide> */ <ide> abstract class AbstractPasswordHasher <ide> { <ide><path>src/Auth/BaseAuthenticate.php <ide> <ide> /** <ide> * Base Authentication class with common methods and properties. <del> * <ide> */ <ide> abstract class BaseAuthenticate implements EventListenerInterface <ide> { <ide><path>src/Auth/DefaultPasswordHasher.php <ide> <ide> /** <ide> * Default password hashing class. <del> * <ide> */ <ide> class DefaultPasswordHasher extends AbstractPasswordHasher <ide> { <ide><path>src/Auth/FallbackPasswordHasher.php <ide> * A password hasher that can use multiple different hashes where only <ide> * one is the preferred one. This is useful when trying to migrate an <ide> * existing database of users from one password type to another. <del> * <ide> */ <ide> class FallbackPasswordHasher extends AbstractPasswordHasher <ide> { <ide><path>src/Auth/PasswordHasherFactory.php <ide> <ide> /** <ide> * Builds password hashing objects <del> * <ide> */ <ide> class PasswordHasherFactory <ide> { <ide><path>src/Auth/WeakPasswordHasher.php <ide> * Password hashing class that use weak hashing algorithms. This class is <ide> * intended only to be used with legacy databases where passwords have <ide> * not been migrated to a stronger algorithm yet. <del> * <ide> */ <ide> class WeakPasswordHasher extends AbstractPasswordHasher <ide> { <ide><path>src/Cache/CacheEngine.php <ide> <ide> /** <ide> * Storage engine for CakePHP caching <del> * <ide> */ <ide> abstract class CacheEngine <ide> { <ide><path>src/Cache/Engine/ApcEngine.php <ide> <ide> /** <ide> * APC storage engine for cache <del> * <ide> */ <ide> class ApcEngine extends CacheEngine <ide> { <ide><path>src/Cache/Engine/FileEngine.php <ide> * engine available, or have content which is not performance sensitive. <ide> * <ide> * You can configure a FileEngine cache, using Cache::config() <del> * <ide> */ <ide> class FileEngine extends CacheEngine <ide> { <ide><path>src/Cache/Engine/MemcachedEngine.php <ide> * support of binary protocol, and igbinary serialization <ide> * (if memcached extension compiled with --enable-igbinary) <ide> * Compressed keys can also be incremented/decremented <del> * <ide> */ <ide> class MemcachedEngine extends CacheEngine <ide> { <ide><path>src/Cache/Engine/RedisEngine.php <ide> <ide> /** <ide> * Redis storage engine for cache. <del> * <ide> */ <ide> class RedisEngine extends CacheEngine <ide> { <ide><path>src/Collection/CollectionInterface.php <ide> * Describes the methods a Collection should implement. A collection is an immutable <ide> * list of elements exposing a number of traversing and extracting method for <ide> * generating other collections. <del> * <ide> */ <ide> interface CollectionInterface extends Iterator, JsonSerializable <ide> { <ide><path>src/Collection/Iterator/NestIterator.php <ide> /** <ide> * A type of collection that is aware of nested items and exposes methods to <ide> * check or retrieve them <del> * <ide> */ <ide> class NestIterator extends Collection implements RecursiveIterator <ide> { <ide><path>src/Collection/Iterator/TreeIterator.php <ide> /** <ide> * A Recursive iterator used to flatten nested structures and also exposes <ide> * all Collection methods <del> * <ide> */ <ide> class TreeIterator extends RecursiveIteratorIterator <ide> { <ide><path>src/Collection/Iterator/TreePrinter.php <ide> /** <ide> * Iterator for flattening elements in a tree structure while adding some <ide> * visual markers for their relative position in the tree <del> * <ide> */ <ide> class TreePrinter extends RecursiveIteratorIterator <ide> { <ide><path>src/Collection/Iterator/ZipIterator.php <ide> * }); <ide> * $iterator->toList(); // Returns [4, 6] <ide> * ``` <del> * <ide> */ <ide> class ZipIterator extends MultipleIterator implements CollectionInterface, Serializable <ide> { <ide><path>src/Console/ConsoleInput.php <ide> <ide> /** <ide> * Object wrapper for interacting with stdin <del> * <ide> */ <ide> class ConsoleInput <ide> { <ide><path>src/Console/ConsoleOptionParser.php <ide> * <ide> * By providing help text for your positional arguments and named arguments, the ConsoleOptionParser <ide> * can generate a help display for you. You can view the help for shells by using the `--help` or `-h` switch. <del> * <ide> */ <ide> class ConsoleOptionParser <ide> { <ide><path>src/Console/ConsoleOutput.php <ide> * This would create orange 'Overwrite:' text, while the rest of the text would remain the normal color. <ide> * See ConsoleOutput::styles() to learn more about defining your own styles. Nested styles are not supported <ide> * at this time. <del> * <ide> */ <ide> class ConsoleOutput <ide> { <ide><path>src/Console/Exception/ConsoleException.php <ide> /** <ide> * Exception class for Console libraries. This exception will be thrown from Console library <ide> * classes when they encounter an error. <del> * <ide> */ <ide> class ConsoleException extends Exception <ide> { <ide><path>src/Console/Exception/MissingHelperException.php <ide> <ide> /** <ide> * Used when a Helper cannot be found. <del> * <ide> */ <ide> class MissingHelperException extends Exception <ide> { <ide><path>src/Console/Exception/MissingShellException.php <ide> <ide> /** <ide> * Used when a shell cannot be found. <del> * <ide> */ <ide> class MissingShellException extends Exception <ide> { <ide><path>src/Console/Exception/MissingShellMethodException.php <ide> <ide> /** <ide> * Used when a shell method cannot be found. <del> * <ide> */ <ide> class MissingShellMethodException extends Exception <ide> { <ide><path>src/Console/Exception/MissingTaskException.php <ide> <ide> /** <ide> * Used when a Task cannot be found. <del> * <ide> */ <ide> class MissingTaskException extends Exception <ide> { <ide><path>src/Controller/Exception/MissingComponentException.php <ide> <ide> /** <ide> * Used when a component cannot be found. <del> * <ide> */ <ide> class MissingComponentException extends Exception <ide> { <ide><path>src/Core/ClassLoader.php <ide> <ide> /** <ide> * ClassLoader <del> * <ide> */ <ide> class ClassLoader <ide> { <ide><path>src/Core/Configure/Engine/PhpConfig.php <ide> * <ide> * Files compatible with PhpConfig should return an array that <ide> * contains all of the configuration data contained in the file. <del> * <ide> */ <ide> class PhpConfig implements ConfigEngineInterface <ide> { <ide><path>src/Core/Exception/Exception.php <ide> <ide> /** <ide> * Base class that all CakePHP Exceptions extend. <del> * <ide> */ <ide> class Exception extends RuntimeException <ide> { <ide><path>src/Core/Exception/MissingPluginException.php <ide> <ide> /** <ide> * Exception raised when a plugin could not be found <del> * <ide> */ <ide> class MissingPluginException extends Exception <ide> { <ide><path>src/Database/Driver.php <ide> /** <ide> * Represents a database diver containing all specificities for <ide> * a database engine including its SQL dialect <del> * <ide> */ <ide> abstract class Driver <ide> { <ide><path>src/Database/Schema/CachedCollection.php <ide> <ide> /** <ide> * Extends the schema collection class to provide caching <del> * <ide> */ <ide> class CachedCollection extends Collection <ide> { <ide><path>src/Datasource/Exception/InvalidPrimaryKeyException.php <ide> <ide> /** <ide> * Exception raised when the provided primary key does not match the table primary key <del> * <ide> */ <ide> class InvalidPrimaryKeyException extends RuntimeException <ide> { <ide><path>src/Datasource/Exception/MissingDatasourceException.php <ide> <ide> /** <ide> * Used when a datasource cannot be found. <del> * <ide> */ <ide> class MissingDatasourceException extends Exception <ide> { <ide><path>src/Datasource/Exception/MissingModelException.php <ide> <ide> /** <ide> * Used when a model cannot be found. <del> * <ide> */ <ide> class MissingModelException extends Exception <ide> { <ide><path>src/Datasource/Exception/RecordNotFoundException.php <ide> <ide> /** <ide> * Exception raised when a particular record was not found <del> * <ide> */ <ide> class RecordNotFoundException extends RuntimeException <ide> { <ide><path>src/Datasource/QueryTrait.php <ide> /** <ide> * Contains the characteristics for an object that is attached to a repository and <ide> * can retrieve results based on any criteria. <del> * <ide> */ <ide> trait QueryTrait <ide> { <ide><path>src/Datasource/ResultSetInterface.php <ide> <ide> /** <ide> * Describes how a collection of datasource results should look like <del> * <ide> */ <ide> interface ResultSetInterface extends CollectionInterface, Countable, Serializable <ide> { <ide><path>src/Error/FatalErrorException.php <ide> <ide> /** <ide> * Represents a fatal error <del> * <ide> */ <ide> class FatalErrorException extends Exception <ide> { <ide><path>src/Error/PHP7ErrorException.php <ide> * Wraps a PHP 7 Error object inside a normal Exception <ide> * so it can be handled correctly by the rest of the <ide> * error handling system <del> * <ide> */ <ide> class PHP7ErrorException extends Exception <ide> { <ide><path>src/Event/Event.php <ide> * Represents the transport class of events across the system. It receives a name, subject and an optional <ide> * payload. The name can be any string that uniquely identifies the event across the application, while the subject <ide> * represents the object that the event applies to. <del> * <ide> */ <ide> class Event <ide> { <ide><path>src/Event/EventDispatcherTrait.php <ide> <ide> /** <ide> * Implements Cake\Event\EventDispatcherInterface. <del> * <ide> */ <ide> trait EventDispatcherTrait <ide> { <ide><path>src/Event/EventListenerInterface.php <ide> /** <ide> * Objects implementing this interface should declare the `implementedEvents` function <ide> * to notify the event manager what methods should be called when an event is triggered. <del> * <ide> */ <ide> interface EventListenerInterface <ide> { <ide><path>src/Filesystem/File.php <ide> <ide> /** <ide> * Convenience class for reading, writing and appending to files. <del> * <ide> */ <ide> class File <ide> { <ide><path>src/I18n/ChainMessagesLoader.php <ide> /** <ide> * Wraps multiple message loaders calling them one after another until <ide> * one of them returns a non-empty package. <del> * <ide> */ <ide> class ChainMessagesLoader <ide> { <ide><path>src/I18n/Time.php <ide> /** <ide> * Extends the built-in DateTime class to provide handy methods and locale-aware <ide> * formatting helpers <del> * <ide> */ <ide> class Time extends MutableDateTime implements JsonSerializable <ide> { <ide><path>src/Log/Engine/BaseLog.php <ide> <ide> /** <ide> * Base log engine class. <del> * <ide> */ <ide> abstract class BaseLog extends AbstractLogger <ide> { <ide><path>src/Log/Engine/FileLog.php <ide> /** <ide> * File Storage stream for Logging. Writes logs to different files <ide> * based on the level of log it is. <del> * <ide> */ <ide> class FileLog extends BaseLog <ide> { <ide><path>src/Mailer/AbstractTransport.php <ide> <ide> /** <ide> * Abstract transport for sending email <del> * <ide> */ <ide> abstract class AbstractTransport <ide> { <ide><path>src/Mailer/Exception/MissingMailerException.php <ide> <ide> /** <ide> * Used when a mailer cannot be found. <del> * <ide> */ <ide> class MissingMailerException extends Exception <ide> { <ide><path>src/Mailer/Transport/DebugTransport.php <ide> /** <ide> * Debug Transport class, useful for emulate the email sending process and inspect the resulted <ide> * email message before actually send it during development <del> * <ide> */ <ide> class DebugTransport extends AbstractTransport <ide> { <ide><path>src/Mailer/Transport/MailTransport.php <ide> <ide> /** <ide> * Send mail using mail() function <del> * <ide> */ <ide> class MailTransport extends AbstractTransport <ide> { <ide><path>src/Network/Exception/BadRequestException.php <ide> <ide> /** <ide> * Represents an HTTP 400 error. <del> * <ide> */ <ide> class BadRequestException extends HttpException <ide> { <ide><path>src/Network/Exception/ConflictException.php <ide> <ide> /** <ide> * Represents an HTTP 409 error. <del> * <ide> */ <ide> class ConflictException extends HttpException <ide> { <ide><path>src/Network/Exception/ForbiddenException.php <ide> <ide> /** <ide> * Represents an HTTP 403 error. <del> * <ide> */ <ide> class ForbiddenException extends HttpException <ide> { <ide><path>src/Network/Exception/GoneException.php <ide> <ide> /** <ide> * Represents an HTTP 410 error. <del> * <ide> */ <ide> class GoneException extends HttpException <ide> { <ide><path>src/Network/Exception/HttpException.php <ide> * <ide> * You may also use this as a meaningful bridge to Cake\Core\Exception\Exception, e.g.: <ide> * throw new \Cake\Network\Exception\HttpException('HTTP Version Not Supported', 505); <del> * <ide> */ <ide> class HttpException extends Exception <ide> { <ide><path>src/Network/Exception/InternalErrorException.php <ide> <ide> /** <ide> * Represents an HTTP 500 error. <del> * <ide> */ <ide> class InternalErrorException extends HttpException <ide> { <ide><path>src/Network/Exception/InvalidCsrfTokenException.php <ide> <ide> /** <ide> * Represents an HTTP 403 error caused by an invalid CSRF token <del> * <ide> */ <ide> class InvalidCsrfTokenException extends HttpException <ide> { <ide><path>src/Network/Exception/MethodNotAllowedException.php <ide> <ide> /** <ide> * Represents an HTTP 405 error. <del> * <ide> */ <ide> class MethodNotAllowedException extends HttpException <ide> { <ide><path>src/Network/Exception/NotAcceptableException.php <ide> <ide> /** <ide> * Represents an HTTP 406 error. <del> * <ide> */ <ide> class NotAcceptableException extends HttpException <ide> { <ide><path>src/Network/Exception/NotFoundException.php <ide> <ide> /** <ide> * Represents an HTTP 404 error. <del> * <ide> */ <ide> class NotFoundException extends HttpException <ide> { <ide><path>src/Network/Exception/NotImplementedException.php <ide> <ide> /** <ide> * Not Implemented Exception - used when an API method is not implemented <del> * <ide> */ <ide> class NotImplementedException extends HttpException <ide> { <ide><path>src/Network/Exception/ServiceUnavailableException.php <ide> <ide> /** <ide> * Represents an HTTP 503 error. <del> * <ide> */ <ide> class ServiceUnavailableException extends HttpException <ide> { <ide><path>src/Network/Exception/SocketException.php <ide> /** <ide> * Exception class for Socket. This exception will be thrown from Socket, Email, HttpSocket <ide> * SmtpTransport, MailTransport and HttpResponse when it encounters an error. <del> * <ide> */ <ide> class SocketException extends RuntimeException <ide> { <ide><path>src/Network/Exception/UnauthorizedException.php <ide> <ide> /** <ide> * Represents an HTTP 401 error. <del> * <ide> */ <ide> class UnauthorizedException extends HttpException <ide> { <ide><path>src/Network/Exception/UnavailableForLegalReasonsException.php <ide> <ide> /** <ide> * Represents an HTTP 451 error. <del> * <ide> */ <ide> class UnavailableForLegalReasonsException extends HttpException <ide> { <ide><path>src/Network/Http/Client.php <ide> * a proxy if you need to use one.. The type sub option can be used to <ide> * specify which authentication strategy you want to use. <ide> * CakePHP comes with built-in support for basic authentication. <del> * <ide> */ <ide> class Client <ide> { <ide><path>src/Network/Http/FormData.php <ide> * <ide> * Used by Http\Client to upload POST/PUT data <ide> * and files. <del> * <ide> */ <ide> class FormData implements Countable <ide> { <ide><path>src/Network/Response.php <ide> * <ide> * By default controllers will use this class to render their response. If you are going to use <ide> * a custom response class it should subclass this object in order to ensure compatibility. <del> * <ide> */ <ide> class Response <ide> { <ide><path>src/Network/Session/DatabaseSession.php <ide> <ide> /** <ide> * DatabaseSession provides methods to be used with Session. <del> * <ide> */ <ide> class DatabaseSession implements SessionHandlerInterface <ide> { <ide><path>src/Network/Socket.php <ide> * CakePHP network socket connection class. <ide> * <ide> * Core base class for network communication. <del> * <ide> */ <ide> class Socket <ide> { <ide><path>src/ORM/Behavior/CounterCacheBehavior.php <ide> * ] <ide> * ] <ide> * ``` <del> * <ide> */ <ide> class CounterCacheBehavior extends Behavior <ide> { <ide><path>src/ORM/Exception/MissingBehaviorException.php <ide> <ide> /** <ide> * Used when a behavior cannot be found. <del> * <ide> */ <ide> class MissingBehaviorException extends Exception <ide> { <ide><path>src/ORM/Exception/MissingEntityException.php <ide> <ide> /** <ide> * Exception raised when an Entity could not be found. <del> * <ide> */ <ide> class MissingEntityException extends Exception <ide> { <ide><path>src/ORM/Exception/MissingTableClassException.php <ide> <ide> /** <ide> * Exception raised when a Table could not be found. <del> * <ide> */ <ide> class MissingTableClassException extends Exception <ide> { <ide><path>src/ORM/Exception/RolledbackTransactionException.php <ide> <ide> /** <ide> * Used when a transaction was rolled back from a callback event. <del> * <ide> */ <ide> class RolledbackTransactionException extends Exception <ide> { <ide><path>src/ORM/ResultSet.php <ide> * This object is responsible for correctly nesting result keys reported from <ide> * the query, casting each field to the correct type and executing the extra <ide> * queries required for eager loading external associations. <del> * <ide> */ <ide> class ResultSet implements ResultSetInterface <ide> { <ide><path>src/ORM/TableRegistry.php <ide> * ``` <ide> * $table = TableRegistry::get('Users', $config); <ide> * ``` <del> * <ide> */ <ide> class TableRegistry <ide> { <ide><path>src/Routing/Dispatcher.php <ide> * Dispatcher converts Requests into controller actions. It uses the dispatched Request <ide> * to locate and load the correct controller. If found, the requested action is called on <ide> * the controller <del> * <ide> */ <ide> class Dispatcher <ide> { <ide><path>src/Routing/DispatcherFilter.php <ide> * <ide> * When using the `for` or `when` matchers, conditions will be re-checked on the before and after <ide> * callback as the conditions could change during the dispatch cycle. <del> * <ide> */ <ide> class DispatcherFilter implements EventListenerInterface <ide> { <ide><path>src/Routing/Exception/MissingControllerException.php <ide> /** <ide> * Missing Controller exception - used when a controller <ide> * cannot be found. <del> * <ide> */ <ide> class MissingControllerException extends Exception <ide> { <ide><path>src/Routing/Exception/MissingDispatcherFilterException.php <ide> <ide> /** <ide> * Exception raised when a Dispatcher filter could not be found <del> * <ide> */ <ide> class MissingDispatcherFilterException extends Exception <ide> { <ide><path>src/Routing/Filter/AssetFilter.php <ide> /** <ide> * Filters a request and tests whether it is a file in the webroot folder or not and <ide> * serves the file to the client if appropriate. <del> * <ide> */ <ide> class AssetFilter extends DispatcherFilter <ide> { <ide><path>src/Routing/RequestActionTrait.php <ide> <ide> /** <ide> * Provides the requestAction() method for doing sub-requests <del> * <ide> */ <ide> trait RequestActionTrait <ide> { <ide><path>src/Routing/Route/PluginShortRoute.php <ide> /** <ide> * Plugin short route, that copies the plugin param to the controller parameters <ide> * It is used for supporting /:plugin routes. <del> * <ide> */ <ide> class PluginShortRoute extends InflectedRoute <ide> { <ide><path>src/Routing/Route/Route.php <ide> * <ide> * Not normally created as a standalone. Use Router::connect() to create <ide> * Routes for your application. <del> * <ide> */ <ide> class Route <ide> { <ide><path>src/Shell/CommandListShell.php <ide> <ide> /** <ide> * Shows a list of commands available from the console. <del> * <ide> */ <ide> class CommandListShell extends Shell <ide> { <ide><path>src/Shell/I18nShell.php <ide> <ide> /** <ide> * Shell for I18N management. <del> * <ide> */ <ide> class I18nShell extends Shell <ide> { <ide><path>src/Shell/PluginShell.php <ide> <ide> /** <ide> * Shell for tasks related to plugins. <del> * <ide> */ <ide> class PluginShell extends Shell <ide> { <ide><path>src/Shell/RoutesShell.php <ide> <ide> /** <ide> * Provides interactive CLI tools for routing. <del> * <ide> */ <ide> class RoutesShell extends Shell <ide> { <ide><path>src/Shell/ServerShell.php <ide> <ide> /** <ide> * built-in Server Shell <del> * <ide> */ <ide> class ServerShell extends Shell <ide> { <ide><path>src/Shell/Task/AssetsTask.php <ide> <ide> /** <ide> * Task for symlinking / copying plugin assets to app's webroot. <del> * <ide> */ <ide> class AssetsTask extends Shell <ide> { <ide><path>src/Shell/Task/CommandTask.php <ide> <ide> /** <ide> * Base class for Shell Command reflection. <del> * <ide> */ <ide> class CommandTask extends Shell <ide> { <ide><path>src/Shell/Task/ExtractTask.php <ide> <ide> /** <ide> * Language string extractor <del> * <ide> */ <ide> class ExtractTask extends Shell <ide> { <ide><path>src/Shell/Task/LoadTask.php <ide> <ide> /** <ide> * Task for loading plugins. <del> * <ide> */ <ide> class LoadTask extends Shell <ide> { <ide><path>src/Shell/Task/UnloadTask.php <ide> <ide> /** <ide> * Task for unloading plugins. <del> * <ide> */ <ide> class UnloadTask extends Shell <ide> { <ide><path>src/TestSuite/Fixture/FixtureManager.php <ide> <ide> /** <ide> * A factory class to manage the life cycle of test fixtures <del> * <ide> */ <ide> class FixtureManager <ide> { <ide><path>src/TestSuite/TestCase.php <ide> <ide> /** <ide> * Cake TestCase class <del> * <ide> */ <ide> abstract class TestCase extends PHPUnit_Framework_TestCase <ide> { <ide><path>src/TestSuite/TestSuite.php <ide> <ide> /** <ide> * A class to contain test cases and run them with shared fixtures <del> * <ide> */ <ide> class TestSuite extends PHPUnit_Framework_TestSuite <ide> { <ide><path>src/Utility/Exception/XmlException.php <ide> /** <ide> * Exception class for Xml. This exception will be thrown from Xml when it <ide> * encounters an error. <del> * <ide> */ <ide> class XmlException extends RuntimeException <ide> { <ide><path>src/Utility/MergeVariablesTrait.php <ide> /** <ide> * Provides features for merging object properties recursively with <ide> * parent classes. <del> * <ide> */ <ide> trait MergeVariablesTrait <ide> { <ide><path>src/Utility/Security.php <ide> <ide> /** <ide> * Security Library contains utility methods related to security <del> * <ide> */ <ide> class Security <ide> { <ide><path>src/Utility/Text.php <ide> <ide> /** <ide> * Text handling methods. <del> * <ide> */ <ide> class Text <ide> { <ide><path>src/Utility/Xml.php <ide> * XML handling for CakePHP. <ide> * <ide> * The methods in these classes enable the datasources that use XML to work. <del> * <ide> */ <ide> class Xml <ide> { <ide><path>src/Validation/Validation.php <ide> * Validation Class. Used for validation of model data <ide> * <ide> * Offers different validation methods. <del> * <ide> */ <ide> class Validation <ide> { <ide><path>src/View/Cell.php <ide> <ide> /** <ide> * Cell base. <del> * <ide> */ <ide> abstract class Cell <ide> { <ide><path>src/View/CellTrait.php <ide> <ide> /** <ide> * Provides cell() method for usage in Controller and View classes. <del> * <ide> */ <ide> trait CellTrait <ide> { <ide><path>src/View/Exception/MissingCellException.php <ide> <ide> /** <ide> * Used when a cell class file cannot be found. <del> * <ide> */ <ide> class MissingCellException extends Exception <ide> { <ide><path>src/View/Exception/MissingHelperException.php <ide> <ide> /** <ide> * Used when a helper cannot be found. <del> * <ide> */ <ide> class MissingHelperException extends Exception <ide> { <ide><path>src/View/Exception/MissingLayoutException.php <ide> <ide> /** <ide> * Used when a layout file cannot be found. <del> * <ide> */ <ide> class MissingLayoutException extends Exception <ide> { <ide><path>src/View/Exception/MissingTemplateException.php <ide> <ide> /** <ide> * Used when a template file cannot be found. <del> * <ide> */ <ide> class MissingTemplateException extends Exception <ide> { <ide><path>src/View/Exception/MissingViewException.php <ide> <ide> /** <ide> * Used when a view class file cannot be found. <del> * <ide> */ <ide> class MissingViewException extends Exception <ide> { <ide><path>src/View/Helper.php <ide> * - `beforeRenderFile(Event $event, $viewFile)` - Called before any view fragment is rendered. <ide> * - `afterRenderFile(Event $event, $viewFile, $content)` - Called after any view fragment is rendered. <ide> * If a listener returns a non-null value, the output of the rendered file will be set to that. <del> * <ide> */ <ide> class Helper implements EventListenerInterface <ide> { <ide><path>src/View/ViewBlock.php <ide> * Slots or blocks are combined with extending views and layouts to afford slots <ide> * of content that are present in a layout or parent view, but are defined by the child <ide> * view or elements used in the view. <del> * <ide> */ <ide> class ViewBlock <ide> { <ide><path>src/View/ViewVarsTrait.php <ide> * <ide> * Once collected context data can be passed to another object. <ide> * This is done in Controller, TemplateTask and View for example. <del> * <ide> */ <ide> trait ViewVarsTrait <ide> { <ide><path>src/View/Widget/MultiCheckboxWidget.php <ide> <ide> /** <ide> * Input widget class for generating multiple checkboxes. <del> * <ide> */ <ide> class MultiCheckboxWidget implements WidgetInterface <ide> { <ide><path>tests/Fixture/ArticlesFixture.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class ArticlesFixture extends TestFixture <ide> { <ide><path>tests/Fixture/ArticlesTagsFixture.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class ArticlesTagsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/AssertHtmlTestCase.php <ide> <ide> /** <ide> * This class helps in indirectly testing the functionalities of TestCase::assertHtml <del> * <ide> */ <ide> class AssertHtmlTestCase extends TestCase <ide> { <ide><path>tests/Fixture/AssertIntegrationTestCase.php <ide> <ide> /** <ide> * This class helps in indirectly testing the functionalities of IntegrationTestCase <del> * <ide> */ <ide> class AssertIntegrationTestCase extends IntegrationTestCase <ide> { <ide><path>tests/Fixture/AttachmentsFixture.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class AttachmentsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/AuthUsersFixture.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class AuthUsersFixture extends TestFixture <ide> { <ide><path>tests/Fixture/AuthorsFixture.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class AuthorsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/AuthorsTagsFixture.php <ide> <ide> /** <ide> * AuthorsTags fixture <del> * <ide> */ <ide> class AuthorsTagsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/CakeSessionsFixture.php <ide> <ide> /** <ide> * Class SessionFixture <del> * <ide> */ <ide> class CakeSessionsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/CategoriesFixture.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class CategoriesFixture extends TestFixture <ide> { <ide><path>tests/Fixture/CommentsFixture.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class CommentsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/CounterCacheCategoriesFixture.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class CounterCacheCategoriesFixture extends TestFixture <ide> { <ide><path>tests/Fixture/CounterCachePostsFixture.php <ide> <ide> /** <ide> * Counter Cache Test Fixtures <del> * <ide> */ <ide> class CounterCachePostsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/CounterCacheUsersFixture.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class CounterCacheUsersFixture extends TestFixture <ide> { <ide><path>tests/Fixture/FeaturedTagsFixture.php <ide> <ide> /** <ide> * Class FeaturedTagsFixture <del> * <ide> */ <ide> class FeaturedTagsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/FixturizedTestCase.php <ide> <ide> /** <ide> * This class helps in testing the life-cycle of fixtures inside a CakeTestCase <del> * <ide> */ <ide> class FixturizedTestCase extends TestCase <ide> { <ide><path>tests/Fixture/GroupsFixture.php <ide> <ide> /** <ide> * Class GroupsFixture <del> * <ide> */ <ide> class GroupsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/GroupsMembersFixture.php <ide> <ide> /** <ide> * Class GroupsMembersFixture <del> * <ide> */ <ide> class GroupsMembersFixture extends TestFixture <ide> { <ide><path>tests/Fixture/MembersFixture.php <ide> <ide> /** <ide> * Class MembersFixture <del> * <ide> */ <ide> class MembersFixture extends TestFixture <ide> { <ide><path>tests/Fixture/MenuLinkTreesFixture.php <ide> * Class NumberTreeFixture <ide> * <ide> * Generates a tree of data for use testing the tree behavior <del> * <ide> */ <ide> class MenuLinkTreesFixture extends TestFixture <ide> { <ide><path>tests/Fixture/NumberTreesFixture.php <ide> * Class NumberTreeFixture <ide> * <ide> * Generates a tree of data for use testing the tree behavior <del> * <ide> */ <ide> class NumberTreesFixture extends TestFixture <ide> { <ide><path>tests/Fixture/OrdersFixture.php <ide> <ide> /** <ide> * Class OrdersFixture <del> * <ide> */ <ide> class OrdersFixture extends TestFixture <ide> { <ide><path>tests/Fixture/PostsFixture.php <ide> <ide> /** <ide> * Class PostFixture <del> * <ide> */ <ide> class PostsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/ProductsFixture.php <ide> <ide> /** <ide> * Class ProductsFixture <del> * <ide> */ <ide> class ProductsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/SessionsFixture.php <ide> <ide> /** <ide> * Class SessionFixture <del> * <ide> */ <ide> class SessionsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/SpecialTagsFixture.php <ide> <ide> /** <ide> * A fixture for a join table containing additional data <del> * <ide> */ <ide> class SpecialTagsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/TagsFixture.php <ide> <ide> /** <ide> * Class TagFixture <del> * <ide> */ <ide> class TagsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/TagsTranslationsFixture.php <ide> <ide> /** <ide> * Class TagsTranslationsFixture <del> * <ide> */ <ide> class TagsTranslationsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/TestPluginCommentsFixture.php <ide> <ide> /** <ide> * Class TestPluginCommentFixture <del> * <ide> */ <ide> class TestPluginCommentsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/TranslatesFixture.php <ide> <ide> /** <ide> * Class TranslateFixture <del> * <ide> */ <ide> class TranslatesFixture extends TestFixture <ide> { <ide><path>tests/Fixture/UsersFixture.php <ide> <ide> /** <ide> * Class UserFixture <del> * <ide> */ <ide> class UsersFixture extends TestFixture <ide> { <ide><path>tests/Fixture/UuiditemsFixture.php <ide> <ide> /** <ide> * Class UuiditemFixture <del> * <ide> */ <ide> class UuiditemsFixture extends TestFixture <ide> { <ide><path>tests/Fixture/UuidportfoliosFixture.php <ide> <ide> /** <ide> * Class UuidportfolioFixture <del> * <ide> */ <ide> class UuidportfoliosFixture extends TestFixture <ide> { <ide><path>tests/TestCase/Auth/BasicAuthenticateTest.php <ide> <ide> /** <ide> * Test case for BasicAuthentication <del> * <ide> */ <ide> class BasicAuthenticateTest extends TestCase <ide> { <ide><path>tests/TestCase/Auth/ControllerAuthorizeTest.php <ide> <ide> /** <ide> * Class ControllerAuthorizeTest <del> * <ide> */ <ide> class ControllerAuthorizeTest extends TestCase <ide> { <ide><path>tests/TestCase/Auth/DefaultPasswordHasherTest.php <ide> <ide> /** <ide> * Test case for DefaultPasswordHasher <del> * <ide> */ <ide> class DefaultPasswordHasherTest extends TestCase <ide> { <ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php <ide> <ide> /** <ide> * Test case for DigestAuthentication <del> * <ide> */ <ide> class DigestAuthenticateTest extends TestCase <ide> { <ide><path>tests/TestCase/Auth/FallbackPasswordHasherTest.php <ide> <ide> /** <ide> * Test case for FallbackPasswordHasher <del> * <ide> */ <ide> class FallbackPasswordHasherTest extends TestCase <ide> { <ide><path>tests/TestCase/Auth/FormAuthenticateTest.php <ide> <ide> /** <ide> * Test case for FormAuthentication <del> * <ide> */ <ide> class FormAuthenticateTest extends TestCase <ide> { <ide><path>tests/TestCase/Auth/PasswordHasherFactoryTest.php <ide> <ide> /** <ide> * Test case for PasswordHasherFactory <del> * <ide> */ <ide> class PasswordHasherFactoryTest extends TestCase <ide> { <ide><path>tests/TestCase/Auth/Storage/MemoryStorageTest.php <ide> <ide> /** <ide> * Test case for MemoryStorage <del> * <ide> */ <ide> class MemoryStorageTest extends TestCase <ide> { <ide><path>tests/TestCase/Auth/Storage/SessionStorageTest.php <ide> <ide> /** <ide> * Test case for SessionStorage <del> * <ide> */ <ide> class SessionStorageTest extends TestCase <ide> { <ide><path>tests/TestCase/Auth/WeakPasswordHasherTest.php <ide> <ide> /** <ide> * Test case for WeakPasswordHasher <del> * <ide> */ <ide> class WeakPasswordHasherTest extends TestCase <ide> { <ide><path>tests/TestCase/Cache/CacheTest.php <ide> <ide> /** <ide> * CacheTest class <del> * <ide> */ <ide> class CacheTest extends TestCase <ide> { <ide><path>tests/TestCase/Cache/Engine/ApcEngineTest.php <ide> <ide> /** <ide> * ApcEngineTest class <del> * <ide> */ <ide> class ApcEngineTest extends TestCase <ide> { <ide><path>tests/TestCase/Cache/Engine/MemcachedEngineTest.php <ide> <ide> /** <ide> * Class TestMemcachedEngine <del> * <ide> */ <ide> class TestMemcachedEngine extends MemcachedEngine <ide> { <ide> public function getMemcached() <ide> <ide> /** <ide> * MemcachedEngineTest class <del> * <ide> */ <ide> class MemcachedEngineTest extends TestCase <ide> { <ide><path>tests/TestCase/Cache/Engine/RedisEngineTest.php <ide> <ide> /** <ide> * RedisEngineTest class <del> * <ide> */ <ide> class RedisEngineTest extends TestCase <ide> { <ide><path>tests/TestCase/Cache/Engine/WincacheEngineTest.php <ide> <ide> /** <ide> * WincacheEngineTest class <del> * <ide> */ <ide> class WincacheEngineTest extends TestCase <ide> { <ide><path>tests/TestCase/Cache/Engine/XcacheEngineTest.php <ide> <ide> /** <ide> * XcacheEngineTest class <del> * <ide> */ <ide> class XcacheEngineTest extends TestCase <ide> { <ide><path>tests/TestCase/Collection/CollectionTest.php <ide> public function __construct($items) <ide> <ide> /** <ide> * CollectionTest <del> * <ide> */ <ide> class CollectionTest extends TestCase <ide> { <ide><path>tests/TestCase/Collection/Iterator/BufferedIteratorTest.php <ide> <ide> /** <ide> * BufferedIterator Test <del> * <ide> */ <ide> class BufferedIteratorTest extends TestCase <ide> { <ide><path>tests/TestCase/Collection/Iterator/ExtractIteratorTest.php <ide> <ide> /** <ide> * ExtractIterator Test <del> * <ide> */ <ide> class ExtractIteratorTest extends TestCase <ide> { <ide><path>tests/TestCase/Collection/Iterator/FilterIteratorTest.php <ide> <ide> /** <ide> * FilterIterator test <del> * <ide> */ <ide> class FilterIteratorTest extends TestCase <ide> { <ide><path>tests/TestCase/Collection/Iterator/InsertIteratorTest.php <ide> <ide> /** <ide> * InsertIterator Test <del> * <ide> */ <ide> class InsertIteratorTest extends TestCase <ide> { <ide><path>tests/TestCase/Collection/Iterator/MapReduceTest.php <ide> <ide> /** <ide> * Tests MapReduce class <del> * <ide> */ <ide> class MapReduceTest extends TestCase <ide> { <ide><path>tests/TestCase/Collection/Iterator/ReplaceIteratorTest.php <ide> <ide> /** <ide> * ReplaceIterator Test <del> * <ide> */ <ide> class ReplaceIteratorTest extends TestCase <ide> { <ide><path>tests/TestCase/Collection/Iterator/SortIteratorTest.php <ide> <ide> /** <ide> * SortIterator Test <del> * <ide> */ <ide> class SortIteratorTest extends TestCase <ide> { <ide><path>tests/TestCase/Collection/Iterator/TreeIteratorTest.php <ide> <ide> /** <ide> * TreeIterator Test <del> * <ide> */ <ide> class TreeIteratorTest extends TestCase <ide> { <ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php <ide> <ide> /** <ide> * Class ConsoleOptionParserTest <del> * <ide> */ <ide> class ConsoleOptionParserTest extends TestCase <ide> { <ide><path>tests/TestCase/Console/ConsoleOutputTest.php <ide> <ide> /** <ide> * Class ConsoleOutputTest <del> * <ide> */ <ide> class ConsoleOutputTest extends TestCase <ide> { <ide><path>tests/TestCase/Console/HelpFormatterTest.php <ide> <ide> /** <ide> * Class HelpFormatterTest <del> * <ide> */ <ide> class HelpFormatterTest extends TestCase <ide> { <ide><path>tests/TestCase/Console/HelperRegistryTest.php <ide> <ide> /** <ide> * Class HelperRegistryTest <del> * <ide> */ <ide> class HelperRegistryTest extends TestCase <ide> { <ide><path>tests/TestCase/Console/ShellDispatcherTest.php <ide> <ide> /** <ide> * ShellDispatcherTest <del> * <ide> */ <ide> class ShellDispatcherTest extends TestCase <ide> { <ide><path>tests/TestCase/Console/ShellTest.php <ide> class MergeShell extends Shell <ide> <ide> /** <ide> * ShellTestShell class <del> * <ide> */ <ide> class ShellTestShell extends Shell <ide> { <ide> public function logSomething() <ide> <ide> /** <ide> * TestAppleTask class <del> * <ide> */ <ide> class TestAppleTask extends Shell <ide> { <ide> } <ide> <ide> /** <ide> * TestBananaTask class <del> * <ide> */ <ide> class TestBananaTask extends Shell <ide> { <ide> class_alias(__NAMESPACE__ . '\TestBananaTask', 'Cake\Shell\Task\TestBananaTask') <ide> <ide> /** <ide> * ShellTest class <del> * <ide> */ <ide> class ShellTest extends TestCase <ide> { <ide><path>tests/TestCase/Console/TaskRegistryTest.php <ide> <ide> /** <ide> * Class TaskRegistryTest <del> * <ide> */ <ide> class TaskRegistryTest extends TestCase <ide> { <ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php <ide> <ide> /** <ide> * AuthComponentTest class <del> * <ide> */ <ide> class AuthComponentTest extends TestCase <ide> { <ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php <ide> <ide> /** <ide> * PaginatorTestController class <del> * <ide> */ <ide> class PaginatorTestController extends Controller <ide> { <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> <ide> /** <ide> * TestSecurityComponent <del> * <ide> */ <ide> class TestSecurityComponent extends SecurityComponent <ide> { <ide> public function authRequired(Controller $controller) <ide> <ide> /** <ide> * SecurityTestController <del> * <ide> */ <ide> class SecurityTestController extends Controller <ide> { <ide><path>tests/TestCase/Controller/ComponentTest.php <ide> <ide> /** <ide> * ComponentTest class <del> * <ide> */ <ide> class ComponentTest extends TestCase <ide> { <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> <ide> /** <ide> * AppController class <del> * <ide> */ <ide> class ControllerTestAppController extends Controller <ide> { <ide> public function beforeRender(Event $event) <ide> <ide> /** <ide> * AnotherTestController class <del> * <ide> */ <ide> class AnotherTestController extends ControllerTestAppController <ide> { <ide> } <ide> <ide> /** <ide> * ControllerTest class <del> * <ide> */ <ide> class ControllerTest extends TestCase <ide> { <ide><path>tests/TestCase/Controller/Exception/AuthSecurityExceptionTest.php <ide> <ide> /** <ide> * AuthSecurityException Test class <del> * <ide> */ <ide> class AuthSecurityExceptionTest extends TestCase <ide> { <ide><path>tests/TestCase/Controller/Exception/SecurityExceptionTest.php <ide> <ide> /** <ide> * SecurityException Test class <del> * <ide> */ <ide> class SecurityExceptionTest extends TestCase <ide> { <ide><path>tests/TestCase/Core/AppTest.php <ide> <ide> /** <ide> * AppTest class <del> * <ide> */ <ide> class AppTest extends TestCase <ide> { <ide><path>tests/TestCase/Core/Configure/Engine/IniConfigTest.php <ide> <ide> /** <ide> * Class IniConfigTest <del> * <ide> */ <ide> class IniConfigTest extends TestCase <ide> { <ide><path>tests/TestCase/Core/Configure/Engine/JsonConfigTest.php <ide> <ide> /** <ide> * Class JsonConfigTest <del> * <ide> */ <ide> class JsonConfigTest extends TestCase <ide> { <ide><path>tests/TestCase/Core/Configure/Engine/PhpConfigTest.php <ide> <ide> /** <ide> * Class PhpConfigTest <del> * <ide> */ <ide> class PhpConfigTest extends TestCase <ide> { <ide><path>tests/TestCase/Core/ConfigureTest.php <ide> <ide> /** <ide> * ConfigureTest <del> * <ide> */ <ide> class ConfigureTest extends TestCase <ide> { <ide><path>tests/TestCase/Core/InstanceConfigTraitTest.php <ide> protected function _configWrite($key, $value = null) <ide> <ide> /** <ide> * InstanceConfigTraitTest <del> * <ide> */ <ide> class InstanceConfigTraitTest extends TestCase <ide> { <ide><path>tests/TestCase/Core/PluginTest.php <ide> <ide> /** <ide> * PluginTest class <del> * <ide> */ <ide> class PluginTest extends TestCase <ide> { <ide><path>tests/TestCase/Core/StaticConfigTraitTest.php <ide> class TestLogStaticConfig <ide> <ide> /** <ide> * StaticConfigTraitTest class <del> * <ide> */ <ide> class StaticConfigTraitTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/Driver/MysqlTest.php <ide> <ide> /** <ide> * Tests Mysql driver <del> * <ide> */ <ide> class MysqlTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/Expression/FunctionExpressionTest.php <ide> <ide> /** <ide> * Tests FunctionExpression class <del> * <ide> */ <ide> class FunctionExpressionTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/Expression/IdentifierExpressionTest.php <ide> <ide> /** <ide> * Tests IdentifierExpression class <del> * <ide> */ <ide> class IdentifierExpressionTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/Expression/TupleComparisonTest.php <ide> <ide> /** <ide> * Tests TupleComparison class <del> * <ide> */ <ide> class TupleComparisonTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/FunctionsBuilderTest.php <ide> <ide> /** <ide> * Tests FunctionsBuilder class <del> * <ide> */ <ide> class FunctionsBuilderTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/Log/LoggedQueryTest.php <ide> <ide> /** <ide> * Tests LoggedQuery class <del> * <ide> */ <ide> class LoggedQueryTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/Log/LoggingStatementTest.php <ide> <ide> /** <ide> * Tests LoggingStatement class <del> * <ide> */ <ide> class LoggingStatementTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/Log/QueryLoggerTest.php <ide> <ide> /** <ide> * Tests QueryLogger class <del> * <ide> */ <ide> class QueryLoggerTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/QueryTest.php <ide> <ide> /** <ide> * Tests Query class <del> * <ide> */ <ide> class QueryTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/Schema/TableTest.php <ide> <ide> /** <ide> * Mock class for testing baseType inheritance <del> * <ide> */ <ide> class FooType extends Type <ide> { <ide><path>tests/TestCase/Database/Statement/StatementDecoratorTest.php <ide> <ide> /** <ide> * Tests StatementDecorator class <del> * <ide> */ <ide> class StatemetDecoratorTest extends TestCase <ide> { <ide><path>tests/TestCase/Database/TypeTest.php <ide> <ide> /** <ide> * Mock class for testing type registering <del> * <ide> */ <ide> class FooType extends \Cake\Database\Type <ide> { <ide><path>tests/TestCase/DatabaseSuite.php <ide> <ide> /** <ide> * All tests related to database <del> * <ide> */ <ide> class DatabaseSuite extends TestSuite <ide> { <ide><path>tests/TestCase/Datasource/ResultSetDecoratorTest.php <ide> <ide> /** <ide> * Tests ResultSetDecorator class <del> * <ide> */ <ide> class ResultSetDecoratorTest extends TestCase <ide> { <ide><path>tests/TestCase/Error/DebuggerTest.php <ide> <ide> /** <ide> * DebuggerTestCaseDebugger class <del> * <ide> */ <ide> class DebuggerTestCaseDebugger extends Debugger <ide> { <ide> public function __debugInfo() <ide> * <ide> * !!! Be careful with changing code below as it may <ide> * !!! change line numbers which are used in the tests <del> * <ide> */ <ide> class DebuggerTest extends TestCase <ide> { <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> <ide> /** <ide> * BlueberryComponent class <del> * <ide> */ <ide> class BlueberryComponent extends Component <ide> { <ide> public function initialize(array $config) <ide> <ide> /** <ide> * TestErrorController class <del> * <ide> */ <ide> class TestErrorController extends Controller <ide> { <ide> public function index() <ide> <ide> /** <ide> * MyCustomExceptionRenderer class <del> * <ide> */ <ide> class MyCustomExceptionRenderer extends ExceptionRenderer <ide> { <ide> public function missingWidgetThing() <ide> <ide> /** <ide> * Exception class for testing app error handlers and custom errors. <del> * <ide> */ <ide> class MissingWidgetThingException extends NotFoundException <ide> { <ide> } <ide> <ide> /** <ide> * Exception class for testing app error handlers and custom errors. <del> * <ide> */ <ide> class MissingWidgetThing extends \Exception <ide> { <ide> } <ide> <ide> /** <ide> * ExceptionRendererTest class <del> * <ide> */ <ide> class ExceptionRendererTest extends TestCase <ide> { <ide><path>tests/TestCase/Event/EventDispatcherTraitTest.php <ide> <ide> /** <ide> * EventDispatcherTrait test case <del> * <ide> */ <ide> class EventDispatcherTraitTest extends TestCase <ide> { <ide><path>tests/TestCase/Event/EventManagerTest.php <ide> public function thirdListenerFunction() <ide> <ide> /** <ide> * Tests the Cake\Event\EventManager class functionality <del> * <ide> */ <ide> class EventManagerTest extends TestCase <ide> { <ide><path>tests/TestCase/Event/EventTest.php <ide> <ide> /** <ide> * Tests the Cake\Event\Event class functionality <del> * <ide> */ <ide> class EventTest extends TestCase <ide> { <ide><path>tests/TestCase/Filesystem/FileTest.php <ide> <ide> /** <ide> * FileTest class <del> * <ide> */ <ide> class FileTest extends TestCase <ide> { <ide><path>tests/TestCase/I18n/Formatter/IcuFormatterTest.php <ide> <ide> /** <ide> * IcuFormatter tests <del> * <ide> */ <ide> class IcuFormatterTest extends TestCase <ide> { <ide><path>tests/TestCase/I18n/Formatter/SprintfFormatterTest.php <ide> <ide> /** <ide> * SprintfFormatter tests <del> * <ide> */ <ide> class SprintfFormatterTest extends TestCase <ide> { <ide><path>tests/TestCase/I18n/I18nTest.php <ide> <ide> /** <ide> * I18nTest class <del> * <ide> */ <ide> class I18nTest extends TestCase <ide> { <ide><path>tests/TestCase/I18n/MessagesFileLoaderTest.php <ide> <ide> /** <ide> * MessagesFileLoaderTest class <del> * <ide> */ <ide> class MessagesFileLoaderTest extends TestCase <ide> { <ide><path>tests/TestCase/I18n/NumberTest.php <ide> <ide> /** <ide> * NumberTest class <del> * <ide> */ <ide> class NumberTest extends TestCase <ide> { <ide><path>tests/TestCase/I18n/Parser/MoFileParserTest.php <ide> <ide> /** <ide> * Tests the MoFileLoader <del> * <ide> */ <ide> class MoFileParserTest extends TestCase <ide> { <ide><path>tests/TestCase/I18n/Parser/PoFileParserTest.php <ide> <ide> /** <ide> * Tests the PoFileLoader <del> * <ide> */ <ide> class PoFileParserTest extends TestCase <ide> { <ide><path>tests/TestCase/I18n/PluralRulesTest.php <ide> <ide> /** <ide> * PluralRules tests <del> * <ide> */ <ide> class PluralRulesTest extends TestCase <ide> { <ide><path>tests/TestCase/I18n/TimeTest.php <ide> <ide> /** <ide> * TimeTest class <del> * <ide> */ <ide> class TimeTest extends TestCase <ide> { <ide><path>tests/TestCase/Log/Engine/ConsoleLogTest.php <ide> <ide> /** <ide> * ConsoleLogTest class <del> * <ide> */ <ide> class ConsoleLogTest extends TestCase <ide> { <ide><path>tests/TestCase/Log/Engine/FileLogTest.php <ide> <ide> /** <ide> * Class used for testing when an object is passed to a logger <del> * <ide> */ <ide> class StringObject <ide> { <ide> public function __toString() <ide> <ide> /** <ide> * Class used for testing when an serializable is passed to a logger <del> * <ide> */ <ide> class JsonObject implements JsonSerializable <ide> { <ide> public function jsonSerialize() <ide> <ide> /** <ide> * FileLogTest class <del> * <ide> */ <ide> class FileLogTest extends TestCase <ide> { <ide><path>tests/TestCase/Log/LogTest.php <ide> <ide> /** <ide> * LogTest class <del> * <ide> */ <ide> class LogTest extends TestCase <ide> { <ide><path>tests/TestCase/Log/LogTraitTest.php <ide> <ide> /** <ide> * Test case for LogTrait <del> * <ide> */ <ide> class LogTraitTest extends TestCase <ide> { <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> <ide> /** <ide> * Help to test Email <del> * <ide> */ <ide> class TestEmail extends Email <ide> { <ide><path>tests/TestCase/Mailer/Transport/DebugTransportTest.php <ide> <ide> /** <ide> * Test case <del> * <ide> */ <ide> class DebugTransportTest extends TestCase <ide> { <ide><path>tests/TestCase/Mailer/Transport/MailTransportTest.php <ide> <ide> /** <ide> * Test case <del> * <ide> */ <ide> class MailTransportTest extends TestCase <ide> { <ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php <ide> <ide> /** <ide> * Help to test SmtpTransport <del> * <ide> */ <ide> class SmtpTestTransport extends SmtpTransport <ide> { <ide> public function __call($method, $args) <ide> <ide> /** <ide> * Test case <del> * <ide> */ <ide> class SmtpTransportTest extends TestCase <ide> { <ide><path>tests/TestCase/Network/RequestTest.php <ide> <ide> /** <ide> * Class TestRequest <del> * <ide> */ <ide> class RequestTest extends TestCase <ide> { <ide><path>tests/TestCase/Network/ResponseTest.php <ide> <ide> /** <ide> * Class ResponseTest <del> * <ide> */ <ide> class ResponseTest extends TestCase <ide> { <ide><path>tests/TestCase/Network/Session/CacheSessionTest.php <ide> <ide> /** <ide> * Class CacheSessionTest <del> * <ide> */ <ide> class CacheSessionTest extends TestCase <ide> { <ide><path>tests/TestCase/Network/Session/DatabaseSessionTest.php <ide> <ide> /** <ide> * Database session test. <del> * <ide> */ <ide> class DatabaseSessionTest extends TestCase <ide> { <ide><path>tests/TestCase/Network/SessionTest.php <ide> <ide> /** <ide> * Class TestCacheSession <del> * <ide> */ <ide> class TestCacheSession extends CacheSession <ide> { <ide> protected function _writeSession() <ide> <ide> /** <ide> * Class TestDatabaseSession <del> * <ide> */ <ide> class TestDatabaseSession extends DatabaseSession <ide> { <ide> protected function _writeSession() <ide> <ide> /** <ide> * SessionTest class <del> * <ide> */ <ide> class SessionTest extends TestCase <ide> { <ide><path>tests/TestCase/Network/SocketTest.php <ide> <ide> /** <ide> * SocketTest class <del> * <ide> */ <ide> class SocketTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> <ide> /** <ide> * Tests BelongsToMany class <del> * <ide> */ <ide> class BelongsToManyTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/Association/BelongsToTest.php <ide> <ide> /** <ide> * Tests BelongsTo class <del> * <ide> */ <ide> class BelongsToTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> <ide> /** <ide> * Tests HasMany class <del> * <ide> */ <ide> class HasManyTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/Association/HasOneTest.php <ide> <ide> /** <ide> * Tests HasOne class <del> * <ide> */ <ide> class HasOneTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/AssociationProxyTest.php <ide> /** <ide> * Tests the features related to proxying methods from the Association <ide> * class to the Table class <del> * <ide> */ <ide> class AssociationProxyTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/AssociationTest.php <ide> <ide> /** <ide> * A Test double used to assert that default tables are created <del> * <ide> */ <ide> class TestTable extends Table <ide> { <ide> public function findPublished($query) <ide> <ide> /** <ide> * Tests Association class <del> * <ide> */ <ide> class AssociationTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/EagerLoaderTest.php <ide> <ide> /** <ide> * Tests EagerLoader <del> * <ide> */ <ide> class EagerLoaderTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/Locator/LocatorAwareTraitTest.php <ide> <ide> /** <ide> * LocatorAwareTrait test case <del> * <ide> */ <ide> class LocatorAwareTraitTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> <ide> /** <ide> * Contains regression test for the Query builder <del> * <ide> */ <ide> class QueryRegressionTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/TableRegressionTest.php <ide> <ide> /** <ide> * Contains regression test for the Table class <del> * <ide> */ <ide> class TableRegressionTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/TableTest.php <ide> class UsersTable extends Table <ide> <ide> /** <ide> * Tests Table class <del> * <ide> */ <ide> class TableTest extends TestCase <ide> { <ide><path>tests/TestCase/ORM/TableUuidTest.php <ide> <ide> /** <ide> * Integration tests for Table class with uuid primary keys. <del> * <ide> */ <ide> class TableUuidTest extends TestCase <ide> { <ide><path>tests/TestCase/Routing/DispatcherTest.php <ide> protected function _invoke(Controller $controller) <ide> <ide> /** <ide> * MyPluginAppController class <del> * <ide> */ <ide> class MyPluginAppController extends Controller <ide> { <ide> public function index(); <ide> <ide> /** <ide> * MyPluginController class <del> * <ide> */ <ide> class MyPluginController extends MyPluginAppController <ide> { <ide> public function admin_add($id = null) <ide> <ide> /** <ide> * OtherPagesController class <del> * <ide> */ <ide> class OtherPagesController extends MyPluginAppController <ide> { <ide> public function index() <ide> <ide> /** <ide> * ArticlesTestAppController class <del> * <ide> */ <ide> class ArticlesTestAppController extends Controller <ide> { <ide> } <ide> <ide> /** <ide> * ArticlesTestController class <del> * <ide> */ <ide> class ArticlesTestController extends ArticlesTestAppController <ide> { <ide> public function index() <ide> <ide> /** <ide> * DispatcherTest class <del> * <ide> */ <ide> class DispatcherTest extends TestCase <ide> { <ide><path>tests/TestCase/Routing/Route/PluginShortRouteTest.php <ide> <ide> /** <ide> * test case for PluginShortRoute <del> * <ide> */ <ide> class PluginShortRouteTest extends TestCase <ide> { <ide><path>tests/TestCase/Routing/Route/RedirectRouteTest.php <ide> <ide> /** <ide> * test case for RedirectRoute <del> * <ide> */ <ide> class RedirectRouteTest extends TestCase <ide> { <ide><path>tests/TestCase/Routing/RouterTest.php <ide> <ide> /** <ide> * RouterTest class <del> * <ide> */ <ide> class RouterTest extends TestCase <ide> { <ide><path>tests/TestCase/Shell/CommandListShellTest.php <ide> <ide> /** <ide> * Class CommandListShellTest <del> * <ide> */ <ide> class CommandListShellTest extends TestCase <ide> { <ide><path>tests/TestCase/Shell/CompletionShellTest.php <ide> <ide> /** <ide> * Class TestCompletionStringOutput <del> * <ide> */ <ide> class TestCompletionStringOutput extends ConsoleOutput <ide> { <ide><path>tests/TestCase/Shell/RoutesShellTest.php <ide> <ide> /** <ide> * Class RoutesShellTest <del> * <ide> */ <ide> class RoutesShellTest extends TestCase <ide> { <ide><path>tests/TestCase/Shell/Task/AssetsTaskTest.php <ide> <ide> /** <ide> * AssetsTaskTest class <del> * <ide> */ <ide> class AssetsTaskTest extends TestCase <ide> { <ide><path>tests/TestCase/Shell/Task/ExtractTaskTest.php <ide> <ide> /** <ide> * ExtractTaskTest class <del> * <ide> */ <ide> class ExtractTaskTest extends TestCase <ide> { <ide><path>tests/TestCase/Shell/Task/LoadTaskTest.php <ide> <ide> /** <ide> * LoadTaskTest class. <del> * <ide> */ <ide> class LoadTaskTest extends TestCase <ide> { <ide><path>tests/TestCase/Shell/Task/UnloadTaskTest.php <ide> <ide> /** <ide> * UnloadTaskTest class <del> * <ide> */ <ide> class UnloadTaskTest extends TestCase <ide> { <ide><path>tests/TestCase/TestSuite/TestCaseTest.php <ide> public static function defaultConnectionName() <ide> <ide> /** <ide> * TestCaseTest <del> * <ide> */ <ide> class TestCaseTest extends TestCase <ide> { <ide><path>tests/TestCase/TestSuite/TestFixtureTest.php <ide> <ide> /** <ide> * ArticlesFixture class <del> * <ide> */ <ide> class ArticlesFixture extends TestFixture <ide> { <ide> class ArticlesFixture extends TestFixture <ide> <ide> /** <ide> * StringsTestsFixture class <del> * <ide> */ <ide> class StringsTestsFixture extends TestFixture <ide> { <ide> class StringsTestsFixture extends TestFixture <ide> <ide> /** <ide> * ImportsFixture class <del> * <ide> */ <ide> class ImportsFixture extends TestFixture <ide> { <ide> class ImportsFixture extends TestFixture <ide> /** <ide> * This class allows testing the fixture data insertion when the properties <ide> * $fields and $import are not set <del> * <ide> */ <ide> class LettersFixture extends TestFixture <ide> { <ide> class LettersFixture extends TestFixture <ide> <ide> /** <ide> * Test case for TestFixture <del> * <ide> */ <ide> class TestFixtureTest extends TestCase <ide> { <ide><path>tests/TestCase/TestSuite/TestSuiteTest.php <ide> <ide> /** <ide> * TestSuiteTest <del> * <ide> */ <ide> class TestSuiteTest extends TestCase <ide> { <ide><path>tests/TestCase/Utility/HashTest.php <ide> <ide> /** <ide> * Class HashTest <del> * <ide> */ <ide> class HashTest extends TestCase <ide> { <ide><path>tests/TestCase/Utility/InflectorTest.php <ide> <ide> /** <ide> * Short description for class. <del> * <ide> */ <ide> class InflectorTest extends TestCase <ide> { <ide><path>tests/TestCase/Utility/MergeVariablesTraitTest.php <ide> class Grandchild extends Child <ide> <ide> /** <ide> * MergeVariablesTrait test case <del> * <ide> */ <ide> class MergeVariablesTraitTest extends TestCase <ide> { <ide><path>tests/TestCase/Utility/SecurityTest.php <ide> <ide> /** <ide> * SecurityTest class <del> * <ide> */ <ide> class SecurityTest extends TestCase <ide> { <ide><path>tests/TestCase/Utility/TextTest.php <ide> <ide> /** <ide> * TextTest class <del> * <ide> */ <ide> class TextTest extends TestCase <ide> { <ide><path>tests/TestCase/Utility/XmlTest.php <ide> <ide> /** <ide> * XmlTest class <del> * <ide> */ <ide> class XmlTest extends TestCase <ide> { <ide><path>tests/TestCase/Validation/RulesProviderTest.php <ide> <ide> /** <ide> * Tests RulesProvider class <del> * <ide> */ <ide> class RulesProviderTest extends TestCase <ide> { <ide><path>tests/TestCase/Validation/ValidationRuleTest.php <ide> <ide> /** <ide> * ValidationRuleTest <del> * <ide> */ <ide> class ValidationRuleTest extends TestCase <ide> { <ide><path>tests/TestCase/Validation/ValidationSetTest.php <ide> <ide> /** <ide> * ValidationSetTest <del> * <ide> */ <ide> class ValidationSetTest extends TestCase <ide> { <ide><path>tests/TestCase/Validation/ValidationTest.php <ide> <ide> /** <ide> * Test Case for Validation Class <del> * <ide> */ <ide> class ValidationTest extends TestCase <ide> { <ide><path>tests/TestCase/Validation/ValidatorTest.php <ide> <ide> /** <ide> * Tests Validator class <del> * <ide> */ <ide> class ValidatorTest extends TestCase <ide> { <ide><path>tests/TestCase/View/Helper/FlashHelperTest.php <ide> <ide> /** <ide> * FlashHelperTest class <del> * <ide> */ <ide> class FlashHelperTest extends TestCase <ide> { <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> class Article extends Entity <ide> <ide> /** <ide> * Contact class <del> * <ide> */ <ide> class ContactsTable extends Table <ide> { <ide> public function initialize(array $config) <ide> <ide> /** <ide> * ValidateUser class <del> * <ide> */ <ide> class ValidateUsersTable extends Table <ide> { <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php <ide> <ide> /** <ide> * HtmlHelperTest class <del> * <ide> */ <ide> class HtmlHelperTest extends TestCase <ide> { <ide><path>tests/TestCase/View/Helper/NumberHelperTest.php <ide> class NumberMock <ide> <ide> /** <ide> * NumberHelperTest class <del> * <ide> */ <ide> class NumberHelperTest extends TestCase <ide> { <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> <ide> /** <ide> * PaginatorHelperTest class <del> * <ide> */ <ide> class PaginatorHelperTest extends TestCase <ide> { <ide><path>tests/TestCase/View/Helper/RssHelperTest.php <ide> <ide> /** <ide> * RssHelperTest class <del> * <ide> */ <ide> class RssHelperTest extends TestCase <ide> { <ide><path>tests/TestCase/View/Helper/TextHelperTest.php <ide> <ide> /** <ide> * Class TextHelperTestObject <del> * <ide> */ <ide> class TextHelperTestObject extends TextHelper <ide> { <ide> public function engine() <ide> <ide> /** <ide> * StringMock class <del> * <ide> */ <ide> class StringMock <ide> { <ide> } <ide> <ide> /** <ide> * TextHelperTest class <del> * <ide> */ <ide> class TextHelperTest extends TestCase <ide> { <ide><path>tests/TestCase/View/Helper/TimeHelperTest.php <ide> <ide> /** <ide> * TimeHelperTest class <del> * <ide> */ <ide> class TimeHelperTest extends TestCase <ide> { <ide><path>tests/TestCase/View/Helper/UrlHelperTest.php <ide> <ide> /** <ide> * UrlHelperTest class <del> * <ide> */ <ide> class UrlHelperTest extends TestCase <ide> { <ide><path>tests/TestCase/View/HelperRegistryTest.php <ide> public function afterRender($viewFile) <ide> <ide> /** <ide> * Class HelperRegistryTest <del> * <ide> */ <ide> class HelperRegistryTest extends TestCase <ide> { <ide><path>tests/TestCase/View/HelperTest.php <ide> public function parseAttributes($options, $exclude = null, $insertBefore = ' ', <ide> <ide> /** <ide> * HelperTest class <del> * <ide> */ <ide> class HelperTest extends TestCase <ide> { <ide><path>tests/TestCase/View/JsonViewTest.php <ide> <ide> /** <ide> * JsonViewTest <del> * <ide> */ <ide> class JsonViewTest extends TestCase <ide> { <ide><path>tests/TestCase/View/StringTemplateTraitTest.php <ide> <ide> /** <ide> * TestStringTemplate <del> * <ide> */ <ide> class TestStringTemplate <ide> { <ide> class TestStringTemplate <ide> <ide> /** <ide> * StringTemplateTraitTest class <del> * <ide> */ <ide> class StringTemplateTraitTest extends TestCase <ide> { <ide><path>tests/TestCase/View/ViewTest.php <ide> <ide> /** <ide> * ViewPostsController class <del> * <ide> */ <ide> class ViewPostsController extends Controller <ide> { <ide> public function nocache_multiple_element() <ide> <ide> /** <ide> * ThemePostsController class <del> * <ide> */ <ide> class ThemePostsController extends Controller <ide> { <ide> public function index() <ide> <ide> /** <ide> * TestView class <del> * <ide> */ <ide> class TestView extends AppView <ide> { <ide> public function ext($ext) <ide> <ide> /** <ide> * TestBeforeAfterHelper class <del> * <ide> */ <ide> class TestBeforeAfterHelper extends Helper <ide> { <ide> public function afterRender(Event $event) <ide> <ide> /** <ide> * ViewTest class <del> * <ide> */ <ide> class ViewTest extends TestCase <ide> { <ide><path>tests/TestCase/View/ViewVarsTraitTest.php <ide> <ide> /** <ide> * ViewVarsTrait test case <del> * <ide> */ <ide> class ViewVarsTraitTest extends TestCase <ide> { <ide><path>tests/TestCase/View/XmlViewTest.php <ide> <ide> /** <ide> * XmlViewTest <del> * <ide> */ <ide> class XmlViewTest extends TestCase <ide> { <ide><path>tests/test_app/Plugin/Company/TestPluginThree/src/Model/Table/TestPluginThreeCommentsTable.php <ide> <ide> /** <ide> * Class TestPluginThreeCommentsTable <del> * <ide> */ <ide> class TestPluginThreeCommentsTable extends Table <ide> { <ide><path>tests/test_app/Plugin/TestPlugin/src/Cache/Engine/TestPluginCacheEngine.php <ide> <ide> /** <ide> * Class TestPluginCacheEngine <del> * <ide> */ <ide> namespace TestPlugin\Cache\Engine; <ide> <ide><path>tests/test_app/Plugin/TestPlugin/src/Controller/Component/PluginsComponent.php <ide> <ide> /** <ide> * Class PluginsComponent <del> * <ide> */ <ide> namespace TestPlugin\Controller\Component; <ide> <ide><path>tests/test_app/Plugin/TestPlugin/src/Controller/Component/TestPluginComponent.php <ide> <ide> /** <ide> * Class TestPluginComponent <del> * <ide> */ <ide> namespace TestPlugin\Controller\Component; <ide> <ide><path>tests/test_app/Plugin/TestPlugin/src/Controller/Component/TestPluginOtherComponent.php <ide> <ide> /** <ide> * Class TestPluginOtherComponent <del> * <ide> */ <ide> namespace TestPlugin\Controller\Component; <ide> <ide><path>tests/test_app/Plugin/TestPlugin/src/Controller/TestPluginAppController.php <ide> <ide> /** <ide> * Class TestPluginAppController <del> * <ide> */ <ide> class TestPluginAppController extends Controller <ide> { <ide><path>tests/test_app/Plugin/TestPlugin/src/Controller/TestsController.php <ide> <ide> /** <ide> * Class TestsController <del> * <ide> */ <ide> namespace TestPlugin\Controller; <ide> <ide><path>tests/test_app/Plugin/TestPlugin/src/Error/TestPluginExceptionRenderer.php <ide> <ide> /** <ide> * Class TestPluginExceptionRenderer <del> * <ide> */ <ide> class TestPluginExceptionRenderer extends ExceptionRenderer <ide> {
300
Javascript
Javascript
use findnextwhere correctly
c476db0dd7269ef47e36162b3f9ab2323f409d2e
<ide><path>src/Chart.Core.js <ide> return animationWrapper.chartInstance === chartInstance; <ide> }); <ide> <del> if (index != -1) <add> if (index) <ide> { <ide> this.animations.splice(index, 1); <ide> }
1
Go
Go
remove misleading comment
99c59d5988d20a6722224da918fdec299d3aaded
<ide><path>distribution/pull_v2.go <ide> func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named) (tagUpdat <ide> tagOrDigest string // Used for logging/progress only <ide> ) <ide> if tagged, isTagged := ref.(reference.NamedTagged); isTagged { <del> // NOTE: not using TagService.Get, since it uses HEAD requests <del> // against the manifests endpoint, which are not supported by <del> // all registry versions. <ide> manifest, err = manSvc.Get(ctx, "", distribution.WithTag(tagged.Tag())) <ide> if err != nil { <ide> return false, allowV1Fallback(err)
1
Text
Text
update variable names.
77f36c7194f405684b00518882dfceaaf92b68b0
<ide><path>guide/english/csharp/null-conditional-operator/index.md <ide> However, in C# 6.0 null-conditional operators were introduced, so now the above <ide> be represented as follows: <ide> <ide> ```csharp <del>Address address = student?.Address; <add>Address address = employee?.Address; <ide> ``` <ide> <ide> If employee is null, address will simply be assigned null, and no NullReferenceExeception will occur. <ide> This becomes more useful with deeper object graphs, as you can handle a chain of conditional member access. <ide> <ide> For example: <ide> ```csharp <del>string city = student?.Address?.City; <add>string city = employee?.Address?.City; <ide> ``` <ide> <ide> Null-conditional operators are short-circuiting, so as soon as one check of conditional member access
1
Ruby
Ruby
extract column check in values_list
89fc7fbf82c29463e20550cca3e10453614b61f8
<ide><path>activerecord/lib/active_record/insert_all.rb <ide> <ide> module ActiveRecord <ide> class InsertAll <del> attr_reader :model, :connection, :inserts, :on_duplicate, :returning, :unique_by <add> attr_reader :model, :connection, :inserts, :keys <add> attr_reader :on_duplicate, :returning, :unique_by <ide> <ide> def initialize(model, inserts, on_duplicate:, returning: nil, unique_by: nil) <ide> raise ArgumentError, "Empty list of attributes passed" if inserts.blank? <ide> <del> @model, @connection, @inserts, @on_duplicate, @returning, @unique_by = model, model.connection, inserts, on_duplicate, returning, unique_by <add> @model, @connection, @inserts, @keys = model, model.connection, inserts, inserts.first.keys.map(&:to_s).to_set <add> @on_duplicate, @returning, @unique_by = on_duplicate, returning, unique_by <ide> <ide> @returning = (connection.supports_insert_returning? ? primary_keys : false) if @returning.nil? <ide> @returning = false if @returning == [] <ide> def execute <ide> connection.exec_query to_sql, "Bulk Insert" <ide> end <ide> <del> def keys <del> inserts.first.keys.map(&:to_s) <del> end <del> <ide> def updatable_columns <ide> keys - readonly_columns - unique_by_columns <ide> end <ide> def into <ide> <ide> def values_list <ide> columns = connection.schema_cache.columns_hash(model.table_name) <del> <del> column_names = columns.keys.to_set <del> keys = insert_all.keys.to_set <del> unknown_columns = keys - column_names <del> <del> unless unknown_columns.empty? <del> raise UnknownAttributeError.new(model.new, unknown_columns.first) <del> end <add> keys = insert_all.keys <add> verify_columns_exist_for(keys, columns) <ide> <ide> types = keys.map { |key| [ key, connection.lookup_cast_type_from_column(columns[key]) ] }.to_h <ide> <ide> def quote_columns(columns) <ide> columns.map(&connection.method(:quote_column_name)) <ide> end <ide> <add> def verify_columns_exist_for(keys, columns) <add> unknown_columns = keys - columns.keys <add> <add> if unknown_columns.any? <add> raise UnknownAttributeError.new(model.new, unknown_columns.first) <add> end <add> end <add> <ide> def conflict_columns <ide> @conflict_columns ||= begin <ide> conflict_columns = insert_all.unique_by.fetch(:columns) if insert_all.unique_by
1
Text
Text
add badge for coverage status
428cbe83e1158e8256b2ba83eab6ab8c61b5e373
<ide><path>README.md <ide> <ide> [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.txt) <ide> [![Build Status](https://img.shields.io/travis/cakephp/cakephp/master.svg?style=flat-square)](https://travis-ci.org/cakephp/cakephp) <add>[![Coverage Status](https://img.shields.io/coveralls/cakephp/cakephp/master.svg?style=flat-square)](https://coveralls.io/r/cakephp/cakephp?branch=master) <ide> [![Code Consistency](http://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/grade.svg)](http://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/) <ide> [![Total Downloads](https://img.shields.io/packagist/dt/cakephp/cakephp.svg?style=flat-square)](https://packagist.org/packages/cakephp/cakephp) <ide>
1
Text
Text
add facebook api key instructions
102d504965e90b68a4ad3231d33923ab1fac7854
<ide><path>README.md <ide> Obtaining API Keys <ide> ------------------ <ide> <ide> <img src="http://images.google.com/intl/en_ALL/images/srpr/logo6w.png" width="200"> <del> - Go to [https://cloud.google.com/console/project](https://cloud.google.com/console/project) <del> - Click **CREATE PROJECT** button <del> - Enter *Project Name*, then click **CREATE** <del> - Then select *APIs & auth* from the sidebar and click on *Credentials* tab <del> - Click **CREATE NEW CLIENT ID** button <del> - **Application Type**: Web Application <del> - **Authorized Javascript origins**: http://localhost:3000 <del> - **Authorized redirect URI**: http://localhost:3000/auth/google/callback <del> - Copy and paste *Client ID* and *Client secret* keys into `config/secrets.js` <add>- Visit [Google Cloud Console](https://cloud.google.com/console/project) <add>- Click **CREATE PROJECT** button <add>- Enter *Project Name*, then click **CREATE** <add>- Then select *APIs & auth* from the sidebar and click on *Credentials* tab <add>- Click **CREATE NEW CLIENT ID** button <add> - **Application Type**: Web Application <add> - **Authorized Javascript origins**: http://localhost:3000 <add> - **Authorized redirect URI**: http://localhost:3000/auth/google/callback <add>- Copy and paste *Client ID* and *Client secret* keys into `config/secrets.js` <ide> <ide> > **Note**: When you ready to deploy to production don't forget to add <ide> > your new url to Authorized Javascript origins and Authorized redirect URI, <ide> > e.g. `http://my-awesome-app.herokuapp.com` and `http://my-awesome-app.herokuapp.com/auth/google/callback` respectively. <ide> <add> <add><img src="http://www.doit.ba/img/facebook.jpg" width="200"> <add>- Visit [Facebook Developers](https://developers.facebook.com/) <add>- Click **Apps > Create a New App** in the navigation bar <add>- Enter *Display Name*, then choose a category, then click **Create app** <add>- Copy and paste *App ID* and *App Secret* keys into `config/secrets.js` <add>- Click on *Settings* on the sidebar, then click **+ Add Platform** <add>- Select **Website** <add>- Enter `http://localhost:3000` for *Site URL* <add> <add> <ide> Recommended Node.js Libraries <ide> ----------------------------- <ide> - nodemon - automatically restart node.js server on code change.
1
Ruby
Ruby
handle sigttou and sigttin to avoid hangs
8eb4756d3efcb13d5d39a0cb0b3d05aef1dfc56a
<ide><path>Library/Homebrew/sandbox.rb <ide> def exec(*args) <ide> end <ide> <ide> write_to_pty = proc do <add> # Don't hang if stdin is not able to be used - throw EIO instead. <add> old_ttin = trap(:TTIN, "IGNORE") <add> <ide> # Update the window size whenever the parent terminal's window size changes. <ide> old_winch = trap(:WINCH, &winch) <ide> winch.call(nil) <ide> <del> stdin_thread = Thread.new { IO.copy_stream($stdin, w) } <add> stdin_thread = Thread.new do <add> IO.copy_stream($stdin, w) <add> rescue Errno::EIO <add> # stdin is unavailable - move on. <add> end <ide> <ide> r.each_char { |c| print(c) } <ide> <ide> Process.wait(pid) <ide> ensure <ide> stdin_thread&.kill <add> trap(:TTIN, old_ttin) <ide> trap(:WINCH, old_winch) <ide> end <ide> <ide> def exec(*args) <ide> # mode while we copy the input/output of the process spawned in the <ide> # PTY. After we've finished copying to/from the PTY process, io.raw <ide> # will restore the stdin TTY to its original state. <del> $stdin.raw(&write_to_pty) <add> begin <add> # Ignore SIGTTOU as setting raw mode will hang if the process is in the background. <add> old_ttou = trap(:TTOU, "IGNORE") <add> $stdin.raw(&write_to_pty) <add> ensure <add> trap(:TTOU, old_ttou) <add> end <ide> else <ide> write_to_pty.call <ide> end
1
PHP
PHP
add empty lines
6a09db676e53f95f07c7ff252dd1842fea053fdc
<ide><path>src/Illuminate/Filesystem/Filesystem.php <ide> public function get($path, $lock = false) <ide> if ($lock) { <ide> return $this->sharedGet($path, $lock); <ide> } <add> <ide> return file_get_contents($path); <ide> } <ide> <ide> public function sharedGet($path) <ide> } <ide> fclose($handle); <ide> } <add> <ide> return $contents; <ide> } <ide>
1
Go
Go
remove unused sysinfo parameter to runconfig.parse
e45b0f92711ff190cff4b61b2ea80cdd53203a16
<ide><path>api/client/commands.go <ide> func (cli *DockerCli) CmdCreate(args ...string) error { <ide> flName = cmd.String([]string{"-name"}, "", "Assign a name to the container") <ide> ) <ide> <del> config, hostConfig, cmd, err := runconfig.Parse(cmd, args, nil) <add> config, hostConfig, cmd, err := runconfig.Parse(cmd, args) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d") <ide> ) <ide> <del> config, hostConfig, cmd, err := runconfig.Parse(cmd, args, nil) <add> config, hostConfig, cmd, err := runconfig.Parse(cmd, args) <ide> if err != nil { <ide> return err <ide> } <ide><path>builder/dispatchers.go <ide> func run(b *Builder, args []string, attributes map[string]bool, original string) <ide> runCmd.SetOutput(ioutil.Discard) <ide> runCmd.Usage = nil <ide> <del> config, _, _, err := runconfig.Parse(runCmd, append([]string{b.image}, args...), nil) <add> config, _, _, err := runconfig.Parse(runCmd, append([]string{b.image}, args...)) <ide> if err != nil { <ide> return err <ide> } <ide><path>integration/runtime_test.go <ide> func TestDefaultContainerName(t *testing.T) { <ide> daemon := mkDaemonFromEngine(eng, t) <ide> defer nuke(daemon) <ide> <del> config, _, _, err := parseRun([]string{unitTestImageID, "echo test"}, nil) <add> config, _, _, err := parseRun([]string{unitTestImageID, "echo test"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestRandomContainerName(t *testing.T) { <ide> daemon := mkDaemonFromEngine(eng, t) <ide> defer nuke(daemon) <ide> <del> config, _, _, err := parseRun([]string{GetTestImage(daemon).ID, "echo test"}, nil) <add> config, _, _, err := parseRun([]string{GetTestImage(daemon).ID, "echo test"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestContainerNameValidation(t *testing.T) { <ide> {"abc-123_AAA.1", true}, <ide> {"\000asdf", false}, <ide> } { <del> config, _, _, err := parseRun([]string{unitTestImageID, "echo test"}, nil) <add> config, _, _, err := parseRun([]string{unitTestImageID, "echo test"}) <ide> if err != nil { <ide> if !test.Valid { <ide> continue <ide> func TestLinkChildContainer(t *testing.T) { <ide> daemon := mkDaemonFromEngine(eng, t) <ide> defer nuke(daemon) <ide> <del> config, _, _, err := parseRun([]string{unitTestImageID, "echo test"}, nil) <add> config, _, _, err := parseRun([]string{unitTestImageID, "echo test"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestLinkChildContainer(t *testing.T) { <ide> t.Fatalf("Expect webapp id to match container id: %s != %s", webapp.ID, container.ID) <ide> } <ide> <del> config, _, _, err = parseRun([]string{GetTestImage(daemon).ID, "echo test"}, nil) <add> config, _, _, err = parseRun([]string{GetTestImage(daemon).ID, "echo test"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestGetAllChildren(t *testing.T) { <ide> daemon := mkDaemonFromEngine(eng, t) <ide> defer nuke(daemon) <ide> <del> config, _, _, err := parseRun([]string{unitTestImageID, "echo test"}, nil) <add> config, _, _, err := parseRun([]string{unitTestImageID, "echo test"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestGetAllChildren(t *testing.T) { <ide> t.Fatalf("Expect webapp id to match container id: %s != %s", webapp.ID, container.ID) <ide> } <ide> <del> config, _, _, err = parseRun([]string{unitTestImageID, "echo test"}, nil) <add> config, _, _, err = parseRun([]string{unitTestImageID, "echo test"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide><path>integration/server_test.go <ide> func TestCreateNumberHostname(t *testing.T) { <ide> eng := NewTestEngine(t) <ide> defer mkDaemonFromEngine(eng, t).Nuke() <ide> <del> config, _, _, err := parseRun([]string{"-h", "web.0", unitTestImageID, "echo test"}, nil) <add> config, _, _, err := parseRun([]string{"-h", "web.0", unitTestImageID, "echo test"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestCommit(t *testing.T) { <ide> eng := NewTestEngine(t) <ide> defer mkDaemonFromEngine(eng, t).Nuke() <ide> <del> config, _, _, err := parseRun([]string{unitTestImageID, "/bin/cat"}, nil) <add> config, _, _, err := parseRun([]string{unitTestImageID, "/bin/cat"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestMergeConfigOnCommit(t *testing.T) { <ide> container1, _, _ := mkContainer(runtime, []string{"-e", "FOO=bar", unitTestImageID, "echo test > /tmp/foo"}, t) <ide> defer runtime.Destroy(container1) <ide> <del> config, _, _, err := parseRun([]string{container1.ID, "cat /tmp/foo"}, nil) <add> config, _, _, err := parseRun([]string{container1.ID, "cat /tmp/foo"}) <ide> if err != nil { <ide> t.Error(err) <ide> } <ide> func TestRestartKillWait(t *testing.T) { <ide> runtime := mkDaemonFromEngine(eng, t) <ide> defer runtime.Nuke() <ide> <del> config, hostConfig, _, err := parseRun([]string{"-i", unitTestImageID, "/bin/cat"}, nil) <add> config, hostConfig, _, err := parseRun([]string{"-i", unitTestImageID, "/bin/cat"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestCreateStartRestartStopStartKillRm(t *testing.T) { <ide> eng := NewTestEngine(t) <ide> defer mkDaemonFromEngine(eng, t).Nuke() <ide> <del> config, hostConfig, _, err := parseRun([]string{"-i", unitTestImageID, "/bin/cat"}, nil) <add> config, hostConfig, _, err := parseRun([]string{"-i", unitTestImageID, "/bin/cat"}) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide><path>integration/utils_test.go <ide> import ( <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/engine" <ide> flag "github.com/docker/docker/pkg/mflag" <del> "github.com/docker/docker/pkg/sysinfo" <ide> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/utils" <ide> ) <ide> func readFile(src string, t *testing.T) (content string) { <ide> // The caller is responsible for destroying the container. <ide> // Call t.Fatal() at the first error. <ide> func mkContainer(r *daemon.Daemon, args []string, t *testing.T) (*daemon.Container, *runconfig.HostConfig, error) { <del> config, hc, _, err := parseRun(args, nil) <add> config, hc, _, err := parseRun(args) <ide> defer func() { <ide> if err != nil && t != nil { <ide> t.Fatal(err) <ide> func getImages(eng *engine.Engine, t *testing.T, all bool, filter string) *engin <ide> <ide> } <ide> <del>func parseRun(args []string, sysInfo *sysinfo.SysInfo) (*runconfig.Config, *runconfig.HostConfig, *flag.FlagSet, error) { <add>func parseRun(args []string) (*runconfig.Config, *runconfig.HostConfig, *flag.FlagSet, error) { <ide> cmd := flag.NewFlagSet("run", flag.ContinueOnError) <ide> cmd.SetOutput(ioutil.Discard) <ide> cmd.Usage = nil <del> return runconfig.Parse(cmd, args, sysInfo) <add> return runconfig.Parse(cmd, args) <ide> } <ide><path>runconfig/config_test.go <ide> import ( <ide> ) <ide> <ide> func parse(t *testing.T, args string) (*Config, *HostConfig, error) { <del> config, hostConfig, _, err := parseRun(strings.Split(args+" ubuntu bash", " "), nil) <add> config, hostConfig, _, err := parseRun(strings.Split(args+" ubuntu bash", " ")) <ide> return config, hostConfig, err <ide> } <ide> <ide><path>runconfig/parse.go <ide> import ( <ide> "github.com/docker/docker/opts" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> "github.com/docker/docker/pkg/parsers" <del> "github.com/docker/docker/pkg/sysinfo" <ide> "github.com/docker/docker/pkg/units" <ide> "github.com/docker/docker/utils" <ide> ) <ide> var ( <ide> ErrConflictHostNetworkAndLinks = fmt.Errorf("Conflicting options: --net=host can't be used with links. This would result in undefined behavior.") <ide> ) <ide> <del>func Parse(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Config, *HostConfig, *flag.FlagSet, error) { <add>func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSet, error) { <ide> var ( <ide> // FIXME: use utils.ListOpts for attach and volumes? <ide> flAttach = opts.NewListOpts(opts.ValidateAttach) <ide> func Parse(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Config, <ide> return nil, nil, cmd, err <ide> } <ide> <del> // Check if the kernel supports memory limit cgroup. <del> if sysInfo != nil && *flMemoryString != "" && !sysInfo.MemoryLimit { <del> *flMemoryString = "" <del> } <del> <ide> // Validate input params <ide> if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) { <ide> return nil, nil, cmd, ErrInvalidWorkingDirectory <ide> func Parse(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Config, <ide> RestartPolicy: restartPolicy, <ide> } <ide> <del> if sysInfo != nil && flMemory > 0 && !sysInfo.SwapLimit { <del> //fmt.Fprintf(stdout, "WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n") <del> config.MemorySwap = -1 <del> } <del> <ide> // When allocating stdin in attached mode, close stdin at client disconnect <ide> if config.OpenStdin && config.AttachStdin { <ide> config.StdinOnce = true <ide><path>runconfig/parse_test.go <ide> import ( <ide> <ide> flag "github.com/docker/docker/pkg/mflag" <ide> "github.com/docker/docker/pkg/parsers" <del> "github.com/docker/docker/pkg/sysinfo" <ide> ) <ide> <del>func parseRun(args []string, sysInfo *sysinfo.SysInfo) (*Config, *HostConfig, *flag.FlagSet, error) { <add>func parseRun(args []string) (*Config, *HostConfig, *flag.FlagSet, error) { <ide> cmd := flag.NewFlagSet("run", flag.ContinueOnError) <ide> cmd.SetOutput(ioutil.Discard) <ide> cmd.Usage = nil <del> return Parse(cmd, args, sysInfo) <add> return Parse(cmd, args) <ide> } <ide> <ide> func TestParseLxcConfOpt(t *testing.T) { <ide> func TestParseLxcConfOpt(t *testing.T) { <ide> } <ide> <ide> func TestNetHostname(t *testing.T) { <del> if _, _, _, err := parseRun([]string{"-h=name", "img", "cmd"}, nil); err != nil { <add> if _, _, _, err := parseRun([]string{"-h=name", "img", "cmd"}); err != nil { <ide> t.Fatalf("Unexpected error: %s", err) <ide> } <ide> <del> if _, _, _, err := parseRun([]string{"--net=host", "img", "cmd"}, nil); err != nil { <add> if _, _, _, err := parseRun([]string{"--net=host", "img", "cmd"}); err != nil { <ide> t.Fatalf("Unexpected error: %s", err) <ide> } <ide> <del> if _, _, _, err := parseRun([]string{"-h=name", "--net=bridge", "img", "cmd"}, nil); err != nil { <add> if _, _, _, err := parseRun([]string{"-h=name", "--net=bridge", "img", "cmd"}); err != nil { <ide> t.Fatalf("Unexpected error: %s", err) <ide> } <ide> <del> if _, _, _, err := parseRun([]string{"-h=name", "--net=none", "img", "cmd"}, nil); err != nil { <add> if _, _, _, err := parseRun([]string{"-h=name", "--net=none", "img", "cmd"}); err != nil { <ide> t.Fatalf("Unexpected error: %s", err) <ide> } <ide> <del> if _, _, _, err := parseRun([]string{"-h=name", "--net=host", "img", "cmd"}, nil); err != ErrConflictNetworkHostname { <add> if _, _, _, err := parseRun([]string{"-h=name", "--net=host", "img", "cmd"}); err != ErrConflictNetworkHostname { <ide> t.Fatalf("Expected error ErrConflictNetworkHostname, got: %s", err) <ide> } <ide> <del> if _, _, _, err := parseRun([]string{"-h=name", "--net=container:other", "img", "cmd"}, nil); err != ErrConflictNetworkHostname { <add> if _, _, _, err := parseRun([]string{"-h=name", "--net=container:other", "img", "cmd"}); err != ErrConflictNetworkHostname { <ide> t.Fatalf("Expected error ErrConflictNetworkHostname, got: %s", err) <ide> } <ide> }
8
Ruby
Ruby
improve exit codes
e9158ca6dc99e3bb7ae475bee98153e78cafa2b0
<ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade <ide> <ide> Homebrew.perform_preinstall_checks <ide> <del> outdated = if ARGV.named.empty? <add> if ARGV.named.empty? <ide> require 'cmd/outdated' <del> Homebrew.outdated_brews <add> outdated = Homebrew.outdated_brews <ide> else <del> ARGV.formulae.select do |f| <add> outdated = ARGV.formulae.select do |f| <ide> if f.installed? <ide> onoe "#{f}-#{f.installed_version} already installed" <ide> elsif not f.rack.exist? or f.rack.children.empty? <ide> def upgrade <ide> true <ide> end <ide> end <add> exit 1 if outdated.empty? <ide> end <ide> <ide> # Expand the outdated list to include outdated dependencies then sort and
1
Go
Go
reduce allocations for logfile reader
933a87236f57af13befe3dc83a396cefced23300
<ide><path>daemon/logger/jsonfilelog/jsonlog/jsonlog.go <ide> func (jl *JSONLog) Reset() { <ide> jl.Log = "" <ide> jl.Stream = "" <ide> jl.Created = time.Time{} <del> jl.Attrs = make(map[string]string) <add> for k := range jl.Attrs { <add> delete(jl.Attrs, k) <add> } <ide> } <ide><path>daemon/logger/jsonfilelog/read.go <ide> func decodeLogLine(dec *json.Decoder, l *jsonlog.JSONLog) (*logger.Message, erro <ide> return msg, nil <ide> } <ide> <del>// decodeFunc is used to create a decoder for the log file reader <del>func decodeFunc(rdr io.Reader) func() (*logger.Message, error) { <del> l := &jsonlog.JSONLog{} <del> dec := json.NewDecoder(rdr) <del> return func() (msg *logger.Message, err error) { <del> for retries := 0; retries < maxJSONDecodeRetry; retries++ { <del> msg, err = decodeLogLine(dec, l) <del> if err == nil || err == io.EOF { <del> break <del> } <del> <del> logrus.WithError(err).WithField("retries", retries).Warn("got error while decoding json") <del> // try again, could be due to a an incomplete json object as we read <del> if _, ok := err.(*json.SyntaxError); ok { <del> dec = json.NewDecoder(rdr) <del> continue <del> } <del> <del> // io.ErrUnexpectedEOF is returned from json.Decoder when there is <del> // remaining data in the parser's buffer while an io.EOF occurs. <del> // If the json logger writes a partial json log entry to the disk <del> // while at the same time the decoder tries to decode it, the race condition happens. <del> if err == io.ErrUnexpectedEOF { <del> reader := io.MultiReader(dec.Buffered(), rdr) <del> dec = json.NewDecoder(reader) <del> continue <del> } <add>type decoder struct { <add> rdr io.Reader <add> dec *json.Decoder <add> jl *jsonlog.JSONLog <add>} <add> <add>func (d *decoder) Reset(rdr io.Reader) { <add> d.rdr = rdr <add> d.dec = nil <add> if d.jl != nil { <add> d.jl.Reset() <add> } <add>} <add> <add>func (d *decoder) Close() { <add> d.dec = nil <add> d.rdr = nil <add> d.jl = nil <add>} <add> <add>func (d *decoder) Decode() (msg *logger.Message, err error) { <add> if d.dec == nil { <add> d.dec = json.NewDecoder(d.rdr) <add> } <add> if d.jl == nil { <add> d.jl = &jsonlog.JSONLog{} <add> } <add> for retries := 0; retries < maxJSONDecodeRetry; retries++ { <add> msg, err = decodeLogLine(d.dec, d.jl) <add> if err == nil || err == io.EOF { <add> break <add> } <add> <add> logrus.WithError(err).WithField("retries", retries).Warn("got error while decoding json") <add> // try again, could be due to a an incomplete json object as we read <add> if _, ok := err.(*json.SyntaxError); ok { <add> d.dec = json.NewDecoder(d.rdr) <add> continue <add> } <add> <add> // io.ErrUnexpectedEOF is returned from json.Decoder when there is <add> // remaining data in the parser's buffer while an io.EOF occurs. <add> // If the json logger writes a partial json log entry to the disk <add> // while at the same time the decoder tries to decode it, the race condition happens. <add> if err == io.ErrUnexpectedEOF { <add> d.rdr = io.MultiReader(d.dec.Buffered(), d.rdr) <add> d.dec = json.NewDecoder(d.rdr) <add> continue <ide> } <del> return msg, err <add> } <add> return msg, err <add>} <add> <add>// decodeFunc is used to create a decoder for the log file reader <add>func decodeFunc(rdr io.Reader) loggerutils.Decoder { <add> return &decoder{ <add> rdr: rdr, <add> dec: nil, <add> jl: nil, <ide> } <ide> } <ide> <ide><path>daemon/logger/jsonfilelog/read_test.go <ide> func TestEncodeDecode(t *testing.T) { <ide> assert.Assert(t, marshalMessage(m2, nil, buf)) <ide> assert.Assert(t, marshalMessage(m3, nil, buf)) <ide> <del> decode := decodeFunc(buf) <del> msg, err := decode() <add> dec := decodeFunc(buf) <add> defer dec.Close() <add> <add> msg, err := dec.Decode() <ide> assert.NilError(t, err) <ide> assert.Assert(t, string(msg.Line) == "hello 1\n", string(msg.Line)) <ide> <del> msg, err = decode() <add> msg, err = dec.Decode() <ide> assert.NilError(t, err) <ide> assert.Assert(t, string(msg.Line) == "hello 2\n") <ide> <del> msg, err = decode() <add> msg, err = dec.Decode() <ide> assert.NilError(t, err) <ide> assert.Assert(t, string(msg.Line) == "hello 3\n") <ide> <del> _, err = decode() <add> _, err = dec.Decode() <ide> assert.Assert(t, err == io.EOF) <ide> } <ide><path>daemon/logger/local/local_test.go <ide> package local <ide> <ide> import ( <add> "bytes" <ide> "context" <ide> "encoding/binary" <add> "fmt" <add> "io" <ide> "io/ioutil" <ide> "os" <ide> "path/filepath" <add> "strings" <ide> "testing" <ide> "time" <ide> <del> "bytes" <del> "fmt" <del> <del> "strings" <del> <del> "io" <del> <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/api/types/plugins/logdriver" <ide> "github.com/docker/docker/daemon/logger" <ide><path>daemon/logger/local/read.go <ide> func getTailReader(ctx context.Context, r loggerutils.SizeReaderAt, req int) (io <ide> return io.NewSectionReader(r, offset, size), found, nil <ide> } <ide> <del>func decodeFunc(rdr io.Reader) func() (*logger.Message, error) { <del> proto := &logdriver.LogEntry{} <del> buf := make([]byte, initialBufSize) <del> <del> return func() (*logger.Message, error) { <del> var ( <del> read int <del> err error <del> ) <del> <del> resetProto(proto) <del> <del> for i := 0; i < maxDecodeRetry; i++ { <del> var n int <del> n, err = io.ReadFull(rdr, buf[read:encodeBinaryLen]) <del> if err != nil { <del> if err != io.ErrUnexpectedEOF { <del> return nil, errors.Wrap(err, "error reading log message length") <del> } <del> read += n <del> continue <add>type decoder struct { <add> rdr io.Reader <add> proto *logdriver.LogEntry <add> buf []byte <add>} <add> <add>func (d *decoder) Decode() (*logger.Message, error) { <add> if d.proto == nil { <add> d.proto = &logdriver.LogEntry{} <add> } else { <add> resetProto(d.proto) <add> } <add> if d.buf == nil { <add> d.buf = make([]byte, initialBufSize) <add> } <add> var ( <add> read int <add> err error <add> ) <add> <add> for i := 0; i < maxDecodeRetry; i++ { <add> var n int <add> n, err = io.ReadFull(d.rdr, d.buf[read:encodeBinaryLen]) <add> if err != nil { <add> if err != io.ErrUnexpectedEOF { <add> return nil, errors.Wrap(err, "error reading log message length") <ide> } <ide> read += n <del> break <del> } <del> if err != nil { <del> return nil, errors.Wrapf(err, "could not read log message length: read: %d, expected: %d", read, encodeBinaryLen) <add> continue <ide> } <add> read += n <add> break <add> } <add> if err != nil { <add> return nil, errors.Wrapf(err, "could not read log message length: read: %d, expected: %d", read, encodeBinaryLen) <add> } <ide> <del> msgLen := int(binary.BigEndian.Uint32(buf[:read])) <add> msgLen := int(binary.BigEndian.Uint32(d.buf[:read])) <ide> <del> if len(buf) < msgLen+encodeBinaryLen { <del> buf = make([]byte, msgLen+encodeBinaryLen) <add> if len(d.buf) < msgLen+encodeBinaryLen { <add> d.buf = make([]byte, msgLen+encodeBinaryLen) <add> } else { <add> if msgLen <= initialBufSize { <add> d.buf = d.buf[:initialBufSize] <ide> } else { <del> if msgLen <= initialBufSize { <del> buf = buf[:initialBufSize] <del> } else { <del> buf = buf[:msgLen+encodeBinaryLen] <del> } <add> d.buf = d.buf[:msgLen+encodeBinaryLen] <ide> } <add> } <ide> <del> return decodeLogEntry(rdr, proto, buf, msgLen) <add> return decodeLogEntry(d.rdr, d.proto, d.buf, msgLen) <add>} <add> <add>func (d *decoder) Reset(rdr io.Reader) { <add> d.rdr = rdr <add> if d.proto != nil { <add> resetProto(d.proto) <add> } <add> if d.buf != nil { <add> d.buf = d.buf[:initialBufSize] <ide> } <ide> } <ide> <add>func (d *decoder) Close() { <add> d.buf = d.buf[:0] <add> d.buf = nil <add> if d.proto != nil { <add> resetProto(d.proto) <add> } <add> d.rdr = nil <add>} <add> <add>func decodeFunc(rdr io.Reader) loggerutils.Decoder { <add> return &decoder{rdr: rdr} <add>} <add> <ide> func decodeLogEntry(rdr io.Reader, proto *logdriver.LogEntry, buf []byte, msgLen int) (*logger.Message, error) { <ide> var ( <ide> read int <ide><path>daemon/logger/loggerutils/logfile.go <ide> type LogFile struct { <ide> filesRefCounter refCounter // keep reference-counted of decompressed files <ide> notifyRotate *pubsub.Publisher <ide> marshal logger.MarshalFunc <del> createDecoder makeDecoderFunc <add> createDecoder MakeDecoderFn <ide> getTailReader GetTailReaderFunc <ide> perms os.FileMode <ide> } <ide> <del>type makeDecoderFunc func(rdr io.Reader) func() (*logger.Message, error) <add>// MakeDecoderFn creates a decoder <add>type MakeDecoderFn func(rdr io.Reader) Decoder <add> <add>// Decoder is for reading logs <add>// It is created by the log reader by calling the `MakeDecoderFunc` <add>type Decoder interface { <add> // Reset resets the decoder <add> // Reset is called for certain events, such as log rotations <add> Reset(io.Reader) <add> // Decode decodes the next log messeage from the stream <add> Decode() (*logger.Message, error) <add> // Close signals to the decoder that it can release whatever resources it was using. <add> Close() <add>} <ide> <ide> // SizeReaderAt defines a ReaderAt that also reports its size. <ide> // This is used for tailing log files. <ide> type SizeReaderAt interface { <ide> type GetTailReaderFunc func(ctx context.Context, f SizeReaderAt, nLogLines int) (rdr io.Reader, nLines int, err error) <ide> <ide> // NewLogFile creates new LogFile <del>func NewLogFile(logPath string, capacity int64, maxFiles int, compress bool, marshaller logger.MarshalFunc, decodeFunc makeDecoderFunc, perms os.FileMode, getTailReader GetTailReaderFunc) (*LogFile, error) { <add>func NewLogFile(logPath string, capacity int64, maxFiles int, compress bool, marshaller logger.MarshalFunc, decodeFunc MakeDecoderFn, perms os.FileMode, getTailReader GetTailReaderFunc) (*LogFile, error) { <ide> log, err := openFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, perms) <ide> if err != nil { <ide> return nil, err <ide> func (w *LogFile) ReadLogs(config logger.ReadConfig, watcher *logger.LogWatcher) <ide> } <ide> defer currentFile.Close() <ide> <add> dec := w.createDecoder(nil) <add> defer dec.Close() <add> <ide> currentChunk, err := newSectionReader(currentFile) <ide> if err != nil { <ide> w.mu.RUnlock() <ide> func (w *LogFile) ReadLogs(config logger.ReadConfig, watcher *logger.LogWatcher) <ide> readers = append(readers, currentChunk) <ide> } <ide> <del> tailFiles(readers, watcher, w.createDecoder, w.getTailReader, config) <add> tailFiles(readers, watcher, dec, w.getTailReader, config) <ide> closeFiles() <ide> <ide> w.mu.RLock() <ide> func (w *LogFile) ReadLogs(config logger.ReadConfig, watcher *logger.LogWatcher) <ide> <ide> notifyRotate := w.notifyRotate.Subscribe() <ide> defer w.notifyRotate.Evict(notifyRotate) <del> followLogs(currentFile, watcher, notifyRotate, w.createDecoder, config.Since, config.Until) <add> followLogs(currentFile, watcher, notifyRotate, dec, config.Since, config.Until) <ide> } <ide> <ide> func (w *LogFile) openRotatedFiles(config logger.ReadConfig) (files []*os.File, err error) { <ide> func newSectionReader(f *os.File) (*io.SectionReader, error) { <ide> return io.NewSectionReader(f, 0, size), nil <ide> } <ide> <del>func tailFiles(files []SizeReaderAt, watcher *logger.LogWatcher, createDecoder makeDecoderFunc, getTailReader GetTailReaderFunc, config logger.ReadConfig) { <add>func tailFiles(files []SizeReaderAt, watcher *logger.LogWatcher, dec Decoder, getTailReader GetTailReaderFunc, config logger.ReadConfig) { <ide> nLines := config.Tail <ide> <ide> ctx, cancel := context.WithCancel(context.Background()) <ide> func tailFiles(files []SizeReaderAt, watcher *logger.LogWatcher, createDecoder m <ide> } <ide> <ide> rdr := io.MultiReader(readers...) <del> decodeLogLine := createDecoder(rdr) <add> dec.Reset(rdr) <add> <ide> for { <del> msg, err := decodeLogLine() <add> msg, err := dec.Decode() <ide> if err != nil { <ide> if errors.Cause(err) != io.EOF { <ide> watcher.Err <- err <ide> func tailFiles(files []SizeReaderAt, watcher *logger.LogWatcher, createDecoder m <ide> } <ide> } <ide> <del>func followLogs(f *os.File, logWatcher *logger.LogWatcher, notifyRotate chan interface{}, createDecoder makeDecoderFunc, since, until time.Time) { <del> decodeLogLine := createDecoder(f) <add>func followLogs(f *os.File, logWatcher *logger.LogWatcher, notifyRotate chan interface{}, dec Decoder, since, until time.Time) { <add> dec.Reset(f) <ide> <ide> name := f.Name() <ide> fileWatcher, err := watchFile(name) <ide> func followLogs(f *os.File, logWatcher *logger.LogWatcher, notifyRotate chan int <ide> if err := fileWatcher.Add(name); err != nil { <ide> return err <ide> } <del> decodeLogLine = createDecoder(f) <add> dec.Reset(f) <ide> return nil <ide> } <ide> <ide> func followLogs(f *os.File, logWatcher *logger.LogWatcher, notifyRotate chan int <ide> case e := <-fileWatcher.Events(): <ide> switch e.Op { <ide> case fsnotify.Write: <del> decodeLogLine = createDecoder(f) <add> dec.Reset(f) <ide> return nil <ide> case fsnotify.Rename, fsnotify.Remove: <ide> select { <ide> func followLogs(f *os.File, logWatcher *logger.LogWatcher, notifyRotate chan int <ide> <ide> // main loop <ide> for { <del> msg, err := decodeLogLine() <add> msg, err := dec.Decode() <ide> if err != nil { <ide> if err := handleDecodeErr(err); err != nil { <ide> if err == errDone { <ide><path>daemon/logger/loggerutils/logfile_test.go <ide> import ( <ide> "gotest.tools/v3/assert" <ide> ) <ide> <add>type testDecoder struct { <add> rdr io.Reader <add> scanner *bufio.Scanner <add>} <add> <add>func (d *testDecoder) Decode() (*logger.Message, error) { <add> if d.scanner == nil { <add> d.scanner = bufio.NewScanner(d.rdr) <add> } <add> if !d.scanner.Scan() { <add> return nil, d.scanner.Err() <add> } <add> // some comment <add> return &logger.Message{Line: d.scanner.Bytes(), Timestamp: time.Now()}, nil <add>} <add> <add>func (d *testDecoder) Reset(rdr io.Reader) { <add> d.rdr = rdr <add> d.scanner = bufio.NewScanner(rdr) <add>} <add> <add>func (d *testDecoder) Close() { <add> d.rdr = nil <add> d.scanner = nil <add>} <add> <ide> func TestTailFiles(t *testing.T) { <ide> s1 := strings.NewReader("Hello.\nMy name is Inigo Montoya.\n") <ide> s2 := strings.NewReader("I'm serious.\nDon't call me Shirley!\n") <ide> s3 := strings.NewReader("Roads?\nWhere we're going we don't need roads.\n") <ide> <ide> files := []SizeReaderAt{s1, s2, s3} <ide> watcher := logger.NewLogWatcher() <del> createDecoder := func(r io.Reader) func() (*logger.Message, error) { <del> scanner := bufio.NewScanner(r) <del> return func() (*logger.Message, error) { <del> if !scanner.Scan() { <del> return nil, scanner.Err() <del> } <del> // some comment <del> return &logger.Message{Line: scanner.Bytes(), Timestamp: time.Now()}, nil <del> } <del> } <ide> <ide> tailReader := func(ctx context.Context, r SizeReaderAt, lines int) (io.Reader, int, error) { <ide> return tailfile.NewTailReader(ctx, r, lines) <ide> } <add> dec := &testDecoder{} <ide> <ide> for desc, config := range map[string]logger.ReadConfig{} { <ide> t.Run(desc, func(t *testing.T) { <ide> started := make(chan struct{}) <ide> go func() { <ide> close(started) <del> tailFiles(files, watcher, createDecoder, tailReader, config) <add> tailFiles(files, watcher, dec, tailReader, config) <ide> }() <ide> <-started <ide> }) <ide> func TestTailFiles(t *testing.T) { <ide> started := make(chan struct{}) <ide> go func() { <ide> close(started) <del> tailFiles(files, watcher, createDecoder, tailReader, config) <add> tailFiles(files, watcher, dec, tailReader, config) <ide> }() <ide> <-started <ide> <ide> func TestTailFiles(t *testing.T) { <ide> } <ide> } <ide> <add>type dummyDecoder struct{} <add> <add>func (dummyDecoder) Decode() (*logger.Message, error) { <add> return &logger.Message{}, nil <add>} <add> <add>func (dummyDecoder) Close() {} <add>func (dummyDecoder) Reset(io.Reader) {} <add> <ide> func TestFollowLogsConsumerGone(t *testing.T) { <ide> lw := logger.NewLogWatcher() <ide> <ide> func TestFollowLogsConsumerGone(t *testing.T) { <ide> os.Remove(f.Name()) <ide> }() <ide> <del> makeDecoder := func(rdr io.Reader) func() (*logger.Message, error) { <del> return func() (*logger.Message, error) { <del> return &logger.Message{}, nil <del> } <del> } <add> dec := dummyDecoder{} <ide> <ide> followLogsDone := make(chan struct{}) <ide> var since, until time.Time <ide> go func() { <del> followLogs(f, lw, make(chan interface{}), makeDecoder, since, until) <add> followLogs(f, lw, make(chan interface{}), dec, since, until) <ide> close(followLogsDone) <ide> }() <ide> <ide> func TestFollowLogsConsumerGone(t *testing.T) { <ide> } <ide> } <ide> <add>type dummyWrapper struct { <add> dummyDecoder <add> fn func() error <add>} <add> <add>func (d *dummyWrapper) Decode() (*logger.Message, error) { <add> if err := d.fn(); err != nil { <add> return nil, err <add> } <add> return d.dummyDecoder.Decode() <add>} <add> <ide> func TestFollowLogsProducerGone(t *testing.T) { <ide> lw := logger.NewLogWatcher() <ide> <ide> func TestFollowLogsProducerGone(t *testing.T) { <ide> defer os.Remove(f.Name()) <ide> <ide> var sent, received, closed int <del> makeDecoder := func(rdr io.Reader) func() (*logger.Message, error) { <del> return func() (*logger.Message, error) { <del> if closed == 1 { <del> closed++ <del> t.Logf("logDecode() closed after sending %d messages\n", sent) <del> return nil, io.EOF <del> } else if closed > 1 { <del> t.Fatal("logDecode() called after closing!") <del> return nil, io.EOF <del> } <add> dec := &dummyWrapper{fn: func() error { <add> switch closed { <add> case 0: <ide> sent++ <del> return &logger.Message{}, nil <add> return nil <add> case 1: <add> closed++ <add> t.Logf("logDecode() closed after sending %d messages\n", sent) <add> return io.EOF <add> default: <add> t.Fatal("logDecode() called after closing!") <add> return io.EOF <ide> } <del> } <add> }} <ide> var since, until time.Time <ide> <ide> followLogsDone := make(chan struct{}) <ide> go func() { <del> followLogs(f, lw, make(chan interface{}), makeDecoder, since, until) <add> followLogs(f, lw, make(chan interface{}), dec, since, until) <ide> close(followLogsDone) <ide> }() <ide>
7
Ruby
Ruby
add removed files too
3a0204dd0b1e31f1ebfb34224e1ffb2d3ca84b8d
<ide><path>Library/Homebrew/formula_installer.rb <ide> def git_etc_preinstall <ide> etc.cd do <ide> quiet_system 'git', 'init' unless (etc+'.git').directory? <ide> quiet_system 'git', 'checkout', '-B', "#{f.name}-last" <del> system 'git', 'add', '.' <add> system 'git', 'add', '--all', '.' <ide> system 'git', 'commit', '-m', "#{f.name}-#{f.version}: preinstall" <ide> end <ide> end <ide> def git_etc_postinstall <ide> etc.cd do <ide> FileUtils.cp_r keg_etc_files, etc <ide> <del> system 'git', 'add', '.' <add> system 'git', 'add', '--all', '.' <ide> if quiet_system 'git', 'diff', '--exit-code', default_branch <ide> quiet_system 'git', 'reset', '--hard' <ide> else <ide> if quiet_system 'git', 'rev-parse', 'master' <ide> quiet_system 'git', 'checkout', '-f', 'master' <ide> FileUtils.cp_r keg_etc_files, etc <del> quiet_system 'git', 'add', '.' <add> quiet_system 'git', 'add', '--all', '.' <ide> else <ide> quiet_system 'git', 'checkout', '-b' 'master' <ide> end
1
Text
Text
suggest usage of https instead of git protocol
82f1d3c82a820a8911478e43a663114153c97540
<ide><path>README.md <ide> directory `build/chromium`. <ide> <ide> To get a local copy of the current code, clone it using git: <ide> <del> $ git clone git://github.com/mozilla/pdf.js.git <add> $ git clone https://github.com/mozilla/pdf.js.git <ide> $ cd pdf.js <ide> <ide> Next, install Node.js via the [official package](http://nodejs.org) or via
1
Python
Python
call replace_listener attr if it's available
44a3a585992bcdf7625aacbb3984796f489cb10e
<ide><path>spacy/language.py <ide> def replace_listeners( <ide> util.set_dot_to_object(pipe_cfg, listener_path, tok2vec_cfg["model"]) <ide> # Go over the listener layers and replace them <ide> for listener in pipe_listeners: <del> util.replace_model_node(pipe.model, listener, tok2vec.model.copy()) <add> new_model = tok2vec.model.copy() <add> if "replace_listener" in new_model.attrs: <add> new_model = new_model.attrs["replace_listener"](new_model) <add> util.replace_model_node(pipe.model, listener, new_model) <ide> tok2vec.remove_listener(listener, pipe_name) <ide> <ide> def to_disk(
1
Ruby
Ruby
introduce class_names helper
f24734a7e12a1514d2570f516f2a50aee03d3d44
<ide><path>actionview/lib/action_view/helpers/tag_helper.rb <ide> def boolean_tag_option(key) <ide> def tag_option(key, value, escape) <ide> case value <ide> when Array, Hash <del> value = build_tag_values(value) if key.to_s == "class" <add> value = TagHelper.build_tag_values(value) if key.to_s == "class" <ide> value = escape ? safe_join(value, " ") : value.join(" ") <ide> else <ide> value = escape ? ERB::Util.unwrapped_html_escape(value) : value.to_s <ide> def tag_option(key, value, escape) <ide> end <ide> <ide> private <del> def build_tag_values(*args) <del> tag_values = [] <del> <del> args.each do |tag_value| <del> case tag_value <del> when Hash <del> tag_value.each do |key, val| <del> tag_values << key if val <del> end <del> when Array <del> tag_values << build_tag_values(*tag_value).presence <del> else <del> tag_values << tag_value.to_s if tag_value.present? <del> end <del> end <del> <del> tag_values.compact.flatten <del> end <del> <ide> def prefix_tag_option(prefix, key, value, escape) <ide> key = "#{prefix}-#{key.to_s.dasherize}" <ide> unless value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(BigDecimal) <ide> def content_tag(name, content_or_options_with_block = nil, options = nil, escape <ide> end <ide> end <ide> <add> # Returns a string of class names built from +args+. <add> # <add> # ==== Examples <add> # class_names("foo", "bar") <add> # # => "foo bar" <add> # class_names({ foo: true, bar: false }) <add> # # => "foo" <add> # class_names(nil, false, 123, "", "foo", { bar: true }) <add> # # => "foo bar" <add> def class_names(*args) <add> safe_join(build_tag_values(*args), " ") <add> end <add> <ide> # Returns a CDATA section with the given +content+. CDATA sections <ide> # are used to escape blocks of text containing characters which would <ide> # otherwise be recognized as markup. CDATA sections begin with the string <ide> def escape_once(html) <ide> end <ide> <ide> private <add> def build_tag_values(*args) <add> tag_values = [] <add> <add> args.each do |tag_value| <add> case tag_value <add> when Hash <add> tag_value.each do |key, val| <add> tag_values << key if val <add> end <add> when Array <add> tag_values << build_tag_values(*tag_value).presence <add> else <add> tag_values << tag_value.to_s if tag_value.present? <add> end <add> end <add> <add> tag_values.compact.flatten <add> end <add> module_function :build_tag_values <add> <ide> def tag_builder <ide> @tag_builder ||= TagBuilder.new(self) <ide> end <ide><path>actionview/test/template/tag_helper_test.rb <ide> def test_tag_builder_with_unescaped_conditional_hash_classes <ide> assert_equal "<p class=\"song play>\">limelight</p>", str <ide> end <ide> <add> def test_class_names <add> assert_equal "song play", class_names(["song", { "play": true }]) <add> assert_equal "song", class_names({ "song": true, "play": false }) <add> assert_equal "song", class_names([{ "song": true }, { "play": false }]) <add> assert_equal "song", class_names({ song: true, play: false }) <add> assert_equal "song", class_names([{ song: true }, nil, false]) <add> assert_equal "song", class_names(["song", { foo: false }]) <add> assert_equal "song play", class_names({ "song": true, "play": true }) <add> assert_equal "", class_names({ "song": false, "play": false }) <add> end <add> <ide> def test_content_tag_with_data_attributes <ide> assert_dom_equal '<p data-number="1" data-string="hello" data-string-with-quotes="double&quot;quote&quot;party&quot;">limelight</p>', <ide> content_tag("p", "limelight", data: { number: 1, string: "hello", string_with_quotes: 'double"quote"party"' })
2
Text
Text
specify default encoding in writable.write
9dcde529a47011c67e928a15f900198ba52637ee
<ide><path>doc/api/stream.md <ide> changes: <ide> not operating in object mode, `chunk` must be a string, `Buffer` or <ide> `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value <ide> other than `null`. <del>* `encoding` {string} The encoding, if `chunk` is a string <add>* `encoding` {string} The encoding, if `chunk` is a string. **Default:** `'utf8'` <ide> * `callback` {Function} Callback for when this chunk of data is flushed <ide> * Returns: {boolean} `false` if the stream wishes for the calling code to <ide> wait for the `'drain'` event to be emitted before continuing to write
1
PHP
PHP
fix typehint inconsistency
3c30fddff8fb81c9f31331fc93c7932161447b0a
<ide><path>src/Error/Debugger.php <ide> use InvalidArgumentException; <ide> use ReflectionObject; <ide> use ReflectionProperty; <add>use Throwable; <ide> <ide> /** <ide> * Provide custom logging and error handling. <ide> public static function trace(array $options = []) <ide> * will be displayed. <ide> * - `start` - The stack frame to start generating a trace from. Defaults to 0 <ide> * <del> * @param array|\Exception $backtrace Trace as array or an exception object. <add> * @param array|\Throwable $backtrace Trace as array or an exception object. <ide> * @param array $options Format for outputting stack trace. <ide> * @return string|array Formatted stack trace. <ide> * @link https://book.cakephp.org/3.0/en/development/debugging.html#generating-stack-traces <ide> */ <ide> public static function formatTrace($backtrace, array $options = []) <ide> { <del> if ($backtrace instanceof Exception) { <add> if ($backtrace instanceof Throwable) { <ide> $backtrace = $backtrace->getTrace(); <ide> } <ide> $self = Debugger::getInstance();
1