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 | add test for withbearertoken method | f9112ad06126d8e265df4b66560e92d924c823e8 | <ide><path>tests/Foundation/Testing/Concerns/MakesHttpRequestsTest.php
<ide> public function testFromSetsHeaderAndSession()
<ide> $this->assertSame('previous/url', $this->app['session']->previousUrl());
<ide> }
<ide>
<add> public function testBearerTokenSetsHeader()
<add> {
<add> $this->withBearerToken('foobar');
<add>
<add> $this->assertSame('Bearer foobar', $this->defaultHeaders['Authorization']);
<add> }
<add>
<ide> public function testWithoutAndWithMiddleware()
<ide> {
<ide> $this->assertFalse($this->app->has('middleware.disable')); | 1 |
PHP | PHP | fix regression around empty options | 2266b76230d351b8263fe75c59e1cf835b4428ff | <ide><path>src/View/Widget/SelectBoxWidget.php
<ide> class SelectBoxWidget extends BasicWidget
<ide> * When true, the select element will be disabled.
<ide> * - `val` - Either a string or an array of options to mark as selected.
<ide> * - `empty` - Set to true to add an empty option at the top of the
<del> * option elements. Set to a string to define the display value of the
<del> * empty option.
<add> * option elements. Set to a string to define the display text of the
<add> * empty option. If an array is used the key will set the value of the empty
<add> * option while, the value will set the display text.
<ide> * - `escape` - Set to false to disable HTML escaping.
<ide> *
<ide> * ### Options format
<ide> protected function _renderContent($data)
<ide> }
<ide>
<ide> if (!empty($data['empty'])) {
<del> $value = $data['empty'] === true ? '' : $data['empty'];
<del> $options = ['' => $value] + (array)$options;
<add> $options = $this->_emptyValue($data['empty']) + (array)$options;
<ide> }
<ide> if (empty($options)) {
<ide> return [];
<ide> protected function _renderContent($data)
<ide> return $this->_renderOptions($options, $disabled, $selected, $data['escape']);
<ide> }
<ide>
<add> /**
<add> * Generate the empty value based on the input.
<add> *
<add> * @param string|bool|array $value The provided empty value.
<add> * @return array The generated option key/value.
<add> */
<add> protected function _emptyValue($value)
<add> {
<add> if ($value === true) {
<add> return ['' => ''];
<add> }
<add> if (is_scalar($value)) {
<add> return ['' => $value];
<add> }
<add> if (is_array($value)) {
<add> return $value;
<add> }
<add> return [];
<add> }
<add>
<ide> /**
<ide> * Render the contents of an optgroup element.
<ide> *
<ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php
<ide> public function testRenderSelectedEmpty()
<ide> $this->assertNotRegExp('/value="\d+" selected="selected"/', $result);
<ide> }
<ide>
<add> /**
<add> * Test empty with custom values.
<add> *
<add> * @return void
<add> */
<add> public function testRenderEmptyCustom()
<add> {
<add> $result = $this->DateTime->render([
<add> 'val' => '',
<add> 'year' => [
<add> 'empty' => ['nope' => '(choose one)'],
<add> ]
<add> ], $this->context);
<add> $this->assertContains('<option value="nope">(choose one)</option>', $result);
<add> $this->assertNotContains('<optgroup', $result, 'No optgroups should be present.');
<add> }
<add>
<ide> /**
<ide> * Data provider for testing various acceptable selected values.
<ide> *
<ide><path>tests/TestCase/View/Widget/SelectBoxWidgetTest.php
<ide> public function testRenderEmptyOption()
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<add> $data['empty'] = ['99' => '(choose one)'];
<add> $result = $select->render($data, $this->context);
<add> $expected = [
<add> 'select' => ['name' => 'Birds[name]', 'id' => 'BirdName'],
<add> ['option' => ['value' => '99']], '(choose one)', '/option',
<add> ['option' => ['value' => 'a']], 'Albatross', '/option',
<add> ['option' => ['value' => 'b']], 'Budgie', '/option',
<add> '/select'
<add> ];
<add> $this->assertHtml($expected, $result);
<add>
<ide> $data['empty'] = 'empty';
<ide> $data['val'] = '';
<ide> $result = $select->render($data, $this->context); | 3 |
PHP | PHP | check method existence before calling | 4bb404085113b92221da84c37dac3cd7d6f7ec69 | <ide><path>lib/Cake/Model/Model.php
<ide> protected function _findFirst($state, $query, $results = array()) {
<ide> protected function _findCount($state, $query, $results = array()) {
<ide> if ($state === 'before') {
<ide> $db = $this->getDataSource();
<add> $query['order'] = false;
<add> if (!method_exists($db, 'calculate') || !method_exists($db, 'expression')) {
<add> return $query;
<add> }
<ide> if (empty($query['fields'])) {
<ide> $query['fields'] = $db->calculate($this, 'count');
<ide> } elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
<ide> $query['fields'] = $db->calculate($this, 'count', array(
<ide> $db->expression($query['fields']), 'count'
<ide> ));
<ide> }
<del> $query['order'] = false;
<ide> return $query;
<ide> } elseif ($state === 'after') {
<ide> foreach (array(0, $this->alias) as $key) { | 1 |
Ruby | Ruby | address random `test_or_with_bind_params` failures | aaed081e08c1a04eabeec9fa5edab5e0760f46e2 | <ide><path>activerecord/test/cases/relation/or_test.rb
<ide> def test_or_with_null_right
<ide> end
<ide>
<ide> def test_or_with_bind_params
<del> assert_equal Post.find([1, 2]), Post.where(id: 1).or(Post.where(id: 2)).to_a
<add> assert_equal Post.find([1, 2]).sort_by(&:id), Post.where(id: 1).or(Post.where(id: 2)).sort_by(&:id)
<ide> end
<ide>
<ide> def test_or_with_null_both | 1 |
Text | Text | fix config example [ci skip] | 3ac620f09d2d18dcc4e347f610eeb3aba32875a0 | <ide><path>website/docs/usage/training.md
<ide> tabular results to a file:
<ide> > ### config.cfg (excerpt)
<ide> > [training.logger]
<ide> > @loggers = "my_custom_logger.v1"
<del>> file_path = "my_file.tab"
<add>> log_path = "my_file.tab"
<ide> > ```
<ide>
<ide> ```python | 1 |
Javascript | Javascript | use object.create(null) for dictionary object | 9d0396cd638983d207cb7bb0a5a21220a86ec1de | <ide><path>lib/util.js
<ide> function stylizeNoColor(str, styleType) {
<ide>
<ide>
<ide> function arrayToHash(array) {
<del> var hash = {};
<add> var hash = Object.create(null);
<ide>
<del> array.forEach(function(val, idx) {
<add> array.forEach(function(val) {
<ide> hash[val] = true;
<ide> });
<ide> | 1 |
Text | Text | fix double-spacing after full stop issues | 6a200cb88adaf5dc3850569b7121f79956bfc1fd | <ide><path>docs/Formula-Cookbook.md
<ide> Homebrew provides two formula DSL methods for launchd plist files:
<ide>
<ide> Homebrew has multiple levels of environment variable filtering which affects variables available to formulae.
<ide>
<del>Firstly, the overall environment in which Homebrew runs is filtered to avoid environment contamination breaking from-source builds (<https://github.com/Homebrew/brew/issues/932>). In particular, this process filters all but the given whitelisted variables, but allows environment variables prefixed with `HOMEBREW_`. The specific implementation can be seen in [`bin/brew`](https://github.com/Homebrew/brew/blob/master/bin/brew).
<add>Firstly, the overall environment in which Homebrew runs is filtered to avoid environment contamination breaking from-source builds (<https://github.com/Homebrew/brew/issues/932>). In particular, this process filters all but the given whitelisted variables, but allows environment variables prefixed with `HOMEBREW_`. The specific implementation can be seen in [`bin/brew`](https://github.com/Homebrew/brew/blob/master/bin/brew).
<ide>
<del>The second level of filtering removes sensitive environment variables (such as credentials like keys, passwords or tokens) to avoid malicious subprocesses obtaining them (<https://github.com/Homebrew/brew/pull/2524>). This has the effect of preventing any such variables from reaching a formula's Ruby code as they are filtered before it is called. The specific implementation can be seen in the [`ENV.clear_sensitive_environment!` method](https://github.com/Homebrew/brew/blob/master/Library/Homebrew/extend/ENV.rb).
<add>The second level of filtering removes sensitive environment variables (such as credentials like keys, passwords or tokens) to avoid malicious subprocesses obtaining them (<https://github.com/Homebrew/brew/pull/2524>). This has the effect of preventing any such variables from reaching a formula's Ruby code as they are filtered before it is called. The specific implementation can be seen in the [`ENV.clear_sensitive_environment!` method](https://github.com/Homebrew/brew/blob/master/Library/Homebrew/extend/ENV.rb).
<ide>
<ide> In summary, environment variables used by a formula need to conform to these filtering rules in order to be available.
<ide> | 1 |
Ruby | Ruby | add basic tests to the configurator#build (#28) | 18720bc8fbf269184ac6f183a82ed045cc0c1965 | <ide><path>test/service/configurator_test.rb
<add>require "service/shared_service_tests"
<add>
<add>class ActiveStorage::Service::ConfiguratorTest < ActiveSupport::TestCase
<add> test "builds correct service instance based on service name" do
<add> service = ActiveStorage::Service::Configurator.build(:s3, SERVICE_CONFIGURATIONS)
<add> assert_instance_of ActiveStorage::Service::S3Service, service
<add> end
<add>
<add> test "raises error when passing non-existent service name" do
<add> assert_raise RuntimeError do
<add> ActiveStorage::Service::Configurator.build(:bigfoot, SERVICE_CONFIGURATIONS)
<add> end
<add> end
<add>end
<add> | 1 |
Javascript | Javascript | remove extra parenthesis | adfb21aaf9149aecc0aef2befdeb147da3c62e5e | <ide><path>server/boot/about.js
<ide> export default function about(app) {
<ide> daysRunning,
<ide> title: dedent`
<ide> About our Open Source Community, our social media presence,
<del> and how to contact us`.split('\n').join(' '),
<add> and how to contact us
<add> `.split('\n').join(' '),
<ide> globalCompletedCount: numberWithCommas(
<del> 5612952 + (Math.floor((Date.now() - 1446268581061) / 1800)
<add> 5612952 + (Math.floor((Date.now() - 1446268581061) / 1800))
<ide> ),
<ide> globalPledgedAmount: numberWithCommas(
<ide> 28000.00 +
<del> (Math.floor(
<del> (Date.now() - 1456207176902) /
<del> (2629746 / 2000)
<del> ) * 8.30)
<add> (
<add> Math.floor((Date.now() - 1456207176902) / (2629746 / 2000)) *
<add> 8.30
<ide> )
<ide> )
<ide> }); | 1 |
Text | Text | capitalize first letter (for consistency) | d8f3567d7ef3022b35456d35c4b381cdd338e2a7 | <ide><path>docs/introduction/Ecosystem.md
<ide> On this page we will only feature a few of them that the Redux maintainers have
<ide>
<ide> * [redux-optimist](https://github.com/ForbesLindesay/redux-optimist) — Optimistically apply actions that can be later commited or reverted
<ide> * [redux-undo](https://github.com/omnidan/redux-undo) — Effortless undo/redo and action history for your reducers
<del>* [redux-ignore](https://github.com/omnidan/redux-ignore) — ignore redux actions by array or filter function
<del>* [redux-recycle](https://github.com/omnidan/redux-recycle) — reset the redux state on certain actions
<add>* [redux-ignore](https://github.com/omnidan/redux-ignore) — Ignore redux actions by array or filter function
<add>* [redux-recycle](https://github.com/omnidan/redux-recycle) — Reset the redux state on certain actions
<ide>
<ide> ## Utilities
<ide> | 1 |
Ruby | Ruby | remove unneded argument | de3bf3ec3d7dfa81870aca5b8ed8c237e093fe9f | <ide><path>activerecord/lib/active_record/relation.rb
<ide> class Relation
<ide> alias :model :klass
<ide> alias :loaded? :loaded
<ide>
<del> def initialize(klass, table, values = {}, offsets = {})
<add> def initialize(klass, table, values = {})
<ide> @klass = klass
<ide> @table = table
<ide> @values = values
<del> @offsets = offsets
<add> @offsets = {}
<ide> @loaded = false
<ide> end
<ide> | 1 |
Javascript | Javascript | add tests for press responder event module | f243deab8286b9c51f44e47926c1ba0ccb53449a | <ide><path>packages/react-events/src/Press.js
<ide> function dispatchPressStartEvents(
<ide> if ((props.onLongPress || props.onLongPressChange) && !state.isLongPressed) {
<ide> const delayLongPress = calculateDelayMS(
<ide> props.delayLongPress,
<del> 0,
<add> 10,
<ide> DEFAULT_LONG_PRESS_DELAY_MS,
<ide> );
<ide>
<ide> state.longPressTimeout = setTimeout(() => {
<ide> state.isLongPressed = true;
<ide> state.longPressTimeout = null;
<ide>
<del> if (
<del> props.onPressChange &&
<del> props.onLongPressShouldCancelPress &&
<del> props.onLongPressShouldCancelPress()
<del> ) {
<del> dispatchPressChangeEvent(false);
<del> }
<del>
<ide> if (props.onLongPress) {
<ide> const longPressEventListener = e => {
<ide> props.onLongPress(e);
<ide><path>packages/react-events/src/__tests__/Press-test.internal.js
<ide> let ReactFeatureFlags;
<ide> let ReactDOM;
<ide> let Press;
<ide>
<del>describe('Press event responder', () => {
<add>const DEFAULT_LONG_PRESS_DELAY = 1000;
<add>
<add>const createPointerEvent = type => {
<add> const event = document.createEvent('Event');
<add> event.initEvent(type, true, true);
<add> return event;
<add>};
<add>
<add>const createKeyboardEvent = (type, data) => {
<add> return new KeyboardEvent(type, {
<add> bubbles: true,
<add> cancelable: true,
<add> ...data,
<add> });
<add>};
<add>
<add>describe('Event responder: Press', () => {
<ide> let container;
<ide>
<ide> beforeEach(() => {
<ide> describe('Press event responder', () => {
<ide> container = null;
<ide> });
<ide>
<del> it('should support onPress', () => {
<del> let buttonRef = React.createRef();
<del> let events = [];
<del>
<del> function handleOnPress1() {
<del> events.push('press 1');
<del> }
<del>
<del> function handleOnPress2() {
<del> events.push('press 2');
<del> }
<del>
<del> function handleOnMouseDown() {
<del> events.push('mousedown');
<del> }
<del>
<del> function handleKeyDown() {
<del> events.push('keydown');
<del> }
<del>
<del> function Component() {
<del> return (
<del> <Press onPress={handleOnPress1}>
<del> <Press onPress={handleOnPress2}>
<del> <button
<del> ref={buttonRef}
<del> onMouseDown={handleOnMouseDown}
<del> onKeyDown={handleKeyDown}>
<del> Press me!
<del> </button>
<del> </Press>
<add> describe('onPressStart', () => {
<add> let onPressStart, ref;
<add>
<add> beforeEach(() => {
<add> onPressStart = jest.fn();
<add> ref = React.createRef();
<add> const element = (
<add> <Press onPressStart={onPressStart}>
<add> <div ref={ref} />
<ide> </Press>
<ide> );
<del> }
<add> ReactDOM.render(element, container);
<add> });
<ide>
<del> ReactDOM.render(<Component />, container);
<add> it('is called after "pointerdown" event', () => {
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> expect(onPressStart).toHaveBeenCalledTimes(1);
<add> });
<ide>
<del> const mouseDownEvent = document.createEvent('Event');
<del> mouseDownEvent.initEvent('mousedown', true, true);
<del> buttonRef.current.dispatchEvent(mouseDownEvent);
<add> it('ignores emulated "mousedown" event', () => {
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> ref.current.dispatchEvent(createPointerEvent('mousedown'));
<add> expect(onPressStart).toHaveBeenCalledTimes(1);
<add> });
<ide>
<del> const mouseUpEvent = document.createEvent('Event');
<del> mouseUpEvent.initEvent('mouseup', true, true);
<del> buttonRef.current.dispatchEvent(mouseUpEvent);
<add> // No PointerEvent fallbacks
<add> it('is called after "mousedown" event', () => {
<add> ref.current.dispatchEvent(createPointerEvent('mousedown'));
<add> expect(onPressStart).toHaveBeenCalledTimes(1);
<add> });
<add> it('is called after "touchstart" event', () => {
<add> ref.current.dispatchEvent(createPointerEvent('touchstart'));
<add> expect(onPressStart).toHaveBeenCalledTimes(1);
<add> });
<add>
<add> // TODO: complete delayPressStart tests
<add> // describe('delayPressStart', () => {});
<add> });
<ide>
<del> expect(events).toEqual(['mousedown', 'press 2', 'press 1']);
<add> describe('onPressEnd', () => {
<add> let onPressEnd, ref;
<add>
<add> beforeEach(() => {
<add> onPressEnd = jest.fn();
<add> ref = React.createRef();
<add> const element = (
<add> <Press onPressEnd={onPressEnd}>
<add> <div ref={ref} />
<add> </Press>
<add> );
<add> ReactDOM.render(element, container);
<add> });
<add>
<add> it('is called after "pointerup" event', () => {
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<add> expect(onPressEnd).toHaveBeenCalledTimes(1);
<add> });
<ide>
<del> events = [];
<del> const keyDownEvent = new KeyboardEvent('keydown', {
<del> key: 'Enter',
<del> bubbles: true,
<del> cancelable: true,
<add> it('ignores emulated "mouseup" event', () => {
<add> ref.current.dispatchEvent(createPointerEvent('touchstart'));
<add> ref.current.dispatchEvent(createPointerEvent('touchend'));
<add> ref.current.dispatchEvent(createPointerEvent('mouseup'));
<add> expect(onPressEnd).toHaveBeenCalledTimes(1);
<add> });
<add>
<add> // No PointerEvent fallbacks
<add> it('is called after "mouseup" event', () => {
<add> ref.current.dispatchEvent(createPointerEvent('mousedown'));
<add> ref.current.dispatchEvent(createPointerEvent('mouseup'));
<add> expect(onPressEnd).toHaveBeenCalledTimes(1);
<add> });
<add>
<add> it('is called after "touchend" event', () => {
<add> ref.current.dispatchEvent(createPointerEvent('touchstart'));
<add> ref.current.dispatchEvent(createPointerEvent('touchend'));
<add> expect(onPressEnd).toHaveBeenCalledTimes(1);
<add> });
<add>
<add> // TODO: complete delayPressStart tests
<add> // describe('delayPressStart', () => {});
<add> });
<add>
<add> describe('onPressChange', () => {
<add> let onPressChange, ref;
<add>
<add> beforeEach(() => {
<add> onPressChange = jest.fn();
<add> ref = React.createRef();
<add> const element = (
<add> <Press onPressChange={onPressChange}>
<add> <div ref={ref} />
<add> </Press>
<add> );
<add> ReactDOM.render(element, container);
<add> });
<add>
<add> it('is called after "pointerdown" and "pointerup" events', () => {
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> expect(onPressChange).toHaveBeenCalledTimes(1);
<add> expect(onPressChange).toHaveBeenCalledWith(true);
<add> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<add> expect(onPressChange).toHaveBeenCalledTimes(2);
<add> expect(onPressChange).toHaveBeenCalledWith(false);
<add> });
<add> });
<add>
<add> describe('onPress', () => {
<add> let onPress, ref;
<add>
<add> beforeEach(() => {
<add> onPress = jest.fn();
<add> ref = React.createRef();
<add> const element = (
<add> <Press onPress={onPress}>
<add> <div ref={ref} />
<add> </Press>
<add> );
<add> ReactDOM.render(element, container);
<ide> });
<del> buttonRef.current.dispatchEvent(keyDownEvent);
<ide>
<del> // press 1 should not occur as press 2 will preventDefault
<del> expect(events).toEqual(['keydown', 'press 2']);
<add> it('is called after "pointerup" event', () => {
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<add> expect(onPress).toHaveBeenCalledTimes(1);
<add> });
<ide> });
<ide>
<del> it('should support onPressStart and onPressEnd', () => {
<del> let divRef = React.createRef();
<del> let events = [];
<add> describe('onLongPress', () => {
<add> let onLongPress, ref;
<add>
<add> beforeEach(() => {
<add> onLongPress = jest.fn();
<add> ref = React.createRef();
<add> const element = (
<add> <Press onLongPress={onLongPress}>
<add> <div ref={ref} />
<add> </Press>
<add> );
<add> ReactDOM.render(element, container);
<add> });
<add>
<add> it('is called if press lasts default delay', () => {
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> jest.advanceTimersByTime(DEFAULT_LONG_PRESS_DELAY - 1);
<add> expect(onLongPress).not.toBeCalled();
<add> jest.advanceTimersByTime(1);
<add> expect(onLongPress).toHaveBeenCalledTimes(1);
<add> });
<ide>
<del> function handleOnPressStart() {
<del> events.push('onPressStart');
<del> }
<add> it('is not called if press is released before delay', () => {
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> jest.advanceTimersByTime(DEFAULT_LONG_PRESS_DELAY - 1);
<add> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<add> jest.advanceTimersByTime(1);
<add> expect(onLongPress).not.toBeCalled();
<add> });
<ide>
<del> function handleOnPressEnd() {
<del> events.push('onPressEnd');
<del> }
<add> describe('delayLongPress', () => {
<add> it('can be configured', () => {
<add> const element = (
<add> <Press delayLongPress={2000} onLongPress={onLongPress}>
<add> <div ref={ref} />
<add> </Press>
<add> );
<add> ReactDOM.render(element, container);
<add>
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> jest.advanceTimersByTime(1999);
<add> expect(onLongPress).not.toBeCalled();
<add> jest.advanceTimersByTime(1);
<add> expect(onLongPress).toHaveBeenCalledTimes(1);
<add> });
<add>
<add> it('uses 10ms minimum delay length', () => {
<add> const element = (
<add> <Press delayLongPress={0} onLongPress={onLongPress}>
<add> <div ref={ref} />
<add> </Press>
<add> );
<add> ReactDOM.render(element, container);
<add>
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> jest.advanceTimersByTime(9);
<add> expect(onLongPress).not.toBeCalled();
<add> jest.advanceTimersByTime(1);
<add> expect(onLongPress).toHaveBeenCalledTimes(1);
<add> });
<add>
<add> /*
<add> it('compounds with "delayPressStart"', () => {
<add> const delayPressStart = 100;
<add> const element = (
<add> <Press delayPressStart={delayPressStart} onLongPress={onLongPress}>
<add> <div ref={ref} />
<add> </Press>
<add> );
<add> ReactDOM.render(element, container);
<add>
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> jest.advanceTimersByTime(delayPressStart + DEFAULT_LONG_PRESS_DELAY - 1);
<add> expect(onLongPress).not.toBeCalled();
<add> jest.advanceTimersByTime(1);
<add> expect(onLongPress).toHaveBeenCalledTimes(1);
<add> });
<add> */
<add> });
<add> });
<ide>
<del> function Component() {
<del> return (
<del> <Press onPressStart={handleOnPressStart} onPressEnd={handleOnPressEnd}>
<del> <div ref={divRef}>Press me!</div>
<add> describe('onLongPressChange', () => {
<add> it('is called when long press state changes', () => {
<add> const onLongPressChange = jest.fn();
<add> const ref = React.createRef();
<add> const element = (
<add> <Press onLongPressChange={onLongPressChange}>
<add> <div ref={ref} />
<ide> </Press>
<ide> );
<del> }
<add> ReactDOM.render(element, container);
<ide>
<del> ReactDOM.render(<Component />, container);
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> jest.advanceTimersByTime(DEFAULT_LONG_PRESS_DELAY);
<add> expect(onLongPressChange).toHaveBeenCalledTimes(1);
<add> expect(onLongPressChange).toHaveBeenCalledWith(true);
<add> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<add> expect(onLongPressChange).toHaveBeenCalledTimes(2);
<add> expect(onLongPressChange).toHaveBeenCalledWith(false);
<add> });
<add> });
<add>
<add> describe('onLongPressShouldCancelPress', () => {
<add> it('if true it cancels "onPress"', () => {
<add> const onPress = jest.fn();
<add> const onPressChange = jest.fn();
<add> const ref = React.createRef();
<add> const element = (
<add> <Press
<add> onLongPress={() => {}}
<add> onLongPressShouldCancelPress={() => true}
<add> onPressChange={onPressChange}
<add> onPress={onPress}>
<add> <div ref={ref} />
<add> </Press>
<add> );
<add> ReactDOM.render(element, container);
<add>
<add> // NOTE: onPressChange behavior should not be affected
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> expect(onPressChange).toHaveBeenCalledTimes(1);
<add> jest.advanceTimersByTime(DEFAULT_LONG_PRESS_DELAY);
<add> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<add> expect(onPress).not.toBeCalled();
<add> expect(onPressChange).toHaveBeenCalledTimes(2);
<add> });
<add> });
<add>
<add> // TODO
<add> //describe('`onPress*` with movement', () => {
<add> //describe('within bounds of hit rect', () => {
<add> /** ┌──────────────────┐
<add> * │ ┌────────────┐ │
<add> * │ │ VisualRect │ │
<add> * │ └────────────┘ │
<add> * │ HitRect X │ <= Move to X and release
<add> * └──────────────────┘
<add> */
<ide>
<del> const pointerEnterEvent = document.createEvent('Event');
<del> pointerEnterEvent.initEvent('pointerdown', true, true);
<del> divRef.current.dispatchEvent(pointerEnterEvent);
<add> //it('"onPress*" events are called when no delay', () => {});
<add> //it('"onPress*" events are called after a delay', () => {});
<add> //});
<ide>
<del> const pointerLeaveEvent = document.createEvent('Event');
<del> pointerLeaveEvent.initEvent('pointerup', true, true);
<del> divRef.current.dispatchEvent(pointerLeaveEvent);
<add> //describe('beyond bounds of hit rect', () => {
<add> /** ┌──────────────────┐
<add> * │ ┌────────────┐ │
<add> * │ │ VisualRect │ │
<add> * │ └────────────┘ │
<add> * │ HitRect │
<add> * └──────────────────┘
<add> * X <= Move to X and release
<add> */
<ide>
<del> expect(events).toEqual(['onPressStart', 'onPressEnd']);
<add> //it('"onPress" only is not called when no delay', () => {});
<add> //it('"onPress*" events are not called after a delay', () => {});
<add> //it('"onPress*" events are called when press is released before measure completes', () => {});
<add> //});
<add> //});
<add>
<add> describe('nested responders', () => {
<add> it('dispatch events in the correct order', () => {
<add> let events = [];
<add> const ref = React.createRef();
<add> const createEventHandler = msg => () => {
<add> events.push(msg);
<add> };
<add>
<add> const element = (
<add> <Press
<add> onPress={createEventHandler('outer: onPress')}
<add> onPressChange={createEventHandler('outer: onPressChange')}
<add> onPressStart={createEventHandler('outer: onPressStart')}
<add> onPressEnd={createEventHandler('outer: onPressEnd')}>
<add> <Press
<add> onPress={createEventHandler('inner: onPress')}
<add> onPressChange={createEventHandler('inner: onPressChange')}
<add> onPressStart={createEventHandler('inner: onPressStart')}
<add> onPressEnd={createEventHandler('inner: onPressEnd')}>
<add> <div
<add> ref={ref}
<add> onPointerDown={createEventHandler('pointerdown')}
<add> onPointerUp={createEventHandler('pointerup')}
<add> onKeyDown={createEventHandler('keydown')}
<add> onKeyUp={createEventHandler('keyup')}
<add> />
<add> </Press>
<add> </Press>
<add> );
<add>
<add> ReactDOM.render(element, container);
<add>
<add> ref.current.dispatchEvent(createPointerEvent('pointerdown'));
<add> ref.current.dispatchEvent(createPointerEvent('pointerup'));
<add> expect(events).toEqual([
<add> 'pointerdown',
<add> 'inner: onPressStart',
<add> 'inner: onPressChange',
<add> 'outer: onPressStart',
<add> 'outer: onPressChange',
<add> 'pointerup',
<add> 'inner: onPressEnd',
<add> 'inner: onPressChange',
<add> 'inner: onPress',
<add> 'outer: onPressEnd',
<add> 'outer: onPressChange',
<add> 'outer: onPress',
<add> ]);
<add>
<add> events = [];
<add> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'}));
<add> // Outer press should not occur as inner press will preventDefault
<add> expect(events).toEqual(['keydown', 'inner: onPress']);
<add> });
<ide> });
<ide> }); | 2 |
Text | Text | add missing changelog authors | 545857125421f2c579c8dd7728d5ae26af720826 | <ide><path>activesupport/CHANGELOG.md
<ide>
<ide> * Deprecate `Notification::Event`'s `#children` and `#parent_of?`
<ide>
<add> *John Hawthorn*
<add>
<ide> * Change default serialization format of `MessageEncryptor` from `Marshal` to `JSON` for Rails 7.1.
<ide>
<ide> Existing apps are provided with an upgrade path to migrate to `JSON` as described in `guides/source/upgrading_ruby_on_rails.md`
<ide>
<ide> * Improve `File.atomic_write` error handling
<ide>
<add> *Daniel Pepper*
<add>
<ide> * Fix `Class#descendants` and `DescendantsTracker#descendants` compatibility with Ruby 3.1.
<ide>
<ide> [The native `Class#descendants` was reverted prior to Ruby 3.1 release](https://bugs.ruby-lang.org/issues/14394#note-33), | 1 |
Text | Text | create model card for lordtt13/covid-scibert | e10fb9cbe6117deda7aa7944276256a2954d3fd7 | <ide><path>model_cards/lordtt13/COVID-SciBERT/README.md
<add>---
<add>language: en
<add>inference: false
<add>---
<add>
<add>## COVID-SciBERT: A small language modelling expansion of SciBERT, a BERT model trained on scientific text.
<add>
<add>### Details of SciBERT
<add>
<add>The **SciBERT** model was presented in [SciBERT: A Pretrained Language Model for Scientific Text](https://arxiv.org/abs/1903.10676) by *Iz Beltagy, Kyle Lo, Arman Cohan* and here is the abstract:
<add>
<add>Obtaining large-scale annotated data for NLP tasks in the scientific domain is challenging and expensive. We release SciBERT, a pretrained language model based on BERT (Devlin et al., 2018) to address the lack of high-quality, large-scale labeled scientific data. SciBERT leverages unsupervised pretraining on a large multi-domain corpus of scientific publications to improve performance on downstream scientific NLP tasks. We evaluate on a suite of tasks including sequence tagging, sentence classification and dependency parsing, with datasets from a variety of scientific domains. We demonstrate statistically significant improvements over BERT and achieve new state-of-the-art results on several of these tasks.
<add>
<add>### Details of the downstream task (Language Modeling) - Dataset 📚
<add>
<add>There are actually two datasets that have been used here:
<add>
<add>- The original SciBERT model is trained on papers from the corpus of [semanticscholar.org](semanticscholar.org). Corpus size is 1.14M papers, 3.1B tokens. They used the full text of the papers in training, not just abstracts. SciBERT has its own vocabulary (scivocab) that's built to best match the training corpus.
<add>
<add>- The expansion is done using the papers present in the [COVID-19 Open Research Dataset Challenge (CORD-19)](https://www.kaggle.com/allen-institute-for-ai/CORD-19-research-challenge). Only the abstracts have been used and vocabulary was pruned and added to the existing scivocab. In response to the COVID-19 pandemic, the White House and a coalition of leading research groups have prepared the COVID-19 Open Research Dataset (CORD-19). CORD-19 is a resource of over 200,000 scholarly articles, including over 100,000 with full text, about COVID-19, SARS-CoV-2, and related coronaviruses. This freely available dataset is provided to the global research community to apply recent advances in natural language processing and other AI techniques to generate new insights in support of the ongoing fight against this infectious disease. There is a growing urgency for these approaches because of the rapid acceleration in new coronavirus literature, making it difficult for the medical research community to keep up.
<add>
<add>### Model training
<add>
<add>The training script is present [here](https://github.com/lordtt13/word-embeddings/blob/master/COVID-19%20Research%20Data/COVID-SciBERT.ipynb).
<add>
<add>### Pipelining the Model
<add>
<add>```python
<add>import transformers
<add>
<add>model = transformers.AutoModelWithLMHead.from_pretrained('lordtt13/COVID-SciBERT')
<add>
<add>tokenizer = transformers.AutoTokenizer.from_pretrained('lordtt13/COVID-SciBERT')
<add>
<add>nlp_fill = transformers.pipeline('fill-mask', model = model, tokenizer = tokenizer)
<add>nlp_fill('Coronavirus or COVID-19 can be prevented by a' + nlp_fill.tokenizer.mask_token)
<add>
<add># Output:
<add># [{'sequence': '[CLS] coronavirus or covid - 19 can be prevented by a combination [SEP]',
<add># 'score': 0.1719885915517807,
<add># 'token': 2702},
<add># {'sequence': '[CLS] coronavirus or covid - 19 can be prevented by a simple [SEP]',
<add># 'score': 0.054218728095293045,
<add># 'token': 2177},
<add># {'sequence': '[CLS] coronavirus or covid - 19 can be prevented by a novel [SEP]',
<add># 'score': 0.043364267796278,
<add># 'token': 3045},
<add># {'sequence': '[CLS] coronavirus or covid - 19 can be prevented by a high [SEP]',
<add># 'score': 0.03732519596815109,
<add># 'token': 597},
<add># {'sequence': '[CLS] coronavirus or covid - 19 can be prevented by a vaccine [SEP]',
<add># 'score': 0.021863549947738647,
<add># 'token': 7039}]
<add>```
<add>
<add>> Created by [Tanmay Thakur](https://github.com/lordtt13) | [LinkedIn](https://www.linkedin.com/in/tanmay-thakur-6bb5a9154/)
<add>
<add>> PS: Still looking for more resources to expand my expansion! | 1 |
Text | Text | add v3.19.0-beta.4 to changelog | 0317ecf1af0f7729eafb6be590e1b0100da08529 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.19.0-beta.4 (May 12, 2020)
<add>
<add>- [#18958](https://github.com/emberjs/ember.js/pull/18958) [BUGFIX] Ensure AST transforms using `in-element` work properly.
<add>- [#18960](https://github.com/emberjs/ember.js/pull/18960) [BUGFIX] More assertions for Application lifecycle methods
<add>
<ide> ### v3.19-0.beta.3 (May 4, 2020)
<ide>
<ide> - [#18941](https://github.com/emberjs/ember.js/pull/18941) [BUGFIX] Update rendering engine to latest version. | 1 |
PHP | PHP | fix magic __isset() | 7badb1d252b9604cbf67d7ed81d191d87116289f | <ide><path>lib/Cake/Test/Case/View/ViewTest.php
<ide> public function testHelperCallbackTriggering() {
<ide> $this->attributeEqualTo('_subject', $View)
<ide> )
<ide> );
<del>
<add>
<ide> $View->Helpers->expects($this->at(4))->method('trigger')
<ide> ->with(
<ide> $this->logicalAnd(
<ide> public function testPropertySetting() {
<ide> $this->assertFalse(isset($this->View->pageTitle));
<ide> $this->View->pageTitle = 'test';
<ide> $this->assertTrue(isset($this->View->pageTitle));
<add> $this->assertTrue(!empty($this->View->pageTitle));
<ide> $this->assertEquals('test', $this->View->pageTitle);
<ide> }
<add>
<add>/**
<add> * Test that setting arbitrary properties still works.
<add> *
<add> * @return void
<add> */
<add> public function testPropertySettingMagicGet() {
<add> $this->assertFalse(isset($this->View->action));
<add> $this->View->request->params['action'] = 'login';
<add> $this->assertEquals('login', $this->View->action);
<add> $this->assertTrue(isset($this->View->action));
<add> $this->assertTrue(!empty($this->View->action));
<add> }
<ide> }
<ide><path>lib/Cake/View/View.php
<ide> public function __get($name) {
<ide> case 'data':
<ide> return $this->request->{$name};
<ide> case 'action':
<del> return isset($this->request->params['action']) ? $this->request->params['action'] : '';
<add> return $this->request->params['action'];
<ide> case 'params':
<ide> return $this->request;
<ide> case 'output':
<ide> public function __set($name, $value) {
<ide> * @return boolean
<ide> */
<ide> public function __isset($name) {
<del> return isset($this->{$name});
<add> if (isset($this->{$name})) {
<add> return true;
<add> }
<add> $magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
<add> if (in_array($name, $magicGet)) {
<add> return $this->__get($name) !== null;
<add> }
<add> return false;
<ide> }
<ide>
<ide> /** | 2 |
Ruby | Ruby | remove unused methods | 9ff5fdeda99b3d8c5148d4c40956842518d1c788 | <ide><path>activerecord/lib/active_record/reflection.rb
<ide> def through_conditions
<ide> [Array.wrap(options[:conditions])]
<ide> end
<ide>
<del> def through_reflection_primary_key_name
<del> end
<del>
<ide> def source_reflection
<ide> nil
<ide> end
<ide> def check_validity!
<ide> check_validity_of_inverse!
<ide> end
<ide>
<del> def through_reflection_primary_key
<del> through_reflection.belongs_to? ? through_reflection.klass.primary_key : through_reflection.primary_key_name
<del> end
<del>
<del> def through_reflection_primary_key_name
<del> through_reflection.primary_key_name if through_reflection.belongs_to?
<del> end
<del>
<ide> private
<ide> def derive_class_name
<ide> # get the class_name of the belongs_to association of the through reflection | 1 |
Text | Text | add clarification for exception behaviour | b406c9c4e95e6e90c43df843512a4c761ad9affa | <ide><path>doc/api/n-api.md
<ide> exception is pending and no additional action is required. If the
<ide> instead of simply returning immediately, [`napi_is_exception_pending`][]
<ide> must be called in order to determine if an exception is pending or not.
<ide>
<add>In many cases when an N-API function is called and an exception is
<add>already pending, the function will return immediately with a
<add>`napi_status` of `napi_pending_exception`. However, this is not the case
<add>for all functions. N-API allows a subset of the functions to be
<add>called to allow for some minimal cleanup before returning to JavaScript.
<add>In that case, `napi_status` will reflect the status for the function. It
<add>will not reflect previous pending exceptions. To avoid confusion, check
<add>the error status after every function call.
<add>
<ide> When an exception is pending one of two approaches can be employed.
<ide>
<ide> The first approach is to do any appropriate cleanup and then return so that | 1 |
Javascript | Javascript | add test for d3.ns | 07b068ea6ca80521024f4e13945fe3237fa2bf38 | <ide><path>test/core/ns-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("ns");
<add>
<add>suite.addBatch({
<add> "prefix": {
<add> topic: function() {
<add> return d3.ns.prefix;
<add> },
<add> "svg is http://www.w3.org/2000/svg": function(prefix) {
<add> assert.equal(prefix.svg, "http://www.w3.org/2000/svg");
<add> },
<add> "xhtml is http://www.w3.org/1999/xhtml": function(prefix) {
<add> assert.equal(prefix.xhtml, "http://www.w3.org/1999/xhtml");
<add> },
<add> "xlink is http://www.w3.org/1999/xlink": function(prefix) {
<add> assert.equal(prefix.xlink, "http://www.w3.org/1999/xlink");
<add> },
<add> "xml is http://www.w3.org/XML/1998/namespace": function(prefix) {
<add> assert.equal(prefix.xml, "http://www.w3.org/XML/1998/namespace");
<add> },
<add> "xmlns is http://www.w3.org/2000/xmlns/": function(prefix) {
<add> assert.equal(prefix.xmlns, "http://www.w3.org/2000/xmlns/");
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "qualify": {
<add> topic: function() {
<add> return d3.ns.qualify;
<add> },
<add> "local name returns name": function() {
<add> assert.equal(d3.ns.qualify("local"), "local");
<add> },
<add> "known qualified name returns space and local": function() {
<add> var name = d3.ns.qualify("svg:path");
<add> assert.equal(name.space, "http://www.w3.org/2000/svg");
<add> assert.equal(name.local, "path");
<add> },
<add> "unknown qualified name returns undefined and local": function() {
<add> var name = d3.ns.qualify("foo:bar");
<add> assert.isUndefined(name.space);
<add> assert.equal(name.local, "bar");
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 1 |
PHP | PHP | fix failing tests in view package | f076f59e7c52a5d97d8e179c8a238fcb050d5f1f | <ide><path>src/View/ViewVarsTrait.php
<ide> public function createView($viewClass = null)
<ide>
<ide> foreach (['name', 'helpers', 'plugin'] as $prop) {
<ide> if (isset($this->{$prop})) {
<del> $builder->{$prop}($this->{$prop});
<add> $method = 'set' . ucfirst($prop);
<add> $builder->{$method}($this->{$prop});
<ide> }
<ide> }
<ide> $builder->setOptions($viewOptions);
<ide><path>tests/TestCase/View/ViewBuilderTest.php
<ide> public function stringPropertyProvider()
<ide> ['theme', 'TestPlugin'],
<ide> ['template', 'edit'],
<ide> ['name', 'Articles'],
<del> ['autoLayout', true],
<ide> ['className', 'Cake\View\JsonView'],
<ide> ];
<ide> }
<ide> public function testStringProperties($property, $value)
<ide> */
<ide> public function testBoolProperties($property, $value)
<ide> {
<del> $get = 'enable' . ucfirst($property);
<del> $set = 'is' . ucfirst($property) . 'Enabled';
<add> $set = 'enable' . ucfirst($property);
<add> $get = 'is' . ucfirst($property) . 'Enabled';
<ide>
<ide> $builder = new ViewBuilder();
<del> $this->assertFalse($builder->{$property}(), 'Default value should be null');
<del> $this->assertSame($builder, $builder->{$property}($value), 'Setter returns this');
<del> $this->assertSame($value, $builder->{$property}(), 'Getter gets value.');
<add> $this->assertNull($builder->{$get}(), 'Default value should be null');
<add> $this->assertSame($builder, $builder->{$set}($value), 'Setter returns this');
<add> $this->assertSame($value, $builder->{$get}(), 'Getter gets value.');
<ide> }
<ide>
<ide> /**
<ide> public function testArrayPropertyMerge($property, $value)
<ide> */
<ide> public function testStringPropertiesDeprecated($property, $value)
<ide> {
<del> $this->deprecated(function () {
<add> $this->deprecated(function () use ($value, $property) {
<ide> $builder = new ViewBuilder();
<ide> $this->assertNull($builder->{$property}(), 'Default value should be null');
<ide> $this->assertSame($builder, $builder->{$property}($value), 'Setter returns this');
<ide> public function testStringPropertiesDeprecated($property, $value)
<ide> */
<ide> public function testBoolPropertiesDeprecated($property, $value)
<ide> {
<del> $this->deprecated(function () {
<add> $this->deprecated(function () use ($value, $property) {
<ide> $builder = new ViewBuilder();
<ide> $this->assertNull($builder->{$property}(), 'Default value should be null');
<ide> $this->assertSame($builder, $builder->{$property}($value), 'Setter returns this');
<ide> public function testBoolPropertiesDeprecated($property, $value)
<ide> */
<ide> public function testArrayPropertiesDeprecated($property, $value)
<ide> {
<del> $this->deprecated(function () {
<add> $this->deprecated(function () use ($value, $property) {
<ide> $builder = new ViewBuilder();
<ide> $this->assertSame([], $builder->{$property}(), 'Default value should be empty list');
<ide> $this->assertSame($builder, $builder->{$property}($value), 'Setter returns this');
<ide> public function testArrayPropertiesDeprecated($property, $value)
<ide> */
<ide> public function testArrayPropertyMergeDeprecated($property, $value)
<ide> {
<del> $this->deprecated(function () {
<add> $this->deprecated(function () use ($value, $property) {
<ide> $builder = new ViewBuilder();
<ide> $builder->{$property}($value);
<ide>
<ide><path>tests/test_app/TestApp/View/Cell/ArticlesCell.php
<ide> public function customTemplateViewBuilder()
<ide> {
<ide> $this->template = 'derp';
<ide> $this->counter++;
<del> $this->viewBuilder()->template('alternate_teaser_list');
<add> $this->viewBuilder()->setTemplate('alternate_teaser_list');
<ide> }
<ide>
<ide> /**
<ide> public function customTemplateViewBuilder()
<ide> */
<ide> public function customTemplatePath()
<ide> {
<del> $this->viewBuilder()->templatePath('Cell/Articles/Subdir');
<add> $this->viewBuilder()->setTemplatePath('Cell/Articles/Subdir');
<ide> }
<ide>
<ide> /** | 3 |
Text | Text | fix examples in "docker port" man page | bf6492e689e2cb375fe6b39327dbe0655452640a | <ide><path>docs/man/docker-port.1.md
<ide> List port mappings for the CONTAINER, or lookup the public-facing port that is N
<ide> Print usage statement
<ide>
<ide> # EXAMPLES
<del>You can find out all the ports mapped by not specifying a `PRIVATE_PORT`, or
<del>ask for just a specific mapping:
<ide>
<del> $ docker ps test
<add> # docker ps
<ide> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
<ide> b650456536c7 busybox:latest top 54 minutes ago Up 54 minutes 0.0.0.0:1234->9876/tcp, 0.0.0.0:4321->7890/tcp test
<del> $ docker port test
<add>
<add>## Find out all the ports mapped
<add>
<add> # docker port test
<ide> 7890/tcp -> 0.0.0.0:4321
<ide> 9876/tcp -> 0.0.0.0:1234
<del> $ docker port test 7890/tcp
<add>
<add>## Find out a specific mapping
<add>
<add> # docker port test 7890/tcp
<ide> 0.0.0.0:4321
<del> $ docker port test 7890/udp
<del> 2014/06/24 11:53:36 Error: No public port '7890/udp' published for test
<del> $ docker port test 7890
<add>
<add> # docker port test 7890
<ide> 0.0.0.0:4321
<ide>
<add>## An example showing error for non-existent mapping
<add>
<add> # docker port test 7890/udp
<add> 2014/06/24 11:53:36 Error: No public port '7890/udp' published for test
<add>
<ide> # HISTORY
<ide> April 2014, Originally compiled by William Henry (whenry at redhat dot com)
<ide> June 2014, updated by Sven Dowideit <SvenDowideit@home.org.au> | 1 |
PHP | PHP | remove old method | d0e8a56624a0e581aa7a46b07cc5acfee57a9376 | <ide><path>src/Illuminate/Console/Scheduling/Event.php
<ide> public function run(Container $container)
<ide> $this->runCommandInForeground($container);
<ide> }
<ide>
<del> /**
<del> * Run the command in the background using exec.
<del> *
<del> * @return void
<del> */
<del> protected function runCommandInBackground()
<del> {
<del> chdir(base_path());
<del>
<del> exec($this->buildCommand());
<del> }
<del>
<ide> /**
<ide> * Run the command in the foreground.
<ide> * | 1 |
Python | Python | add example to runtests usage doc | b312137d6fb37bd8e81cc18ae9a642b4aada4c4b | <ide><path>runtests.py
<ide> $ python runtests.py
<ide> $ python runtests.py -s {SAMPLE_SUBMODULE}
<ide> $ python runtests.py -t {SAMPLE_TEST}
<add> $ python runtests.py -t {SAMPLE_TEST} -- {ARGUMENTS_FOR_NOSE}
<ide> $ python runtests.py --ipython
<ide> $ python runtests.py --python somescript.py
<ide> $ python runtests.py --bench
<ide> PROJECT_ROOT_FILES = ['numpy', 'LICENSE.txt', 'setup.py']
<ide> SAMPLE_TEST = "numpy/linalg/tests/test_linalg.py:test_byteorder_check"
<ide> SAMPLE_SUBMODULE = "linalg"
<add>ARGUMENTS_FOR_NOSE = "--pdb"
<ide>
<ide> EXTRA_PATH = ['/usr/lib/ccache', '/usr/lib/f90cache',
<ide> '/usr/local/lib/ccache', '/usr/local/lib/f90cache'] | 1 |
Javascript | Javascript | allow log in teststring, restrict test errors | febba792e7c19109bd0a8dedf098d85d7617e344 | <ide><path>client/src/client/workers/test-evaluator.js
<ide> const __utils = (() => {
<ide> self.postMessage(data);
<ide> }
<ide>
<del> function logToBoth(err) {
<add> function log(err) {
<ide> if (!(err instanceof chai.AssertionError)) {
<ide> // report to both the browser and the fcc consoles, discarding the
<ide> // stack trace via toString as it only useful to debug the site, not a
<ide> const __utils = (() => {
<ide> }
<ide> }
<ide>
<del> const toggleLogging = on => {
<del> self.console.log = on ? proxyLog : () => {};
<add> const toggleProxyLogger = on => {
<add> self.console.log = on ? proxyLog : oldLog;
<ide> };
<ide>
<ide> return {
<ide> postResult,
<del> logToBoth,
<del> toggleLogging
<add> log,
<add> toggleProxyLogger
<ide> };
<ide> })();
<ide>
<ide> self.onmessage = async e => {
<ide> // Fake Deep Equal dependency
<ide> const DeepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
<ide>
<del> __utils.toggleLogging(e.data.firstTest);
<add> // User code errors should be reported, but only once:
<add> __utils.toggleProxyLogger(e.data.firstTest);
<ide> /* eslint-enable no-unused-vars */
<ide> try {
<ide> let testResult;
<ide> self.onmessage = async e => {
<ide> throw err;
<ide> }
<ide> // log build errors
<del> __utils.logToBoth(err);
<add> __utils.log(err);
<ide> // the tests may not require working code, so they are evaluated even if
<ide> // the user code does not get executed.
<ide> testResult = eval(e.data.testString);
<ide> self.onmessage = async e => {
<ide> pass: true
<ide> });
<ide> } catch (err) {
<del> // report errors that happened during testing, so the user learns of
<del> // execution errors and not just build errors.
<del> __utils.toggleLogging(true);
<del> __utils.logToBoth(err);
<add> // Errors from testing go to the browser console only.
<add> __utils.toggleProxyLogger(false);
<add> // Report execution errors in case user code has errors that are only
<add> // uncovered during testing.
<add> __utils.log(err);
<ide> // postResult flushes the logs and must be called after logging is finished.
<ide> __utils.postResult({
<ide> err: {
<ide><path>client/src/templates/Challenges/redux/execute-challenge-saga.js
<ide> import {
<ide>
<ide> import {
<ide> buildChallenge,
<add> canBuildChallenge,
<ide> getTestRunner,
<ide> challengeHasPreview,
<ide> updatePreview,
<ide> function* previewChallengeSaga() {
<ide> yield fork(takeEveryConsole, logProxy);
<ide>
<ide> const challengeData = yield select(challengeDataSelector);
<del> const buildData = yield buildChallengeData(challengeData);
<del> // evaluate the user code in the preview frame or in the worker
<del> if (challengeHasPreview(challengeData)) {
<del> const document = yield getContext('document');
<del> yield call(updatePreview, buildData, document, proxyLogger);
<del> } else if (isJavaScriptChallenge(challengeData)) {
<del> const runUserCode = getTestRunner(buildData, { proxyLogger });
<del> // without a testString the testRunner just evaluates the user's code
<del> yield call(runUserCode, null, 5000);
<add> if (canBuildChallenge(challengeData)) {
<add> const buildData = yield buildChallengeData(challengeData);
<add> // evaluate the user code in the preview frame or in the worker
<add> if (challengeHasPreview(challengeData)) {
<add> const document = yield getContext('document');
<add> yield call(updatePreview, buildData, document, proxyLogger);
<add> } else if (isJavaScriptChallenge(challengeData)) {
<add> const runUserCode = getTestRunner(buildData, { proxyLogger });
<add> // without a testString the testRunner just evaluates the user's code
<add> yield call(runUserCode, null, 5000);
<add> }
<ide> }
<ide> } catch (err) {
<ide> console.log(err);
<ide><path>client/src/templates/Challenges/utils/build.js
<ide> const buildFunctions = {
<ide> [challengeTypes.backEndProject]: buildBackendChallenge
<ide> };
<ide>
<add>export function canBuildChallenge(challengeData) {
<add> const { challengeType } = challengeData;
<add> return buildFunctions.hasOwnProperty(challengeType);
<add>}
<add>
<ide> export async function buildChallenge(challengeData) {
<ide> const { challengeType } = challengeData;
<ide> let build = buildFunctions[challengeType];
<ide><path>client/src/templates/Challenges/utils/frame.js
<ide> const initTestFrame = frameReady => ctx => {
<ide> const initMainFrame = (frameReady, proxyLogger) => ctx => {
<ide> waitForFrame(ctx).then(() => {
<ide> // Overwriting the onerror added by createHeader to catch any errors thrown
<del> // after the frame is ready. It has to be overwritten, as proxyUpdateConsole
<del> // cannot be added as part of createHeader.
<add> // after the frame is ready. It has to be overwritten, as proxyLogger cannot
<add> // be added as part of createHeader.
<ide> ctx.window.onerror = function(msg) {
<ide> console.log(msg);
<ide> if (proxyLogger) { | 4 |
Python | Python | skip metric tests for cntk | 3e70caf7c6e03fe7a112d60a2ed920f0deda0b43 | <ide><path>tests/keras/metrics_training_test.py
<ide> from keras.layers import Dense
<ide> from keras.models import Sequential
<ide>
<add>
<add>if K.backend() == 'cntk':
<add> pytestmark = pytest.mark.skip
<add>
<add>
<ide> METRICS = [
<ide> metrics.Accuracy,
<ide> metrics.MeanSquaredError, | 1 |
Ruby | Ruby | run bin/yarn via ruby | 44d1006de3d5de0d00c5bffcd041e1f06162d98b | <ide><path>actiontext/lib/generators/action_text/install/install_generator.rb
<ide> def js_dependencies
<ide> end
<ide>
<ide> def yarn_command(command, config = {})
<del> in_root { run "bin/yarn #{command}", abort_on_failure: true, **config }
<add> in_root { run "#{Thor::Util.ruby_command} bin/yarn #{command}", abort_on_failure: true, **config }
<ide> end
<ide> end
<ide> end
<ide><path>railties/test/generators/action_text_install_generator_test.rb
<ide> class ActionText::Generators::InstallGeneratorTest < Rails::Generators::TestCase
<ide> assert_migration "db/migrate/create_action_text_tables.action_text.rb"
<ide> end
<ide>
<add> test "#yarn_command runs bin/yarn via Ruby" do
<add> ran = nil
<add> run_stub = -> (command, *) { ran = command }
<add>
<add> generator.stub(:run, run_stub) do
<add> generator.send(:yarn_command, "foo")
<add> end
<add>
<add> assert_match %r"\S bin/yarn foo$", ran
<add> end
<add>
<ide> private
<ide> def run_generator_instance
<ide> @yarn_commands = [] | 2 |
Python | Python | remove unsused dummy variable | 62de5da1ff994ea6731368d19be2236bb3aa2199 | <ide><path>spacy/tests/regression/test_issue1622.py
<ide>
<ide> @pytest.mark.xfail
<ide> def test_cli_trained_model_can_be_saved(tmpdir):
<del> cmd = None
<ide> lang = 'nl'
<ide> output_dir = str(tmpdir)
<ide> train_file = NamedTemporaryFile('wb', dir=output_dir, delete=False) | 1 |
Text | Text | add v3.23.0-beta.3 to changelog | 05e278a573a07f40177f75a5ab3daa41ea738d44 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.23.0-beta.3 (October 26, 2020)
<add>
<add>- [#19199](https://github.com/emberjs/ember.js/pull/19199) [BUGFIX] Fix Ember Inspector to not be in a broken state after render errors
<add>- [#19221](https://github.com/emberjs/ember.js/pull/19221) [BUGFIX] Ensure fn and (mut) work with falsy values
<add>
<ide> ### v3.23.0-beta.2 (October 19, 2020)
<ide>
<ide> - [#19193](https://github.com/emberjs/ember.js/pull/19193) [BUGFIX] Ensure user lifecycle hooks are untracked | 1 |
PHP | PHP | fix cs error | 0ca35508a9491ce3c156038bb36ccad776dc408a | <ide><path>src/Model/Behavior/TreeBehavior.php
<ide> */
<ide> namespace Cake\Model\Behavior;
<ide>
<add>use Cake\Datasource\Exception\RecordNotFoundException;
<ide> use Cake\Event\Event;
<ide> use Cake\ORM\Behavior;
<ide> use Cake\ORM\Entity;
<del>use Cake\Datasource\Exception\RecordNotFoundException;
<ide> use Cake\ORM\Query;
<ide> use Cake\ORM\Table;
<ide> | 1 |
Javascript | Javascript | fix isdefined -> angular.isdefined | 2a4a8226d1c7dc9d6a86a3429144c065c8f01c89 | <ide><path>src/ngResource/resource.js
<ide> angular.module('ngResource', ['ng']).
<ide> params = params || {};
<ide> forEach(this.urlParams, function(_, urlParam){
<ide> val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
<del> if (isDefined(val) && val !== null) {
<add> if (angular.isDefined(val) && val !== null) {
<ide> encodedVal = encodeUriSegment(val);
<ide> url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1");
<ide> } else { | 1 |
Java | Java | fix onpress event for nested text in rn android | e494e4beb6a124008fd116178cbc38335bd87809 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java
<ide> public static boolean isMapBufferSerializationEnabled() {
<ide> public static boolean useDispatchUniqueForCoalescableEvents = false;
<ide>
<ide> public static boolean useUpdatedTouchPreprocessing = false;
<add>
<add> /** TODO: T103427072 Delete ReactFeatureFlags.enableNestedTextOnPressEventFix */
<add> public static boolean enableNestedTextOnPressEventFix = true;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java
<ide> import android.text.method.LinkMovementMethod;
<ide> import android.text.util.Linkify;
<ide> import android.view.Gravity;
<add>import android.view.MotionEvent;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<ide> import androidx.annotation.Nullable;
<ide> import com.facebook.react.bridge.WritableArray;
<ide> import com.facebook.react.bridge.WritableMap;
<ide> import com.facebook.react.common.ReactConstants;
<add>import com.facebook.react.config.ReactFeatureFlags;
<ide> import com.facebook.react.uimanager.PixelUtil;
<ide> import com.facebook.react.uimanager.ReactCompoundView;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> public int reactTagForTouch(float touchX, float touchY) {
<ide> return target;
<ide> }
<ide>
<add> @Override
<add> public boolean onTouchEvent(MotionEvent ev) {
<add> // The root view always assumes any view that was tapped wants the touch
<add> // and sends the event to JS as such.
<add> // We don't need to do bubbling in native (it's already happening in JS).
<add> // For an explanation of bubbling and capturing, see
<add> // http://javascript.info/tutorial/bubbling-and-capturing#capturing
<add> return ReactFeatureFlags.enableNestedTextOnPressEventFix;
<add> }
<add>
<ide> @Override
<ide> protected boolean verifyDrawable(Drawable drawable) {
<ide> if (mContainsImages && getText() instanceof Spanned) { | 2 |
Go | Go | add buffer32kpool & use it for copy | ba40f4593f79a653f1e3a8b9597b7900fb68a564 | <ide><path>pkg/pools/pools.go
<ide> import (
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> )
<ide>
<add>const buffer32K = 32 * 1024
<add>
<ide> var (
<ide> // BufioReader32KPool is a pool which returns bufio.Reader with a 32K buffer.
<ide> BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K)
<ide> // BufioWriter32KPool is a pool which returns bufio.Writer with a 32K buffer.
<ide> BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K)
<add> buffer32KPool = newBufferPoolWithSize(buffer32K)
<ide> )
<ide>
<del>const buffer32K = 32 * 1024
<del>
<ide> // BufioReaderPool is a bufio reader that uses sync.Pool.
<ide> type BufioReaderPool struct {
<ide> pool sync.Pool
<ide> func (bufPool *BufioReaderPool) Put(b *bufio.Reader) {
<ide> bufPool.pool.Put(b)
<ide> }
<ide>
<add>type bufferPool struct {
<add> pool sync.Pool
<add>}
<add>
<add>func newBufferPoolWithSize(size int) *bufferPool {
<add> return &bufferPool{
<add> pool: sync.Pool{
<add> New: func() interface{} { return make([]byte, size) },
<add> },
<add> }
<add>}
<add>
<add>func (bp *bufferPool) Get() []byte {
<add> return bp.pool.Get().([]byte)
<add>}
<add>
<add>func (bp *bufferPool) Put(b []byte) {
<add> bp.pool.Put(b)
<add>}
<add>
<ide> // Copy is a convenience wrapper which uses a buffer to avoid allocation in io.Copy.
<ide> func Copy(dst io.Writer, src io.Reader) (written int64, err error) {
<del> buf := BufioReader32KPool.Get(src)
<del> written, err = io.Copy(dst, buf)
<del> BufioReader32KPool.Put(buf)
<add> buf := buffer32KPool.Get()
<add> written, err = io.CopyBuffer(dst, src, buf)
<add> buffer32KPool.Put(buf)
<ide> return
<ide> }
<ide>
<ide><path>pkg/pools/pools_test.go
<ide> func TestNewWriteCloserWrapperWithAWriteCloser(t *testing.T) {
<ide> t.Fatalf("The ReaderCloser should have been closed, it is not.")
<ide> }
<ide> }
<add>
<add>func TestBufferPoolPutAndGet(t *testing.T) {
<add> buf := buffer32KPool.Get()
<add> buffer32KPool.Put(buf)
<add>} | 2 |
Javascript | Javascript | implement contents for every annotation type | cf07918ccb22851e65b87ffdca0794c4003a69c5 | <ide><path>src/core/annotation.js
<ide> function getTransformMatrix(rect, bbox, matrix) {
<ide>
<ide> class Annotation {
<ide> constructor(params) {
<del> let dict = params.dict;
<add> const dict = params.dict;
<ide>
<add> this.setContents(dict.get('Contents'));
<ide> this.setCreationDate(dict.get('CreationDate'));
<ide> this.setModificationDate(dict.get('M'));
<ide> this.setFlags(dict.get('F'));
<ide> class Annotation {
<ide> annotationFlags: this.flags,
<ide> borderStyle: this.borderStyle,
<ide> color: this.color,
<add> contents: this.contents,
<ide> creationDate: this.creationDate,
<ide> hasAppearance: !!this.appearance,
<ide> id: params.id,
<ide> class Annotation {
<ide> return this._isPrintable(this.flags);
<ide> }
<ide>
<add> /**
<add> * Set the contents.
<add> *
<add> * @public
<add> * @memberof Annotation
<add> * @param {string} contents - Text to display for the annotation or, if the
<add> * type of annotation does not display text, a
<add> * description of the annotation's contents
<add> */
<add> setContents(contents) {
<add> this.contents = stringToPDFString(contents || '');
<add> }
<add>
<ide> /**
<ide> * Set the creation date.
<ide> *
<ide> class MarkupAnnotation extends Annotation {
<ide>
<ide> this.data.hasPopup = dict.has('Popup');
<ide> this.data.title = stringToPDFString(dict.get('T') || '');
<del> this.data.contents = stringToPDFString(dict.get('Contents') || '');
<ide> }
<ide> }
<ide>
<ide><path>test/unit/annotation_spec.js
<ide> describe('annotation', function() {
<ide> dict = ref = null;
<ide> });
<ide>
<add> it('should set and get valid contents', function() {
<add> const annotation = new Annotation({ dict, ref, });
<add> annotation.setContents('Foo bar baz');
<add>
<add> expect(annotation.contents).toEqual('Foo bar baz');
<add> });
<add>
<add> it('should not set and get invalid contents', function() {
<add> const annotation = new Annotation({ dict, ref, });
<add> annotation.setContents(undefined);
<add>
<add> expect(annotation.contents).toEqual('');
<add> });
<add>
<ide> it('should set and get a valid creation date', function() {
<ide> const annotation = new Annotation({ dict, ref, });
<ide> annotation.setCreationDate('D:20190422'); | 2 |
Python | Python | add test for column-vector bug in dotblas | 83d691d731082ec8d2367affb77b454c2a0b0855 | <ide><path>numpy/core/tests/test_numeric.py
<ide> def check_matscalar(self):
<ide> b1 = matrix(ones((3,3),dtype=complex))
<ide> assert_equal(b1*1.0, b1)
<ide>
<add> def check_columnvect(self):
<add> b1 = ones((3,1))
<add> b2 = [5.3]
<add> c1 = dot(b1,b2)
<add> c2 = dot_(b1,b2)
<add> assert_almost_equal(c1, c2, decimal=self.N)
<add>
<ide>
<ide> class test_bool_scalar(ScipyTestCase):
<ide> def test_logical(self):
<ide><path>numpy/lib/function_base.py
<ide> def piecewise(x, condlist, funclist, *args, **kw):
<ide> Each function should return an array output for an array input
<ide> Each function can take (the same set) of extra arguments and
<ide> keyword arguments which are passed in after the function list.
<add> A constant may be used in funclist for a function that returns a
<add> constant (e.g. val and lambda x: val are equivalent in a funclist).
<ide>
<ide> The output is the same shape and type as x and is found by
<ide> calling the functions on the appropriate portions of x. | 2 |
Mixed | Text | add documentation for brotli support | b91093f0e529229cb2810dbc22781a57a71c3749 | <ide><path>doc/api/errors.md
<ide> An attempt was made to register something that is not a function as an
<ide> The type of an asynchronous resource was invalid. Note that users are also able
<ide> to define their own types if using the public embedder API.
<ide>
<add><a id="ERR_BROTLI_COMPRESSION_FAILED"></a>
<add>### ERR_BROTLI_COMPRESSION_FAILED
<add>
<add>Data passed to a Brotli stream was not successfully compressed.
<add>
<ide> <a id="ERR_BROTLI_INVALID_PARAM"></a>
<ide> ### ERR_BROTLI_INVALID_PARAM
<ide>
<ide> An invalid parameter key was passed during construction of a Brotli stream.
<ide>
<del><a id="ERR_BROTLI_COMPRESSION_FAILED">
<del>### ERR_BROTLI_COMPRESSION_FAILED
<del>
<del>Data passed to a Brotli stream was not successfully compressed.
<del>
<ide> <a id="ERR_BUFFER_CONTEXT_NOT_AVAILABLE"></a>
<ide> ### ERR_BUFFER_CONTEXT_NOT_AVAILABLE
<ide>
<ide><path>doc/api/zlib.md
<ide> > Stability: 2 - Stable
<ide>
<ide> The `zlib` module provides compression functionality implemented using Gzip and
<del>Deflate/Inflate. It can be accessed using:
<add>Deflate/Inflate, as well as Brotli. It can be accessed using:
<ide>
<ide> ```js
<ide> const zlib = require('zlib');
<ide> and/or unrecoverable and catastrophic memory fragmentation.
<ide>
<ide> ## Compressing HTTP requests and responses
<ide>
<del>The `zlib` module can be used to implement support for the `gzip` and `deflate`
<del>content-encoding mechanisms defined by
<add>The `zlib` module can be used to implement support for the `gzip`, `deflate`
<add>and `br` content-encoding mechanisms defined by
<ide> [HTTP](https://tools.ietf.org/html/rfc7230#section-4.2).
<ide>
<ide> The HTTP [`Accept-Encoding`][] header is used within an http request to identify
<ide> const fs = require('fs');
<ide> const request = http.get({ host: 'example.com',
<ide> path: '/',
<ide> port: 80,
<del> headers: { 'Accept-Encoding': 'gzip,deflate' } });
<add> headers: { 'Accept-Encoding': 'br,gzip,deflate' } });
<ide> request.on('response', (response) => {
<ide> const output = fs.createWriteStream('example.com_index.html');
<ide>
<ide> switch (response.headers['content-encoding']) {
<del> // Or, just use zlib.createUnzip() to handle both cases
<add> case 'br':
<add> response.pipe(zlib.createBrotliDecompress()).pipe(output);
<add> break;
<add> // Or, just use zlib.createUnzip() to handle both of the following cases:
<ide> case 'gzip':
<ide> response.pipe(zlib.createGunzip()).pipe(output);
<ide> break;
<ide> http.createServer((request, response) => {
<ide> } else if (/\bgzip\b/.test(acceptEncoding)) {
<ide> response.writeHead(200, { 'Content-Encoding': 'gzip' });
<ide> raw.pipe(zlib.createGzip()).pipe(response);
<add> } else if (/\bbr\b/.test(acceptEncoding)) {
<add> response.writeHead(200, { 'Content-Encoding': 'br' });
<add> raw.pipe(zlib.createBrotliCompress()).pipe(response);
<ide> } else {
<ide> response.writeHead(200, {});
<ide> raw.pipe(response);
<ide> const buffer = Buffer.from('eJzT0yMA', 'base64');
<ide>
<ide> zlib.unzip(
<ide> buffer,
<add> // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.
<ide> { finishFlush: zlib.constants.Z_SYNC_FLUSH },
<ide> (err, buffer) => {
<ide> if (!err) {
<ide> decompressed result is valid.
<ide>
<ide> <!--type=misc-->
<ide>
<add>### For zlib-based streams
<add>
<ide> From `zlib/zconf.h`, modified to Node.js's usage:
<ide>
<ide> The memory requirements for deflate are (in bytes):
<ide> fewer calls to `zlib` because it will be able to process more data on
<ide> each `write` operation. So, this is another factor that affects the
<ide> speed, at the cost of memory usage.
<ide>
<add>### For Brotli-based streams
<add>
<add>There are equivalents to the zlib options for Brotli-based streams, although
<add>these options have different ranges than the zlib ones:
<add>
<add>- zlib’s `level` option matches Brotli’s `BROTLI_PARAM_QUALITY` option.
<add>- zlib’s `windowBits` option matches Brotli’s `BROTLI_PARAM_LGWIN` option.
<add>
<add>See [below][Brotli parameters] for more details on Brotli-specific options.
<add>
<ide> ## Flushing
<ide>
<ide> Calling [`.flush()`][] on a compression stream will make `zlib` return as much
<ide> added: v0.5.8
<ide>
<ide> <!--type=misc-->
<ide>
<add>### zlib constants
<add>
<ide> All of the constants defined in `zlib.h` are also defined on
<ide> `require('zlib').constants`. In the normal course of operations, it will not be
<ide> necessary to use these constants. They are documented so that their presence is
<ide> Compression strategy.
<ide> * `zlib.constants.Z_FIXED`
<ide> * `zlib.constants.Z_DEFAULT_STRATEGY`
<ide>
<add>### Brotli constants
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>There are several options and other constants available for Brotli-based
<add>streams:
<add>
<add>#### Flush operations
<add>
<add>The following values are valid flush operations for Brotli-based streams:
<add>
<add>* `zlib.constants.BROTLI_OPERATION_PROCESS` (default for all operations)
<add>* `zlib.constants.BROTLI_OPERATION_FLUSH` (default when calling `.flush()`)
<add>* `zlib.constants.BROTLI_OPERATION_FINISH` (default for the last chunk)
<add>* `zlib.constants.BROTLI_OPERATION_EMIT_METADATA`
<add> * This particular operation may be hard to use in a Node.js context,
<add> as the streaming layer makes it hard to know which data will end up
<add> in this frame. Also, there is currently no way to consume this data through
<add> the Node.js API.
<add>
<add>#### Compressor options
<add>
<add>There are several options that can be set on Brotli encoders, affecting
<add>compression efficiency and speed. Both the keys and the values can be accessed
<add>as properties of the `zlib.constants` object.
<add>
<add>The most important options are:
<add>
<add>* `BROTLI_PARAM_MODE`
<add> * `BROTLI_MODE_GENERIC` (default)
<add> * `BROTLI_MODE_TEXT`, adjusted for UTF-8 text
<add> * `BROTLI_MODE_FONT`, adjusted for WOFF 2.0 fonts
<add>* `BROTLI_PARAM_QUALITY`
<add> * Ranges from `BROTLI_MIN_QUALITY` to `BROTLI_MAX_QUALITY`,
<add> with a default of `BROTLI_DEFAULT_QUALITY`.
<add>* `BROTLI_PARAM_SIZE_HINT`
<add> * Integer value representing the expected input size;
<add> defaults to `0` for an unknown input size.
<add>
<add>The following flags can be set for advanced control over the compression
<add>algorithm and memory usage tuning:
<add>
<add>* `BROTLI_PARAM_LGWIN`
<add> * Ranges from `BROTLI_MIN_WINDOW_BITS` to `BROTLI_MAX_WINDOW_BITS`,
<add> with a default of `BROTLI_DEFAULT_WINDOW`, or up to
<add> `BROTLI_LARGE_MAX_WINDOW_BITS` if the `BROTLI_PARAM_LARGE_WINDOW` flag
<add> is set.
<add>* `BROTLI_PARAM_LGBLOCK`
<add> * Ranges from `BROTLI_MIN_INPUT_BLOCK_BITS` to `BROTLI_MAX_INPUT_BLOCK_BITS`.
<add>* `BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING`
<add> * Boolean flag that decreases compression ratio in favour of
<add> decompression speed.
<add>* `BROTLI_PARAM_LARGE_WINDOW`
<add> * Boolean flag enabling “Large Window Brotli” mode (not compatible with the
<add> Brotli format as standardized in [RFC 7932][]).
<add>* `BROTLI_PARAM_NPOSTFIX`
<add> * Ranges from `0` to `BROTLI_MAX_NPOSTFIX`.
<add>* `BROTLI_PARAM_NDIRECT`
<add> * Ranges from `0` to `15 << NPOSTFIX` in steps of `1 << NPOSTFIX`.
<add>
<add>#### Decompressor options
<add>
<add>These advanced options are available for controlling decompression:
<add>
<add>* `BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION`
<add> * Boolean flag that affects internal memory allocation patterns.
<add>* `BROTLI_DECODER_PARAM_LARGE_WINDOW`
<add> * Boolean flag enabling “Large Window Brotli” mode (not compatible with the
<add> Brotli format as standardized in [RFC 7932][]).
<add>
<ide> ## Class: Options
<ide> <!-- YAML
<ide> added: v0.11.1
<ide> changes:
<ide>
<ide> <!--type=misc-->
<ide>
<del>Each class takes an `options` object. All options are optional.
<add>Each zlib-based class takes an `options` object. All options are optional.
<ide>
<ide> Note that some options are only relevant when compressing, and are
<ide> ignored by the decompression classes.
<ide> ignored by the decompression classes.
<ide> See the description of `deflateInit2` and `inflateInit2` at
<ide> <https://zlib.net/manual.html#Advanced> for more information on these.
<ide>
<add>## Class: BrotliOptions
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add><!--type=misc-->
<add>
<add>Each Brotli-based class takes an `options` object. All options are optional.
<add>
<add>* `flush` {integer} **Default:** `zlib.constants.BROTLI_OPERATION_PROCESS`
<add>* `finishFlush` {integer} **Default:** `zlib.constants.BROTLI_OPERATION_FINISH`
<add>* `chunkSize` {integer} **Default:** `16 * 1024`
<add>* `params` {Object} Key-value object containing indexed [Brotli parameters][].
<add>
<add>For example:
<add>
<add>```js
<add>const stream = zlib.createBrotliCompress({
<add> chunkSize: 32 * 1024,
<add> params: {
<add> [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
<add> [zlib.constants.BROTLI_PARAM_QUALITY]: 4,
<add> [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size
<add> }
<add>});
<add>```
<add>
<add>## Class: zlib.BrotliCompress
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>Compress data using the Brotli algorithm.
<add>
<add>## Class: zlib.BrotliDecompress
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>Decompress data using the Brotli algorithm.
<add>
<ide> ## Class: zlib.Deflate
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> added: v0.5.8
<ide> Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
<ide> the header.
<ide>
<del>## Class: zlib.Zlib
<add>## Class: zlib.ZlibBase
<ide> <!-- YAML
<ide> added: v0.5.8
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/24939
<add> description: This class was renamed from `Zlib` to `ZlibBase`.
<ide> -->
<ide>
<ide> Not exported by the `zlib` module. It is documented here because it is the base
<ide> Close the underlying handle.
<ide> added: v0.5.8
<ide> -->
<ide>
<del>* `kind` **Default:** `zlib.constants.Z_FULL_FLUSH`
<add>* `kind` **Default:** `zlib.constants.Z_FULL_FLUSH` for zlib-based streams,
<add> `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams.
<ide> * `callback` {Function}
<ide>
<ide> Flush pending data. Don't call this frivolously, premature flushes negatively
<ide> added: v0.11.4
<ide> * `strategy` {integer}
<ide> * `callback` {Function}
<ide>
<add>This function is only available for zlib-based streams, i.e. not Brotli.
<add>
<ide> Dynamically update the compression level and compression strategy.
<ide> Only applicable to deflate algorithm.
<ide>
<ide> added: v7.0.0
<ide>
<ide> Provides an object enumerating Zlib-related constants.
<ide>
<add>## zlib.createBrotliCompress([options])
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `options` {brotli options}
<add>
<add>Creates and returns a new [`BrotliCompress`][] object.
<add>
<add>## zlib.createBrotliDecompress([options])
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `options` {brotli options}
<add>
<add>Creates and returns a new [`BrotliDecompress`][] object.
<add>
<ide> ## zlib.createDeflate([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> with `callback(error, result)`.
<ide> Every method has a `*Sync` counterpart, which accept the same arguments, but
<ide> without a callback.
<ide>
<add>### zlib.brotliCompress(buffer[, options], callback)
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {brotli options}
<add>* `callback` {Function}
<add>
<add>### zlib.brotliCompressSync(buffer[, options])
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {brotli options}
<add>
<add>Compress a chunk of data with [`BrotliCompress`][].
<add>
<add>### zlib.brotliDecompress(buffer[, options], callback)
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {brotli options}
<add>* `callback` {Function}
<add>
<add>### zlib.brotliDecompressSync(buffer[, options])
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {brotli options}
<add>
<add>Decompress a chunk of data with [`BrotliDecompress`][].
<add>
<ide> ### zlib.deflate(buffer[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> Decompress a chunk of data with [`Unzip`][].
<ide> [`.flush()`]: #zlib_zlib_flush_kind_callback
<ide> [`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
<ide> [`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
<add>[`BrotliCompress`]: #zlib_class_zlib_brotlicompress
<add>[`BrotliDecompress`]: #zlib_class_zlib_brotlidecompress
<ide> [`Buffer`]: buffer.html#buffer_class_buffer
<ide> [`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
<ide> [`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
<ide> Decompress a chunk of data with [`Unzip`][].
<ide> [`Unzip`]: #zlib_class_zlib_unzip
<ide> [`stream.Transform`]: stream.html#stream_class_stream_transform
<ide> [`zlib.bytesWritten`]: #zlib_zlib_byteswritten
<add>[Brotli parameters]: #zlib_brotli_constants
<ide> [Memory Usage Tuning]: #zlib_memory_usage_tuning
<add>[RFC 7932]: https://www.rfc-editor.org/rfc/rfc7932.txt
<ide> [pool size]: cli.html#cli_uv_threadpool_size_size
<ide> [zlib documentation]: https://zlib.net/manual.html#Constants
<ide><path>tools/doc/type-parser.js
<ide> const customTypesMap = {
<ide> 'AsyncHook': 'async_hooks.html#async_hooks_async_hooks_createhook_callbacks',
<ide> 'AsyncResource': 'async_hooks.html#async_hooks_class_asyncresource',
<ide>
<add> 'brotli options': 'zlib.html#zlib_class_brotlioptions',
<add>
<ide> 'Buffer': 'buffer.html#buffer_class_buffer',
<ide>
<ide> 'ChildProcess': 'child_process.html#child_process_class_childprocess', | 3 |
Javascript | Javascript | add placeholders for static prop type tests | e31f23fc2ac9925dfb445f0f61e93a7363dda5fc | <ide><path>src/modern/types/__tests__/ReactFlowPropTypes-test.js
<add>/**
<add> * Copyright 2014, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @emails react-core
<add> */
<add>
<add>"use strict";
<add>
<add>describe('ReactFlowPropTypes', function() {
<add>
<add> // TODO: Test Flow integration and ensure that prop types works.
<add>
<add>});
<ide><path>src/modern/types/__tests__/ReactTypeScriptPropTypes-test.js
<add>/**
<add> * Copyright 2014, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @emails react-core
<add> */
<add>
<add>"use strict";
<add>
<add>describe('ReactTypeScriptPropTypes', function() {
<add>
<add> // TODO: Test TypeScript integration and ensure that prop types works.
<add>
<add>}); | 2 |
Javascript | Javascript | remove eslint comments" | 9f7b54945e64a929d1709a82b59bbd87d144ee5c | <ide><path>test/parallel/test-whatwg-url-tojson.js
<ide> const common = require('../common');
<ide> const URL = require('url').URL;
<ide> const { test, assert_equals } = common.WPT;
<ide>
<add>/* eslint-disable */
<ide> /* WPT Refs:
<ide> https://github.com/w3c/web-platform-tests/blob/02585db/url/url-tojson.html
<ide> License: http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html
<ide> */
<ide> test(() => {
<del> const a = new URL('https://example.com/');
<del> assert_equals(JSON.stringify(a), '"https://example.com/"');
<del>});
<add> const a = new URL("https://example.com/")
<add> assert_equals(JSON.stringify(a), "\"https://example.com/\"")
<add>})
<add>/* eslint-enable */ | 1 |
Ruby | Ruby | fix reporting matches with spaces in them | d9afb4f9ea54d2b6e4f04c1e6fe5f3b051258447 | <ide><path>Library/Homebrew/cmd/bottle.rb
<ide> def keg_contains string, keg
<ide> # Use strings to search through the file for each string
<ide> strings = `strings -t x - "#{file}"`.select{ |str| str.include? string }.map{ |s| s.strip }
<ide>
<del> # Don't bother reporting a string if it was found by otool
<del> strings.reject!{ |str| linked_libraries.include? str.split[1] }
<ide> strings.each do |str|
<del> offset, match = str.split
<add> offset, match = str.split(" ", 2)
<add> next if linked_libraries.include? match # Don't bother reporting a string if it was found by otool
<ide> puts " #{Tty.gray}-->#{Tty.reset} match '#{match}' at offset #{Tty.em}0x#{offset}#{Tty.reset}"
<ide> end
<ide> end | 1 |
Javascript | Javascript | port the `mozcentraldiff` target to gulp | 19cc9bcdedf80e04873944dfa302500599dcf39e | <ide><path>gulpfile.js
<ide> var COMMON_WEB_FILES = [
<ide> 'web/images/*.{png,svg,gif,cur}',
<ide> 'web/debugger.js'
<ide> ];
<add>var MOZCENTRAL_DIFF_FILE = 'mozcentral.diff';
<ide>
<ide> var REPO = 'git@github.com:mozilla/pdf.js.git';
<ide> var DIST_REPO_URL = 'https://github.com/mozilla/pdfjs-dist';
<ide> gulp.task('mozcentralbaseline', ['baseline'], function (done) {
<ide> });
<ide> });
<ide>
<add>gulp.task('mozcentraldiff', ['mozcentral', 'mozcentralbaseline'],
<add> function (done) {
<add> console.log();
<add> console.log('### Creating mozcentral diff');
<add>
<add> // Create the diff between the current mozcentral build and the
<add> // baseline mozcentral build, which both exist at this point.
<add> // The mozcentral baseline directory is a Git repository, so we
<add> // remove all files and copy the current mozcentral build files
<add> // into it to create the diff.
<add> rimraf.sync(MOZCENTRAL_BASELINE_DIR + '*');
<add>
<add> gulp.src([BUILD_DIR + 'mozcentral/**/*'])
<add> .pipe(gulp.dest(MOZCENTRAL_BASELINE_DIR))
<add> .on('end', function () {
<add> spawnSync('git', ['add', '-A'], {cwd: MOZCENTRAL_BASELINE_DIR});
<add> var diff = spawnSync('git',
<add> ['diff', '--binary', '--cached', '--unified=8'],
<add> {cwd: MOZCENTRAL_BASELINE_DIR}).stdout;
<add>
<add> createStringSource(MOZCENTRAL_DIFF_FILE, diff)
<add> .pipe(gulp.dest(BUILD_DIR))
<add> .on('end', function () {
<add> console.log('Result diff can be found at ' + BUILD_DIR +
<add> MOZCENTRAL_DIFF_FILE);
<add> done();
<add> });
<add> });
<add>});
<add>
<ide> // Getting all shelljs registered tasks and register them with gulp
<ide> require('./make.js');
<ide>
<ide><path>make.js
<ide> target.mozcentralbaseline = function() {
<ide> };
<ide>
<ide> target.mozcentraldiff = function() {
<del> target.mozcentral();
<del>
<del> cd(ROOT_DIR);
<del>
<del> echo();
<del> echo('### Creating mozcentral diff');
<del>
<del> var MOZCENTRAL_DIFF = BUILD_DIR + 'mozcentral.diff';
<del> if (test('-f', MOZCENTRAL_DIFF)) {
<del> rm(MOZCENTRAL_DIFF);
<del> }
<del>
<del> var MOZCENTRAL_BASELINE_DIR = BUILD_DIR + 'mozcentral.baseline';
<del> if (!test('-d', MOZCENTRAL_BASELINE_DIR)) {
<del> echo('mozcentral baseline was not found');
<del> echo('Please build one using "gulp mozcentralbaseline"');
<del> exit(1);
<del> }
<del> cd(MOZCENTRAL_BASELINE_DIR);
<del> exec('git reset --hard');
<del> cd(ROOT_DIR); rm('-rf', MOZCENTRAL_BASELINE_DIR + '/*'); // trying to be safe
<del> cd(MOZCENTRAL_BASELINE_DIR);
<del> cp('-Rf', '../mozcentral/*', '.');
<del> exec('git add -A');
<del> exec('git diff --binary --cached --unified=8', {silent: true}).output.
<del> to('../mozcentral.diff');
<del>
<del> echo('Result diff can be found at ' + MOZCENTRAL_DIFF);
<add> execGulp('mozcentraldiff');
<ide> };
<ide>
<ide> //////////////////////////////////////////////////////////////////////////////// | 2 |
Java | Java | use consistent class design | eeebd51f57f452c57bc159fa8a2ad9746c4c2f8c | <ide><path>spring-aop/src/main/java/org/springframework/aop/TrueClassFilter.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Rod Johnson
<ide> */
<ide> @SuppressWarnings("serial")
<del>class TrueClassFilter implements ClassFilter, Serializable {
<add>final class TrueClassFilter implements ClassFilter, Serializable {
<ide>
<ide> public static final TrueClassFilter INSTANCE = new TrueClassFilter();
<ide>
<ide><path>spring-aop/src/main/java/org/springframework/aop/TrueMethodMatcher.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Rod Johnson
<ide> */
<ide> @SuppressWarnings("serial")
<del>class TrueMethodMatcher implements MethodMatcher, Serializable {
<add>final class TrueMethodMatcher implements MethodMatcher, Serializable {
<ide>
<ide> public static final TrueMethodMatcher INSTANCE = new TrueMethodMatcher();
<ide>
<ide><path>spring-aop/src/main/java/org/springframework/aop/TruePointcut.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Rod Johnson
<ide> */
<ide> @SuppressWarnings("serial")
<del>class TruePointcut implements Pointcut, Serializable {
<add>final class TruePointcut implements Pointcut, Serializable {
<ide>
<ide> public static final TruePointcut INSTANCE = new TruePointcut();
<ide>
<ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java
<ide> public String toString() {
<ide> return sb.toString();
<ide> }
<ide>
<add> //---------------------------------------------------------------------
<add> // Serialization support
<add> //---------------------------------------------------------------------
<add>
<add> private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
<add> // Rely on default serialization, just initialize state after deserialization.
<add> ois.defaultReadObject();
<add>
<add> // Initialize transient fields.
<add> // pointcutExpression will be initialized lazily by checkReadyToMatch()
<add> this.shadowMatchCache = new ConcurrentHashMap<>(32);
<add> }
<add>
<ide>
<ide> /**
<ide> * Handler for the Spring-specific {@code bean()} pointcut designator
<ide> private boolean matchesBean(String advisedBeanName) {
<ide> }
<ide>
<ide>
<del> //---------------------------------------------------------------------
<del> // Serialization support
<del> //---------------------------------------------------------------------
<del>
<del> private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
<del> // Rely on default serialization, just initialize state after deserialization.
<del> ois.defaultReadObject();
<del>
<del> // Initialize transient fields.
<del> // pointcutExpression will be initialized lazily by checkReadyToMatch()
<del> this.shadowMatchCache = new ConcurrentHashMap<>(32);
<del> }
<del>
<del>
<ide> private static class DefensiveShadowMatch implements ShadowMatch {
<ide>
<ide> private final ShadowMatch primary;
<ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @since 2.0
<ide> */
<ide> @SuppressWarnings("serial")
<del>class InstantiationModelAwarePointcutAdvisorImpl
<add>final class InstantiationModelAwarePointcutAdvisorImpl
<ide> implements InstantiationModelAwarePointcutAdvisor, AspectJPrecedenceInformation, Serializable {
<ide>
<ide> private static final Advice EMPTY_ADVICE = new Advice() {};
<ide> private void readObject(ObjectInputStream inputStream) throws IOException, Class
<ide> * Note that this is a <i>dynamic</i> pointcut. Otherwise it might
<ide> * be optimized out if it does not at first match statically.
<ide> */
<del> private class PerTargetInstantiationModelPointcut extends DynamicMethodMatcherPointcut {
<add> private final class PerTargetInstantiationModelPointcut extends DynamicMethodMatcherPointcut {
<ide>
<ide> private final AspectJExpressionPointcut declaredPointcut;
<ide>
<ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/NotAnAtAspectException.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class NotAnAtAspectException extends AopConfigException {
<ide>
<del> private Class<?> nonAspectClass;
<add> private final Class<?> nonAspectClass;
<ide>
<ide>
<ide> /**
<ide><path>spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/ProxyCreationContext.java
<ide> * @author Ramnivas Laddad
<ide> * @since 2.5
<ide> */
<del>public class ProxyCreationContext {
<add>public final class ProxyCreationContext {
<ide>
<ide> /** ThreadLocal holding the current proxied bean name during Advisor matching. */
<ide> private static final ThreadLocal<String> currentProxiedBeanName =
<ide> new NamedThreadLocal<>("Name of currently proxied bean");
<ide>
<ide>
<add> private ProxyCreationContext() {
<add> }
<add>
<add>
<ide> /**
<ide> * Return the name of the currently proxied bean instance.
<ide> * @return the name of the bean, or {@code null} if none available
<ide><path>spring-aop/src/main/java/org/springframework/aop/interceptor/ExposeInvocationInterceptor.java
<ide> * @author Juergen Hoeller
<ide> */
<ide> @SuppressWarnings("serial")
<del>public class ExposeInvocationInterceptor implements MethodInterceptor, PriorityOrdered, Serializable {
<add>public final class ExposeInvocationInterceptor implements MethodInterceptor, PriorityOrdered, Serializable {
<ide>
<ide> /** Singleton instance of this class. */
<ide> public static final ExposeInvocationInterceptor INSTANCE = new ExposeInvocationInterceptor();
<ide><path>spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java
<ide> * @author Rod Johnson
<ide> * @author Juergen Hoeller
<ide> */
<del>public class EmptyTargetSource implements TargetSource, Serializable {
<add>public final class EmptyTargetSource implements TargetSource, Serializable {
<ide>
<ide> /** use serialVersionUID from Spring 1.2 for interoperability. */
<ide> private static final long serialVersionUID = 3680494563553489691L;
<ide><path>spring-aspects/src/main/java/org/springframework/cache/aspectj/AnyThrow.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> *
<ide> * @author Stephane Nicoll
<ide> */
<del>class AnyThrow {
<add>final class AnyThrow {
<add>
<add> private AnyThrow() {
<add> }
<add>
<ide>
<ide> static void throwUnchecked(Throwable e) {
<ide> AnyThrow.<RuntimeException>throwAny(e);
<ide><path>spring-beans/src/main/java/org/springframework/beans/BeanInstantiationException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class BeanInstantiationException extends FatalBeanException {
<ide>
<del> private Class<?> beanClass;
<add> private final Class<?> beanClass;
<ide>
<ide> @Nullable
<del> private Constructor<?> constructor;
<add> private final Constructor<?> constructor;
<ide>
<ide> @Nullable
<del> private Method constructingMethod;
<add> private final Method constructingMethod;
<ide>
<ide>
<ide> /**
<ide> public BeanInstantiationException(Class<?> beanClass, String msg) {
<ide> public BeanInstantiationException(Class<?> beanClass, String msg, @Nullable Throwable cause) {
<ide> super("Failed to instantiate [" + beanClass.getName() + "]: " + msg, cause);
<ide> this.beanClass = beanClass;
<add> this.constructor = null;
<add> this.constructingMethod = null;
<ide> }
<ide>
<ide> /**
<ide> public BeanInstantiationException(Constructor<?> constructor, String msg, @Nulla
<ide> super("Failed to instantiate [" + constructor.getDeclaringClass().getName() + "]: " + msg, cause);
<ide> this.beanClass = constructor.getDeclaringClass();
<ide> this.constructor = constructor;
<add> this.constructingMethod = null;
<ide> }
<ide>
<ide> /**
<ide> public BeanInstantiationException(Constructor<?> constructor, String msg, @Nulla
<ide> public BeanInstantiationException(Method constructingMethod, String msg, @Nullable Throwable cause) {
<ide> super("Failed to instantiate [" + constructingMethod.getReturnType().getName() + "]: " + msg, cause);
<ide> this.beanClass = constructingMethod.getReturnType();
<add> this.constructor = null;
<ide> this.constructingMethod = constructingMethod;
<ide> }
<ide>
<ide><path>spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java
<ide> * @see #clearClassLoader(ClassLoader)
<ide> * @see #forClass(Class)
<ide> */
<del>public class CachedIntrospectionResults {
<add>public final class CachedIntrospectionResults {
<ide>
<ide> /**
<ide> * System property that instructs Spring to use the {@link Introspector#IGNORE_ALL_BEANINFO}
<ide><path>spring-beans/src/main/java/org/springframework/beans/InvalidPropertyException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class InvalidPropertyException extends FatalBeanException {
<ide>
<del> private Class<?> beanClass;
<add> private final Class<?> beanClass;
<ide>
<del> private String propertyName;
<add> private final String propertyName;
<ide>
<ide>
<ide> /**
<ide><path>spring-beans/src/main/java/org/springframework/beans/NotWritablePropertyException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class NotWritablePropertyException extends InvalidPropertyException {
<ide>
<ide> @Nullable
<del> private String[] possibleMatches;
<add> private final String[] possibleMatches;
<ide>
<ide>
<ide> /**
<ide> public NotWritablePropertyException(Class<?> beanClass, String propertyName) {
<ide> super(beanClass, propertyName,
<ide> "Bean property '" + propertyName + "' is not writable or has an invalid setter method: " +
<ide> "Does the return type of the getter match the parameter type of the setter?");
<add> this.possibleMatches = null;
<ide> }
<ide>
<ide> /**
<ide> public NotWritablePropertyException(Class<?> beanClass, String propertyName) {
<ide> */
<ide> public NotWritablePropertyException(Class<?> beanClass, String propertyName, String msg) {
<ide> super(beanClass, propertyName, msg);
<add> this.possibleMatches = null;
<ide> }
<ide>
<ide> /**
<ide> public NotWritablePropertyException(Class<?> beanClass, String propertyName, Str
<ide> */
<ide> public NotWritablePropertyException(Class<?> beanClass, String propertyName, String msg, Throwable cause) {
<ide> super(beanClass, propertyName, msg, cause);
<add> this.possibleMatches = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-beans/src/main/java/org/springframework/beans/PropertyAccessException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public abstract class PropertyAccessException extends BeansException {
<ide>
<ide> @Nullable
<del> private transient PropertyChangeEvent propertyChangeEvent;
<add> private final PropertyChangeEvent propertyChangeEvent;
<ide>
<ide>
<ide> /**
<ide> public PropertyAccessException(PropertyChangeEvent propertyChangeEvent, String m
<ide> */
<ide> public PropertyAccessException(String msg, @Nullable Throwable cause) {
<ide> super(msg, cause);
<add> this.propertyChangeEvent = null;
<ide> }
<ide>
<ide>
<ide><path>spring-beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java
<ide> public class PropertyBatchUpdateException extends BeansException {
<ide>
<ide> /** List of PropertyAccessException objects. */
<del> private PropertyAccessException[] propertyAccessExceptions;
<add> private final PropertyAccessException[] propertyAccessExceptions;
<ide>
<ide>
<ide> /**
<ide><path>spring-beans/src/main/java/org/springframework/beans/PropertyDescriptorUtils.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Chris Beams
<ide> * @author Juergen Hoeller
<ide> */
<del>class PropertyDescriptorUtils {
<add>final class PropertyDescriptorUtils {
<add>
<add>
<add> private PropertyDescriptorUtils() {
<add> }
<add>
<ide>
<ide> /**
<ide> * See {@link java.beans.FeatureDescriptor}.
<ide><path>spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java
<ide> private void addStrippedPropertyPaths(List<String> strippedPaths, String nestedP
<ide> * Holder for a registered custom editor with property name.
<ide> * Keeps the PropertyEditor itself plus the type it was registered for.
<ide> */
<del> private static class CustomEditorHolder {
<add> private static final class CustomEditorHolder {
<ide>
<ide> private final PropertyEditor propertyEditor;
<ide>
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java
<ide> public class BeanCreationException extends FatalBeanException {
<ide>
<ide> @Nullable
<del> private String beanName;
<add> private final String beanName;
<ide>
<ide> @Nullable
<del> private String resourceDescription;
<add> private final String resourceDescription;
<ide>
<ide> @Nullable
<ide> private List<Throwable> relatedCauses;
<ide> public class BeanCreationException extends FatalBeanException {
<ide> */
<ide> public BeanCreationException(String msg) {
<ide> super(msg);
<add> this.beanName = null;
<add> this.resourceDescription = null;
<ide> }
<ide>
<ide> /**
<ide> public BeanCreationException(String msg) {
<ide> */
<ide> public BeanCreationException(String msg, Throwable cause) {
<ide> super(msg, cause);
<add> this.beanName = null;
<add> this.resourceDescription = null;
<ide> }
<ide>
<ide> /**
<ide> public BeanCreationException(String msg, Throwable cause) {
<ide> public BeanCreationException(String beanName, String msg) {
<ide> super("Error creating bean with name '" + beanName + "': " + msg);
<ide> this.beanName = beanName;
<add> this.resourceDescription = null;
<ide> }
<ide>
<ide> /**
<ide> public BeanCreationException(@Nullable String resourceDescription, @Nullable Str
<ide> (resourceDescription != null ? " defined in " + resourceDescription : "") + ": " + msg);
<ide> this.resourceDescription = resourceDescription;
<ide> this.beanName = beanName;
<add> this.relatedCauses = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/BeanDefinitionStoreException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class BeanDefinitionStoreException extends FatalBeanException {
<ide>
<ide> @Nullable
<del> private String resourceDescription;
<add> private final String resourceDescription;
<ide>
<ide> @Nullable
<del> private String beanName;
<add> private final String beanName;
<ide>
<ide>
<ide> /**
<ide> public class BeanDefinitionStoreException extends FatalBeanException {
<ide> */
<ide> public BeanDefinitionStoreException(String msg) {
<ide> super(msg);
<add> this.resourceDescription = null;
<add> this.beanName = null;
<ide> }
<ide>
<ide> /**
<ide> public BeanDefinitionStoreException(String msg) {
<ide> */
<ide> public BeanDefinitionStoreException(String msg, @Nullable Throwable cause) {
<ide> super(msg, cause);
<add> this.resourceDescription = null;
<add> this.beanName = null;
<ide> }
<ide>
<ide> /**
<ide> public BeanDefinitionStoreException(String msg, @Nullable Throwable cause) {
<ide> public BeanDefinitionStoreException(@Nullable String resourceDescription, String msg) {
<ide> super(msg);
<ide> this.resourceDescription = resourceDescription;
<add> this.beanName = null;
<ide> }
<ide>
<ide> /**
<ide> public BeanDefinitionStoreException(@Nullable String resourceDescription, String
<ide> public BeanDefinitionStoreException(@Nullable String resourceDescription, String msg, @Nullable Throwable cause) {
<ide> super(msg, cause);
<ide> this.resourceDescription = resourceDescription;
<add> this.beanName = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/BeanNotOfRequiredTypeException.java
<ide> public class BeanNotOfRequiredTypeException extends BeansException {
<ide>
<ide> /** The name of the instance that was of the wrong type. */
<del> private String beanName;
<add> private final String beanName;
<ide>
<ide> /** The required type. */
<del> private Class<?> requiredType;
<add> private final Class<?> requiredType;
<ide>
<ide> /** The offending type. */
<del> private Class<?> actualType;
<add> private final Class<?> actualType;
<ide>
<ide>
<ide> /**
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/CannotLoadBeanClassException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class CannotLoadBeanClassException extends FatalBeanException {
<ide>
<ide> @Nullable
<del> private String resourceDescription;
<add> private final String resourceDescription;
<ide>
<ide> @Nullable
<del> private String beanName;
<add> private final String beanName;
<ide>
<ide> @Nullable
<del> private String beanClassName;
<add> private final String beanClassName;
<ide>
<ide>
<ide> /**
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/NoSuchBeanDefinitionException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class NoSuchBeanDefinitionException extends BeansException {
<ide>
<ide> @Nullable
<del> private String beanName;
<add> private final String beanName;
<ide>
<ide> @Nullable
<del> private ResolvableType resolvableType;
<add> private final ResolvableType resolvableType;
<ide>
<ide>
<ide> /**
<ide> public class NoSuchBeanDefinitionException extends BeansException {
<ide> public NoSuchBeanDefinitionException(String name) {
<ide> super("No bean named '" + name + "' available");
<ide> this.beanName = name;
<add> this.resolvableType = null;
<ide> }
<ide>
<ide> /**
<ide> public NoSuchBeanDefinitionException(String name) {
<ide> public NoSuchBeanDefinitionException(String name, String message) {
<ide> super("No bean named '" + name + "' available: " + message);
<ide> this.beanName = name;
<add> this.resolvableType = null;
<ide> }
<ide>
<ide> /**
<ide> public NoSuchBeanDefinitionException(Class<?> type, String message) {
<ide> */
<ide> public NoSuchBeanDefinitionException(ResolvableType type) {
<ide> super("No qualifying bean of type '" + type + "' available");
<add> this.beanName = null;
<ide> this.resolvableType = type;
<ide> }
<ide>
<ide> public NoSuchBeanDefinitionException(ResolvableType type) {
<ide> */
<ide> public NoSuchBeanDefinitionException(ResolvableType type, String message) {
<ide> super("No qualifying bean of type '" + type + "' available: " + message);
<add> this.beanName = null;
<ide> this.resolvableType = type;
<ide> }
<ide>
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/NoUniqueBeanDefinitionException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class NoUniqueBeanDefinitionException extends NoSuchBeanDefinitionException {
<ide>
<del> private int numberOfBeansFound;
<add> private final int numberOfBeansFound;
<ide>
<ide> @Nullable
<del> private Collection<String> beanNamesFound;
<add> private final Collection<String> beanNamesFound;
<ide>
<ide>
<ide> /**
<ide> public class NoUniqueBeanDefinitionException extends NoSuchBeanDefinitionExcepti
<ide> public NoUniqueBeanDefinitionException(Class<?> type, int numberOfBeansFound, String message) {
<ide> super(type, message);
<ide> this.numberOfBeansFound = numberOfBeansFound;
<add> this.beanNamesFound = null;
<ide> }
<ide>
<ide> /**
<ide> public NoUniqueBeanDefinitionException(Class<?> type, int numberOfBeansFound, St
<ide> * @param beanNamesFound the names of all matching beans (as a Collection)
<ide> */
<ide> public NoUniqueBeanDefinitionException(Class<?> type, Collection<String> beanNamesFound) {
<del> this(type, beanNamesFound.size(), "expected single matching bean but found " + beanNamesFound.size() + ": " +
<add> super(type, "expected single matching bean but found " + beanNamesFound.size() + ": " +
<ide> StringUtils.collectionToCommaDelimitedString(beanNamesFound));
<add> this.numberOfBeansFound = beanNamesFound.size();
<ide> this.beanNamesFound = beanNamesFound;
<ide> }
<ide>
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/UnsatisfiedDependencyException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class UnsatisfiedDependencyException extends BeanCreationException {
<ide>
<ide> @Nullable
<del> private InjectionPoint injectionPoint;
<add> private final InjectionPoint injectionPoint;
<ide>
<ide>
<ide> /**
<ide> public UnsatisfiedDependencyException(
<ide> super(resourceDescription, beanName,
<ide> "Unsatisfied dependency expressed through bean property '" + propertyName + "'" +
<ide> (StringUtils.hasLength(msg) ? ": " + msg : ""));
<add> this.injectionPoint = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public String resolveStringValue(String strVal) throws BeansException {
<ide> }
<ide>
<ide>
<del> private class PropertyPlaceholderConfigurerResolver implements PlaceholderResolver {
<add> private final class PropertyPlaceholderConfigurerResolver implements PlaceholderResolver {
<ide>
<ide> private final Properties props;
<ide>
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Juergen Hoeller
<ide> * @since 2.0
<ide> */
<del>public class BeanDefinitionBuilder {
<add>public final class BeanDefinitionBuilder {
<ide>
<ide> /**
<ide> * Create a new {@code BeanDefinitionBuilder} used to construct a {@link GenericBeanDefinition}.
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @see PropertiesBeanDefinitionReader
<ide> * @see org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader
<ide> */
<del>public class BeanDefinitionReaderUtils {
<add>public final class BeanDefinitionReaderUtils {
<ide>
<ide> /**
<ide> * Separator for generated bean names. If a class name or parent name is not
<ide> public class BeanDefinitionReaderUtils {
<ide> public static final String GENERATED_BEAN_NAME_SEPARATOR = BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR;
<ide>
<ide>
<add> private BeanDefinitionReaderUtils() {
<add> }
<add>
<add>
<ide> /**
<ide> * Create a new GenericBeanDefinition for the given parent name and class name,
<ide> * eagerly loading the bean class if a ClassLoader has been specified.
<ide><path>spring-context-support/src/main/java/org/springframework/mail/MailSendException.java
<ide> public class MailSendException extends MailException {
<ide> private final transient Map<Object, Exception> failedMessages;
<ide>
<ide> @Nullable
<del> private Exception[] messageExceptions;
<add> private final Exception[] messageExceptions;
<ide>
<ide>
<ide> /**
<ide> public MailSendException(String msg) {
<ide> public MailSendException(String msg, @Nullable Throwable cause) {
<ide> super(msg, cause);
<ide> this.failedMessages = new LinkedHashMap<>();
<add> this.messageExceptions = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-context/src/main/java/org/springframework/cache/config/CacheManagementConfigUtils.java
<ide> * @author Juergen Hoeller
<ide> * @since 4.1
<ide> */
<del>public class CacheManagementConfigUtils {
<add>public final class CacheManagementConfigUtils {
<ide>
<ide> /**
<ide> * The name of the cache advisor bean.
<ide> public class CacheManagementConfigUtils {
<ide> public static final String JCACHE_ASPECT_BEAN_NAME =
<ide> "org.springframework.cache.config.internalJCacheAspect";
<ide>
<add>
<add> private CacheManagementConfigUtils() {
<add> }
<add>
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java
<ide> * @see org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor
<ide> * @see org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
<ide> */
<del>public class AnnotationConfigUtils {
<add>public final class AnnotationConfigUtils {
<ide>
<ide> /**
<ide> * The bean name of the internally managed Configuration annotation processor.
<ide> public class AnnotationConfigUtils {
<ide> ClassUtils.isPresent(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, AnnotationConfigUtils.class.getClassLoader());
<ide>
<ide>
<add> private AnnotationConfigUtils() {
<add> }
<add>
<add>
<ide> /**
<ide> * Register all relevant annotation post processors in the given registry.
<ide> * @param registry the registry to operate on
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/BeanAnnotationHelper.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Juergen Hoeller
<ide> * @since 3.1
<ide> */
<del>class BeanAnnotationHelper {
<add>final class BeanAnnotationHelper {
<add>
<add>
<add> private BeanAnnotationHelper() {
<add> }
<add>
<ide>
<ide> public static boolean isBeanAnnotated(Method method) {
<ide> return AnnotatedElementUtils.hasAnnotation(method, Bean.class);
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/ScopedProxyCreator.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @since 3.0
<ide> * @see org.springframework.aop.scope.ScopedProxyUtils#createScopedProxy
<ide> */
<del>class ScopedProxyCreator {
<add>final class ScopedProxyCreator {
<add>
<add>
<add> private ScopedProxyCreator() {
<add> }
<add>
<ide>
<ide> public static BeanDefinitionHolder createScopedProxy(
<ide> BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry, boolean proxyTargetClass) {
<ide><path>spring-context/src/main/java/org/springframework/context/index/CandidateComponentsIndexLoader.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Stephane Nicoll
<ide> * @since 5.0
<ide> */
<del>public class CandidateComponentsIndexLoader {
<add>public final class CandidateComponentsIndexLoader {
<ide>
<ide> /**
<ide> * The location to look for components.
<ide> public class CandidateComponentsIndexLoader {
<ide> new ConcurrentReferenceHashMap<>();
<ide>
<ide>
<add> private CandidateComponentsIndexLoader() {
<add> }
<add>
<add>
<ide> /**
<ide> * Load and instantiate the {@link CandidateComponentsIndex} from
<ide> * {@value #COMPONENTS_RESOURCE_LOCATION}, using the given class loader. If no
<ide><path>spring-context/src/main/java/org/springframework/context/support/PostProcessorRegistrationDelegate.java
<ide> * @author Juergen Hoeller
<ide> * @since 4.0
<ide> */
<del>class PostProcessorRegistrationDelegate {
<add>final class PostProcessorRegistrationDelegate {
<add>
<add>
<add> private PostProcessorRegistrationDelegate() {
<add> }
<add>
<ide>
<ide> public static void invokeBeanFactoryPostProcessors(
<ide> ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
<ide><path>spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeContextHolder.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public final class JodaTimeContextHolder {
<ide> new NamedThreadLocal<>("JodaTimeContext");
<ide>
<ide>
<add> private JodaTimeContextHolder() {
<add> }
<add>
<add>
<ide> /**
<ide> * Reset the JodaTimeContext for the current thread.
<ide> */
<ide><path>spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeConverters.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> final class JodaTimeConverters {
<ide>
<add>
<add> private JodaTimeConverters() {
<add> }
<add>
<add>
<ide> /**
<ide> * Install the converters into the converter registry.
<ide> * @param registry the converter registry
<ide><path>spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeContextHolder.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public final class DateTimeContextHolder {
<ide> new NamedThreadLocal<>("DateTimeContext");
<ide>
<ide>
<add> private DateTimeContextHolder() {
<add> }
<add>
<add>
<ide> /**
<ide> * Reset the DateTimeContext for the current thread.
<ide> */
<ide><path>spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeConverters.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> final class DateTimeConverters {
<ide>
<add>
<add> private DateTimeConverters() {
<add> }
<add>
<add>
<ide> /**
<ide> * Install the converters into the converter registry.
<ide> * @param registry the converter registry
<ide><path>spring-context/src/main/java/org/springframework/jmx/support/ObjectNameManager.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @since 1.2
<ide> * @see javax.management.ObjectName#getInstance(String)
<ide> */
<del>public class ObjectNameManager {
<add>public final class ObjectNameManager {
<add>
<add>
<add> private ObjectNameManager() {
<add> }
<add>
<ide>
<ide> /**
<ide> * Retrieve the {@code ObjectName} instance corresponding to the supplied name.
<ide><path>spring-context/src/main/java/org/springframework/scheduling/config/TaskManagementConfigUtils.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Juergen Hoeller
<ide> * @since 4.1
<ide> */
<del>public class TaskManagementConfigUtils {
<add>public final class TaskManagementConfigUtils {
<ide>
<ide> /**
<ide> * The bean name of the internally managed Scheduled annotation processor.
<ide> public class TaskManagementConfigUtils {
<ide> public static final String ASYNC_EXECUTION_ASPECT_BEAN_NAME =
<ide> "org.springframework.scheduling.config.internalAsyncExecutionAspect";
<ide>
<add>
<add> private TaskManagementConfigUtils() {
<add> }
<add>
<add>
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/scripting/ScriptCompilationException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class ScriptCompilationException extends NestedRuntimeException {
<ide>
<ide> @Nullable
<del> private ScriptSource scriptSource;
<add> private final ScriptSource scriptSource;
<ide>
<ide>
<ide> /**
<ide> public class ScriptCompilationException extends NestedRuntimeException {
<ide> */
<ide> public ScriptCompilationException(String msg) {
<ide> super(msg);
<add> this.scriptSource = null;
<ide> }
<ide>
<ide> /**
<ide> public ScriptCompilationException(String msg) {
<ide> */
<ide> public ScriptCompilationException(String msg, Throwable cause) {
<ide> super(msg, cause);
<add> this.scriptSource = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptUtils.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private boolean isProxyForSameBshObject(Object other) {
<ide> * Exception to be thrown on script execution failure.
<ide> */
<ide> @SuppressWarnings("serial")
<del> public static class BshExecutionException extends NestedRuntimeException {
<add> public static final class BshExecutionException extends NestedRuntimeException {
<ide>
<ide> private BshExecutionException(EvalError ex) {
<ide> super("BeanShell script execution failed", ex);
<ide><path>spring-core/src/main/java/org/springframework/core/ReactiveTypeDescriptor.java
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> */
<del>public class ReactiveTypeDescriptor {
<add>public final class ReactiveTypeDescriptor {
<ide>
<ide> private final Class<?> reactiveType;
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/SpringVersion.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Juergen Hoeller
<ide> * @since 1.1
<ide> */
<del>public class SpringVersion {
<add>public final class SpringVersion {
<add>
<add>
<add> private SpringVersion() {
<add> }
<add>
<ide>
<ide> /**
<ide> * Return the full version string of the present Spring codebase,
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java
<ide> private List<A> getValue(AnnotatedElement element, Annotation annotation) {
<ide> * @see #getAttributeAliasNames
<ide> * @see #getAttributeOverrideName
<ide> */
<del> private static class AliasDescriptor {
<add> private static final class AliasDescriptor {
<ide>
<ide> private final Method sourceAttribute;
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/codec/CharSequenceEncoder.java
<ide> * @since 5.0
<ide> * @see StringDecoder
<ide> */
<del>public class CharSequenceEncoder extends AbstractEncoder<CharSequence> {
<add>public final class CharSequenceEncoder extends AbstractEncoder<CharSequence> {
<ide>
<ide> /**
<ide> * The default charset used by the encoder.
<ide><path>spring-core/src/main/java/org/springframework/core/codec/StringDecoder.java
<ide> * @since 5.0
<ide> * @see CharSequenceEncoder
<ide> */
<del>public class StringDecoder extends AbstractDataBufferDecoder<String> {
<add>public final class StringDecoder extends AbstractDataBufferDecoder<String> {
<ide>
<ide> private static final DataBuffer END_FRAME = new DefaultDataBufferFactory().wrap(new byte[0]);
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/env/ProfilesParser.java
<ide> * @author Phillip Webb
<ide> * @since 5.1
<ide> */
<del>class ProfilesParser {
<add>final class ProfilesParser {
<add>
<add> private ProfilesParser() {
<add> }
<ide>
<ide> static Profiles parse(String... expressions) {
<ide> Assert.notEmpty(expressions, "Must specify at least one profile");
<ide><path>spring-core/src/main/java/org/springframework/util/ReflectionUtils.java
<ide> public abstract class ReflectionUtils {
<ide>
<ide> private static final Field[] NO_FIELDS = {};
<ide>
<add> /**
<add> * Pre-built FieldFilter that matches all non-static, non-final fields.
<add> */
<add> public static final FieldFilter COPYABLE_FIELDS =
<add> field -> !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
<add>
<add>
<add> /**
<add> * Pre-built MethodFilter that matches all non-bridge methods.
<add> */
<add> public static final MethodFilter NON_BRIDGED_METHODS =
<add> (method -> !method.isBridge());
<add>
<add>
<add> /**
<add> * Pre-built MethodFilter that matches all non-bridge non-synthetic methods
<add> * which are not declared on {@code java.lang.Object}.
<add> */
<add> public static final MethodFilter USER_DECLARED_METHODS =
<add> (method -> (!method.isBridge() && !method.isSynthetic() && method.getDeclaringClass() != Object.class));
<add>
<ide>
<ide> /**
<ide> * Cache for {@link Class#getDeclaredMethods()} plus equivalent default methods
<ide> public interface FieldFilter {
<ide> }
<ide>
<ide>
<del> /**
<del> * Pre-built FieldFilter that matches all non-static, non-final fields.
<del> */
<del> public static final FieldFilter COPYABLE_FIELDS =
<del> field -> !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
<del>
<del>
<del> /**
<del> * Pre-built MethodFilter that matches all non-bridge methods.
<del> */
<del> public static final MethodFilter NON_BRIDGED_METHODS =
<del> (method -> !method.isBridge());
<del>
<del>
<del> /**
<del> * Pre-built MethodFilter that matches all non-bridge non-synthetic methods
<del> * which are not declared on {@code java.lang.Object}.
<del> */
<del> public static final MethodFilter USER_DECLARED_METHODS =
<del> (method -> (!method.isBridge() && !method.isSynthetic() && method.getDeclaringClass() != Object.class));
<del>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/ExpressionException.java
<ide> public class ExpressionException extends RuntimeException {
<ide>
<ide> @Nullable
<del> protected String expressionString;
<add> protected final String expressionString;
<ide>
<ide> protected int position; // -1 if not known; should be known in all reasonable cases
<ide>
<ide> public class ExpressionException extends RuntimeException {
<ide> */
<ide> public ExpressionException(String message) {
<ide> super(message);
<add> this.expressionString = null;
<add> this.position = 0;
<ide> }
<ide>
<ide> /**
<ide> public ExpressionException(String message) {
<ide> */
<ide> public ExpressionException(String message, Throwable cause) {
<ide> super(message, cause);
<add> this.expressionString = null;
<add> this.position = 0;
<ide> }
<ide>
<ide> /**
<ide> public ExpressionException(@Nullable String expressionString, int position, Stri
<ide> */
<ide> public ExpressionException(int position, String message) {
<ide> super(message);
<add> this.expressionString = null;
<ide> this.position = position;
<ide> }
<ide>
<ide> public ExpressionException(int position, String message) {
<ide> */
<ide> public ExpressionException(int position, String message, Throwable cause) {
<ide> super(message, cause);
<add> this.expressionString = null;
<ide> this.position = position;
<ide> }
<ide>
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/CodeFlow.java
<ide> public static void insertNumericUnboxOrPrimitiveTypeCoercion(
<ide> }
<ide> }
<ide>
<add> public static final String toBoxedDescriptor(String primitiveDescriptor) {
<add> switch (primitiveDescriptor.charAt(0)) {
<add> case 'I': return "Ljava/lang/Integer";
<add> case 'J': return "Ljava/lang/Long";
<add> case 'F': return "Ljava/lang/Float";
<add> case 'D': return "Ljava/lang/Double";
<add> case 'B': return "Ljava/lang/Byte";
<add> case 'C': return "Ljava/lang/Character";
<add> case 'S': return "Ljava/lang/Short";
<add> case 'Z': return "Ljava/lang/Boolean";
<add> default:
<add> throw new IllegalArgumentException("Unexpected non primitive descriptor "+primitiveDescriptor);
<add> }
<add> }
<add>
<ide>
<ide> /**
<ide> * Interface used to generate fields.
<ide> public interface ClinitAdder {
<ide> void generateCode(MethodVisitor mv, CodeFlow codeflow);
<ide> }
<ide>
<del> public static String toBoxedDescriptor(String primitiveDescriptor) {
<del> switch (primitiveDescriptor.charAt(0)) {
<del> case 'I': return "Ljava/lang/Integer";
<del> case 'J': return "Ljava/lang/Long";
<del> case 'F': return "Ljava/lang/Float";
<del> case 'D': return "Ljava/lang/Double";
<del> case 'B': return "Ljava/lang/Byte";
<del> case 'C': return "Ljava/lang/Character";
<del> case 'S': return "Ljava/lang/Short";
<del> case 'Z': return "Ljava/lang/Boolean";
<del> default:
<del> throw new IllegalArgumentException("Unexpected non primitive descriptor "+primitiveDescriptor);
<del> }
<del> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Operator.java
<ide> public abstract class Operator extends SpelNodeImpl {
<ide>
<ide> private final String operatorName;
<del>
<add>
<ide> // The descriptors of the runtime operand values are used if the discovered declared
<ide> // descriptors are not providing enough information (for example a generic type
<ide> // whose accessors seem to only be returning 'Object' - the actual descriptors may
<ide> protected boolean isCompilableOperatorUsingNumerics() {
<ide> return (dc.areNumbers && dc.areCompatible);
<ide> }
<ide>
<del> /**
<del> * Numeric comparison operators share very similar generated code, only differing in
<add> /**
<add> * Numeric comparison operators share very similar generated code, only differing in
<ide> * two comparison instructions.
<ide> */
<ide> protected void generateComparisonCode(MethodVisitor mv, CodeFlow cf, int compInstruction1, int compInstruction2) {
<ide> SpelNodeImpl left = getLeftOperand();
<ide> SpelNodeImpl right = getRightOperand();
<ide> String leftDesc = left.exitTypeDescriptor;
<ide> String rightDesc = right.exitTypeDescriptor;
<del>
<add>
<ide> boolean unboxLeft = !CodeFlow.isPrimitive(leftDesc);
<ide> boolean unboxRight = !CodeFlow.isPrimitive(rightDesc);
<ide> DescriptorComparison dc = DescriptorComparison.checkNumericCompatibility(
<ide> leftDesc, rightDesc, this.leftActualDescriptor, this.rightActualDescriptor);
<ide> char targetType = dc.compatibleType; // CodeFlow.toPrimitiveTargetDesc(leftDesc);
<del>
<add>
<ide> cf.enterCompilationScope();
<ide> left.generateCode(mv, cf);
<ide> cf.exitCompilationScope();
<ide> if (unboxLeft) {
<ide> CodeFlow.insertUnboxInsns(mv, targetType, leftDesc);
<ide> }
<del>
<add>
<ide> cf.enterCompilationScope();
<ide> right.generateCode(mv, cf);
<ide> cf.exitCompilationScope();
<ide> protected void generateComparisonCode(MethodVisitor mv, CodeFlow cf, int compIns
<ide> mv.visitJumpInsn(compInstruction1, elseTarget);
<ide> }
<ide> else if (targetType == 'F') {
<del> mv.visitInsn(FCMPG);
<add> mv.visitInsn(FCMPG);
<ide> mv.visitJumpInsn(compInstruction1, elseTarget);
<ide> }
<ide> else if (targetType == 'J') {
<del> mv.visitInsn(LCMP);
<add> mv.visitInsn(LCMP);
<ide> mv.visitJumpInsn(compInstruction1, elseTarget);
<ide> }
<ide> else if (targetType == 'I') {
<ide> else if (leftNumber instanceof Byte || rightNumber instanceof Byte) {
<ide>
<ide> return false;
<ide> }
<del>
<add>
<ide>
<ide> /**
<ide> * A descriptor comparison encapsulates the result of comparing descriptor
<ide> * for two operands and describes at what level they are compatible.
<ide> */
<del> protected static class DescriptorComparison {
<add> protected static final class DescriptorComparison {
<ide>
<ide> static final DescriptorComparison NOT_NUMBERS = new DescriptorComparison(false, false, ' ');
<ide>
<ide> private DescriptorComparison(boolean areNumbers, boolean areCompatible, char com
<ide> this.areCompatible = areCompatible;
<ide> this.compatibleType = compatibleType;
<ide> }
<del>
<add>
<ide> /**
<ide> * Return an object that indicates whether the input descriptors are compatible.
<ide> * <p>A declared descriptor is what could statically be determined (e.g. from looking
<ide> public static DescriptorComparison checkNumericCompatibility(
<ide>
<ide> boolean leftNumeric = CodeFlow.isPrimitiveOrUnboxableSupportedNumberOrBoolean(ld);
<ide> boolean rightNumeric = CodeFlow.isPrimitiveOrUnboxableSupportedNumberOrBoolean(rd);
<del>
<add>
<ide> // If the declared descriptors aren't providing the information, try the actual descriptors
<ide> if (!leftNumeric && !ObjectUtils.nullSafeEquals(ld, leftActualDescriptor)) {
<ide> ld = leftActualDescriptor;
<ide> public static DescriptorComparison checkNumericCompatibility(
<ide> rd = rightActualDescriptor;
<ide> rightNumeric = CodeFlow.isPrimitiveOrUnboxableSupportedNumberOrBoolean(rd);
<ide> }
<del>
<add>
<ide> if (leftNumeric && rightNumeric) {
<ide> if (CodeFlow.areBoxingCompatible(ld, rd)) {
<ide> return new DescriptorComparison(true, true, CodeFlow.toPrimitiveTargetDesc(ld));
<ide> public static DescriptorComparison checkNumericCompatibility(
<ide> }
<ide> else {
<ide> return DescriptorComparison.NOT_NUMBERS;
<del> }
<add> }
<ide> }
<ide> }
<ide>
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelCompiler.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Andy Clement
<ide> * @since 4.1
<ide> */
<del>public class SpelCompiler implements Opcodes {
<add>public final class SpelCompiler implements Opcodes {
<ide>
<ide> private static final Log logger = LogFactory.getLog(SpelCompiler.class);
<ide>
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/BooleanTypedValue.java
<ide> * @author Andy Clement
<ide> * @since 3.0
<ide> */
<del>public class BooleanTypedValue extends TypedValue {
<add>public final class BooleanTypedValue extends TypedValue {
<ide>
<ide> /**
<ide> * True.
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/DataBindingMethodResolver.java
<ide> * @see #forInstanceMethodInvocation()
<ide> * @see DataBindingPropertyAccessor
<ide> */
<del>public class DataBindingMethodResolver extends ReflectiveMethodResolver {
<add>public final class DataBindingMethodResolver extends ReflectiveMethodResolver {
<ide>
<ide> private DataBindingMethodResolver() {
<ide> super();
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/DataBindingPropertyAccessor.java
<ide> * @see StandardEvaluationContext
<ide> * @see ReflectivePropertyAccessor
<ide> */
<del>public class DataBindingPropertyAccessor extends ReflectivePropertyAccessor {
<add>public final class DataBindingPropertyAccessor extends ReflectivePropertyAccessor {
<ide>
<ide> /**
<ide> * Create a new property accessor for reading and possibly also writing.
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/SimpleEvaluationContext.java
<ide> * @see StandardTypeConverter
<ide> * @see DataBindingPropertyAccessor
<ide> */
<del>public class SimpleEvaluationContext implements EvaluationContext {
<add>public final class SimpleEvaluationContext implements EvaluationContext {
<ide>
<ide> private static final TypeLocator typeNotFoundTypeLocator = typeName -> {
<ide> throw new SpelEvaluationException(SpelMessage.TYPE_NOT_FOUND, typeName);
<ide><path>spring-instrument/src/main/java/org/springframework/instrument/InstrumentationSavingAgent.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @since 2.0
<ide> * @see org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver
<ide> */
<del>public class InstrumentationSavingAgent {
<add>public final class InstrumentationSavingAgent {
<ide>
<ide> private static volatile Instrumentation instrumentation;
<ide>
<ide>
<add> private InstrumentationSavingAgent() {
<add> }
<add>
<add>
<ide> /**
<ide> * Save the {@link Instrumentation} interface exposed by the JVM.
<ide> */
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/BadSqlGrammarException.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class BadSqlGrammarException extends InvalidDataAccessResourceUsageException {
<ide>
<del> private String sql;
<add> private final String sql;
<ide>
<ide>
<ide> /**
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/IncorrectResultSetColumnCountException.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class IncorrectResultSetColumnCountException extends DataRetrievalFailureException {
<ide>
<del> private int expectedCount;
<add> private final int expectedCount;
<ide>
<del> private int actualCount;
<add> private final int actualCount;
<ide>
<ide>
<ide> /**
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/InvalidResultSetAccessException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class InvalidResultSetAccessException extends InvalidDataAccessResourceUsageException {
<ide>
<ide> @Nullable
<del> private String sql;
<add> private final String sql;
<ide>
<ide>
<ide> /**
<ide> public InvalidResultSetAccessException(String task, String sql, SQLException ex)
<ide> */
<ide> public InvalidResultSetAccessException(SQLException ex) {
<ide> super(ex.getMessage(), ex);
<add> this.sql = null;
<ide> }
<ide>
<ide>
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/JdbcUpdateAffectedIncorrectNumberOfRowsException.java
<ide> public class JdbcUpdateAffectedIncorrectNumberOfRowsException extends IncorrectUpdateSemanticsDataAccessException {
<ide>
<ide> /** Number of rows that should have been affected. */
<del> private int expected;
<add> private final int expected;
<ide>
<ide> /** Number of rows that actually were affected. */
<del> private int actual;
<add> private final int actual;
<ide>
<ide>
<ide> /**
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/config/DatabasePopulatorConfigUtils.java
<ide> * @author Stephane Nicoll
<ide> * @since 3.1
<ide> */
<del>class DatabasePopulatorConfigUtils {
<add>final class DatabasePopulatorConfigUtils {
<add>
<add>
<add> private DatabasePopulatorConfigUtils() {
<add> }
<add>
<ide>
<ide> public static void setDatabasePopulator(Element element, BeanDefinitionBuilder builder) {
<ide> List<Element> scripts = DomUtils.getChildElementsByTagName(element, "script");
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataProviderFactory.java
<ide> * @author Juergen Hoeller
<ide> * @since 2.5
<ide> */
<del>public class CallMetaDataProviderFactory {
<add>public final class CallMetaDataProviderFactory {
<ide>
<ide> /** List of supported database products for procedure calls. */
<ide> public static final List<String> supportedDatabaseProductsForProcedures = Arrays.asList(
<ide> public class CallMetaDataProviderFactory {
<ide> private static final Log logger = LogFactory.getLog(CallMetaDataProviderFactory.class);
<ide>
<ide>
<add> private CallMetaDataProviderFactory() {
<add> }
<add>
<add>
<ide> /**
<ide> * Create a {@link CallMetaDataProvider} based on the database meta-data.
<ide> * @param dataSource the JDBC DataSource to use for retrieving meta-data
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataProviderFactory.java
<ide> * @author Thomas Risberg
<ide> * @since 2.5
<ide> */
<del>public class TableMetaDataProviderFactory {
<add>public final class TableMetaDataProviderFactory {
<ide>
<ide> private static final Log logger = LogFactory.getLog(TableMetaDataProviderFactory.class);
<ide>
<ide>
<add> private TableMetaDataProviderFactory() {
<add> }
<add>
<add>
<ide> /**
<ide> * Create a {@link TableMetaDataProvider} based on the database meta-data.
<ide> * @param dataSource used to retrieve meta-data
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapter.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> protected Connection doGetConnection(@Nullable String username, @Nullable String
<ide> /**
<ide> * Inner class used as ThreadLocal value.
<ide> */
<del> private static class JdbcUserCredentials {
<add> private static final class JdbcUserCredentials {
<ide>
<ide> public final String username;
<ide>
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseConfigurerFactory.java
<ide> */
<ide> final class EmbeddedDatabaseConfigurerFactory {
<ide>
<add>
<add> private EmbeddedDatabaseConfigurerFactory() {
<add> }
<add>
<add>
<ide> /**
<ide> * Return a configurer instance for the given embedded database type.
<ide> * @param type the embedded database type (HSQL, H2 or Derby)
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/OutputStreamFactory.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Juergen Hoeller
<ide> * @since 3.0
<ide> */
<del>public class OutputStreamFactory {
<add>public final class OutputStreamFactory {
<add>
<add>
<add> private OutputStreamFactory() {
<add> }
<add>
<ide>
<ide> /**
<ide> * Returns an {@link java.io.OutputStream} that ignores all data given to it.
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/CustomSQLExceptionTranslatorRegistry.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @since 3.1.1
<ide> * @see SQLErrorCodesFactory
<ide> */
<del>public class CustomSQLExceptionTranslatorRegistry {
<add>public final class CustomSQLExceptionTranslatorRegistry {
<ide>
<ide> private static final Log logger = LogFactory.getLog(CustomSQLExceptionTranslatorRegistry.class);
<ide>
<ide><path>spring-jms/src/main/java/org/springframework/jms/connection/UserCredentialsConnectionFactoryAdapter.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private ConnectionFactory obtainTargetConnectionFactory() {
<ide> /**
<ide> * Inner class used as ThreadLocal value.
<ide> */
<del> private static class JmsUserCredentials {
<add> private static final class JmsUserCredentials {
<ide>
<ide> public final String username;
<ide>
<ide> public final String password;
<ide>
<add>
<ide> private JmsUserCredentials(String username, String password) {
<ide> this.username = username;
<ide> this.password = password;
<ide> }
<ide>
<add>
<ide> @Override
<ide> public String toString() {
<ide> return "JmsUserCredentials[username='" + this.username + "',password='" + this.password + "']";
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/DestinationVariableMethodArgumentResolver.java
<ide> protected void handleMissingValue(String name, MethodParameter parameter, Messag
<ide> }
<ide>
<ide>
<del> private static class DestinationVariableNamedValueInfo extends NamedValueInfo {
<add> private static final class DestinationVariableNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private DestinationVariableNamedValueInfo(DestinationVariable annotation) {
<ide> super(annotation.value(), true, ValueConstants.DEFAULT_NONE);
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolver.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> protected void handleMissingValue(String headerName, MethodParameter parameter,
<ide> }
<ide>
<ide>
<del> private static class HeaderNamedValueInfo extends NamedValueInfo {
<add> private static final class HeaderNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private HeaderNamedValueInfo(Header annotation) {
<ide> super(annotation.name(), annotation.required(), annotation.defaultValue());
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/MethodArgumentNotValidException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class MethodArgumentNotValidException extends MethodArgumentResolutionException {
<ide>
<del> private BindingResult bindingResult;
<add> private final BindingResult bindingResult;
<ide>
<ide>
<ide> /**
<ide> * Create a new instance with the invalid {@code MethodParameter}.
<ide> */
<ide> public MethodArgumentNotValidException(Message<?> message, MethodParameter parameter) {
<ide> super(message, parameter);
<add> this.bindingResult = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
<ide> private class StompConnectionHandler implements TcpConnectionHandler<byte[]> {
<ide> private volatile boolean isStompConnected;
<ide>
<ide>
<del> private StompConnectionHandler(String sessionId, StompHeaderAccessor connectHeaders) {
<add> protected StompConnectionHandler(String sessionId, StompHeaderAccessor connectHeaders) {
<ide> this(sessionId, connectHeaders, true);
<ide> }
<ide>
<ide><path>spring-orm/src/main/java/org/springframework/orm/ObjectOptimisticLockingFailureException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class ObjectOptimisticLockingFailureException extends OptimisticLockingFailureException {
<ide>
<ide> @Nullable
<del> private Object persistentClass;
<add> private final Object persistentClass;
<ide>
<ide> @Nullable
<del> private Object identifier;
<add> private final Object identifier;
<ide>
<ide>
<ide> /**
<ide> public class ObjectOptimisticLockingFailureException extends OptimisticLockingFa
<ide> */
<ide> public ObjectOptimisticLockingFailureException(String msg, Throwable cause) {
<ide> super(msg, cause);
<add> this.persistentClass = null;
<add> this.identifier = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-orm/src/main/java/org/springframework/orm/ObjectRetrievalFailureException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class ObjectRetrievalFailureException extends DataRetrievalFailureException {
<ide>
<ide> @Nullable
<del> private Object persistentClass;
<add> private final Object persistentClass;
<ide>
<ide> @Nullable
<del> private Object identifier;
<add> private final Object identifier;
<ide>
<ide>
<ide> /**
<ide> public class ObjectRetrievalFailureException extends DataRetrievalFailureExcepti
<ide> */
<ide> public ObjectRetrievalFailureException(String msg, Throwable cause) {
<ide> super(msg, cause);
<add> this.persistentClass = null;
<add> this.identifier = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/HibernateTransactionManager.java
<ide> public void flush() {
<ide> * Holder for suspended resources.
<ide> * Used internally by {@code doSuspend} and {@code doResume}.
<ide> */
<del> private static class SuspendedResourcesHolder {
<add> private static final class SuspendedResourcesHolder {
<ide>
<ide> private final SessionHolder sessionHolder;
<ide>
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/ExtendedEntityManagerCreator.java
<ide> private static EntityManager createProxy(
<ide> * InvocationHandler for extended EntityManagers as defined in the JPA spec.
<ide> */
<ide> @SuppressWarnings("serial")
<del> private static class ExtendedEntityManagerInvocationHandler implements InvocationHandler, Serializable {
<add> private static final class ExtendedEntityManagerInvocationHandler implements InvocationHandler, Serializable {
<ide>
<ide> private static final Log logger = LogFactory.getLog(ExtendedEntityManagerInvocationHandler.class);
<ide>
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/JpaTransactionManager.java
<ide> private SavepointManager getSavepointManager() {
<ide> * Holder for suspended resources.
<ide> * Used internally by {@code doSuspend} and {@code doResume}.
<ide> */
<del> private static class SuspendedResourcesHolder {
<add> private static final class SuspendedResourcesHolder {
<ide>
<ide> private final EntityManagerHolder entityManagerHolder;
<ide>
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java
<ide> public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, Generi
<ide>
<ide> private static final String CID = "cid:";
<ide>
<add> private static final EntityResolver NO_OP_ENTITY_RESOLVER =
<add> (publicId, systemId) -> new InputSource(new StringReader(""));
<add>
<ide>
<ide> /** Logger available to subclasses. */
<ide> protected final Log logger = LogFactory.getLog(getClass());
<ide> public String getName() {
<ide> }
<ide> }
<ide>
<del>
<del> private static final EntityResolver NO_OP_ENTITY_RESOLVER =
<del> (publicId, systemId) -> new InputSource(new StringReader(""));
<del>
<ide> }
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/support/MarshallingSource.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void setXMLReader(XMLReader reader) {
<ide> }
<ide>
<ide>
<del> private static class MarshallingXMLReader implements XMLReader {
<add> private static final class MarshallingXMLReader implements XMLReader {
<ide>
<ide> private final Marshaller marshaller;
<ide>
<ide><path>spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> */
<del>public class MockServerHttpRequest extends AbstractServerHttpRequest {
<add>public final class MockServerHttpRequest extends AbstractServerHttpRequest {
<ide>
<ide> private final HttpMethod httpMethod;
<ide>
<ide><path>spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContext.java
<ide> public void close() {
<ide> }
<ide>
<ide>
<del> private static class NameClassPairEnumeration extends AbstractNamingEnumeration<NameClassPair> {
<add> private static final class NameClassPairEnumeration extends AbstractNamingEnumeration<NameClassPair> {
<ide>
<ide> private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException {
<ide> super(context, root);
<ide> protected NameClassPair createObject(String strippedName, Object obj) {
<ide> }
<ide>
<ide>
<del> private static class BindingEnumeration extends AbstractNamingEnumeration<Binding> {
<add> private static final class BindingEnumeration extends AbstractNamingEnumeration<Binding> {
<ide>
<ide> private BindingEnumeration(SimpleNamingContext context, String root) throws NamingException {
<ide> super(context, root);
<ide><path>spring-test/src/main/java/org/springframework/mock/web/MockFilterChain.java
<ide> public void reset() {
<ide> /**
<ide> * A filter that simply delegates to a Servlet.
<ide> */
<del> private static class ServletFilterProxy implements Filter {
<add> private static final class ServletFilterProxy implements Filter {
<ide>
<ide> private final Servlet delegateServlet;
<ide>
<ide><path>spring-test/src/main/java/org/springframework/mock/web/reactive/function/server/MockServerRequest.java
<ide> * @author Arjen Poutsma
<ide> * @since 5.0
<ide> */
<del>public class MockServerRequest implements ServerRequest {
<add>public final class MockServerRequest implements ServerRequest {
<ide>
<ide> private final HttpMethod method;
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/annotation/SystemProfileValueSource.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Sam Brannen
<ide> * @since 2.0
<ide> */
<del>public class SystemProfileValueSource implements ProfileValueSource {
<add>public final class SystemProfileValueSource implements ProfileValueSource {
<ide>
<ide> private static final SystemProfileValueSource INSTANCE = new SystemProfileValueSource();
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/annotation/TestAnnotationUtils.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Sam Brannen
<ide> * @since 4.2
<ide> */
<del>public class TestAnnotationUtils {
<add>public final class TestAnnotationUtils {
<add>
<add>
<add> private TestAnnotationUtils() {
<add> }
<add>
<ide>
<ide> /**
<ide> * Get the {@code timeout} configured via the {@link Timed @Timed}
<ide><path>spring-test/src/main/java/org/springframework/test/context/transaction/TestTransaction.java
<ide> * @since 4.1
<ide> * @see TransactionalTestExecutionListener
<ide> */
<del>public class TestTransaction {
<add>public final class TestTransaction {
<add>
<add>
<add> private TestTransaction() {
<add> }
<add>
<ide>
<ide> /**
<ide> * Determine whether a test-managed transaction is currently <em>active</em>.
<ide><path>spring-test/src/main/java/org/springframework/test/context/transaction/TransactionContextHolder.java
<ide> * @author Sam Brannen
<ide> * @since 4.1
<ide> */
<del>class TransactionContextHolder {
<add>final class TransactionContextHolder {
<ide>
<ide> private static final ThreadLocal<TransactionContext> currentTransactionContext =
<ide> new NamedInheritableThreadLocal<>("Test Transaction Context");
<ide>
<ide>
<add> private TransactionContextHolder() {
<add> }
<add>
<add>
<ide> static void setCurrentTransactionContext(TransactionContext transactionContext) {
<ide> currentTransactionContext.set(transactionContext);
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @see org.springframework.jdbc.datasource.init.ResourceDatabasePopulator
<ide> * @see org.springframework.jdbc.datasource.init.DatabasePopulatorUtils
<ide> */
<del>public class JdbcTestUtils {
<add>public final class JdbcTestUtils {
<ide>
<ide> private static final Log logger = LogFactory.getLog(JdbcTestUtils.class);
<ide>
<ide>
<add> private JdbcTestUtils() {
<add> }
<add>
<add>
<ide> /**
<ide> * Count the rows in the given table.
<ide> * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/ExpectedCount.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.3
<ide> */
<del>public class ExpectedCount {
<add>public final class ExpectedCount {
<ide>
<ide> private final int minCount;
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/MockRestServiceServer.java
<ide> * @since 3.2
<ide> */
<ide> @SuppressWarnings("deprecation")
<del>public class MockRestServiceServer {
<add>public final class MockRestServiceServer {
<ide>
<ide> private final RequestExpectationManager expectationManager;
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/setup/MockMvcBuilders.java
<ide> * @see #webAppContextSetup(WebApplicationContext)
<ide> * @see #standaloneSetup(Object...)
<ide> */
<del>public class MockMvcBuilders {
<add>public final class MockMvcBuilders {
<add>
<add>
<add> private MockMvcBuilders() {
<add> }
<add>
<ide>
<ide> /**
<ide> * Build a {@link MockMvc} instance using the given, fully initialized
<ide><path>spring-tx/src/main/java/org/springframework/dao/IncorrectResultSizeDataAccessException.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class IncorrectResultSizeDataAccessException extends DataRetrievalFailureException {
<ide>
<del> private int expectedSize;
<add> private final int expectedSize;
<ide>
<del> private int actualSize;
<add> private final int actualSize;
<ide>
<ide>
<ide> /**
<ide><path>spring-tx/src/main/java/org/springframework/jca/cci/connection/SingleConnectionFactory.java
<ide> protected Connection getCloseSuppressingConnectionProxy(Connection target) {
<ide> /**
<ide> * Invocation handler that suppresses close calls on CCI Connections.
<ide> */
<del> private static class CloseSuppressingInvocationHandler implements InvocationHandler {
<add> private static final class CloseSuppressingInvocationHandler implements InvocationHandler {
<ide>
<ide> private final Connection target;
<ide>
<ide><path>spring-tx/src/main/java/org/springframework/transaction/HeuristicCompletionException.java
<ide> public static String getStateString(int state) {
<ide> /**
<ide> * The outcome state of the transaction: have some or all resources been committed?
<ide> */
<del> private int outcomeState = STATE_UNKNOWN;
<add> private final int outcomeState;
<ide>
<ide>
<ide> /**
<ide><path>spring-tx/src/main/java/org/springframework/transaction/InvalidTimeoutException.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class InvalidTimeoutException extends TransactionUsageException {
<ide>
<del> private int timeout;
<add> private final int timeout;
<ide>
<ide>
<ide> /**
<ide><path>spring-tx/src/main/java/org/springframework/transaction/support/AbstractPlatformTransactionManager.java
<ide> private void readObject(ObjectInputStream ois) throws IOException, ClassNotFound
<ide> * Holder for suspended resources.
<ide> * Used internally by {@code suspend} and {@code resume}.
<ide> */
<del> protected static class SuspendedResourcesHolder {
<add> protected static final class SuspendedResourcesHolder {
<ide>
<ide> @Nullable
<ide> private final Object suspendedResources;
<ide><path>spring-web/src/main/java/org/springframework/http/ContentDisposition.java
<ide> * @since 5.0
<ide> * @see <a href="https://tools.ietf.org/html/rfc2183">RFC 2183</a>
<ide> */
<del>public class ContentDisposition {
<add>public final class ContentDisposition {
<ide>
<ide> @Nullable
<ide> private final String type;
<ide><path>spring-web/src/main/java/org/springframework/http/InvalidMediaTypeException.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class InvalidMediaTypeException extends IllegalArgumentException {
<ide>
<del> private String mediaType;
<add> private final String mediaType;
<ide>
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/http/MediaTypeFactory.java
<ide> * @author Arjen Poutsma
<ide> * @since 5.0
<ide> */
<del>public class MediaTypeFactory {
<add>public final class MediaTypeFactory {
<ide>
<ide> private static final String MIME_TYPES_FILE_NAME = "/org/springframework/http/mime.types";
<ide>
<ide> private static final MultiValueMap<String, MediaType> fileExtensionToMediaTypes = parseMimeTypes();
<ide>
<ide>
<add> private MediaTypeFactory() {
<add> }
<add>
<add>
<ide> /**
<ide> * Parse the {@code mime.types} file found in the resources. Format is:
<ide> * <code>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/CodecConfigurerFactory.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @see ClientCodecConfigurer#create()
<ide> * @see ServerCodecConfigurer#create()
<ide> */
<del>class CodecConfigurerFactory {
<add>final class CodecConfigurerFactory {
<ide>
<ide> private static final String DEFAULT_CONFIGURERS_PATH = "CodecConfigurer.properties";
<ide>
<ide> class CodecConfigurerFactory {
<ide> }
<ide>
<ide>
<add> private CodecConfigurerFactory() {
<add> }
<add>
<add>
<ide> @SuppressWarnings("unchecked")
<ide> public static <T extends CodecConfigurer> T create(Class<T> ifc) {
<ide> Class<?> impl = defaultCodecConfigurers.get(ifc);
<ide><path>spring-web/src/main/java/org/springframework/http/codec/ServerSentEvent.java
<ide> * @see ServerSentEventHttpMessageWriter
<ide> * @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommendation</a>
<ide> */
<del>public class ServerSentEvent<T> {
<add>public final class ServerSentEvent<T> {
<ide>
<ide> @Nullable
<ide> private final String id;
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2Tokenizer.java
<ide> * @author Arjen Poutsma
<ide> * @since 5.0
<ide> */
<del>class Jackson2Tokenizer {
<add>final class Jackson2Tokenizer {
<ide>
<ide> private final JsonParser parser;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/DefaultPathContainer.java
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> */
<del>class DefaultPathContainer implements PathContainer {
<add>final class DefaultPathContainer implements PathContainer {
<ide>
<ide> private static final MultiValueMap<String, String> EMPTY_MAP = new LinkedMultiValueMap<>(0);
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/HttpRequestMethodNotSupportedException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @SuppressWarnings("serial")
<ide> public class HttpRequestMethodNotSupportedException extends ServletException {
<ide>
<del> private String method;
<add> private final String method;
<ide>
<ide> @Nullable
<del> private String[] supportedMethods;
<add> private final String[] supportedMethods;
<ide>
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/web/HttpSessionRequiredException.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class HttpSessionRequiredException extends ServletException {
<ide>
<ide> @Nullable
<del> private String expectedAttribute;
<add> private final String expectedAttribute;
<ide>
<ide>
<ide> /**
<ide> public class HttpSessionRequiredException extends ServletException {
<ide> */
<ide> public HttpSessionRequiredException(String msg) {
<ide> super(msg);
<add> this.expectedAttribute = null;
<ide> }
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/web/filter/RelativeRedirectResponseWrapper.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.3.10
<ide> */
<del>class RelativeRedirectResponseWrapper extends HttpServletResponseWrapper {
<add>final class RelativeRedirectResponseWrapper extends HttpServletResponseWrapper {
<ide>
<ide> private final HttpStatus redirectStatus;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/method/HandlerTypePredicate.java
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.1
<ide> */
<del>public class HandlerTypePredicate implements Predicate<Class<?>> {
<add>public final class HandlerTypePredicate implements Predicate<Class<?>> {
<ide>
<ide> private final Set<String> basePackages;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/method/annotation/AbstractCookieValueMethodArgumentResolver.java
<ide> protected void handleMissingValue(String name, MethodParameter parameter) throws
<ide> }
<ide>
<ide>
<del> private static class CookieValueNamedValueInfo extends NamedValueInfo {
<add> private static final class CookieValueNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private CookieValueNamedValueInfo(CookieValue annotation) {
<ide> super(annotation.name(), annotation.required(), annotation.defaultValue());
<ide><path>spring-web/src/main/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolver.java
<ide> protected void handleMissingValue(String name, MethodParameter parameter) throws
<ide> }
<ide>
<ide>
<del> private static class ExpressionValueNamedValueInfo extends NamedValueInfo {
<add> private static final class ExpressionValueNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private ExpressionValueNamedValueInfo(Value annotation) {
<ide> super("@Value", false, annotation.value());
<ide><path>spring-web/src/main/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolver.java
<ide> protected void handleMissingValue(String name, MethodParameter parameter) throws
<ide> }
<ide>
<ide>
<del> private static class RequestHeaderNamedValueInfo extends NamedValueInfo {
<add> private static final class RequestHeaderNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private RequestHeaderNamedValueInfo(RequestHeader annotation) {
<ide> super(annotation.name(), annotation.required(), annotation.defaultValue());
<ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/WebHttpHandlerBuilder.java
<ide> * @since 5.0
<ide> * @see HttpWebHandlerAdapter
<ide> */
<del>public class WebHttpHandlerBuilder {
<add>public final class WebHttpHandlerBuilder {
<ide>
<ide> /** Well-known name for the target WebHandler in the bean factory. */
<ide> public static final String WEB_HANDLER_BEAN_NAME = "webHandler";
<ide><path>spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java
<ide> final class HierarchicalUriComponents extends UriComponents {
<ide>
<ide> private static final String PATH_DELIMITER_STRING = "/";
<ide>
<add> /**
<add> * Represents an empty path.
<add> */
<add> static final PathComponent NULL_PATH_COMPONENT = new PathComponent() {
<add>
<add> @Override
<add> public String getPath() {
<add> return "";
<add> }
<add>
<add> @Override
<add> public List<String> getPathSegments() {
<add> return Collections.emptyList();
<add> }
<add>
<add> @Override
<add> public PathComponent encode(Charset charset) {
<add> return this;
<add> }
<add>
<add> @Override
<add> public void verify() {
<add> }
<add>
<add> @Override
<add> public PathComponent expand(UriTemplateVariables uriVariables) {
<add> return this;
<add> }
<add>
<add> @Override
<add> public void copyToUriComponentsBuilder(UriComponentsBuilder builder) {
<add> }
<add>
<add> @Override
<add> public boolean equals(Object obj) {
<add> return (this == obj);
<add> }
<add>
<add> @Override
<add> public int hashCode() {
<add> return getClass().hashCode();
<add> }
<add> };
<add>
<ide>
<ide> @Nullable
<ide> private final String userInfo;
<ide> public void copyToUriComponentsBuilder(UriComponentsBuilder builder) {
<ide> }
<ide>
<ide>
<del> /**
<del> * Represents an empty path.
<del> */
<del> static final PathComponent NULL_PATH_COMPONENT = new PathComponent() {
<del> @Override
<del> public String getPath() {
<del> return "";
<del> }
<del> @Override
<del> public List<String> getPathSegments() {
<del> return Collections.emptyList();
<del> }
<del> @Override
<del> public PathComponent encode(Charset charset) {
<del> return this;
<del> }
<del> @Override
<del> public void verify() {
<del> }
<del> @Override
<del> public PathComponent expand(UriTemplateVariables uriVariables) {
<del> return this;
<del> }
<del> @Override
<del> public void copyToUriComponentsBuilder(UriComponentsBuilder builder) {
<del> }
<del> @Override
<del> public boolean equals(Object obj) {
<del> return (this == obj);
<del> }
<del> @Override
<del> public int hashCode() {
<del> return getClass().hashCode();
<del> }
<del> };
<del>
<del>
<ide> private static class QueryUriTemplateVariables implements UriTemplateVariables {
<ide>
<ide> private final UriTemplateVariables delegate;
<ide><path>spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Rossen Stoyanchev
<ide> * @since 1.1.1
<ide> */
<del>public class JavaScriptUtils {
<add>public final class JavaScriptUtils {
<add>
<add>
<add> private JavaScriptUtils() {
<add> }
<add>
<ide>
<ide> /**
<ide> * Turn JavaScript special characters into escaped characters.
<ide><path>spring-web/src/main/java/org/springframework/web/util/UriTemplate.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public String toString() {
<ide> /**
<ide> * Helper to extract variable names and regex for matching to actual URLs.
<ide> */
<del> private static class TemplateInfo {
<add> private static final class TemplateInfo {
<ide>
<ide> private final List<String> variableNames;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java
<ide> public class PathPattern implements Comparable<PathPattern> {
<ide>
<ide> private static final PathContainer EMPTY_PATH = PathContainer.parsePath("");
<ide>
<add> /**
<add> * Comparator that sorts patterns by specificity as follows:
<add> * <ol>
<add> * <li>Null instances are last.
<add> * <li>Catch-all patterns are last.
<add> * <li>If both patterns are catch-all, consider the length (longer wins).
<add> * <li>Compare wildcard and captured variable count (lower wins).
<add> * <li>Consider length (longer wins)
<add> * </ol>
<add> */
<add> public static final Comparator<PathPattern> SPECIFICITY_COMPARATOR =
<add> Comparator.nullsLast(
<add> Comparator.<PathPattern>
<add> comparingInt(p -> p.isCatchAll() ? 1 : 0)
<add> .thenComparingInt(p -> p.isCatchAll() ? scoreByNormalizedLength(p) : 0)
<add> .thenComparingInt(PathPattern::getScore)
<add> .thenComparingInt(PathPattern::scoreByNormalizedLength)
<add> );
<add>
<ide>
<ide> /** The text of the parsed pattern. */
<ide> private final String patternString;
<ide> public String toString() {
<ide> return this.patternString;
<ide> }
<ide>
<add> int getScore() {
<add> return this.score;
<add> }
<add>
<add> boolean isCatchAll() {
<add> return this.catchAll;
<add> }
<add>
<add> /**
<add> * The normalized length is trying to measure the 'active' part of the pattern. It is computed
<add> * by assuming all capture variables have a normalized length of 1. Effectively this means changing
<add> * your variable name lengths isn't going to change the length of the active part of the pattern.
<add> * Useful when comparing two patterns.
<add> */
<add> int getNormalizedLength() {
<add> return this.normalizedLength;
<add> }
<add>
<add> char getSeparator() {
<add> return this.separator;
<add> }
<add>
<add> int getCapturedVariableCount() {
<add> return this.capturedVariableCount;
<add> }
<add>
<add> String toChainString() {
<add> StringBuilder buf = new StringBuilder();
<add> PathElement pe = this.head;
<add> while (pe != null) {
<add> buf.append(pe.toString()).append(" ");
<add> pe = pe.next;
<add> }
<add> return buf.toString().trim();
<add> }
<add>
<add> /**
<add> * Return the string form of the pattern built from walking the path element chain.
<add> * @return the string form of the pattern
<add> */
<add> String computePatternString() {
<add> StringBuilder buf = new StringBuilder();
<add> PathElement pe = this.head;
<add> while (pe != null) {
<add> buf.append(pe.getChars());
<add> pe = pe.next;
<add> }
<add> return buf.toString();
<add> }
<add>
<add> @Nullable
<add> PathElement getHeadSection() {
<add> return this.head;
<add> }
<add>
<add> /**
<add> * Join two paths together including a separator if necessary.
<add> * Extraneous separators are removed (if the first path
<add> * ends with one and the second path starts with one).
<add> * @param path1 first path
<add> * @param path2 second path
<add> * @return joined path that may include separator if necessary
<add> */
<add> private String concat(String path1, String path2) {
<add> boolean path1EndsWithSeparator = (path1.charAt(path1.length() - 1) == this.separator);
<add> boolean path2StartsWithSeparator = (path2.charAt(0) == this.separator);
<add> if (path1EndsWithSeparator && path2StartsWithSeparator) {
<add> return path1 + path2.substring(1);
<add> }
<add> else if (path1EndsWithSeparator || path2StartsWithSeparator) {
<add> return path1 + path2;
<add> }
<add> else {
<add> return path1 + this.separator + path2;
<add> }
<add> }
<add>
<add> /**
<add> * Return if the container is not null and has more than zero elements.
<add> * @param container a path container
<add> * @return {@code true} has more than zero elements
<add> */
<add> private boolean hasLength(@Nullable PathContainer container) {
<add> return container != null && container.elements().size() > 0;
<add> }
<add>
<add> private static int scoreByNormalizedLength(PathPattern pattern) {
<add> return -pattern.getNormalizedLength();
<add> }
<add>
<add> private boolean pathContainerIsJustSeparator(PathContainer pathContainer) {
<add> return pathContainer.value().length() == 1 &&
<add> pathContainer.value().charAt(0) == separator;
<add> }
<ide>
<ide> /**
<ide> * Holder for URI variables and path parameters (matrix variables) extracted
<ide> public String toString() {
<ide> }
<ide> }
<ide>
<add>
<ide> /**
<ide> * Holder for the result of a match on the start of a pattern.
<ide> * Provides access to the remaining path not matched to the pattern as well
<ide> public Map<String, MultiValueMap<String, String>> getMatrixVariables() {
<ide> }
<ide> }
<ide>
<del> int getScore() {
<del> return this.score;
<del> }
<del>
<del> boolean isCatchAll() {
<del> return this.catchAll;
<del> }
<del>
<del> /**
<del> * The normalized length is trying to measure the 'active' part of the pattern. It is computed
<del> * by assuming all capture variables have a normalized length of 1. Effectively this means changing
<del> * your variable name lengths isn't going to change the length of the active part of the pattern.
<del> * Useful when comparing two patterns.
<del> */
<del> int getNormalizedLength() {
<del> return this.normalizedLength;
<del> }
<del>
<del> char getSeparator() {
<del> return this.separator;
<del> }
<del>
<del> int getCapturedVariableCount() {
<del> return this.capturedVariableCount;
<del> }
<del>
<del> String toChainString() {
<del> StringBuilder buf = new StringBuilder();
<del> PathElement pe = this.head;
<del> while (pe != null) {
<del> buf.append(pe.toString()).append(" ");
<del> pe = pe.next;
<del> }
<del> return buf.toString().trim();
<del> }
<del>
<del> /**
<del> * Return the string form of the pattern built from walking the path element chain.
<del> * @return the string form of the pattern
<del> */
<del> String computePatternString() {
<del> StringBuilder buf = new StringBuilder();
<del> PathElement pe = this.head;
<del> while (pe != null) {
<del> buf.append(pe.getChars());
<del> pe = pe.next;
<del> }
<del> return buf.toString();
<del> }
<del>
<del> @Nullable
<del> PathElement getHeadSection() {
<del> return this.head;
<del> }
<ide>
<ide> /**
<ide> * Encapsulates context when attempting a match. Includes some fixed state like the
<ide> String pathElementValue(int pathIndex) {
<ide> return "";
<ide> }
<ide> }
<del>
<del> /**
<del> * Join two paths together including a separator if necessary.
<del> * Extraneous separators are removed (if the first path
<del> * ends with one and the second path starts with one).
<del> * @param path1 first path
<del> * @param path2 second path
<del> * @return joined path that may include separator if necessary
<del> */
<del> private String concat(String path1, String path2) {
<del> boolean path1EndsWithSeparator = (path1.charAt(path1.length() - 1) == this.separator);
<del> boolean path2StartsWithSeparator = (path2.charAt(0) == this.separator);
<del> if (path1EndsWithSeparator && path2StartsWithSeparator) {
<del> return path1 + path2.substring(1);
<del> }
<del> else if (path1EndsWithSeparator || path2StartsWithSeparator) {
<del> return path1 + path2;
<del> }
<del> else {
<del> return path1 + this.separator + path2;
<del> }
<del> }
<del>
<del> /**
<del> * Return if the container is not null and has more than zero elements.
<del> * @param container a path container
<del> * @return {@code true} has more than zero elements
<del> */
<del> private boolean hasLength(@Nullable PathContainer container) {
<del> return container != null && container.elements().size() > 0;
<del> }
<del>
<del>
<del> /**
<del> * Comparator that sorts patterns by specificity as follows:
<del> * <ol>
<del> * <li>Null instances are last.
<del> * <li>Catch-all patterns are last.
<del> * <li>If both patterns are catch-all, consider the length (longer wins).
<del> * <li>Compare wildcard and captured variable count (lower wins).
<del> * <li>Consider length (longer wins)
<del> * </ol>
<del> */
<del> public static final Comparator<PathPattern> SPECIFICITY_COMPARATOR =
<del> Comparator.nullsLast(
<del> Comparator.<PathPattern>
<del> comparingInt(p -> p.isCatchAll() ? 1 : 0)
<del> .thenComparingInt(p -> p.isCatchAll() ? scoreByNormalizedLength(p) : 0)
<del> .thenComparingInt(PathPattern::getScore)
<del> .thenComparingInt(PathPattern::scoreByNormalizedLength)
<del> );
<del>
<del> private static int scoreByNormalizedLength(PathPattern pattern) {
<del> return -pattern.getNormalizedLength();
<del> }
<del>
<del> private boolean pathContainerIsJustSeparator(PathContainer pathContainer) {
<del> return pathContainer.value().length() == 1 &&
<del> pathContainer.value().charAt(0) == separator;
<del> }
<del>
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/CookieValueMethodArgumentResolver.java
<ide> protected void handleMissingValue(String name, MethodParameter parameter) {
<ide> }
<ide>
<ide>
<del> private static class CookieValueNamedValueInfo extends NamedValueInfo {
<add> private static final class CookieValueNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private CookieValueNamedValueInfo(CookieValue annotation) {
<ide> super(annotation.name(), annotation.required(), annotation.defaultValue());
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/ExpressionValueMethodArgumentResolver.java
<ide> protected void handleMissingValue(String name, MethodParameter parameter) {
<ide> }
<ide>
<ide>
<del> private static class ExpressionValueNamedValueInfo extends NamedValueInfo {
<add> private static final class ExpressionValueNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private ExpressionValueNamedValueInfo(Value annotation) {
<ide> super("@Value", false, annotation.value());
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/MatrixVariableMethodArgumentResolver.java
<ide> protected void handleMissingValue(String name, MethodParameter parameter) throws
<ide> }
<ide>
<ide>
<del> private static class MatrixVariableNamedValueInfo extends NamedValueInfo {
<add> private static final class MatrixVariableNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private MatrixVariableNamedValueInfo(MatrixVariable annotation) {
<ide> super(annotation.name(), annotation.required(), annotation.defaultValue());
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMethodArgumentResolver.java
<ide> protected void handleMissingValue(String name, MethodParameter parameter) {
<ide> }
<ide>
<ide>
<del> private static class RequestHeaderNamedValueInfo extends NamedValueInfo {
<add> private static final class RequestHeaderNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private RequestHeaderNamedValueInfo(RequestHeader annotation) {
<ide> super(annotation.name(), annotation.required(), annotation.defaultValue());
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/ModelAndViewDefiningException.java
<ide> @SuppressWarnings("serial")
<ide> public class ModelAndViewDefiningException extends ServletException {
<ide>
<del> private ModelAndView modelAndView;
<add> private final ModelAndView modelAndView;
<ide>
<ide>
<ide> /**
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariableMethodArgumentResolver.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> protected void handleMissingValue(String name, MethodParameter parameter) throws
<ide> }
<ide>
<ide>
<del> private static class MatrixVariableNamedValueInfo extends NamedValueInfo {
<add> private static final class MatrixVariableNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private MatrixVariableNamedValueInfo(MatrixVariable annotation) {
<ide> super(annotation.name(), annotation.required(), annotation.defaultValue());
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParser.java
<ide> private static void registerBeanDefByName(
<ide> context.registerComponent(new BeanComponentDefinition(beanDef, name));
<ide> }
<ide>
<del> private static class DecoratingFactoryBean implements FactoryBean<WebSocketHandler> {
<add> private static final class DecoratingFactoryBean implements FactoryBean<WebSocketHandler> {
<ide>
<ide> private final WebSocketHandler handler;
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketNamespaceUtils.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>class WebSocketNamespaceUtils {
<add>final class WebSocketNamespaceUtils {
<add>
<add>
<add> private WebSocketNamespaceUtils() {
<add> }
<add>
<ide>
<ide> public static RuntimeBeanReference registerHandshakeHandler(
<ide> Element element, ParserContext context, @Nullable Object source) {
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketAnnotationMethodMessageHandler.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private void initMessagingAdviceCache(@Nullable List<MessagingAdviceBean> beans)
<ide> /**
<ide> * Adapt ControllerAdviceBean to MessagingAdviceBean.
<ide> */
<del> private static class MessagingControllerAdviceBean implements MessagingAdviceBean {
<add> private static final class MessagingControllerAdviceBean implements MessagingAdviceBean {
<ide>
<ide> private final ControllerAdviceBean adviceBean;
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java
<ide> public abstract class AbstractSockJsService implements SockJsService, CorsConfig
<ide>
<ide> private static final String XFRAME_OPTIONS_HEADER = "X-Frame-Options";
<ide>
<del>
<ide> protected final Log logger = LogFactory.getLog(getClass());
<ide>
<ide> private final TaskScheduler taskScheduler;
<ide> public abstract class AbstractSockJsService implements SockJsService, CorsConfig
<ide>
<ide> protected final Set<String> allowedOrigins = new LinkedHashSet<>();
<ide>
<add> private final SockJsRequestHandler infoHandler = new InfoHandler();
<add>
<add> private final SockJsRequestHandler iframeHandler = new IframeHandler();
<add>
<ide>
<ide> public AbstractSockJsService(TaskScheduler scheduler) {
<ide> Assert.notNull(scheduler, "TaskScheduler must not be null");
<ide> private interface SockJsRequestHandler {
<ide> }
<ide>
<ide>
<del> private final SockJsRequestHandler infoHandler = new SockJsRequestHandler() {
<add> private class InfoHandler implements SockJsRequestHandler {
<ide>
<ide> private static final String INFO_CONTENT =
<ide> "{\"entropy\":%s,\"origins\":[\"*:*\"],\"cookie_needed\":%s,\"websocket\":%s}";
<ide> else if (request.getMethod() == HttpMethod.OPTIONS) {
<ide> };
<ide>
<ide>
<del> private final SockJsRequestHandler iframeHandler = new SockJsRequestHandler() {
<add> private class IframeHandler implements SockJsRequestHandler {
<ide>
<ide> private static final String IFRAME_CONTENT =
<ide> "<!DOCTYPE html>\n" + | 128 |
Ruby | Ruby | evaluate the default block only when necessary | 4c1d22183c9ed4dea74ef60a3cca1891fa588b74 | <ide><path>activerecord/lib/active_record/associations/belongs_to_association.rb
<ide> def replace(record)
<ide> self.target = record
<ide> end
<ide>
<del> def default(record)
<del> writer(record) if reader.nil?
<add> def default(&block)
<add> writer(instance_exec(&block)) if reader.nil?
<ide> end
<ide>
<ide> def reset
<ide><path>activerecord/lib/active_record/associations/builder/belongs_to.rb
<ide> def self.add_touch_callbacks(model, reflection)
<ide>
<ide> def self.add_default_callbacks(model, reflection)
<ide> model.before_validation lambda { |o|
<del> o.association(reflection.name).default o.instance_exec(&reflection.options[:default])
<add> o.association(reflection.name).default(&reflection.options[:default])
<ide> }
<ide> end
<ide> | 2 |
Python | Python | fix morphology task in ud-train | f03640b41ff94f42c38b21d1247e29a53a0dbb1a | <ide><path>spacy/cli/ud_train.py
<ide> def read_data(nlp, conllu_file, text_file, raw_text=True, oracle_segments=False,
<ide> if oracle_segments:
<ide> docs.append(Doc(nlp.vocab, words=sent['words'], spaces=sent['spaces']))
<ide> golds.append(GoldParse(docs[-1], **sent))
<add> assert golds[-1].morphology is not None
<ide>
<ide> sent_annots.append(sent)
<ide> if raw_text and max_doc_length and len(sent_annots) >= max_doc_length:
<ide> doc, gold = _make_gold(nlp, None, sent_annots)
<add> assert gold.morphology is not None
<ide> sent_annots = []
<ide> docs.append(doc)
<ide> golds.append(gold)
<ide> def read_data(nlp, conllu_file, text_file, raw_text=True, oracle_segments=False,
<ide>
<ide> def _parse_morph_string(morph_string):
<ide> if morph_string == '_':
<del> return None
<add> return set()
<ide> output = []
<ide> replacements = {'1': 'one', '2': 'two', '3': 'three'}
<ide> for feature in morph_string.split('|'):
<ide> key, value = feature.split('=')
<ide> value = replacements.get(value, value)
<add> value = value.split(',')[0]
<ide> output.append('%s_%s' % (key, value.lower()))
<ide> return set(output)
<ide>
<ide> def _make_gold(nlp, text, sent_annots, drop_deps=0.0):
<ide> sent_starts = []
<ide> for sent in sent_annots:
<ide> flat['heads'].extend(len(flat['words'])+head for head in sent['heads'])
<del> for field in ['words', 'tags', 'deps', 'entities', 'spaces']:
<add> for field in ['words', 'tags', 'deps', 'morphology', 'entities', 'spaces']:
<ide> flat[field].extend(sent[field])
<ide> sent_starts.append(True)
<ide> sent_starts.extend([False] * (len(sent['words'])-1))
<ide> def write_conllu(docs, file_):
<ide> def print_progress(itn, losses, ud_scores):
<ide> fields = {
<ide> 'dep_loss': losses.get('parser', 0.0),
<add> 'morph_loss': losses.get('morphologizer', 0.0),
<ide> 'tag_loss': losses.get('tagger', 0.0),
<ide> 'words': ud_scores['Words'].f1 * 100,
<ide> 'sents': ud_scores['Sentences'].f1 * 100,
<ide> 'tags': ud_scores['XPOS'].f1 * 100,
<ide> 'uas': ud_scores['UAS'].f1 * 100,
<ide> 'las': ud_scores['LAS'].f1 * 100,
<add> 'morph': ud_scores['Feats'].f1 * 100,
<ide> }
<del> header = ['Epoch', 'Loss', 'LAS', 'UAS', 'TAG', 'SENT', 'WORD']
<add> header = ['Epoch', 'P.Loss', 'M.Loss', 'LAS', 'UAS', 'TAG', 'MORPH', 'SENT', 'WORD']
<ide> if itn == 0:
<ide> print('\t'.join(header))
<ide> tpl = '\t'.join((
<ide> '{:d}',
<ide> '{dep_loss:.1f}',
<add> '{morph_loss:.1f}',
<ide> '{las:.1f}',
<ide> '{uas:.1f}',
<ide> '{tags:.1f}',
<add> '{morph:.1f}',
<ide> '{sents:.1f}',
<ide> '{words:.1f}',
<ide> ))
<ide> def get_token_conllu(token, i):
<ide> head = 0
<ide> else:
<ide> head = i + (token.head.i - token.i) + 1
<del> fields = [str(i+1), token.text, token.lemma_, token.pos_, token.tag_, '_',
<add> features = token.vocab.morphology.get(token.morph_key)
<add> feat_str = []
<add> replacements = {'one': '1', 'two': '2', 'three': '3'}
<add> for feat in features:
<add> if not feat.startswith('begin') and not feat.startswith('end'):
<add> key, value = feat.split('_')
<add> value = replacements.get(value, value)
<add> feat_str.append('%s=%s' % (key, value.title()))
<add> if not feat_str:
<add> feat_str = '_'
<add> else:
<add> feat_str = '|'.join(feat_str)
<add> fields = [str(i+1), token.text, token.lemma_, token.pos_, token.tag_, feat_str,
<ide> str(head), token.dep_.lower(), '_', '_']
<ide> lines.append('\t'.join(fields))
<ide> return '\n'.join(lines)
<ide> def load_nlp(corpus, config, vectors=None):
<ide>
<ide> def initialize_pipeline(nlp, docs, golds, config, device):
<ide> nlp.add_pipe(nlp.create_pipe('tagger'))
<add> nlp.add_pipe(nlp.create_pipe('morphologizer'))
<ide> nlp.add_pipe(nlp.create_pipe('parser'))
<ide> if config.multitask_tag:
<ide> nlp.parser.add_multitask_objective('tag')
<ide> def main(ud_dir, parses_dir, corpus, config=None, limit=0, gpu_device=-1, vector
<ide> with nlp.use_params(optimizer.averages):
<ide> if use_oracle_segments:
<ide> parsed_docs, scores = evaluate(nlp, paths.dev.conllu,
<del> paths.dev.conllu, out_path)
<add> paths.dev.conllu, out_path)
<ide> else:
<ide> parsed_docs, scores = evaluate(nlp, paths.dev.text,
<del> paths.dev.conllu, out_path)
<del> print_progress(i, losses, scores)
<add> paths.dev.conllu, out_path)
<add> print_progress(i, losses, scores)
<ide>
<ide>
<ide> def _render_parses(i, to_render): | 1 |
PHP | PHP | apply fixes from styleci | c1cdcab67f356c7729d2d1b89747f2ba50fce9e5 | <ide><path>src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php
<ide> public function compileUpdate(Builder $query, $values)
<ide> {
<ide> $table = $this->wrapTable($query->from);
<ide>
<del> $columns = collect($values)->map(function ($value, $key) use($query) {
<add> $columns = collect($values)->map(function ($value, $key) use ($query) {
<ide> return $this->wrap(Str::after($key, $query->from.'.')).' = '.$this->parameter($value);
<ide> })->implode(', ');
<ide>
<ide><path>tests/Integration/Database/EloquentUpdateTest.php
<ide> public function setUp()
<ide> $table->string('name')->nullable();
<ide> $table->string('title')->nullable();
<ide> });
<del>
<add>
<ide> Schema::create('test_model2', function ($table) {
<ide> $table->increments('id');
<ide> $table->string('name');
<ide> public function setUp()
<ide> public function testBasicUpdate()
<ide> {
<ide> TestUpdateModel1::create([
<del> 'name' => str_random(),
<add> 'name' => str_random(),
<ide> 'title' => 'Ms.',
<ide> ]);
<ide>
<ide> public function testBasicUpdate()
<ide>
<ide> public function testUpdateWithLimitsAndOrders()
<ide> {
<del> for($i=1; $i <= 10; $i++){
<add> for ($i = 1; $i <= 10; $i++) {
<ide> TestUpdateModel1::create();
<ide> }
<ide>
<ide> public function testUpdateWithLimitsAndOrders()
<ide> public function testUpdatedAtWithJoins()
<ide> {
<ide> TestUpdateModel1::create([
<del> 'name' => 'Abdul',
<add> 'name' => 'Abdul',
<ide> 'title' => 'Mr.',
<ide> ]);
<ide>
<ide> TestUpdateModel2::create([
<del> 'name' => str_random()
<add> 'name' => str_random(),
<ide> ]);
<ide>
<del> TestUpdateModel2::join('test_model1', function($join) {
<add> TestUpdateModel2::join('test_model1', function ($join) {
<ide> $join->on('test_model1.id', '=', 'test_model2.id')
<ide> ->where('test_model1.title', '=', 'Mr.');
<ide> })->update(['test_model2.name' => 'Abdul', 'job'=>'Engineer']);
<del>
<add>
<ide> $record = TestUpdateModel2::find(1);
<ide>
<ide> $this->assertEquals('Engineer: Abdul', $record->job.': '.$record->name);
<ide> public function testUpdatedAtWithJoins()
<ide> public function testSoftDeleteWithJoins()
<ide> {
<ide> TestUpdateModel1::create([
<del> 'name' => str_random(),
<add> 'name' => str_random(),
<ide> 'title' => 'Mr.',
<ide> ]);
<ide>
<ide> TestUpdateModel2::create([
<del> 'name' => str_random()
<add> 'name' => str_random(),
<ide> ]);
<ide>
<del>
<del> TestUpdateModel2::join('test_model1', function($join) {
<add> TestUpdateModel2::join('test_model1', function ($join) {
<ide> $join->on('test_model1.id', '=', 'test_model2.id')
<ide> ->where('test_model1.title', '=', 'Mr.');
<ide> })->delete();
<ide> public function testSoftDeleteWithJoins()
<ide> }
<ide> }
<ide>
<del>
<ide> class TestUpdateModel1 extends Model
<ide> {
<ide> public $table = 'test_model1'; | 2 |
Ruby | Ruby | add both branches to the only_path conditional | ef686a60951342a189cc82bfc4823180a6cf3a32 | <ide><path>actionpack/lib/action_dispatch/http/url.rb
<ide> def url_for(options)
<ide> path = options[:script_name].to_s.chomp("/")
<ide> path << options[:path].to_s
<ide>
<del> add_trailing_slash(path) if options[:trailing_slash]
<add> path = add_trailing_slash(path) if options[:trailing_slash]
<ide>
<del> result = path
<del>
<del> unless options[:only_path]
<del> result.prepend build_host_url(options)
<del> end
<add> result = if options[:only_path]
<add> path
<add> else
<add> build_host_url(options).concat path
<add> end
<ide>
<ide> if options.key? :params
<ide> params = options[:params].is_a?(Hash) ? | 1 |
Javascript | Javascript | remove unnecessary binding | 6721c736edb2395497d61f3c53eab69868706f42 | <ide><path>packages/ember-metal/lib/observer_set.js
<ide> export default class ObserverSet {
<ide> let observers = this.observers;
<ide> let senderGuid = guidFor(sender);
<ide> let keySet = observerSet[senderGuid];
<del> let index;
<ide>
<del> if (!keySet) {
<add> if (keySet === undefined) {
<ide> observerSet[senderGuid] = keySet = {};
<ide> }
<del> index = keySet[keyName];
<add>
<add> let index = keySet[keyName];
<ide> if (index === undefined) {
<ide> index = observers.push({
<ide> sender,
<ide> export default class ObserverSet {
<ide>
<ide> flush() {
<ide> let observers = this.observers;
<del> let i, observer, sender;
<add> let observer, sender;
<ide> this.clear();
<del> for (i = 0; i < observers.length; ++i) {
<add> for (let i = 0; i < observers.length; ++i) {
<ide> observer = observers[i];
<ide> sender = observer.sender;
<ide> if (sender.isDestroying || sender.isDestroyed) { continue; }
<ide><path>packages/ember-metal/lib/property_events.js
<ide> import {
<ide> } from 'ember/features';
<ide> import { assertNotRendered } from './transaction';
<ide>
<del>export let PROPERTY_DID_CHANGE = symbol('PROPERTY_DID_CHANGE');
<add>export const PROPERTY_DID_CHANGE = symbol('PROPERTY_DID_CHANGE');
<ide>
<ide> const beforeObserverSet = new ObserverSet();
<ide> const observerSet = new ObserverSet();
<ide> function propertyDidChange(obj, keyName, _meta) {
<ide> }
<ide>
<ide> if (hasMeta && meta.peekWatching(keyName) > 0) {
<del> if (meta.hasDeps(keyName) && !meta.isSourceDestroying()) {
<del> dependentKeysDidChange(obj, keyName, meta);
<del> }
<del>
<add> dependentKeysDidChange(obj, keyName, meta);
<ide> chainsDidChange(obj, keyName, meta);
<ide> notifyObservers(obj, keyName, meta);
<ide> }
<ide> function propertyDidChange(obj, keyName, _meta) {
<ide> let WILL_SEEN, DID_SEEN;
<ide> // called whenever a property is about to change to clear the cache of any dependent keys (and notify those properties of changes, etc...)
<ide> function dependentKeysWillChange(obj, depKey, meta) {
<del> if (meta.isSourceDestroying()) { return; }
<del> if (meta.hasDeps(depKey)) {
<del> let seen = WILL_SEEN;
<del> let top = !seen;
<add> if (meta.isSourceDestroying() || !meta.hasDeps(depKey)) { return; }
<add> let seen = WILL_SEEN;
<add> let top = !seen;
<ide>
<del> if (top) {
<del> seen = WILL_SEEN = {};
<del> }
<add> if (top) {
<add> seen = WILL_SEEN = {};
<add> }
<ide>
<del> iterDeps(propertyWillChange, obj, depKey, seen, meta);
<add> iterDeps(propertyWillChange, obj, depKey, seen, meta);
<ide>
<del> if (top) {
<del> WILL_SEEN = null;
<del> }
<add> if (top) {
<add> WILL_SEEN = null;
<ide> }
<ide> }
<ide>
<ide> // called whenever a property has just changed to update dependent keys
<ide> function dependentKeysDidChange(obj, depKey, meta) {
<add> if (meta.isSourceDestroying() || !meta.hasDeps(depKey)) { return; }
<ide> let seen = DID_SEEN;
<ide> let top = !seen;
<ide>
<ide> function changeProperties(callback, binding) {
<ide> try {
<ide> callback.call(binding);
<ide> } finally {
<del> endPropertyChanges.call(binding);
<add> endPropertyChanges();
<ide> }
<ide> }
<ide>
<ide> function notifyBeforeObservers(obj, keyName, meta) {
<ide> if (deferred) {
<ide> listeners = beforeObserverSet.add(obj, keyName, eventName);
<ide> added = accumulateListeners(obj, eventName, listeners, meta);
<del> sendEvent(obj, eventName, [obj, keyName], added);
<del> } else {
<del> sendEvent(obj, eventName, [obj, keyName]);
<ide> }
<add> sendEvent(obj, eventName, [obj, keyName], added);
<ide> }
<ide>
<ide> function notifyObservers(obj, keyName, meta) { | 2 |
Ruby | Ruby | use caller for helpers_dir deprecation warnings | f8011e67b002990e1c25550c161ab0af6af6620f | <ide><path>actionpack/lib/action_controller/metal/helpers.rb
<ide> module Helpers
<ide>
<ide> module ClassMethods
<ide> def helpers_dir
<del> ActiveSupport::Deprecation.warn "helpers_dir is deprecated, use helpers_path instead"
<add> ActiveSupport::Deprecation.warn "helpers_dir is deprecated, use helpers_path instead", caller
<ide> self.helpers_path
<ide> end
<ide>
<ide> def helpers_dir=(value)
<del> ActiveSupport::Deprecation.warn "helpers_dir= is deprecated, use helpers_path= instead"
<add> ActiveSupport::Deprecation.warn "helpers_dir= is deprecated, use helpers_path= instead", caller
<ide> self.helpers_path = Array(value)
<ide> end
<ide> | 1 |
Mixed | Javascript | add rejects() and doesnotreject() | 599337f43e0e0d66263e69d70edab26b61d3038a | <ide><path>doc/api/assert.md
<ide> parameter is undefined, a default error message is assigned. If the `message`
<ide> parameter is an instance of an [`Error`][] then it will be thrown instead of the
<ide> `AssertionError`.
<ide>
<add>## assert.doesNotReject(block[, error][, message])
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>* `block` {Function}
<add>* `error` {RegExp|Function}
<add>* `message` {any}
<add>
<add>Awaits for the promise returned by function `block` to complete and not be
<add>rejected. See [`assert.rejects()`][] for more details.
<add>
<add>When `assert.doesNotReject()` is called, it will immediately call the `block`
<add>function, and awaits for completion.
<add>
<add>Besides the async nature to await the completion behaves identical to
<add>[`assert.doesNotThrow()`][].
<add>
<add>```js
<add>(async () => {
<add> await assert.doesNotReject(
<add> async () => {
<add> throw new TypeError('Wrong value');
<add> },
<add> SyntaxError
<add> );
<add>})();
<add>```
<add>
<add>```js
<add>assert.doesNotReject(
<add> () => Promise.reject(new TypeError('Wrong value')),
<add> SyntaxError
<add>).then(() => {
<add> // ...
<add>});
<add>```
<add>
<ide> ## assert.doesNotThrow(block[, error][, message])
<ide> <!-- YAML
<ide> added: v0.1.21
<ide> If the values are not strictly equal, an `AssertionError` is thrown with a
<ide> `message` parameter is an instance of an [`Error`][] then it will be thrown
<ide> instead of the `AssertionError`.
<ide>
<add>## assert.rejects(block[, error][, message])
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>* `block` {Function}
<add>* `error` {RegExp|Function|Object}
<add>* `message` {any}
<add>
<add>Awaits for promise returned by function `block` to be rejected.
<add>
<add>When `assert.rejects()` is called, it will immediately call the `block`
<add>function, and awaits for completion.
<add>
<add>Besides the async nature to await the completion behaves identical to
<add>[`assert.throws()`][].
<add>
<add>If specified, `error` can be a constructor, [`RegExp`][], a validation
<add>function, or an object where each property will be tested for.
<add>
<add>If specified, `message` will be the message provided by the `AssertionError` if
<add>the block fails to reject.
<add>
<add>```js
<add>(async () => {
<add> await assert.rejects(
<add> async () => {
<add> throw new Error('Wrong value');
<add> },
<add> Error
<add> );
<add>})();
<add>```
<add>
<add>```js
<add>assert.rejects(
<add> () => Promise.reject(new Error('Wrong value')),
<add> Error
<add>).then(() => {
<add> // ...
<add>});
<add>```
<add>
<ide> ## assert.throws(block[, error][, message])
<ide> <!-- YAML
<ide> added: v0.1.21
<ide> second argument. This might lead to difficult-to-spot errors.
<ide> [`assert.ok()`]: #assert_assert_ok_value_message
<ide> [`assert.strictEqual()`]: #assert_assert_strictequal_actual_expected_message
<ide> [`assert.throws()`]: #assert_assert_throws_block_error_message
<add>[`assert.rejects()`]: #assert_assert_rejects_block_error_message
<ide> [`strict mode`]: #assert_strict_mode
<ide> [Abstract Equality Comparison]: https://tc39.github.io/ecma262/#sec-abstract-equality-comparison
<ide> [Object.prototype.toString()]: https://tc39.github.io/ecma262/#sec-object.prototype.tostring
<ide><path>lib/assert.js
<ide> function getActual(block) {
<ide> return NO_EXCEPTION_SENTINEL;
<ide> }
<ide>
<del>// Expected to throw an error.
<del>assert.throws = function throws(block, error, message) {
<del> const actual = getActual(block);
<add>async function waitForActual(block) {
<add> if (typeof block !== 'function') {
<add> throw new ERR_INVALID_ARG_TYPE('block', 'Function', block);
<add> }
<add> try {
<add> await block();
<add> } catch (e) {
<add> return e;
<add> }
<add> return NO_EXCEPTION_SENTINEL;
<add>}
<ide>
<add>function expectsError(stackStartFn, actual, error, message) {
<ide> if (typeof error === 'string') {
<del> if (arguments.length === 3)
<add> if (arguments.length === 4) {
<ide> throw new ERR_INVALID_ARG_TYPE('error', ['Function', 'RegExp'], error);
<del>
<add> }
<ide> message = error;
<ide> error = null;
<ide> }
<ide> assert.throws = function throws(block, error, message) {
<ide> details += ` (${error.name})`;
<ide> }
<ide> details += message ? `: ${message}` : '.';
<add> const fnType = stackStartFn === rejects ? 'rejection' : 'exception';
<ide> innerFail({
<ide> actual,
<ide> expected: error,
<del> operator: 'throws',
<del> message: `Missing expected exception${details}`,
<del> stackStartFn: throws
<add> operator: stackStartFn.name,
<add> message: `Missing expected ${fnType}${details}`,
<add> stackStartFn
<ide> });
<ide> }
<ide> if (error && expectedException(actual, error, message) === false) {
<ide> throw actual;
<ide> }
<del>};
<add>}
<ide>
<del>assert.doesNotThrow = function doesNotThrow(block, error, message) {
<del> const actual = getActual(block);
<add>function expectsNoError(stackStartFn, actual, error, message) {
<ide> if (actual === NO_EXCEPTION_SENTINEL)
<ide> return;
<ide>
<ide> assert.doesNotThrow = function doesNotThrow(block, error, message) {
<ide>
<ide> if (!error || expectedException(actual, error)) {
<ide> const details = message ? `: ${message}` : '.';
<add> const fnType = stackStartFn === doesNotReject ? 'rejection' : 'exception';
<ide> innerFail({
<ide> actual,
<ide> expected: error,
<del> operator: 'doesNotThrow',
<del> message: `Got unwanted exception${details}\n${actual && actual.message}`,
<del> stackStartFn: doesNotThrow
<add> operator: stackStartFn.name,
<add> message: `Got unwanted ${fnType}${details}\n${actual && actual.message}`,
<add> stackStartFn
<ide> });
<ide> }
<ide> throw actual;
<del>};
<add>}
<add>
<add>function throws(block, ...args) {
<add> expectsError(throws, getActual(block), ...args);
<add>}
<add>
<add>assert.throws = throws;
<add>
<add>async function rejects(block, ...args) {
<add> expectsError(rejects, await waitForActual(block), ...args);
<add>}
<add>
<add>assert.rejects = rejects;
<add>
<add>function doesNotThrow(block, ...args) {
<add> expectsNoError(doesNotThrow, getActual(block), ...args);
<add>}
<add>
<add>assert.doesNotThrow = doesNotThrow;
<add>
<add>async function doesNotReject(block, ...args) {
<add> expectsNoError(doesNotReject, await waitForActual(block), ...args);
<add>}
<add>
<add>assert.doesNotReject = doesNotReject;
<ide>
<ide> assert.ifError = function ifError(err) {
<ide> if (err !== null && err !== undefined) {
<ide><path>test/parallel/test-assert-async.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const { promisify } = require('util');
<add>const wait = promisify(setTimeout);
<add>
<add>/* eslint-disable prefer-common-expectserror, no-restricted-properties */
<add>
<add>// Test assert.rejects() and assert.doesNotReject() by checking their
<add>// expected output and by verifying that they do not work sync
<add>
<add>assert.rejects(
<add> () => assert.fail(),
<add> common.expectsError({
<add> code: 'ERR_ASSERTION',
<add> type: assert.AssertionError,
<add> message: 'Failed'
<add> })
<add>);
<add>
<add>assert.doesNotReject(() => {});
<add>
<add>{
<add> const promise = assert.rejects(async () => {
<add> await wait(1);
<add> assert.fail();
<add> }, common.expectsError({
<add> code: 'ERR_ASSERTION',
<add> type: assert.AssertionError,
<add> message: 'Failed'
<add> }));
<add> assert.doesNotReject(() => promise);
<add>}
<add>
<add>{
<add> const promise = assert.doesNotReject(async () => {
<add> await wait(1);
<add> throw new Error();
<add> });
<add> assert.rejects(() => promise,
<add> (err) => {
<add> assert(err instanceof assert.AssertionError,
<add> `${err.name} is not instance of AssertionError`);
<add> assert.strictEqual(err.code, 'ERR_ASSERTION');
<add> assert(/^Got unwanted rejection\.\n$/.test(err.message));
<add> assert.strictEqual(err.operator, 'doesNotReject');
<add> assert.ok(!err.stack.includes('at Function.doesNotReject'));
<add> return true;
<add> }
<add> );
<add>}
<add>
<add>{
<add> const promise = assert.rejects(() => {});
<add> assert.rejects(() => promise,
<add> (err) => {
<add> assert(err instanceof assert.AssertionError,
<add> `${err.name} is not instance of AssertionError`);
<add> assert.strictEqual(err.code, 'ERR_ASSERTION');
<add> assert(/^Missing expected rejection\.$/.test(err.message));
<add> assert.strictEqual(err.operator, 'rejects');
<add> assert.ok(!err.stack.includes('at Function.rejects'));
<add> return true;
<add> }
<add> );
<add>}
<ide><path>test/parallel/test-assert.js
<ide> assert.throws(() => thrower(TypeError));
<ide> } catch (e) {
<ide> threw = true;
<ide> assert.ok(e instanceof a.AssertionError);
<add> assert.ok(!e.stack.includes('at Function.doesNotThrow'));
<ide> }
<ide> assert.ok(threw, 'a.doesNotThrow is not catching type matching errors');
<ide> }
<ide> a.throws(() => thrower(TypeError), (err) => {
<ide> code: 'ERR_ASSERTION',
<ide> message: /^Missing expected exception \(TypeError\): fhqwhgads$/
<ide> }));
<add>
<add> let threw = false;
<add> try {
<add> a.throws(noop);
<add> } catch (e) {
<add> threw = true;
<add> assert.ok(e instanceof a.AssertionError);
<add> assert.ok(!e.stack.includes('at Function.throws'));
<add> }
<add> assert.ok(threw);
<ide> }
<ide>
<ide> const circular = { y: 1 }; | 4 |
PHP | PHP | improve docblocks and code readability | bdb81998f44a1f987672f75b4da232b949db3755 | <ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> use RuntimeException;
<ide>
<ide> /**
<del> * Request object for handling alternative HTTP requests
<add> * Request object handling for alternative HTTP requests.
<ide> *
<del> * Alternative HTTP requests can come from wireless units like mobile phones, palmtop computers,
<del> * and the like. These units have no use for AJAX requests, and this Component can tell how Cake
<del> * should respond to the different needs of a handheld computer and a desktop machine.
<add> * This Component checks for requests for different content types like JSON, XML,
<add> * XMLHttpRequest(AJAX) and configures the response object and view builder accordingly.
<add> *
<add> * It can also check for HTTP caching headers like `Last-Modified`, `If-Modified-Since`
<add> * etc. and return response accordingly.
<ide> *
<ide> * @link https://book.cakephp.org/3.0/en/controllers/components/request-handling.html
<ide> */
<ide> class RequestHandlerComponent extends Component
<ide> protected $ext;
<ide>
<ide> /**
<del> * The template to use when rendering the given content type.
<add> * The template type to use when rendering the given content type.
<ide> *
<ide> * @var string|null
<ide> */
<ide> class RequestHandlerComponent extends Component
<ide> *
<ide> * These are merged with user-provided config when the component is used.
<ide> *
<del> * - `checkHttpCache` - Whether to check for HTTP cache.
<add> * - `checkHttpCache` - Whether to check for HTTP cache. Default `true`.
<ide> * - `viewClassMap` - Mapping between type and view classes. If undefined
<ide> * json, xml, and ajax will be mapped. Defining any types will omit the defaults.
<ide> * - `inputTypeMap` - A mapping between types and deserializers for request bodies.
<ide> public function implementedEvents(): array
<ide> }
<ide>
<ide> /**
<del> * Set the extension based on the accept headers.
<add> * Set the extension based on the `Accept` header or URL extension.
<add> *
<ide> * Compares the accepted types and configured extensions.
<ide> * If there is one common type, that is assigned as the ext/content type for the response.
<ide> * The type with the highest weight will be set. If the highest weight has more
<ide> protected function _setExtension(ServerRequest $request, Response $response): vo
<ide> */
<ide> public function startup(EventInterface $event): void
<ide> {
<del> /** @var \Cake\Controller\Controller $controller */
<del> $controller = $event->getSubject();
<add> $controller = $this->getController();
<ide> $request = $controller->getRequest();
<ide> $response = $controller->getResponse();
<ide>
<del> if ($request->getParam('_ext')) {
<del> $this->ext = $request->getParam('_ext');
<del> }
<add> $this->ext = $request->getParam('_ext');
<ide> if (!$this->ext || in_array($this->ext, ['html', 'htm'], true)) {
<ide> $this->_setExtension($request, $response);
<ide> }
<ide> public function startup(EventInterface $event): void
<ide> if ($request->getParsedBody() !== []) {
<ide> return;
<ide> }
<add>
<ide> foreach ($this->getConfig('inputTypeMap') as $type => $handler) {
<ide> if (!is_callable($handler[0])) {
<ide> throw new RuntimeException(sprintf("Invalid callable for '%s' type.", $type));
<ide> public function convertXml(string $xml): array
<ide> if ((int)$xml->childNodes->length > 0) {
<ide> return Xml::toArray($xml);
<ide> }
<del>
<del> return [];
<ide> } catch (XmlException $e) {
<del> return [];
<ide> }
<add>
<add> return [];
<ide> }
<ide>
<ide> /**
<ide> public function convertXml(string $xml): array
<ide> */
<ide> public function beforeRender(EventInterface $event): void
<ide> {
<del> /** @var \Cake\Controller\Controller $controller */
<del> $controller = $event->getSubject();
<add> $controller = $this->getController();
<ide> $response = $controller->getResponse();
<del> $request = $controller->getRequest();
<ide>
<ide> if ($this->ext && !in_array($this->ext, ['html', 'htm'], true)) {
<ide> if (!$response->getMimeType($this->ext)) {
<ide> public function beforeRender(EventInterface $event): void
<ide>
<ide> if (
<ide> $this->_config['checkHttpCache'] &&
<del> $response->checkNotModified($request)
<add> $response->checkNotModified($controller->getRequest())
<ide> ) {
<ide> $controller->setResponse($response);
<ide> $event->stopPropagation();
<ide>
<ide> return;
<ide> }
<add>
<ide> $controller->setResponse($response);
<ide> }
<ide>
<ide> public function beforeRender(EventInterface $event): void
<ide> public function accepts($type = null)
<ide> {
<ide> $controller = $this->getController();
<del> $request = $controller->getRequest();
<del> $response = $controller->getResponse();
<ide> /** @var array $accepted */
<del> $accepted = $request->accepts();
<add> $accepted = $controller->getRequest()->accepts();
<ide>
<ide> if (!$type) {
<del> return $response->mapType($accepted);
<add> return $controller->getResponse()->mapType($accepted);
<ide> }
<add>
<ide> if (is_array($type)) {
<ide> foreach ($type as $t) {
<ide> $t = $this->mapAlias($t);
<ide> public function accepts($type = null)
<ide>
<ide> return false;
<ide> }
<add>
<ide> if (is_string($type)) {
<ide> return in_array($this->mapAlias($type), $accepted, true);
<ide> }
<ide> public function requestedWith($type = null)
<ide> {
<ide> $controller = $this->getController();
<ide> $request = $controller->getRequest();
<del> $response = $controller->getResponse();
<ide>
<ide> if (
<ide> !$request->is('post') &&
<ide> public function requestedWith($type = null)
<ide>
<ide> [$contentType] = explode(';', $request->contentType() ?? '');
<ide> if ($type === null) {
<del> return $response->mapType($contentType);
<add> return $controller->getResponse()->mapType($contentType);
<ide> }
<add>
<ide> if (is_string($type)) {
<del> return $type === $response->mapType($contentType);
<add> return $type === $controller->getResponse()->mapType($contentType);
<ide> }
<ide> }
<ide>
<ide> public function requestedWith($type = null)
<ide> public function prefers($type = null)
<ide> {
<ide> $controller = $this->getController();
<del> $request = $controller->getRequest();
<del> $response = $controller->getResponse();
<del> /** @var array $acceptRaw */
<del> $acceptRaw = $request->parseAccept();
<ide>
<add> /** @var array $acceptRaw */
<add> $acceptRaw = $controller->getRequest()->parseAccept();
<ide> if (empty($acceptRaw)) {
<ide> return $type ? $type === $this->ext : $this->ext;
<ide> }
<del> /** @var array $accepts */
<del> $accepts = $response->mapType(array_shift($acceptRaw));
<ide>
<add> /** @var array $accepts */
<add> $accepts = $controller->getResponse()->mapType(array_shift($acceptRaw));
<ide> if (!$type) {
<ide> if (empty($this->ext) && !empty($accepts)) {
<ide> return $accepts[0];
<ide> public function prefers($type = null)
<ide> }
<ide>
<ide> $types = (array)$type;
<del>
<ide> if (count($types) === 1) {
<ide> if ($this->ext) {
<ide> return in_array($this->ext, $types, true);
<ide> public function respondAs($type, array $options = []): bool
<ide> if (!$cType) {
<ide> return false;
<ide> }
<add>
<ide> if (!$request->getParam('requested')) {
<ide> $response = $response->withType($cType);
<ide> }
<ide> public function mapAlias($alias)
<ide> if (is_array($alias)) {
<ide> return array_map([$this, 'mapAlias'], $alias);
<ide> }
<del> $response = $this->getController()->getResponse();
<del> $type = $response->getMimeType($alias);
<add>
<add> $type = $this->getController()->getResponse()->getMimeType($alias);
<ide> if ($type) {
<ide> if (is_array($type)) {
<ide> return $type[0]; | 1 |
Javascript | Javascript | fix issues in driver.js when getting css sheets | 4b96735e1d67c5c8363016b32c831dd18e44846b | <ide><path>test/driver.js
<ide> var rasterizeTextLayer = (function rasterizeTextLayerClosure() {
<ide> foreignObject.appendChild(div);
<ide>
<ide> stylePromise
<del> .then(async cssRules => {
<add> .then(async ([cssRules]) => {
<ide> style.textContent = cssRules;
<ide>
<ide> // Rendering text layer as HTML.
<ide> var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
<ide>
<ide> // Rendering annotation layer as HTML.
<ide> stylePromise
<del> .then(async (common, overrides) => {
<del> style.textContent = common + overrides;
<add> .then(async ([common, overrides]) => {
<add> style.textContent = common + "\n" + overrides;
<ide>
<ide> var annotation_viewport = viewport.clone({ dontFlip: true });
<ide> var parameters = {
<ide> var rasterizeXfaLayer = (function rasterizeXfaLayerClosure() {
<ide> foreignObject.appendChild(div);
<ide>
<ide> stylePromise
<del> .then(async cssRules => {
<add> .then(async ([cssRules]) => {
<ide> style.textContent = fontRules + "\n" + cssRules;
<ide>
<ide> XfaLayer.render({ | 1 |
Ruby | Ruby | clarify #form_with `local` option documentation | 491ec7333c6d8c4db21742cd42fc165358b44f4c | <ide><path>actionview/lib/action_view/helpers/form_helper.rb
<ide> def apply_form_for_options!(record, object, options) #:nodoc:
<ide> # This is helpful when fragment-caching the form. Remote forms
<ide> # get the authenticity token from the <tt>meta</tt> tag, so embedding is
<ide> # unnecessary unless you support browsers without JavaScript.
<del> # * <tt>:local</tt> - By default form submits via typical HTTP requests.
<del> # Enable remote and unobtrusive XHRs submits with <tt>local: false</tt>.
<del> # Remote forms may be enabled by default by setting
<del> # <tt>config.action_view.form_with_generates_remote_forms = true</tt>.
<add> # * <tt>:local</tt> - Whether to use standard HTTP form submission.
<add> # When <tt>false</tt>, the form will be a "remote form" which means
<add> # form submission will be handled by rails UJS as an XHR.
<add> # If this option is not specified, the behavior is the inverse of the value of
<add> # <tt>config.action_view.form_with_generates_remote_forms</tt>.
<add> # As of Rails 6.1, that configuration option defaults to <tt>false</tt>
<add> # (which has the equivalent effect of passing <tt>local: true</tt>).
<add> # In previous versions of Rails, that configuration option defaults to
<add> # <tt>true</tt> (the equivalent of passing <tt>local: false</tt>).
<ide> # * <tt>:skip_enforcing_utf8</tt> - If set to true, a hidden input with name
<ide> # utf8 is not output.
<ide> # * <tt>:builder</tt> - Override the object used to build the form. | 1 |
Go | Go | use distribution reference | 3a1279393faf78632bf169619d407e584da84b66 | <ide><path>api/server/router/plugin/backend.go
<ide> import (
<ide> "io"
<ide> "net/http"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> enginetypes "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<del> "github.com/docker/docker/reference"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide><path>api/server/router/plugin/plugin_routes.go
<ide> import (
<ide> "strconv"
<ide> "strings"
<ide>
<del> distreference "github.com/docker/distribution/reference"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/streamformatter"
<del> "github.com/docker/docker/reference"
<ide> "github.com/pkg/errors"
<ide> "golang.org/x/net/context"
<ide> )
<ide> func parseHeaders(headers http.Header) (map[string][]string, *types.AuthConfig)
<ide> // be returned.
<ide> func parseRemoteRef(remote string) (reference.Named, string, error) {
<ide> // Parse remote reference, supporting remotes with name and tag
<del> // NOTE: Using distribution reference to handle references
<del> // containing both a name and digest
<del> remoteRef, err := distreference.ParseNamed(remote)
<add> remoteRef, err := reference.ParseNormalizedNamed(remote)
<ide> if err != nil {
<ide> return nil, "", err
<ide> }
<ide>
<del> var tag string
<del> if t, ok := remoteRef.(distreference.Tagged); ok {
<del> tag = t.Tag()
<add> type canonicalWithTag interface {
<add> reference.Canonical
<add> Tag() string
<ide> }
<ide>
<del> // Convert distribution reference to docker reference
<del> // TODO: remove when docker reference changes reconciled upstream
<del> ref, err := reference.WithName(remoteRef.Name())
<del> if err != nil {
<del> return nil, "", err
<del> }
<del> if d, ok := remoteRef.(distreference.Digested); ok {
<del> ref, err = reference.WithDigest(ref, d.Digest())
<del> if err != nil {
<del> return nil, "", err
<del> }
<del> } else if tag != "" {
<del> ref, err = reference.WithTag(ref, tag)
<add> if canonical, ok := remoteRef.(canonicalWithTag); ok {
<add> remoteRef, err = reference.WithDigest(reference.TrimNamed(remoteRef), canonical.Digest())
<ide> if err != nil {
<ide> return nil, "", err
<ide> }
<del> } else {
<del> ref = reference.WithDefaultTag(ref)
<add> return remoteRef, canonical.Tag(), nil
<ide> }
<ide>
<del> return ref, tag, nil
<add> remoteRef = reference.TagNameOnly(remoteRef)
<add>
<add> return remoteRef, "", nil
<ide> }
<ide>
<ide> func (pr *pluginRouter) getPrivileges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> func getName(ref reference.Named, tag, name string) (string, error) {
<ide> if err != nil {
<ide> return "", err
<ide> }
<del> name = nt.String()
<add> name = reference.FamiliarString(nt)
<ide> } else {
<del> name = reference.WithDefaultTag(trimmed).String()
<add> name = reference.FamiliarString(reference.TagNameOnly(trimmed))
<ide> }
<ide> } else {
<del> name = ref.String()
<add> name = reference.FamiliarString(ref)
<ide> }
<ide> } else {
<del> localRef, err := reference.ParseNamed(name)
<add> localRef, err := reference.ParseNormalizedNamed(name)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> if _, ok := localRef.(reference.Canonical); ok {
<ide> return "", errors.New("cannot use digest in plugin tag")
<ide> }
<del> if distreference.IsNameOnly(localRef) {
<add> if reference.IsNameOnly(localRef) {
<ide> // TODO: log change in name to out stream
<del> name = reference.WithDefaultTag(localRef).String()
<add> name = reference.FamiliarString(reference.TagNameOnly(localRef))
<ide> }
<ide> }
<ide> return name, nil
<ide><path>api/types/reference/image_reference.go
<del>package reference
<del>
<del>import (
<del> distreference "github.com/docker/distribution/reference"
<del>)
<del>
<del>// Parse parses the given references and returns the repository and
<del>// tag (if present) from it. If there is an error during parsing, it will
<del>// return an error.
<del>func Parse(ref string) (string, string, error) {
<del> distributionRef, err := distreference.ParseNamed(ref)
<del> if err != nil {
<del> return "", "", err
<del> }
<del>
<del> tag := GetTagFromNamedRef(distributionRef)
<del> return distributionRef.Name(), tag, nil
<del>}
<del>
<del>// GetTagFromNamedRef returns a tag from the specified reference.
<del>// This function is necessary as long as the docker "server" api makes the distinction between repository
<del>// and tags.
<del>func GetTagFromNamedRef(ref distreference.Named) string {
<del> var tag string
<del> switch x := ref.(type) {
<del> case distreference.Digested:
<del> tag = x.Digest().String()
<del> case distreference.NamedTagged:
<del> tag = x.Tag()
<del> default:
<del> tag = "latest"
<del> }
<del> return tag
<del>}
<ide><path>api/types/reference/image_reference_test.go
<del>package reference
<del>
<del>import (
<del> _ "crypto/sha256"
<del> "testing"
<del>)
<del>
<del>func TestParse(t *testing.T) {
<del> testCases := []struct {
<del> ref string
<del> expectedName string
<del> expectedTag string
<del> expectedError bool
<del> }{
<del> {
<del> ref: "",
<del> expectedName: "",
<del> expectedTag: "",
<del> expectedError: true,
<del> },
<del> {
<del> ref: "repository",
<del> expectedName: "repository",
<del> expectedTag: "latest",
<del> expectedError: false,
<del> },
<del> {
<del> ref: "repository:tag",
<del> expectedName: "repository",
<del> expectedTag: "tag",
<del> expectedError: false,
<del> },
<del> {
<del> ref: "test.com/repository",
<del> expectedName: "test.com/repository",
<del> expectedTag: "latest",
<del> expectedError: false,
<del> },
<del> {
<del> ref: "test.com:5000/test/repository",
<del> expectedName: "test.com:5000/test/repository",
<del> expectedTag: "latest",
<del> expectedError: false,
<del> },
<del> {
<del> ref: "test.com:5000/repo@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
<del> expectedName: "test.com:5000/repo",
<del> expectedTag: "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
<del> expectedError: false,
<del> },
<del> {
<del> ref: "test.com:5000/repo:tag@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
<del> expectedName: "test.com:5000/repo",
<del> expectedTag: "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
<del> expectedError: false,
<del> },
<del> }
<del>
<del> for _, c := range testCases {
<del> name, tag, err := Parse(c.ref)
<del> if err != nil && c.expectedError {
<del> continue
<del> } else if err != nil {
<del> t.Fatalf("error with %s: %s", c.ref, err.Error())
<del> }
<del> if name != c.expectedName {
<del> t.Fatalf("expected name %s, got %s", c.expectedName, name)
<del> }
<del> if tag != c.expectedTag {
<del> t.Fatalf("expected tag %s, got %s", c.expectedTag, tag)
<del> }
<del> }
<del>}
<ide><path>builder/builder.go
<ide> import (
<ide> "os"
<ide> "time"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/image"
<del> "github.com/docker/docker/reference"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide><path>builder/dockerfile/builder.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> apierrors "github.com/docker/docker/api/errors"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/backend"
<ide> import (
<ide> "github.com/docker/docker/builder/dockerfile/parser"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/reference"
<ide> perrors "github.com/pkg/errors"
<ide> "golang.org/x/net/context"
<ide> )
<ide> func sanitizeRepoAndTags(names []string) ([]reference.Named, error) {
<ide> continue
<ide> }
<ide>
<del> ref, err := reference.ParseNamed(repo)
<add> ref, err := reference.ParseNormalizedNamed(repo)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide>
<del> ref = reference.WithDefaultTag(ref)
<del>
<ide> if _, isCanonical := ref.(reference.Canonical); isCanonical {
<ide> return nil, errors.New("build tag cannot contain a digest")
<ide> }
<ide>
<del> if _, isTagged := ref.(reference.NamedTagged); !isTagged {
<del> ref, err = reference.WithTag(ref, reference.DefaultTag)
<del> if err != nil {
<del> return nil, err
<del> }
<del> }
<add> ref = reference.TagNameOnly(ref)
<ide>
<ide> nameWithTag := ref.String()
<ide>
<ide><path>cli/command/container/create.go
<ide> func createContainer(ctx context.Context, dockerCli *command.DockerCli, config *
<ide> return nil, err
<ide> }
<ide> if named, ok := ref.(reference.Named); ok {
<del> if reference.IsNameOnly(named) {
<del> namedRef = reference.EnsureTagged(named)
<del> } else {
<del> namedRef = named
<del> }
<add> namedRef = reference.TagNameOnly(named)
<ide>
<ide> if taggedRef, ok := namedRef.(reference.NamedTagged); ok && command.IsTrusted() {
<ide> var err error
<ide><path>cli/command/formatter/disk_usage.go
<ide> func (ctx *DiskUsageContext) Write() {
<ide> tag := "<none>"
<ide> if len(i.RepoTags) > 0 && !isDangling(*i) {
<ide> // Only show the first tag
<del> ref, err := reference.ParseNamed(i.RepoTags[0])
<add> ref, err := reference.ParseNormalizedNamed(i.RepoTags[0])
<ide> if err != nil {
<ide> continue
<ide> }
<ide> if nt, ok := ref.(reference.NamedTagged); ok {
<del> repo = ref.Name()
<add> repo = reference.FamiliarName(ref)
<ide> tag = nt.Tag()
<ide> }
<ide> }
<ide><path>cli/command/formatter/image.go
<ide> func imageFormat(ctx ImageContext, images []types.ImageSummary, format func(subC
<ide> repoTags := map[string][]string{}
<ide> repoDigests := map[string][]string{}
<ide>
<del> for _, refString := range append(image.RepoTags) {
<add> for _, refString := range image.RepoTags {
<ide> ref, err := reference.ParseNormalizedNamed(refString)
<ide> if err != nil {
<ide> continue
<ide> func imageFormat(ctx ImageContext, images []types.ImageSummary, format func(subC
<ide> repoTags[familiarRef] = append(repoTags[familiarRef], nt.Tag())
<ide> }
<ide> }
<del> for _, refString := range append(image.RepoDigests) {
<add> for _, refString := range image.RepoDigests {
<ide> ref, err := reference.ParseNormalizedNamed(refString)
<ide> if err != nil {
<ide> continue
<ide><path>cli/command/formatter/service.go
<ide> import (
<ide> "strings"
<ide> "time"
<ide>
<del> distreference "github.com/docker/distribution/reference"
<add> "github.com/docker/distribution/reference"
<ide> mounttypes "github.com/docker/docker/api/types/mount"
<ide> "github.com/docker/docker/api/types/swarm"
<ide> "github.com/docker/docker/cli/command/inspect"
<ide> func (c *serviceContext) Replicas() string {
<ide> func (c *serviceContext) Image() string {
<ide> c.AddHeader(imageHeader)
<ide> image := c.service.Spec.TaskTemplate.ContainerSpec.Image
<del> if ref, err := distreference.ParseNamed(image); err == nil {
<del> // update image string for display
<del> namedTagged, ok := ref.(distreference.NamedTagged)
<del> if ok {
<del> image = namedTagged.Name() + ":" + namedTagged.Tag()
<add> if ref, err := reference.ParseNormalizedNamed(image); err == nil {
<add> // update image string for display, (strips any digest)
<add> if nt, ok := ref.(reference.NamedTagged); ok {
<add> if namedTagged, err := reference.WithTag(reference.TrimNamed(nt), nt.Tag()); err == nil {
<add> image = reference.FamiliarString(namedTagged)
<add> }
<ide> }
<ide> }
<ide>
<ide><path>cli/command/image/build.go
<ide> func rewriteDockerfileFrom(ctx context.Context, dockerfile io.Reader, translator
<ide> if err != nil {
<ide> return nil, nil, err
<ide> }
<del> if reference.IsNameOnly(ref) {
<del> ref = reference.EnsureTagged(ref)
<del> }
<add> ref = reference.TagNameOnly(ref)
<ide> if ref, ok := ref.(reference.NamedTagged); ok && command.IsTrusted() {
<ide> trustedRef, err := translator(ctx, ref)
<ide> if err != nil {
<ide><path>cli/command/image/pull.go
<ide> func NewPullCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> }
<ide>
<ide> func runPull(dockerCli *command.DockerCli, opts pullOptions) error {
<del> var distributionRef reference.Named
<ide> distributionRef, err := reference.ParseNormalizedNamed(opts.remote)
<ide> if err != nil {
<ide> return err
<ide> func runPull(dockerCli *command.DockerCli, opts pullOptions) error {
<ide> }
<ide>
<ide> if !opts.all && reference.IsNameOnly(distributionRef) {
<del> taggedRef := reference.EnsureTagged(distributionRef)
<del> fmt.Fprintf(dockerCli.Out(), "Using default tag: %s\n", taggedRef.Tag())
<del> distributionRef = taggedRef
<add> distributionRef = reference.TagNameOnly(distributionRef)
<add> if tagged, ok := distributionRef.(reference.Tagged); ok {
<add> fmt.Fprintf(dockerCli.Out(), "Using default tag: %s\n", tagged.Tag())
<add> }
<ide> }
<ide>
<ide> // Resolve the Repository name from fqn to RepositoryInfo
<ide><path>cli/command/image/trust.go
<ide> func PushTrustedReference(cli *command.DockerCli, repoInfo *registry.RepositoryI
<ide>
<ide> // Initialize the notary repository with a remotely managed snapshot key
<ide> if err := repo.Initialize([]string{rootKeyID}, data.CanonicalSnapshotRole); err != nil {
<del> return trust.NotaryError(repoInfo.FullName(), err)
<add> return trust.NotaryError(repoInfo.Name.Name(), err)
<ide> }
<del> fmt.Fprintf(cli.Out(), "Finished initializing %q\n", repoInfo.FullName())
<add> fmt.Fprintf(cli.Out(), "Finished initializing %q\n", repoInfo.Name.Name())
<ide> err = repo.AddTarget(target, data.CanonicalTargetsRole)
<ide> case nil:
<ide> // already initialized and we have successfully downloaded the latest metadata
<ide> err = addTargetToAllSignableRoles(repo, target)
<ide> default:
<del> return trust.NotaryError(repoInfo.FullName(), err)
<add> return trust.NotaryError(repoInfo.Name.Name(), err)
<ide> }
<ide>
<ide> if err == nil {
<ide> err = repo.Publish()
<ide> }
<ide>
<ide> if err != nil {
<del> fmt.Fprintf(cli.Out(), "Failed to sign %q:%s - %s\n", repoInfo.FullName(), tag, err.Error())
<del> return trust.NotaryError(repoInfo.FullName(), err)
<add> fmt.Fprintf(cli.Out(), "Failed to sign %q:%s - %s\n", repoInfo.Name.Name(), tag, err.Error())
<add> return trust.NotaryError(repoInfo.Name.Name(), err)
<ide> }
<ide>
<del> fmt.Fprintf(cli.Out(), "Successfully signed %q:%s\n", repoInfo.FullName(), tag)
<add> fmt.Fprintf(cli.Out(), "Successfully signed %q:%s\n", repoInfo.Name.Name(), tag)
<ide> return nil
<ide> }
<ide>
<ide> func TrustedReference(ctx context.Context, cli *command.DockerCli, ref reference
<ide>
<ide> t, err := notaryRepo.GetTargetByName(ref.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
<ide> if err != nil {
<del> return nil, trust.NotaryError(repoInfo.FullName(), err)
<add> return nil, trust.NotaryError(repoInfo.Name.Name(), err)
<ide> }
<ide> // Only list tags in the top level targets role or the releases delegation role - ignore
<ide> // all other delegation roles
<ide> if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
<del> return nil, trust.NotaryError(repoInfo.FullName(), fmt.Errorf("No trust data for %s", ref.Tag()))
<add> return nil, trust.NotaryError(repoInfo.Name.Name(), fmt.Errorf("No trust data for %s", ref.Tag()))
<ide> }
<ide> r, err := convertTarget(t.Target)
<ide> if err != nil {
<ide><path>cli/command/plugin/install.go
<ide> import (
<ide>
<ide> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<del> registrytypes "github.com/docker/docker/api/types/registry"
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/cli/command"
<ide> "github.com/docker/docker/cli/command/image"
<ide> func newInstallCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> return cmd
<ide> }
<ide>
<del>func getRepoIndexFromUnnormalizedRef(ref reference.Named) (*registrytypes.IndexInfo, error) {
<del> named, err := reference.ParseNormalizedNamed(ref.Name())
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> repoInfo, err := registry.ParseRepositoryInfo(named)
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> return repoInfo.Index, nil
<del>}
<del>
<ide> type pluginRegistryService struct {
<ide> registry.Service
<ide> }
<ide> func buildPullConfig(ctx context.Context, dockerCli *command.DockerCli, opts plu
<ide>
<ide> _, isCanonical := ref.(reference.Canonical)
<ide> if command.IsTrusted() && !isCanonical {
<add> ref = reference.TagNameOnly(ref)
<ide> nt, ok := ref.(reference.NamedTagged)
<ide> if !ok {
<del> nt = reference.EnsureTagged(ref)
<add> return types.PluginInstallOptions{}, fmt.Errorf("invalid name: %s", ref.String())
<ide> }
<ide>
<ide> ctx := context.Background()
<ide> func runInstall(dockerCli *command.DockerCli, opts pluginOptions) error {
<ide> if _, ok := aref.(reference.Canonical); ok {
<ide> return fmt.Errorf("invalid name: %s", opts.localName)
<ide> }
<del> localName = reference.FamiliarString(reference.EnsureTagged(aref))
<add> localName = reference.FamiliarString(reference.TagNameOnly(aref))
<ide> }
<ide>
<ide> ctx := context.Background()
<ide><path>cli/command/plugin/push.go
<ide> func runPush(dockerCli *command.DockerCli, name string) error {
<ide> return fmt.Errorf("invalid name: %s", name)
<ide> }
<ide>
<del> taggedRef, ok := named.(reference.NamedTagged)
<del> if !ok {
<del> taggedRef = reference.EnsureTagged(named)
<del> }
<add> named = reference.TagNameOnly(named)
<ide>
<ide> ctx := context.Background()
<ide>
<ide> func runPush(dockerCli *command.DockerCli, name string) error {
<ide> return err
<ide> }
<ide>
<del> responseBody, err := dockerCli.Client().PluginPush(ctx, reference.FamiliarString(taggedRef), encodedAuth)
<add> responseBody, err := dockerCli.Client().PluginPush(ctx, reference.FamiliarString(named), encodedAuth)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>cli/command/plugin/upgrade.go
<ide> import (
<ide> "fmt"
<ide> "strings"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/cli/command"
<ide> "github.com/docker/docker/pkg/jsonmessage"
<del> "github.com/docker/docker/reference"
<ide> "github.com/pkg/errors"
<ide> "github.com/spf13/cobra"
<ide> )
<ide> func runUpgrade(dockerCli *command.DockerCli, opts pluginOptions) error {
<ide> if opts.remote == "" {
<ide> opts.remote = p.PluginReference
<ide> }
<del> remote, err := reference.ParseNamed(opts.remote)
<add> remote, err := reference.ParseNormalizedNamed(opts.remote)
<ide> if err != nil {
<ide> return errors.Wrap(err, "error parsing remote upgrade image reference")
<ide> }
<del> remote = reference.WithDefaultTag(remote)
<add> remote = reference.TagNameOnly(remote)
<ide>
<del> old, err := reference.ParseNamed(p.PluginReference)
<add> old, err := reference.ParseNormalizedNamed(p.PluginReference)
<ide> if err != nil {
<ide> return errors.Wrap(err, "error parsing current image reference")
<ide> }
<del> old = reference.WithDefaultTag(old)
<add> old = reference.TagNameOnly(old)
<ide>
<del> fmt.Fprintf(dockerCli.Out(), "Upgrading plugin %s from %s to %s\n", p.Name, old, remote)
<add> fmt.Fprintf(dockerCli.Out(), "Upgrading plugin %s from %s to %s\n", p.Name, reference.FamiliarString(old), reference.FamiliarString(remote))
<ide> if !opts.skipRemoteCheck && remote.String() != old.String() {
<ide> if !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), "Plugin images do not match, are you sure?") {
<ide> return errors.New("canceling upgrade request")
<ide><path>cli/command/service/trust.go
<ide> func resolveServiceImageDigest(dockerCli *command.DockerCli, service *swarm.Serv
<ide> namedRef, ok := ref.(reference.Named)
<ide> if !ok {
<ide> return errors.New("failed to resolve image digest using content trust: reference is not named")
<del>
<ide> }
<del>
<del> taggedRef := reference.EnsureTagged(namedRef)
<add> namedRef = reference.TagNameOnly(namedRef)
<add> taggedRef, ok := namedRef.(reference.NamedTagged)
<add> if !ok {
<add> return errors.New("failed to resolve image digest using content trust: reference is not tagged")
<add> }
<ide>
<ide> resolvedImage, err := trustedResolveDigest(context.Background(), dockerCli, taggedRef)
<ide> if err != nil {
<ide> func trustedResolveDigest(ctx context.Context, cli *command.DockerCli, ref refer
<ide>
<ide> t, err := notaryRepo.GetTargetByName(ref.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
<ide> if err != nil {
<del> return nil, trust.NotaryError(repoInfo.FullName(), err)
<add> return nil, trust.NotaryError(repoInfo.Name.Name(), err)
<ide> }
<ide> // Only get the tag if it's in the top level targets role or the releases delegation role
<ide> // ignore it if it's in any other delegation roles
<ide> if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
<del> return nil, trust.NotaryError(repoInfo.FullName(), fmt.Errorf("No trust data for %s", reference.FamiliarString(ref)))
<add> return nil, trust.NotaryError(repoInfo.Name.Name(), fmt.Errorf("No trust data for %s", reference.FamiliarString(ref)))
<ide> }
<ide>
<ide> logrus.Debugf("retrieving target for %s role\n", t.Role)
<ide><path>cli/command/task/print.go
<ide> import (
<ide>
<ide> "golang.org/x/net/context"
<ide>
<del> distreference "github.com/docker/distribution/reference"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types/swarm"
<ide> "github.com/docker/docker/cli/command"
<ide> "github.com/docker/docker/cli/command/idresolver"
<ide> func print(out io.Writer, ctx context.Context, tasks []swarm.Task, resolver *idr
<ide>
<ide> image := task.Spec.ContainerSpec.Image
<ide> if !noTrunc {
<del> ref, err := distreference.ParseNamed(image)
<add> ref, err := reference.ParseNormalizedNamed(image)
<ide> if err == nil {
<del> // update image string for display
<del> namedTagged, ok := ref.(distreference.NamedTagged)
<del> if ok {
<del> image = namedTagged.Name() + ":" + namedTagged.Tag()
<add> // update image string for display, (strips any digest)
<add> if nt, ok := ref.(reference.NamedTagged); ok {
<add> if namedTagged, err := reference.WithTag(reference.TrimNamed(nt), nt.Tag()); err == nil {
<add> image = reference.FamiliarString(namedTagged)
<add> }
<ide> }
<add>
<ide> }
<ide> }
<ide>
<ide><path>cli/trust/trust.go
<ide> func GetNotaryRepository(streams command.Streams, repoInfo *registry.RepositoryI
<ide> }
<ide>
<ide> scope := auth.RepositoryScope{
<del> Repository: repoInfo.FullName(),
<add> Repository: repoInfo.Name.Name(),
<ide> Actions: actions,
<ide> Class: repoInfo.Class,
<ide> }
<ide> func GetNotaryRepository(streams command.Streams, repoInfo *registry.RepositoryI
<ide>
<ide> return client.NewNotaryRepository(
<ide> trustDirectory(),
<del> repoInfo.FullName(),
<add> repoInfo.Name.Name(),
<ide> server,
<ide> tr,
<ide> getPassphraseRetriever(streams),
<ide><path>client/container_commit.go
<ide> import (
<ide> "errors"
<ide> "net/url"
<ide>
<del> distreference "github.com/docker/distribution/reference"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/api/types/reference"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> // ContainerCommit applies changes into a container and creates a new tagged image.
<ide> func (cli *Client) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) {
<ide> var repository, tag string
<ide> if options.Reference != "" {
<del> distributionRef, err := distreference.ParseNamed(options.Reference)
<add> ref, err := reference.ParseNormalizedNamed(options.Reference)
<ide> if err != nil {
<ide> return types.IDResponse{}, err
<ide> }
<ide>
<del> if _, isCanonical := distributionRef.(distreference.Canonical); isCanonical {
<add> if _, isCanonical := ref.(reference.Canonical); isCanonical {
<ide> return types.IDResponse{}, errors.New("refusing to create a tag with a digest reference")
<ide> }
<add> ref = reference.TagNameOnly(ref)
<ide>
<del> tag = reference.GetTagFromNamedRef(distributionRef)
<del> repository = distributionRef.Name()
<add> if tagged, ok := ref.(reference.Tagged); ok {
<add> tag = tagged.Tag()
<add> }
<add> repository = reference.FamiliarName(ref)
<ide> }
<ide>
<ide> query := url.Values{}
<ide><path>client/image_create.go
<ide> import (
<ide>
<ide> "golang.org/x/net/context"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/api/types/reference"
<ide> )
<ide>
<ide> // ImageCreate creates a new image based in the parent options.
<ide> // It returns the JSON content in the response body.
<ide> func (cli *Client) ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) {
<del> repository, tag, err := reference.Parse(parentReference)
<add> ref, err := reference.ParseNormalizedNamed(parentReference)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> query := url.Values{}
<del> query.Set("fromImage", repository)
<del> query.Set("tag", tag)
<add> query.Set("fromImage", reference.FamiliarName(ref))
<add> query.Set("tag", getAPITagFromNamedRef(ref))
<ide> resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth)
<ide> if err != nil {
<ide> return nil, err
<ide><path>client/image_import.go
<ide> import (
<ide> func (cli *Client) ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) {
<ide> if ref != "" {
<ide> //Check if the given image name can be resolved
<del> if _, err := reference.ParseNamed(ref); err != nil {
<add> if _, err := reference.ParseNormalizedNamed(ref); err != nil {
<ide> return nil, err
<ide> }
<ide> }
<ide><path>client/image_pull.go
<ide> import (
<ide>
<ide> "golang.org/x/net/context"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/api/types/reference"
<ide> )
<ide>
<ide> // ImagePull requests the docker host to pull an image from a remote registry.
<ide> import (
<ide> // FIXME(vdemeester): there is currently used in a few way in docker/docker
<ide> // - if not in trusted content, ref is used to pass the whole reference, and tag is empty
<ide> // - if in trusted content, ref is used to pass the reference name, and tag for the digest
<del>func (cli *Client) ImagePull(ctx context.Context, ref string, options types.ImagePullOptions) (io.ReadCloser, error) {
<del> repository, tag, err := reference.Parse(ref)
<add>func (cli *Client) ImagePull(ctx context.Context, refStr string, options types.ImagePullOptions) (io.ReadCloser, error) {
<add> ref, err := reference.ParseNormalizedNamed(refStr)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> query := url.Values{}
<del> query.Set("fromImage", repository)
<del> if tag != "" && !options.All {
<del> query.Set("tag", tag)
<add> query.Set("fromImage", reference.FamiliarName(ref))
<add> if !options.All {
<add> query.Set("tag", getAPITagFromNamedRef(ref))
<ide> }
<ide>
<ide> resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth)
<ide> func (cli *Client) ImagePull(ctx context.Context, ref string, options types.Imag
<ide> }
<ide> return resp.body, nil
<ide> }
<add>
<add>// getAPITagFromNamedRef returns a tag from the specified reference.
<add>// This function is necessary as long as the docker "server" api expects
<add>// digests to be sent as tags and makes a distinction between the name
<add>// and tag/digest part of a reference.
<add>func getAPITagFromNamedRef(ref reference.Named) string {
<add> if digested, ok := ref.(reference.Digested); ok {
<add> return digested.Digest().String()
<add> }
<add> ref = reference.TagNameOnly(ref)
<add> if tagged, ok := ref.(reference.Tagged); ok {
<add> return tagged.Tag()
<add> }
<add> return ""
<add>}
<ide><path>client/image_pull_test.go
<ide> func TestImagePullReferenceParseError(t *testing.T) {
<ide> }
<ide> // An empty reference is an invalid reference
<ide> _, err := client.ImagePull(context.Background(), "", types.ImagePullOptions{})
<del> if err == nil || err.Error() != "repository name must have at least one component" {
<add> if err == nil || !strings.Contains(err.Error(), "invalid reference format") {
<ide> t.Fatalf("expected an error, got %v", err)
<ide> }
<ide> }
<ide><path>client/image_push.go
<ide> import (
<ide>
<ide> "golang.org/x/net/context"
<ide>
<del> distreference "github.com/docker/distribution/reference"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> )
<ide>
<ide> // ImagePush requests the docker host to push an image to a remote registry.
<ide> // It executes the privileged function if the operation is unauthorized
<ide> // and it tries one more time.
<ide> // It's up to the caller to handle the io.ReadCloser and close it properly.
<del>func (cli *Client) ImagePush(ctx context.Context, ref string, options types.ImagePushOptions) (io.ReadCloser, error) {
<del> distributionRef, err := distreference.ParseNamed(ref)
<add>func (cli *Client) ImagePush(ctx context.Context, image string, options types.ImagePushOptions) (io.ReadCloser, error) {
<add> ref, err := reference.ParseNormalizedNamed(image)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide>
<del> if _, isCanonical := distributionRef.(distreference.Canonical); isCanonical {
<add> if _, isCanonical := ref.(reference.Canonical); isCanonical {
<ide> return nil, errors.New("cannot push a digest reference")
<ide> }
<ide>
<del> var tag = ""
<del> if nameTaggedRef, isNamedTagged := distributionRef.(distreference.NamedTagged); isNamedTagged {
<add> tag := ""
<add> name := reference.FamiliarName(ref)
<add>
<add> if nameTaggedRef, isNamedTagged := ref.(reference.NamedTagged); isNamedTagged {
<ide> tag = nameTaggedRef.Tag()
<ide> }
<ide>
<ide> query := url.Values{}
<ide> query.Set("tag", tag)
<ide>
<del> resp, err := cli.tryImagePush(ctx, distributionRef.Name(), query, options.RegistryAuth)
<add> resp, err := cli.tryImagePush(ctx, name, query, options.RegistryAuth)
<ide> if resp.statusCode == http.StatusUnauthorized && options.PrivilegeFunc != nil {
<ide> newAuthHeader, privilegeErr := options.PrivilegeFunc()
<ide> if privilegeErr != nil {
<ide> return nil, privilegeErr
<ide> }
<del> resp, err = cli.tryImagePush(ctx, distributionRef.Name(), query, newAuthHeader)
<add> resp, err = cli.tryImagePush(ctx, name, query, newAuthHeader)
<ide> }
<ide> if err != nil {
<ide> return nil, err
<ide><path>client/image_push_test.go
<ide> func TestImagePushReferenceError(t *testing.T) {
<ide> }
<ide> // An empty reference is an invalid reference
<ide> _, err := client.ImagePush(context.Background(), "", types.ImagePushOptions{})
<del> if err == nil || err.Error() != "repository name must have at least one component" {
<add> if err == nil || !strings.Contains(err.Error(), "invalid reference format") {
<ide> t.Fatalf("expected an error, got %v", err)
<ide> }
<ide> // An canonical reference cannot be pushed
<ide><path>client/image_tag.go
<ide> package client
<ide> import (
<ide> "net/url"
<ide>
<del> distreference "github.com/docker/distribution/reference"
<del> "github.com/docker/docker/api/types/reference"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/pkg/errors"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> // ImageTag tags an image in the docker host
<ide> func (cli *Client) ImageTag(ctx context.Context, source, target string) error {
<del> if _, err := distreference.ParseNamed(source); err != nil {
<add> if _, err := reference.ParseNormalizedNamed(source); err != nil {
<ide> return errors.Wrapf(err, "Error parsing reference: %q is not a valid repository/tag", source)
<ide> }
<ide>
<del> distributionRef, err := distreference.ParseNamed(target)
<add> ref, err := reference.ParseNormalizedNamed(target)
<ide> if err != nil {
<ide> return errors.Wrapf(err, "Error parsing reference: %q is not a valid repository/tag", target)
<ide> }
<ide>
<del> if _, isCanonical := distributionRef.(distreference.Canonical); isCanonical {
<add> if _, isCanonical := ref.(reference.Canonical); isCanonical {
<ide> return errors.New("refusing to create a tag with a digest reference")
<ide> }
<ide>
<del> tag := reference.GetTagFromNamedRef(distributionRef)
<add> ref = reference.TagNameOnly(ref)
<ide>
<ide> query := url.Values{}
<del> query.Set("repo", distributionRef.Name())
<del> query.Set("tag", tag)
<add> query.Set("repo", reference.FamiliarName(ref))
<add> if tagged, ok := ref.(reference.Tagged); ok {
<add> query.Set("tag", tagged.Tag())
<add> }
<ide>
<ide> resp, err := cli.post(ctx, "/images/"+source+"/tag", query, nil, nil)
<ide> ensureReaderClosed(resp)
<ide><path>client/plugin_install.go
<ide> import (
<ide> // PluginInstall installs a plugin
<ide> func (cli *Client) PluginInstall(ctx context.Context, name string, options types.PluginInstallOptions) (rc io.ReadCloser, err error) {
<ide> query := url.Values{}
<del> if _, err := reference.ParseNamed(options.RemoteRef); err != nil {
<add> if _, err := reference.ParseNormalizedNamed(options.RemoteRef); err != nil {
<ide> return nil, errors.Wrap(err, "invalid remote reference")
<ide> }
<ide> query.Set("remote", options.RemoteRef)
<ide><path>client/plugin_upgrade.go
<ide> import (
<ide> // PluginUpgrade upgrades a plugin
<ide> func (cli *Client) PluginUpgrade(ctx context.Context, name string, options types.PluginInstallOptions) (rc io.ReadCloser, err error) {
<ide> query := url.Values{}
<del> if _, err := reference.ParseNamed(options.RemoteRef); err != nil {
<add> if _, err := reference.ParseNormalizedNamed(options.RemoteRef); err != nil {
<ide> return nil, errors.Wrap(err, "invalid remote reference")
<ide> }
<ide> query.Set("remote", options.RemoteRef)
<ide><path>daemon/cluster/cluster.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<del> distreference "github.com/docker/distribution/reference"
<add> "github.com/docker/distribution/reference"
<ide> apierrors "github.com/docker/docker/api/errors"
<ide> apitypes "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/backend"
<ide> import (
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/signal"
<ide> "github.com/docker/docker/pkg/stdcopy"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/runconfig"
<ide> swarmapi "github.com/docker/swarmkit/api"
<ide> "github.com/docker/swarmkit/manager/encryption"
<ide> swarmnode "github.com/docker/swarmkit/node"
<ide> gogotypes "github.com/gogo/protobuf/types"
<del> "github.com/opencontainers/go-digest"
<ide> "github.com/pkg/errors"
<ide> "golang.org/x/net/context"
<ide> )
<ide> func (c *Cluster) GetServices(options apitypes.ServiceListOptions) ([]types.Serv
<ide> }
<ide>
<ide> // imageWithDigestString takes an image such as name or name:tag
<del>// and returns the image pinned to a digest, such as name@sha256:34234...
<del>// Due to the difference between the docker/docker/reference, and the
<del>// docker/distribution/reference packages, we're parsing the image twice.
<del>// As the two packages converge, this function should be simplified.
<del>// TODO(nishanttotla): After the packages converge, the function must
<del>// convert distreference.Named -> distreference.Canonical, and the logic simplified.
<add>// and returns the image pinned to a digest, such as name@sha256:34234
<ide> func (c *Cluster) imageWithDigestString(ctx context.Context, image string, authConfig *apitypes.AuthConfig) (string, error) {
<del> if _, err := digest.Parse(image); err == nil {
<del> return "", errors.New("image reference is an image ID")
<del> }
<del> ref, err := distreference.ParseNamed(image)
<add> ref, err := reference.ParseAnyReference(image)
<ide> if err != nil {
<ide> return "", err
<ide> }
<del> // only query registry if not a canonical reference (i.e. with digest)
<del> if _, ok := ref.(distreference.Canonical); !ok {
<del> // create a docker/docker/reference Named object because GetRepository needs it
<del> dockerRef, err := reference.ParseNamed(image)
<del> if err != nil {
<del> return "", err
<add> namedRef, ok := ref.(reference.Named)
<add> if !ok {
<add> if _, ok := ref.(reference.Digested); ok {
<add> return "", errors.New("image reference is an image ID")
<ide> }
<del> dockerRef = reference.WithDefaultTag(dockerRef)
<del> namedTaggedRef, ok := dockerRef.(reference.NamedTagged)
<add> return "", errors.Errorf("unknown image reference format: %s", image)
<add> }
<add> // only query registry if not a canonical reference (i.e. with digest)
<add> if _, ok := namedRef.(reference.Canonical); !ok {
<add> namedRef = reference.TagNameOnly(namedRef)
<add>
<add> taggedRef, ok := namedRef.(reference.NamedTagged)
<ide> if !ok {
<del> return "", errors.New("unable to cast image to NamedTagged reference object")
<add> return "", errors.Errorf("image reference not tagged: %s", image)
<ide> }
<ide>
<del> repo, _, err := c.config.Backend.GetRepository(ctx, namedTaggedRef, authConfig)
<add> repo, _, err := c.config.Backend.GetRepository(ctx, taggedRef, authConfig)
<ide> if err != nil {
<ide> return "", err
<ide> }
<del> dscrptr, err := repo.Tags(ctx).Get(ctx, namedTaggedRef.Tag())
<add> dscrptr, err := repo.Tags(ctx).Get(ctx, taggedRef.Tag())
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide>
<del> namedDigestedRef, err := distreference.WithDigest(distreference.EnsureTagged(ref), dscrptr.Digest)
<add> namedDigestedRef, err := reference.WithDigest(taggedRef, dscrptr.Digest)
<ide> if err != nil {
<ide> return "", err
<ide> }
<del> return namedDigestedRef.String(), nil
<add> // return familiar form until interface updated to return type
<add> return reference.FamiliarString(namedDigestedRef), nil
<ide> }
<ide> // reference already contains a digest, so just return it
<del> return ref.String(), nil
<add> return reference.FamiliarString(ref), nil
<ide> }
<ide>
<ide> // CreateService creates a new service in a managed swarm cluster.
<ide><path>daemon/cluster/executor/backend.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/distribution"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/api/types/container"
<ide> import (
<ide> swarmtypes "github.com/docker/docker/api/types/swarm"
<ide> clustertypes "github.com/docker/docker/daemon/cluster/provider"
<ide> "github.com/docker/docker/plugin"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/libnetwork"
<ide> "github.com/docker/libnetwork/cluster"
<ide> networktypes "github.com/docker/libnetwork/types"
<ide><path>daemon/cluster/executor/container/adapter.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/backend"
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/daemon/cluster/convert"
<ide> executorpkg "github.com/docker/docker/daemon/cluster/executor"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/libnetwork"
<ide> "github.com/docker/swarmkit/agent/exec"
<ide> "github.com/docker/swarmkit/api"
<ide> func (c *containerAdapter) pullImage(ctx context.Context) error {
<ide>
<ide> // Skip pulling if the image is referenced by digest and already
<ide> // exists locally.
<del> named, err := reference.ParseNamed(spec.Image)
<add> named, err := reference.ParseNormalizedNamed(spec.Image)
<ide> if err == nil {
<ide> if _, ok := named.(reference.Canonical); ok {
<ide> _, err := c.backend.LookupImage(spec.Image)
<ide><path>daemon/cluster/executor/container/container.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> enginecontainer "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/api/types/events"
<ide> import (
<ide> "github.com/docker/docker/api/types/network"
<ide> volumetypes "github.com/docker/docker/api/types/volume"
<ide> clustertypes "github.com/docker/docker/daemon/cluster/provider"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/go-connections/nat"
<ide> "github.com/docker/swarmkit/agent/exec"
<ide> "github.com/docker/swarmkit/api"
<ide> func (c *containerConfig) name() string {
<ide>
<ide> func (c *containerConfig) image() string {
<ide> raw := c.spec().Image
<del> ref, err := reference.ParseNamed(raw)
<add> ref, err := reference.ParseNormalizedNamed(raw)
<ide> if err != nil {
<ide> return raw
<ide> }
<del> return reference.WithDefaultTag(ref).String()
<add> return reference.FamiliarString(reference.TagNameOnly(ref))
<ide> }
<ide>
<ide> func (c *containerConfig) portBindings() nat.PortMap {
<ide><path>daemon/commit.go
<ide> package daemon
<ide>
<ide> import (
<ide> "encoding/json"
<del> "fmt"
<ide> "io"
<ide> "runtime"
<ide> "strings"
<ide> "time"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types/backend"
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/builder/dockerfile"
<ide> import (
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/reference"
<add> "github.com/pkg/errors"
<ide> )
<ide>
<ide> // merge merges two Config, the image container configuration (defaults values),
<ide> func (daemon *Daemon) Commit(name string, c *backend.ContainerCommitConfig) (str
<ide>
<ide> // It is not possible to commit a running container on Windows and on Solaris.
<ide> if (runtime.GOOS == "windows" || runtime.GOOS == "solaris") && container.IsRunning() {
<del> return "", fmt.Errorf("%+v does not support commit of a running container", runtime.GOOS)
<add> return "", errors.Errorf("%+v does not support commit of a running container", runtime.GOOS)
<ide> }
<ide>
<ide> if c.Pause && !container.IsPaused() {
<ide> func (daemon *Daemon) Commit(name string, c *backend.ContainerCommitConfig) (str
<ide>
<ide> imageRef := ""
<ide> if c.Repo != "" {
<del> newTag, err := reference.WithName(c.Repo) // todo: should move this to API layer
<add> newTag, err := reference.ParseNormalizedNamed(c.Repo) // todo: should move this to API layer
<ide> if err != nil {
<ide> return "", err
<ide> }
<add> if !reference.IsNameOnly(newTag) {
<add> return "", errors.Errorf("unexpected repository name: %s", c.Repo)
<add> }
<ide> if c.Tag != "" {
<ide> if newTag, err = reference.WithTag(newTag, c.Tag); err != nil {
<ide> return "", err
<ide> func (daemon *Daemon) Commit(name string, c *backend.ContainerCommitConfig) (str
<ide> if err := daemon.TagImageWithReference(id, newTag); err != nil {
<ide> return "", err
<ide> }
<del> imageRef = newTag.String()
<add> imageRef = reference.FamiliarString(newTag)
<ide> }
<ide>
<ide> attributes := map[string]string{
<ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/pkg/truncindex"
<ide> "github.com/docker/docker/plugin"
<del> "github.com/docker/docker/reference"
<add> refstore "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/runconfig"
<ide> volumedrivers "github.com/docker/docker/volume/drivers"
<ide> type Daemon struct {
<ide> repository string
<ide> containers container.Store
<ide> execCommands *exec.Store
<del> referenceStore reference.Store
<add> referenceStore refstore.Store
<ide> downloadManager *xfer.LayerDownloadManager
<ide> uploadManager *xfer.LayerUploadManager
<ide> distributionMetadataStore dmetadata.Store
<ide> func NewDaemon(config *Config, registryService registry.Service, containerdRemot
<ide>
<ide> eventsService := events.New()
<ide>
<del> referenceStore, err := reference.NewReferenceStore(filepath.Join(imageRoot, "repositories.json"))
<add> referenceStore, err := refstore.NewReferenceStore(filepath.Join(imageRoot, "repositories.json"))
<ide> if err != nil {
<ide> return nil, fmt.Errorf("Couldn't create Tag store repositories: %s", err)
<ide> }
<ide><path>daemon/daemon_solaris.go
<ide> import (
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> "github.com/docker/docker/pkg/sysinfo"
<del> "github.com/docker/docker/reference"
<add> refstore "github.com/docker/docker/reference"
<ide> "github.com/docker/libnetwork"
<ide> nwconfig "github.com/docker/libnetwork/config"
<ide> "github.com/docker/libnetwork/drivers/solaris/bridge"
<ide> func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container
<ide> return daemon.Unmount(container)
<ide> }
<ide>
<del>func restoreCustomImage(is image.Store, ls layer.Store, rs reference.Store) error {
<add>func restoreCustomImage(is image.Store, ls layer.Store, rs refstore.Store) error {
<ide> // Solaris has no custom images to register
<ide> return nil
<ide> }
<ide><path>daemon/errors.go
<ide> package daemon
<ide>
<ide> import (
<ide> "fmt"
<del> "strings"
<ide>
<ide> "github.com/docker/docker/api/errors"
<del> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> func (d *Daemon) imageNotExistToErrcode(err error) error {
<ide> if dne, isDNE := err.(ErrImageDoesNotExist); isDNE {
<del> if strings.Contains(dne.RefOrID, "@") {
<del> e := fmt.Errorf("No such image: %s", dne.RefOrID)
<del> return errors.NewRequestNotFoundError(e)
<del> }
<del> tag := reference.DefaultTag
<del> ref, err := reference.ParseNamed(dne.RefOrID)
<del> if err != nil {
<del> e := fmt.Errorf("No such image: %s:%s", dne.RefOrID, tag)
<del> return errors.NewRequestNotFoundError(e)
<del> }
<del> if tagged, isTagged := ref.(reference.NamedTagged); isTagged {
<del> tag = tagged.Tag()
<del> }
<del> e := fmt.Errorf("No such image: %s:%s", ref.Name(), tag)
<del> return errors.NewRequestNotFoundError(e)
<add> return errors.NewRequestNotFoundError(dne)
<ide> }
<ide> return err
<ide> }
<ide><path>daemon/events/filter.go
<ide> package events
<ide>
<ide> import (
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/api/types/filters"
<del> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> // Filter can filter out docker events from a stream
<ide> func (ef *Filter) matchImage(ev events.Message) bool {
<ide> }
<ide>
<ide> func stripTag(image string) string {
<del> ref, err := reference.ParseNamed(image)
<add> ref, err := reference.ParseNormalizedNamed(image)
<ide> if err != nil {
<ide> return image
<ide> }
<del> return ref.Name()
<add> return reference.FamiliarName(ref)
<ide> }
<ide><path>daemon/image.go
<ide> package daemon
<ide> import (
<ide> "fmt"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> // ErrImageDoesNotExist is error returned when no image can be found for a reference.
<ide> type ErrImageDoesNotExist struct {
<del> RefOrID string
<add> ref reference.Reference
<ide> }
<ide>
<ide> func (e ErrImageDoesNotExist) Error() string {
<del> return fmt.Sprintf("no such id: %s", e.RefOrID)
<add> ref := e.ref
<add> if named, ok := ref.(reference.Named); ok {
<add> ref = reference.TagNameOnly(named)
<add> }
<add> return fmt.Sprintf("No such image: %s", reference.FamiliarString(ref))
<ide> }
<ide>
<ide> // GetImageID returns an image ID corresponding to the image referred to by
<ide> // refOrID.
<ide> func (daemon *Daemon) GetImageID(refOrID string) (image.ID, error) {
<del> id, ref, err := reference.ParseIDOrReference(refOrID)
<add> ref, err := reference.ParseAnyReference(refOrID)
<ide> if err != nil {
<ide> return "", err
<ide> }
<del> if id != "" {
<del> if _, err := daemon.imageStore.Get(image.IDFromDigest(id)); err != nil {
<del> return "", ErrImageDoesNotExist{refOrID}
<add> namedRef, ok := ref.(reference.Named)
<add> if !ok {
<add> digested, ok := ref.(reference.Digested)
<add> if !ok {
<add> return "", ErrImageDoesNotExist{ref}
<ide> }
<del> return image.IDFromDigest(id), nil
<add> id := image.IDFromDigest(digested.Digest())
<add> if _, err := daemon.imageStore.Get(id); err != nil {
<add> return "", ErrImageDoesNotExist{ref}
<add> }
<add> return id, nil
<ide> }
<ide>
<del> if id, err := daemon.referenceStore.Get(ref); err == nil {
<add> if id, err := daemon.referenceStore.Get(namedRef); err == nil {
<ide> return image.IDFromDigest(id), nil
<ide> }
<ide>
<ide> // deprecated: repo:shortid https://github.com/docker/docker/pull/799
<del> if tagged, ok := ref.(reference.NamedTagged); ok {
<add> if tagged, ok := namedRef.(reference.Tagged); ok {
<ide> if tag := tagged.Tag(); stringid.IsShortID(stringid.TruncateID(tag)) {
<ide> if id, err := daemon.imageStore.Search(tag); err == nil {
<del> for _, namedRef := range daemon.referenceStore.References(id.Digest()) {
<del> if namedRef.Name() == ref.Name() {
<add> for _, storeRef := range daemon.referenceStore.References(id.Digest()) {
<add> if storeRef.Name() == namedRef.Name() {
<ide> return id, nil
<ide> }
<ide> }
<ide> func (daemon *Daemon) GetImageID(refOrID string) (image.ID, error) {
<ide> return id, nil
<ide> }
<ide>
<del> return "", ErrImageDoesNotExist{refOrID}
<add> return "", ErrImageDoesNotExist{ref}
<ide> }
<ide>
<ide> // GetImage returns an image corresponding to the image referred to by refOrID.
<ide><path>daemon/image_delete.go
<ide> import (
<ide> "strings"
<ide> "time"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/errors"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> type conflictType int
<ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I
<ide> }
<ide> }
<ide>
<del> parsedRef, err := reference.ParseNamed(imageRef)
<add> parsedRef, err := reference.ParseNormalizedNamed(imageRef)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I
<ide> return nil, err
<ide> }
<ide>
<del> untaggedRecord := types.ImageDeleteResponseItem{Untagged: parsedRef.String()}
<add> untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
<ide>
<ide> daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
<ide> records = append(records, untaggedRecord)
<ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I
<ide> return records, err
<ide> }
<ide>
<del> untaggedRecord := types.ImageDeleteResponseItem{Untagged: repoRef.String()}
<add> untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(repoRef)}
<ide> records = append(records, untaggedRecord)
<ide> } else {
<ide> remainingRefs = append(remainingRefs, repoRef)
<ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I
<ide> return nil, err
<ide> }
<ide>
<del> untaggedRecord := types.ImageDeleteResponseItem{Untagged: parsedRef.String()}
<add> untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
<ide>
<ide> daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
<ide> records = append(records, untaggedRecord)
<ide> func (daemon *Daemon) getContainerUsingImage(imageID image.ID) *container.Contai
<ide> // optional tag or digest reference. If tag or digest is omitted, the default
<ide> // tag is used. Returns the resolved image reference and an error.
<ide> func (daemon *Daemon) removeImageRef(ref reference.Named) (reference.Named, error) {
<del> ref = reference.WithDefaultTag(ref)
<add> ref = reference.TagNameOnly(ref)
<add>
<ide> // Ignore the boolean value returned, as far as we're concerned, this
<ide> // is an idempotent operation and it's okay if the reference didn't
<ide> // exist in the first place.
<ide> func (daemon *Daemon) removeAllReferencesToImageID(imgID image.ID, records *[]ty
<ide> return err
<ide> }
<ide>
<del> untaggedRecord := types.ImageDeleteResponseItem{Untagged: parsedRef.String()}
<add> untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
<ide>
<ide> daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
<ide> *records = append(*records, untaggedRecord)
<ide><path>daemon/image_history.go
<ide> import (
<ide> "fmt"
<ide> "time"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types/image"
<ide> "github.com/docker/docker/layer"
<del> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> // ImageHistory returns a slice of ImageHistory structures for the specified image
<ide> func (daemon *Daemon) ImageHistory(name string) ([]*image.HistoryResponseItem, e
<ide> var tags []string
<ide> for _, r := range daemon.referenceStore.References(id.Digest()) {
<ide> if _, ok := r.(reference.NamedTagged); ok {
<del> tags = append(tags, r.String())
<add> tags = append(tags, reference.FamiliarString(r))
<ide> }
<ide> }
<ide>
<ide><path>daemon/image_inspect.go
<ide> package daemon
<ide> import (
<ide> "time"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/layer"
<del> "github.com/docker/docker/reference"
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<ide> func (daemon *Daemon) LookupImage(name string) (*types.ImageInspect, error) {
<ide> for _, ref := range refs {
<ide> switch ref.(type) {
<ide> case reference.NamedTagged:
<del> repoTags = append(repoTags, ref.String())
<add> repoTags = append(repoTags, reference.FamiliarString(ref))
<ide> case reference.Canonical:
<del> repoDigests = append(repoDigests, ref.String())
<add> repoDigests = append(repoDigests, reference.FamiliarString(ref))
<ide> }
<ide> }
<ide>
<ide><path>daemon/image_pull.go
<ide> import (
<ide> "strings"
<ide>
<ide> dist "github.com/docker/distribution"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/distribution"
<ide> progressutils "github.com/docker/docker/distribution/utils"
<ide> "github.com/docker/docker/pkg/progress"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/opencontainers/go-digest"
<ide> "golang.org/x/net/context"
<ide> func (daemon *Daemon) PullImage(ctx context.Context, image, tag string, metaHead
<ide> // compatibility.
<ide> image = strings.TrimSuffix(image, ":")
<ide>
<del> ref, err := reference.ParseNamed(image)
<add> ref, err := reference.ParseNormalizedNamed(image)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (daemon *Daemon) PullImage(ctx context.Context, image, tag string, metaHead
<ide>
<ide> // PullOnBuild tells Docker to pull image referenced by `name`.
<ide> func (daemon *Daemon) PullOnBuild(ctx context.Context, name string, authConfigs map[string]types.AuthConfig, output io.Writer) (builder.Image, error) {
<del> ref, err := reference.ParseNamed(name)
<add> ref, err := reference.ParseNormalizedNamed(name)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> ref = reference.WithDefaultTag(ref)
<add> ref = reference.TagNameOnly(ref)
<ide>
<ide> pullRegistryAuth := &types.AuthConfig{}
<ide> if len(authConfigs) > 0 {
<ide> func (daemon *Daemon) GetRepository(ctx context.Context, ref reference.NamedTagg
<ide> return nil, false, err
<ide> }
<ide> // makes sure name is not empty or `scratch`
<del> if err := distribution.ValidateRepoName(repoInfo.Name()); err != nil {
<add> if err := distribution.ValidateRepoName(repoInfo.Name); err != nil {
<ide> return nil, false, err
<ide> }
<ide>
<ide> // get endpoints
<del> endpoints, err := daemon.RegistryService.LookupPullEndpoints(repoInfo.Hostname())
<add> endpoints, err := daemon.RegistryService.LookupPullEndpoints(reference.Domain(repoInfo.Name))
<ide> if err != nil {
<ide> return nil, false, err
<ide> }
<ide><path>daemon/image_push.go
<ide> import (
<ide> "io"
<ide>
<ide> "github.com/docker/distribution/manifest/schema2"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/distribution"
<ide> progressutils "github.com/docker/docker/distribution/utils"
<ide> "github.com/docker/docker/pkg/progress"
<del> "github.com/docker/docker/reference"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> // PushImage initiates a push operation on the repository named localName.
<ide> func (daemon *Daemon) PushImage(ctx context.Context, image, tag string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<del> ref, err := reference.ParseNamed(image)
<add> ref, err := reference.ParseNormalizedNamed(image)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>daemon/image_tag.go
<ide> package daemon
<ide>
<ide> import (
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/image"
<del> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> // TagImage creates the tag specified by newTag, pointing to the image named
<ide> func (daemon *Daemon) TagImage(imageName, repository, tag string) error {
<ide> return err
<ide> }
<ide>
<del> newTag, err := reference.WithName(repository)
<add> newTag, err := reference.ParseNormalizedNamed(repository)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> if tag != "" {
<del> if newTag, err = reference.WithTag(newTag, tag); err != nil {
<add> if newTag, err = reference.WithTag(reference.TrimNamed(newTag), tag); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (daemon *Daemon) TagImageWithReference(imageID image.ID, newTag reference.N
<ide> return err
<ide> }
<ide>
<del> daemon.LogImageEvent(imageID.String(), newTag.String(), "tag")
<add> daemon.LogImageEvent(imageID.String(), reference.FamiliarString(newTag), "tag")
<ide> return nil
<ide> }
<ide><path>daemon/images.go
<ide> func (daemon *Daemon) Images(imageFilters filters.Args, all bool, withExtraAttrs
<ide> var found bool
<ide> var matchErr error
<ide> for _, pattern := range imageFilters.Get("reference") {
<del> found, matchErr = reference.Match(pattern, ref)
<add> found, matchErr = reference.FamiliarMatch(pattern, ref)
<ide> if matchErr != nil {
<ide> return nil, matchErr
<ide> }
<ide> func (daemon *Daemon) Images(imageFilters filters.Args, all bool, withExtraAttrs
<ide> }
<ide> }
<ide> if _, ok := ref.(reference.Canonical); ok {
<del> newImage.RepoDigests = append(newImage.RepoDigests, ref.String())
<add> newImage.RepoDigests = append(newImage.RepoDigests, reference.FamiliarString(ref))
<ide> }
<ide> if _, ok := ref.(reference.NamedTagged); ok {
<del> newImage.RepoTags = append(newImage.RepoTags, ref.String())
<add> newImage.RepoTags = append(newImage.RepoTags, reference.FamiliarString(ref))
<ide> }
<ide> }
<ide> if newImage.RepoDigests == nil && newImage.RepoTags == nil {
<ide><path>daemon/import.go
<ide> package daemon
<ide>
<ide> import (
<ide> "encoding/json"
<del> "errors"
<ide> "io"
<ide> "net/http"
<ide> "net/url"
<ide> "runtime"
<ide> "time"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/builder/dockerfile"
<ide> "github.com/docker/docker/dockerversion"
<ide> import (
<ide> "github.com/docker/docker/pkg/httputils"
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/streamformatter"
<del> "github.com/docker/docker/reference"
<add> "github.com/pkg/errors"
<ide> )
<ide>
<ide> // ImportImage imports an image, getting the archived layer data either from
<ide> func (daemon *Daemon) ImportImage(src string, repository, tag string, msg string
<ide>
<ide> if repository != "" {
<ide> var err error
<del> newRef, err = reference.ParseNamed(repository)
<add> newRef, err = reference.ParseNormalizedNamed(repository)
<ide> if err != nil {
<ide> return err
<ide> }
<del>
<ide> if _, isCanonical := newRef.(reference.Canonical); isCanonical {
<ide> return errors.New("cannot import digest reference")
<ide> }
<ide><path>daemon/prune.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<ide> timetypes "github.com/docker/docker/api/types/time"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/directory"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/volume"
<ide> "github.com/docker/libnetwork"
<ide><path>distribution/config.go
<ide> import (
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/progress"
<del> "github.com/docker/docker/reference"
<add> refstore "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/libtrust"
<ide> "github.com/opencontainers/go-digest"
<ide> type Config struct {
<ide> ImageStore ImageConfigStore
<ide> // ReferenceStore manages tags. This value is optional, when excluded
<ide> // content will not be tagged.
<del> ReferenceStore reference.Store
<add> ReferenceStore refstore.Store
<ide> // RequireSchema2 ensures that only schema2 manifests are used.
<ide> RequireSchema2 bool
<ide> }
<ide><path>distribution/errors.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/api/errcode"
<ide> "github.com/docker/distribution/registry/api/v2"
<ide> "github.com/docker/distribution/registry/client"
<ide> "github.com/docker/distribution/registry/client/auth"
<ide> "github.com/docker/docker/distribution/xfer"
<del> "github.com/docker/docker/reference"
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<ide> func TranslatePullError(err error, ref reference.Named) error {
<ide> switch v.Code {
<ide> case errcode.ErrorCodeDenied:
<ide> // ErrorCodeDenied is used when access to the repository was denied
<del> newErr = errors.Errorf("repository %s not found: does not exist or no pull access", ref.Name())
<add> newErr = errors.Errorf("repository %s not found: does not exist or no pull access", reference.FamiliarName(ref))
<ide> case v2.ErrorCodeManifestUnknown:
<del> newErr = errors.Errorf("manifest for %s not found", ref.String())
<add> newErr = errors.Errorf("manifest for %s not found", reference.FamiliarString(ref))
<ide> case v2.ErrorCodeNameUnknown:
<del> newErr = errors.Errorf("repository %s not found", ref.Name())
<add> newErr = errors.Errorf("repository %s not found", reference.FamiliarName(ref))
<ide> }
<ide> if newErr != nil {
<ide> logrus.Infof("Translating %q to %q", err, newErr)
<ide><path>distribution/pull.go
<ide> package distribution
<ide>
<ide> import (
<del> "errors"
<ide> "fmt"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/pkg/progress"
<del> "github.com/docker/docker/reference"
<add> refstore "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/opencontainers/go-digest"
<ide> "golang.org/x/net/context"
<ide> func Pull(ctx context.Context, ref reference.Named, imagePullConfig *ImagePullCo
<ide> return err
<ide> }
<ide>
<del> // makes sure name is not empty or `scratch`
<del> if err := ValidateRepoName(repoInfo.Name()); err != nil {
<add> // makes sure name is not `scratch`
<add> if err := ValidateRepoName(repoInfo.Name); err != nil {
<ide> return err
<ide> }
<ide>
<del> endpoints, err := imagePullConfig.RegistryService.LookupPullEndpoints(repoInfo.Hostname())
<add> endpoints, err := imagePullConfig.RegistryService.LookupPullEndpoints(reference.Domain(repoInfo.Name))
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func Pull(ctx context.Context, ref reference.Named, imagePullConfig *ImagePullCo
<ide> }
<ide> }
<ide>
<del> logrus.Debugf("Trying to pull %s from %s %s", repoInfo.Name(), endpoint.URL, endpoint.Version)
<add> logrus.Debugf("Trying to pull %s from %s %s", reference.FamiliarName(repoInfo.Name), endpoint.URL, endpoint.Version)
<ide>
<ide> puller, err := newPuller(endpoint, repoInfo, imagePullConfig)
<ide> if err != nil {
<ide> func Pull(ctx context.Context, ref reference.Named, imagePullConfig *ImagePullCo
<ide> return TranslatePullError(err, ref)
<ide> }
<ide>
<del> imagePullConfig.ImageEventLogger(ref.String(), repoInfo.Name(), "pull")
<add> imagePullConfig.ImageEventLogger(reference.FamiliarString(ref), reference.FamiliarName(repoInfo.Name), "pull")
<ide> return nil
<ide> }
<ide>
<ide> if lastErr == nil {
<del> lastErr = fmt.Errorf("no endpoints found for %s", ref.String())
<add> lastErr = fmt.Errorf("no endpoints found for %s", reference.FamiliarString(ref))
<ide> }
<ide>
<ide> return TranslatePullError(lastErr, ref)
<ide> func writeStatus(requestedTag string, out progress.Output, layersDownloaded bool
<ide> }
<ide>
<ide> // ValidateRepoName validates the name of a repository.
<del>func ValidateRepoName(name string) error {
<del> if name == "" {
<del> return errors.New("Repository name can't be empty")
<del> }
<del> if name == api.NoBaseImageSpecifier {
<add>func ValidateRepoName(name reference.Named) error {
<add> if reference.FamiliarName(name) == api.NoBaseImageSpecifier {
<ide> return fmt.Errorf("'%s' is a reserved name", api.NoBaseImageSpecifier)
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func addDigestReference(store reference.Store, ref reference.Named, dgst digest.Digest, id digest.Digest) error {
<add>func addDigestReference(store refstore.Store, ref reference.Named, dgst digest.Digest, id digest.Digest) error {
<ide> dgstRef, err := reference.WithDigest(reference.TrimNamed(ref), dgst)
<ide> if err != nil {
<ide> return err
<ide> func addDigestReference(store reference.Store, ref reference.Named, dgst digest.
<ide> logrus.Errorf("Image ID for digest %s changed from %s to %s, cannot update", dgst.String(), oldTagID, id)
<ide> }
<ide> return nil
<del> } else if err != reference.ErrDoesNotExist {
<add> } else if err != refstore.ErrDoesNotExist {
<ide> return err
<ide> }
<ide>
<ide><path>distribution/pull_v1.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/client/transport"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/distribution/xfer"
<ide> import (
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "golang.org/x/net/context"
<ide> )
<ide> func (p *v1Puller) Pull(ctx context.Context, ref reference.Named) error {
<ide> // TODO(dmcgowan): Check if should fallback
<ide> return err
<ide> }
<del> progress.Message(p.config.ProgressOutput, "", p.repoInfo.FullName()+": this image was pulled from a legacy registry. Important: This registry version will not be supported in future versions of docker.")
<add> progress.Message(p.config.ProgressOutput, "", p.repoInfo.Name.Name()+": this image was pulled from a legacy registry. Important: This registry version will not be supported in future versions of docker.")
<ide>
<ide> return nil
<ide> }
<ide>
<ide> func (p *v1Puller) pullRepository(ctx context.Context, ref reference.Named) error {
<del> progress.Message(p.config.ProgressOutput, "", "Pulling repository "+p.repoInfo.FullName())
<add> progress.Message(p.config.ProgressOutput, "", "Pulling repository "+p.repoInfo.Name.Name())
<ide>
<ide> tagged, isTagged := ref.(reference.NamedTagged)
<ide>
<del> repoData, err := p.session.GetRepositoryData(p.repoInfo)
<add> repoData, err := p.session.GetRepositoryData(p.repoInfo.Name)
<ide> if err != nil {
<ide> if strings.Contains(err.Error(), "HTTP code: 404") {
<ide> if isTagged {
<del> return fmt.Errorf("Error: image %s:%s not found", p.repoInfo.RemoteName(), tagged.Tag())
<add> return fmt.Errorf("Error: image %s:%s not found", reference.Path(p.repoInfo.Name), tagged.Tag())
<ide> }
<del> return fmt.Errorf("Error: image %s not found", p.repoInfo.RemoteName())
<add> return fmt.Errorf("Error: image %s not found", reference.Path(p.repoInfo.Name))
<ide> }
<ide> // Unexpected HTTP error
<ide> return err
<ide> func (p *v1Puller) pullRepository(ctx context.Context, ref reference.Named) erro
<ide> logrus.Debug("Retrieving the tag list")
<ide> var tagsList map[string]string
<ide> if !isTagged {
<del> tagsList, err = p.session.GetRemoteTags(repoData.Endpoints, p.repoInfo)
<add> tagsList, err = p.session.GetRemoteTags(repoData.Endpoints, p.repoInfo.Name)
<ide> } else {
<ide> var tagID string
<ide> tagsList = make(map[string]string)
<del> tagID, err = p.session.GetRemoteTag(repoData.Endpoints, p.repoInfo, tagged.Tag())
<add> tagID, err = p.session.GetRemoteTag(repoData.Endpoints, p.repoInfo.Name, tagged.Tag())
<ide> if err == registry.ErrRepoNotFound {
<del> return fmt.Errorf("Tag %s not found in repository %s", tagged.Tag(), p.repoInfo.FullName())
<add> return fmt.Errorf("Tag %s not found in repository %s", tagged.Tag(), p.repoInfo.Name.Name())
<ide> }
<ide> tagsList[tagged.Tag()] = tagID
<ide> }
<ide> func (p *v1Puller) pullRepository(ctx context.Context, ref reference.Named) erro
<ide> }
<ide> }
<ide>
<del> writeStatus(ref.String(), p.config.ProgressOutput, layersDownloaded)
<add> writeStatus(reference.FamiliarString(ref), p.config.ProgressOutput, layersDownloaded)
<ide> return nil
<ide> }
<ide>
<ide> func (p *v1Puller) downloadImage(ctx context.Context, repoData *registry.Reposit
<ide> return nil
<ide> }
<ide>
<del> localNameRef, err := reference.WithTag(p.repoInfo, img.Tag)
<add> localNameRef, err := reference.WithTag(p.repoInfo.Name, img.Tag)
<ide> if err != nil {
<ide> retErr := fmt.Errorf("Image (id: %s) has invalid tag: %s", img.ID, img.Tag)
<ide> logrus.Debug(retErr.Error())
<ide> func (p *v1Puller) downloadImage(ctx context.Context, repoData *registry.Reposit
<ide> return err
<ide> }
<ide>
<del> progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), "Pulling image (%s) from %s", img.Tag, p.repoInfo.FullName())
<add> progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), "Pulling image (%s) from %s", img.Tag, p.repoInfo.Name.Name())
<ide> success := false
<ide> var lastErr error
<ide> for _, ep := range p.repoInfo.Index.Mirrors {
<ide> ep += "v1/"
<del> progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, mirror: %s", img.Tag, p.repoInfo.FullName(), ep))
<add> progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, mirror: %s", img.Tag, p.repoInfo.Name.Name(), ep))
<ide> if err = p.pullImage(ctx, img.ID, ep, localNameRef, layersDownloaded); err != nil {
<ide> // Don't report errors when pulling from mirrors.
<del> logrus.Debugf("Error pulling image (%s) from %s, mirror: %s, %s", img.Tag, p.repoInfo.FullName(), ep, err)
<add> logrus.Debugf("Error pulling image (%s) from %s, mirror: %s, %s", img.Tag, p.repoInfo.Name.Name(), ep, err)
<ide> continue
<ide> }
<ide> success = true
<ide> break
<ide> }
<ide> if !success {
<ide> for _, ep := range repoData.Endpoints {
<del> progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), "Pulling image (%s) from %s, endpoint: %s", img.Tag, p.repoInfo.FullName(), ep)
<add> progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), "Pulling image (%s) from %s, endpoint: %s", img.Tag, p.repoInfo.Name.Name(), ep)
<ide> if err = p.pullImage(ctx, img.ID, ep, localNameRef, layersDownloaded); err != nil {
<ide> // It's not ideal that only the last error is returned, it would be better to concatenate the errors.
<ide> // As the error is also given to the output stream the user will see the error.
<ide> lastErr = err
<del> progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), "Error pulling image (%s) from %s, endpoint: %s, %s", img.Tag, p.repoInfo.FullName(), ep, err)
<add> progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), "Error pulling image (%s) from %s, endpoint: %s, %s", img.Tag, p.repoInfo.Name.Name(), ep, err)
<ide> continue
<ide> }
<ide> success = true
<ide> break
<ide> }
<ide> }
<ide> if !success {
<del> err := fmt.Errorf("Error pulling image (%s) from %s, %v", img.Tag, p.repoInfo.FullName(), lastErr)
<add> err := fmt.Errorf("Error pulling image (%s) from %s, %v", img.Tag, p.repoInfo.Name.Name(), lastErr)
<ide> progress.Update(p.config.ProgressOutput, stringid.TruncateID(img.ID), err.Error())
<ide> return err
<ide> }
<ide><path>distribution/pull_v2.go
<ide> import (
<ide> "github.com/docker/distribution/manifest/manifestlist"
<ide> "github.com/docker/distribution/manifest/schema1"
<ide> "github.com/docker/distribution/manifest/schema2"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/api/errcode"
<ide> "github.com/docker/distribution/registry/client/auth"
<ide> "github.com/docker/distribution/registry/client/transport"
<ide> import (
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/reference"
<add> refstore "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/opencontainers/go-digest"
<ide> "golang.org/x/net/context"
<ide> func (p *v2Puller) pullV2Repository(ctx context.Context, ref reference.Named) (e
<ide> }
<ide> }
<ide>
<del> writeStatus(ref.String(), p.config.ProgressOutput, layersDownloaded)
<add> writeStatus(reference.FamiliarString(ref), p.config.ProgressOutput, layersDownloaded)
<ide>
<ide> return nil
<ide> }
<ide> func (ld *v2LayerDescriptor) truncateDownloadFile() error {
<ide>
<ide> func (ld *v2LayerDescriptor) Registered(diffID layer.DiffID) {
<ide> // Cache mapping from this layer's DiffID to the blobsum
<del> ld.V2MetadataService.Add(diffID, metadata.V2Metadata{Digest: ld.digest, SourceRepository: ld.repoInfo.FullName()})
<add> ld.V2MetadataService.Add(diffID, metadata.V2Metadata{Digest: ld.digest, SourceRepository: ld.repoInfo.Name.Name()})
<ide> }
<ide>
<ide> func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named) (tagUpdated bool, err error) {
<ide> func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named) (tagUpdat
<ide> }
<ide> tagOrDigest = digested.Digest().String()
<ide> } else {
<del> return false, fmt.Errorf("internal error: reference has neither a tag nor a digest: %s", ref.String())
<add> return false, fmt.Errorf("internal error: reference has neither a tag nor a digest: %s", reference.FamiliarString(ref))
<ide> }
<ide>
<ide> if manifest == nil {
<ide> func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named) (tagUpdat
<ide> // the other side speaks the v2 protocol.
<ide> p.confirmedV2 = true
<ide>
<del> logrus.Debugf("Pulling ref from V2 registry: %s", ref.String())
<del> progress.Message(p.config.ProgressOutput, tagOrDigest, "Pulling from "+p.repo.Named().Name())
<add> logrus.Debugf("Pulling ref from V2 registry: %s", reference.FamiliarString(ref))
<add> progress.Message(p.config.ProgressOutput, tagOrDigest, "Pulling from "+reference.FamiliarName(p.repo.Named()))
<ide>
<ide> var (
<ide> id digest.Digest
<ide> func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named) (tagUpdat
<ide> if oldTagID == id {
<ide> return false, addDigestReference(p.config.ReferenceStore, ref, manifestDigest, id)
<ide> }
<del> } else if err != reference.ErrDoesNotExist {
<add> } else if err != refstore.ErrDoesNotExist {
<ide> return false, err
<ide> }
<ide>
<ide> func verifySchema1Manifest(signedManifest *schema1.SignedManifest, ref reference
<ide> m = &signedManifest.Manifest
<ide>
<ide> if m.SchemaVersion != 1 {
<del> return nil, fmt.Errorf("unsupported schema version %d for %q", m.SchemaVersion, ref.String())
<add> return nil, fmt.Errorf("unsupported schema version %d for %q", m.SchemaVersion, reference.FamiliarString(ref))
<ide> }
<ide> if len(m.FSLayers) != len(m.History) {
<del> return nil, fmt.Errorf("length of history not equal to number of layers for %q", ref.String())
<add> return nil, fmt.Errorf("length of history not equal to number of layers for %q", reference.FamiliarString(ref))
<ide> }
<ide> if len(m.FSLayers) == 0 {
<del> return nil, fmt.Errorf("no FSLayers in manifest for %q", ref.String())
<add> return nil, fmt.Errorf("no FSLayers in manifest for %q", reference.FamiliarString(ref))
<ide> }
<ide> return m, nil
<ide> }
<ide><path>distribution/pull_v2_test.go
<ide> import (
<ide> "testing"
<ide>
<ide> "github.com/docker/distribution/manifest/schema1"
<del> "github.com/docker/docker/reference"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide>
<ide> func TestValidateManifest(t *testing.T) {
<ide> if runtime.GOOS == "windows" {
<ide> t.Skip("Needs fixing on Windows")
<ide> }
<del> expectedDigest, err := reference.ParseNamed("repo@sha256:02fee8c3220ba806531f606525eceb83f4feb654f62b207191b1c9209188dedd")
<add> expectedDigest, err := reference.ParseNormalizedNamed("repo@sha256:02fee8c3220ba806531f606525eceb83f4feb654f62b207191b1c9209188dedd")
<ide> if err != nil {
<ide> t.Fatal("could not parse reference")
<ide> }
<ide><path>distribution/push.go
<ide> import (
<ide> "io"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/pkg/progress"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "golang.org/x/net/context"
<ide> )
<ide> func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushCo
<ide> return err
<ide> }
<ide>
<del> endpoints, err := imagePushConfig.RegistryService.LookupPushEndpoints(repoInfo.Hostname())
<add> endpoints, err := imagePushConfig.RegistryService.LookupPushEndpoints(reference.Domain(repoInfo.Name))
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> progress.Messagef(imagePushConfig.ProgressOutput, "", "The push refers to a repository [%s]", repoInfo.FullName())
<add> progress.Messagef(imagePushConfig.ProgressOutput, "", "The push refers to a repository [%s]", repoInfo.Name.Name())
<ide>
<del> associations := imagePushConfig.ReferenceStore.ReferencesByName(repoInfo)
<add> associations := imagePushConfig.ReferenceStore.ReferencesByName(repoInfo.Name)
<ide> if len(associations) == 0 {
<del> return fmt.Errorf("An image does not exist locally with the tag: %s", repoInfo.Name())
<add> return fmt.Errorf("An image does not exist locally with the tag: %s", reference.FamiliarName(repoInfo.Name))
<ide> }
<ide>
<ide> var (
<ide> func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushCo
<ide> }
<ide> }
<ide>
<del> logrus.Debugf("Trying to push %s to %s %s", repoInfo.FullName(), endpoint.URL, endpoint.Version)
<add> logrus.Debugf("Trying to push %s to %s %s", repoInfo.Name.Name(), endpoint.URL, endpoint.Version)
<ide>
<ide> pusher, err := NewPusher(ref, endpoint, repoInfo, imagePushConfig)
<ide> if err != nil {
<ide> func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushCo
<ide> return err
<ide> }
<ide>
<del> imagePushConfig.ImageEventLogger(ref.String(), repoInfo.Name(), "push")
<add> imagePushConfig.ImageEventLogger(reference.FamiliarString(ref), reference.FamiliarName(repoInfo.Name), "push")
<ide> return nil
<ide> }
<ide>
<ide> if lastErr == nil {
<del> lastErr = fmt.Errorf("no endpoints found for %s", repoInfo.FullName())
<add> lastErr = fmt.Errorf("no endpoints found for %s", repoInfo.Name.Name())
<ide> }
<ide> return lastErr
<ide> }
<ide><path>distribution/push_v1.go
<ide> import (
<ide> "sync"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/client/transport"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/dockerversion"
<ide> import (
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/opencontainers/go-digest"
<ide> "golang.org/x/net/context"
<ide> func (p *v1Pusher) pushImageToEndpoint(ctx context.Context, endpoint string, ima
<ide> }
<ide> if topImage, isTopImage := img.(*v1TopImage); isTopImage {
<ide> for _, tag := range tags[topImage.imageID] {
<del> progress.Messagef(p.config.ProgressOutput, "", "Pushing tag for rev [%s] on {%s}", stringid.TruncateID(v1ID), endpoint+"repositories/"+p.repoInfo.RemoteName()+"/tags/"+tag)
<del> if err := p.session.PushRegistryTag(p.repoInfo, v1ID, tag, endpoint); err != nil {
<add> progress.Messagef(p.config.ProgressOutput, "", "Pushing tag for rev [%s] on {%s}", stringid.TruncateID(v1ID), endpoint+"repositories/"+reference.Path(p.repoInfo.Name)+"/tags/"+tag)
<add> if err := p.session.PushRegistryTag(p.repoInfo.Name, v1ID, tag, endpoint); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (p *v1Pusher) pushRepository(ctx context.Context) error {
<ide>
<ide> // Register all the images in a repository with the registry
<ide> // If an image is not in this list it will not be associated with the repository
<del> repoData, err := p.session.PushImageJSONIndex(p.repoInfo, imageIndex, false, nil)
<add> repoData, err := p.session.PushImageJSONIndex(p.repoInfo.Name, imageIndex, false, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (p *v1Pusher) pushRepository(ctx context.Context) error {
<ide> return err
<ide> }
<ide> }
<del> _, err = p.session.PushImageJSONIndex(p.repoInfo, imageIndex, true, repoData.Endpoints)
<add> _, err = p.session.PushImageJSONIndex(p.repoInfo.Name, imageIndex, true, repoData.Endpoints)
<ide> return err
<ide> }
<ide>
<ide><path>distribution/push_v2.go
<ide> import (
<ide> "github.com/docker/distribution"
<ide> "github.com/docker/distribution/manifest/schema1"
<ide> "github.com/docker/distribution/manifest/schema2"
<del> distreference "github.com/docker/distribution/reference"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/client"
<ide> apitypes "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> import (
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide> func (p *v2Pusher) pushV2Repository(ctx context.Context) (err error) {
<ide> if namedTagged, isNamedTagged := p.ref.(reference.NamedTagged); isNamedTagged {
<ide> imageID, err := p.config.ReferenceStore.Get(p.ref)
<ide> if err != nil {
<del> return fmt.Errorf("tag does not exist: %s", p.ref.String())
<add> return fmt.Errorf("tag does not exist: %s", reference.FamiliarString(p.ref))
<ide> }
<ide>
<ide> return p.pushV2Tag(ctx, namedTagged, imageID)
<ide> func (p *v2Pusher) pushV2Repository(ctx context.Context) (err error) {
<ide> }
<ide>
<ide> if pushed == 0 {
<del> return fmt.Errorf("no tags to push for %s", p.repoInfo.Name())
<add> return fmt.Errorf("no tags to push for %s", reference.FamiliarName(p.repoInfo.Name))
<ide> }
<ide>
<ide> return nil
<ide> }
<ide>
<ide> func (p *v2Pusher) pushV2Tag(ctx context.Context, ref reference.NamedTagged, id digest.Digest) error {
<del> logrus.Debugf("Pushing repository: %s", ref.String())
<add> logrus.Debugf("Pushing repository: %s", reference.FamiliarString(ref))
<ide>
<ide> imgConfig, err := p.config.ImageStore.Get(id)
<ide> if err != nil {
<del> return fmt.Errorf("could not find image from tag %s: %v", ref.String(), err)
<add> return fmt.Errorf("could not find image from tag %s: %v", reference.FamiliarString(ref), err)
<ide> }
<ide>
<ide> rootfs, err := p.config.ImageStore.RootFSFromConfig(imgConfig)
<ide> if err != nil {
<del> return fmt.Errorf("unable to get rootfs for image %s: %s", ref.String(), err)
<add> return fmt.Errorf("unable to get rootfs for image %s: %s", reference.FamiliarString(ref), err)
<ide> }
<ide>
<ide> l, err := p.config.LayerStore.Get(rootfs.ChainID())
<ide> func (p *v2Pusher) pushV2Tag(ctx context.Context, ref reference.NamedTagged, id
<ide> descriptorTemplate := v2PushDescriptor{
<ide> v2MetadataService: p.v2MetadataService,
<ide> hmacKey: hmacKey,
<del> repoInfo: p.repoInfo,
<add> repoInfo: p.repoInfo.Name,
<ide> ref: p.ref,
<ide> repo: p.repo,
<ide> pushState: &p.pushState,
<ide> func (p *v2Pusher) pushV2Tag(ctx context.Context, ref reference.NamedTagged, id
<ide>
<ide> logrus.Warnf("failed to upload schema2 manifest: %v - falling back to schema1", err)
<ide>
<del> manifestRef, err := distreference.WithTag(p.repo.Named(), ref.Tag())
<add> manifestRef, err := reference.WithTag(p.repo.Named(), ref.Tag())
<ide> if err != nil {
<ide> return err
<ide> }
<ide> type v2PushDescriptor struct {
<ide> }
<ide>
<ide> func (pd *v2PushDescriptor) Key() string {
<del> return "v2push:" + pd.ref.FullName() + " " + pd.layer.DiffID().String()
<add> return "v2push:" + pd.ref.Name() + " " + pd.layer.DiffID().String()
<ide> }
<ide>
<ide> func (pd *v2PushDescriptor) ID() string {
<ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.
<ide> createOpts := []distribution.BlobCreateOption{}
<ide>
<ide> if len(mountCandidate.SourceRepository) > 0 {
<del> namedRef, err := reference.WithName(mountCandidate.SourceRepository)
<add> namedRef, err := reference.ParseNormalizedNamed(mountCandidate.SourceRepository)
<ide> if err != nil {
<del> logrus.Errorf("failed to parse source repository reference %v: %v", namedRef.String(), err)
<add> logrus.Errorf("failed to parse source repository reference %v: %v", reference.FamiliarString(namedRef), err)
<ide> pd.v2MetadataService.Remove(mountCandidate)
<ide> continue
<ide> }
<ide>
<del> // TODO (brianbland): We need to construct a reference where the Name is
<del> // only the full remote name, so clean this up when distribution has a
<del> // richer reference package
<del> remoteRef, err := distreference.WithName(namedRef.RemoteName())
<add> // Candidates are always under same domain, create remote reference
<add> // with only path to set mount from with
<add> remoteRef, err := reference.WithName(reference.Path(namedRef))
<ide> if err != nil {
<del> logrus.Errorf("failed to make remote reference out of %q: %v", namedRef.RemoteName(), namedRef.RemoteName())
<add> logrus.Errorf("failed to make remote reference out of %q: %v", reference.Path(namedRef), err)
<ide> continue
<ide> }
<ide>
<del> canonicalRef, err := distreference.WithDigest(distreference.TrimNamed(remoteRef), mountCandidate.Digest)
<add> canonicalRef, err := reference.WithDigest(reference.TrimNamed(remoteRef), mountCandidate.Digest)
<ide> if err != nil {
<ide> logrus.Errorf("failed to make canonical reference: %v", err)
<ide> continue
<ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.
<ide> // Cache mapping from this layer's DiffID to the blobsum
<ide> if err := pd.v2MetadataService.TagAndAdd(diffID, pd.hmacKey, metadata.V2Metadata{
<ide> Digest: err.Descriptor.Digest,
<del> SourceRepository: pd.repoInfo.FullName(),
<add> SourceRepository: pd.repoInfo.Name(),
<ide> }); err != nil {
<ide> return distribution.Descriptor{}, xfer.DoNotRetry{Err: err}
<ide> }
<ide> func (pd *v2PushDescriptor) uploadUsingSession(
<ide> // Cache mapping from this layer's DiffID to the blobsum
<ide> if err := pd.v2MetadataService.TagAndAdd(diffID, pd.hmacKey, metadata.V2Metadata{
<ide> Digest: pushDigest,
<del> SourceRepository: pd.repoInfo.FullName(),
<add> SourceRepository: pd.repoInfo.Name(),
<ide> }); err != nil {
<ide> return distribution.Descriptor{}, xfer.DoNotRetry{Err: err}
<ide> }
<ide> func (pd *v2PushDescriptor) layerAlreadyExists(
<ide> // filter the metadata
<ide> candidates := []metadata.V2Metadata{}
<ide> for _, meta := range v2Metadata {
<del> if len(meta.SourceRepository) > 0 && !checkOtherRepositories && meta.SourceRepository != pd.repoInfo.FullName() {
<add> if len(meta.SourceRepository) > 0 && !checkOtherRepositories && meta.SourceRepository != pd.repoInfo.Name() {
<ide> continue
<ide> }
<ide> candidates = append(candidates, meta)
<ide> func (pd *v2PushDescriptor) layerAlreadyExists(
<ide> attempts:
<ide> for _, dgst := range layerDigests {
<ide> meta := digestToMetadata[dgst]
<del> logrus.Debugf("Checking for presence of layer %s (%s) in %s", diffID, dgst, pd.repoInfo.FullName())
<add> logrus.Debugf("Checking for presence of layer %s (%s) in %s", diffID, dgst, pd.repoInfo.Name())
<ide> desc, err = pd.repo.Blobs(ctx).Stat(ctx, dgst)
<ide> pd.checkedDigests[meta.Digest] = struct{}{}
<ide> switch err {
<ide> case nil:
<del> if m, ok := digestToMetadata[desc.Digest]; !ok || m.SourceRepository != pd.repoInfo.FullName() || !metadata.CheckV2MetadataHMAC(m, pd.hmacKey) {
<add> if m, ok := digestToMetadata[desc.Digest]; !ok || m.SourceRepository != pd.repoInfo.Name() || !metadata.CheckV2MetadataHMAC(m, pd.hmacKey) {
<ide> // cache mapping from this layer's DiffID to the blobsum
<ide> if err := pd.v2MetadataService.TagAndAdd(diffID, pd.hmacKey, metadata.V2Metadata{
<ide> Digest: desc.Digest,
<del> SourceRepository: pd.repoInfo.FullName(),
<add> SourceRepository: pd.repoInfo.Name(),
<ide> }); err != nil {
<ide> return distribution.Descriptor{}, false, xfer.DoNotRetry{Err: err}
<ide> }
<ide> attempts:
<ide> exists = true
<ide> break attempts
<ide> case distribution.ErrBlobUnknown:
<del> if meta.SourceRepository == pd.repoInfo.FullName() {
<add> if meta.SourceRepository == pd.repoInfo.Name() {
<ide> // remove the mapping to the target repository
<ide> pd.v2MetadataService.Remove(*meta)
<ide> }
<ide> default:
<del> logrus.WithError(err).Debugf("Failed to check for presence of layer %s (%s) in %s", diffID, dgst, pd.repoInfo.FullName())
<add> logrus.WithError(err).Debugf("Failed to check for presence of layer %s (%s) in %s", diffID, dgst, pd.repoInfo.Name())
<ide> }
<ide> }
<ide>
<ide> func getRepositoryMountCandidates(
<ide> candidates := []metadata.V2Metadata{}
<ide> for _, meta := range v2Metadata {
<ide> sourceRepo, err := reference.ParseNamed(meta.SourceRepository)
<del> if err != nil || repoInfo.Hostname() != sourceRepo.Hostname() {
<add> if err != nil || reference.Domain(repoInfo) != reference.Domain(sourceRepo) {
<ide> continue
<ide> }
<ide> // target repository is not a viable candidate
<del> if meta.SourceRepository == repoInfo.FullName() {
<add> if meta.SourceRepository == repoInfo.Name() {
<ide> continue
<ide> }
<ide> candidates = append(candidates, meta)
<ide> func sortV2MetadataByLikenessAndAge(repoInfo reference.Named, hmacKey []byte, ma
<ide> sort.Stable(byLikeness{
<ide> arr: marr,
<ide> hmacKey: hmacKey,
<del> pathComponents: getPathComponents(repoInfo.FullName()),
<add> pathComponents: getPathComponents(repoInfo.Name()),
<ide> })
<ide> }
<ide>
<ide> func numOfMatchingPathComponents(pth string, matchComponents []string) int {
<ide> }
<ide>
<ide> func getPathComponents(path string) []string {
<del> // make sure to add docker.io/ prefix to the path
<del> named, err := reference.ParseNamed(path)
<del> if err == nil {
<del> path = named.FullName()
<del> }
<ide> return strings.Split(path, "/")
<ide> }
<ide>
<ide><path>distribution/push_v2_test.go
<ide> import (
<ide> "github.com/docker/distribution"
<ide> "github.com/docker/distribution/context"
<ide> "github.com/docker/distribution/manifest/schema2"
<del> distreference "github.com/docker/distribution/reference"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/progress"
<del> "github.com/docker/docker/reference"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide>
<ide> func TestGetRepositoryMountCandidates(t *testing.T) {
<ide> name: "one item matching",
<ide> targetRepo: "busybox",
<ide> maxCandidates: -1,
<del> metadata: []metadata.V2Metadata{taggedMetadata("hash", "1", "hello-world")},
<del> candidates: []metadata.V2Metadata{taggedMetadata("hash", "1", "hello-world")},
<add> metadata: []metadata.V2Metadata{taggedMetadata("hash", "1", "docker.io/library/hello-world")},
<add> candidates: []metadata.V2Metadata{taggedMetadata("hash", "1", "docker.io/library/hello-world")},
<ide> },
<ide> {
<ide> name: "allow missing SourceRepository",
<ide> func TestGetRepositoryMountCandidates(t *testing.T) {
<ide> maxCandidates: -1,
<ide> metadata: []metadata.V2Metadata{
<ide> {Digest: digest.Digest("1"), SourceRepository: "docker.io/user/foo"},
<del> {Digest: digest.Digest("3"), SourceRepository: "user/bar"},
<del> {Digest: digest.Digest("2"), SourceRepository: "app"},
<add> {Digest: digest.Digest("3"), SourceRepository: "docker.io/user/bar"},
<add> {Digest: digest.Digest("2"), SourceRepository: "docker.io/library/app"},
<ide> },
<ide> candidates: []metadata.V2Metadata{
<del> {Digest: digest.Digest("3"), SourceRepository: "user/bar"},
<add> {Digest: digest.Digest("3"), SourceRepository: "docker.io/user/bar"},
<ide> {Digest: digest.Digest("1"), SourceRepository: "docker.io/user/foo"},
<del> {Digest: digest.Digest("2"), SourceRepository: "app"},
<add> {Digest: digest.Digest("2"), SourceRepository: "docker.io/library/app"},
<ide> },
<ide> },
<ide> {
<ide> func TestGetRepositoryMountCandidates(t *testing.T) {
<ide> targetRepo: "127.0.0.1/foo/bar",
<ide> maxCandidates: -1,
<ide> metadata: []metadata.V2Metadata{
<del> taggedMetadata("hash", "1", "hello-world"),
<add> taggedMetadata("hash", "1", "docker.io/library/hello-world"),
<ide> taggedMetadata("efgh", "2", "127.0.0.1/hello-world"),
<del> taggedMetadata("abcd", "3", "busybox"),
<del> taggedMetadata("hash", "4", "busybox"),
<add> taggedMetadata("abcd", "3", "docker.io/library/busybox"),
<add> taggedMetadata("hash", "4", "docker.io/library/busybox"),
<ide> taggedMetadata("hash", "5", "127.0.0.1/foo"),
<ide> taggedMetadata("hash", "6", "127.0.0.1/bar"),
<ide> taggedMetadata("efgh", "7", "127.0.0.1/foo/bar"),
<ide> func TestGetRepositoryMountCandidates(t *testing.T) {
<ide> targetRepo: "user/app",
<ide> maxCandidates: 3,
<ide> metadata: []metadata.V2Metadata{
<del> taggedMetadata("abcd", "1", "user/app1"),
<del> taggedMetadata("abcd", "2", "user/app/base"),
<del> taggedMetadata("hash", "3", "user/app"),
<add> taggedMetadata("abcd", "1", "docker.io/user/app1"),
<add> taggedMetadata("abcd", "2", "docker.io/user/app/base"),
<add> taggedMetadata("hash", "3", "docker.io/user/app"),
<ide> taggedMetadata("abcd", "4", "127.0.0.1/user/app"),
<del> taggedMetadata("hash", "5", "user/foo"),
<del> taggedMetadata("hash", "6", "app/bar"),
<add> taggedMetadata("hash", "5", "docker.io/user/foo"),
<add> taggedMetadata("hash", "6", "docker.io/app/bar"),
<ide> },
<ide> candidates: []metadata.V2Metadata{
<ide> // first by matching hash
<del> taggedMetadata("abcd", "2", "user/app/base"),
<del> taggedMetadata("abcd", "1", "user/app1"),
<add> taggedMetadata("abcd", "2", "docker.io/user/app/base"),
<add> taggedMetadata("abcd", "1", "docker.io/user/app1"),
<ide> // then by longest matching prefix
<del> taggedMetadata("hash", "3", "user/app"),
<add> // "docker.io/usr/app" is excluded since candidates must
<add> // be from a different repository
<add> taggedMetadata("hash", "5", "docker.io/user/foo"),
<ide> },
<ide> },
<ide> } {
<del> repoInfo, err := reference.ParseNamed(tc.targetRepo)
<add> repoInfo, err := reference.ParseNormalizedNamed(tc.targetRepo)
<ide> if err != nil {
<ide> t.Fatalf("[%s] failed to parse reference name: %v", tc.name, err)
<ide> }
<ide> func TestLayerAlreadyExists(t *testing.T) {
<ide> {Digest: digest.Digest("apple"), SourceRepository: "docker.io/library/hello-world"},
<ide> {Digest: digest.Digest("orange"), SourceRepository: "docker.io/busybox/subapp"},
<ide> {Digest: digest.Digest("pear"), SourceRepository: "docker.io/busybox"},
<del> {Digest: digest.Digest("plum"), SourceRepository: "busybox"},
<add> {Digest: digest.Digest("plum"), SourceRepository: "docker.io/library/busybox"},
<ide> {Digest: digest.Digest("banana"), SourceRepository: "127.0.0.1/busybox"},
<ide> },
<del> expectedRequests: []string{"plum", "pear", "apple", "orange", "banana"},
<add> expectedRequests: []string{"plum", "apple", "pear", "orange", "banana"},
<add> expectedRemovals: []metadata.V2Metadata{
<add> {Digest: digest.Digest("plum"), SourceRepository: "docker.io/library/busybox"},
<add> },
<ide> },
<ide> {
<ide> name: "find existing blob",
<ide> func TestLayerAlreadyExists(t *testing.T) {
<ide> },
<ide> },
<ide> } {
<del> repoInfo, err := reference.ParseNamed(tc.targetRepo)
<add> repoInfo, err := reference.ParseNormalizedNamed(tc.targetRepo)
<ide> if err != nil {
<ide> t.Fatalf("[%s] failed to parse reference name: %v", tc.name, err)
<ide> }
<ide> type mockRepo struct {
<ide>
<ide> var _ distribution.Repository = &mockRepo{}
<ide>
<del>func (m *mockRepo) Named() distreference.Named {
<add>func (m *mockRepo) Named() reference.Named {
<ide> m.t.Fatalf("Named() not implemented")
<ide> return nil
<ide> }
<ide><path>distribution/registry.go
<ide> import (
<ide>
<ide> "github.com/docker/distribution"
<ide> "github.com/docker/distribution/manifest/schema2"
<del> distreference "github.com/docker/distribution/reference"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/client"
<ide> "github.com/docker/distribution/registry/client/auth"
<ide> "github.com/docker/distribution/registry/client/transport"
<ide> func init() {
<ide> // providing timeout settings and authentication support, and also verifies the
<ide> // remote API version.
<ide> func NewV2Repository(ctx context.Context, repoInfo *registry.RepositoryInfo, endpoint registry.APIEndpoint, metaHeaders http.Header, authConfig *types.AuthConfig, actions ...string) (repo distribution.Repository, foundVersion bool, err error) {
<del> repoName := repoInfo.FullName()
<add> repoName := repoInfo.Name.Name()
<ide> // If endpoint does not support CanonicalName, use the RemoteName instead
<ide> if endpoint.TrimHostname {
<del> repoName = repoInfo.RemoteName()
<add> repoName = reference.Path(repoInfo.Name)
<ide> }
<ide>
<ide> direct := &net.Dialer{
<ide> func NewV2Repository(ctx context.Context, repoInfo *registry.RepositoryInfo, end
<ide> }
<ide> tr := transport.NewTransport(base, modifiers...)
<ide>
<del> repoNameRef, err := distreference.ParseNamed(repoName)
<add> repoNameRef, err := reference.WithName(repoName)
<ide> if err != nil {
<ide> return nil, foundVersion, fallbackError{
<ide> err: err,
<ide><path>distribution/registry_unit_test.go
<ide> import (
<ide> "testing"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> registrytypes "github.com/docker/docker/api/types/registry"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "golang.org/x/net/context"
<ide> )
<ide> func testTokenPassThru(t *testing.T, ts *httptest.Server) {
<ide> TrimHostname: false,
<ide> TLSConfig: nil,
<ide> }
<del> n, _ := reference.ParseNamed("testremotename")
<add> n, _ := reference.ParseNormalizedNamed("testremotename")
<ide> repoInfo := ®istry.RepositoryInfo{
<del> Named: n,
<add> Name: n,
<ide> Index: ®istrytypes.IndexInfo{
<ide> Name: "testrepo",
<ide> Mirrors: nil,
<ide><path>image/tarexport/load.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/image/v1"
<ide> "github.com/docker/docker/layer"
<ide> import (
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/pkg/symlink"
<ide> "github.com/docker/docker/pkg/system"
<del> "github.com/docker/docker/reference"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide>
<ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool)
<ide>
<ide> imageRefCount = 0
<ide> for _, repoTag := range m.RepoTags {
<del> named, err := reference.ParseNamed(repoTag)
<add> named, err := reference.ParseNormalizedNamed(repoTag)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool)
<ide> return fmt.Errorf("invalid tag %q", repoTag)
<ide> }
<ide> l.setLoadedTag(ref, imgID.Digest(), outStream)
<del> outStream.Write([]byte(fmt.Sprintf("Loaded image: %s\n", ref)))
<add> outStream.Write([]byte(fmt.Sprintf("Loaded image: %s\n", reference.FamiliarString(ref))))
<ide> imageRefCount++
<ide> }
<ide>
<ide> func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS, id string,
<ide>
<ide> func (l *tarexporter) setLoadedTag(ref reference.NamedTagged, imgID digest.Digest, outStream io.Writer) error {
<ide> if prevID, err := l.rs.Get(ref); err == nil && prevID != imgID {
<del> fmt.Fprintf(outStream, "The image %s already exists, renaming the old one with ID %s to empty string\n", ref.String(), string(prevID)) // todo: this message is wrong in case of multiple tags
<add> fmt.Fprintf(outStream, "The image %s already exists, renaming the old one with ID %s to empty string\n", reference.FamiliarString(ref), string(prevID)) // todo: this message is wrong in case of multiple tags
<ide> }
<ide>
<ide> if err := l.rs.AddTag(ref, imgID, true); err != nil {
<ide> func (l *tarexporter) legacyLoad(tmpDir string, outStream io.Writer, progressOut
<ide> if !ok {
<ide> return fmt.Errorf("invalid target ID: %v", oldID)
<ide> }
<del> named, err := reference.WithName(name)
<add> named, err := reference.ParseNormalizedNamed(name)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>image/tarexport/save.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/distribution"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/image/v1"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/system"
<del> "github.com/docker/docker/reference"
<ide> "github.com/opencontainers/go-digest"
<ide> "github.com/pkg/errors"
<ide> )
<ide> func (l *tarexporter) parseNames(names []string) (map[image.ID]*imageDescriptor,
<ide> }
<ide>
<ide> if ref != nil {
<del> var tagged reference.NamedTagged
<ide> if _, ok := ref.(reference.Canonical); ok {
<ide> return
<ide> }
<del> var ok bool
<del> if tagged, ok = ref.(reference.NamedTagged); !ok {
<del> var err error
<del> if tagged, err = reference.WithTag(ref, reference.DefaultTag); err != nil {
<del> return
<del> }
<add> tagged, ok := reference.TagNameOnly(ref).(reference.NamedTagged)
<add> if !ok {
<add> return
<ide> }
<ide>
<ide> for _, t := range imgDescr[id].refs {
<ide> func (l *tarexporter) parseNames(names []string) (map[image.ID]*imageDescriptor,
<ide> }
<ide>
<ide> for _, name := range names {
<del> id, ref, err := reference.ParseIDOrReference(name)
<add> ref, err := reference.ParseAnyReference(name)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> if id != "" {
<del> _, err := l.is.Get(image.IDFromDigest(id))
<del> if err != nil {
<del> return nil, err
<add> namedRef, ok := ref.(reference.Named)
<add> if !ok {
<add> // Check if digest ID reference
<add> if digested, ok := ref.(reference.Digested); ok {
<add> id := image.IDFromDigest(digested.Digest())
<add> _, err := l.is.Get(id)
<add> if err != nil {
<add> return nil, err
<add> }
<add> addAssoc(id, nil)
<add> continue
<ide> }
<del> addAssoc(image.IDFromDigest(id), nil)
<del> continue
<add> return nil, errors.Errorf("invalid reference: %v", name)
<ide> }
<del> if ref.Name() == string(digest.Canonical) {
<add>
<add> if reference.FamiliarName(namedRef) == string(digest.Canonical) {
<ide> imgID, err := l.is.Search(name)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> addAssoc(imgID, nil)
<ide> continue
<ide> }
<del> if reference.IsNameOnly(ref) {
<del> assocs := l.rs.ReferencesByName(ref)
<add> if reference.IsNameOnly(namedRef) {
<add> assocs := l.rs.ReferencesByName(namedRef)
<ide> for _, assoc := range assocs {
<ide> addAssoc(image.IDFromDigest(assoc.ID), assoc.Ref)
<ide> }
<ide> func (l *tarexporter) parseNames(names []string) (map[image.ID]*imageDescriptor,
<ide> }
<ide> continue
<ide> }
<del> id, err = l.rs.Get(ref)
<add> id, err := l.rs.Get(namedRef)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> addAssoc(image.IDFromDigest(id), ref)
<add> addAssoc(image.IDFromDigest(id), namedRef)
<ide>
<ide> }
<ide> return imgDescr, nil
<ide> func (s *saveSession) save(outStream io.Writer) error {
<ide> var layers []string
<ide>
<ide> for _, ref := range imageDescr.refs {
<del> if _, ok := reposLegacy[ref.Name()]; !ok {
<del> reposLegacy[ref.Name()] = make(map[string]string)
<add> familiarName := reference.FamiliarName(ref)
<add> if _, ok := reposLegacy[familiarName]; !ok {
<add> reposLegacy[familiarName] = make(map[string]string)
<ide> }
<del> reposLegacy[ref.Name()][ref.Tag()] = imageDescr.layers[len(imageDescr.layers)-1]
<del> repoTags = append(repoTags, ref.String())
<add> reposLegacy[familiarName][ref.Tag()] = imageDescr.layers[len(imageDescr.layers)-1]
<add> repoTags = append(repoTags, reference.FamiliarString(ref))
<ide> }
<ide>
<ide> for _, l := range imageDescr.layers {
<ide><path>image/tarexport/tarexport.go
<ide> import (
<ide> "github.com/docker/distribution"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<del> "github.com/docker/docker/reference"
<add> refstore "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> const (
<ide> type manifestItem struct {
<ide> type tarexporter struct {
<ide> is image.Store
<ide> ls layer.Store
<del> rs reference.Store
<add> rs refstore.Store
<ide> loggerImgEvent LogImageEvent
<ide> }
<ide>
<ide> type LogImageEvent interface {
<ide> }
<ide>
<ide> // NewTarExporter returns new Exporter for tar packages
<del>func NewTarExporter(is image.Store, ls layer.Store, rs reference.Store, loggerImgEvent LogImageEvent) image.Exporter {
<add>func NewTarExporter(is image.Store, ls layer.Store, rs refstore.Store, loggerImgEvent LogImageEvent) image.Exporter {
<ide> return &tarexporter{
<ide> is: is,
<ide> ls: ls,
<ide><path>integration-cli/docker_cli_images_test.go
<ide> func (s *DockerSuite) TestImagesFormat(c *check.C) {
<ide> expected := []string{"myimage", "myimage"}
<ide> var names []string
<ide> names = append(names, lines...)
<del> c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
<add> c.Assert(names, checker.DeepEquals, expected, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
<ide> }
<ide>
<ide> // ImagesDefaultFormatAndQuiet
<ide><path>migrate/v1/migratev1.go
<ide> import (
<ide> "encoding/json"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/image"
<ide> imagev1 "github.com/docker/docker/image/v1"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/reference"
<add> refstore "github.com/docker/docker/reference"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide>
<ide> var (
<ide>
<ide> // Migrate takes an old graph directory and transforms the metadata into the
<ide> // new format.
<del>func Migrate(root, driverName string, ls layer.Store, is image.Store, rs reference.Store, ms metadata.Store) error {
<add>func Migrate(root, driverName string, ls layer.Store, is image.Store, rs refstore.Store, ms metadata.Store) error {
<ide> graphDir := filepath.Join(root, graphDirName)
<ide> if _, err := os.Lstat(graphDir); os.IsNotExist(err) {
<ide> return nil
<ide> func migrateRefs(root, driverName string, rs refAdder, mappings map[string]image
<ide> for name, repo := range repos.Repositories {
<ide> for tag, id := range repo {
<ide> if strongID, exists := mappings[id]; exists {
<del> ref, err := reference.WithName(name)
<add> ref, err := reference.ParseNormalizedNamed(name)
<ide> if err != nil {
<ide> logrus.Errorf("migrate tags: invalid name %q, %q", name, err)
<ide> continue
<ide> }
<add> if !reference.IsNameOnly(ref) {
<add> logrus.Errorf("migrate tags: invalid name %q, unexpected tag or digest", name)
<add> continue
<add> }
<ide> if dgst, err := digest.Parse(tag); err == nil {
<ide> canonical, err := reference.WithDigest(reference.TrimNamed(ref), dgst)
<ide> if err != nil {
<ide> logrus.Errorf("migrate tags: invalid digest %q, %q", dgst, err)
<ide> continue
<ide> }
<ide> if err := rs.AddDigest(canonical, strongID.Digest(), false); err != nil {
<del> logrus.Errorf("can't migrate digest %q for %q, err: %q", ref.String(), strongID, err)
<add> logrus.Errorf("can't migrate digest %q for %q, err: %q", reference.FamiliarString(ref), strongID, err)
<ide> }
<ide> } else {
<ide> tagRef, err := reference.WithTag(ref, tag)
<ide> func migrateRefs(root, driverName string, rs refAdder, mappings map[string]image
<ide> continue
<ide> }
<ide> if err := rs.AddTag(tagRef, strongID.Digest(), false); err != nil {
<del> logrus.Errorf("can't migrate tag %q for %q, err: %q", ref.String(), strongID, err)
<add> logrus.Errorf("can't migrate tag %q for %q, err: %q", reference.FamiliarString(ref), strongID, err)
<ide> }
<ide> }
<ide> logrus.Infof("migrated tag %s:%s to point to %s", name, tag, strongID)
<ide><path>migrate/v1/migratev1_test.go
<ide> import (
<ide> "runtime"
<ide> "testing"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<del> "github.com/docker/docker/reference"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide>
<ide> func TestMigrateRefs(t *testing.T) {
<ide> }
<ide>
<ide> expected := map[string]string{
<del> "busybox:latest": "sha256:fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9",
<del> "busybox@sha256:16a2a52884c2a9481ed267c2d46483eac7693b813a63132368ab098a71303f8a": "sha256:fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9",
<del> "registry:2": "sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
<add> "docker.io/library/busybox:latest": "sha256:fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9",
<add> "docker.io/library/busybox@sha256:16a2a52884c2a9481ed267c2d46483eac7693b813a63132368ab098a71303f8a": "sha256:fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9",
<add> "docker.io/library/registry:2": "sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
<ide> }
<ide>
<ide> if !reflect.DeepEqual(expected, ta.refs) {
<ide><path>plugin/backend_linux.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/manifest/schema2"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<ide> "github.com/docker/docker/distribution"
<ide> import (
<ide> "github.com/docker/docker/pkg/pools"
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/plugin/v2"
<del> "github.com/docker/docker/reference"
<add> refstore "github.com/docker/docker/reference"
<ide> "github.com/opencontainers/go-digest"
<ide> "github.com/pkg/errors"
<ide> "golang.org/x/net/context"
<ide> func (pm *Manager) Upgrade(ctx context.Context, ref reference.Named, name string
<ide> defer pm.muGC.RUnlock()
<ide>
<ide> // revalidate because Pull is public
<del> nameref, err := reference.ParseNamed(name)
<add> nameref, err := reference.ParseNormalizedNamed(name)
<ide> if err != nil {
<ide> return errors.Wrapf(err, "failed to parse %q", name)
<ide> }
<del> name = reference.WithDefaultTag(nameref).String()
<add> name = reference.FamiliarString(reference.TagNameOnly(nameref))
<ide>
<ide> tmpRootFSDir, err := ioutil.TempDir(pm.tmpDir(), ".rootfs")
<ide> defer os.RemoveAll(tmpRootFSDir)
<ide> func (pm *Manager) Pull(ctx context.Context, ref reference.Named, name string, m
<ide> defer pm.muGC.RUnlock()
<ide>
<ide> // revalidate because Pull is public
<del> nameref, err := reference.ParseNamed(name)
<add> nameref, err := reference.ParseNormalizedNamed(name)
<ide> if err != nil {
<ide> return errors.Wrapf(err, "failed to parse %q", name)
<ide> }
<del> name = reference.WithDefaultTag(nameref).String()
<add> name = reference.FamiliarString(reference.TagNameOnly(nameref))
<ide>
<ide> if err := pm.config.Store.validateName(name); err != nil {
<ide> return err
<ide> func (pm *Manager) Push(ctx context.Context, name string, metaHeader http.Header
<ide> return err
<ide> }
<ide>
<del> ref, err := reference.ParseNamed(p.Name())
<add> ref, err := reference.ParseNormalizedNamed(p.Name())
<ide> if err != nil {
<ide> return errors.Wrapf(err, "plugin has invalid name %v for push", p.Name())
<ide> }
<ide> func (r *pluginReference) References(id digest.Digest) []reference.Named {
<ide> return []reference.Named{r.name}
<ide> }
<ide>
<del>func (r *pluginReference) ReferencesByName(ref reference.Named) []reference.Association {
<del> return []reference.Association{
<add>func (r *pluginReference) ReferencesByName(ref reference.Named) []refstore.Association {
<add> return []refstore.Association{
<ide> {
<ide> Ref: r.name,
<ide> ID: r.pluginID,
<ide> func (r *pluginReference) ReferencesByName(ref reference.Named) []reference.Asso
<ide>
<ide> func (r *pluginReference) Get(ref reference.Named) (digest.Digest, error) {
<ide> if r.name.String() != ref.String() {
<del> return digest.Digest(""), reference.ErrDoesNotExist
<add> return digest.Digest(""), refstore.ErrDoesNotExist
<ide> }
<ide> return r.pluginID, nil
<ide> }
<ide> func (pm *Manager) CreateFromContext(ctx context.Context, tarCtx io.ReadCloser,
<ide> pm.muGC.RLock()
<ide> defer pm.muGC.RUnlock()
<ide>
<del> ref, err := reference.ParseNamed(options.RepoName)
<add> ref, err := reference.ParseNormalizedNamed(options.RepoName)
<ide> if err != nil {
<ide> return errors.Wrapf(err, "failed to parse reference %v", options.RepoName)
<ide> }
<ide> if _, ok := ref.(reference.Canonical); ok {
<ide> return errors.Errorf("canonical references are not permitted")
<ide> }
<del> taggedRef := reference.WithDefaultTag(ref)
<del> name := taggedRef.String()
<add> name := reference.FamiliarString(reference.TagNameOnly(ref))
<ide>
<ide> if err := pm.config.Store.validateName(name); err != nil { // fast check, real check is in createPlugin()
<ide> return err
<ide> func (pm *Manager) CreateFromContext(ctx context.Context, tarCtx io.ReadCloser,
<ide> if err != nil {
<ide> return err
<ide> }
<del> p.PluginObj.PluginReference = taggedRef.String()
<add> p.PluginObj.PluginReference = name
<ide>
<ide> pm.config.LogPluginEvent(p.PluginObj.ID, name, "create")
<ide>
<ide><path>plugin/backend_unsupported.go
<ide> import (
<ide> "io"
<ide> "net/http"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<del> "github.com/docker/docker/reference"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide><path>plugin/store.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/pkg/plugingetter"
<ide> "github.com/docker/docker/pkg/plugins"
<ide> "github.com/docker/docker/plugin/v2"
<del> "github.com/docker/docker/reference"
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<ide> func (ps *Store) resolvePluginID(idOrName string) (string, error) {
<ide> return idOrName, nil
<ide> }
<ide>
<del> ref, err := reference.ParseNamed(idOrName)
<add> ref, err := reference.ParseNormalizedNamed(idOrName)
<ide> if err != nil {
<ide> return "", errors.WithStack(ErrNotFound(idOrName))
<ide> }
<ide> if _, ok := ref.(reference.Canonical); ok {
<del> logrus.Warnf("canonical references cannot be resolved: %v", ref.String())
<add> logrus.Warnf("canonical references cannot be resolved: %v", reference.FamiliarString(ref))
<ide> return "", errors.WithStack(ErrNotFound(idOrName))
<ide> }
<ide>
<del> fullRef := reference.WithDefaultTag(ref)
<add> ref = reference.TagNameOnly(ref)
<ide>
<ide> for _, p := range ps.plugins {
<del> if p.PluginObj.Name == fullRef.String() {
<add> if p.PluginObj.Name == reference.FamiliarString(ref) {
<ide> return p.PluginObj.ID, nil
<ide> }
<ide> }
<ide><path>reference/reference.go
<del>package reference
<del>
<del>import (
<del> "fmt"
<del>
<del> distreference "github.com/docker/distribution/reference"
<del> "github.com/docker/docker/pkg/stringid"
<del> "github.com/opencontainers/go-digest"
<del> "github.com/pkg/errors"
<del>)
<del>
<del>const (
<del> // DefaultTag defines the default tag used when performing images related actions and no tag or digest is specified
<del> DefaultTag = "latest"
<del> // DefaultHostname is the default built-in hostname
<del> DefaultHostname = "docker.io"
<del> // LegacyDefaultHostname is automatically converted to DefaultHostname
<del> LegacyDefaultHostname = "index.docker.io"
<del> // DefaultRepoPrefix is the prefix used for default repositories in default host
<del> DefaultRepoPrefix = "library/"
<del>)
<del>
<del>// Named is an object with a full name
<del>type Named interface {
<del> // Name returns normalized repository name, like "ubuntu".
<del> Name() string
<del> // String returns full reference, like "ubuntu@sha256:abcdef..."
<del> String() string
<del> // FullName returns full repository name with hostname, like "docker.io/library/ubuntu"
<del> FullName() string
<del> // Hostname returns hostname for the reference, like "docker.io"
<del> Hostname() string
<del> // RemoteName returns the repository component of the full name, like "library/ubuntu"
<del> RemoteName() string
<del>}
<del>
<del>// NamedTagged is an object including a name and tag.
<del>type NamedTagged interface {
<del> Named
<del> Tag() string
<del>}
<del>
<del>// Canonical reference is an object with a fully unique
<del>// name including a name with hostname and digest
<del>type Canonical interface {
<del> Named
<del> Digest() digest.Digest
<del>}
<del>
<del>// ParseNamed parses s and returns a syntactically valid reference implementing
<del>// the Named interface. The reference must have a name, otherwise an error is
<del>// returned.
<del>// If an error was encountered it is returned, along with a nil Reference.
<del>func ParseNamed(s string) (Named, error) {
<del> named, err := distreference.ParseNormalizedNamed(s)
<del> if err != nil {
<del> return nil, errors.Wrapf(err, "failed to parse reference %q", s)
<del> }
<del> if err := validateName(distreference.FamiliarName(named)); err != nil {
<del> return nil, err
<del> }
<del>
<del> // Ensure returned reference cannot have tag and digest
<del> if canonical, isCanonical := named.(distreference.Canonical); isCanonical {
<del> r, err := distreference.WithDigest(distreference.TrimNamed(named), canonical.Digest())
<del> if err != nil {
<del> return nil, err
<del> }
<del> return &canonicalRef{namedRef{r}}, nil
<del> }
<del> if tagged, isTagged := named.(distreference.NamedTagged); isTagged {
<del> r, err := distreference.WithTag(distreference.TrimNamed(named), tagged.Tag())
<del> if err != nil {
<del> return nil, err
<del> }
<del> return &taggedRef{namedRef{r}}, nil
<del> }
<del>
<del> return &namedRef{named}, nil
<del>}
<del>
<del>// TrimNamed removes any tag or digest from the named reference
<del>func TrimNamed(ref Named) Named {
<del> return &namedRef{distreference.TrimNamed(ref)}
<del>}
<del>
<del>// WithName returns a named object representing the given string. If the input
<del>// is invalid ErrReferenceInvalidFormat will be returned.
<del>func WithName(name string) (Named, error) {
<del> r, err := distreference.ParseNormalizedNamed(name)
<del> if err != nil {
<del> return nil, err
<del> }
<del> if err := validateName(distreference.FamiliarName(r)); err != nil {
<del> return nil, err
<del> }
<del> if !distreference.IsNameOnly(r) {
<del> return nil, distreference.ErrReferenceInvalidFormat
<del> }
<del> return &namedRef{r}, nil
<del>}
<del>
<del>// WithTag combines the name from "name" and the tag from "tag" to form a
<del>// reference incorporating both the name and the tag.
<del>func WithTag(name Named, tag string) (NamedTagged, error) {
<del> r, err := distreference.WithTag(name, tag)
<del> if err != nil {
<del> return nil, err
<del> }
<del> return &taggedRef{namedRef{r}}, nil
<del>}
<del>
<del>// WithDigest combines the name from "name" and the digest from "digest" to form
<del>// a reference incorporating both the name and the digest.
<del>func WithDigest(name Named, digest digest.Digest) (Canonical, error) {
<del> r, err := distreference.WithDigest(name, digest)
<del> if err != nil {
<del> return nil, err
<del> }
<del> return &canonicalRef{namedRef{r}}, nil
<del>}
<del>
<del>type namedRef struct {
<del> distreference.Named
<del>}
<del>type taggedRef struct {
<del> namedRef
<del>}
<del>type canonicalRef struct {
<del> namedRef
<del>}
<del>
<del>func (r *namedRef) Name() string {
<del> return distreference.FamiliarName(r.Named)
<del>}
<del>
<del>func (r *namedRef) String() string {
<del> return distreference.FamiliarString(r.Named)
<del>}
<del>
<del>func (r *namedRef) FullName() string {
<del> return r.Named.Name()
<del>}
<del>func (r *namedRef) Hostname() string {
<del> return distreference.Domain(r.Named)
<del>}
<del>func (r *namedRef) RemoteName() string {
<del> return distreference.Path(r.Named)
<del>}
<del>func (r *taggedRef) Tag() string {
<del> return r.namedRef.Named.(distreference.NamedTagged).Tag()
<del>}
<del>func (r *canonicalRef) Digest() digest.Digest {
<del> return r.namedRef.Named.(distreference.Canonical).Digest()
<del>}
<del>
<del>// WithDefaultTag adds a default tag to a reference if it only has a repo name.
<del>func WithDefaultTag(ref Named) Named {
<del> if IsNameOnly(ref) {
<del> ref, _ = WithTag(ref, DefaultTag)
<del> }
<del> return ref
<del>}
<del>
<del>// IsNameOnly returns true if reference only contains a repo name.
<del>func IsNameOnly(ref Named) bool {
<del> if _, ok := ref.(NamedTagged); ok {
<del> return false
<del> }
<del> if _, ok := ref.(Canonical); ok {
<del> return false
<del> }
<del> return true
<del>}
<del>
<del>// ParseIDOrReference parses string for an image ID or a reference. ID can be
<del>// without a default prefix.
<del>func ParseIDOrReference(idOrRef string) (digest.Digest, Named, error) {
<del> if err := stringid.ValidateID(idOrRef); err == nil {
<del> idOrRef = "sha256:" + idOrRef
<del> }
<del> if dgst, err := digest.Parse(idOrRef); err == nil {
<del> return dgst, nil, nil
<del> }
<del> ref, err := ParseNamed(idOrRef)
<del> return "", ref, err
<del>}
<del>
<del>func validateName(name string) error {
<del> if err := stringid.ValidateID(name); err == nil {
<del> return fmt.Errorf("Invalid repository name (%s), cannot specify 64-byte hexadecimal strings", name)
<del> }
<del> return nil
<del>}
<ide><path>reference/reference_test.go
<del>package reference
<del>
<del>import (
<del> "testing"
<del>
<del> "github.com/opencontainers/go-digest"
<del>)
<del>
<del>func TestValidateReferenceName(t *testing.T) {
<del> validRepoNames := []string{
<del> "docker/docker",
<del> "library/debian",
<del> "debian",
<del> "docker.io/docker/docker",
<del> "docker.io/library/debian",
<del> "docker.io/debian",
<del> "index.docker.io/docker/docker",
<del> "index.docker.io/library/debian",
<del> "index.docker.io/debian",
<del> "127.0.0.1:5000/docker/docker",
<del> "127.0.0.1:5000/library/debian",
<del> "127.0.0.1:5000/debian",
<del> "thisisthesongthatneverendsitgoesonandonandonthisisthesongthatnev",
<del> }
<del> invalidRepoNames := []string{
<del> "https://github.com/docker/docker",
<del> "docker/Docker",
<del> "-docker",
<del> "-docker/docker",
<del> "-docker.io/docker/docker",
<del> "docker///docker",
<del> "docker.io/docker/Docker",
<del> "docker.io/docker///docker",
<del> "1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a",
<del> "docker.io/1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a",
<del> }
<del>
<del> for _, name := range invalidRepoNames {
<del> _, err := ParseNamed(name)
<del> if err == nil {
<del> t.Fatalf("Expected invalid repo name for %q", name)
<del> }
<del> }
<del>
<del> for _, name := range validRepoNames {
<del> _, err := ParseNamed(name)
<del> if err != nil {
<del> t.Fatalf("Error parsing repo name %s, got: %q", name, err)
<del> }
<del> }
<del>}
<del>
<del>func TestValidateRemoteName(t *testing.T) {
<del> validRepositoryNames := []string{
<del> // Sanity check.
<del> "docker/docker",
<del>
<del> // Allow 64-character non-hexadecimal names (hexadecimal names are forbidden).
<del> "thisisthesongthatneverendsitgoesonandonandonthisisthesongthatnev",
<del>
<del> // Allow embedded hyphens.
<del> "docker-rules/docker",
<del>
<del> // Allow multiple hyphens as well.
<del> "docker---rules/docker",
<del>
<del> //Username doc and image name docker being tested.
<del> "doc/docker",
<del>
<del> // single character names are now allowed.
<del> "d/docker",
<del> "jess/t",
<del>
<del> // Consecutive underscores.
<del> "dock__er/docker",
<del> }
<del> for _, repositoryName := range validRepositoryNames {
<del> _, err := ParseNamed(repositoryName)
<del> if err != nil {
<del> t.Errorf("Repository name should be valid: %v. Error: %v", repositoryName, err)
<del> }
<del> }
<del>
<del> invalidRepositoryNames := []string{
<del> // Disallow capital letters.
<del> "docker/Docker",
<del>
<del> // Only allow one slash.
<del> "docker///docker",
<del>
<del> // Disallow 64-character hexadecimal.
<del> "1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a",
<del>
<del> // Disallow leading and trailing hyphens in namespace.
<del> "-docker/docker",
<del> "docker-/docker",
<del> "-docker-/docker",
<del>
<del> // Don't allow underscores everywhere (as opposed to hyphens).
<del> "____/____",
<del>
<del> "_docker/_docker",
<del>
<del> // Disallow consecutive periods.
<del> "dock..er/docker",
<del> "dock_.er/docker",
<del> "dock-.er/docker",
<del>
<del> // No repository.
<del> "docker/",
<del>
<del> //namespace too long
<del> "this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255_this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255_this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255_this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255/docker",
<del> }
<del> for _, repositoryName := range invalidRepositoryNames {
<del> if _, err := ParseNamed(repositoryName); err == nil {
<del> t.Errorf("Repository name should be invalid: %v", repositoryName)
<del> }
<del> }
<del>}
<del>
<del>func TestParseRepositoryInfo(t *testing.T) {
<del> type tcase struct {
<del> RemoteName, NormalizedName, FullName, AmbiguousName, Hostname string
<del> }
<del>
<del> tcases := []tcase{
<del> {
<del> RemoteName: "fooo/bar",
<del> NormalizedName: "fooo/bar",
<del> FullName: "docker.io/fooo/bar",
<del> AmbiguousName: "index.docker.io/fooo/bar",
<del> Hostname: "docker.io",
<del> },
<del> {
<del> RemoteName: "library/ubuntu",
<del> NormalizedName: "ubuntu",
<del> FullName: "docker.io/library/ubuntu",
<del> AmbiguousName: "library/ubuntu",
<del> Hostname: "docker.io",
<del> },
<del> {
<del> RemoteName: "nonlibrary/ubuntu",
<del> NormalizedName: "nonlibrary/ubuntu",
<del> FullName: "docker.io/nonlibrary/ubuntu",
<del> AmbiguousName: "",
<del> Hostname: "docker.io",
<del> },
<del> {
<del> RemoteName: "other/library",
<del> NormalizedName: "other/library",
<del> FullName: "docker.io/other/library",
<del> AmbiguousName: "",
<del> Hostname: "docker.io",
<del> },
<del> {
<del> RemoteName: "private/moonbase",
<del> NormalizedName: "127.0.0.1:8000/private/moonbase",
<del> FullName: "127.0.0.1:8000/private/moonbase",
<del> AmbiguousName: "",
<del> Hostname: "127.0.0.1:8000",
<del> },
<del> {
<del> RemoteName: "privatebase",
<del> NormalizedName: "127.0.0.1:8000/privatebase",
<del> FullName: "127.0.0.1:8000/privatebase",
<del> AmbiguousName: "",
<del> Hostname: "127.0.0.1:8000",
<del> },
<del> {
<del> RemoteName: "private/moonbase",
<del> NormalizedName: "example.com/private/moonbase",
<del> FullName: "example.com/private/moonbase",
<del> AmbiguousName: "",
<del> Hostname: "example.com",
<del> },
<del> {
<del> RemoteName: "privatebase",
<del> NormalizedName: "example.com/privatebase",
<del> FullName: "example.com/privatebase",
<del> AmbiguousName: "",
<del> Hostname: "example.com",
<del> },
<del> {
<del> RemoteName: "private/moonbase",
<del> NormalizedName: "example.com:8000/private/moonbase",
<del> FullName: "example.com:8000/private/moonbase",
<del> AmbiguousName: "",
<del> Hostname: "example.com:8000",
<del> },
<del> {
<del> RemoteName: "privatebasee",
<del> NormalizedName: "example.com:8000/privatebasee",
<del> FullName: "example.com:8000/privatebasee",
<del> AmbiguousName: "",
<del> Hostname: "example.com:8000",
<del> },
<del> {
<del> RemoteName: "library/ubuntu-12.04-base",
<del> NormalizedName: "ubuntu-12.04-base",
<del> FullName: "docker.io/library/ubuntu-12.04-base",
<del> AmbiguousName: "index.docker.io/library/ubuntu-12.04-base",
<del> Hostname: "docker.io",
<del> },
<del> }
<del>
<del> for _, tcase := range tcases {
<del> refStrings := []string{tcase.NormalizedName, tcase.FullName}
<del> if tcase.AmbiguousName != "" {
<del> refStrings = append(refStrings, tcase.AmbiguousName)
<del> }
<del>
<del> var refs []Named
<del> for _, r := range refStrings {
<del> named, err := ParseNamed(r)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> refs = append(refs, named)
<del> named, err = WithName(r)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> refs = append(refs, named)
<del> }
<del>
<del> for _, r := range refs {
<del> if expected, actual := tcase.NormalizedName, r.Name(); expected != actual {
<del> t.Fatalf("Invalid normalized reference for %q. Expected %q, got %q", r, expected, actual)
<del> }
<del> if expected, actual := tcase.FullName, r.FullName(); expected != actual {
<del> t.Fatalf("Invalid fullName for %q. Expected %q, got %q", r, expected, actual)
<del> }
<del> if expected, actual := tcase.Hostname, r.Hostname(); expected != actual {
<del> t.Fatalf("Invalid hostname for %q. Expected %q, got %q", r, expected, actual)
<del> }
<del> if expected, actual := tcase.RemoteName, r.RemoteName(); expected != actual {
<del> t.Fatalf("Invalid remoteName for %q. Expected %q, got %q", r, expected, actual)
<del> }
<del>
<del> }
<del> }
<del>}
<del>
<del>func TestParseReferenceWithTagAndDigest(t *testing.T) {
<del> ref, err := ParseNamed("busybox:latest@sha256:86e0e091d0da6bde2456dbb48306f3956bbeb2eae1b5b9a43045843f69fe4aaa")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if _, isTagged := ref.(NamedTagged); isTagged {
<del> t.Fatalf("Reference from %q should not support tag", ref)
<del> }
<del> if _, isCanonical := ref.(Canonical); !isCanonical {
<del> t.Fatalf("Reference from %q should not support digest", ref)
<del> }
<del> if expected, actual := "busybox@sha256:86e0e091d0da6bde2456dbb48306f3956bbeb2eae1b5b9a43045843f69fe4aaa", ref.String(); actual != expected {
<del> t.Fatalf("Invalid parsed reference for %q: expected %q, got %q", ref, expected, actual)
<del> }
<del>}
<del>
<del>func TestInvalidReferenceComponents(t *testing.T) {
<del> if _, err := WithName("-foo"); err == nil {
<del> t.Fatal("Expected WithName to detect invalid name")
<del> }
<del> ref, err := WithName("busybox")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if _, err := WithTag(ref, "-foo"); err == nil {
<del> t.Fatal("Expected WithName to detect invalid tag")
<del> }
<del> if _, err := WithDigest(ref, digest.Digest("foo")); err == nil {
<del> t.Fatal("Expected WithName to detect invalid digest")
<del> }
<del>}
<ide><path>reference/store.go
<ide> import (
<ide> "sort"
<ide> "sync"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide> var (
<ide>
<ide> // An Association is a tuple associating a reference with an image ID.
<ide> type Association struct {
<del> Ref Named
<add> Ref reference.Named
<ide> ID digest.Digest
<ide> }
<ide>
<ide> // Store provides the set of methods which can operate on a tag store.
<ide> type Store interface {
<del> References(id digest.Digest) []Named
<del> ReferencesByName(ref Named) []Association
<del> AddTag(ref Named, id digest.Digest, force bool) error
<del> AddDigest(ref Canonical, id digest.Digest, force bool) error
<del> Delete(ref Named) (bool, error)
<del> Get(ref Named) (digest.Digest, error)
<add> References(id digest.Digest) []reference.Named
<add> ReferencesByName(ref reference.Named) []Association
<add> AddTag(ref reference.Named, id digest.Digest, force bool) error
<add> AddDigest(ref reference.Canonical, id digest.Digest, force bool) error
<add> Delete(ref reference.Named) (bool, error)
<add> Get(ref reference.Named) (digest.Digest, error)
<ide> }
<ide>
<ide> type store struct {
<ide> type store struct {
<ide> Repositories map[string]repository
<ide> // referencesByIDCache is a cache of references indexed by ID, to speed
<ide> // up References.
<del> referencesByIDCache map[digest.Digest]map[string]Named
<add> referencesByIDCache map[digest.Digest]map[string]reference.Named
<ide> }
<ide>
<ide> // Repository maps tags to digests. The key is a stringified Reference,
<ide> // including the repository name.
<ide> type repository map[string]digest.Digest
<ide>
<del>type lexicalRefs []Named
<add>type lexicalRefs []reference.Named
<ide>
<del>func (a lexicalRefs) Len() int { return len(a) }
<del>func (a lexicalRefs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
<del>func (a lexicalRefs) Less(i, j int) bool { return a[i].String() < a[j].String() }
<add>func (a lexicalRefs) Len() int { return len(a) }
<add>func (a lexicalRefs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
<add>func (a lexicalRefs) Less(i, j int) bool {
<add> return a[i].String() < a[j].String()
<add>}
<ide>
<ide> type lexicalAssociations []Association
<ide>
<del>func (a lexicalAssociations) Len() int { return len(a) }
<del>func (a lexicalAssociations) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
<del>func (a lexicalAssociations) Less(i, j int) bool { return a[i].Ref.String() < a[j].Ref.String() }
<add>func (a lexicalAssociations) Len() int { return len(a) }
<add>func (a lexicalAssociations) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
<add>func (a lexicalAssociations) Less(i, j int) bool {
<add> return a[i].Ref.String() < a[j].Ref.String()
<add>}
<ide>
<ide> // NewReferenceStore creates a new reference store, tied to a file path where
<ide> // the set of references are serialized in JSON format.
<ide> func NewReferenceStore(jsonPath string) (Store, error) {
<ide> store := &store{
<ide> jsonPath: abspath,
<ide> Repositories: make(map[string]repository),
<del> referencesByIDCache: make(map[digest.Digest]map[string]Named),
<add> referencesByIDCache: make(map[digest.Digest]map[string]reference.Named),
<ide> }
<ide> // Load the json file if it exists, otherwise create it.
<ide> if err := store.reload(); os.IsNotExist(err) {
<ide> func NewReferenceStore(jsonPath string) (Store, error) {
<ide>
<ide> // AddTag adds a tag reference to the store. If force is set to true, existing
<ide> // references can be overwritten. This only works for tags, not digests.
<del>func (store *store) AddTag(ref Named, id digest.Digest, force bool) error {
<del> if _, isCanonical := ref.(Canonical); isCanonical {
<add>func (store *store) AddTag(ref reference.Named, id digest.Digest, force bool) error {
<add> if _, isCanonical := ref.(reference.Canonical); isCanonical {
<ide> return errors.New("refusing to create a tag with a digest reference")
<ide> }
<del> return store.addReference(WithDefaultTag(ref), id, force)
<add> return store.addReference(reference.TagNameOnly(ref), id, force)
<ide> }
<ide>
<ide> // AddDigest adds a digest reference to the store.
<del>func (store *store) AddDigest(ref Canonical, id digest.Digest, force bool) error {
<add>func (store *store) AddDigest(ref reference.Canonical, id digest.Digest, force bool) error {
<ide> return store.addReference(ref, id, force)
<ide> }
<ide>
<del>func (store *store) addReference(ref Named, id digest.Digest, force bool) error {
<del> if ref.Name() == string(digest.Canonical) {
<add>func (store *store) addReference(ref reference.Named, id digest.Digest, force bool) error {
<add> refName := reference.FamiliarName(ref)
<add> refStr := reference.FamiliarString(ref)
<add>
<add> if refName == string(digest.Canonical) {
<ide> return errors.New("refusing to create an ambiguous tag using digest algorithm as name")
<ide> }
<ide>
<ide> store.mu.Lock()
<ide> defer store.mu.Unlock()
<ide>
<del> repository, exists := store.Repositories[ref.Name()]
<add> repository, exists := store.Repositories[refName]
<ide> if !exists || repository == nil {
<ide> repository = make(map[string]digest.Digest)
<del> store.Repositories[ref.Name()] = repository
<add> store.Repositories[refName] = repository
<ide> }
<ide>
<del> refStr := ref.String()
<ide> oldID, exists := repository[refStr]
<ide>
<ide> if exists {
<ide> // force only works for tags
<del> if digested, isDigest := ref.(Canonical); isDigest {
<add> if digested, isDigest := ref.(reference.Canonical); isDigest {
<ide> return fmt.Errorf("Cannot overwrite digest %s", digested.Digest().String())
<ide> }
<ide>
<ide> if !force {
<del> return fmt.Errorf("Conflict: Tag %s is already set to image %s, if you want to replace it, please use -f option", ref.String(), oldID.String())
<add> return fmt.Errorf("Conflict: Tag %s is already set to image %s, if you want to replace it, please use -f option", refStr, oldID.String())
<ide> }
<ide>
<ide> if store.referencesByIDCache[oldID] != nil {
<ide> func (store *store) addReference(ref Named, id digest.Digest, force bool) error
<ide>
<ide> repository[refStr] = id
<ide> if store.referencesByIDCache[id] == nil {
<del> store.referencesByIDCache[id] = make(map[string]Named)
<add> store.referencesByIDCache[id] = make(map[string]reference.Named)
<ide> }
<ide> store.referencesByIDCache[id][refStr] = ref
<ide>
<ide> func (store *store) addReference(ref Named, id digest.Digest, force bool) error
<ide>
<ide> // Delete deletes a reference from the store. It returns true if a deletion
<ide> // happened, or false otherwise.
<del>func (store *store) Delete(ref Named) (bool, error) {
<del> ref = WithDefaultTag(ref)
<add>func (store *store) Delete(ref reference.Named) (bool, error) {
<add> ref = reference.TagNameOnly(ref)
<add>
<add> refName := reference.FamiliarName(ref)
<add> refStr := reference.FamiliarString(ref)
<ide>
<ide> store.mu.Lock()
<ide> defer store.mu.Unlock()
<ide>
<del> repoName := ref.Name()
<del>
<del> repository, exists := store.Repositories[repoName]
<add> repository, exists := store.Repositories[refName]
<ide> if !exists {
<ide> return false, ErrDoesNotExist
<ide> }
<ide>
<del> refStr := ref.String()
<ide> if id, exists := repository[refStr]; exists {
<ide> delete(repository, refStr)
<ide> if len(repository) == 0 {
<del> delete(store.Repositories, repoName)
<add> delete(store.Repositories, refName)
<ide> }
<ide> if store.referencesByIDCache[id] != nil {
<ide> delete(store.referencesByIDCache[id], refStr)
<ide> func (store *store) Delete(ref Named) (bool, error) {
<ide> }
<ide>
<ide> // Get retrieves an item from the store by reference
<del>func (store *store) Get(ref Named) (digest.Digest, error) {
<del> ref = WithDefaultTag(ref)
<add>func (store *store) Get(ref reference.Named) (digest.Digest, error) {
<add> if canonical, ok := ref.(reference.Canonical); ok {
<add> // If reference contains both tag and digest, only
<add> // lookup by digest as it takes precendent over
<add> // tag, until tag/digest combos are stored.
<add> if _, ok := ref.(reference.Tagged); ok {
<add> var err error
<add> ref, err = reference.WithDigest(reference.TrimNamed(canonical), canonical.Digest())
<add> if err != nil {
<add> return "", err
<add> }
<add> }
<add> } else {
<add> ref = reference.TagNameOnly(ref)
<add> }
<add>
<add> refName := reference.FamiliarName(ref)
<add> refStr := reference.FamiliarString(ref)
<ide>
<ide> store.mu.RLock()
<ide> defer store.mu.RUnlock()
<ide>
<del> repository, exists := store.Repositories[ref.Name()]
<add> repository, exists := store.Repositories[refName]
<ide> if !exists || repository == nil {
<ide> return "", ErrDoesNotExist
<ide> }
<ide>
<del> id, exists := repository[ref.String()]
<add> id, exists := repository[refStr]
<ide> if !exists {
<ide> return "", ErrDoesNotExist
<ide> }
<ide> func (store *store) Get(ref Named) (digest.Digest, error) {
<ide>
<ide> // References returns a slice of references to the given ID. The slice
<ide> // will be nil if there are no references to this ID.
<del>func (store *store) References(id digest.Digest) []Named {
<add>func (store *store) References(id digest.Digest) []reference.Named {
<ide> store.mu.RLock()
<ide> defer store.mu.RUnlock()
<ide>
<ide> // Convert the internal map to an array for two reasons:
<ide> // 1) We must not return a mutable
<ide> // 2) It would be ugly to expose the extraneous map keys to callers.
<ide>
<del> var references []Named
<add> var references []reference.Named
<ide> for _, ref := range store.referencesByIDCache[id] {
<ide> references = append(references, ref)
<ide> }
<ide> func (store *store) References(id digest.Digest) []Named {
<ide> // ReferencesByName returns the references for a given repository name.
<ide> // If there are no references known for this repository name,
<ide> // ReferencesByName returns nil.
<del>func (store *store) ReferencesByName(ref Named) []Association {
<add>func (store *store) ReferencesByName(ref reference.Named) []Association {
<add> refName := reference.FamiliarName(ref)
<add>
<ide> store.mu.RLock()
<ide> defer store.mu.RUnlock()
<ide>
<del> repository, exists := store.Repositories[ref.Name()]
<add> repository, exists := store.Repositories[refName]
<ide> if !exists {
<ide> return nil
<ide> }
<ide>
<ide> var associations []Association
<ide> for refStr, refID := range repository {
<del> ref, err := ParseNamed(refStr)
<add> ref, err := reference.ParseNormalizedNamed(refStr)
<ide> if err != nil {
<ide> // Should never happen
<ide> return nil
<ide> func (store *store) reload() error {
<ide>
<ide> for _, repository := range store.Repositories {
<ide> for refStr, refID := range repository {
<del> ref, err := ParseNamed(refStr)
<add> ref, err := reference.ParseNormalizedNamed(refStr)
<ide> if err != nil {
<ide> // Should never happen
<ide> continue
<ide> }
<ide> if store.referencesByIDCache[refID] == nil {
<del> store.referencesByIDCache[refID] = make(map[string]Named)
<add> store.referencesByIDCache[refID] = make(map[string]reference.Named)
<ide> }
<ide> store.referencesByIDCache[refID][refStr] = ref
<ide> }
<ide><path>reference/store_test.go
<ide> import (
<ide> "strings"
<ide> "testing"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> "github.com/opencontainers/go-digest"
<ide> )
<ide>
<ide> func TestLoad(t *testing.T) {
<ide> }
<ide>
<ide> for refStr, expectedID := range saveLoadTestCases {
<del> ref, err := ParseNamed(refStr)
<add> ref, err := reference.ParseNormalizedNamed(refStr)
<ide> if err != nil {
<ide> t.Fatalf("failed to parse reference: %v", err)
<ide> }
<ide> func TestSave(t *testing.T) {
<ide> }
<ide>
<ide> for refStr, id := range saveLoadTestCases {
<del> ref, err := ParseNamed(refStr)
<add> ref, err := reference.ParseNormalizedNamed(refStr)
<ide> if err != nil {
<ide> t.Fatalf("failed to parse reference: %v", err)
<ide> }
<del> if canonical, ok := ref.(Canonical); ok {
<add> if canonical, ok := ref.(reference.Canonical); ok {
<ide> err = store.AddDigest(canonical, id, false)
<ide> if err != nil {
<ide> t.Fatalf("could not add digest reference %s: %v", refStr, err)
<ide> func TestAddDeleteGet(t *testing.T) {
<ide> testImageID3 := digest.Digest("sha256:9655aef5fd742a1b4e1b7b163aa9f1c76c186304bf39102283d80927c916ca9e")
<ide>
<ide> // Try adding a reference with no tag or digest
<del> nameOnly, err := WithName("username/repo")
<add> nameOnly, err := reference.ParseNormalizedNamed("username/repo")
<ide> if err != nil {
<ide> t.Fatalf("could not parse reference: %v", err)
<ide> }
<ide> func TestAddDeleteGet(t *testing.T) {
<ide> }
<ide>
<ide> // Add a few references
<del> ref1, err := ParseNamed("username/repo1:latest")
<add> ref1, err := reference.ParseNormalizedNamed("username/repo1:latest")
<ide> if err != nil {
<ide> t.Fatalf("could not parse reference: %v", err)
<ide> }
<ide> if err = store.AddTag(ref1, testImageID1, false); err != nil {
<ide> t.Fatalf("error adding to store: %v", err)
<ide> }
<ide>
<del> ref2, err := ParseNamed("username/repo1:old")
<add> ref2, err := reference.ParseNormalizedNamed("username/repo1:old")
<ide> if err != nil {
<ide> t.Fatalf("could not parse reference: %v", err)
<ide> }
<ide> if err = store.AddTag(ref2, testImageID2, false); err != nil {
<ide> t.Fatalf("error adding to store: %v", err)
<ide> }
<ide>
<del> ref3, err := ParseNamed("username/repo1:alias")
<add> ref3, err := reference.ParseNormalizedNamed("username/repo1:alias")
<ide> if err != nil {
<ide> t.Fatalf("could not parse reference: %v", err)
<ide> }
<ide> if err = store.AddTag(ref3, testImageID1, false); err != nil {
<ide> t.Fatalf("error adding to store: %v", err)
<ide> }
<ide>
<del> ref4, err := ParseNamed("username/repo2:latest")
<add> ref4, err := reference.ParseNormalizedNamed("username/repo2:latest")
<ide> if err != nil {
<ide> t.Fatalf("could not parse reference: %v", err)
<ide> }
<ide> if err = store.AddTag(ref4, testImageID2, false); err != nil {
<ide> t.Fatalf("error adding to store: %v", err)
<ide> }
<ide>
<del> ref5, err := ParseNamed("username/repo3@sha256:58153dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c")
<add> ref5, err := reference.ParseNormalizedNamed("username/repo3@sha256:58153dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c")
<ide> if err != nil {
<ide> t.Fatalf("could not parse reference: %v", err)
<ide> }
<del> if err = store.AddDigest(ref5.(Canonical), testImageID2, false); err != nil {
<add> if err = store.AddDigest(ref5.(reference.Canonical), testImageID2, false); err != nil {
<ide> t.Fatalf("error adding to store: %v", err)
<ide> }
<ide>
<ide> func TestAddDeleteGet(t *testing.T) {
<ide> }
<ide>
<ide> // Get should return ErrDoesNotExist for a nonexistent repo
<del> nonExistRepo, err := ParseNamed("username/nonexistrepo:latest")
<add> nonExistRepo, err := reference.ParseNormalizedNamed("username/nonexistrepo:latest")
<ide> if err != nil {
<ide> t.Fatalf("could not parse reference: %v", err)
<ide> }
<ide> func TestAddDeleteGet(t *testing.T) {
<ide> }
<ide>
<ide> // Get should return ErrDoesNotExist for a nonexistent tag
<del> nonExistTag, err := ParseNamed("username/repo1:nonexist")
<add> nonExistTag, err := reference.ParseNormalizedNamed("username/repo1:nonexist")
<ide> if err != nil {
<ide> t.Fatalf("could not parse reference: %v", err)
<ide> }
<ide> func TestAddDeleteGet(t *testing.T) {
<ide> }
<ide>
<ide> // Check ReferencesByName
<del> repoName, err := WithName("username/repo1")
<add> repoName, err := reference.ParseNormalizedNamed("username/repo1")
<ide> if err != nil {
<ide> t.Fatalf("could not parse reference: %v", err)
<ide> }
<ide> func TestInvalidTags(t *testing.T) {
<ide> id := digest.Digest("sha256:470022b8af682154f57a2163d030eb369549549cba00edc69e1b99b46bb924d6")
<ide>
<ide> // sha256 as repo name
<del> ref, err := ParseNamed("sha256:abc")
<add> ref, err := reference.ParseNormalizedNamed("sha256:abc")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestInvalidTags(t *testing.T) {
<ide> }
<ide>
<ide> // setting digest as a tag
<del> ref, err = ParseNamed("registry@sha256:367eb40fd0330a7e464777121e39d2f5b3e8e23a1e159342e53ab05c9e4d94e6")
<add> ref, err = reference.ParseNormalizedNamed("registry@sha256:367eb40fd0330a7e464777121e39d2f5b3e8e23a1e159342e53ab05c9e4d94e6")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide><path>registry/config.go
<ide> import (
<ide> "github.com/docker/distribution/reference"
<ide> registrytypes "github.com/docker/docker/api/types/registry"
<ide> "github.com/docker/docker/opts"
<del> forkedref "github.com/docker/docker/reference"
<ide> "github.com/pkg/errors"
<ide> "github.com/spf13/pflag"
<ide> )
<ide> func ValidateMirror(val string) (string, error) {
<ide>
<ide> // ValidateIndexName validates an index name.
<ide> func ValidateIndexName(val string) (string, error) {
<del> if val == forkedref.LegacyDefaultHostname {
<del> val = forkedref.DefaultHostname
<add> // TODO: upstream this to check to reference package
<add> if val == "index.docker.io" {
<add> val = "docker.io"
<ide> }
<ide> if strings.HasPrefix(val, "-") || strings.HasSuffix(val, "-") {
<ide> return "", fmt.Errorf("Invalid index name (%s). Cannot begin or end with a hyphen.", val)
<ide> func newRepositoryInfo(config *serviceConfig, name reference.Named) (*Repository
<ide> }
<ide> official := !strings.ContainsRune(reference.FamiliarName(name), '/')
<ide>
<del> // TODO: remove used of forked reference package
<del> nameref, err := forkedref.ParseNamed(name.String())
<del> if err != nil {
<del> return nil, err
<del> }
<ide> return &RepositoryInfo{
<del> Named: nameref,
<add> Name: reference.TrimNamed(name),
<ide> Index: index,
<ide> Official: official,
<ide> }, nil
<ide><path>registry/registry_mock_test.go
<ide> import (
<ide> "testing"
<ide> "time"
<ide>
<add> "github.com/docker/distribution/reference"
<ide> registrytypes "github.com/docker/docker/api/types/registry"
<del> "github.com/docker/docker/reference"
<ide> "github.com/gorilla/mux"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide><path>registry/registry_test.go
<ide> import (
<ide> "github.com/docker/distribution/registry/client/transport"
<ide> "github.com/docker/docker/api/types"
<ide> registrytypes "github.com/docker/docker/api/types/registry"
<del> forkedref "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> var (
<ide> func TestGetRemoteImageLayer(t *testing.T) {
<ide>
<ide> func TestGetRemoteTag(t *testing.T) {
<ide> r := spawnTestRegistrySession(t)
<del> repoRef, err := forkedref.ParseNamed(REPO)
<add> repoRef, err := reference.ParseNormalizedNamed(REPO)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestGetRemoteTag(t *testing.T) {
<ide> }
<ide> assertEqual(t, tag, imageID, "Expected tag test to map to "+imageID)
<ide>
<del> bazRef, err := forkedref.ParseNamed("foo42/baz")
<add> bazRef, err := reference.ParseNormalizedNamed("foo42/baz")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestGetRemoteTag(t *testing.T) {
<ide>
<ide> func TestGetRemoteTags(t *testing.T) {
<ide> r := spawnTestRegistrySession(t)
<del> repoRef, err := forkedref.ParseNamed(REPO)
<add> repoRef, err := reference.ParseNormalizedNamed(REPO)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestGetRemoteTags(t *testing.T) {
<ide> assertEqual(t, tags["latest"], imageID, "Expected tag latest to map to "+imageID)
<ide> assertEqual(t, tags["test"], imageID, "Expected tag test to map to "+imageID)
<ide>
<del> bazRef, err := forkedref.ParseNamed("foo42/baz")
<add> bazRef, err := reference.ParseNormalizedNamed("foo42/baz")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestGetRepositoryData(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> host := "http://" + parsedURL.Host + "/v1/"
<del> repoRef, err := forkedref.ParseNamed(REPO)
<add> repoRef, err := reference.ParseNormalizedNamed(REPO)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestParseRepositoryInfo(t *testing.T) {
<ide> t.Error(err)
<ide> } else {
<ide> checkEqual(t, repoInfo.Index.Name, expectedRepoInfo.Index.Name, reposName)
<del> checkEqual(t, repoInfo.RemoteName(), expectedRepoInfo.RemoteName, reposName)
<del> checkEqual(t, repoInfo.Name(), expectedRepoInfo.LocalName, reposName)
<del> checkEqual(t, repoInfo.FullName(), expectedRepoInfo.CanonicalName, reposName)
<add> checkEqual(t, reference.Path(repoInfo.Name), expectedRepoInfo.RemoteName, reposName)
<add> checkEqual(t, reference.FamiliarName(repoInfo.Name), expectedRepoInfo.LocalName, reposName)
<add> checkEqual(t, repoInfo.Name.Name(), expectedRepoInfo.CanonicalName, reposName)
<ide> checkEqual(t, repoInfo.Index.Official, expectedRepoInfo.Index.Official, reposName)
<ide> checkEqual(t, repoInfo.Official, expectedRepoInfo.Official, reposName)
<ide> }
<ide> func TestMirrorEndpointLookup(t *testing.T) {
<ide>
<ide> func TestPushRegistryTag(t *testing.T) {
<ide> r := spawnTestRegistrySession(t)
<del> repoRef, err := forkedref.ParseNamed(REPO)
<add> repoRef, err := reference.ParseNormalizedNamed(REPO)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestPushImageJSONIndex(t *testing.T) {
<ide> Checksum: "sha256:bea7bf2e4bacd479344b737328db47b18880d09096e6674165533aa994f5e9f2",
<ide> },
<ide> }
<del> repoRef, err := forkedref.ParseNamed(REPO)
<add> repoRef, err := reference.ParseNormalizedNamed(REPO)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide><path>registry/session.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/api/errcode"
<ide> "github.com/docker/docker/api/types"
<ide> registrytypes "github.com/docker/docker/api/types/registry"
<ide> "github.com/docker/docker/pkg/httputils"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/pkg/tarsum"
<del> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> var (
<ide> func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io
<ide> // argument, and returns data from the first one that answers the query
<ide> // successfully.
<ide> func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Named, askedTag string) (string, error) {
<del> repository := repositoryRef.RemoteName()
<add> repository := reference.Path(repositoryRef)
<ide>
<ide> if strings.Count(repository, "/") == 0 {
<ide> // This will be removed once the registry supports auto-resolution on
<ide> func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Name
<ide> // the first one that answers the query successfully. It returns a map with
<ide> // tag names as the keys and image IDs as the values.
<ide> func (r *Session) GetRemoteTags(registries []string, repositoryRef reference.Named) (map[string]string, error) {
<del> repository := repositoryRef.RemoteName()
<add> repository := reference.Path(repositoryRef)
<ide>
<ide> if strings.Count(repository, "/") == 0 {
<ide> // This will be removed once the registry supports auto-resolution on
<ide> func buildEndpointsList(headers []string, indexEp string) ([]string, error) {
<ide>
<ide> // GetRepositoryData returns lists of images and endpoints for the repository
<ide> func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, error) {
<del> repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.String(), name.RemoteName())
<add> repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.String(), reference.Path(name))
<ide>
<ide> logrus.Debugf("[registry] Calling GET %s", repositoryTarget)
<ide>
<ide> func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, erro
<ide> if err != nil {
<ide> logrus.Debugf("Error reading response body: %s", err)
<ide> }
<del> return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, name.RemoteName(), errBody), res)
<add> return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, reference.Path(name), errBody), res)
<ide> }
<ide>
<ide> var endpoints []string
<ide> func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry
<ide> func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registry string) error {
<ide> // "jsonify" the string
<ide> revision = "\"" + revision + "\""
<del> path := fmt.Sprintf("repositories/%s/tags/%s", remote.RemoteName(), tag)
<add> path := fmt.Sprintf("repositories/%s/tags/%s", reference.Path(remote), tag)
<ide>
<ide> req, err := http.NewRequest("PUT", registry+path, strings.NewReader(revision))
<ide> if err != nil {
<ide> func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registr
<ide> }
<ide> res.Body.Close()
<ide> if res.StatusCode != 200 && res.StatusCode != 201 {
<del> return httputils.NewHTTPRequestError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, remote.RemoteName()), res)
<add> return httputils.NewHTTPRequestError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, reference.Path(remote)), res)
<ide> }
<ide> return nil
<ide> }
<ide> func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData,
<ide> if validate {
<ide> suffix = "images"
<ide> }
<del> u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.String(), remote.RemoteName(), suffix)
<add> u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.String(), reference.Path(remote), suffix)
<ide> logrus.Debugf("[registry] PUT %s", u)
<ide> logrus.Debugf("Image list pushed to index:\n%s", imgListJSON)
<ide> headers := map[string][]string{
<ide> func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData,
<ide> if err != nil {
<ide> logrus.Debugf("Error reading response body: %s", err)
<ide> }
<del> return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, remote.RemoteName(), errBody), res)
<add> return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, reference.Path(remote), errBody), res)
<ide> }
<ide> tokens = res.Header["X-Docker-Token"]
<ide> logrus.Debugf("Auth token: %v", tokens)
<ide> func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData,
<ide> if err != nil {
<ide> logrus.Debugf("Error reading response body: %s", err)
<ide> }
<del> return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, remote.RemoteName(), errBody), res)
<add> return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, reference.Path(remote), errBody), res)
<ide> }
<ide> }
<ide>
<ide><path>registry/types.go
<ide> package registry
<ide>
<ide> import (
<add> "github.com/docker/distribution/reference"
<ide> registrytypes "github.com/docker/docker/api/types/registry"
<del> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> // RepositoryData tracks the image list, list of endpoints for a repository
<ide> var apiVersions = map[APIVersion]string{
<ide>
<ide> // RepositoryInfo describes a repository
<ide> type RepositoryInfo struct {
<del> reference.Named
<add> Name reference.Named
<ide> // Index points to registry information
<ide> Index *registrytypes.IndexInfo
<ide> // Official indicates whether the repository is considered official. | 78 |
Text | Text | fix portuguese translation for arraylist | 140dab84897bb210e59cdef005694ef98ab62f1f | <ide><path>guide/portuguese/java/abstract-class/index.md
<ide> localeTitle: Classes Abstratas em Java
<ide> ---
<ide> Vamos discutir classes abstratas. Antes de mergulhar neste tutorial, é melhor que você tenha entendido conceitos de classes e herança.
<ide>
<del>Classes abstratas são classes que podem ser subclassificadas (isto é, estendidas), mas não podem ser instanciadas. Você pode pensar neles como uma **versão** de **classe** de interfaces ou como uma interface com código real anexado aos métodos.
<add>Classes abstratas são classes que podem ser herdadas (isto é, estendidas), mas não podem ser instanciadas. Você pode pensar neles como uma **versão** de **classe** de interfaces ou como uma interface com código real anexado aos métodos.
<ide>
<del>Considere o seguinte exemplo para entender classes abstratas: Você tem uma classe Vehicle que define certas funcionalidades básicas (métodos) e certos componentes (variáveis de objeto) que uma máquina deve ter, para ser classificada como veículo. Você não pode criar um objeto de Veículo porque um veículo em si é um conceito abstrato. No entanto, você pode estender a funcionalidade da classe de veículo para criar um carro ou uma motocicleta.
<add>Considere o seguinte exemplo para entender classes abstratas: Você tem uma classe Veículo que define certas funcionalidades básicas (métodos) e certos componentes (variáveis de objeto) que uma máquina deve ter, para ser classificada como veículo. Você não pode criar um objeto de tipo Veículo porque um veículo em si é um conceito abstrato. No entanto, você pode estender a funcionalidade da classe de veículo para criar um carro ou uma motocicleta.
<ide>
<del>\`\` \`java classe abstrata Veículo { // variável usada para declarar o não. de rodas em um veículo rodas int privadas;
<add>``` java
<add>abstract class Veiculo {
<ide>
<del>// Variável para definir o tipo de motor usado Motor privado;
<add>// variável usada para declarar o não. de rodas em um veículo
<add>private int rodas;
<ide>
<del>// um método abstrato que apenas declara, mas não define o início // funcionalidade porque cada veículo usa um mecanismo de partida diferente Resumo void start (); }
<add>// Variável para definir o tipo de motor
<add>private Motor motor;
<ide>
<del>carro de classe pública estende veículo { … }
<add>// um método abstrato que apenas declara, mas não define o mecanismo de partida
<add>// funcionalidade porque cada veículo usa um mecanismo de partida diferente
<add>abstract void start ();
<ide>
<del>classe pública motocicleta estende veículo { … }
<del>```
<del>You cannot create an object of Vehicle class anywhere in your program. You can however, extend the abstract vehicle class and create objects of the child classes;
<add>}
<add>public class Carro extends Veiculo
<add>{
<add> ...
<add>}
<add>
<add>public class Motocicleta extends Veiculo
<add>{
<add> ...
<add>}
<ide> ```
<add>Você não pode criar um objeto usando a classe Veiculo. Porém, você pode extender a classe Veiculo, e, então, criar um objeto desta classe que extendeu Veiculo.
<add>
<add>``` java
<add>
<ide>
<del>Java Veículo newVehicle = new Vehicle (); // Inválido Veículo car = new Car (); // válido Veículo mBike = new Motorcycle (); // válido
<add> Veiculo veiculo = new Veiculo (); // Inválido
<add> Veiculo carro = new Carro(); // válido
<add> Veiculo mBike = new Motocicleta (); // válido
<ide>
<del>Car carObj = carro novo (); // válido Motocicleta mBikeObj = nova motocicleta (); // válido \`\` \`
<ide>\ No newline at end of file
<add> Carro carro = new Carro(); // válido
<add> Motocicleta mBikeObj = new Motocicleta(); // válido
<add>
<add> ```
<ide><path>guide/portuguese/java/arraylist/index.md
<ide> localeTitle: ArrayList
<ide> ---
<ide> # ArrayList
<ide>
<del>ArrayList é uma parte de algo chamado de _estrutura de coleção_ .
<add>ArrayList é uma parte de algo chamado de _estrutura de Coleção (Collection)_ .
<ide>
<del>A _estrutura de coleta_ consiste em todas as interfaces e classes que podem conter um conjunto de valores (semelhante a [matrizes](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) ). **ArrayList** é uma classe que está nesta hierarquia e é conhecida como um _**objeto Collection**_ . Ele implementa a interface _List_ , que por sua vez implementa a interface _Collection_ . Essa interface _Collection_ pode ser encontrada no pacote `java.util` . Você precisará importar este pacote.
<add>A _estrutura de Coleção_ consiste de todas as interfaces e classes que podem conter um conjunto de valores (semelhante a [arrays](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) ). **ArrayList** é uma classe que está nesta hierarquia e é conhecida como um _**objeto Collection**_. ArrayList implementa a interface _List_, que por sua vez implementa a interface _Collection_ . Essa interface _Collection_ pode ser encontrada no pacote `java.util`. Você precisará importar este pacote.
<ide>
<ide> ArrayList é uma classe usada para criar matrizes dinâmicas. É mais lento que os arrays regulares, mas permite muita manipulação. Pode ser inicializado para ter um tamanho específico ou terá um tamanho padrão de 10 unidades.
<ide>
<del>`java ArrayList<String> names = new ArrayList<>(); ArrayList<Integer> ages = new ArrayList<>(5);`
<add>``` java
<add>ArrayList<String> nomes = new ArrayList<>();
<add>ArrayList<Integer> idades = new ArrayList<>(5);
<add>```
<ide>
<del>No snippet acima, o ângulo breackets `<>` toma um tipo de dados genérico como argumento especificando o tipo de dados dos elementos no ArrayList. Os primeiros `names` ArrayList são especificados como contendo elementos _String_ . Assim, só será permitido conter elementos String. Seu tamanho não é especificado, portanto, ele terá um tamanho padrão de 10. A segunda `ages` ArrayList especificou que ele só conterá inteiros. Mas ArrayList não pode conter primitivos, ele só contém objetos. Assim, para torná-lo armazenar números inteiros, flutuantes, etc., podemos usar classes wrapper. `names` terão um tamanho especificado de 5.
<add>No snippet acima, `<>` toma um tipo de dados genérico como argumento especificando o tipo de dados dos elementos no ArrayList. No primeiro exemplo, o ArrayList `nomes` são especificados como contendo elementos _String_. Assim, só será permitido conter elementos String. Seu tamanho não é especificado, portanto, ele terá um tamanho inicial de 10. O segundo exemplo, o ArrayList `idades`, especificou que ele só conterá inteiros. Mas ArrayList não pode conter primitivos, ele só contém objetos. Assim, para poder armazenar números inteiros, reais, etc., podemos usar classes wrapper. `idades` terão um tamanho inicial especificado: 5.
<ide>
<del>Como ArrayList implementa _List_ , um ArrayList pode ser criado usando a seguinte sintaxe: `java List<Integer> students = new ArrayList<>();`
<add>Como ArrayList implementa _List_ , um ArrayList pode ser criado usando a seguinte sintaxe:
<ide>
<del>Um ArrayList é dinâmico, o que significa que ele aumentará de tamanho se necessário e, da mesma forma, diminuirá em tamanho se os elementos forem excluídos dele. É isso que faz com que seja melhor usar do que os arrays normais.
<add>``` java
<add>List<Integer> estudantes = new ArrayList<>();
<add>```
<ide>
<del>Um ArrayList nos permite acessar elementos aleatoriamente. ArrayList é semelhante ao _Vector de_ várias formas. Mas é mais rápido que Vetores. A principal coisa a notar é que - Os vetores são mais rápidos que os arrays, mas os ArrayLists não são.
<add>Um ArrayList é dinâmico, o que significa que ele aumentará de tamanho se necessário e, da mesma forma, diminuirá de tamanho se os elementos forem excluídos dele. É esta dinamicidade que faz com que seja melhor usar do que os arrays normais quando queremos que o array cresça ou dimunua de tamanho.
<add>
<add>Para criar/remover todos os elementos de um ArrayList
<add>
<add> ```java
<add> variavel.clear();
<add> ```
<add> Nos podemos remover elementos existentes em uma lista
<add>
<add> ```java
<add> variavel.remove(posicao);
<add> ```
<add> Para acessar um elemento presente na lista
<add>
<add> ```java
<add> variavel.get(posicao);
<add> ```
<add> Nos podemos modificar um elemento presente na lista também
<add>
<add> ```java
<add> variavel.set(posicao, elemento);
<add> ```
<add> Nos podemos inverter a ordem dos elementos no ArrayList
<add>
<add> ```java
<add> import java.util.Collections; // package
<add>
<add> Collections.reverse(variavel);
<add> ```
<add> Ordenar em ordem ascendente
<add> ```java
<add> Collections.sort(variavel);
<add> ```
<add>
<add> Ordenar em ordem descendente
<add> ```java
<add> Collections.reverseOrder();
<add> ```
<add> Um ArrayList nos permite acessar elementos aleatoriamente. ArrayList é semelhante ao _Vector_ de_ várias formas. Mas é mais rápido que _Vector_. A principal coisa a notar é que - Objetos _Vector_ são mais rápidos que objetos que são arrays, mas objectos _ArrayList_ não são.
<add>
<add> Então, quando se trata de escolher entre os dois - se a velocidade é crítica, então _Vector_ devem ser considerados, caso contrário, _ArrayList_ são melhores quando se trata de armazenar grande número de elementos e acessá-los de forma eficiente.
<add>
<add>## More Information
<add>- [ArrayList Documentation](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)
<ide>
<del>Então, quando se trata de escolher entre os dois - se a velocidade é crítica, então os vetores devem ser considerados, caso contrário, ArrayLists são melhores quando se trata de armazenar grande número de elementos e acessá-los de forma eficiente.
<ide>\ No newline at end of file | 2 |
PHP | PHP | simplify doc block | d44d156aaa545c3231608a423728523a976c4e4b | <ide><path>src/Illuminate/Database/Schema/PostgresBuilder.php
<ide> public function getColumnListing($table)
<ide> }
<ide>
<ide> /**
<del> * Determines which schema should be used
<del> * Returns and array of schema and table name
<del> * less schema name if found
<add> * Determines which schema should be used.
<ide> *
<ide> * @param string $table
<ide> * @return [ string, string ] | 1 |
Javascript | Javascript | fix bug where node is removed while dragging | 01124f27b83fbde05628cf44afc620a18aca93ca | <ide><path>d3.layout.js
<ide> d3.layout.force = function() {
<ide>
<ide> function dragmove() {
<ide> if (!d3_layout_forceDragNode) return;
<add>
<add> // O NOES! The drag element was removed from the DOM.
<add> if (!d3_layout_forceDragElement.parentNode) {
<add> d3_layout_forceDragNode.fixed = false;
<add> d3_layout_forceDragNode = d3_layout_forceDragElement = null;
<add> return;
<add> }
<add>
<ide> var m = d3.svg.mouse(d3_layout_forceDragElement);
<ide> d3_layout_forceDragNode.px = m[0];
<ide> d3_layout_forceDragNode.py = m[1];
<ide><path>d3.layout.min.js
<del>(function(){function N(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function M(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function L(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function K(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function J(a,b){return a.depth-b.depth}function I(a,b){return b.x-a.x}function H(a,b){return a.x-b.x}function G(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=G(c[f],b),a)>0&&(a=d)}return a}function F(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function E(a){return a.children?a.children[0]:a._tree.thread}function D(a,b){return a.parent==b.parent?1:2}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a){var b=a.children;return b?B(b[b.length-1]):a}function A(a){var b=a.children;return b?A(b[0]):a}function z(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function y(a){return 1+d3.max(a,function(a){return a.y})}function x(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function w(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)w(e[f],b,c,d)}}function v(a){var b=a.children;b?(b.forEach(v),a.r=s(b)):a.r=Math.sqrt(a.value)}function u(a){delete a._pack_next,delete a._pack_prev}function t(a){a._pack_next=a._pack_prev=a}function s(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(t),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],x(g,h,i),l(i),p(g,i),g._pack_prev=i,p(i,h),h=g._pack_next;for(var m=3;m<f;m++){x(g,h,i=a[m]);var n=0,o=1,s=1;for(j=h._pack_next;j!=h;j=j._pack_next,o++)if(r(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!=j._pack_prev;k=k._pack_prev,s++)if(r(k,i)){s<o&&(n=-1,j=k);break}n==0?(p(g,i),h=i,l(i)):n>0?(q(g,j),h=j,m--):(q(j,h),g=j,m--)}}}var v=(b+c)/2,w=(d+e)/2,y=0;for(var m=0;m<f;m++){var z=a[m];z.x-=v,z.y-=w,y=Math.max(y,z.r+Math.sqrt(z.x*z.x+z.y*z.y))}a.forEach(u);return y}function r(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function q(a,b){a._pack_next=b,b._pack_prev=a}function p(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function o(a,b){return a.value-b.value}function n(a,b){return b.value-a.value}function m(a){return a.value}function l(a){return a.children}function k(a,b){return a+b.y}function j(a){var b=1,c=0,d=a[0].y,e,f=a.length;for(;b<f;++b)(e=a[b].y)>d&&(c=b,d=e);return c}function i(a){return a.reduce(k,0)}function f(c){(a=c).fixed=!0,b=this,d3.event.stopPropagation(),d3.event.preventDefault()}function e(b){b!==a&&(b.fixed=!1)}function c(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function w(){!a||(v(),a.fixed=!1,a=b=null)}function v(){if(!!a){var c=d3.svg.mouse(b);a.px=c[0],a.py=c[1],d.resume()}}function u(){var a=p.length,b=q.length,c=d3.geom.quadtree(p),d,e,f,n,o,r,u;d=-1;while(++d<a)(e=p[d]).fx=e.fy=0;for(d=0;d<b;++d){e=q[d],f=e.source,n=e.target,r=n.x-f.x,u=n.y-f.y;if(o=Math.sqrt(r*r+u*u))o=i*(o-k)/o,r*=o,u*=o,n.x-=r,n.y-=u,f.x+=r,f.y+=u}s(c);var v=i*m;r=h[0]/2,u=h[1]/2,d=-1;while(++d<a)e=p[d],f=r-e.x,n=u-e.y,o=v*Math.pow(f*f+n*n,.01),f*=o,n*=o,e.fx+=f,e.fy+=n;var w=i*l;d=-1;while(++d<a)c.visit(t(p[d],w));d=-1;while(++d<a)e=p[d],e.fixed?(e.x=e.px,e.y=e.py):(r=e.px-(e.px=e.x),u=e.py-(e.py=e.y),e.x+=e.fx-r*j,e.y+=e.fy-u*j);g.tick.dispatch({type:"tick"});return(i*=.99)<.005}function t(a,b){return function(c,d,e,f,g){if(c.point!=a){var h=c.cx-a.x||Math.random(),i=c.cy-a.y||Math.random(),j=1/Math.sqrt(h*h+i*i);if((f-d)*j<n){var k=b*c.count*j*j;a.fx+=h*k,a.fy+=i*k;return!0}if(c.point){var k=b*j*j;a.fx+=h*k,a.fy+=i*k}}}}function s(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){s(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}var d={},g=d3.dispatch("tick"),h=[1,1],i,j=.9,k=20,l=-30,m=.1,n=.8,o,p,q,r;d.on=function(a,b){g[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return p;p=a;return d},d.links=function(a){if(!arguments.length)return q;q=a;return d},d.size=function(a){if(!arguments.length)return h;h=a;return d},d.distance=function(a){if(!arguments.length)return k;k=a;return d},d.drag=function(a){if(!arguments.length)return j;j=a;return d},d.charge=function(a){if(!arguments.length)return l;l=a;return d},d.gravity=function(a){if(!arguments.length)return m;m=a;return d},d.theta=function(a){if(!arguments.length)return n;n=a;return d},d.start=function(){var a,b=p.length,c=q.length,e=h[0],f=h[1],g;for(a=0;a<b;++a)g=p[a],isNaN(g.x)&&(g.x=Math.random()*e),isNaN(g.y)&&(g.y=Math.random()*f),isNaN(g.px)&&(g.px=g.x),isNaN(g.py)&&(g.py=g.y);for(a=0;a<c;++a)g=q[a],typeof g.source=="number"&&(g.source=p[g.source]),typeof g.target=="number"&&(g.target=p[g.target]);return d.resume()},d.resume=function(){i=.1,d3.timer(u);return d},d.stop=function(){i=0;return d},d.drag=function(){this.on("mouseover",c).on("mouseout",e).on("mousedown",f),d3.select(window).on("mousemove",v).on("mouseup",w);return d};return d};var a,b;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function c(c){var d=c.length,e=c[0].length,f,i,j,k=g[a](c);h[b](c,k);for(i=0;i<e;++i)for(f=1,j=c[k[0]][i].y0;f<d;++f)c[k[f]][i].y0=j+=c[k[f-1]][i].y;return c}var a="default",b="zero";c.order=function(b){if(!arguments.length)return a;a=b;return c},c.offset=function(a){if(!arguments.length)return b;b=a;return c};return c};var g={"inside-out":function(a){var b=a.length,c,d,e=a.map(j),f=a.map(i),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,k=0,l=[],m=[];for(c=0;c<b;c++)d=g[c],h<k?(h+=f[d],l.push(d)):(k+=f[d],m.push(d));return m.reverse().concat(l)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},h={silhouette:function(a,b){var c=a.length,d=a[0].length,e=[],f=0,g,h,i;for(h=0;h<d;++h){for(g=0,i=0;g<c;g++)i+=a[g][h].y;i>f&&(f=i),e.push(i)}for(h=0,g=b[0];h<d;++h)a[g][h].y0=(f-e[h])/2},wiggle:function(a,b){var c=a.length,d=a[0],e=d.length,f=0,g,h,i,j,k,l=b[0],m,n,o,p,q,r;a[l][0].y0=q=r=0;for(h=1;h<e;++h){for(g=0,m=0;g<c;++g)m+=a[g][h].y;for(g=0,n=0,p=d[h].x-d[h-1].x;g<c;++g){for(i=0,j=b[g],o=(a[j][h].y-a[j][h-1].y)/(2*p);i<g;++i)o+=(a[k=b[i]][h].y-a[k][h-1].y)/p;n+=o*a[j][h].y}a[l][h].y0=q-=m?n/m*p:0,q<r&&(r=q)}for(h=0;h<e;++h)a[l][h].y0-=r},zero:function(a,b){var c=0,d=a[0].length,e=b[0];for(;c<d;++c)a[e][c].y0=0}};d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=n,b=l,c=m;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,v(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);w(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(o)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;K(g,function(a){a.children?(a.x=z(a.children),a.y=y(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=A(g),m=B(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;K(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=D,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=C,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=F(g),e=E(e),g&&e)h=E(h),f=F(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(M(N(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!F(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!E(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;L(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];K(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=G(g,I),l=G(g,H),m=G(g,J),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;K(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=D,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=C,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})()
<ide>\ No newline at end of file
<add>(function(){function N(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function M(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function L(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function K(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function J(a,b){return a.depth-b.depth}function I(a,b){return b.x-a.x}function H(a,b){return a.x-b.x}function G(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=G(c[f],b),a)>0&&(a=d)}return a}function F(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function E(a){return a.children?a.children[0]:a._tree.thread}function D(a,b){return a.parent==b.parent?1:2}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a){var b=a.children;return b?B(b[b.length-1]):a}function A(a){var b=a.children;return b?A(b[0]):a}function z(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function y(a){return 1+d3.max(a,function(a){return a.y})}function x(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function w(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)w(e[f],b,c,d)}}function v(a){var b=a.children;b?(b.forEach(v),a.r=s(b)):a.r=Math.sqrt(a.value)}function u(a){delete a._pack_next,delete a._pack_prev}function t(a){a._pack_next=a._pack_prev=a}function s(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(t),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],x(g,h,i),l(i),p(g,i),g._pack_prev=i,p(i,h),h=g._pack_next;for(var m=3;m<f;m++){x(g,h,i=a[m]);var n=0,o=1,s=1;for(j=h._pack_next;j!=h;j=j._pack_next,o++)if(r(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!=j._pack_prev;k=k._pack_prev,s++)if(r(k,i)){s<o&&(n=-1,j=k);break}n==0?(p(g,i),h=i,l(i)):n>0?(q(g,j),h=j,m--):(q(j,h),g=j,m--)}}}var v=(b+c)/2,w=(d+e)/2,y=0;for(var m=0;m<f;m++){var z=a[m];z.x-=v,z.y-=w,y=Math.max(y,z.r+Math.sqrt(z.x*z.x+z.y*z.y))}a.forEach(u);return y}function r(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function q(a,b){a._pack_next=b,b._pack_prev=a}function p(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function o(a,b){return a.value-b.value}function n(a,b){return b.value-a.value}function m(a){return a.value}function l(a){return a.children}function k(a,b){return a+b.y}function j(a){var b=1,c=0,d=a[0].y,e,f=a.length;for(;b<f;++b)(e=a[b].y)>d&&(c=b,d=e);return c}function i(a){return a.reduce(k,0)}function f(c){(a=c).fixed=!0,b=this,d3.event.stopPropagation(),d3.event.preventDefault()}function e(b){b!==a&&(b.fixed=!1)}function c(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function w(){!a||(v(),a.fixed=!1,a=b=null)}function v(){if(!!a){if(!b.parentNode){a.fixed=!1,a=b=null;return}var c=d3.svg.mouse(b);a.px=c[0],a.py=c[1],d.resume()}}function u(){var a=p.length,b=q.length,c=d3.geom.quadtree(p),d,e,f,n,o,r,u;d=-1;while(++d<a)(e=p[d]).fx=e.fy=0;for(d=0;d<b;++d){e=q[d],f=e.source,n=e.target,r=n.x-f.x,u=n.y-f.y;if(o=Math.sqrt(r*r+u*u))o=i*(o-k)/o,r*=o,u*=o,n.x-=r,n.y-=u,f.x+=r,f.y+=u}s(c);var v=i*m;r=h[0]/2,u=h[1]/2,d=-1;while(++d<a)e=p[d],f=r-e.x,n=u-e.y,o=v*Math.pow(f*f+n*n,.01),f*=o,n*=o,e.fx+=f,e.fy+=n;var w=i*l;d=-1;while(++d<a)c.visit(t(p[d],w));d=-1;while(++d<a)e=p[d],e.fixed?(e.x=e.px,e.y=e.py):(r=e.px-(e.px=e.x),u=e.py-(e.py=e.y),e.x+=e.fx-r*j,e.y+=e.fy-u*j);g.tick.dispatch({type:"tick"});return(i*=.99)<.005}function t(a,b){return function(c,d,e,f,g){if(c.point!=a){var h=c.cx-a.x||Math.random(),i=c.cy-a.y||Math.random(),j=1/Math.sqrt(h*h+i*i);if((f-d)*j<n){var k=b*c.count*j*j;a.fx+=h*k,a.fy+=i*k;return!0}if(c.point){var k=b*j*j;a.fx+=h*k,a.fy+=i*k}}}}function s(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){s(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}var d={},g=d3.dispatch("tick"),h=[1,1],i,j=.9,k=20,l=-30,m=.1,n=.8,o,p,q,r;d.on=function(a,b){g[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return p;p=a;return d},d.links=function(a){if(!arguments.length)return q;q=a;return d},d.size=function(a){if(!arguments.length)return h;h=a;return d},d.distance=function(a){if(!arguments.length)return k;k=a;return d},d.drag=function(a){if(!arguments.length)return j;j=a;return d},d.charge=function(a){if(!arguments.length)return l;l=a;return d},d.gravity=function(a){if(!arguments.length)return m;m=a;return d},d.theta=function(a){if(!arguments.length)return n;n=a;return d},d.start=function(){var a,b=p.length,c=q.length,e=h[0],f=h[1],g;for(a=0;a<b;++a)g=p[a],isNaN(g.x)&&(g.x=Math.random()*e),isNaN(g.y)&&(g.y=Math.random()*f),isNaN(g.px)&&(g.px=g.x),isNaN(g.py)&&(g.py=g.y);for(a=0;a<c;++a)g=q[a],typeof g.source=="number"&&(g.source=p[g.source]),typeof g.target=="number"&&(g.target=p[g.target]);return d.resume()},d.resume=function(){i=.1,d3.timer(u);return d},d.stop=function(){i=0;return d},d.drag=function(){this.on("mouseover",c).on("mouseout",e).on("mousedown",f),d3.select(window).on("mousemove",v).on("mouseup",w);return d};return d};var a,b;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function c(c){var d=c.length,e=c[0].length,f,i,j,k=g[a](c);h[b](c,k);for(i=0;i<e;++i)for(f=1,j=c[k[0]][i].y0;f<d;++f)c[k[f]][i].y0=j+=c[k[f-1]][i].y;return c}var a="default",b="zero";c.order=function(b){if(!arguments.length)return a;a=b;return c},c.offset=function(a){if(!arguments.length)return b;b=a;return c};return c};var g={"inside-out":function(a){var b=a.length,c,d,e=a.map(j),f=a.map(i),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,k=0,l=[],m=[];for(c=0;c<b;c++)d=g[c],h<k?(h+=f[d],l.push(d)):(k+=f[d],m.push(d));return m.reverse().concat(l)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},h={silhouette:function(a,b){var c=a.length,d=a[0].length,e=[],f=0,g,h,i;for(h=0;h<d;++h){for(g=0,i=0;g<c;g++)i+=a[g][h].y;i>f&&(f=i),e.push(i)}for(h=0,g=b[0];h<d;++h)a[g][h].y0=(f-e[h])/2},wiggle:function(a,b){var c=a.length,d=a[0],e=d.length,f=0,g,h,i,j,k,l=b[0],m,n,o,p,q,r;a[l][0].y0=q=r=0;for(h=1;h<e;++h){for(g=0,m=0;g<c;++g)m+=a[g][h].y;for(g=0,n=0,p=d[h].x-d[h-1].x;g<c;++g){for(i=0,j=b[g],o=(a[j][h].y-a[j][h-1].y)/(2*p);i<g;++i)o+=(a[k=b[i]][h].y-a[k][h-1].y)/p;n+=o*a[j][h].y}a[l][h].y0=q-=m?n/m*p:0,q<r&&(r=q)}for(h=0;h<e;++h)a[l][h].y0-=r},zero:function(a,b){var c=0,d=a[0].length,e=b[0];for(;c<d;++c)a[e][c].y0=0}};d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=n,b=l,c=m;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,v(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);w(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(o)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;K(g,function(a){a.children?(a.x=z(a.children),a.y=y(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=A(g),m=B(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;K(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=D,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=C,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=F(g),e=E(e),g&&e)h=E(h),f=F(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(M(N(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!F(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!E(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;L(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];K(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=G(g,I),l=G(g,H),m=G(g,J),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;K(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=D,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=C,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})()
<ide>\ No newline at end of file
<ide><path>src/layout/force.js
<ide> d3.layout.force = function() {
<ide>
<ide> function dragmove() {
<ide> if (!d3_layout_forceDragNode) return;
<add>
<add> // O NOES! The drag element was removed from the DOM.
<add> if (!d3_layout_forceDragElement.parentNode) {
<add> d3_layout_forceDragNode.fixed = false;
<add> d3_layout_forceDragNode = d3_layout_forceDragElement = null;
<add> return;
<add> }
<add>
<ide> var m = d3.svg.mouse(d3_layout_forceDragElement);
<ide> d3_layout_forceDragNode.px = m[0];
<ide> d3_layout_forceDragNode.py = m[1]; | 3 |
PHP | PHP | apply fixes from styleci | a7a0c65b3d2ee1eae68d3d7e749ba41aba7caa72 | <ide><path>src/Illuminate/Cache/DynamoDbLock.php
<ide>
<ide> namespace Illuminate\Cache;
<ide>
<del>use Illuminate\Cache\Lock;
<del>use Aws\DynamoDb\DynamoDbClient;
<del>
<ide> class DynamoDbLock extends Lock
<ide> {
<ide> /**
<ide><path>src/Illuminate/Cache/DynamoDbStore.php
<ide> public function many(array $keys)
<ide> 'Keys' => collect($keys)->map(function ($key) {
<ide> return [
<ide> $this->keyAttribute => [
<del> 'S' => $key
<del> ]
<add> 'S' => $key,
<add> ],
<ide> ];
<del> })->all()
<add> })->all(),
<ide> ],
<ide> ],
<ide> ]);
<ide> public function forget($key)
<ide> */
<ide> public function flush()
<ide> {
<del> throw new RuntimeException("DynamoDb does not support flushing an entire table. Please create a new table.");
<add> throw new RuntimeException('DynamoDb does not support flushing an entire table. Please create a new table.');
<ide> }
<ide>
<ide> /**
<ide><path>tests/Integration/Cache/DynamoDbStoreTest.php
<ide>
<ide> namespace Illuminate\Tests\Integration\Cache;
<ide>
<del>use Memcached;
<ide> use Illuminate\Support\Str;
<del>use Illuminate\Support\Carbon;
<ide> use Orchestra\Testbench\TestCase;
<ide> use Illuminate\Support\Facades\Cache;
<ide> | 3 |
Javascript | Javascript | add headers prop in source array type prop | ddc2210eba0376231b4bdb1c9259ef46241f9442 | <ide><path>Libraries/Image/Image.android.js
<ide> var Image = createReactClass({
<ide> uri: PropTypes.string,
<ide> width: PropTypes.number,
<ide> height: PropTypes.number,
<add> headers: PropTypes.objectOf(PropTypes.string),
<ide> }))
<ide> ]),
<ide> /** | 1 |
Java | Java | respect existing content-length for http head | b86c11cc9b00693fc3446724ffd37ae379189b7f | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/HttpHeadResponseDecorator.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<add>import org.springframework.http.HttpHeaders;
<ide>
<ide> /**
<ide> * {@link ServerHttpResponse} decorator for HTTP HEAD requests.
<ide> public final Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
<ide> DataBufferUtils.release(buffer);
<ide> return next;
<ide> })
<del> .doOnNext(count -> getHeaders().setContentLength(count))
<add> .doOnNext(length -> {
<add> if (length > 0 || getHeaders().getFirst(HttpHeaders.CONTENT_LENGTH) == null) {
<add> getHeaders().setContentLength(length);
<add> }
<add> })
<ide> .then();
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/HttpHeadResponseDecoratorTests.java
<add>/*
<add> * Copyright 2002-2019 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.http.server.reactive;
<add>
<add>import java.nio.charset.StandardCharsets;
<add>
<add>import io.netty.buffer.PooledByteBufAllocator;
<add>import org.junit.After;
<add>import org.junit.Test;
<add>import reactor.core.publisher.Flux;
<add>
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.LeakAwareDataBufferFactory;
<add>import org.springframework.core.io.buffer.NettyDataBufferFactory;
<add>import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>
<add>/**
<add> * Unit tests for {@link HttpHeadResponseDecorator}.
<add> * @author Rossen Stoyanchev
<add> */
<add>public class HttpHeadResponseDecoratorTests {
<add>
<add> private final LeakAwareDataBufferFactory bufferFactory =
<add> new LeakAwareDataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT));
<add>
<add> private final ServerHttpResponse response =
<add> new HttpHeadResponseDecorator(new MockServerHttpResponse(this.bufferFactory));
<add>
<add>
<add> @After
<add> public void tearDown() {
<add> this.bufferFactory.checkForLeaks();
<add> }
<add>
<add>
<add> @Test
<add> public void write() {
<add> Flux<DataBuffer> body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2"));
<add> response.writeWith(body).block();
<add> assertEquals(10, response.getHeaders().getContentLength());
<add> }
<add>
<add> @Test // gh-23484
<add> public void writeWithGivenContentLength() {
<add> int length = 15;
<add> this.response.getHeaders().setContentLength(length);
<add> this.response.writeWith(Flux.empty()).block();
<add> assertEquals(length, this.response.getHeaders().getContentLength());
<add> }
<add>
<add>
<add> private DataBuffer toDataBuffer(String s) {
<add> DataBuffer buffer = this.bufferFactory.allocateBuffer();
<add> buffer.write(s.getBytes(StandardCharsets.UTF_8));
<add> return buffer;
<add> }
<add>
<add>} | 2 |
PHP | PHP | show route collision in routes command | 12bf3db07f77479e89132337e107518f9872d7e6 | <ide><path>src/Command/RoutesCommand.php
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> $header[] = 'Defaults';
<ide> }
<ide>
<del> $output = [];
<add> $output = $duplicateRoutesCounter = [];
<ide>
<ide> foreach (Router::routes() as $route) {
<ide> $methods = $route->defaults['_method'] ?? '';
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> }
<ide>
<ide> $output[] = $item;
<add>
<add> // Count route templates
<add> if (!array_key_exists($route->template, $duplicateRoutesCounter)) {
<add> $duplicateRoutesCounter[$route->template] = 0;
<add> }
<add> $duplicateRoutesCounter[$route->template]++;
<ide> }
<ide>
<ide> if ($args->getOption('sort')) {
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> $io->helper('table')->output($output);
<ide> $io->out();
<ide>
<add> $duplicateRoutes = [];
<add>
<add> // Check duplicate routes
<add> foreach (Router::routes() as $route) {
<add> if ($duplicateRoutesCounter[$route->template] > 1) {
<add> $methods = $route->defaults['_method'] ?? '';
<add>
<add> $duplicateRoutes[] = [
<add> $route->options['_name'] ?? $route->getName(),
<add> $route->template,
<add> $route->defaults['plugin'] ?? '',
<add> $route->defaults['prefix'] ?? '',
<add> $route->defaults['controller'] ?? '',
<add> $route->defaults['action'] ?? '',
<add> is_string($methods) ? $methods : implode(', ', $route->defaults['_method']),
<add> ];
<add> }
<add> }
<add>
<add> if (!empty($duplicateRoutes)) {
<add> array_unshift($duplicateRoutes, $header);
<add> $io->warning('The following route collisions were being detected');
<add> $io->helper('table')->output($duplicateRoutes);
<add> $io->out();
<add> }
<add>
<ide> return static::CODE_SUCCESS;
<ide> }
<ide>
<ide><path>tests/TestCase/Command/RoutesCommandTest.php
<ide> public function testGenerateMissing(): void
<ide> $this->assertExitCode(Command::CODE_ERROR);
<ide> $this->assertErrorContains('do not match');
<ide> }
<add>
<add> /**
<add> * Test routes duplicate warning
<add> */
<add> public function testRouteDuplicateWarning(): void
<add> {
<add> $builder = Router::createRouteBuilder('/');
<add> $builder->connect(
<add> new Route('/unique-path', [], ['_name' => '_aRoute'])
<add> );
<add> $builder->connect(
<add> new Route('/unique-path', [], ['_name' => '_bRoute'])
<add> );
<add>
<add> $this->exec('routes');
<add> $this->assertExitCode(Command::CODE_SUCCESS);
<add> $this->assertOutputContainsRow([
<add> '<info>Route name</info>',
<add> '<info>URI template</info>',
<add> '<info>Plugin</info>',
<add> '<info>Prefix</info>',
<add> '<info>Controller</info>',
<add> '<info>Action</info>',
<add> '<info>Method(s)</info>',
<add> ]);
<add> $this->assertOutputContainsRow([
<add> '_aRoute',
<add> '/unique-path',
<add> '',
<add> '',
<add> '',
<add> '',
<add> '',
<add> ]);
<add> $this->assertOutputContainsRow([
<add> '_bRoute',
<add> '/unique-path',
<add> '',
<add> '',
<add> '',
<add> '',
<add> '',
<add> ]);
<add> }
<ide> } | 2 |
Text | Text | add mention of e2fsprogs to runtime dependencies | 91502ba66bfc2a3edafb2ddf7f27393250bfa459 | <ide><path>hack/PACKAGERS.md
<ide> installed and available at runtime:
<ide>
<ide> * iptables version 1.4 or later
<ide> * procps (or similar provider of a "ps" executable)
<add>* e2fsprogs version 1.4.12 or later (in use: mkfs.ext4, mkfs.xfs, tune2fs)
<ide> * XZ Utils version 4.9 or later
<ide> * a [properly
<ide> mounted](https://github.com/tianon/cgroupfs-mount/blob/master/cgroupfs-mount) | 1 |
Ruby | Ruby | fix secure_password setter | 692b3b6b6a565a27b968db8027daabcc766cfede | <ide><path>activemodel/lib/active_model/secure_password.rb
<ide> def authenticate(unencrypted_password)
<ide>
<ide> # Encrypts the password into the password_digest attribute.
<ide> def password=(unencrypted_password)
<del> @password = unencrypted_password
<ide> unless unencrypted_password.blank?
<add> @password = unencrypted_password
<ide> self.password_digest = BCrypt::Password.create(unencrypted_password)
<ide> end
<ide> end
<ide><path>activemodel/test/cases/secure_password_test.rb
<ide> class SecurePasswordTest < ActiveModel::TestCase
<ide> assert !@user.valid?, 'user should be invalid'
<ide> end
<ide>
<add> test "blank password doesn't override previous password" do
<add> @user.password = 'test'
<add> @user.password = ''
<add> assert_equal @user.password, 'test'
<add> end
<add>
<ide> test "password must be present" do
<ide> assert !@user.valid?
<ide> assert_equal 1, @user.errors.size | 2 |
Ruby | Ruby | send people to new issue wiki page | 1e71489d5176ffe40dfb10c002438f962c7464f3 | <ide><path>Library/Homebrew/brew.h.rb
<ide> FORMULA_META_FILES = %w[README README.md ChangeLog COPYING LICENSE LICENCE COPYRIGHT AUTHORS]
<del>PLEASE_REPORT_BUG = "#{Tty.white}Please report this bug at #{Tty.em}http://github.com/mxcl/homebrew/issues#{Tty.reset}"
<add>PLEASE_REPORT_BUG = "#{Tty.white}Please follow the instructions to report this bug at #{Tty.em}https://github.com/mxcl/homebrew/wiki/new-issue#{Tty.reset}"
<ide>
<ide> def check_for_blacklisted_formula names
<ide> return if ARGV.force? | 1 |
PHP | PHP | fix trailing newline | 335db95ba880b61099cf26a83a70adf29c16b04d | <ide><path>tests/TestCase/BasicsTest.php
<ide> public function testEventManagerReset2($prevEventManager)
<ide> $this->assertInstanceOf(EventManager::class, $prevEventManager);
<ide> $this->assertNotSame($prevEventManager, EventManager::instance());
<ide> }
<del>
<ide> } | 1 |
Python | Python | add japan to linode driver | b0d540e471fecb171f52897c388f308612dceec8 | <ide><path>libcloud/compute/drivers/linode.py
<ide> def list_locations(self):
<ide> country = None
<ide> if "USA" in dc["LOCATION"]: country = "US"
<ide> elif "UK" in dc["LOCATION"]: country = "GB"
<add> elif "JP" in dc["LOCATION"]: country = "JP"
<ide> else: country = "??"
<ide> nl.append(NodeLocation(dc["DATACENTERID"],
<ide> dc["LOCATION"], | 1 |
Python | Python | support env var for num build jobs | 78a84f0d78630a6a2849bb95f7dabfad4a513aea | <ide><path>setup.py
<ide> def build_options(self):
<ide>
<ide> class build_ext_subclass(build_ext, build_ext_options):
<ide> def build_extensions(self):
<add> if not self.parallel:
<add> self.parallel = int(os.environ.get("SPACY_NUM_BUILD_JOBS", 1))
<ide> build_ext_options.build_options(self)
<ide> build_ext.build_extensions(self)
<ide> | 1 |
Java | Java | add tosingle method to observable | cb9d1eb676c22aedf89dd99879a6df724d2aaaa4 | <ide><path>src/main/java/rx/Observable.java
<ide> public <R> Observable<R> compose(Transformer<? super T, ? extends R> transformer
<ide> public interface Transformer<T, R> extends Func1<Observable<T>, Observable<R>> {
<ide> // cover for generics insanity
<ide> }
<del>
<del>
<add>
<add> /**
<add> * Returns a Single that emits the single item emitted by the source Observable, if that Observable
<add> * emits only a single item. If the source Observable emits more than one item or no items, notify of an
<add> * {@code IllegalArgumentException} or {@code NoSuchElementException} respectively.
<add> * <p>
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code toSingle} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @return a Single that emits the single item emitted by the source Observable
<add> * @throws IllegalArgumentException
<add> * if the source observable emits more than one item
<add> * @throws NoSuchElementException
<add> * if the source observable emits no items
<add> */
<add> @Experimental
<add> public Single<T> toSingle() {
<add> return new Single<T>(OnSubscribeSingle.create(this));
<add> }
<add>
<ide>
<ide> /* *********************************************************************************************************
<ide> * Operators Below Here
<ide><path>src/main/java/rx/internal/operators/OnSubscribeSingle.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package rx.internal.operators;
<add>
<add>import rx.Observable;
<add>import rx.Single;
<add>import rx.SingleSubscriber;
<add>import rx.Subscriber;
<add>
<add>import java.util.NoSuchElementException;
<add>
<add>/**
<add> * Allows conversion of an Observable to a Single ensuring that exactly one item is emitted - no more and no less.
<add> * Also forwards errors as appropriate.
<add> */
<add>public class OnSubscribeSingle<T> implements Single.OnSubscribe<T> {
<add>
<add> private final Observable<T> observable;
<add>
<add> public OnSubscribeSingle(Observable<T> observable) {
<add> this.observable = observable;
<add> }
<add>
<add> @Override
<add> public void call(final SingleSubscriber<? super T> child) {
<add> Subscriber<T> parent = new Subscriber<T>() {
<add> private boolean emittedTooMany = false;
<add> private boolean itemEmitted = false;
<add> private T emission = null;
<add>
<add> @Override
<add> public void onStart() {
<add> // We request 2 here since we need 1 for the single and 1 to check that the observable
<add> // doesn't emit more than one item
<add> request(2);
<add> }
<add>
<add> @Override
<add> public void onCompleted() {
<add> if (emittedTooMany) {
<add> // Don't need to do anything here since we already sent an error downstream
<add> } else {
<add> if (itemEmitted) {
<add> child.onSuccess(emission);
<add> } else {
<add> child.onError(new NoSuchElementException("Observable emitted no items"));
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> child.onError(e);
<add> unsubscribe();
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> if (itemEmitted) {
<add> emittedTooMany = true;
<add> child.onError(new IllegalArgumentException("Observable emitted too many elements"));
<add> unsubscribe();
<add> } else {
<add> itemEmitted = true;
<add> emission = t;
<add> }
<add> }
<add> };
<add> child.add(parent);
<add> observable.subscribe(parent);
<add> }
<add>
<add> public static <T> OnSubscribeSingle<T> create(Observable<T> observable) {
<add> return new OnSubscribeSingle<T>(observable);
<add> }
<add>}
<ide><path>src/test/java/rx/internal/operators/OnSubscribeSingleTest.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package rx.internal.operators;
<add>
<add>import org.junit.Test;
<add>import rx.Observable;
<add>import rx.Single;
<add>import rx.observers.TestSubscriber;
<add>
<add>import java.util.Collections;
<add>import java.util.NoSuchElementException;
<add>
<add>public class OnSubscribeSingleTest {
<add>
<add> @Test
<add> public void testJustSingleItemObservable() {
<add> TestSubscriber<String> subscriber = TestSubscriber.create();
<add> Single<String> single = Observable.just("Hello World!").toSingle();
<add> single.subscribe(subscriber);
<add>
<add> subscriber.assertReceivedOnNext(Collections.singletonList("Hello World!"));
<add> }
<add>
<add> @Test
<add> public void testErrorObservable() {
<add> TestSubscriber<String> subscriber = TestSubscriber.create();
<add> IllegalArgumentException error = new IllegalArgumentException("Error");
<add> Single<String> single = Observable.<String>error(error).toSingle();
<add> single.subscribe(subscriber);
<add>
<add> subscriber.assertError(error);
<add> }
<add>
<add> @Test
<add> public void testJustTwoEmissionsObservableThrowsError() {
<add> TestSubscriber<String> subscriber = TestSubscriber.create();
<add> Single<String> single = Observable.just("First", "Second").toSingle();
<add> single.subscribe(subscriber);
<add>
<add> subscriber.assertError(IllegalArgumentException.class);
<add> }
<add>
<add> @Test
<add> public void testEmptyObservable() {
<add> TestSubscriber<String> subscriber = TestSubscriber.create();
<add> Single<String> single = Observable.<String>empty().toSingle();
<add> single.subscribe(subscriber);
<add>
<add> subscriber.assertError(NoSuchElementException.class);
<add> }
<add>
<add> @Test
<add> public void testRepeatObservableThrowsError() {
<add> TestSubscriber<String> subscriber = TestSubscriber.create();
<add> Single<String> single = Observable.just("First", "Second").repeat().toSingle();
<add> single.subscribe(subscriber);
<add>
<add> subscriber.assertError(IllegalArgumentException.class);
<add> }
<add>} | 3 |
Go | Go | add libdevmapper wrapper | 739af0a17f6a5a9956bbc9fd1e81e4d40bff8167 | <ide><path>devmapper/devmapper.go
<add>package devmapper
<add>
<add>/*
<add>#cgo LDFLAGS: -L. -ldevmapper
<add>#include <stdio.h>
<add>#include <stdlib.h>
<add>#include <unistd.h>
<add>#include <libdevmapper.h>
<add>#include <linux/loop.h>
<add>#include <sys/types.h>
<add>#include <sys/stat.h>
<add>#include <fcntl.h>
<add>#include <sys/ioctl.h>
<add>#include <linux/fs.h>
<add>#include <errno.h>
<add>
<add>static char *
<add>attach_loop_device(const char *filename, int *loop_fd_out)
<add>{
<add> struct loop_info64 loopinfo = { 0 };
<add> struct stat st;
<add> char buf[64];
<add> int i, loop_fd, fd, start_index;
<add> char *loopname;
<add>
<add> *loop_fd_out = -1;
<add>
<add> start_index = 0;
<add> fd = open("/dev/loop-control", O_RDONLY);
<add> if (fd == 0) {
<add> start_index = ioctl(fd, LOOP_CTL_GET_FREE);
<add> close(fd);
<add>
<add> if (start_index < 0)
<add> start_index = 0;
<add> }
<add>
<add> fd = open(filename, O_RDWR);
<add> if (fd < 0) {
<add> return NULL;
<add> }
<add>
<add> loop_fd = -1;
<add> for (i = start_index ; loop_fd < 0 ; i++ ) {
<add> if (sprintf(buf, "/dev/loop%d", i) < 0) {
<add> close(fd);
<add> return NULL;
<add> }
<add>
<add> if (stat(buf, &st) || !S_ISBLK(st.st_mode)) {
<add> close(fd);
<add> return NULL;
<add> }
<add>
<add> loop_fd = open(buf, O_RDWR);
<add> if (loop_fd < 0 && errno == ENOENT) {
<add> close(fd);
<add> fprintf (stderr, "no available loopback device!");
<add> return NULL;
<add> } else if (loop_fd < 0)
<add> continue;
<add>
<add> if (ioctl (loop_fd, LOOP_SET_FD, (void *)(size_t)fd) < 0) {
<add> close(loop_fd);
<add> loop_fd = -1;
<add> if (errno != EBUSY) {
<add> close (fd);
<add> fprintf (stderr, "cannot set up loopback device %s", buf);
<add> return NULL;
<add> }
<add> continue;
<add> }
<add>
<add> close (fd);
<add>
<add> strncpy((char*)loopinfo.lo_file_name, buf, LO_NAME_SIZE);
<add> loopinfo.lo_offset = 0;
<add> loopinfo.lo_flags = LO_FLAGS_AUTOCLEAR;
<add>
<add> if (ioctl(loop_fd, LOOP_SET_STATUS64, &loopinfo) < 0) {
<add> ioctl(loop_fd, LOOP_CLR_FD, 0);
<add> close(loop_fd);
<add> fprintf (stderr, "cannot set up loopback device info");
<add> return NULL;
<add> }
<add>
<add> loopname = strdup(buf);
<add> if (loopname == NULL) {
<add> close(loop_fd);
<add> return NULL;
<add> }
<add>
<add> *loop_fd_out = loop_fd;
<add> return loopname;
<add> }
<add> return NULL;
<add>}
<add>
<add>static int64_t
<add>get_block_size(int fd)
<add>{
<add> uint64_t size;
<add> if (ioctl(fd, BLKGETSIZE64, &size) == -1)
<add> return -1;
<add> return (int64_t)size;
<add>}
<add>
<add>
<add>*/
<add>import "C"
<add>import "unsafe"
<add>import "fmt"
<add>import "runtime"
<add>import "os"
<add>
<add>func SetDevDir(dir string) error {
<add> c_dir := C.CString(dir)
<add> defer C.free(unsafe.Pointer(c_dir))
<add> res := C.dm_set_dev_dir(c_dir)
<add> if res != 1 {
<add> return fmt.Errorf("dm_set_dev_dir failed")
<add> }
<add> return nil
<add>}
<add>
<add>func GetLibraryVersion() (string, error) {
<add> buffer := (*C.char)(C.malloc(128))
<add> defer C.free(unsafe.Pointer(buffer))
<add> res := C.dm_get_library_version(buffer, 128)
<add> if res != 1 {
<add> return "", fmt.Errorf("dm_get_library_version failed")
<add> } else {
<add> return C.GoString(buffer), nil
<add> }
<add>}
<add>
<add>type TaskType int
<add>
<add>const (
<add> DeviceCreate TaskType = iota
<add> DeviceReload
<add> DeviceRemove
<add> DeviceRemoveAll
<add> DeviceSuspend
<add> DeviceResume
<add> DeviceInfo
<add> DeviceDeps
<add> DeviceRename
<add> DeviceVersion
<add> DeviceStatus
<add> DeviceTable
<add> DeviceWaitevent
<add> DeviceList
<add> DeviceClear
<add> DeviceMknodes
<add> DeviceListVersions
<add> DeviceTargetMsg
<add> DeviceSetGeometry
<add>)
<add>
<add>type Task struct {
<add> unmanaged *C.struct_dm_task
<add>}
<add>
<add>type Info struct {
<add> Exists int
<add> Suspended int
<add> LiveTable int
<add> InactiveTable int
<add> OpenCount int32
<add> EventNr uint32
<add> Major uint32
<add> Minor uint32
<add> ReadOnly int
<add> TargetCount int32
<add>}
<add>
<add>func (t *Task) destroy() {
<add> if t != nil {
<add> C.dm_task_destroy(t.unmanaged)
<add> runtime.SetFinalizer(t, nil)
<add> }
<add>}
<add>
<add>func TaskCreate(tasktype TaskType) *Task {
<add> c_task := C.dm_task_create(C.int(int(tasktype)))
<add> if c_task == nil {
<add> return nil
<add> }
<add> task := &Task{c_task}
<add> runtime.SetFinalizer(task, (*Task).destroy)
<add> return task
<add>}
<add>
<add>func (t *Task) Run() error {
<add> res := C.dm_task_run(t.unmanaged)
<add> if res != 1 {
<add> return fmt.Errorf("dm_task_run failed")
<add> }
<add> return nil
<add>}
<add>
<add>func (t *Task) SetName(name string) error {
<add> c_name := C.CString(name)
<add> defer C.free(unsafe.Pointer(c_name))
<add>
<add> res := C.dm_task_set_name(t.unmanaged, c_name)
<add> if res != 1 {
<add> return fmt.Errorf("dm_task_set_name failed")
<add> }
<add> return nil
<add>}
<add>
<add>func (t *Task) SetMessage(message string) error {
<add> c_message := C.CString(message)
<add> defer C.free(unsafe.Pointer(c_message))
<add>
<add> res := C.dm_task_set_message(t.unmanaged, c_message)
<add> if res != 1 {
<add> return fmt.Errorf("dm_task_set_message failed")
<add> }
<add> return nil
<add>}
<add>
<add>func (t *Task) SetSector(sector uint64) error {
<add> res := C.dm_task_set_sector(t.unmanaged, C.uint64_t(sector))
<add> if res != 1 {
<add> return fmt.Errorf("dm_task_set_add_node failed")
<add> }
<add> return nil
<add>}
<add>
<add>func (t *Task) SetCookie(cookie *uint32, flags uint16) error {
<add> var c_cookie C.uint32_t
<add> c_cookie = C.uint32_t(*cookie)
<add> res := C.dm_task_set_cookie(t.unmanaged, &c_cookie, C.uint16_t(flags))
<add> if res != 1 {
<add> return fmt.Errorf("dm_task_set_add_node failed")
<add> }
<add> *cookie = uint32(c_cookie)
<add> return nil
<add>}
<add>
<add>func (t *Task) SetRo() error {
<add> res := C.dm_task_set_ro(t.unmanaged)
<add> if res != 1 {
<add> return fmt.Errorf("dm_task_set_ro failed")
<add> }
<add> return nil
<add>}
<add>
<add>func (t *Task) AddTarget(start uint64, size uint64, ttype string, params string) error {
<add> c_ttype := C.CString(ttype)
<add> defer C.free(unsafe.Pointer(c_ttype))
<add>
<add> c_params := C.CString(params)
<add> defer C.free(unsafe.Pointer(c_params))
<add>
<add> res := C.dm_task_add_target(t.unmanaged, C.uint64_t(start), C.uint64_t(size), c_ttype, c_params)
<add> if res != 1 {
<add> return fmt.Errorf("dm_task_add_target failed")
<add> }
<add> return nil
<add>}
<add>
<add>func (t *Task) GetDriverVersion() (string, error) {
<add> buffer := (*C.char)(C.malloc(128))
<add> defer C.free(unsafe.Pointer(buffer))
<add>
<add> res := C.dm_task_get_driver_version(t.unmanaged, buffer, 128)
<add> if res != 1 {
<add> return "", fmt.Errorf("dm_task_get_driver_version")
<add> } else {
<add> return C.GoString(buffer), nil
<add> }
<add>}
<add>
<add>func (t *Task) GetInfo() (*Info, error) {
<add> c_info := C.struct_dm_info{}
<add> res := C.dm_task_get_info(t.unmanaged, &c_info)
<add> if res != 1 {
<add> return nil, fmt.Errorf("dm_task_get_driver_version")
<add> } else {
<add> info := &Info{}
<add> info.Exists = int(c_info.exists)
<add> info.Suspended = int(c_info.suspended)
<add> info.LiveTable = int(c_info.live_table)
<add> info.InactiveTable = int(c_info.inactive_table)
<add> info.OpenCount = int32(c_info.open_count)
<add> info.EventNr = uint32(c_info.event_nr)
<add> info.Major = uint32(c_info.major)
<add> info.Minor = uint32(c_info.minor)
<add> info.ReadOnly = int(c_info.read_only)
<add> info.TargetCount = int32(c_info.target_count)
<add>
<add> return info, nil
<add> }
<add>}
<add>
<add>func (t *Task) GetNextTarget(next uintptr) (uintptr, uint64, uint64, string, string) {
<add> nextp := unsafe.Pointer(next)
<add> var c_start C.uint64_t
<add> var c_length C.uint64_t
<add> var c_target_type *C.char
<add> var c_params *C.char
<add>
<add> nextp = C.dm_get_next_target(t.unmanaged, nextp, &c_start, &c_length, &c_target_type, &c_params)
<add>
<add> target_type := C.GoString(c_target_type)
<add> params := C.GoString(c_params)
<add>
<add> return uintptr(nextp), uint64(c_start), uint64(c_length), target_type, params
<add>}
<add>
<add>func AttachLoopDevice(filename string) (*os.File, error) {
<add> c_filename := C.CString(filename)
<add> defer C.free(unsafe.Pointer(c_filename))
<add>
<add> var fd C.int
<add> res := C.attach_loop_device(c_filename, &fd)
<add> if res == nil {
<add> return nil, fmt.Errorf("error loopback mounting")
<add> }
<add> file := os.NewFile(uintptr(fd), C.GoString(res))
<add> C.free(unsafe.Pointer(res))
<add> return file, nil
<add>}
<add>
<add>func GetBlockDeviceSize(file *os.File) (uint64, error) {
<add> fd := file.Fd()
<add> size := C.get_block_size(C.int(fd))
<add> if size == -1 {
<add> return 0, fmt.Errorf("Can't get block size")
<add> }
<add> return uint64(size), nil
<add>
<add>}
<add>
<add>func UdevWait(cookie uint32) error {
<add> res := C.dm_udev_wait(C.uint32_t(cookie))
<add> if res != 1 {
<add> return fmt.Errorf("Failed to wait on udev cookie %d", cookie)
<add> }
<add> return nil
<add>}
<add>
<add>func LogInitVerbose(level int) {
<add> C.dm_log_init_verbose(C.int(level))
<add>} | 1 |
Javascript | Javascript | hide legacy tiers | f1ddec3f9bb5766bfeb88956adda238923d5212e | <ide><path>client/src/components/Donation/components/DonateServicebotEmbed.js
<ide> export class DonationServicebotEmbed extends Component {
<ide> cancel_now: true,
<ide> disableCoupon: true,
<ide> forceCard: true,
<del> disableTiers: [
<del> 'Monthly $10 Donation - Unavailable',
<del> 'Monthly $3 Donation - Unavailable'
<add> hideTiers: [
<add> 'Monthly $3 Donation - Unavailable',
<add> 'Monthly $10 Donation - Unavailable'
<ide> ],
<ide> card: {
<ide> hideName: true, | 1 |
Javascript | Javascript | add test for transition.select | 80fa16a35114620956ddb902f4294f8f36e136db | <ide><path>test/core/transition-test-select.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var assert = require("assert");
<add>
<add>module.exports = {
<add> topic: function() {
<add> var s = d3.select("body").append("div").selectAll("div")
<add> .data(["one", "two", "three", "four"])
<add> .enter().append("div")
<add> .attr("class", String);
<add>
<add> s.filter(function(d, i) { return i > 0; }).append("span");
<add> s[0][3] = null;
<add>
<add> return s.transition()
<add> .delay(function(d, i) { return i * 13; })
<add> .duration(function(d, i) { return i * 21; });
<add> },
<add>
<add> "selects the first matching element": function(transition) {
<add> var t = transition.select("span");
<add> assert.domEqual(t[0][1].node.parentNode, transition[0][1].node);
<add> assert.domEqual(t[0][2].node.parentNode, transition[0][2].node);
<add> },
<add> "ignores null elements": function(transition) {
<add> var t = transition.select("span");
<add> assert.isNull(t[0][3]);
<add> },
<add> "propagates data to the selected elements": function(transition) {
<add> var t = transition.select("span");
<add> assert.equal(t[0][1].node.__data__, "two");
<add> assert.equal(t[0][2].node.__data__, "three");
<add> },
<add> "propagates delay to the selected elements": function(transition) {
<add> var t = transition.select("span");
<add> assert.equal(t[0][1].delay, 13);
<add> assert.equal(t[0][2].delay, 26);
<add> },
<add> "propagates duration to the selected elements": function(transition) {
<add> var t = transition.select("span");
<add> assert.equal(t[0][1].duration, 21);
<add> assert.equal(t[0][2].duration, 42);
<add> },
<add> "does not propagate data if no data was specified": function(transition) {
<add> delete transition[0][1].node.__data__;
<add> delete transition[0][1].node.firstChild.__data__;
<add> var t = transition.select("span");
<add> assert.isUndefined(t[0][1].node.__data__);
<add> assert.equal(t[0][2].node.__data__, "three");
<add> },
<add> "returns null if no match is found": function(transition) {
<add> var t = transition.select("span");
<add> assert.isNull(t[0][0]);
<add> }
<add>};
<ide><path>test/core/transition-test.js
<ide> var suite = vows.describe("transition");
<ide> suite.addBatch({
<ide>
<ide> // Subtransitions
<del> // select
<add> "select": require("./transition-test-select"),
<ide> // selectAll
<ide>
<ide> // Content | 2 |
Python | Python | add lookup properties for components in language | 939e8ed567c41af87cb264fe768d7dc5f45bf8f2 | <ide><path>spacy/language.py
<ide> def __init__(self, vocab=True, make_doc=True, pipeline=None, meta={}, **kwargs):
<ide> flat_list.append(pipe)
<ide> self.pipeline = flat_list
<ide>
<add> # Conveniences to access pipeline components
<add> @property
<add> def tensorizer(self):
<add> return self.get_component('tensorizer')
<add>
<add> @property
<add> def tagger(self):
<add> return self.get_component('tagger')
<add>
<add> @property
<add> def parser(self):
<add> return self.get_component('parser')
<add>
<add> @property
<add> def entity(self):
<add> return self.get_component('ner')
<add>
<add> @property
<add> def matcher(self):
<add> return self.get_component('matcher')
<add>
<add> def get_component(self, name):
<add> if self.pipeline in (True, None):
<add> return None
<add> for proc in self.pipeline:
<add> if hasattr(proc, 'name') and proc.name.endswith(name):
<add> return proc
<add> return None
<add>
<ide> def __call__(self, text, disable=[]):
<ide> """'Apply the pipeline to some text. The text can span multiple sentences,
<ide> and can contain arbtrary whitespace. Alignment into the original string | 1 |
Ruby | Ruby | remove prepend_and_append requirement from as | af0582968dfb400375bbef6ace7166aac1041f3d | <ide><path>activerecord/lib/active_record/validations/uniqueness.rb
<del>require 'active_support/core_ext/array/prepend_and_append'
<del>
<ide> module ActiveRecord
<ide> module Validations
<ide> class UniquenessValidator < ActiveModel::EachValidator # :nodoc:
<ide> def find_finder_class_for(record) #:nodoc:
<ide> class_hierarchy = [record.class]
<ide>
<ide> while class_hierarchy.first != @klass
<del> class_hierarchy.prepend(class_hierarchy.first.superclass)
<add> class_hierarchy.unshift(class_hierarchy.first.superclass)
<ide> end
<ide>
<ide> class_hierarchy.detect { |klass| !klass.abstract_class? } | 1 |
Mixed | Ruby | update actioncable docs [ci skip] | 4858c9fa2d02f0244eda01aa20ac703bfeabc3fe | <ide><path>actioncable/lib/action_cable/channel/streams.rb
<ide> module Channel
<ide> #
<ide> # An example broadcasting for this channel looks like so:
<ide> #
<del> # ActionCable.server.broadcast "comments_for_45", author: 'DHH', content: 'Rails is just swell'
<add> # ActionCable.server.broadcast "comments_for_45", { author: 'DHH', content: 'Rails is just swell' }
<ide> #
<ide> # If you have a stream that is related to a model, then the broadcasting used can be generated from the model and channel.
<ide> # The following example would subscribe to a broadcasting like <tt>comments:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE</tt>.
<ide><path>guides/source/action_cable_overview.md
<ide> Then, elsewhere in your Rails application, you can broadcast to such a room by
<ide> calling [`broadcast`][]:
<ide>
<ide> ```ruby
<del>ActionCable.server.broadcast("chat_Best Room", body: "This Room is Best Room.")
<add>ActionCable.server.broadcast("chat_Best Room", { body: "This Room is Best Room." })
<ide> ```
<ide>
<ide> If you have a stream that is related to a model, then the broadcasting name
<ide> consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
<ide> # from a NewCommentJob.
<ide> ActionCable.server.broadcast(
<ide> "chat_#{room}",
<del> sent_by: 'Paul',
<del> body: 'This is a cool chat app.'
<add> {
<add> sent_by: 'Paul',
<add> body: 'This is a cool chat app.'
<add> }
<ide> )
<ide> ```
<ide> | 2 |
Java | Java | add velocity to onscrollenddrag event | 076eaec8053952c87cdc257f5c85466749c18260 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/OnScrollDispatchHelper.java
<ide> public class OnScrollDispatchHelper {
<ide>
<ide> private int mPrevX = Integer.MIN_VALUE;
<ide> private int mPrevY = Integer.MIN_VALUE;
<del> private float mXFlingVelocity = 0;
<del> private float mYFlingVelocity = 0;
<del>
<ide> private long mLastScrollEventTimeMs = -(MIN_EVENT_SEPARATION_MS + 1);
<ide>
<del> private static final float THRESHOLD = 0.1f; // Threshold for end fling
<del>
<ide> /**
<ide> * Call from a ScrollView in onScrollChanged, returns true if this onScrollChanged is legit (not a
<ide> * duplicate) and should be dispatched.
<ide> public boolean onScrollChanged(int x, int y) {
<ide> mPrevX != x ||
<ide> mPrevY != y;
<ide>
<del> // Skip the first calculation in each scroll
<del> if (Math.abs(mXFlingVelocity) < THRESHOLD && Math.abs(mYFlingVelocity) < THRESHOLD) {
<del> shouldDispatch = false;
<del> }
<del>
<del> if (eventTime - mLastScrollEventTimeMs != 0) {
<del> mXFlingVelocity = (float) (x - mPrevX) / (eventTime - mLastScrollEventTimeMs);
<del> mYFlingVelocity = (float) (y - mPrevY) / (eventTime - mLastScrollEventTimeMs);
<del> }
<del>
<ide> mLastScrollEventTimeMs = eventTime;
<ide> mPrevX = x;
<ide> mPrevY = y;
<ide>
<ide> return shouldDispatch;
<ide> }
<del>
<del> public float getXFlingVelocity() {
<del> return this.mXFlingVelocity;
<del> }
<del>
<del> public float getYFlingVelocity() {
<del> return this.mYFlingVelocity;
<del> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java
<ide> public class ReactHorizontalScrollView extends HorizontalScrollView implements
<ide> ReactClippingViewGroup {
<ide>
<ide> private final OnScrollDispatchHelper mOnScrollDispatchHelper = new OnScrollDispatchHelper();
<del> private final VelocityHelper mVelocityHelper = new VelocityHelper();
<ide>
<ide> private boolean mActivelyScrolling;
<ide> private @Nullable Rect mClippingRect;
<ide> protected void onScrollChanged(int x, int y, int oldX, int oldY) {
<ide>
<ide> mActivelyScrolling = true;
<ide>
<del> ReactScrollViewHelper.emitScrollEvent(
<del> this,
<del> mOnScrollDispatchHelper.getXFlingVelocity(),
<del> mOnScrollDispatchHelper.getYFlingVelocity());
<add> ReactScrollViewHelper.emitScrollEvent(this);
<ide> }
<ide> }
<ide>
<ide> public boolean onTouchEvent(MotionEvent ev) {
<ide> return false;
<ide> }
<ide>
<del> mVelocityHelper.calculateVelocity(ev);
<ide> int action = ev.getAction() & MotionEvent.ACTION_MASK;
<ide> if (action == MotionEvent.ACTION_UP && mDragging) {
<del> ReactScrollViewHelper.emitScrollEndDragEvent(
<del> this,
<del> mVelocityHelper.getXVelocity(),
<del> mVelocityHelper.getYVelocity());
<add> ReactScrollViewHelper.emitScrollEndDragEvent(this);
<ide> mDragging = false;
<ide> // After the touch finishes, we may need to do some scrolling afterwards either as a result
<ide> // of a fling or because we need to page align the content
<ide> handlePostTouchScrolling();
<ide> }
<del>
<ide> return super.onTouchEvent(ev);
<ide> }
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java
<ide> public class ReactScrollView extends ScrollView implements ReactClippingViewGrou
<ide>
<ide> private final OnScrollDispatchHelper mOnScrollDispatchHelper = new OnScrollDispatchHelper();
<ide> private final OverScroller mScroller;
<del> private final VelocityHelper mVelocityHelper = new VelocityHelper();
<ide>
<ide> private @Nullable Rect mClippingRect;
<ide> private boolean mDoneFlinging;
<ide> protected void onScrollChanged(int x, int y, int oldX, int oldY) {
<ide> mDoneFlinging = false;
<ide> }
<ide>
<del> ReactScrollViewHelper.emitScrollEvent(
<del> this,
<del> mOnScrollDispatchHelper.getXFlingVelocity(),
<del> mOnScrollDispatchHelper.getYFlingVelocity());
<add> ReactScrollViewHelper.emitScrollEvent(this);
<ide> }
<ide> }
<ide>
<ide> public boolean onTouchEvent(MotionEvent ev) {
<ide> return false;
<ide> }
<ide>
<del> mVelocityHelper.calculateVelocity(ev);
<ide> int action = ev.getAction() & MotionEvent.ACTION_MASK;
<ide> if (action == MotionEvent.ACTION_UP && mDragging) {
<del> ReactScrollViewHelper.emitScrollEndDragEvent(
<del> this,
<del> mVelocityHelper.getXVelocity(),
<del> mVelocityHelper.getYVelocity());
<add> ReactScrollViewHelper.emitScrollEndDragEvent(this);
<ide> mDragging = false;
<ide> disableFpsListener();
<ide> }
<del>
<ide> return super.onTouchEvent(ev);
<ide> }
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java
<ide> public class ReactScrollViewHelper {
<ide> /**
<ide> * Shared by {@link ReactScrollView} and {@link ReactHorizontalScrollView}.
<ide> */
<del> public static void emitScrollEvent(ViewGroup scrollView, float xVelocity, float yVelocity) {
<del> emitScrollEvent(scrollView, ScrollEventType.SCROLL, xVelocity, yVelocity);
<add> public static void emitScrollEvent(ViewGroup scrollView) {
<add> emitScrollEvent(scrollView, ScrollEventType.SCROLL);
<ide> }
<ide>
<ide> public static void emitScrollBeginDragEvent(ViewGroup scrollView) {
<ide> emitScrollEvent(scrollView, ScrollEventType.BEGIN_DRAG);
<ide> }
<ide>
<del> public static void emitScrollEndDragEvent(
<del> ViewGroup scrollView,
<del> float xVelocity,
<del> float yVelocity) {
<del> emitScrollEvent(scrollView, ScrollEventType.END_DRAG, xVelocity, yVelocity);
<add> public static void emitScrollEndDragEvent(ViewGroup scrollView) {
<add> emitScrollEvent(scrollView, ScrollEventType.END_DRAG);
<ide> }
<ide>
<ide> public static void emitScrollMomentumBeginEvent(ViewGroup scrollView) {
<ide> public static void emitScrollMomentumEndEvent(ViewGroup scrollView) {
<ide> }
<ide>
<ide> private static void emitScrollEvent(ViewGroup scrollView, ScrollEventType scrollEventType) {
<del> emitScrollEvent(scrollView, scrollEventType, 0, 0);
<del> }
<del>
<del> private static void emitScrollEvent(
<del> ViewGroup scrollView,
<del> ScrollEventType scrollEventType,
<del> float xVelocity,
<del> float yVelocity) {
<ide> View contentView = scrollView.getChildAt(0);
<ide>
<ide> if (contentView == null) {
<ide> private static void emitScrollEvent(
<ide> scrollEventType,
<ide> scrollView.getScrollX(),
<ide> scrollView.getScrollY(),
<del> xVelocity,
<del> yVelocity,
<ide> contentView.getWidth(),
<ide> contentView.getHeight(),
<ide> scrollView.getWidth(),
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEvent.java
<ide> public class ScrollEvent extends Event<ScrollEvent> {
<ide>
<ide> private int mScrollX;
<ide> private int mScrollY;
<del> private double mXVelocity;
<del> private double mYVelocity;
<ide> private int mContentWidth;
<ide> private int mContentHeight;
<ide> private int mScrollViewWidth;
<ide> public static ScrollEvent obtain(
<ide> ScrollEventType scrollEventType,
<ide> int scrollX,
<ide> int scrollY,
<del> float xVelocity,
<del> float yVelocity,
<ide> int contentWidth,
<ide> int contentHeight,
<ide> int scrollViewWidth,
<ide> public static ScrollEvent obtain(
<ide> scrollEventType,
<ide> scrollX,
<ide> scrollY,
<del> xVelocity,
<del> yVelocity,
<ide> contentWidth,
<ide> contentHeight,
<ide> scrollViewWidth,
<ide> private void init(
<ide> ScrollEventType scrollEventType,
<ide> int scrollX,
<ide> int scrollY,
<del> float xVelocity,
<del> float yVelocity,
<ide> int contentWidth,
<ide> int contentHeight,
<ide> int scrollViewWidth,
<ide> private void init(
<ide> mScrollEventType = scrollEventType;
<ide> mScrollX = scrollX;
<ide> mScrollY = scrollY;
<del> mXVelocity = xVelocity;
<del> mYVelocity = yVelocity;
<ide> mContentWidth = contentWidth;
<ide> mContentHeight = contentHeight;
<ide> mScrollViewWidth = scrollViewWidth;
<ide> private WritableMap serializeEventData() {
<ide> layoutMeasurement.putDouble("width", PixelUtil.toDIPFromPixel(mScrollViewWidth));
<ide> layoutMeasurement.putDouble("height", PixelUtil.toDIPFromPixel(mScrollViewHeight));
<ide>
<del> WritableMap velocity = Arguments.createMap();
<del> velocity.putDouble("x", mXVelocity);
<del> velocity.putDouble("y", mYVelocity);
<del>
<ide> WritableMap event = Arguments.createMap();
<ide> event.putMap("contentInset", contentInset);
<ide> event.putMap("contentOffset", contentOffset);
<ide> event.putMap("contentSize", contentSize);
<ide> event.putMap("layoutMeasurement", layoutMeasurement);
<del> event.putMap("velocity", velocity);
<ide>
<ide> event.putInt("target", getViewTag());
<ide> event.putBoolean("responderIgnoreScroll", true);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/VelocityHelper.java
<del>/**
<del> * Copyright (c) 2017-present, Facebook, Inc.
<del> * All rights reserved.
<del> *
<del> * This source code is licensed under the BSD-style license found in the
<del> * LICENSE file in the root directory of this source tree. An additional grant
<del> * of patent rights can be found in the PATENTS file in the same directory.
<del> */
<del>
<del>package com.facebook.react.views.scroll;
<del>
<del>import javax.annotation.Nullable;
<del>
<del>import android.view.MotionEvent;
<del>import android.view.VelocityTracker;
<del>
<del>/**
<del> * This Class helps to calculate the velocity for all ScrollView. The x and y velocity
<del> * will later on send to ReactScrollViewHelper for further use.
<del> *
<del> * Created by wenjiam on 6/20/17.
<del> */
<del>public class VelocityHelper {
<del>
<del> private @Nullable VelocityTracker mVelocityTracker;
<del> private float mXVelocity;
<del> private float mYVelocity;
<del>
<del> /**
<del> * Call from a ScrollView in onTouchEvent.
<del> * Calculating the velocity for END_DRAG movement and send them back to react ScrollResponder.js
<del> * */
<del> public void calculateVelocity(MotionEvent ev) {
<del> int action = ev.getAction() & MotionEvent.ACTION_MASK;
<del> if (mVelocityTracker == null) {
<del> mVelocityTracker = mVelocityTracker.obtain();
<del> }
<del>
<del> switch (action) {
<del> case MotionEvent.ACTION_MOVE: {
<del> mVelocityTracker.addMovement(ev);
<del> break;
<del> }
<del> case MotionEvent.ACTION_UP:
<del> case MotionEvent.ACTION_CANCEL: {
<del> // Calculate velocity on END_DRAG
<del> mVelocityTracker.computeCurrentVelocity(1); // points/millisecond
<del> mXVelocity = mVelocityTracker.getXVelocity();
<del> mYVelocity = mVelocityTracker.getYVelocity();
<del>
<del> mVelocityTracker.recycle();
<del> break;
<del> }
<del> }
<del> }
<del>
<del> /* Needs to call ACTION_UP/CANCEL to update the mXVelocity */
<del> public float getXVelocity() { return mXVelocity; }
<del>
<del> /* Needs to call ACTION_UP/CANCEL to update the mYVelocity */
<del> public float getYVelocity() { return mYVelocity; }
<del>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java
<ide> public void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) {
<ide> ScrollEventType.SCROLL,
<ide> horiz,
<ide> vert,
<del> 0f, // can't get x velocity
<del> 0f, // can't get y velocity
<ide> 0, // can't get content width
<ide> 0, // can't get content height
<ide> mReactEditText.getWidth(),
<del> mReactEditText.getHeight());
<add> mReactEditText.getHeight()
<add> );
<ide>
<ide> mEventDispatcher.dispatchEvent(event);
<ide> | 7 |
Ruby | Ruby | prevent some double diagostic failures | 9686ebe3550fda62e867ebd7b51ffdd8bb5e7822 | <ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb
<ide> def check_if_supported_sdk_available
<ide> locator = MacOS.sdk_locator
<ide>
<ide> source = if locator.source == :clt
<add> return if MacOS::CLT.below_minimum_version? # Handled by other diagnostics.
<add>
<ide> update_instructions = MacOS::CLT.update_instructions
<ide> "Command Line Tools (CLT)"
<ide> else
<add> return if MacOS::Xcode.below_minimum_version? # Handled by other diagnostics.
<add>
<ide> update_instructions = MacOS::Xcode.update_instructions
<ide> "Xcode"
<ide> end
<ide><path>Library/Homebrew/test/os/mac/diagnostic_spec.rb
<ide> before do
<ide> allow(DevelopmentTools).to receive(:installed?).and_return(true)
<ide> allow(OS::Mac).to receive(:version).and_return(macos_version)
<add> allow(OS::Mac::CLT).to receive(:below_minimum_version?).and_return(false)
<add> allow(OS::Mac::Xcode).to receive(:below_minimum_version?).and_return(false)
<ide> end
<ide>
<ide> it "doesn't trigger when SDK root is not needed" do | 2 |
Python | Python | remove useless override of self.style | 679627660fef3c7a9f7be743a168930e4a0e58ae | <ide><path>django/core/management/commands/migrate.py
<ide> from django.conf import settings
<ide> from django.core.management import call_command
<ide> from django.core.management.base import BaseCommand, CommandError
<del>from django.core.management.color import color_style, no_style
<add>from django.core.management.color import no_style
<ide> from django.core.management.sql import custom_sql_for_model, emit_post_migrate_signal, emit_pre_migrate_signal
<ide> from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS
<ide> from django.db.migrations.executor import MigrationExecutor
<ide> def handle(self, *args, **options):
<ide> self.load_initial_data = options.get('load_initial_data')
<ide> self.test_database = options.get('test_database', False)
<ide>
<del> self.style = color_style()
<del>
<ide> # Import the 'management' module within each installed app, to register
<ide> # dispatcher events.
<ide> for app_name in settings.INSTALLED_APPS: | 1 |
Javascript | Javascript | add test for module._stat | 37b8a603f886634416046e337936e4c586f4ff58 | <ide><path>test/parallel/test-module-stat.js
<add>'use strict';
<add>require('../common');
<add>
<add>// This tests Module._stat.
<add>
<add>const Module = require('module');
<add>const fs = require('fs');
<add>const tmpdir = require('../common/tmpdir');
<add>const { ok, strictEqual } = require('assert');
<add>const { join } = require('path');
<add>
<add>const directory = join(tmpdir.path, 'directory');
<add>const doesNotExist = join(tmpdir.path, 'does-not-exist');
<add>const file = join(tmpdir.path, 'file.js');
<add>
<add>tmpdir.refresh();
<add>fs.writeFileSync(file, "module.exports = { a: 'b' }");
<add>fs.mkdirSync(directory);
<add>
<add>strictEqual(Module._stat(directory), 1); // Returns 1 for directories.
<add>strictEqual(Module._stat(file), 0); // Returns 0 for files.
<add>ok(Module._stat(doesNotExist) < 0); // Returns a negative integer for any other kind of strings.
<add>
<add>// TODO(RaisinTen): Add tests that make sure that Module._stat() does not crash when called
<add>// with a non-string data type. It crashes currently.
<ide><path>test/parallel/test-vfs.js
<add>'use strict';
<add>const common = require('../common');
<add>
<add>// This tests the creation of a vfs by monkey-patching fs and Module._stat.
<add>
<add>const Module = require('module');
<add>const fs = require('fs');
<add>const tmpdir = require('../common/tmpdir');
<add>const { deepStrictEqual, ok, strictEqual, throws } = require('assert');
<add>const { join } = require('path');
<add>
<add>const directory = join(tmpdir.path, 'directory');
<add>const doesNotExist = join(tmpdir.path, 'does-not-exist');
<add>const file = join(tmpdir.path, 'file.js');
<add>
<add>tmpdir.refresh();
<add>fs.writeFileSync(file, "module.exports = { a: 'b' }");
<add>fs.mkdirSync(directory);
<add>
<add>strictEqual(Module._stat(directory), 1);
<add>ok(Module._stat(doesNotExist) < 0);
<add>strictEqual(Module._stat(file), 0);
<add>
<add>const vfsDirectory = join(process.execPath, 'directory');
<add>const vfsDoesNotExist = join(process.execPath, 'does-not-exist');
<add>const vfsFile = join(process.execPath, 'file.js');
<add>
<add>ok(Module._stat(vfsDirectory) < 0);
<add>ok(Module._stat(vfsDoesNotExist) < 0);
<add>ok(Module._stat(vfsFile) < 0);
<add>
<add>deepStrictEqual(require(file), { a: 'b' });
<add>throws(() => require(vfsFile), { code: 'MODULE_NOT_FOUND' });
<add>
<add>common.expectWarning(
<add> 'ExperimentalWarning',
<add> 'Module._stat is an experimental feature. This feature could change at any time');
<add>
<add>process.on('warning', common.mustCall());
<add>
<add>const originalStat = Module._stat;
<add>Module._stat = function(filename) {
<add> if (!filename.startsWith(process.execPath)) {
<add> return originalStat(filename);
<add> }
<add>
<add> if (filename === process.execPath) {
<add> return 1;
<add> }
<add>
<add> switch (filename) {
<add> case vfsDirectory:
<add> return 1;
<add> case vfsDoesNotExist:
<add> return -2;
<add> case vfsFile:
<add> return 0;
<add> }
<add>};
<add>
<add>const originalReadFileSync = fs.readFileSync;
<add>// TODO(aduh95): We'd like to have a better way to achieve this without monkey-patching fs.
<add>fs.readFileSync = function readFileSync(pathArgument, options) {
<add> if (!pathArgument.startsWith(process.execPath)) {
<add> return originalReadFileSync.apply(this, arguments);
<add> }
<add> if (pathArgument === vfsFile) {
<add> return "module.exports = { x: 'y' };";
<add> }
<add> throw new Error();
<add>};
<add>
<add>fs.realpathSync = function realpathSync(pathArgument, options) {
<add> return pathArgument;
<add>};
<add>
<add>strictEqual(Module._stat(directory), 1);
<add>ok(Module._stat(doesNotExist) < 0);
<add>strictEqual(Module._stat(file), 0);
<add>
<add>strictEqual(Module._stat(vfsDirectory), 1);
<add>ok(Module._stat(vfsDoesNotExist) < 0);
<add>strictEqual(Module._stat(vfsFile), 0);
<add>
<add>strictEqual(Module._stat(process.execPath), 1);
<add>
<add>deepStrictEqual(require(file), { a: 'b' });
<add>deepStrictEqual(require(vfsFile), { x: 'y' }); | 2 |
Text | Text | add link to women techmakers | dd2df85e77ca6b83246120502ade6e08d44f5b56 | <ide><path>guide/english/working-in-tech/women-in-tech/index.md
<ide> The worst thing you can do is to sell yourself short if you want something take
<ide> - [Rails Girls](http://railsgirls.com/)
<ide> - [Girls Who Code](https://girlswhocode.com/)
<ide> - [1 Million Women To Tech](https://1millionwomentotech.com/)
<add>- [Women Techmakers](https://www.womentechmakers.com/)
<ide> - [Women Who Code](https://www.womenwhocode.com/)
<ide> | 1 |
Python | Python | fix title in about.py | bbd2a3dee1e01bb063fd26a4d98914cca27a9581 | <ide><path>spacy/about.py
<ide> # https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
<ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
<ide>
<del>__title__ = 'spacy-nightly'
<del>__version__ = '2.0.0rc2'
<add>__title__ = 'spacy'
<add>__version__ = '2.0.0'
<ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
<ide> __uri__ = 'https://spacy.io'
<ide> __author__ = 'Explosion AI' | 1 |
Text | Text | fix description of middleware | 768a893d6419887a897b788ed7a540e51fb536d3 | <ide><path>docs/advanced/Middleware.md
<ide>
<ide> If you've used server-side libraries like [Express](http://expressjs.com/) and [Koa](http://koajs.com/), you are familiar with the concept of *middleware*. In these frameworks, middleware is some code you can put between the framework receiving a request, and framework generating a response. For example, Express or Koa middleware may add CORS headers, logging, compression, and more. The best feature of middleware is that it’s composable in a chain. You can use multiple independent third-party middleware in a single project.
<ide>
<del>Redux middleware solves different problems than Express or Koa middleware, but in a conceptually similar way. **It provides a third-party extension point between dispatching an action, and the moment it reaches the store.** People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.
<add>Redux middleware solves different problems than Express or Koa middleware, but in a conceptually similar way. **It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer.** People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.
<ide>
<ide> This article is divided into an in-depth intro to help you grok the concept, and [a few practical examples](#seven-examples) to show the power of middleware at the very end. You may find it helpful to switch back and forth between them, as you flip between feeling bored and inspired.
<ide> | 1 |
PHP | PHP | use elvis operators instead | 06e222adef11d1c177eed599a6f9fa46378dbe05 | <ide><path>src/Console/ConsoleIo.php
<ide> class ConsoleIo
<ide> */
<ide> public function __construct(ConsoleOutput $out = null, ConsoleOutput $err = null, ConsoleInput $in = null, HelperRegistry $helpers = null)
<ide> {
<del> $this->_out = $out ? $out : new ConsoleOutput('php://stdout');
<del> $this->_err = $err ? $err : new ConsoleOutput('php://stderr');
<del> $this->_in = $in ? $in : new ConsoleInput('php://stdin');
<del> $this->_helpers = $helpers ? $helpers : new HelperRegistry();
<add> $this->_out = $out ?: new ConsoleOutput('php://stdout');
<add> $this->_err = $err ?: new ConsoleOutput('php://stderr');
<add> $this->_in = $in ?: new ConsoleInput('php://stdin');
<add> $this->_helpers = $helpers ?: new HelperRegistry();
<ide> $this->_helpers->setIo($this);
<ide> }
<ide>
<ide><path>src/Core/functions.php
<ide> function h($text, $double = true, $charset = null)
<ide> $charset = $double;
<ide> }
<ide>
<del> return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, ($charset) ? $charset : $defaultCharset, $double);
<add> return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, $charset ?: $defaultCharset, $double);
<ide> }
<ide>
<ide> }
<ide><path>src/Database/Schema/PostgresSchema.php
<ide> public function convertColumnDescription(TableSchema $schema, $row)
<ide>
<ide> if ($field['type'] === 'numeric' || $field['type'] === 'decimal') {
<ide> $field['length'] = $row['column_precision'];
<del> $field['precision'] = $row['column_scale'] ? $row['column_scale'] : null;
<add> $field['precision'] = $row['column_scale'] ?: null;
<ide> }
<ide> $schema->addColumn($row['name'], $field);
<ide> } | 3 |
PHP | PHP | add unique modifier | dcf971805df5e5cb86b03ced4240c5bbbe516164 | <ide><path>database/factories/ModelFactory.php
<ide>
<ide> return [
<ide> 'name' => $faker->name,
<del> 'email' => $faker->safeEmail,
<add> 'email' => $faker->unique()->safeEmail,
<ide> 'password' => $password ?: $password = bcrypt('secret'),
<ide> 'remember_token' => str_random(10),
<ide> ]; | 1 |
Python | Python | update theano backend | 9c93d8ec0681521bffd903eab9bba1a6c42a1bd8 | <ide><path>keras/backend/theano_backend.py
<ide> def _step(input, *states):
<ide> def switch(condition, then_expression, else_expression):
<ide> """condition: scalar tensor.
<ide> """
<add> if callable(then_expression):
<add> then_expression = then_expression()
<add> if callable(else_expression):
<add> else_expression = else_expression()
<ide> return T.switch(condition, then_expression, else_expression)
<ide>
<ide>
<ide> def in_train_phase(x, alt):
<ide> return x
<ide> elif _LEARNING_PHASE is 0:
<ide> return alt
<add> if callable(x):
<add> x = x()
<add> if callable(alt):
<add> alt = alt()
<ide> x = theano.ifelse.ifelse(_LEARNING_PHASE, x, alt)
<ide> x._uses_learning_phase = True
<ide> return x
<ide> def in_test_phase(x, alt):
<ide> return alt
<ide> elif _LEARNING_PHASE is 0:
<ide> return x
<add> if callable(x):
<add> x = x()
<add> if callable(alt):
<add> alt = alt()
<ide> x = theano.ifelse.ifelse(_LEARNING_PHASE, alt, x)
<ide> x._uses_learning_phase = True
<ide> return x
<ide> def dropout(x, level, noise_shape=None, seed=None):
<ide> raise ValueError('Dropout level must be in interval [0, 1[.')
<ide> if seed is None:
<ide> seed = np.random.randint(1, 10e6)
<add> if isinstance(noise_shape, list):
<add> noise_shape = tuple(noise_shape)
<ide>
<ide> rng = RandomStreams(seed=seed)
<ide> retain_prob = 1. - level
<ide> def dropout(x, level, noise_shape=None, seed=None):
<ide> random_tensor = rng.binomial(x.shape, p=retain_prob, dtype=x.dtype)
<ide> else:
<ide> random_tensor = rng.binomial(noise_shape, p=retain_prob, dtype=x.dtype)
<del> random_tensor = T.patternbroadcast(random_tensor, [dim == 1 for dim in noise_shape])
<del>
<add> random_tensor = T.patternbroadcast(random_tensor,
<add> [dim == 1 for dim in noise_shape])
<ide> x *= random_tensor
<ide> x /= retain_prob
<ide> return x | 1 |
Javascript | Javascript | add xmlns to svg wrap | c9fab582c48c43ba81e266ede714abf1e2ef3740 | <ide><path>src/shared/vendor/core/getMarkupWrap.js
<ide> var selectWrap = [1, '<select multiple="true">', '</select>'];
<ide> var tableWrap = [1, '<table>', '</table>'];
<ide> var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
<ide>
<del>var svgWrap = [1, '<svg>', '</svg>'];
<add>var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>'];
<ide>
<ide> var markupWrap = {
<ide> '*': [1, '?<div>', '</div>'], | 1 |
PHP | PHP | remove unneeded "use" statements | c83e6428d14c5faac5d9d3ff159908999bb75801 | <ide><path>src/Http/Client/Request.php
<ide> */
<ide> namespace Cake\Http\Client;
<ide>
<del>use Cake\Core\Exception\Exception;
<ide> use Psr\Http\Message\RequestInterface;
<ide> use Zend\Diactoros\RequestTrait;
<ide> use Zend\Diactoros\Stream;
<ide><path>src/Http/Response.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Filesystem\File;
<del>use Cake\Filesystem\Folder;
<ide> use Cake\Http\Cookie\Cookie;
<ide> use Cake\Http\Cookie\CookieCollection;
<ide> use Cake\Http\Cookie\CookieInterface;
<ide> use Cake\Http\CorsBuilder;
<ide> use Cake\Http\Exception\NotFoundException;
<del>use Cake\Log\Log;
<ide> use DateTime;
<ide> use DateTimeZone;
<ide> use InvalidArgumentException;
<ide><path>src/ORM/Query.php
<ide> use Cake\Database\ValueBinder;
<ide> use Cake\Datasource\QueryInterface;
<ide> use Cake\Datasource\QueryTrait;
<del>use InvalidArgumentException;
<ide> use JsonSerializable;
<ide> use RuntimeException;
<ide>
<ide><path>src/TestSuite/Constraint/Response/CookieEncryptedEquals.php
<ide>
<ide> use Cake\Http\Response;
<ide> use Cake\Utility\CookieCryptTrait;
<del>use InvalidArgumentException;
<ide>
<ide> /**
<ide> * CookieEncryptedEquals
<ide><path>src/TestSuite/IntegrationTestCase.php
<ide> */
<ide> namespace Cake\TestSuite;
<ide>
<del>use Cake\Core\Configure;
<del>use Cake\Database\Exception as DatabaseException;
<del>use Cake\Http\ServerRequest;
<del>use Cake\Http\Session;
<del>use Cake\Routing\Router;
<del>use Cake\TestSuite\Stub\TestExceptionRenderer;
<del>use Cake\Utility\CookieCryptTrait;
<del>use Cake\Utility\Hash;
<del>use Cake\Utility\Security;
<del>use Cake\Utility\Text;
<del>use Cake\View\Helper\SecureFieldTokenTrait;
<del>use Exception;
<del>use LogicException;
<del>use PHPUnit\Exception as PhpunitException;
<ide>
<ide> /**
<ide> * A test case class intended to make integration tests of
<ide><path>src/View/Form/ArrayContext.php
<ide>
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Utility\Hash;
<del>use Cake\Validation\Validator;
<ide>
<ide> /**
<ide> * Provides a basic array based context provider for FormHelper.
<ide><path>src/View/View.php
<ide> use Cake\Routing\Router;
<ide> use Cake\Utility\Inflector;
<ide> use Cake\View\Exception\MissingElementException;
<del>use Cake\View\Exception\MissingHelperException;
<ide> use Cake\View\Exception\MissingLayoutException;
<ide> use Cake\View\Exception\MissingTemplateException;
<ide> use InvalidArgumentException;
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> use Cake\Database\Log\LoggingStatement;
<ide> use Cake\Database\Log\QueryLogger;
<ide> use Cake\Database\StatementInterface;
<del>use Cake\Database\Statement\BufferedStatement;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\Log\Log;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/Http/BaseApplicationTest.php
<ide> use Cake\Http\ServerRequestFactory;
<ide> use Cake\Routing\RouteBuilder;
<ide> use Cake\Routing\RouteCollection;
<del>use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> use InvalidArgumentException;
<ide> use TestPlugin\Plugin as TestPlugin;
<ide><path>tests/TestCase/Http/Client/RequestTest.php
<ide>
<ide> use Cake\Http\Client\Request;
<ide> use Cake\TestSuite\TestCase;
<del>use Zend\Diactoros\Uri;
<ide>
<ide> /**
<ide> * HTTP request test. | 10 |
Javascript | Javascript | extract docs during static site generation | 11707d5ce2473c0f8f101ca56e5a69f2557896e6 | <ide><path>website/server/convert.js
<ide> function buildFile(layout, metadata, rawContent) {
<ide> }
<ide>
<ide> function execute(options) {
<add> if (options === undefined) {
<add> options = {};
<add> }
<add>
<ide> var DOCS_MD_DIR = '../docs/';
<ide> var BLOG_MD_DIR = '../blog/';
<ide>
<ide><path>website/server/generate.js
<ide> var mkdirp = require('mkdirp');
<ide> var server = require('./server.js');
<ide> var Feed = require('feed');
<ide>
<del>require('./convert.js')();
<add>require('./convert.js')({extractDocs: true});
<ide> server.noconvert = true;
<ide>
<ide> // Sadly, our setup fatals when doing multiple concurrent requests | 2 |
Javascript | Javascript | normalize context creation for option resolution | 8d36927b290bfe28b2ecb7393ccf5c0a473fd08a | <ide><path>src/controllers/controller.bubble.js
<ide> export default class BubbleController extends DatasetController {
<ide> resolveDataElementOptions(index, mode) {
<ide> const me = this;
<ide> const chart = me.chart;
<del> const dataset = me.getDataset();
<ide> const parsed = me.getParsed(index);
<ide> let values = super.resolveDataElementOptions(index, mode);
<ide>
<ide> // Scriptable options
<del> const context = {
<del> chart,
<del> dataPoint: parsed,
<del> dataIndex: index,
<del> dataset,
<del> datasetIndex: me.index
<del> };
<add> const context = me.getContext(index, mode === 'active');
<ide>
<ide> // In case values were cached (and thus frozen), we need to clone the values
<ide> if (values.$shared) {
<ide><path>src/controllers/controller.polarArea.js
<ide> export default class PolarAreaController extends DatasetController {
<ide> me._cachedMeta.count = me.countVisibleElements();
<ide>
<ide> for (i = 0; i < start; ++i) {
<del> angle += me._computeAngle(i);
<add> angle += me._computeAngle(i, mode);
<ide> }
<ide> for (i = start; i < start + count; i++) {
<ide> const arc = arcs[i];
<ide> let startAngle = angle;
<del> let endAngle = angle + me._computeAngle(i);
<add> let endAngle = angle + me._computeAngle(i, mode);
<ide> let outerRadius = this.chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(dataset.data[i]) : 0;
<ide> angle = endAngle;
<ide>
<ide> export default class PolarAreaController extends DatasetController {
<ide> /**
<ide> * @private
<ide> */
<del> _computeAngle(index) {
<add> _computeAngle(index, mode) {
<ide> const me = this;
<ide> const meta = me._cachedMeta;
<ide> const count = meta.count;
<ide> export default class PolarAreaController extends DatasetController {
<ide> }
<ide>
<ide> // Scriptable options
<del> const context = {
<del> chart: me.chart,
<del> dataPoint: this.getParsed(index),
<del> dataIndex: index,
<del> dataset,
<del> datasetIndex: me.index
<del> };
<add> const context = me.getContext(index, mode === 'active');
<ide>
<ide> return resolve([
<ide> me.chart.options.elements.arc.angle,
<ide><path>src/core/core.datasetController.js
<ide> export default class DatasetController {
<ide> }
<ide>
<ide> /**
<del> * @private
<add> * @protected
<ide> */
<del> _getContext(index, active) {
<add> getContext(index, active) {
<ide> return {
<ide> chart: this.chart,
<ide> dataPoint: this.getParsed(index),
<ide> export default class DatasetController {
<ide> const datasetOpts = me._config;
<ide> const options = me.chart.options.elements[type] || {};
<ide> const values = {};
<del> const context = me._getContext(index, active);
<add> const context = me.getContext(index, active);
<ide> const keys = optionKeys(optionNames);
<ide>
<ide> for (let i = 0, ilen = keys.length; i < ilen; ++i) {
<ide> export default class DatasetController {
<ide> }
<ide>
<ide> const info = {cacheable: true};
<del> const context = me._getContext(index, active);
<add> const context = me.getContext(index, active);
<ide> const chartAnim = resolve([chart.options.animation], context, index, info);
<ide> const datasetAnim = resolve([me._config.animation], context, index, info);
<ide> let config = chartAnim && mergeIf({}, [datasetAnim, chartAnim]);
<ide><path>src/core/core.scale.js
<ide> export default class Scale extends Element {
<ide> 0;
<ide> }
<ide>
<add> /**
<add> * @protected
<add> */
<add> getContext(index) {
<add> const ticks = this.ticks || [];
<add> return {
<add> chart: this.chart,
<add> scale: this,
<add> tick: ticks[index],
<add> index
<add> };
<add> }
<add>
<ide> /**
<ide> * Returns a subset of ticks to be plotted to avoid overlapping labels.
<ide> * @param {Tick[]} ticks
<ide> export default class Scale extends Element {
<ide> const tl = getTickMarkLength(gridLines);
<ide> const items = [];
<ide>
<del> let context = {
<del> chart,
<del> scale: me,
<del> tick: ticks[0],
<del> index: 0,
<del> };
<add> let context = this.getContext(0);
<ide> const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0;
<ide> const axisHalfWidth = axisWidth / 2;
<ide> const alignBorderValue = function(pixel) {
<ide> export default class Scale extends Element {
<ide> }
<ide>
<ide> for (i = 0; i < ticksLength; ++i) {
<del> /** @type {Tick|object} */
<del> const tick = ticks[i] || {};
<del>
<del> context = {
<del> chart,
<del> scale: me,
<del> tick,
<del> index: i,
<del> };
<add> context = this.getContext(i);
<ide>
<ide> const lineWidth = resolve([gridLines.lineWidth], context, i);
<ide> const lineColor = resolve([gridLines.color], context, i);
<ide> export default class Scale extends Element {
<ide> const gridLines = me.options.gridLines;
<ide> const ctx = me.ctx;
<ide> const chart = me.chart;
<del> let context = {
<del> chart,
<del> scale: me,
<del> tick: me.ticks[0],
<del> index: 0,
<del> };
<add> let context = me.getContext(0);
<ide> const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0;
<ide> const items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
<ide> let i, ilen;
<ide> export default class Scale extends Element {
<ide> if (axisWidth) {
<ide> // Draw the line at the edge of the axis
<ide> const firstLineWidth = axisWidth;
<del> context = {
<del> chart,
<del> scale: me,
<del> tick: me.ticks[me._ticksLength - 1],
<del> index: me._ticksLength - 1,
<del> };
<add> context = me.getContext(me._ticksLength - 1);
<ide> const lastLineWidth = resolve([gridLines.lineWidth, 1], context, me._ticksLength - 1);
<ide> const borderValue = me._borderValue;
<ide> let x1, x2, y1, y2;
<ide> export default class Scale extends Element {
<ide> const me = this;
<ide> const chart = me.chart;
<ide> const options = me.options.ticks;
<del> const ticks = me.ticks || [];
<del> const context = {
<del> chart,
<del> scale: me,
<del> tick: ticks[index],
<del> index
<del> };
<add> const context = me.getContext(index);
<ide> return toFont(resolve([options.font], context), chart.options.font);
<ide> }
<ide> }
<ide><path>src/scales/scale.radialLinear.js
<ide> function fitWithPointLabels(scale) {
<ide> for (i = 0; i < valueCount; i++) {
<ide> pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
<ide>
<del> const context = {
<del> chart: scale.chart,
<del> scale,
<del> index: i,
<del> label: scale.pointLabels[i]
<del> };
<add> const context = scale.getContext(i);
<ide> const plFont = toFont(resolve([scale.options.pointLabels.font], context, i), scale.chart.options.font);
<ide> scale.ctx.font = plFont.string;
<ide> textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
<ide> function drawPointLabels(scale) {
<ide> const extra = (i === 0 ? tickBackdropHeight / 2 : 0);
<ide> const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
<ide>
<del> const context = {
<del> chart: scale.chart,
<del> scale,
<del> index: i,
<del> label: scale.pointLabels[i],
<del> };
<add> const context = scale.getContext(i);
<ide> const plFont = toFont(resolve([pointLabelOpts.font], context, i), scale.chart.options.font);
<ide> ctx.font = plFont.string;
<ide> ctx.fillStyle = plFont.color;
<ide> function drawRadiusLine(scale, gridLineOpts, radius, index) {
<ide> const circular = gridLineOpts.circular;
<ide> const valueCount = scale.chart.data.labels.length;
<ide>
<del> const context = {
<del> chart: scale.chart,
<del> scale,
<del> index,
<del> tick: scale.ticks[index],
<del> };
<add> const context = scale.getContext(index);
<ide> const lineColor = resolve([gridLineOpts.color], context, index - 1);
<ide> const lineWidth = resolve([gridLineOpts.lineWidth], context, index - 1);
<ide> let pointPosition;
<ide> export default class RadialLinearScale extends LinearScaleBase {
<ide> ctx.save();
<ide>
<ide> for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
<del> const context = {
<del> chart: me.chart,
<del> scale: me,
<del> index: i,
<del> label: me.pointLabels[i],
<del> };
<add> const context = me.getContext(i);
<ide> const lineWidth = resolve([angleLineOpts.lineWidth, gridLineOpts.lineWidth], context, i);
<ide> const color = resolve([angleLineOpts.color, gridLineOpts.color], context, i);
<ide>
<ide> export default class RadialLinearScale extends LinearScaleBase {
<ide> ctx.textBaseline = 'middle';
<ide>
<ide> me.ticks.forEach((tick, index) => {
<del> const context = {
<del> chart: me.chart,
<del> scale: me,
<del> index,
<del> tick,
<del> };
<del>
<ide> if (index === 0 && !opts.reverse) {
<ide> return;
<ide> }
<ide>
<add> const context = me.getContext(index);
<ide> const tickFont = me._resolveTickFontOptions(index);
<ide> ctx.font = tickFont.string;
<ide> offset = me.getDistanceFromCenterForValue(me.ticks[index].value); | 5 |
PHP | PHP | fix broken cookbook link in doc | ca6143e7babc2f12267aebc9fa9df2f9564ab99d | <ide><path>src/Controller/Controller.php
<ide> public function referer($default = null, $local = false)
<ide> * @param \Cake\ORM\Table|string|\Cake\ORM\Query|null $object Table to paginate
<ide> * (e.g: Table instance, 'TableName' or a Query object)
<ide> * @return \Cake\ORM\ResultSet Query results
<del> * @link http://book.cakephp.org/3.0/en/controllers.html#Controller::paginate
<add> * @link http://book.cakephp.org/3.0/en/controllers.html#paginating-a-model
<ide> * @throws \RuntimeException When no compatible table object can be found.
<ide> */
<ide> public function paginate($object = null) | 1 |
Python | Python | fix a typo in cropping3d docs. | 4b1b706aa4effbf7c2886755ab99f5b75377762b | <ide><path>keras/layers/convolutional.py
<ide> def get_config(self):
<ide>
<ide>
<ide> class Cropping3D(Layer):
<del> '''Cropping layer for 3D data (e.g. spatial or saptio-temporal).
<add> '''Cropping layer for 3D data (e.g. spatial or spatio-temporal).
<ide>
<ide> # Arguments
<ide> cropping: tuple of tuple of int (length 3) | 1 |
Text | Text | update rbdms urls to new repos | 160931cd6a2b7b86ed2e4ead56d5dceba27b779a | <ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/celestial-bodies-database.md
<ide> id: 5f1a4ef5d5d6b5ab580fc6ae
<ide> title: 天體數據庫
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.celestial-bodies-database
<add>url: https://github.com/freeCodeCamp/learn-celestial-bodies-database
<ide> dashedName: celestial-bodies-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/learn-advanced-bash-by-building-a-kitty-ipsum-translator.md
<ide> id: 602da0de22201c65d2a019f6
<ide> title: 通過構建一個 Kitty Ipsum 翻譯器來學習高級 Bash
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-advanced-bash-by-building-a-kitty-ipsum-translator
<add>url: https://github.com/freeCodeCamp/learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> dashedName: learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/learn-bash-and-sql-by-building-a-bike-rental-shop.md
<ide> id: 5f5b969a05380d2179fe6e18
<ide> title: 通過構建自行車租賃店來學習 Bash 和 SQL
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-and-sql-by-building-a-bike-rental-shop
<add>url: https://github.com/freeCodeCamp/learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> dashedName: learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/learn-bash-by-building-a-boilerplate.md
<ide> id: 5ea8adfab628f68d805bfc5e
<ide> title: 通過構建模版學習 Bash
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/freeCodeCamp/.learn-bash-by-building-a-boilerplate
<add>url: https://github.com/freeCodeCamp/learn-bash-by-building-a-boilerplate
<ide> dashedName: learn-bash-by-building-a-boilerplate
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/learn-bash-scripting-by-building-five-programs.md
<ide> id: 5f5904ac738bc2fa9efecf5a
<ide> title: 通過構建五個程序學習 Bash 腳本
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-scripting-by-building-five-programs
<add>url: https://github.com/freeCodeCamp/learn-bash-scripting-by-building-five-programs
<ide> dashedName: learn-bash-scripting-by-building-five-programs
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/learn-git-by-building-an-sql-reference-object.md
<ide> id: 5fa323cdaf6a73463d590659
<ide> title: 通過構建 SQL 引用對象來學習 Git
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-git-by-building-an-sql-reference-object
<add>url: https://github.com/freeCodeCamp/learn-git-by-building-an-sql-reference-object
<ide> dashedName: learn-git-by-building-an-sql-reference-object
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/learn-github-by-building-a-list-of-inspirational-quotes.md
<ide> id: 602da04222201c65d2a019f3
<ide> title: 通過建立勵志名言列表來學習 GitHub
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-github-by-building-a-list-of-inspirational-quotes
<add>url: https://github.com/moT01/learn-github-by-building-a-list-of-inspirational-quotes
<ide> dashedName: learn-github-by-building-a-list-of-inspirational-quotes
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/learn-nano-by-building-a-castle.md
<ide> id: 5f32db63eb37f7e17323f459
<ide> title: 通過構建城堡來學習 Nano
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-nano-by-building-a-castle
<add>url: https://github.com/freeCodeCamp/learn-nano-by-building-a-castle
<ide> dashedName: learn-nano-by-building-a-castle
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/learn-relational-databases-by-building-a-mario-database.md
<ide> id: 5f2c289f164c29556da632fd
<ide> title: 通過構建 Mario 數據庫來學習關係型數據庫
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-relational-databases-by-building-a-mario-database
<add>url: https://github.com/freeCodeCamp/learn-relational-databases-by-building-a-mario-database
<ide> dashedName: learn-relational-databases-by-building-a-mario-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/learn-sql-by-building-a-student-database.md
<ide> id: 602da0c222201c65d2a019f5
<ide> title: 通過構建學生數據庫學習 SQL
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-sql-by-building-a-student-database
<add>url: https://github.com/freeCodeCamp/learn-sql-by-building-a-student-database
<ide> dashedName: learn-sql-by-building-a-student-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/number-guessing-game.md
<ide> id: 602da04c22201c65d2a019f4
<ide> title: 猜數字遊戲
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.number-guessing-game
<add>url: https://github.com/freeCodeCamp/learn-number-guessing-game
<ide> dashedName: number-guessing-game
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/periodic-table-database.md
<ide> id: 602d9ff222201c65d2a019f2
<ide> title: 元素週期表數據庫
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.periodic-table-database
<add>url: https://github.com/freeCodeCamp/learn-periodic-table-database
<ide> dashedName: periodic-table-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/salon-appointment-scheduler.md
<ide> id: 5f87ac112ae598023a42df1a
<ide> title: 沙龍日程安排程序
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.salon-appointment-scheduler
<add>url: https://github.com/freeCodeCamp/learn-salon-appointment-scheduler
<ide> dashedName: salon-appointment-scheduler
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese-traditional/13-relational-databases/learn-relational-databases/world-cup-database.md
<ide> id: 5f9771307d4d22b9d2b75a94
<ide> title: 世界盃數據庫
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.world-cup-database
<add>url: https://github.com/freeCodeCamp/learn-world-cup-database
<ide> dashedName: world-cup-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/celestial-bodies-database.md
<ide> id: 5f1a4ef5d5d6b5ab580fc6ae
<ide> title: 天体数据库
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.celestial-bodies-database
<add>url: https://github.com/freeCodeCamp/learn-celestial-bodies-database
<ide> dashedName: celestial-bodies-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/learn-advanced-bash-by-building-a-kitty-ipsum-translator.md
<ide> id: 602da0de22201c65d2a019f6
<ide> title: 通过构建一个 Kitty Ipsum 翻译器来学习高级 Bash
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-advanced-bash-by-building-a-kitty-ipsum-translator
<add>url: https://github.com/freeCodeCamp/learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> dashedName: learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/learn-bash-and-sql-by-building-a-bike-rental-shop.md
<ide> id: 5f5b969a05380d2179fe6e18
<ide> title: 通过构建自行车租赁店来学习 Bash 和 SQL
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-and-sql-by-building-a-bike-rental-shop
<add>url: https://github.com/freeCodeCamp/learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> dashedName: learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/learn-bash-by-building-a-boilerplate.md
<ide> id: 5ea8adfab628f68d805bfc5e
<ide> title: 通过构建模版学习 Bash
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/freeCodeCamp/.learn-bash-by-building-a-boilerplate
<add>url: https://github.com/freeCodeCamp/learn-bash-by-building-a-boilerplate
<ide> dashedName: learn-bash-by-building-a-boilerplate
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/learn-bash-scripting-by-building-five-programs.md
<ide> id: 5f5904ac738bc2fa9efecf5a
<ide> title: 通过构建五个程序学习 Bash 脚本
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-scripting-by-building-five-programs
<add>url: https://github.com/freeCodeCamp/learn-bash-scripting-by-building-five-programs
<ide> dashedName: learn-bash-scripting-by-building-five-programs
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/learn-git-by-building-an-sql-reference-object.md
<ide> id: 5fa323cdaf6a73463d590659
<ide> title: 通过构建 SQL 引用对象来学习 Git
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-git-by-building-an-sql-reference-object
<add>url: https://github.com/freeCodeCamp/learn-git-by-building-an-sql-reference-object
<ide> dashedName: learn-git-by-building-an-sql-reference-object
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/learn-github-by-building-a-list-of-inspirational-quotes.md
<ide> id: 602da04222201c65d2a019f3
<ide> title: 通过建立励志名言列表来学习 GitHub
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-github-by-building-a-list-of-inspirational-quotes
<add>url: https://github.com/moT01/learn-github-by-building-a-list-of-inspirational-quotes
<ide> dashedName: learn-github-by-building-a-list-of-inspirational-quotes
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/learn-nano-by-building-a-castle.md
<ide> id: 5f32db63eb37f7e17323f459
<ide> title: 通过构建城堡来学习 Nano
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-nano-by-building-a-castle
<add>url: https://github.com/freeCodeCamp/learn-nano-by-building-a-castle
<ide> dashedName: learn-nano-by-building-a-castle
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/learn-relational-databases-by-building-a-mario-database.md
<ide> id: 5f2c289f164c29556da632fd
<ide> title: 通过构建 Mario 数据库来学习关系型数据库
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-relational-databases-by-building-a-mario-database
<add>url: https://github.com/freeCodeCamp/learn-relational-databases-by-building-a-mario-database
<ide> dashedName: learn-relational-databases-by-building-a-mario-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/learn-sql-by-building-a-student-database.md
<ide> id: 602da0c222201c65d2a019f5
<ide> title: 通过构建学生数据库学习 SQL
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-sql-by-building-a-student-database
<add>url: https://github.com/freeCodeCamp/learn-sql-by-building-a-student-database
<ide> dashedName: learn-sql-by-building-a-student-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/number-guessing-game.md
<ide> id: 602da04c22201c65d2a019f4
<ide> title: 猜数字游戏
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.number-guessing-game
<add>url: https://github.com/freeCodeCamp/learn-number-guessing-game
<ide> dashedName: number-guessing-game
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/periodic-table-database.md
<ide> id: 602d9ff222201c65d2a019f2
<ide> title: 元素周期表数据库
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.periodic-table-database
<add>url: https://github.com/freeCodeCamp/learn-periodic-table-database
<ide> dashedName: periodic-table-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/salon-appointment-scheduler.md
<ide> id: 5f87ac112ae598023a42df1a
<ide> title: 沙龙日程安排程序
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.salon-appointment-scheduler
<add>url: https://github.com/freeCodeCamp/learn-salon-appointment-scheduler
<ide> dashedName: salon-appointment-scheduler
<ide> ---
<ide>
<ide><path>curriculum/challenges/chinese/13-relational-databases/learn-relational-databases/world-cup-database.md
<ide> id: 5f9771307d4d22b9d2b75a94
<ide> title: 世界杯数据库
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.world-cup-database
<add>url: https://github.com/freeCodeCamp/learn-world-cup-database
<ide> dashedName: world-cup-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/celestial-bodies-database.md
<ide> id: 5f1a4ef5d5d6b5ab580fc6ae
<ide> title: Celestial Bodies Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.celestial-bodies-database
<add>url: https://github.com/freeCodeCamp/learn-celestial-bodies-database
<ide> dashedName: celestial-bodies-database
<ide>
<ide> ---
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/learn-advanced-bash-by-building-a-kitty-ipsum-translator.md
<ide> id: 602da0de22201c65d2a019f6
<ide> title: Learn Advanced Bash by Building a Kitty Ipsum Translator
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-advanced-bash-by-building-a-kitty-ipsum-translator
<add>url: https://github.com/freeCodeCamp/learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> dashedName: learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/learn-bash-and-sql-by-building-a-bike-rental-shop.md
<ide> id: 5f5b969a05380d2179fe6e18
<ide> title: Learn Bash and SQL by Building a Bike Rental Shop
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-and-sql-by-building-a-bike-rental-shop
<add>url: https://github.com/freeCodeCamp/learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> dashedName: learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/learn-bash-by-building-a-boilerplate.md
<ide> id: 5ea8adfab628f68d805bfc5e
<ide> title: Learn Bash by Building a Boilerplate
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/freeCodeCamp/.learn-bash-by-building-a-boilerplate
<add>url: https://github.com/freeCodeCamp/learn-bash-by-building-a-boilerplate
<ide> dashedName: learn-bash-by-building-a-boilerplate
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/learn-bash-scripting-by-building-five-programs.md
<ide> id: 5f5904ac738bc2fa9efecf5a
<ide> title: Learn Bash Scripting by Building Five Programs
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-scripting-by-building-five-programs
<add>url: https://github.com/freeCodeCamp/learn-bash-scripting-by-building-five-programs
<ide> dashedName: learn-bash-scripting-by-building-five-programs
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/learn-git-by-building-an-sql-reference-object.md
<ide> id: 5fa323cdaf6a73463d590659
<ide> title: Learn Git by Building an SQL Reference Object
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-git-by-building-an-sql-reference-object
<add>url: https://github.com/freeCodeCamp/learn-git-by-building-an-sql-reference-object
<ide> dashedName: learn-git-by-building-an-sql-reference-object
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/learn-github-by-building-a-list-of-inspirational-quotes.md
<ide> id: 602da04222201c65d2a019f3
<ide> title: Learn GitHub by Building a List of Inspirational Quotes
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-github-by-building-a-list-of-inspirational-quotes
<add>url: https://github.com/moT01/learn-github-by-building-a-list-of-inspirational-quotes
<ide> dashedName: learn-github-by-building-a-list-of-inspirational-quotes
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/learn-nano-by-building-a-castle.md
<ide> id: 5f32db63eb37f7e17323f459
<ide> title: Learn Nano by Building a Castle
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-nano-by-building-a-castle
<add>url: https://github.com/freeCodeCamp/learn-nano-by-building-a-castle
<ide> dashedName: learn-nano-by-building-a-castle
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/learn-relational-databases-by-building-a-mario-database.md
<ide> id: 5f2c289f164c29556da632fd
<ide> title: Learn Relational Databases by Building a Mario Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-relational-databases-by-building-a-mario-database
<add>url: https://github.com/freeCodeCamp/learn-relational-databases-by-building-a-mario-database
<ide> dashedName: learn-relational-databases-by-building-a-mario-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/learn-sql-by-building-a-student-database.md
<ide> id: 602da0c222201c65d2a019f5
<ide> title: Learn SQL by Building a Student Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-sql-by-building-a-student-database
<add>url: https://github.com/freeCodeCamp/learn-sql-by-building-a-student-database
<ide> dashedName: learn-sql-by-building-a-student-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/number-guessing-game.md
<ide> id: 602da04c22201c65d2a019f4
<ide> title: Number Guessing Game
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.number-guessing-game
<add>url: https://github.com/freeCodeCamp/learn-number-guessing-game
<ide> dashedName: number-guessing-game
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/periodic-table-database.md
<ide> id: 602d9ff222201c65d2a019f2
<ide> title: Periodic Table Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.periodic-table-database
<add>url: https://github.com/freeCodeCamp/learn-periodic-table-database
<ide> dashedName: periodic-table-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/salon-appointment-scheduler.md
<ide> id: 5f87ac112ae598023a42df1a
<ide> title: Salon Appointment Scheduler
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.salon-appointment-scheduler
<add>url: https://github.com/freeCodeCamp/learn-salon-appointment-scheduler
<ide> dashedName: salon-appointment-scheduler
<ide> ---
<ide>
<ide><path>curriculum/challenges/english/13-relational-databases/learn-relational-databases/world-cup-database.md
<ide> id: 5f9771307d4d22b9d2b75a94
<ide> title: World Cup Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.world-cup-database
<add>url: https://github.com/freeCodeCamp/learn-world-cup-database
<ide> dashedName: world-cup-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/celestial-bodies-database.md
<ide> id: 5f1a4ef5d5d6b5ab580fc6ae
<ide> title: Celestial Bodies Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.celestial-bodies-database
<add>url: https://github.com/freeCodeCamp/learn-celestial-bodies-database
<ide> dashedName: celestial-bodies-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/learn-advanced-bash-by-building-a-kitty-ipsum-translator.md
<ide> id: 602da0de22201c65d2a019f6
<ide> title: Learn Advanced Bash by Building a Kitty Ipsum Translator
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-advanced-bash-by-building-a-kitty-ipsum-translator
<add>url: https://github.com/freeCodeCamp/learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> dashedName: learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/learn-bash-and-sql-by-building-a-bike-rental-shop.md
<ide> id: 5f5b969a05380d2179fe6e18
<ide> title: Learn Bash and SQL by Building a Bike Rental Shop
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-and-sql-by-building-a-bike-rental-shop
<add>url: https://github.com/freeCodeCamp/learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> dashedName: learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/learn-bash-by-building-a-boilerplate.md
<ide> id: 5ea8adfab628f68d805bfc5e
<ide> title: Learn Bash by Building a Boilerplate
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/freeCodeCamp/.learn-bash-by-building-a-boilerplate
<add>url: https://github.com/freeCodeCamp/learn-bash-by-building-a-boilerplate
<ide> dashedName: learn-bash-by-building-a-boilerplate
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/learn-bash-scripting-by-building-five-programs.md
<ide> id: 5f5904ac738bc2fa9efecf5a
<ide> title: Learn Bash Scripting by Building Five Programs
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-scripting-by-building-five-programs
<add>url: https://github.com/freeCodeCamp/learn-bash-scripting-by-building-five-programs
<ide> dashedName: learn-bash-scripting-by-building-five-programs
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/learn-git-by-building-an-sql-reference-object.md
<ide> id: 5fa323cdaf6a73463d590659
<ide> title: Learn Git by Building an SQL Reference Object
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-git-by-building-an-sql-reference-object
<add>url: https://github.com/freeCodeCamp/learn-git-by-building-an-sql-reference-object
<ide> dashedName: learn-git-by-building-an-sql-reference-object
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/learn-github-by-building-a-list-of-inspirational-quotes.md
<ide> id: 602da04222201c65d2a019f3
<ide> title: Learn GitHub by Building a List of Inspirational Quotes
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-github-by-building-a-list-of-inspirational-quotes
<add>url: https://github.com/moT01/learn-github-by-building-a-list-of-inspirational-quotes
<ide> dashedName: learn-github-by-building-a-list-of-inspirational-quotes
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/learn-nano-by-building-a-castle.md
<ide> id: 5f32db63eb37f7e17323f459
<ide> title: Learn Nano by Building a Castle
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-nano-by-building-a-castle
<add>url: https://github.com/freeCodeCamp/learn-nano-by-building-a-castle
<ide> dashedName: learn-nano-by-building-a-castle
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/learn-relational-databases-by-building-a-mario-database.md
<ide> id: 5f2c289f164c29556da632fd
<ide> title: Learn Relational Databases by Building a Mario Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-relational-databases-by-building-a-mario-database
<add>url: https://github.com/freeCodeCamp/learn-relational-databases-by-building-a-mario-database
<ide> dashedName: learn-relational-databases-by-building-a-mario-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/learn-sql-by-building-a-student-database.md
<ide> id: 602da0c222201c65d2a019f5
<ide> title: Learn SQL by Building a Student Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-sql-by-building-a-student-database
<add>url: https://github.com/freeCodeCamp/learn-sql-by-building-a-student-database
<ide> dashedName: learn-sql-by-building-a-student-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/number-guessing-game.md
<ide> id: 602da04c22201c65d2a019f4
<ide> title: Number Guessing Game
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.number-guessing-game
<add>url: https://github.com/freeCodeCamp/learn-number-guessing-game
<ide> dashedName: number-guessing-game
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/periodic-table-database.md
<ide> id: 602d9ff222201c65d2a019f2
<ide> title: Periodic Table Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.periodic-table-database
<add>url: https://github.com/freeCodeCamp/learn-periodic-table-database
<ide> dashedName: periodic-table-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/salon-appointment-scheduler.md
<ide> id: 5f87ac112ae598023a42df1a
<ide> title: Salon Appointment Scheduler
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.salon-appointment-scheduler
<add>url: https://github.com/freeCodeCamp/learn-salon-appointment-scheduler
<ide> dashedName: salon-appointment-scheduler
<ide> ---
<ide>
<ide><path>curriculum/challenges/espanol/13-relational-databases/learn-relational-databases/world-cup-database.md
<ide> id: 5f9771307d4d22b9d2b75a94
<ide> title: World Cup Database
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.world-cup-database
<add>url: https://github.com/freeCodeCamp/learn-world-cup-database
<ide> dashedName: world-cup-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/celestial-bodies-database.md
<ide> id: 5f1a4ef5d5d6b5ab580fc6ae
<ide> title: Database Corpi Celesti
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.celestial-bodies-database
<add>url: https://github.com/freeCodeCamp/learn-celestial-bodies-database
<ide> dashedName: celestial-bodies-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/learn-advanced-bash-by-building-a-kitty-ipsum-translator.md
<ide> id: 602da0de22201c65d2a019f6
<ide> title: Impara Bash avanzato costruendo un traduttore Kitty Ipsum
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-advanced-bash-by-building-a-kitty-ipsum-translator
<add>url: https://github.com/freeCodeCamp/learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> dashedName: learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/learn-bash-and-sql-by-building-a-bike-rental-shop.md
<ide> id: 5f5b969a05380d2179fe6e18
<ide> title: Impara Bash e SQL costruendo uno shop di noleggio biciclette
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-and-sql-by-building-a-bike-rental-shop
<add>url: https://github.com/freeCodeCamp/learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> dashedName: learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/learn-bash-by-building-a-boilerplate.md
<ide> id: 5ea8adfab628f68d805bfc5e
<ide> title: Impara Bash costruendo un codice Boilerplate
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/freeCodeCamp/.learn-bash-by-building-a-boilerplate
<add>url: https://github.com/freeCodeCamp/learn-bash-by-building-a-boilerplate
<ide> dashedName: learn-bash-by-building-a-boilerplate
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/learn-bash-scripting-by-building-five-programs.md
<ide> id: 5f5904ac738bc2fa9efecf5a
<ide> title: Impara lo Scripting Bash costruendo cinque programmi
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-scripting-by-building-five-programs
<add>url: https://github.com/freeCodeCamp/learn-bash-scripting-by-building-five-programs
<ide> dashedName: learn-bash-scripting-by-building-five-programs
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/learn-git-by-building-an-sql-reference-object.md
<ide> id: 5fa323cdaf6a73463d590659
<ide> title: Impara Git costruendo un oggetto di riferimento SQL
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-git-by-building-an-sql-reference-object
<add>url: https://github.com/freeCodeCamp/learn-git-by-building-an-sql-reference-object
<ide> dashedName: learn-git-by-building-an-sql-reference-object
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/learn-github-by-building-a-list-of-inspirational-quotes.md
<ide> id: 602da04222201c65d2a019f3
<ide> title: Impara GitHub costruendo una lista di citazioni motivazionali
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-github-by-building-a-list-of-inspirational-quotes
<add>url: https://github.com/moT01/learn-github-by-building-a-list-of-inspirational-quotes
<ide> dashedName: learn-github-by-building-a-list-of-inspirational-quotes
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/learn-nano-by-building-a-castle.md
<ide> id: 5f32db63eb37f7e17323f459
<ide> title: Impara Nano costruendo un castello
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-nano-by-building-a-castle
<add>url: https://github.com/freeCodeCamp/learn-nano-by-building-a-castle
<ide> dashedName: learn-nano-by-building-a-castle
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/learn-relational-databases-by-building-a-mario-database.md
<ide> id: 5f2c289f164c29556da632fd
<ide> title: Impara i database relazionali costruendo un database Mario
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-relational-databases-by-building-a-mario-database
<add>url: https://github.com/freeCodeCamp/learn-relational-databases-by-building-a-mario-database
<ide> dashedName: learn-relational-databases-by-building-a-mario-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/learn-sql-by-building-a-student-database.md
<ide> id: 602da0c222201c65d2a019f5
<ide> title: Impara SQL costruendo un database degli studenti
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-sql-by-building-a-student-database
<add>url: https://github.com/freeCodeCamp/learn-sql-by-building-a-student-database
<ide> dashedName: learn-sql-by-building-a-student-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/number-guessing-game.md
<ide> id: 602da04c22201c65d2a019f4
<ide> title: Gioco di indovinare il numero
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.number-guessing-game
<add>url: https://github.com/freeCodeCamp/learn-number-guessing-game
<ide> dashedName: number-guessing-game
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/periodic-table-database.md
<ide> id: 602d9ff222201c65d2a019f2
<ide> title: Database della Tavola Periodica
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.periodic-table-database
<add>url: https://github.com/freeCodeCamp/learn-periodic-table-database
<ide> dashedName: periodic-table-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/salon-appointment-scheduler.md
<ide> id: 5f87ac112ae598023a42df1a
<ide> title: Pianificatore Appuntamento Salone
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.salon-appointment-scheduler
<add>url: https://github.com/freeCodeCamp/learn-salon-appointment-scheduler
<ide> dashedName: salon-appointment-scheduler
<ide> ---
<ide>
<ide><path>curriculum/challenges/italian/13-relational-databases/learn-relational-databases/world-cup-database.md
<ide> id: 5f9771307d4d22b9d2b75a94
<ide> title: Database Coppa Del Mondo
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.world-cup-database
<add>url: https://github.com/freeCodeCamp/learn-world-cup-database
<ide> dashedName: world-cup-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/celestial-bodies-database.md
<ide> id: 5f1a4ef5d5d6b5ab580fc6ae
<ide> title: Banco de dados de corpos celestiais
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.celestial-bodies-database
<add>url: https://github.com/freeCodeCamp/learn-celestial-bodies-database
<ide> dashedName: celestial-bodies-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/learn-advanced-bash-by-building-a-kitty-ipsum-translator.md
<ide> id: 602da0de22201c65d2a019f6
<ide> title: Aprenda Bash avançado construindo um tradutor de Kitty Ipsum
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-advanced-bash-by-building-a-kitty-ipsum-translator
<add>url: https://github.com/freeCodeCamp/learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> dashedName: learn-advanced-bash-by-building-a-kitty-ipsum-translator
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/learn-bash-and-sql-by-building-a-bike-rental-shop.md
<ide> id: 5f5b969a05380d2179fe6e18
<ide> title: Aprenda Bash e SQL criando uma loja de aluguel de bicicletas
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-and-sql-by-building-a-bike-rental-shop
<add>url: https://github.com/freeCodeCamp/learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> dashedName: learn-bash-and-sql-by-building-a-bike-rental-shop
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/learn-bash-by-building-a-boilerplate.md
<ide> id: 5ea8adfab628f68d805bfc5e
<ide> title: Aprenda Bash criando um boilerplate
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/freeCodeCamp/.learn-bash-by-building-a-boilerplate
<add>url: https://github.com/freeCodeCamp/learn-bash-by-building-a-boilerplate
<ide> dashedName: learn-bash-by-building-a-boilerplate
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/learn-bash-scripting-by-building-five-programs.md
<ide> id: 5f5904ac738bc2fa9efecf5a
<ide> title: Aprenda Bash Scripting desenvolvendo cinco programas
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-bash-scripting-by-building-five-programs
<add>url: https://github.com/freeCodeCamp/learn-bash-scripting-by-building-five-programs
<ide> dashedName: learn-bash-scripting-by-building-five-programs
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/learn-git-by-building-an-sql-reference-object.md
<ide> id: 5fa323cdaf6a73463d590659
<ide> title: Aprenda Git criando um objeto de referência SQL
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-git-by-building-an-sql-reference-object
<add>url: https://github.com/freeCodeCamp/learn-git-by-building-an-sql-reference-object
<ide> dashedName: learn-git-by-building-an-sql-reference-object
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/learn-github-by-building-a-list-of-inspirational-quotes.md
<ide> id: 602da04222201c65d2a019f3
<ide> title: Aprenda GitHub criando uma lista de citações inspiradoras
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-github-by-building-a-list-of-inspirational-quotes
<add>url: https://github.com/moT01/learn-github-by-building-a-list-of-inspirational-quotes
<ide> dashedName: learn-github-by-building-a-list-of-inspirational-quotes
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/learn-nano-by-building-a-castle.md
<ide> id: 5f32db63eb37f7e17323f459
<ide> title: Aprenda Nano criando um castelo
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-nano-by-building-a-castle
<add>url: https://github.com/freeCodeCamp/learn-nano-by-building-a-castle
<ide> dashedName: learn-nano-by-building-a-castle
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/learn-relational-databases-by-building-a-mario-database.md
<ide> id: 5f2c289f164c29556da632fd
<ide> title: Aprenda bancos de dados relacionais criando um banco de dados sobre Mario
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-relational-databases-by-building-a-mario-database
<add>url: https://github.com/freeCodeCamp/learn-relational-databases-by-building-a-mario-database
<ide> dashedName: learn-relational-databases-by-building-a-mario-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/learn-sql-by-building-a-student-database.md
<ide> id: 602da0c222201c65d2a019f5
<ide> title: Aprenda SQL criando um banco de dados de alunos
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.learn-sql-by-building-a-student-database
<add>url: https://github.com/freeCodeCamp/learn-sql-by-building-a-student-database
<ide> dashedName: learn-sql-by-building-a-student-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/number-guessing-game.md
<ide> id: 602da04c22201c65d2a019f4
<ide> title: Jogo de adivinhação de números
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.number-guessing-game
<add>url: https://github.com/freeCodeCamp/learn-number-guessing-game
<ide> dashedName: number-guessing-game
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/periodic-table-database.md
<ide> id: 602d9ff222201c65d2a019f2
<ide> title: Banco de dados da tabela periódica
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.periodic-table-database
<add>url: https://github.com/freeCodeCamp/learn-periodic-table-database
<ide> dashedName: periodic-table-database
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/salon-appointment-scheduler.md
<ide> id: 5f87ac112ae598023a42df1a
<ide> title: Agendador de compromissos do salão de beleza
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.salon-appointment-scheduler
<add>url: https://github.com/freeCodeCamp/learn-salon-appointment-scheduler
<ide> dashedName: salon-appointment-scheduler
<ide> ---
<ide>
<ide><path>curriculum/challenges/portuguese/13-relational-databases/learn-relational-databases/world-cup-database.md
<ide> id: 5f9771307d4d22b9d2b75a94
<ide> title: Banco de dados da Copa do Mundo
<ide> challengeType: 12
<ide> helpCategory: Relational Databases
<del>url: https://github.com/moT01/.world-cup-database
<add>url: https://github.com/freeCodeCamp/learn-world-cup-database
<ide> dashedName: world-cup-database
<ide> ---
<ide> | 84 |
Text | Text | update stream.pipeline() signature | 2f23918ca5090417ad0e06be6ecce63553f17985 | <ide><path>doc/api/stream.md
<ide> const cleanup = finished(rs, (err) => {
<ide> });
<ide> ```
<ide>
<del>### `stream.pipeline(source, ...transforms, destination, callback)`
<add>### `stream.pipeline(source[, ...transforms], destination, callback)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> changes: | 1 |
Ruby | Ruby | unify install name parsing | ce19fa222361839d2c04986f81ae66c8a8748a61 | <ide><path>Library/Homebrew/cmd/bottle.rb
<ide> def keg_contains string, keg
<ide> keg_ref_files.each do |file|
<ide> puts "#{Tty.red}#{file}#{Tty.reset}"
<ide>
<del> linked_libraries = []
<del>
<ide> # Check dynamic library linkage. Importantly, do not run otool on static
<ide> # libraries, which will falsely report "linkage" to themselves.
<ide> if file.mach_o_executable? or file.dylib? or file.mach_o_bundle?
<del> linked_libraries.concat `otool -L "#{file}"`.split("\n").drop(1)
<del> linked_libraries.map! { |lib| lib[Keg::OTOOL_RX, 1] }
<add> linked_libraries = file.dynamically_linked_libraries
<ide> linked_libraries = linked_libraries.select { |lib| lib.include? string }
<add> else
<add> linked_libraries = []
<ide> end
<ide>
<ide> linked_libraries.each do |lib|
<ide><path>Library/Homebrew/keg_fix_install_names.rb
<ide> def detect_cxx_stdlibs
<ide>
<ide> private
<ide>
<del> OTOOL_RX = /\t(.*) \(compatibility version (\d+\.)*\d+, current version (\d+\.)*\d+\)/
<del>
<ide> def install_name_tool(*args)
<ide> system(MacOS.locate("install_name_tool"), *args)
<ide> end
<ide> def fixed_name(file, bad_name)
<ide> def lib; join 'lib' end
<ide>
<ide> def each_install_name_for file, &block
<del> ENV['HOMEBREW_MACH_O_FILE'] = file.to_s # solves all shell escaping problems
<del> install_names = `#{MacOS.locate("otool")} -L "$HOMEBREW_MACH_O_FILE"`.split "\n"
<del>
<del> install_names.shift # first line is fluff
<del> install_names.map!{ |s| OTOOL_RX =~ s && $1 }
<del>
<del> # For dylibs, the next line is the ID
<del> install_names.shift if file.dylib?
<del>
<del> install_names.compact!
<del> install_names.reject!{ |fn| fn =~ /^@(loader_|executable_|r)path/ }
<del>
<del> install_names.each(&block)
<add> dylibs = file.dynamically_linked_libraries
<add> dylibs.reject! { |fn| fn =~ /^@(loader_|executable_|r)path/ }
<add> dylibs.each(&block)
<ide> end
<ide>
<ide> def dylib_id_for file, options={}
<ide><path>Library/Homebrew/mach.rb
<ide> def intersects_all?(*set)
<ide> end
<ide>
<ide> module MachO
<add> OTOOL_RX = /\t(.*) \(compatibility version (\d+\.)*\d+, current version (\d+\.)*\d+\)/
<add>
<ide> # Mach-O binary methods, see:
<ide> # /usr/include/mach-o/loader.h
<ide> # /usr/include/mach-o/fat.h
<ide> def mach_o_bundle?
<ide> # Returns an empty array both for software that links against no libraries,
<ide> # and for non-mach objects.
<ide> def dynamically_linked_libraries
<del> `#{MacOS.locate("otool")} -L "#{expand_path}"`.chomp.split("\n")[1..-1].map do |line|
<del> line[/\t(.+) \([^(]+\)/, 1]
<del> end
<add> # Use an environment variable to avoid escaping problems
<add> ENV['HOMEBREW_MACH_O_FILE'] = expand_path.to_s
<add>
<add> libs = `#{MacOS.locate("otool")} -L "$HOMEBREW_MACH_O_FILE"`.split("\n")
<add>
<add> # First line is the filename
<add> libs.shift
<add>
<add> # For dylibs, the next line is the ID
<add> libs.shift if dylib?
<add>
<add> libs.map! { |lib| lib[OTOOL_RX, 1] }
<add> libs.compact!
<add> libs
<add> ensure
<add> ENV.delete 'HOMEBREW_MACH_O_FILE'
<ide> end
<ide> end | 3 |
Javascript | Javascript | implement loading states for linkview | ae87fc90ca0b925e0ec3260466aeb71fc5850b08 | <ide><path>packages/ember-htmlbars/lib/hooks/get-root.js
<ide> function getKey(scope, key) {
<ide>
<ide> var self = scope.self;
<ide>
<del> if (!scope.attrs) {
<del> return self.getKey(key);
<del> }
<del>
<del> if (key in scope.attrs) {
<add> if (scope.attrs && key in scope.attrs) {
<ide> Ember.deprecate("You accessed the `" + key + "` attribute directly. Please use `attrs." + key + "` instead.");
<ide> return scope.attrs[key];
<add> } else if (self) {
<add> return self.getKey(key);
<ide> } else {
<ide> return scope.locals.view.getKey(key);
<ide> }
<ide><path>packages/ember-htmlbars/lib/keywords/outlet.js
<ide> export default {
<ide> self: toRender.controller
<ide> };
<ide>
<del> var componentNode = ComponentNode.create(renderNode, env, null, options, parentView, null, null, template);
<add> var componentNode = ComponentNode.create(renderNode, env, {}, options, parentView, null, null, template);
<ide> state.componentNode = componentNode;
<ide>
<ide> componentNode.render(env, hash, visitor);
<ide><path>packages/ember-routing-views/lib/views/link.js
<ide> import Ember from "ember-metal/core"; // FEATURES, Logger, assert
<ide>
<ide> import { get } from "ember-metal/property_get";
<add>import { set } from "ember-metal/property_set";
<ide> import { computed } from "ember-metal/computed";
<ide> import { isSimpleClick } from "ember-views/system/utils";
<ide> import EmberComponent from "ember-views/views/component";
<ide> var LinkComponent = EmberComponent.extend({
<ide>
<ide> @property href
<ide> **/
<del> href: computed('models', function computeLinkViewHref() {
<add> href: computed('models', 'targetRouteName', function computeLinkViewHref() {
<ide> if (get(this, 'tagName') !== 'a') { return; }
<ide>
<add> var targetRouteName = get(this, 'targetRouteName');
<add> var models = get(this, 'models');
<add>
<add> if (get(this, 'loading')) { return get(this, 'loadingHref'); }
<add>
<ide> var routing = get(this, '_routing');
<del> return routing.generateURL(get(this, 'targetRouteName'), get(this, 'models'), get(this, 'queryParams'));
<add> return routing.generateURL(targetRouteName, models, get(this, 'queryParams'));
<add> }),
<add>
<add> loading: computed('models', 'targetRouteName', function() {
<add> var targetRouteName = get(this, 'targetRouteName');
<add> var models = get(this, 'models');
<add>
<add> if (!modelsAreLoaded(models) || targetRouteName == null) {
<add> return get(this, 'loadingClass');
<add> }
<ide> }),
<ide>
<ide> /**
<ide> var LinkComponent = EmberComponent.extend({
<ide> this.set('linkTitle', params.shift());
<ide> }
<ide>
<add> if (attrs.loadingClass) {
<add> set(this, 'loadingClass', attrs.loadingClass);
<add> }
<add>
<ide> for (var i = 0; i < params.length; i++) {
<ide> var value = params[i];
<ide>
<ide> function computeActive(view, routerState) {
<ide> return false;
<ide> }
<ide>
<add>function modelsAreLoaded(models) {
<add> for (var i=0, l=models.length; i<l; i++) {
<add> if (models[i] == null) { return false; }
<add> }
<add>
<add> return true;
<add>}
<add>
<ide> function isActiveForRoute(view, routeName, isCurrentWhenSpecified, routerState) {
<ide> var service = get(view, '_routing');
<ide> return service.isActiveForRoute(get(view, 'models'), get(view, 'queryParams'), routeName, routerState, isCurrentWhenSpecified);
<ide><path>packages/ember/tests/helpers/link_to_test.js
<ide> QUnit.test("The {{link-to}} helper works in an #each'd array of string route nam
<ide> });
<ide>
<ide> Ember.TEMPLATES = {
<del> index: compile('{{#each routeName in routeNames}}{{#link-to routeName}}{{routeName}}{{/link-to}}{{/each}}{{#each routeNames}}{{#link-to this}}{{this}}{{/link-to}}{{/each}}{{#link-to route1}}a{{/link-to}}{{#link-to route2}}b{{/link-to}}')
<add> index: compile('{{#each routeNames as |routeName|}}{{#link-to routeName}}{{routeName}}{{/link-to}}{{/each}}{{#each routeNames as |r|}}{{#link-to r}}{{r}}{{/link-to}}{{/each}}{{#link-to route1}}a{{/link-to}}{{#link-to route2}}b{{/link-to}}')
<ide> };
<ide>
<del> expectDeprecation(function() {
<del> bootApplication();
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<add> bootApplication();
<ide>
<ide> function linksEqual($links, expected) {
<ide> equal($links.length, expected.length, "Has correct number of links"); | 4 |
Python | Python | fix stdout messes in `on_epoch_end` with verbose=1 | dc4dd03683e1a691adae4b6c5fe8266987998f4e | <ide><path>keras/engine/training.py
<ide> def _fit_loop(self, f, ins, out_labels=None, batch_size=None,
<ide> count_mode = 'steps'
<ide> else:
<ide> count_mode = 'samples'
<del> callbacks += [cbks.ProgbarLogger(count_mode)]
<add> callbacks.insert(1, cbks.ProgbarLogger(count_mode))
<ide> callbacks = cbks.CallbackList(callbacks)
<ide> out_labels = out_labels or []
<ide>
<ide> def generate_arrays_from_file(path):
<ide> self.history = cbks.History()
<ide> callbacks = [cbks.BaseLogger()] + (callbacks or []) + [self.history]
<ide> if verbose:
<del> callbacks += [cbks.ProgbarLogger(count_mode='steps')]
<add> callbacks.insert(1, cbks.ProgbarLogger(count_mode='steps'))
<ide> callbacks = cbks.CallbackList(callbacks)
<ide>
<ide> # it's possible to callback a different model than self: | 1 |
Ruby | Ruby | remove dead code | efd52da101cbed109d8045c02fcf0cdc4ffa7989 | <ide><path>Library/Homebrew/cmd/update.rb
<ide> def dump
<ide> dump_formula_report :D, "Deleted Formulae"
<ide> end
<ide>
<del> def tapped_formula_for key
<del> fetch(key, []).select { |path| HOMEBREW_TAP_PATH_REGEX === path.to_s }
<del> end
<del>
<del> def new_tapped_formula
<del> tapped_formula_for :A
<del> end
<del>
<del> def removed_tapped_formula
<del> tapped_formula_for :D
<del> end
<del>
<ide> def select_formula key
<ide> fetch(key, []).map do |path|
<ide> case path.to_s
<ide><path>Library/Homebrew/test/test_updater.rb
<ide> def test_update_homebrew_with_tap_formulae_changes
<ide> assert_equal %w{foo/bar/lua}, @report.select_formula(:A)
<ide> assert_equal %w{foo/bar/git}, @report.select_formula(:M)
<ide> assert_empty @report.select_formula(:D)
<del>
<del> assert_empty @report.removed_tapped_formula
<del> assert_equal [repo.join("Formula", "lua.rb")],
<del> @report.new_tapped_formula
<del> assert_equal [repo.join("Formula", "git.rb")],
<del> @report.tapped_formula_for(:M)
<ide> end
<ide> end | 2 |
Javascript | Javascript | add absolutepath keyword for ajv | 254b60337d0a21b1ed16ac4fe97c0efc810a7425 | <ide><path>schemas/ajv.absolutePath.js
<add>"use strict";
<add>
<add>const os = require("os");
<add>
<add>const getErrorFor = (shouldBeAbsolute, data, schema) => {
<add> const message = shouldBeAbsolute ?
<add> `The provided value ${JSON.stringify(data)} is not an absolute path!${os.EOL}`
<add> : `A non absolut path is expected. However the provided value ${JSON.stringify(data)} is an absolute path!${os.EOL}`;
<add>
<add> return {
<add> keyword: "absolutePath",
<add> params: { absolutePath: data },
<add> message: message,
<add> parentSchema: schema,
<add> };
<add>};
<add>module.exports = (ajv) => ajv.addKeyword("absolutePath", {
<add> errors: true,
<add> type: "string",
<add> compile(expected, schema) {
<add> function callback(data) {
<add> const passes = expected === /^(?:[a-zA-Z]:)?(?:\/|\\)/.test(data);
<add> if(!passes) {
<add> getErrorFor(expected, data, schema);
<add> callback.errors = [getErrorFor(expected, data, schema)];
<add> }
<add> return passes;
<add> }
<add> callback.errors = [];
<add> return callback;
<add> }
<add>}); | 1 |
Javascript | Javascript | rename the `guard` utility to `tryparse` | 1de76d28422447f11d2864125999a09eece31e2e | <ide><path>packages/eslint-plugin-codegen/react-native-modules.js
<ide> function rule(context) {
<ide> } = requireModuleParser();
<ide> const flowParser = require('flow-parser');
<ide>
<del> const [parsingErrors, guard] = createParserErrorCapturer();
<add> const [parsingErrors, tryParse] = createParserErrorCapturer();
<ide>
<ide> const sourceCode = context.getSourceCode().getText();
<ide> const ast = flowParser.parse(sourceCode);
<del> guard(() => buildModuleSchema(hasteModuleName, ast, guard));
<add>
<add> tryParse(() => {
<add> buildModuleSchema(hasteModuleName, ast, tryParse);
<add> });
<add>
<ide> parsingErrors.forEach(error => {
<ide> error.nodes.forEach(flowNode => {
<ide> context.report({
<ide><path>packages/react-native-codegen/src/parsers/flow/index.js
<ide> function buildSchema(contents: string, filename: ?string): SchemaType {
<ide> }
<ide> const hasteModuleName = path.basename(filename).replace(/\.js$/, '');
<ide>
<del> const [parsingErrors, guard] = createParserErrorCapturer();
<del> const schema = guard(() => buildModuleSchema(hasteModuleName, ast, guard));
<add> const [parsingErrors, tryParse] = createParserErrorCapturer();
<add> const schema = tryParse(() =>
<add> buildModuleSchema(hasteModuleName, ast, tryParse),
<add> );
<ide>
<ide> if (parsingErrors.length > 0) {
<ide> /**
<ide><path>packages/react-native-codegen/src/parsers/flow/modules/index.js
<ide> function translateTypeAnnotation(
<ide> flowTypeAnnotation: $FlowFixMe,
<ide> types: TypeDeclarationMap,
<ide> aliasMap: {...NativeModuleAliasMap},
<del> guard: ParserErrorCapturer,
<add> tryParse: ParserErrorCapturer,
<ide> ): Nullable<NativeModuleTypeAnnotation> {
<ide> const {
<ide> nullable,
<ide> function translateTypeAnnotation(
<ide> typeAnnotation.typeParameters.params[0],
<ide> types,
<ide> aliasMap,
<del> guard,
<add> tryParse,
<ide> );
<ide> }
<ide> case 'Stringish': {
<ide> function translateTypeAnnotation(
<ide> properties: (typeAnnotation.properties: Array<$FlowFixMe>)
<ide> .map<?NamedShape<Nullable<NativeModuleBaseTypeAnnotation>>>(
<ide> property => {
<del> return guard(() => {
<add> return tryParse(() => {
<ide> if (property.type !== 'ObjectTypeProperty') {
<ide> throw new UnsupportedObjectPropertyTypeAnnotationParserError(
<ide> hasteModuleName,
<ide> function translateTypeAnnotation(
<ide> property.value,
<ide> types,
<ide> aliasMap,
<del> guard,
<add> tryParse,
<ide> ),
<ide> );
<ide>
<ide> function translateTypeAnnotation(
<ide> typeAnnotation,
<ide> types,
<ide> aliasMap,
<del> guard,
<add> tryParse,
<ide> ),
<ide> );
<ide> }
<ide> function translateFunctionTypeAnnotation(
<ide> flowFunctionTypeAnnotation: $FlowFixMe,
<ide> types: TypeDeclarationMap,
<ide> aliasMap: {...NativeModuleAliasMap},
<del> guard: ParserErrorCapturer,
<add> tryParse: ParserErrorCapturer,
<ide> ): NativeModuleFunctionTypeAnnotation {
<ide> type Param = NamedShape<Nullable<NativeModuleParamTypeAnnotation>>;
<ide> const params: Array<Param> = [];
<ide>
<ide> for (const flowParam of (flowFunctionTypeAnnotation.params: $ReadOnlyArray<$FlowFixMe>)) {
<del> const parsedParam = guard(() => {
<add> const parsedParam = tryParse(() => {
<ide> if (flowParam.name == null) {
<ide> throw new UnnamedFunctionParamParserError(flowParam, hasteModuleName);
<ide> }
<ide> function translateFunctionTypeAnnotation(
<ide> flowParam.typeAnnotation,
<ide> types,
<ide> aliasMap,
<del> guard,
<add> tryParse,
<ide> ),
<ide> );
<ide>
<ide> function translateFunctionTypeAnnotation(
<ide> flowFunctionTypeAnnotation.returnType,
<ide> types,
<ide> aliasMap,
<del> guard,
<add> tryParse,
<ide> ),
<ide> );
<ide>
<ide> function buildPropertySchema(
<ide> property: $FlowFixMe,
<ide> types: TypeDeclarationMap,
<ide> aliasMap: {...NativeModuleAliasMap},
<del> guard: ParserErrorCapturer,
<add> tryParse: ParserErrorCapturer,
<ide> ): NativeModulePropertyShape {
<ide> let nullable = false;
<ide> let {key, value} = property;
<ide> function buildPropertySchema(
<ide> value,
<ide> types,
<ide> aliasMap,
<del> guard,
<add> tryParse,
<ide> ),
<ide> ),
<ide> };
<ide> function buildModuleSchema(
<ide> * TODO(T71778680): Flow-type this node.
<ide> */
<ide> ast: $FlowFixMe,
<del> guard: ParserErrorCapturer,
<add> tryParse: ParserErrorCapturer,
<ide> ): NativeModuleSchema {
<ide> const types = getTypes(ast);
<ide> const moduleInterfaceNames = (Object.keys(
<ide> function buildModuleSchema(
<ide> }
<ide>
<ide> // Parse Module Names
<del> const moduleName = guard((): string => {
<add> const moduleName = tryParse((): string => {
<ide> const callExpressions = findChildren(ast, isCallIntoModuleRegistry);
<ide> if (callExpressions.length === 0) {
<ide> throw new UnusedModuleFlowInterfaceParserError(
<ide> function buildModuleSchema(
<ide> }>(property => {
<ide> const aliasMap: {...NativeModuleAliasMap} = {};
<ide>
<del> return guard(() => ({
<add> return tryParse(() => ({
<ide> aliasMap: aliasMap,
<ide> propertyShape: buildPropertySchema(
<ide> hasteModuleName,
<ide> property,
<ide> types,
<ide> aliasMap,
<del> guard,
<add> tryParse,
<ide> ),
<ide> }));
<ide> }) | 3 |
Javascript | Javascript | fix lint error (unused variable) | 277abbfe7b0190197b5eae278a4848f945fcf4e5 | <ide><path>vendor/constants.js
<ide> */
<ide> 'use strict';
<ide>
<del>var assert = require('assert');
<ide> var recast = require('recast');
<ide> var types = recast.types;
<ide> var namedTypes = types.namedTypes; | 1 |
Java | Java | operatorany needs to handle backpressure | 70d0308da5efbc921442ec5f0442f8f7776a44dc | <ide><path>rxjava-core/src/main/java/rx/internal/operators/OperatorAny.java
<ide> public Subscriber<? super T> call(final Subscriber<? super Boolean> child) {
<ide> return new Subscriber<T>(child) {
<ide> boolean hasElements;
<ide> boolean done;
<add>
<ide> @Override
<ide> public void onNext(T t) {
<ide> hasElements = true;
<ide> public void onNext(T t) {
<ide> child.onNext(!returnOnEmpty);
<ide> child.onCompleted();
<ide> unsubscribe();
<add> } else {
<add> // if we drop values we must replace them upstream as downstream won't receive and request more
<add> request(1);
<ide> }
<ide> }
<ide>
<ide> public void onCompleted() {
<ide> child.onCompleted();
<ide> }
<ide> }
<del>
<add>
<ide> };
<ide> }
<ide> }
<ide><path>rxjava-core/src/test/java/rx/internal/operators/OperatorAnyTest.java
<ide> */
<ide> package rx.internal.operators;
<ide>
<add>import static org.junit.Assert.assertTrue;
<ide> import static org.mockito.Mockito.mock;
<ide> import static org.mockito.Mockito.never;
<ide> import static org.mockito.Mockito.times;
<ide> import rx.functions.Func1;
<ide> import rx.functions.Functions;
<ide>
<add>import java.util.Arrays;
<add>
<ide> public class OperatorAnyTest {
<ide>
<ide> @Test
<ide> public Boolean call(Integer t1) {
<ide> verify(observer, never()).onError(org.mockito.Matchers.any(Throwable.class));
<ide> verify(observer, times(1)).onCompleted();
<ide> }
<add>
<add> @Test
<add> public void testWithFollowingFirst() {
<add> Observable<Integer> o = Observable.from(Arrays.asList(1, 3, 5, 6));
<add> Observable<Boolean> anyEven = o.exists(new Func1<Integer, Boolean>() {
<add> @Override
<add> public Boolean call(Integer i) {
<add> return i % 2 == 0;
<add> }
<add> });
<add> assertTrue(anyEven.toBlocking().first());
<add> }
<ide> } | 2 |
Mixed | Go | add sockets (-h) list to `docker -d info` | f54823bf05af1d549aee4f0d1f56f9a8995eb268 | <ide><path>CONTRIBUTING.md
<ide> feels wrong or incomplete.
<ide> When reporting [issues](https://github.com/dotcloud/docker/issues)
<ide> on GitHub please include your host OS (Ubuntu 12.04, Fedora 19, etc),
<ide> the output of `uname -a` and the output of `docker version` along with
<del>the output of `docker info`. Please include the steps required to reproduce
<add>the output of `docker -D info`. Please include the steps required to reproduce
<ide> the problem if possible and applicable.
<ide> This information will help us review and fix your issue faster.
<ide>
<ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide> if initPath := remoteInfo.Get("InitPath"); initPath != "" {
<ide> fmt.Fprintf(cli.out, "Init Path: %s\n", initPath)
<ide> }
<add> if len(remoteInfo.GetList("Sockets")) != 0 {
<add> fmt.Fprintf(cli.out, "Sockets: %v\n", remoteInfo.GetList("Sockets"))
<add> }
<ide> }
<ide>
<ide> if len(remoteInfo.GetList("IndexServerAddress")) != 0 {
<ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide> containerGraph *graphdb.Database
<ide> driver graphdriver.Driver
<ide> execDriver execdriver.Driver
<add> Sockets []string
<ide> }
<ide>
<ide> // Install installs daemon capabilities to eng.
<ide> func NewDaemonFromDirectory(config *daemonconfig.Config, eng *engine.Engine) (*D
<ide> sysInitPath: sysInitPath,
<ide> execDriver: ed,
<ide> eng: eng,
<add> Sockets: config.Sockets,
<ide> }
<ide>
<ide> if err := daemon.checkLocaldns(); err != nil {
<ide><path>daemonconfig/config.go
<ide> type Config struct {
<ide> DisableNetwork bool
<ide> EnableSelinuxSupport bool
<ide> Context map[string][]string
<add> Sockets []string
<ide> }
<ide>
<ide> // ConfigFromJob creates and returns a new DaemonConfig object
<ide> func ConfigFromJob(job *engine.Job) *Config {
<ide> config.Mtu = GetDefaultNetworkMtu()
<ide> }
<ide> config.DisableNetwork = config.BridgeIface == DisableNetworkBridge
<add> if sockets := job.GetenvList("Sockets"); sockets != nil {
<add> config.Sockets = sockets
<add> }
<ide>
<ide> return config
<ide> }
<ide><path>docker/docker.go
<ide> func main() {
<ide> job.Setenv("ExecDriver", *flExecDriver)
<ide> job.SetenvInt("Mtu", *flMtu)
<ide> job.SetenvBool("EnableSelinuxSupport", *flSelinuxEnabled)
<add> job.SetenvList("Sockets", flHosts.GetAll())
<ide> if err := job.Run(); err != nil {
<ide> log.Fatal(err)
<ide> }
<ide><path>docs/sources/reference/api/docker_remote_api_v1.11.md
<ide> Display system-wide information
<ide> {
<ide> "Containers":11,
<ide> "Images":16,
<add> "Driver":"btrfs",
<add> "ExecutionDriver":"native-0.1",
<add> "KernelVersion":"3.12.0-1-amd64"
<ide> "Debug":false,
<ide> "NFd": 11,
<ide> "NGoroutines":21,
<add> "NEventsListener":0,
<add> "InitPath":"/usr/bin/docker",
<add> "Sockets":["unix:///var/run/docker.sock"],
<add> "IndexServerAddress":["https://index.docker.io/v1/"],
<ide> "MemoryLimit":true,
<ide> "SwapLimit":false,
<ide> "IPv4Forwarding":true
<ide><path>docs/sources/reference/commandline/cli.md
<ide> tar, then the ownerships might not get preserved.
<ide>
<ide> ## info
<ide>
<del> Usage: docker info
<ide>
<del> Display system-wide information
<add> Usage: docker info
<ide>
<ide> For example:
<ide>
<del> $ sudo docker info
<del> Containers: 292
<del> Images: 194
<add> $ sudo docker -D info
<add> Containers: 16
<add> Images: 2138
<add> Storage Driver: btrfs
<add> Execution Driver: native-0.1
<add> Kernel Version: 3.12.0-1-amd64
<ide> Debug mode (server): false
<del> Debug mode (client): false
<del> Fds: 22
<del> Goroutines: 67
<del> LXC Version: 0.9.0
<del> EventsListeners: 115
<del> Kernel Version: 3.8.0-33-generic
<del> WARNING: No swap limit support
<del>
<del>When sending issue reports, please use `docker version` and `docker info` to
<add> Debug mode (client): true
<add> Fds: 16
<add> Goroutines: 104
<add> EventsListeners: 0
<add> Init Path: /usr/bin/docker
<add> Sockets: [unix:///var/run/docker.sock tcp://0.0.0.0:4243]
<add> Username: svendowideit
<add> Registry: [https://index.docker.io/v1/]
<add>
<add>The global `-D` option tells all `docker` comands to output debug information.
<add>
<add>When sending issue reports, please use `docker version` and `docker -D info` to
<ide> ensure we know how your setup is configured.
<ide>
<ide> ## inspect
<ide><path>server/server.go
<ide> func (srv *Server) DockerInfo(job *engine.Job) engine.Status {
<ide> v.Set("IndexServerAddress", registry.IndexServerAddress())
<ide> v.Set("InitSha1", dockerversion.INITSHA1)
<ide> v.Set("InitPath", initPath)
<add> v.SetList("Sockets", srv.daemon.Sockets)
<ide> if _, err := v.WriteTo(job.Stdout); err != nil {
<ide> return job.Error(err)
<ide> } | 8 |
Python | Python | add more examples to the `issubdtype` docstring | 3a06142f5e26c6294ffd5fa24cd450addef45e13 | <ide><path>numpy/core/numerictypes.py
<ide> def issubsctype(arg1, arg2):
<ide>
<ide> @set_module('numpy')
<ide> def issubdtype(arg1, arg2):
<del> """
<add> r"""
<ide> Returns True if first argument is a typecode lower/equal in type hierarchy.
<ide>
<add> This is like the builtin :func:`issubclass`, but for `dtype`\ s.
<add>
<ide> Parameters
<ide> ----------
<ide> arg1, arg2 : dtype_like
<del> dtype or string representing a typecode.
<add> `dtype` or object coercible to one
<ide>
<ide> Returns
<ide> -------
<ide> def issubdtype(arg1, arg2):
<ide>
<ide> Examples
<ide> --------
<del> >>> np.issubdtype('S1', np.string_)
<add> `issubdtype` can be used to check the type of arrays:
<add>
<add> >>> ints = np.array([1, 2, 3], dtype=np.int32)
<add> >>> np.issubdtype(ints.dtype, np.integer)
<add> True
<add> >>> np.issubdtype(ints.dtype, np.floating)
<add> False
<add>
<add> >>> floats = np.array([1, 2, 3], dtype=np.float32)
<add> >>> np.issubdtype(floats.dtype, np.integer)
<add> False
<add> >>> np.issubdtype(floats.dtype, np.floating)
<ide> True
<add>
<add> Similar types of different sizes are not subdtypes of each other:
<add>
<ide> >>> np.issubdtype(np.float64, np.float32)
<ide> False
<add> >>> np.issubdtype(np.float32, np.float64)
<add> False
<add>
<add> but both are subtypes of `floating`:
<add>
<add> >>> np.issubdtype(np.float64, np.floating)
<add> True
<add> >>> np.issubdtype(np.float32, np.floating)
<add> True
<add>
<add> For convenience, dtype-like objects are allowed too:
<add>
<add> >>> np.issubdtype('S1', np.string_)
<add> True
<add> >>> np.issubdtype('i4', np.signedinteger)
<add> True
<ide>
<ide> """
<ide> if not issubclass_(arg1, generic): | 1 |
Text | Text | add test case to check country code | 6f628e6133e6876a59faa5140146f67949a6b053 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.md
<ide> assert(telephoneCheck('(555)5(55?)-5555') === false);
<ide> assert(telephoneCheck('55 55-55-555-5') === false);
<ide> ```
<ide>
<add>`telephoneCheck("11 555-555-5555")` should return `false`.
<add>
<add>```js
<add>assert(telephoneCheck('11 555-555-5555') === false);
<add>```
<add>
<ide> # --seed--
<ide>
<ide> ## --seed-contents-- | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.