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 typehints to form widgets | 87879693ddaf91e8030a501f562c958bc516ed15 | <ide><path>src/View/Widget/BasicWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct($templates)
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data += [
<ide> 'name' => '',
<ide> public function render(array $data, ContextInterface $context)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function secureFields(array $data)
<add> public function secureFields(array $data): array
<ide> {
<ide> if (!isset($data['name']) || $data['name'] === '') {
<ide> return [];
<ide><path>src/View/Widget/ButtonWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class ButtonWidget extends BasicWidget
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data += [
<ide> 'text' => '',
<ide><path>src/View/Widget/CheckboxWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class CheckboxWidget extends BasicWidget
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string Generated HTML string.
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data += [
<ide> 'name' => '',
<ide><path>src/View/Widget/DateTimeWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct(StringTemplate $templates, SelectBoxWidget $selectBo
<ide> * @return string A generated select box.
<ide> * @throws \RuntimeException When option data is invalid.
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data = $this->_normalizeData($data);
<ide>
<ide> protected function _deconstructDate($value, $options)
<ide> $validDate = true;
<ide> }
<ide> if ($exists && $value[$key] !== '') {
<del> $dateArray[$key] = str_pad($value[$key], 2, '0', STR_PAD_LEFT);
<add> $dateArray[$key] = str_pad((string)$value[$key], 2, '0', STR_PAD_LEFT);
<ide> }
<ide> }
<ide> if ($validDate) {
<ide> protected function _generateNumbers($start, $end, $options = [])
<ide> * @param array $data The data to render.
<ide> * @return array Array of fields to secure.
<ide> */
<del> public function secureFields(array $data)
<add> public function secureFields(array $data): array
<ide> {
<ide> $data = $this->_normalizeData($data);
<ide>
<ide><path>src/View/Widget/FileWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct($templates)
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string HTML elements.
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data += [
<ide> 'name' => '',
<ide> public function render(array $data, ContextInterface $context)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function secureFields(array $data)
<add> public function secureFields(array $data): array
<ide> {
<ide> $fields = [];
<ide> foreach (['name', 'type', 'tmp_name', 'error', 'size'] as $suffix) {
<ide><path>src/View/Widget/LabelWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct($templates)
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data += [
<ide> 'text' => '',
<ide> public function render(array $data, ContextInterface $context)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function secureFields(array $data)
<add> public function secureFields(array $data): array
<ide> {
<ide> return [];
<ide> }
<ide><path>src/View/Widget/MultiCheckboxWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct($templates, $label)
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data += [
<ide> 'name' => '',
<ide> protected function _isDisabled($key, $disabled)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function secureFields(array $data)
<add> public function secureFields(array $data): array
<ide> {
<ide> return [$data['name']];
<ide> }
<ide><path>src/View/Widget/NestingLabelWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/View/Widget/RadioWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct($templates, $label)
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data += [
<ide> 'name' => '',
<ide> protected function _renderLabel($radio, $label, $input, $context, $escape)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function secureFields(array $data)
<add> public function secureFields(array $data): array
<ide> {
<ide> return [$data['name']];
<ide> }
<ide><path>src/View/Widget/SelectBoxWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class SelectBoxWidget extends BasicWidget
<ide> * @return string A generated select box.
<ide> * @throws \RuntimeException when the name attribute is empty.
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data += [
<ide> 'name' => '',
<ide><path>src/View/Widget/TextareaWidget.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class TextareaWidget extends BasicWidget
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string HTML elements.
<ide> */
<del> public function render(array $data, ContextInterface $context)
<add> public function render(array $data, ContextInterface $context): string
<ide> {
<ide> $data += [
<ide> 'val' => '',
<ide><path>src/View/Widget/WidgetInterface.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> interface WidgetInterface
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string Generated HTML for the widget element.
<ide> */
<del> public function render(array $data, ContextInterface $context);
<add> public function render(array $data, ContextInterface $context): string;
<ide>
<ide> /**
<ide> * Returns a list of fields that need to be secured for
<ide> public function render(array $data, ContextInterface $context);
<ide> * @param array $data The data to render.
<ide> * @return array Array of fields to secure.
<ide> */
<del> public function secureFields(array $data);
<add> public function secureFields(array $data): array;
<ide> }
<ide><path>src/View/Widget/WidgetLocator.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct(StringTemplate $templates, View $view, $widgets = []
<ide> * @param string $file The file to load
<ide> * @return void
<ide> */
<del> public function load($file)
<add> public function load(string $file): void
<ide> {
<ide> $loader = new PhpConfig();
<ide> $widgets = $loader->read($file);
<ide> public function load($file)
<ide> * @return void
<ide> * @throws \RuntimeException When class does not implement WidgetInterface.
<ide> */
<del> public function add(array $widgets)
<add> public function add(array $widgets): void
<ide> {
<ide> foreach ($widgets as $object) {
<ide> if (is_object($object) &&
<ide> public function add(array $widgets)
<ide> * the `_default` widget is undefined.
<ide> *
<ide> * @param string $name The widget name to get.
<del> * @return \Cake\View\Widget\WidgetInterface widget interface class.
<add> * @return \Cake\View\Widget\WidgetInterface|\Cake\View\View WidgetInterface instance.
<add> * or \Cake\View\View instance in case of special name "_view".
<ide> * @throws \RuntimeException when widget is undefined.
<ide> * @throws \ReflectionException
<ide> */
<del> public function get($name)
<add> public function get(string $name)
<ide> {
<ide> if (!isset($this->_widgets[$name]) && empty($this->_widgets['_default'])) {
<ide> throw new RuntimeException(sprintf('Unknown widget "%s"', $name));
<ide> public function get($name)
<ide> *
<ide> * @return void
<ide> */
<del> public function clear()
<add> public function clear(): void
<ide> {
<ide> $this->_widgets = [];
<ide> } | 13 |
Text | Text | add missing parenthesis | b63898bb782661949f8d5c4b29696db533d8e96d | <ide><path>docs/recipes/reducers/SplittingReducerLogic.md
<ide> For clarity, these terms will be used to distinguish between different types of
<ide> - ***root reducer***: the reducer function that is actually passed as the first argument to `createStore`. This is the only part of the reducer logic that _must_ have the `(state, action) -> newState` signature.
<ide> - ***slice reducer***: a reducer that is being used to handle updates to one specific slice of the state tree, usually done by passing it to `combineReducers`
<ide> - ***case function***: a function that is being used to handle the update logic for a specific action. This may actually be a reducer function, or it may require other parameters to do its work properly.
<del>- ***higher-order reducer***: a function that takes a reducer function as an argument, and/or returns a new reducer function as a result (such as `combineReducers`, or `redux-undo`
<add>- ***higher-order reducer***: a function that takes a reducer function as an argument, and/or returns a new reducer function as a result (such as `combineReducers`, or `redux-undo`)
<ide>
<ide> The term "*sub-reducer*" has also been used in various discussions to mean any function that is not the root reducer, although the term is not very precise. Some people may also refer to some functions as "*business logic*" (functions that relate to application-specific behavior) or "*utility functions*" (generic functions that are not application-specific).
<ide> | 1 |
Text | Text | add v3.15.0 to changelog | c76e584adef6a613799e4611499b6078eedafd99 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### v3.15.0-beta.5 (December 4, 2019)
<del>
<del>- [#18582](https://github.com/emberjs/ember.js/pull/18582) [BUGFIX] Ensure `loader.js` is transpiled to the applications specified targets (from `config/targets.js`).
<del>
<del>### v3.15.0-beta.4 (November 25, 2019)
<del>
<del>- [#17834](https://github.com/emberjs/ember.js/pull/17834) [BUGFIX] Prevents autotracking ArrayProxy creation
<del>- [#18554](https://github.com/emberjs/ember.js/pull/18554) [BREAKING BUGFIX] Adds autotracking transaction
<del>
<del>### v3.15.0-beta.3 (November 18, 2019)
<del>
<del>- [#18549](https://github.com/emberjs/ember.js/pull/18549) [BUGFIX] Add component reference to the mouse event handler deprecation warnings
<del>
<del>### v3.15.0-beta.2 (November 11, 2019)
<del>
<del>- [#18539](https://github.com/emberjs/ember.js/pull/18539) [BUGFIX] Add ID to `CapturedRenderNode`
<del>
<del>### v3.15.0-beta.1 (October 31, 2019)
<add>### v3.15.0 (December 9, 2019)
<ide>
<ide> - [#17948](https://github.com/emberjs/ember.js/pull/17948) [DEPRECATION] Deprecate `Component#isVisible` per [RFC #324](https://github.com/emberjs/rfcs/blob/master/text/0324-deprecate-component-isvisible.md).
<ide> - [#18491](https://github.com/emberjs/ember.js/pull/18491) [DEPRECATION] Deprecate `{{partial}}` per [RFC #449](https://github.com/emberjs/rfcs/blob/master/text/0449-deprecate-partials.md).
<del>- [#18441](https://github.com/emberjs/ember.js/pull/18441) [DEPRECATION] Deprecate window.ENV
<add>- [#18441](https://github.com/emberjs/ember.js/pull/18441) [DEPRECATION] Deprecate use of window.ENV to configure boot options
<add>- [#18554](https://github.com/emberjs/ember.js/pull/18554) [BREAKING BUGFIX] Adds autotracking transaction
<add>- [#17834](https://github.com/emberjs/ember.js/pull/17834) [BUGFIX] Prevents autotracking ArrayProxy creation
<ide>
<ide> ### v3.14.3 (December 3, 2019)
<ide> | 1 |
Text | Text | remove reference to mad libs | 6d7b49ffe029c7e2950ef9673459d690a896e4ea | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.md
<ide> assert(
<ide> );
<ide> ```
<ide>
<del>`wordBlanks` should contain all of the words assigned to the variables `myNoun`, `myVerb`, `myAdjective` and `myAdverb` separated by non-word characters (and any additional words in your madlib).
<add>`wordBlanks` should contain all of the words assigned to the variables `myNoun`, `myVerb`, `myAdjective` and `myAdverb` separated by non-word characters (and any additional words of your choice).
<ide>
<ide> ```js
<ide> assert( | 1 |
PHP | PHP | use output buffering instead of a log file | 5f86f594aa09fb6a61e3c5b86bbdf646800cc69a | <ide><path>tests/TestCase/Console/ShellTest.php
<ide> public function testRunCommandHittingTaskInSubcommand()
<ide> */
<ide> public function testDispatchShell()
<ide> {
<del> $this->skipIf(!touch(TEST_APP . 'shell.log'), 'Can\'t write shell test log file');
<ide> $Shell = new TestingDispatchShell();
<add> ob_start();
<ide> $Shell->runCommand(['test_task'], true);
<add> $result = ob_get_clean();
<ide>
<del> $result = file_get_contents(TEST_APP . 'shell.log');
<ide> $expected = <<<TEXT
<ide> <info>Welcome to CakePHP v3.0.1 Console</info>
<ide> I am a test task, I dispatch another Shell
<ide> public function testDispatchShell()
<ide>
<ide> TEXT;
<ide> $this->assertEquals($expected, $result);
<del>
<del> //@codingStandardsIgnoreStart
<del> @unlink(TEST_APP . 'shell.log');
<del> //@codingStandardsIgnoreEnd
<ide> }
<ide>
<ide> /**
<ide><path>tests/test_app/TestApp/Shell/TestingDispatchShell.php
<ide> class TestingDispatchShell extends Shell
<ide> {
<ide>
<del> public $outPath = '';
<del>
<ide> protected function _welcome()
<ide> {
<ide> $this->out(sprintf('<info>Welcome to CakePHP %s Console</info>', 'v' . Configure::version()));
<ide> }
<ide>
<ide> public function out($message = null, $newlines = 1, $level = Shell::NORMAL)
<ide> {
<del> file_put_contents(TEST_APP . 'shell.log', $message . "\n", FILE_APPEND);
<add> echo $message . "\n";
<ide> }
<ide>
<ide> public function testTask() | 2 |
Javascript | Javascript | fix dragcontrols for containers not at (0,0) | 5b1b197305a7bdfa58e118ece1ee7375a6560dbf | <ide><path>examples/js/controls/DragControls.js
<ide> THREE.DragControls = function ( _objects, _camera, _domElement ) {
<ide>
<ide> event.preventDefault();
<ide>
<del> _mouse.x = ( event.clientX / _domElement.clientWidth ) * 2 - 1;
<del> _mouse.y = - ( event.clientY / _domElement.clientHeight ) * 2 + 1;
<add> var rect = _domElement.getBoundingClientRect();
<add>
<add> _mouse.x = ( (event.clientX - rect.left) / rect.width ) * 2 - 1;
<add> _mouse.y = - ( (event.clientY - rect.top) / rect.height ) * 2 + 1;
<ide>
<ide> _raycaster.setFromCamera( _mouse, _camera );
<ide> | 1 |
Text | Text | improve rinfo object documentation | 109bfd21d881f9559d08c1cf5f99822a054ed44f | <ide><path>doc/api/dgram.md
<ide> datagram messages. This occurs as soon as UDP sockets are created.
<ide> added: v0.1.99
<ide> -->
<ide>
<add>The `'message'` event is emitted when a new datagram is available on a socket.
<add>The event handler function is passed two arguments: `msg` and `rinfo`.
<ide> * `msg` {Buffer} - The message
<ide> * `rinfo` {Object} - Remote address information
<del>
<del>The `'message'` event is emitted when a new datagram is available on a socket.
<del>The event handler function is passed two arguments: `msg` and `rinfo`. The
<del>`msg` argument is a [`Buffer`][] and `rinfo` is an object with the sender's
<del>address information provided by the `address`, `family` and `port` properties:
<del>
<del>```js
<del>socket.on('message', (msg, rinfo) => {
<del> console.log('Received %d bytes from %s:%d\n',
<del> msg.length, rinfo.address, rinfo.port);
<del>});
<del>```
<add> * `address` {String} The sender address
<add> * `family` {String} The address family (`'IPv4'` or `'IPv6'`)
<add> * `port` {Number} The sender port
<add> * `size` {Number} The message size
<ide>
<ide> ### socket.addMembership(multicastAddress[, multicastInterface])
<ide> <!-- YAML | 1 |
Mixed | Javascript | add compile time to statistics | e60514aac19986481ae1fa7ecb98e8e9f8554429 | <ide><path>README.md
<ide> else `stats` as json:
<ide> ``` javascript
<ide> {
<ide> hash: "52bd9213...38d",
<add> time: 1234, // in ms
<ide> chunkCount: 2,
<ide> modulesCount: 10,
<ide> modulesIncludingDuplicates: 10,
<ide><path>lib/formatOutput.js
<ide> module.exports = function(stats, options) {
<ide> }
<ide>
<ide> buf.push("Hash: "+c("\033[1m") + stats.hash + c("\033[22m"));
<add> buf.push("Compile Time: "+c("\033[1m") + Math.round(stats.time) + "ms" + c("\033[22m"));
<ide> buf.push("Chunks: "+c("\033[1m") + stats.chunkCount + c("\033[22m"));
<ide> buf.push("Modules: "+c("\033[1m") + stats.modulesCount + c("\033[22m"));
<ide> buf.push("Modules including duplicates: "+c("\033[1m") + stats.modulesIncludingDuplicates + c("\033[22m"));
<ide><path>lib/webpack.js
<ide> module.exports = function(context, moduleName, options, callback) {
<ide> return webpack(context, moduleName, options, callback);
<ide> }
<ide> function webpack(context, moduleName, options, callback) {
<add> var startTime = new Date();
<ide>
<ide> // Defaults
<ide> if(!options.outputJsonpFunction)
<ide> function webpack(context, moduleName, options, callback) {
<ide>
<ide> options.loader = options.loader || {};
<ide> options.loader.emitFile = options.loader.emitFile || function(filename, content) {
<del> fileWrites.push([path.join(options.outputDirectory, filename), content]);
<add> options.internal.fileWrites.push([path.join(options.outputDirectory, filename), content]);
<ide> }
<ide>
<add> options.internal = {};
<add>
<ide> // all writes to files
<ide> // items: [filename, content]
<ide> var fileWrites = [];
<add> options.internal.fileWrites = fileWrites;
<ide>
<ide> // Some status info
<ide> options.events.emit("task", "create ouput directory");
<ide> function webpack(context, moduleName, options, callback) {
<ide> buffer.warnings = depTree.warnings;
<ide> buffer.errors = depTree.errors;
<ide> buffer.fileModules = fileModulesMap;
<add> buffer.time = new Date() - startTime;
<ide> options.events.emit("task-end", "statistics");
<ide> options.events.emit("bundle", buffer);
<ide> callback(null, buffer); | 3 |
PHP | PHP | convert log to use new registry object | 9778b62879b56a910da84b3d79014f0ed95c6bd1 | <ide><path>lib/Cake/Log/Log.php
<ide> protected static function _init() {
<ide> */
<ide> protected static function _loadConfig() {
<ide> $loggers = Configure::read('Log');
<del> foreach ((array)$loggers as $key => $config) {
<del> static::$_registry->load($key, $config);
<add> foreach ((array)$loggers as $name => $properties) {
<add> if (isset($properties['engine'])) {
<add> $properties['className'] = $properties['engine'];
<add> }
<add> static::$_registry->load($name, $properties);
<ide> }
<ide> }
<ide>
<ide> public static function disable($streamName) {
<ide> public static function engine($name, $engine = null) {
<ide> static::_init();
<ide> if ($engine) {
<del> static::$_registry->load($name, $engine);
<add> static::$_registry->add($name, $engine);
<ide> return;
<ide> }
<ide> if (static::$_registry->{$name}) {
<ide> public static function write($level, $message, $scope = array()) {
<ide> $level = static::$_levels[$level];
<ide> }
<ide> $logged = false;
<del> foreach (static::$_registry->enabled() as $streamName) {
<add> foreach (static::$_registry->loaded() as $streamName) {
<ide> $logger = static::$_registry->{$streamName};
<ide> $levels = $scopes = null;
<ide> if ($logger instanceof BaseLog) {
<ide><path>lib/Cake/Log/LogEngineRegistry.php
<ide> use Cake\Core\App;
<ide> use Cake\Error;
<ide> use Cake\Log\LogInterface;
<del>use Cake\Utility\ObjectCollection;
<add>use Cake\Utility\ObjectRegistry;
<ide>
<ide> /**
<ide> * Registry of loaded log engines
<del> *
<del> * @package Cake.Log
<ide> */
<del>class LogEngineRegistry extends ObjectCollection {
<add>class LogEngineRegistry extends ObjectRegistry {
<add>
<ide>
<ide> /**
<del> * Loads/constructs a Log engine.
<add> * Resolve a logger classname.
<ide> *
<del> * @param string $name instance identifier
<del> * @param LogInterface|array $options Setting for the Log Engine, or the log engine
<del> * If a log engine is used, the adapter will be enabled.
<del> * @return BaseLog BaseLog engine instance
<del> * @throws Cake\Error\Exception when logger class does not implement a write method
<add> * Part of the template method for Cake\Utility\ObjectRegistry::load()
<add> *
<add> * @param string $class Partial classname to resolve.
<add> * @return string|false Either the correct classname or false.
<ide> */
<del> public function load($name, $options = array()) {
<del> $logger = false;
<del> if ($options instanceof LogInterface) {
<del> $enable = true;
<del> $logger = $options;
<del> $options = null;
<del> }
<del> if (is_array($options)) {
<del> $enable = isset($options['enabled']) ? $options['enabled'] : true;
<del> $logger = $this->_getLogger($options);
<del> }
<del> if (!$logger instanceof LogInterface) {
<del> throw new Error\Exception(sprintf(
<del> __d('cake_dev', 'logger class %s is not an instance of Cake\Log\LogInterface.'), $name
<del> ));
<del> }
<del> $this->_loaded[$name] = $logger;
<del> if ($enable) {
<del> $this->enable($name);
<del> }
<del> return $logger;
<add> protected function _resolveClassName($class) {
<add> return App::classname($class, 'Log/Engine', 'Log');
<ide> }
<ide>
<ide> /**
<del> * Attempts to import a logger class from the various paths it could be on.
<del> * Checks that the logger class implements a write method as well.
<add> * Throws an exception when a logger is missing.
<ide> *
<del> * @param array $options The configuration options to load a logger with.
<del> * @return false|LogInterface boolean false on any failures, log adapter interface on success
<add> * Part of the template method for Cake\Utility\ObjectRegistry::load()
<add> *
<add> * @param string $class The classname that is missing.
<add> * @param string $plugin The plugin the logger is missing in.
<ide> * @throws Cake\Error\Exception
<ide> */
<del> protected static function _getLogger($options) {
<del> $name = isset($options['engine']) ? $options['engine'] : null;
<del> unset($options['engine']);
<del> $class = App::classname($name, 'Log/Engine', 'Log');
<del> if (!$class) {
<del> throw new Error\Exception(__d('cake_dev', 'Could not load class %s', $name));
<add> protected function _throwMissingClassError($class, $plugin) {
<add> throw new Error\Exception(__d('cake_dev', 'Could not load class %s', $class));
<add> }
<add>
<add>/**
<add> * Create the logger instance.
<add> *
<add> * Part of the template method for Cake\Utility\ObjectRegistry::load()
<add> * @param string $class The classname that is missing.
<add> * @param array $settings An array of settings to use for the logger.
<add> * @return LogEngine The constructed logger class.
<add> */
<add> protected function _create($class, $settings) {
<add> $instance = new $class($settings);
<add> $this->_checkInstance($instance);
<add> return $instance;
<add> }
<add>
<add>/**
<add> * Check an instance to see if it implements the LogInterface.
<add> *
<add> * @param mixed $instance The instance to check.
<add> * @return void
<add> * @throws Cake\Error\Exception when an object doesn't implement
<add> * the correct interface.
<add> */
<add> protected function _checkInstance($instance) {
<add> if ($instance instanceof LogInterface) {
<add> return;
<ide> }
<del> $logger = new $class($options);
<del> return $logger;
<add> throw new Error\Exception(__d(
<add> 'cake_dev',
<add> 'Loggers must implement Cake\Log\LogInterface.'
<add> ));
<add> }
<add>
<add>/**
<add> * Add a logger into a given name.
<add> *
<add> * @param string $name The name of the logger.
<add> * @param Cake\Log\LogInterface $instance A logger implementing LogInterface.
<add> */
<add> public function add($name, $instance) {
<add> $this->_checkInstance($instance);
<add> $this->_loaded[$name] = $instance;
<add> }
<add>
<add>/**
<add> * Remove a single logger from the registry.
<add> *
<add> * @param string $name The logger name.
<add> * @return void
<add> */
<add> public function unload($name) {
<add> unset($this->_loaded[$name]);
<ide> }
<ide>
<ide> } | 2 |
Text | Text | fix indent on as changelog [ci skip] | aaa5463cc0d81e400ddfb4fdacc0caee319fd587 | <ide><path>activesupport/CHANGELOG.md
<ide>
<ide> Imported from https://github.com/37signals/concerning#readme
<ide>
<del> class Todo < ActiveRecord::Base
<del> concerning :EventTracking do
<del> included do
<del> has_many :events
<del> end
<del>
<del> def latest_event
<del> ...
<del> end
<add> class Todo < ActiveRecord::Base
<add> concerning :EventTracking do
<add> included do
<add> has_many :events
<add> end
<ide>
<del> private
<del> def some_internal_method
<add> def latest_event
<ide> ...
<ide> end
<del> end
<ide>
<del> concerning :Trashable do
<del> def trashed?
<del> ...
<add> private
<add> def some_internal_method
<add> ...
<add> end
<ide> end
<ide>
<del> def latest_event
<del> super some_option: true
<add> concerning :Trashable do
<add> def trashed?
<add> ...
<add> end
<add>
<add> def latest_event
<add> super some_option: true
<add> end
<ide> end
<ide> end
<del> end
<ide>
<ide> is equivalent to defining these modules inline, extending them into
<ide> concerns, then mixing them in to the class. | 1 |
Go | Go | support zstd with skippable frame | 23abee412ba02db8f322ae67687cd2e0c6af0c1d | <ide><path>pkg/archive/archive.go
<ide> import (
<ide> "compress/bzip2"
<ide> "compress/gzip"
<ide> "context"
<add> "encoding/binary"
<ide> "fmt"
<ide> "io"
<ide> "os"
<ide> func IsArchivePath(path string) bool {
<ide> return err == nil
<ide> }
<ide>
<add>const (
<add> zstdMagicSkippableStart = 0x184D2A50
<add> zstdMagicSkippableMask = 0xFFFFFFF0
<add>)
<add>
<add>var (
<add> bzip2Magic = []byte{0x42, 0x5A, 0x68}
<add> gzipMagic = []byte{0x1F, 0x8B, 0x08}
<add> xzMagic = []byte{0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}
<add> zstdMagic = []byte{0x28, 0xb5, 0x2f, 0xfd}
<add>)
<add>
<add>type matcher = func([]byte) bool
<add>
<add>func magicNumberMatcher(m []byte) matcher {
<add> return func(source []byte) bool {
<add> return bytes.HasPrefix(source, m)
<add> }
<add>}
<add>
<add>// zstdMatcher detects zstd compression algorithm.
<add>// Zstandard compressed data is made of one or more frames.
<add>// There are two frame formats defined by Zstandard: Zstandard frames and Skippable frames.
<add>// See https://tools.ietf.org/id/draft-kucherawy-dispatch-zstd-00.html#rfc.section.2 for more details.
<add>func zstdMatcher() matcher {
<add> return func(source []byte) bool {
<add> if bytes.HasPrefix(source, zstdMagic) {
<add> // Zstandard frame
<add> return true
<add> }
<add> // skippable frame
<add> if len(source) < 8 {
<add> return false
<add> }
<add> // magic number from 0x184D2A50 to 0x184D2A5F.
<add> if binary.LittleEndian.Uint32(source[:4])&zstdMagicSkippableMask == zstdMagicSkippableStart {
<add> return true
<add> }
<add> return false
<add> }
<add>}
<add>
<ide> // DetectCompression detects the compression algorithm of the source.
<ide> func DetectCompression(source []byte) Compression {
<del> for compression, m := range map[Compression][]byte{
<del> Bzip2: {0x42, 0x5A, 0x68},
<del> Gzip: {0x1F, 0x8B, 0x08},
<del> Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00},
<del> Zstd: {0x28, 0xb5, 0x2f, 0xfd},
<del> } {
<del> if bytes.HasPrefix(source, m) {
<add> compressionMap := map[Compression]matcher{
<add> Bzip2: magicNumberMatcher(bzip2Magic),
<add> Gzip: magicNumberMatcher(gzipMagic),
<add> Xz: magicNumberMatcher(xzMagic),
<add> Zstd: zstdMatcher(),
<add> }
<add> for _, compression := range []Compression{Bzip2, Gzip, Xz, Zstd} {
<add> fn := compressionMap[compression]
<add> if fn(source) {
<ide> return compression
<ide> }
<ide> }
<ide><path>pkg/archive/archive_test.go
<ide> func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error
<ide> return ChangesDirs(origin, tmp)
<ide> }
<ide>
<add>func TestDetectCompressionZstd(t *testing.T) {
<add> // test zstd compression without skippable frames.
<add> compressedData := []byte{
<add> 0x28, 0xb5, 0x2f, 0xfd, // magic number of Zstandard frame: 0xFD2FB528
<add> 0x04, 0x00, 0x31, 0x00, 0x00, // frame header
<add> 0x64, 0x6f, 0x63, 0x6b, 0x65, 0x72, // data block "docker"
<add> 0x16, 0x0e, 0x21, 0xc3, // content checksum
<add> }
<add> compression := DetectCompression(compressedData)
<add> if compression != Zstd {
<add> t.Fatal("Unexpected compression")
<add> }
<add> // test zstd compression with skippable frames.
<add> hex := []byte{
<add> 0x50, 0x2a, 0x4d, 0x18, // magic number of skippable frame: 0x184D2A50 to 0x184D2A5F
<add> 0x04, 0x00, 0x00, 0x00, // frame size
<add> 0x5d, 0x00, 0x00, 0x00, // user data
<add> 0x28, 0xb5, 0x2f, 0xfd, // magic number of Zstandard frame: 0xFD2FB528
<add> 0x04, 0x00, 0x31, 0x00, 0x00, // frame header
<add> 0x64, 0x6f, 0x63, 0x6b, 0x65, 0x72, // data block "docker"
<add> 0x16, 0x0e, 0x21, 0xc3, // content checksum
<add> }
<add> compression = DetectCompression(hex)
<add> if compression != Zstd {
<add> t.Fatal("Unexpected compression")
<add> }
<add>}
<add>
<ide> func TestTarUntar(t *testing.T) {
<ide> origin, err := os.MkdirTemp("", "docker-test-untar-origin")
<ide> if err != nil { | 2 |
Javascript | Javascript | use strict comparison for isselected with selectas | 9e305948e4965fb86b0c79985dc6e8c59a9c66af | <ide><path>src/ng/directive/select.js
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> if (multiple) {
<ide> return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));
<ide> } else {
<del> return viewValue == callExpression(compareValueFn, key, value);
<add> return viewValue === callExpression(compareValueFn, key, value);
<ide> }
<ide> };
<ide> }
<ide><path>test/ng/directive/selectSpec.js
<ide> describe('select', function() {
<ide> expect(element.val()).toEqual('?');
<ide> expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
<ide> });
<add>
<add>
<add> it('should select the correct option for selectAs and falsy values', function() {
<add> scope.values = [{value: 0, label: 'zero'}, {value: 1, label: 'one'}];
<add> scope.selected = '';
<add> createSelect({
<add> 'ng-model': 'selected',
<add> 'ng-options': 'option.value as option.label for option in values'
<add> });
<add>
<add> var option = element.find('option').eq(0);
<add> expect(option.val()).toBe('?');
<add> expect(option.text()).toBe('');
<add> });
<ide> });
<ide>
<ide> | 2 |
Ruby | Ruby | pass the starting env and session to build_request | 3cae6bc5fc8765b5a06fd3d123528159d1f850b7 | <ide><path>actionpack/lib/action_controller/test_case.rb
<ide> def setup_controller_request_and_response
<ide> end
<ide> end
<ide>
<del> @request = build_request
<add> @request = build_request({}, TestRequest.new_session)
<ide> @request.env["rack.request.cookie_hash"] = {}.with_indifferent_access
<ide> @response = build_response @response_klass
<ide> @response.request = @request
<ide> def setup_controller_request_and_response
<ide> end
<ide> end
<ide>
<del> def build_request
<del> TestRequest.new({}, TestRequest.new_session)
<add> def build_request(env, session)
<add> TestRequest.new(env, session)
<ide> end
<ide>
<ide> def build_response(klass)
<ide><path>actionpack/lib/action_dispatch/testing/assertions/routing.rb
<ide> def recognized_request_for(path, extras = {}, msg)
<ide> end
<ide>
<ide> # Assume given controller
<del> request = build_request
<add> request = build_request({}, ActionController::TestRequest.new_session)
<ide>
<ide> if path =~ %r{://}
<ide> fail_on(URI::InvalidURIError, msg) do | 2 |
Go | Go | remove rules for linkgraph.db sqlite database | e553a03627c20cbedb97f5f8cb4b02a0ff47c54e | <ide><path>contrib/apparmor/template.go
<ide> profile /usr/bin/docker (attach_disconnected, complain) {
<ide> capability,
<ide> owner /** rw,
<ide> @{DOCKER_GRAPH_PATH}/** rwl,
<del> @{DOCKER_GRAPH_PATH}/linkgraph.db k,
<ide> @{DOCKER_GRAPH_PATH}/network/files/boltdb.db k,
<ide> @{DOCKER_GRAPH_PATH}/network/files/local-kv.db k,
<del> @{DOCKER_GRAPH_PATH}/[0-9]*.[0-9]*/linkgraph.db k,
<ide>
<ide> # For non-root client use:
<ide> /dev/urandom r, | 1 |
Javascript | Javascript | redirect old wiki urls to root of forum | 88557bfa4be92b7f966d3025473f28bda1d9cb70 | <ide><path>server/boot/t-wiki.js
<ide> module.exports = function(app) {
<ide> var router = app.loopback.Router();
<del> router.get('/wiki/*', showWiki);
<del> router.get('/wiki', (req, res) => res.redirect(301, '/wiki/en/'));
<add> router.get('/wiki/*', showForum);
<ide>
<ide> app.use(router);
<ide>
<del> function showWiki(req, res) {
<del> res.render(
<del> 'wiki/show',
<del> {
<del> title: 'Wiki | Free Code Camp',
<del> path: req.path.replace(/^\/wiki/, '')
<del> }
<add> function showForum(req, res) {
<add> res.redirect(
<add> 'http://forum.freecodecamp.com/'
<ide> );
<ide> }
<ide> }; | 1 |
Python | Python | clarify documentation for np.fft.ifft | 44293bb2834f2a4495dacee4ba112a3bfeef5b0c | <ide><path>numpy/fft/fftpack.py
<ide> def ifft(a, n=None, axis=-1, norm=None):
<ide> see `numpy.fft`.
<ide>
<ide> The input should be ordered in the same way as is returned by `fft`,
<del> i.e., ``a[0]`` should contain the zero frequency term,
<del> ``a[1:n/2]`` should contain the positive-frequency terms, and
<del> ``a[n/2+1:]`` should contain the negative-frequency terms, in order of
<del> decreasingly negative frequency. For an even number of input points,
<del> ``A[n/2]`` represents both positive and negative Nyquist frequency.
<del> See `numpy.fft` for details.
<add> i.e.,
<add>
<add> * ``a[0]`` should contain the zero frequency term,
<add> * ``a[1:n//2]`` should contain the positive-frequency terms,
<add> * ``a[n//2 + 1:]`` should contain the negative-frequency terms, in
<add> increasing order starting from the most negative frequency.
<add>
<add> For an even number of input points, ``A[n//2]`` represents the sum of
<add> the values at the positive and negative Nyquist frequencies, as the two
<add> are aliased together. See `numpy.fft` for details.
<ide>
<ide> Parameters
<ide> ----------
<ide> def ifft(a, n=None, axis=-1, norm=None):
<ide> >>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,)))
<ide> >>> s = np.fft.ifft(n)
<ide> >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
<del> [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]
<add> ...
<ide> >>> plt.legend(('real', 'imaginary'))
<del> <matplotlib.legend.Legend object at 0x...>
<add> ...
<ide> >>> plt.show()
<ide>
<ide> """ | 1 |
Python | Python | remove get_session() call in multi_gpu_utils.py | 408a344e50ef809812febc6e8dcabd34cfc11c60 | <ide><path>keras/utils/multi_gpu_utils.py
<ide>
<ide>
<ide> def _get_available_devices():
<del> return [x.name for x in K.get_session().list_devices()]
<add> return K.tensorflow_backend._get_available_gpus()
<ide>
<ide>
<ide> def _normalize_device_name(name):
<ide> def multi_gpu_model(model, gpus=None, cpu_merge=True, cpu_relocation=False):
<ide> if not gpus:
<ide> # Using all visible GPUs when not specifying `gpus`
<ide> # e.g. CUDA_VISIBLE_DEVICES=0,2 python keras_mgpu.py
<del> gpus = len([x for x in available_devices if 'gpu' in x])
<add> gpus = len(available_devices)
<ide>
<ide> if isinstance(gpus, (list, tuple)):
<ide> if len(gpus) <= 1: | 1 |
Python | Python | fix classifier dropout in albertformultiplechoice | 3f52c685c135394e0a238bc821460ad4df891bd7 | <ide><path>src/transformers/models/albert/modeling_albert.py
<ide> def __init__(self, config):
<ide> super().__init__(config)
<ide>
<ide> self.albert = AlbertModel(config)
<del> self.dropout = nn.Dropout(config.hidden_dropout_prob)
<add> self.dropout = nn.Dropout(config.classifier_dropout_prob)
<ide> self.classifier = nn.Linear(config.hidden_size, 1)
<ide>
<ide> self.init_weights() | 1 |
Python | Python | add tests for inputs set dynamically | 13548e8b212b504c9f506495b01855de6d9f6117 | <ide><path>tests/keras/engine/test_training.py
<ide>
<ide> import keras
<ide> from keras import losses
<del>from keras.layers import Dense, Dropout, Conv2D
<add>from keras.layers import Activation, Dense, Dropout, Conv2D
<ide> from keras.engine import Input
<ide> from keras.engine.training import Model
<ide> from keras.engine import training_utils
<ide> def prepare_simple_model(input_tensor, loss_name, target):
<ide> 'channels_first and channels_last.'))
<ide>
<ide>
<add>@keras_test
<add>def test_dynamic_set_inputs():
<add> model = Sequential()
<add> model.add(Dense(16, input_dim=32))
<add> model.add(Activation('relu'))
<add>
<add> model2 = Sequential()
<add> model2.add(model.layers[-1])
<add> model2.add(Dense(8))
<add> preds2 = model2.predict([np.random.random((1, 32))])
<add> assert preds2.shape == (1, 8)
<add>
<add> model3 = Model(inputs=model.inputs, outputs=model.outputs)
<add> model3.inputs = None
<add> model3._set_inputs(model.inputs)
<add> preds3 = model3.predict([np.random.random((1, 32))])
<add> assert preds3.shape == (1, 16)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> pytest.main([__file__]) | 1 |
Ruby | Ruby | add test for json-based cask config loader | dd3267ece0b2252c13f23e10a8d905f96f067406 | <ide><path>Library/Homebrew/cask/config.rb
<ide> def self.clear
<ide>
<ide> def self.for_cask(cask)
<ide> if cask.config_path.exist?
<del> from_file(cask.config_path)
<add> from_json(File.read(cask.config_path))
<ide> else
<ide> global
<ide> end
<ide> end
<ide>
<del> def self.from_file(path)
<add> def self.from_json(json)
<ide> config = begin
<del> JSON.parse(File.read(path))
<add> JSON.parse(json)
<ide> rescue JSON::ParserError => e
<ide> raise e, "Cannot parse #{path}: #{e}", e.backtrace
<ide> end
<ide><path>Library/Homebrew/test/cask/config_spec.rb
<ide> describe Cask::Config, :cask do
<ide> subject(:config) { described_class.new }
<ide>
<add> describe "::from_json" do
<add> it "deserializes a configuration in JSON format" do
<add> config = described_class.from_json <<~EOS
<add> {
<add> "default": {
<add> "appdir": "/path/to/apps"
<add> },
<add> "env": {},
<add> "explicit": {}
<add> }
<add> EOS
<add> expect(config.appdir).to eq(Pathname("/path/to/apps"))
<add> end
<add> end
<add>
<ide> describe "#default" do
<ide> it "returns the default directories" do
<ide> expect(config.default[:appdir]).to eq(Pathname(TEST_TMPDIR).join("cask-appdir")) | 2 |
Text | Text | update documentation for imagedatagenerator | 98b95762b63598e7d69410d8b6fbd69013377b1e | <ide><path>docs/templates/preprocessing/image.md
<ide> keras.preprocessing.image.ImageDataGenerator(featurewise_center=False,
<ide> horizontal_flip=False,
<ide> vertical_flip=False,
<ide> rescale=None,
<add> preprocessing_function=None,
<ide> data_format=K.image_data_format())
<ide> ```
<ide>
<ide> Generate batches of tensor image data with real-time data augmentation. The data
<ide> - __rescale__: rescaling factor. Defaults to None. If None or 0, no rescaling is applied,
<ide> otherwise we multiply the data by the value provided (before applying
<ide> any other transformation).
<add> - __preprocessing_function__: function that will be implied on each input.
<add> The function will run before any other modification on it.
<add> The function should take one argument:
<add> one image (Numpy tensor with rank 3),
<add> and should output a Numpy tensor with the same shape.
<ide> - _data_format_: One of {"channels_first", "channels_last"}.
<ide> "channels_last" mode means that the images should have shape `(samples, height, width, channels)`,
<ide> "channels_first" mode means that the images should have shape `(samples, channels, height, width)`. | 1 |
Ruby | Ruby | remove unused hash.ruby2_keywords_hash? backport | dce43bb01d85d09c0f7423719b1052d59a6ab3b0 | <ide><path>activejob/lib/active_job/arguments.rb
<ide> def deserialize(arguments)
<ide> private_constant :PERMITTED_TYPES, :RESERVED_KEYS, :GLOBALID_KEY,
<ide> :SYMBOL_KEYS_KEY, :RUBY2_KEYWORDS_KEY, :WITH_INDIFFERENT_ACCESS_KEY
<ide>
<del> unless Hash.respond_to?(:ruby2_keywords_hash?) && Hash.respond_to?(:ruby2_keywords_hash)
<del> using Module.new {
<del> refine Hash do
<del> class << Hash
<del> def ruby2_keywords_hash?(hash)
<del> !new(*[hash]).default.equal?(hash)
<del> end
<del>
<del> def ruby2_keywords_hash(hash)
<del> _ruby2_keywords_hash(**hash)
<del> end
<del>
<del> private
<del> def _ruby2_keywords_hash(*args)
<del> args.last
<del> end
<del> ruby2_keywords(:_ruby2_keywords_hash)
<del> end
<del> end
<del> }
<del> end
<del>
<ide> def serialize_argument(argument)
<ide> case argument
<ide> when *PERMITTED_TYPES | 1 |
Text | Text | update active record changelog for | db8460ca0f1131ac322f708063b63586b008ec69 | <ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Rails now raise an exception when you're trying to run a migration that has an invalid
<add> file name. Only lower case letters, numbers, and '_' are allowed in migration's file name.
<add> Please see #7419 for more details.
<add>
<add> *Jan Bernacki*
<add>
<ide> * Fix bug when call `store_accessor` multiple times.
<ide> Fixes #7532.
<ide> | 1 |
PHP | PHP | correct exception handler doc | 846f7a193a6c4ff92b6595596c9bbcb3cf8c426e | <ide><path>app/Exceptions/Handler.php
<ide> class Handler extends ExceptionHandler
<ide> *
<ide> * @param \Exception $exception
<ide> * @return void
<add> *
<add> * @throws \Exception
<ide> */
<ide> public function report(Exception $exception)
<ide> {
<ide> public function report(Exception $exception)
<ide> *
<ide> * @param \Illuminate\Http\Request $request
<ide> * @param \Exception $exception
<del> * @return \Illuminate\Http\Response
<add> * @return \Symfony\Component\HttpFoundation\Response
<add> *
<add> * @throws \Exception
<ide> */
<ide> public function render($request, Exception $exception)
<ide> { | 1 |
Text | Text | improve wording and style of buffer docs | 87a097da51a0b113975f4a4672656db3b1fc5e15 | <ide><path>doc/api/buffer.md
<ide> resized.
<ide> The `Buffer` class is a global within Node.js, making it unlikely that one
<ide> would need to ever use `require('buffer').Buffer`.
<ide>
<add>Examples:
<add>
<ide> ```js
<ide> // Creates a zero-filled Buffer of length 10.
<ide> const buf1 = Buffer.alloc(10);
<ide> validate the input arguments passed to `new Buffer()`, or that fail to
<ide> appropriately initialize newly allocated `Buffer` content, can inadvertently
<ide> introduce security and reliability issues into their code.
<ide>
<del>To make the creation of `Buffer` objects more reliable and less error prone,
<add>To make the creation of `Buffer` instances more reliable and less error prone,
<ide> the various forms of the `new Buffer()` constructor have been **deprecated**
<ide> and replaced by separate `Buffer.from()`, [`Buffer.alloc()`], and
<ide> [`Buffer.allocUnsafe()`] methods.
<ide> impact* on performance. Use of the `--zero-fill-buffers` option is recommended
<ide> only when necessary to enforce that newly allocated `Buffer` instances cannot
<ide> contain potentially sensitive data.
<ide>
<add>Example:
<add>
<ide> ```txt
<ide> $ node --zero-fill-buffers
<ide> > Buffer.allocUnsafe(5);
<ide> vulnerabilities into an application.
<ide>
<ide> ## Buffers and Character Encodings
<ide>
<del>Buffers are commonly used to represent sequences of encoded characters
<del>such as UTF8, UCS2, Base64 or even Hex-encoded data. It is possible to
<del>convert back and forth between Buffers and ordinary JavaScript string objects
<del>by using an explicit encoding method.
<add>`Buffer` instances are commonly used to represent sequences of encoded characters
<add>such as UTF-8, UCS2, Base64 or even Hex-encoded data. It is possible to
<add>convert back and forth between `Buffer` instances and ordinary JavaScript strings
<add>by using an explicit character encoding.
<add>
<add>Example:
<ide>
<ide> ```js
<ide> const buf = Buffer.from('hello world', 'ascii');
<ide> console.log(buf.toString('base64'));
<ide>
<ide> The character encodings currently supported by Node.js include:
<ide>
<del>* `'ascii'` - for 7-bit ASCII data only. This encoding method is very fast and
<del> will strip the high bit if set.
<add>* `'ascii'` - for 7-bit ASCII data only. This encoding is fast and will strip
<add> the high bit if set.
<ide>
<ide> * `'utf8'` - Multibyte encoded Unicode characters. Many web pages and other
<ide> document formats use UTF-8.
<ide> The character encodings currently supported by Node.js include:
<ide>
<ide> * `'ucs2'` - Alias of `'utf16le'`.
<ide>
<del>* `'base64'` - Base64 string encoding. When creating a buffer from a string,
<add>* `'base64'` - Base64 encoding. When creating a `Buffer` from a string,
<ide> this encoding will also correctly accept "URL and Filename Safe Alphabet" as
<ide> specified in [RFC4648, Section 5].
<ide>
<ide> * `'latin1'` - A way of encoding the `Buffer` into a one-byte encoded string
<ide> (as defined by the IANA in [RFC1345],
<ide> page 63, to be the Latin-1 supplement block and C0/C1 control codes).
<ide>
<del>* `'binary'` - Alias for `latin1`.
<add>* `'binary'` - Alias for `'latin1'`.
<ide>
<ide> * `'hex'` - Encode each byte as two hexadecimal characters.
<ide>
<ide> _Note_: Today's browsers follow the [WHATWG spec] which aliases both 'latin1' and
<del>ISO-8859-1 to Windows-1252. This means that while doing something like `http.get()`,
<add>ISO-8859-1 to win-1252. This means that while doing something like `http.get()`,
<ide> if the returned charset is one of those listed in the WHATWG spec it's possible
<del>that the server actually returned `win-1252` encoded data, and using `latin1`
<del>encoding may incorrectly decode the graphical characters.
<add>that the server actually returned win-1252-encoded data, and using `'latin1'`
<add>encoding may incorrectly decode the characters.
<ide>
<ide> ## Buffers and TypedArray
<ide>
<ide> elements, and not as a byte array of the target type. That is,
<ide> It is possible to create a new `Buffer` that shares the same allocated memory as
<ide> a [`TypedArray`] instance by using the TypeArray object's `.buffer` property.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const arr = new Uint16Array(2);
<ide>
<ide> Note that when creating a `Buffer` using a [`TypedArray`]'s `.buffer`, it is
<ide> possible to use only a portion of the underlying [`ArrayBuffer`] by passing in
<ide> `byteOffset` and `length` parameters.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const arr = new Uint16Array(20);
<ide> const buf = Buffer.from(arr.buffer, 0, 16);
<ide> function:
<ide>
<ide> ## Buffers and ES6 iteration
<ide>
<del>Buffers can be iterated over using the ECMAScript 2015 (ES6) `for..of` syntax:
<add>`Buffer` instances can be iterated over using the ECMAScript 2015 (ES6) `for..of`
<add>syntax.
<add>
<add>Example:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([1, 2, 3]);
<ide> Additionally, the [`buf.values()`], [`buf.keys()`], and
<ide>
<ide> ## Class: Buffer
<ide>
<del>The Buffer class is a global type for dealing with binary data directly.
<add>The `Buffer` class is a global type for dealing with binary data directly.
<ide> It can be constructed in a variety of ways.
<ide>
<ide> ### new Buffer(array)
<ide> deprecated: v6.0.0
<ide>
<ide> * `array` {Array}
<ide>
<del>Allocates a new Buffer using an `array` of octets.
<add>Allocates a new `Buffer` using an `array` of octets.
<add>
<add>Example:
<ide>
<ide> ```js
<ide> // Creates a new Buffer containing the ASCII bytes of the string 'buffer'
<ide> deprecated: v6.0.0
<ide>
<ide> Copies the passed `buffer` data onto a new `Buffer` instance.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const buf1 = new Buffer('buffer');
<ide> const buf2 = new Buffer(buf1);
<ide> the newly created `Buffer` will share the same allocated memory as the
<ide> The optional `byteOffset` and `length` arguments specify a memory range within
<ide> the `arrayBuffer` that will be shared by the `Buffer`.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const arr = new Uint16Array(2);
<ide>
<ide> created in this way is *not initialized*. The contents of a newly created `Buffe
<ide> are unknown and *could contain sensitive data*. Use [`buf.fill(0)`][`buf.fill()`]
<ide> to initialize a `Buffer` to zeroes.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const buf = new Buffer(5);
<ide>
<ide> deprecated: v6.0.0
<ide> Creates a new Buffer containing the given JavaScript string `str`. If
<ide> provided, the `encoding` parameter identifies the strings character encoding.
<ide>
<add>Examples:
<add>
<ide> ```js
<ide> const buf1 = new Buffer('this is a tést');
<ide>
<ide> added: v5.10.0
<ide> Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
<ide> `Buffer` will be *zero-filled*.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const buf = Buffer.alloc(5);
<ide>
<ide> be created if a `size` less than or equal to 0 is specified.
<ide> If `fill` is specified, the allocated `Buffer` will be initialized by calling
<ide> [`buf.fill(fill)`][`buf.fill()`].
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const buf = Buffer.alloc(5, 'a');
<ide>
<ide> console.log(buf);
<ide> If both `fill` and `encoding` are specified, the allocated `Buffer` will be
<ide> initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
<ide>
<ide> added: v5.10.0
<ide>
<ide> * `size` {Number}
<ide>
<del>Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
<add>Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
<ide> be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
<ide> architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
<ide> thrown. A zero-length Buffer will be created if a `size` less than or equal to
<ide> initialized*. The contents of the newly created `Buffer` are unknown and
<ide> *may contain sensitive data*. Use [`buf.fill(0)`][`buf.fill()`] to initialize such
<ide> `Buffer` instances to zeroes.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(5);
<ide>
<ide> value of `Buffer.poolSize` is `8192` but can be modified.
<ide>
<ide> Use of this pre-allocated internal memory pool is a key difference between
<ide> calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
<del>Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer
<add>Specifically, `Buffer.alloc(size, fill)` will *never* use the internal `Buffer`
<ide> pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
<ide> Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The
<ide> difference is subtle but can be important when an application requires the
<ide> added: v5.10.0
<ide>
<ide> * `size` {Number}
<ide>
<del>Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
<add>Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
<ide> `size` must be less than or equal to the value of
<ide> `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
<ide> `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
<ide> initialized*. The contents of the newly created `Buffer` are unknown and
<ide> When using [`Buffer.allocUnsafe()`] to allocate new `Buffer` instances,
<ide> allocations under 4KB are, by default, sliced from a single pre-allocated
<ide> `Buffer`. This allows applications to avoid the garbage collection overhead of
<del>creating many individually allocated Buffers. This approach improves both
<del>performance and memory usage by eliminating the need to track and cleanup as
<add>creating many individually allocated `Buffer` instances. This approach improves
<add>both performance and memory usage by eliminating the need to track and cleanup as
<ide> many `Persistent` objects.
<ide>
<ide> However, in the case where a developer may need to retain a small chunk of
<ide> memory from a pool for an indeterminate amount of time, it may be appropriate
<del>to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then
<add>to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` then
<ide> copy out the relevant bits.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> // Need to keep around a few small chunks of memory
<ide> const store = [];
<ide> Compares `buf1` to `buf2` typically for the purpose of sorting arrays of
<ide> `Buffer` instances. This is equivalent to calling
<ide> [`buf1.compare(buf2)`][`buf.compare()`].
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const buf1 = Buffer.from('1234');
<ide> const buf2 = Buffer.from('0123');
<ide> added: v0.7.11
<ide> when concatenated
<ide> * Return: {Buffer}
<ide>
<del>Returns a new Buffer which is the result of concatenating all the Buffers in
<del>the `list` together.
<add>Returns a new `Buffer` which is the result of concatenating all the `Buffer`
<add>instances in the `list` together.
<ide>
<ide> If the list has no items, or if the `totalLength` is 0, then a new zero-length
<del>Buffer is returned.
<add>`Buffer` is returned.
<ide>
<del>If `totalLength` is not provided, it is calculated from the Buffers in the
<del>`list`. This, however, adds an additional loop to the function, so it is faster
<del>to provide the length explicitly.
<add>If `totalLength` is not provided, it is calculated from the `Buffer` instances
<add>in `list`. This however causes an additional loop to be executed in order to
<add>calculate the `totalLength`, so it is faster to provide the length explicitly if
<add>it is already known.
<ide>
<del>Example: build a single Buffer from a list of three Buffers:
<add>Example: Create a single `Buffer` from a list of three `Buffer` instances
<ide>
<ide> ```js
<ide> const buf1 = Buffer.alloc(10);
<ide> added: v3.0.0
<ide>
<ide> Allocates a new `Buffer` using an `array` of octets.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> // Creates a new Buffer containing ASCII bytes of the string 'buffer'
<ide> const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
<ide> When passed a reference to the `.buffer` property of a [`TypedArray`] instance,
<ide> the newly created `Buffer` will share the same allocated memory as the
<ide> [`TypedArray`].
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const arr = new Uint16Array(2);
<ide>
<ide> console.log(buf);
<ide> The optional `byteOffset` and `length` arguments specify a memory range within
<ide> the `arrayBuffer` that will be shared by the `Buffer`.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const ab = new ArrayBuffer(10);
<ide> const buf = Buffer.from(ab, 0, 2);
<ide> added: v3.0.0
<ide>
<ide> Copies the passed `buffer` data onto a new `Buffer` instance.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const buf1 = Buffer.from('buffer');
<ide> const buf2 = Buffer.from(buf1);
<ide> Creates a new `Buffer` containing the given JavaScript string `str`. If
<ide> provided, the `encoding` parameter identifies the character encoding.
<ide> If not provided, `encoding` defaults to `'utf8'`.
<ide>
<add>Examples:
<add>
<ide> ```js
<ide> const buf1 = Buffer.from('this is a tést');
<ide>
<ide> A `TypeError` will be thrown if `str` is not a string.
<ide> * `obj` {Object}
<ide> * Return: {Boolean}
<ide>
<del>Returns 'true' if `obj` is a Buffer.
<add>Returns `true` if `obj` is a `Buffer`, `false` otherwise.
<ide>
<ide> ### Class Method: Buffer.isEncoding(encoding)
<ide> <!-- YAML
<ide> added: v0.9.1
<ide> * `encoding` {String} The encoding string to test
<ide> * Return: {Boolean}
<ide>
<del>Returns true if the `encoding` is a valid encoding argument, or false
<add>Returns `true` if `encoding` contains a supported character encoding, or `false`
<ide> otherwise.
<ide>
<ide> ### buf[index]
<ide> name: [index]
<ide> -->
<ide>
<ide> The index operator `[index]` can be used to get and set the octet at position
<del>`index` in the Buffer. The values refer to individual bytes, so the legal value
<add>`index` in `buf`. The values refer to individual bytes, so the legal value
<ide> range is between `0x00` and `0xFF` (hex) or `0` and `255` (decimal).
<ide>
<del>Example: copy an ASCII string into a Buffer, one byte at a time:
<add>Example: Copy an ASCII string into a `Buffer`, one byte at a time
<ide>
<ide> ```js
<ide> const str = 'Node.js';
<ide> added: v0.11.13
<ide> Ignored when `targetStart` is `undefined`. default = `buf.byteLength`.
<ide> * Return: {Number}
<ide>
<del>Compares two Buffer instances and returns a number indicating whether `buf`
<del>comes before, after, or is the same as the `target` in sort order.
<del>Comparison is based on the actual sequence of bytes in each Buffer.
<add>Compares `buf` with `target` and returns a number indicating whether `buf`
<add>comes before, after, or is the same as `target` in sort order.
<add>Comparison is based on the actual sequence of bytes in each `Buffer`.
<ide>
<ide> * `0` is returned if `target` is the same as `buf`
<ide> * `1` is returned if `target` should come *before* `buf` when sorted.
<ide> * `-1` is returned if `target` should come *after* `buf` when sorted.
<ide>
<add>Examples:
<add>
<ide> ```js
<ide> const buf1 = Buffer.from('ABC');
<ide> const buf2 = Buffer.from('BCD');
<ide> console.log([buf1, buf2, buf3].sort(Buffer.compare));
<ide> ```
<ide>
<ide> The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`
<del>arguments can be used to limit the comparison to specific ranges within the two
<del>`Buffer` objects.
<add>arguments can be used to limit the comparison to specific ranges within `target`
<add>and `buf` respectively.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
<ide> A `RangeError` will be thrown if: `targetStart < 0`, `sourceStart < 0`,
<ide> * `sourceEnd` {Number} Default: `buffer.length`
<ide> * Return: {Number} The number of bytes copied.
<ide>
<del>Copies data from a region of this Buffer to a region in the target Buffer even
<del>if the target memory region overlaps with the source.
<add>Copies data from a region of `buf` to a region in `target` even if the `target`
<add>memory region overlaps with `buf`.
<ide>
<del>Example: build two Buffers, then copy `buf1` from byte 16 through byte 19
<del>into `buf2`, starting at the 8th byte in `buf2`.
<add>Example: Create two `Buffer` instances, `buf1` and `buf2`, and copy `buf1` from
<add>byte 16 through byte 19 into `buf2`, starting at the 8th byte in `buf2`
<ide>
<ide> ```js
<ide> const buf1 = Buffer.allocUnsafe(26);
<ide> buf1.copy(buf2, 8, 16, 20);
<ide> console.log(buf2.toString('ascii', 0, 25));
<ide> ```
<ide>
<del>Example: Build a single Buffer, then copy data from one region to an overlapping
<del>region in the same Buffer
<add>Example: Create a single `Buffer` and copy data from one region to an
<add>overlapping region within the same `Buffer`
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(26);
<ide> added: v1.1.0
<ide> Creates and returns an [iterator] of `[index, byte]` pairs from the contents of
<ide> `buf`.
<ide>
<add>Example: Log the entire contents of a `Buffer`
<add>
<ide> ```js
<ide> const buf = Buffer.from('buffer');
<ide>
<ide> added: v1.0.0
<ide> * `otherBuffer` {Buffer}
<ide> * Return: {Boolean}
<ide>
<del>Returns a boolean indicating whether `this` and `otherBuffer` have exactly the
<del>same bytes.
<add>Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,
<add>`false` otherwise.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf1 = Buffer.from('ABC');
<ide> added: v0.5.0
<ide> * `encoding` {String} Default: `'utf8'`
<ide> * Return: {Buffer}
<ide>
<del>Fills the Buffer with the specified value. If the `offset` (defaults to `0`)
<del>and `end` (defaults to `buf.length`) are not given the entire buffer will be
<del>filled. The method returns a reference to the Buffer, so calls can be chained.
<del>This is meant as a small simplification to creating a Buffer. Allowing the
<del>creation and fill of the Buffer to be done on a single line:
<add>Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
<add>the entire `buf` will be filled. This is meant to be a small simplification to
<add>allow the creation and filling of a `Buffer` to be done on a single line.
<add>
<add>Example: Fill a `Buffer` with the ASCII character `'h'`
<ide>
<ide> ```js
<ide> const b = Buffer.allocUnsafe(50).fill('h');
<ide> console.log(b.toString());
<ide> `encoding` is only relevant if `value` is a string. Otherwise it is ignored.
<ide> `value` is coerced to a `uint32` value if it is not a String or Number.
<ide>
<del>The `fill()` operation writes bytes into the Buffer dumbly. If the final write
<del>falls in between a multi-byte character then whatever bytes fit into the buffer
<del>are written.
<add>If the final write of a `fill()` operation falls on a multi-byte character,
<add>then only the first bytes of that character that fit into `buf` are written.
<add>
<add>Example: Fill a `Buffer` with a two-byte character
<ide>
<ide> ```js
<ide> // Prints: <Buffer c8 a2 c8>
<ide> added: v1.5.0
<ide> * `encoding` {String} Default: `'utf8'`
<ide> * Return: {Number}
<ide>
<del>Operates similar to [`Array#indexOf()`][] in that it returns either the
<del>starting index position of `value` in Buffer or `-1` if the Buffer does not
<del>contain `value`. The `value` can be a String, Buffer or Number. Strings are by
<del>default interpreted as UTF8. Buffers will use the entire Buffer (to compare a
<del>partial Buffer use [`buf.slice()`][]). Numbers will be interpreted as unsigned 8-bit
<del>integer values between `0` and `255`.
<add>If `value` is:
<add>
<add> * a string, `value` is interpreted according to the character encoding in
<add> `encoding`.
<add> * a `Buffer`, `value` will be used in its entirety. To compare a partial
<add> `Buffer` use [`buf.slice()`].
<add> * a number, `value` will be interpreted as an unsigned 8-bit integer
<add> value between `0` and `255`.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from('this is a buffer');
<ide> added: v5.3.0
<ide> * `encoding` {String} Default: `'utf8'`
<ide> * Return: {Boolean}
<ide>
<del>Operates similar to [`Array#includes()`][]. The `value` can be a String, Buffer
<del>or Number. Strings are interpreted as UTF8 unless overridden with the
<del>`encoding` argument. Buffers will use the entire Buffer (to compare a partial
<del>Buffer use [`buf.slice()`][]). Numbers will be interpreted as unsigned 8-bit
<del>integer values between `0` and `255`.
<add>Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`].
<ide>
<del>The `byteOffset` indicates the index in `buf` where searching begins.
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from('this is a buffer');
<ide> added: v1.1.0
<ide>
<ide> Creates and returns an [iterator] of `buf` keys (indices).
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const buf = Buffer.from('buffer');
<ide>
<ide> added: v6.0.0
<ide> * `encoding` {String} Default: `'utf8'`
<ide> * Return: {Number}
<ide>
<del>Identical to [`Buffer#indexOf()`][], but searches the Buffer from back to front
<del>instead of front to back. Returns the starting index position of `value` in
<del>Buffer or `-1` if the Buffer does not contain `value`. The `value` can be a
<del>String, Buffer or Number. Strings are by default interpreted as UTF8. If
<del>`byteOffset` is provided, will return the last match that begins at or before
<del>`byteOffset`.
<add>Identical to [`buf.indexOf()`], except `buf` is searched from back to front
<add>instead of front to back.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from('this buffer is a buffer');
<ide> console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'ucs2'));
<ide>
<ide> * {Number}
<ide>
<del>Returns the amount of memory allocated for the Buffer in number of bytes. Note
<del>that this does not necessarily reflect the amount of usable data within the
<del>Buffer. For instance, in the example below, a Buffer with 1234 bytes is
<del>allocated, but only 11 ASCII bytes are written.
<add>Returns the amount of memory allocated for `buf` in bytes. Note that this
<add>does not necessarily reflect the amount of "usable" data within `buf`.
<add>
<add>Example: Create a `Buffer` and write a shorter ASCII string to it
<ide>
<ide> ```js
<ide> const buf = Buffer.alloc(1234);
<ide> can result in undefined and inconsistent behavior. Applications that wish to
<ide> modify the length of a `Buffer` should therefore treat `length` as read-only and
<ide> use [`buf.slice()`] to create a new `Buffer`.
<ide>
<add>Examples:
<add>
<ide> ```js
<ide> var buf = Buffer.allocUnsafe(10);
<ide>
<ide> console.log(buf.length);
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads a 64-bit double from the Buffer at the specified `offset` with specified
<add>Reads a 64-bit double from `buf` at the specified `offset` with specified
<ide> endian format (`readDoubleBE()` returns big endian, `readDoubleLE()` returns
<ide> little endian).
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
<ide> console.log(buf.readDoubleLE(1, true));
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads a 32-bit float from the Buffer at the specified `offset` with specified
<add>Reads a 32-bit float from `buf` at the specified `offset` with specified
<ide> endian format (`readFloatBE()` returns big endian, `readFloatLE()` returns
<ide> little endian).
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([1, 2, 3, 4]);
<ide> console.log(buf.readFloatLE(1, true));
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads a signed 8-bit integer from the Buffer at the specified `offset`.
<add>Reads a signed 8-bit integer from `buf` at the specified `offset`.
<add>
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<add>Integers read from a `Buffer` are interpreted as two's complement signed values.
<ide>
<del>Integers read from the Buffer are interpreted as two's complement signed values.
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([-1, 5]);
<ide> console.log(buf.readInt8(2));
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads a signed 16-bit integer from the Buffer at the specified `offset` with
<add>Reads a signed 16-bit integer from `buf` at the specified `offset` with
<ide> the specified endian format (`readInt16BE()` returns big endian,
<ide> `readInt16LE()` returns little endian).
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<ide>
<del>Integers read from the Buffer are interpreted as two's complement signed values.
<add>Integers read from a `Buffer` are interpreted as two's complement signed values.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([0, 5]);
<ide> console.log(buf.readInt16LE(1));
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads a signed 32-bit integer from the Buffer at the specified `offset` with
<add>Reads a signed 32-bit integer from `buf` at the specified `offset` with
<ide> the specified endian format (`readInt32BE()` returns big endian,
<ide> `readInt32LE()` returns little endian).
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<add>
<add>Integers read from a `Buffer` are interpreted as two's complement signed values.
<ide>
<del>Integers read from the Buffer are interpreted as two's complement signed values.
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([0, 0, 0, 5]);
<ide> added: v1.0.0
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads `byteLength` number of bytes from the Buffer at the specified `offset`
<add>Reads `byteLength` number of bytes from `buf` at the specified `offset`
<ide> and interprets the result as a two's complement signed value. Supports up to 48
<del>bits of accuracy. For example:
<add>bits of accuracy.
<add>
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
<ide> console.log(buf.readIntBE(0, 6).toString(16));
<ide> console.log(buf.readIntBE(1, 6).toString(16));
<ide> ```
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<del>
<ide> ### buf.readUInt8(offset[, noAssert])
<ide>
<ide> * `offset` {Number} `0 <= offset <= buf.length - 1`
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads an unsigned 8-bit integer from the Buffer at the specified `offset`.
<add>Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
<add>
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([1, -2]);
<ide> console.log(buf.readUInt8(2));
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads an unsigned 16-bit integer from the Buffer at the specified `offset` with
<del>specified endian format (`readUInt16BE()` returns big endian,
<del>`readUInt16LE()` returns little endian).
<add>Reads an unsigned 16-bit integer from `buf` at the specified `offset` with
<add>specified endian format (`readUInt16BE()` returns big endian, `readUInt16LE()`
<add>returns little endian).
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<ide>
<del>Example:
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([0x12, 0x34, 0x56]);
<ide> console.log(buf.readUInt16LE(2).toString(16));
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads an unsigned 32-bit integer from the Buffer at the specified `offset` with
<add>Reads an unsigned 32-bit integer from `buf` at the specified `offset` with
<ide> specified endian format (`readUInt32BE()` returns big endian,
<ide> `readUInt32LE()` returns little endian).
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<ide>
<del>Example:
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
<ide> added: v1.0.0
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number}
<ide>
<del>Reads `byteLength` number of bytes from the Buffer at the specified `offset`
<add>Reads `byteLength` number of bytes from `buf` at the specified `offset`
<ide> and interprets the result as an unsigned integer. Supports up to 48
<del>bits of accuracy. For example:
<add>bits of accuracy.
<add>
<add>Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but
<add>the result should be considered undefined behavior.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
<ide> console.log(buf.readUIntBE(0, 6).toString(16));
<ide> console.log(buf.readUIntBE(1, 6).toString(16));
<ide> ```
<ide>
<del>Setting `noAssert` to `true` skips validation of the `offset`. This allows the
<del>`offset` to be beyond the end of the Buffer.
<del>
<ide> ### buf.slice([start[, end]])
<ide>
<ide> * `start` {Number} Default: 0
<ide> * `end` {Number} Default: `buffer.length`
<ide> * Return: {Buffer}
<ide>
<del>Returns a new Buffer that references the same memory as the original, but
<add>Returns a new `Buffer` that references the same memory as the original, but
<ide> offset and cropped by the `start` and `end` indices.
<ide>
<del>**Note that modifying the new Buffer slice will modify the memory in the
<del>original Buffer because the allocated memory of the two objects overlap.**
<add>**Note that modifying the new `Buffer` slice will modify the memory in the
<add>original `Buffer` because the allocated memory of the two objects overlap.**
<ide>
<del>Example: build a Buffer with the ASCII alphabet, take a slice, then modify one
<del>byte from the original Buffer.
<add>Example: Create a `Buffer` with the ASCII alphabet, take a slice, and then modify
<add>one byte from the original `Buffer`
<ide>
<ide> ```js
<ide> const buf1 = Buffer.allocUnsafe(26);
<ide> console.log(buf2.toString('ascii', 0, buf2.length));
<ide> ```
<ide>
<ide> Specifying negative indexes causes the slice to be generated relative to the
<del>end of the Buffer rather than the beginning.
<add>end of `buf` rather than the beginning.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.from('buffer');
<ide> added: v5.10.0
<ide>
<ide> * Return: {Buffer}
<ide>
<del>Interprets the `Buffer` as an array of unsigned 16-bit integers and swaps
<del>the byte-order *in-place*. Throws a `RangeError` if the `Buffer` length is
<del>not a multiple of 16 bits. The method returns a reference to the Buffer, so
<del>calls can be chained.
<add>Interprets `buf` as an array of unsigned 16-bit integers and swaps the byte-order
<add>*in-place*. Throws a `RangeError` if [`buf.length`] is not a multiple of 2.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
<ide> added: v5.10.0
<ide>
<ide> * Return: {Buffer}
<ide>
<del>Interprets the `Buffer` as an array of unsigned 32-bit integers and swaps
<del>the byte-order *in-place*. Throws a `RangeError` if the `Buffer` length is
<del>not a multiple of 32 bits. The method returns a reference to the Buffer, so
<del>calls can be chained.
<add>Interprets `buf` as an array of unsigned 32-bit integers and swaps the byte-order
<add>*in-place*. Throws a `RangeError` if [`buf.length`] is not a multiple of 4.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
<ide> added: v6.3.0
<ide>
<ide> * Return: {Buffer}
<ide>
<del>Interprets the `Buffer` as an array of 64-bit numbers and swaps
<del>the byte-order *in-place*. Throws a `RangeError` if the `Buffer` length is
<del>not a multiple of 64 bits. The method returns a reference to the Buffer, so
<del>calls can be chained.
<add>Interprets `buf` as an array of 64-bit numbers and swaps the byte-order *in-place*.
<add>Throws a `RangeError` if [`buf.length`] is not a multiple of 8.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
<ide> for working with 64-bit floats.
<ide> * `end` {Number} Default: `buffer.length`
<ide> * Return: {String}
<ide>
<del>Decodes and returns a string from the Buffer data using the specified
<del>character set `encoding`.
<add>Decodes `buf` to a string according to the specified character encoding in `encoding`.
<add>`start` and `end` may be passed to decode only a subset of `buf`.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf1 = Buffer.allocUnsafe(26);
<ide> added: v0.9.2
<ide>
<ide> * Return: {Object}
<ide>
<del>Returns a JSON representation of `buf`. [`JSON.stringify()`] implicitly calls
<add>Returns a JSON representation of `buf`. [`JSON.stringify()`] implicitly calls
<ide> this function when stringifying a `Buffer` instance.
<ide>
<ide> Example:
<ide> added: v1.1.0
<ide> Creates and returns an [iterator] for `buf` values (bytes). This function is
<ide> called automatically when a `Buffer` is used in a `for..of` statement.
<ide>
<add>Examples:
<add>
<ide> ```js
<ide> const buf = Buffer.from('buffer');
<ide>
<ide> for (var value of buf) {
<ide> * `encoding` {String} Default: `'utf8'`
<ide> * Return: {Number} Numbers of bytes written
<ide>
<del>Writes `string` to the Buffer at `offset` using the given `encoding`.
<del>The `length` parameter is the number of bytes to write. If the Buffer did not
<del>contain enough space to fit the entire string, only a partial amount of the
<del>string will be written however, it will not write only partially encoded
<del>characters.
<add>Writes `string` to `buf` at `offset` according to the character encoding in `encoding`.
<add>The `length` parameter is the number of bytes to write. If `buf` did not contain
<add>enough space to fit the entire string, only a partial amount of `string` will
<add>be written. However, partially encoded characters will not be written.
<add>
<add>Example:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(256);
<ide> console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset` with specified endian
<add>Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeDoubleBE()` writes big endian, `writeDoubleLE()` writes little
<del>endian). The `value` argument *should* be a valid 64-bit double. Behavior is
<del>not defined when `value` is anything other than a 64-bit double.
<add>endian). `value` *should* be a valid 64-bit double. Behavior is undefined when
<add>`value` is anything other than a 64-bit double.
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<ide>
<del>Example:
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(8);
<ide> console.log(buf);
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset` with specified endian
<add>Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeFloatBE()` writes big endian, `writeFloatLE()` writes little
<del>endian). Behavior is not defined when `value` is anything other than a 32-bit
<del>float.
<add>endian). `value` *should* be a valid 32-bit float. Behavior is undefined when
<add>`value` is anything other than a 32-bit float.
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<ide>
<del>Example:
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(4);
<ide> console.log(buf);
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset`. The `value` should be a
<del>valid signed 8-bit integer. Behavior is not defined when `value` is anything
<del>other than a signed 8-bit integer.
<add>Writes `value` to `buf` at the specified `offset`. `value` *should* be a valid
<add>signed 8-bit integer. Behavior is undefined when `value` is anything other than
<add>a signed 8-bit integer.
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<ide>
<del>The `value` is interpreted and written as a two's complement signed integer.
<add>`value` is interpreted and written as a two's complement signed integer.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(2);
<ide> console.log(buf);
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset` with specified endian
<add>Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeInt16BE()` writes big endian, `writeInt16LE()` writes little
<del>endian). The `value` should be a valid signed 16-bit integer. Behavior is
<del>not defined when `value` is anything other than a signed 16-bit integer.
<add>endian). `value` *should* be a valid signed 16-bit integer. Behavior is undefined
<add>when `value` is anything other than a signed 16-bit integer.
<add>
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<add>`value` is interpreted and written as a two's complement signed integer.
<ide>
<del>The `value` is interpreted and written as a two's complement signed integer.
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(4);
<ide> console.log(buf);
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset` with specified endian
<add>Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeInt32BE()` writes big endian, `writeInt32LE()` writes little
<del>endian). The `value` should be a valid signed 32-bit integer. Behavior is
<del>not defined when `value` is anything other than a signed 32-bit integer.
<add>endian). `value` *should* be a valid signed 32-bit integer. Behavior is undefined
<add>when `value` is anything other than a signed 32-bit integer.
<add>
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<add>`value` is interpreted and written as a two's complement signed integer.
<ide>
<del>The `value` is interpreted and written as a two's complement signed integer.
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(8);
<ide> added: v1.0.0
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset` and `byteLength`.
<del>Supports up to 48 bits of accuracy. For example:
<add>Writes `byteLength` bytes of `value` to `buf` at the specified `offset`.
<add>Supports up to 48 bits of accuracy. Behavior is undefined when `value` is
<add>anything other than a signed integer.
<add>
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(6);
<ide> buf.writeUIntLE(0x1234567890ab, 0, 6);
<ide> console.log(buf);
<ide> ```
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<del>
<del>Behavior is not defined when `value` is anything other than an integer.
<del>
<ide> ### buf.writeUInt8(value, offset[, noAssert])
<ide>
<ide> * `value` {Number} Bytes to be written to Buffer
<ide> * `offset` {Number} `0 <= offset <= buf.length - 1`
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset`. The `value` should be a
<del>valid unsigned 8-bit integer. Behavior is not defined when `value` is anything
<add>Writes `value` to `buf` at the specified `offset`. `value` *should* be a
<add>valid unsigned 8-bit integer. Behavior is undefined when `value` is anything
<ide> other than an unsigned 8-bit integer.
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<ide>
<del>Example:
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(4);
<ide> console.log(buf);
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset` with specified endian
<add>Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeUInt16BE()` writes big endian, `writeUInt16LE()` writes little
<del>endian). The `value` should be a valid unsigned 16-bit integer. Behavior is
<del>not defined when `value` is anything other than an unsigned 16-bit integer.
<add>endian). `value` should be a valid unsigned 16-bit integer. Behavior is
<add>undefined when `value` is anything other than an unsigned 16-bit integer.
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<ide>
<del>Example:
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(4);
<ide> console.log(buf);
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset` with specified endian
<add>Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeUInt32BE()` writes big endian, `writeUInt32LE()` writes little
<del>endian). The `value` should be a valid unsigned 32-bit integer. Behavior is
<del>not defined when `value` is anything other than an unsigned 32-bit integer.
<add>endian). `value` should be a valid unsigned 32-bit integer. Behavior is
<add>undefined when `value` is anything other than an unsigned 32-bit integer.
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<ide>
<del>Example:
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(4);
<ide> console.log(buf);
<ide> * `noAssert` {Boolean} Default: false
<ide> * Return: {Number} The offset plus the number of written bytes
<ide>
<del>Writes `value` to the Buffer at the specified `offset` and `byteLength`.
<del>Supports up to 48 bits of accuracy. For example:
<add>Writes `byteLength` bytes of `value` to `buf` at the specified `offset`.
<add>Supports up to 48 bits of accuracy. Behavior is undefined when `value` is
<add>anything other than an unsigned integer.
<add>
<add>Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond
<add>the end of `buf`, but the result should be considered undefined behavior.
<add>
<add>Examples:
<ide>
<ide> ```js
<ide> const buf = Buffer.allocUnsafe(6);
<ide> buf.writeUIntLE(0x1234567890ab, 0, 6);
<ide> console.log(buf);
<ide> ```
<ide>
<del>Set `noAssert` to true to skip validation of `value` and `offset`. This means
<del>that `value` may be too large for the specific function and `offset` may be
<del>beyond the end of the Buffer leading to the values being silently dropped. This
<del>should not be used unless you are certain of correctness.
<del>
<del>Behavior is not defined when `value` is anything other than an unsigned integer.
<del>
<ide> ## buffer.INSPECT_MAX_BYTES
<ide>
<ide> * {Number} Default: 50
<ide> Returns the maximum number of bytes that will be returned when
<ide> [`util.inspect()`] for more details on `buf.inspect()` behavior.
<ide>
<ide> Note that this is a property on the `buffer` module as returned by
<del>`require('buffer')`, not on the Buffer global or a Buffer instance.
<add>`require('buffer')`, not on the `Buffer` global or a `Buffer` instance.
<ide>
<ide> ## Class: SlowBuffer
<ide> <!-- YAML
<ide> deprecated: v6.0.0
<ide> Returns an un-pooled `Buffer`.
<ide>
<ide> In order to avoid the garbage collection overhead of creating many individually
<del>allocated Buffers, by default allocations under 4KB are sliced from a single
<del>larger allocated object. This approach improves both performance and memory
<add>allocated `Buffer` instances, by default allocations under 4KB are sliced from a
<add>single larger allocated object. This approach improves both performance and memory
<ide> usage since v8 does not need to track and cleanup as many `Persistent` objects.
<ide>
<ide> In the case where a developer may need to retain a small chunk of memory from a
<ide> pool for an indeterminate amount of time, it may be appropriate to create an
<del>un-pooled Buffer instance using `SlowBuffer` then copy out the relevant bits.
<add>un-pooled `Buffer` instance using `SlowBuffer` then copy out the relevant bits.
<add>
<add>Example:
<ide>
<ide> ```js
<ide> // Need to keep around a few small chunks of memory
<ide> deprecated: v6.0.0
<ide>
<ide> * `size` Number
<ide>
<del>Allocates a new `SlowBuffer` of `size` bytes. The `size` must be less than
<add>Allocates a new `SlowBuffer` of `size` bytes. The `size` must be less than
<ide> or equal to the value of `require('buffer').kMaxLength` (on 64-bit
<ide> architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
<ide> thrown. A zero-length Buffer will be created if a `size` less than or equal to
<ide> The underlying memory for `SlowBuffer` instances is *not initialized*. The
<ide> contents of a newly created `SlowBuffer` are unknown and could contain
<ide> sensitive data. Use [`buf.fill(0)`][`buf.fill()`] to initialize a `SlowBuffer` to zeroes.
<ide>
<add>Example:
<add>
<ide> ```js
<ide> const SlowBuffer = require('buffer').SlowBuffer;
<ide> | 1 |
Javascript | Javascript | load common.js in all tests | c78091d689d0d4d56b3231b9050d52ca69ecb449 | <ide><path>test/addons/async-hello-world/test.js
<ide> 'use strict';
<add>require('../../common');
<ide> var assert = require('assert');
<ide> var binding = require('./build/Release/binding');
<ide> var called = false;
<ide><path>test/addons/at-exit/test.js
<ide> 'use strict';
<add>require('../../common');
<ide> var binding = require('./build/Release/binding');
<ide><path>test/addons/heap-profiler/test.js
<ide> 'use strict';
<ide>
<add>require('../../common');
<add>
<ide> const binding = require('./build/Release/binding');
<ide>
<ide> // Create an AsyncWrap object.
<ide><path>test/addons/hello-world-function-export/test.js
<ide> 'use strict';
<add>require('../../common');
<ide> var assert = require('assert');
<ide> var binding = require('./build/Release/binding');
<ide> assert.equal('world', binding());
<ide><path>test/addons/hello-world/test.js
<ide> 'use strict';
<add>require('../../common');
<ide> var assert = require('assert');
<ide> var binding = require('./build/Release/binding');
<ide> assert.equal('world', binding.hello());
<ide><path>test/addons/repl-domain-abort/test.js
<ide> 'use strict';
<add>require('../../common');
<ide> var assert = require('assert');
<ide> var repl = require('repl');
<ide> var stream = require('stream');
<ide><path>test/debugger/test-debugger-repl-break-in-module.js
<ide> 'use strict';
<add>require('../common');
<ide> var repl = require('./helper-debugger-repl.js');
<ide>
<ide> repl.startDebugger('break-in-module/main.js');
<ide><path>test/debugger/test-debugger-repl-restart.js
<ide> 'use strict';
<add>require('../common');
<ide> var repl = require('./helper-debugger-repl.js');
<ide>
<ide> repl.startDebugger('breakpoints.js');
<ide><path>test/debugger/test-debugger-repl-term.js
<ide> 'use strict';
<add>require('../common');
<ide> process.env.NODE_FORCE_READLINE = 1;
<ide>
<ide> var repl = require('./helper-debugger-repl.js');
<ide><path>test/debugger/test-debugger-repl.js
<ide> 'use strict';
<add>require('../common');
<ide> var repl = require('./helper-debugger-repl.js');
<ide>
<ide> repl.startDebugger('breakpoints.js'); | 10 |
PHP | PHP | update listenermakecommand.php | 9adce329ede8750b92dd96eb791434e0cf9aa7e2 | <ide><path>src/Illuminate/Foundation/Console/ListenerMakeCommand.php
<ide> protected function getDefaultNamespace($rootNamespace)
<ide> protected function getOptions()
<ide> {
<ide> return [
<del> ['event', null, InputOption::VALUE_REQUIRED, 'The event class being listened for.'],
<add> ['event', 'e', InputOption::VALUE_REQUIRED, 'The event class being listened for.'],
<ide>
<del> ['queued', null, InputOption::VALUE_NONE, 'Indicates the event listener should be queued.'],
<add> ['queued', 'q', InputOption::VALUE_NONE, 'Indicates the event listener should be queued.'],
<ide> ];
<ide> }
<ide> } | 1 |
Python | Python | fix failing static checks in main | 60848a6ea78e29f20004a5e9f177335e6b99c706 | <ide><path>airflow/utils/log/file_task_handler.py
<ide> def _read(self, ti, try_number, metadata=None):
<ide> response.encoding = "utf-8"
<ide>
<ide> if response.status_code == 403:
<del> log += "*** !!!! Please make sure that all your webservers and workers have" \
<del> " the same 'secret_key' configured in 'webserver' section !!!!!\n***"
<del> log += "*** See more at https://airflow.apache.org/docs/apache-airflow/" \
<del> "stable/configurations-ref.html#secret-key\n***"
<add> log += (
<add> "*** !!!! Please make sure that all your Airflow components (e.g. schedulers, webservers and workers) have"
<add> " the same 'secret_key' configured in 'webserver' section !!!!!\n***"
<add> )
<add> log += (
<add> "*** See more at https://airflow.apache.org/docs/apache-airflow/"
<add> "stable/configurations-ref.html#secret-key\n***"
<add> )
<ide> # Check if the resource was properly fetched
<ide> response.raise_for_status()
<ide> | 1 |
Ruby | Ruby | add deprecation note for sourceannotationextractor | 92dac547fdf073e034c11a452d3b965a38a0f948 | <ide><path>railties/lib/rails/source_annotation_extractor.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "active_support/deprecation"
<add>
<add># Remove this deprecated class in the next minor version
<add>#:nodoc:
<add>SourceAnnotationExtractor = ActiveSupport::Deprecation::DeprecatedConstantProxy.
<add> new("SourceAnnotationExtractor", "Rails::SourceAnnotationExtractor")
<add>
<ide> module Rails
<ide> # Implements the logic behind the rake tasks for annotations like
<ide> # | 1 |
PHP | PHP | fix styleci lint | 87bb1352e9e15c28700ffdd3656b429ceddf4e7d | <ide><path>src/Illuminate/Support/Stringable.php
<ide> public function explode($delimiter, $limit = PHP_INT_MAX)
<ide> {
<ide> return collect(explode($delimiter, $this->value, $limit));
<ide> }
<del>
<add>
<ide> /**
<ide> * Split string by a regular expression.
<ide> *
<ide> public function split($pattern, $limit = -1, $flags = 0)
<ide> {
<ide> $keywords = preg_split($pattern, $this->value, $limit, $flags);
<ide>
<del> if(! $keywords) {
<add> if (! $keywords) {
<ide> return collect();
<ide> }
<ide> | 1 |
Ruby | Ruby | require provided_content to be a string | 8b5e334be48f0589a5d0c1fc376e161ff73ea49e | <ide><path>Library/Homebrew/livecheck/strategy/page_match.rb
<ide> def self.page_matches(content, regex, &block)
<ide> def self.find_versions(url, regex, provided_content = nil, &block)
<ide> match_data = { matches: {}, regex: regex, url: url }
<ide>
<del> content = if provided_content.present?
<add> content = if provided_content.is_a?(String)
<ide> provided_content
<ide> else
<ide> match_data.merge!(Strategy.page_content(url)) | 1 |
Javascript | Javascript | remove odd evented view tests | 6eab29284fcab388d6d9ba4003e7658a4075b6e9 | <ide><path>packages/ember-views/tests/views/view/evented_test.js
<del>import run from 'ember-metal/run_loop';
<del>import EmberObject from 'ember-runtime/system/object';
<del>import EmberView from 'ember-views/views/view';
<del>
<del>let view;
<del>
<del>QUnit.module('EmberView evented helpers', {
<del> teardown() {
<del> run(() => view.destroy());
<del> }
<del>});
<del>
<del>QUnit.test('fire should call method sharing event name if it exists on the view', function() {
<del> let eventFired = false;
<del>
<del> view = EmberView.create({
<del> fireMyEvent() {
<del> this.trigger('myEvent');
<del> },
<del>
<del> myEvent() {
<del> eventFired = true;
<del> }
<del> });
<del>
<del> run(() => view.fireMyEvent());
<del>
<del> equal(eventFired, true, 'fired the view method sharing the event name');
<del>});
<del>
<del>QUnit.test('fire does not require a view method with the same name', function() {
<del> let eventFired = false;
<del>
<del> view = EmberView.create({
<del> fireMyEvent() {
<del> this.trigger('myEvent');
<del> }
<del> });
<del>
<del> let listenObject = EmberObject.create({
<del> onMyEvent() {
<del> eventFired = true;
<del> }
<del> });
<del>
<del> view.on('myEvent', listenObject, 'onMyEvent');
<del>
<del> run(() => view.fireMyEvent());
<del>
<del> equal(eventFired, true, 'fired the event without a view method sharing its name');
<del>
<del> run(() => listenObject.destroy());
<del>});
<del> | 1 |
Text | Text | fix typo and simplify autoload paths intro | d122ae6143856c1c4a0045afcb81aab2f2c10db1 | <ide><path>guides/source/autoloading_and_reloading_constants.md
<ide> Please, check the [Zeitwerk documentation](https://github.com/fxn/zeitwerk#file-
<ide> Autoload paths
<ide> --------------
<ide>
<del>We call _autoload paths_ to the list of application directories whose contents are to be autoloaded. For example, `app/models`. Such directories represent the root namespace: `Object`.
<add>We refer to the list of application directories whose contents are to be autoloaded as _autoload paths_. For example, `app/models`. Such directories represent the root namespace: `Object`.
<ide>
<ide> INFO. Autoload paths are called _root directories_ in Zeitwerk documentation, but we'll stay with "autoload path" in this guide.
<ide> | 1 |
Go | Go | modify test to accept error from mkcontainer | ced93bcabdc0dd0f6dcfa52174be552adf6c5bd1 | <ide><path>server_test.go
<ide> func TestContainerTop(t *testing.T) {
<ide> srv := &Server{runtime: runtime}
<ide> defer nuke(runtime)
<ide>
<del> c, hostConfig := mkContainer(runtime, []string{"_", "/bin/sh", "-c", "sleep 2"}, t)
<add> c, hostConfig, err := mkContainer(runtime, []string{"_", "/bin/sh", "-c", "sleep 2"}, t)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide> defer runtime.Destroy(c)
<ide> if err := c.Start(hostConfig); err != nil {
<ide> t.Fatal(err) | 1 |
PHP | PHP | add mailable assertions | 4bc8737955c01a7e04b0fd47e84cd16ac42acba3 | <ide><path>src/Illuminate/Mail/Mailable.php
<ide> public function hasMetadata($key, $value)
<ide> (method_exists($this, 'envelope') && $this->envelope()->hasMetadata($key, $value));
<ide> }
<ide>
<add> /**
<add> * Assert that the mailable is from the given address.
<add> *
<add> * @param object|array|string $address
<add> * @param string|null $name
<add> * @return $this
<add> */
<add> public function assertFrom($address, $name = null)
<add> {
<add> $recipient = $this->formatAssertionRecipient($address, $name);
<add>
<add> PHPUnit::assertTrue(
<add> $this->hasFrom($address, $name),
<add> "Email was not from expected address [{$recipient}]."
<add> );
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Assert that the mailable has the given recipient.
<add> *
<add> * @param object|array|string $address
<add> * @param string|null $name
<add> * @return $this
<add> */
<add> public function assertTo($address, $name = null)
<add> {
<add> $recipient = $this->formatAssertionRecipient($address, $name);
<add>
<add> PHPUnit::assertTrue(
<add> $this->hasTo($address, $name),
<add> "Did not see expected recipient [{$recipient}] in email recipients."
<add> );
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Assert that the mailable has the given recipient.
<add> *
<add> * @param object|array|string $address
<add> * @param string|null $name
<add> * @return $this
<add> */
<add> public function assertHasTo($address, $name = null)
<add> {
<add> return $this->assertTo($address, $name);
<add> }
<add>
<add> /**
<add> * Assert that the mailable has the given recipient.
<add> *
<add> * @param object|array|string $address
<add> * @param string|null $name
<add> * @return $this
<add> */
<add> public function assertHasCc($address, $name = null)
<add> {
<add> $recipient = $this->formatAssertionRecipient($address, $name);
<add>
<add> PHPUnit::assertTrue(
<add> $this->hasCc($address, $name),
<add> "Did not see expected recipient [{$recipient}] in email recipients."
<add> );
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Assert that the mailable has the given recipient.
<add> *
<add> * @param object|array|string $address
<add> * @param string|null $name
<add> * @return $this
<add> */
<add> public function assertHasBcc($address, $name = null)
<add> {
<add> $recipient = $this->formatAssertionRecipient($address, $name);
<add>
<add> PHPUnit::assertTrue(
<add> $this->hasBcc($address, $name),
<add> "Did not see expected recipient [{$recipient}] in email recipients."
<add> );
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Assert that the mailable has the given "reply to" address.
<add> *
<add> * @param object|array|string $address
<add> * @param string|null $name
<add> * @return $this
<add> */
<add> public function assertHasReplyTo($address, $name = null)
<add> {
<add> $replyTo = $this->formatAssertionRecipient($address, $name);
<add>
<add> PHPUnit::assertTrue(
<add> $this->hasReplyTo($address, $name),
<add> "Did not see expected address [{$replyTo}] as email 'reply to' recipient."
<add> );
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Format the mailable recipeint for display in an assertion message.
<add> *
<add> * @param object|array|string $address
<add> * @param string|null $name
<add> * @return string
<add> */
<add> private function formatAssertionRecipient($address, $name = null)
<add> {
<add> if (! is_string($address)) {
<add> $address = json_encode($address);
<add> }
<add>
<add> if (filled($name)) {
<add> $address .= ' ('.$name.')';
<add> }
<add>
<add> return $address;
<add> }
<add>
<add> /**
<add> * Assert that the mailable has the given subject.
<add> *
<add> * @param string $subject
<add> * @return $this
<add> */
<add> public function assertHasSubject($subject)
<add> {
<add> PHPUnit::assertTrue(
<add> $this->hasSubject($subject),
<add> "Did not see expected text [{$subject}] in email subject."
<add> );
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Assert that the given text is present in the HTML email body.
<ide> *
<ide> public function assertHasAttachmentFromStorageDisk($disk, $path, $name = null, a
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Assert that the mailable has the given tag.
<add> *
<add> * @param string $tag
<add> * @return $this
<add> */
<add> public function assertHasTag($tag)
<add> {
<add> PHPUnit::assertTrue(
<add> $this->hasTag($tag),
<add> "Did not see expected tag [{$tag}] in email tags."
<add> );
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Assert that the mailable has the given metadata.
<add> *
<add> * @param string $key
<add> * @param string $value
<add> * @return $this
<add> */
<add> public function assertHasMetadata($key, $value)
<add> {
<add> PHPUnit::assertTrue(
<add> $this->hasMetadata($key, $value),
<add> "Did not see expected key [{$key}] and value [{$value}] in email metadata."
<add> );
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Render the HTML and plain-text version of the mailable into views for assertions.
<ide> *
<ide><path>tests/Mail/MailMailableTest.php
<ide> public function testMailableSetsRecipientsCorrectly()
<ide> $mailable->to('taylor@laravel.com');
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->to);
<ide> $this->assertTrue($mailable->hasTo('taylor@laravel.com'));
<add> $mailable->assertHasTo('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->to('taylor@laravel.com', 'Taylor Otwell');
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->to);
<ide> $this->assertTrue($mailable->hasTo('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasTo('taylor@laravel.com'));
<add> $mailable->assertHasTo('taylor@laravel.com', 'Taylor Otwell');
<add> $mailable->assertHasTo('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->to(['taylor@laravel.com']);
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->to);
<ide> $this->assertTrue($mailable->hasTo('taylor@laravel.com'));
<ide> $this->assertFalse($mailable->hasTo('taylor@laravel.com', 'Taylor Otwell'));
<add> $mailable->assertHasTo('taylor@laravel.com');
<add> try {
<add> $mailable->assertHasTo('taylor@laravel.com', 'Taylor Otwell');
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> $this->assertSame("Did not see expected recipient [taylor@laravel.com (Taylor Otwell)] in email recipients.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->to([['name' => 'Taylor Otwell', 'email' => 'taylor@laravel.com']]);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->to);
<ide> $this->assertTrue($mailable->hasTo('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasTo('taylor@laravel.com'));
<add> $mailable->assertHasTo('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->to(new MailableTestUserStub);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->to);
<ide> $this->assertTrue($mailable->hasTo(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasTo('taylor@laravel.com'));
<add> $mailable->assertHasTo('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->to(collect([new MailableTestUserStub]));
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->to);
<ide> $this->assertTrue($mailable->hasTo(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasTo('taylor@laravel.com'));
<add> $mailable->assertHasTo('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->to(collect([new MailableTestUserStub, new MailableTestUserStub]));
<ide> public function testMailableSetsRecipientsCorrectly()
<ide> ], $mailable->to);
<ide> $this->assertTrue($mailable->hasTo(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasTo('taylor@laravel.com'));
<add> $mailable->assertHasTo('taylor@laravel.com');
<ide>
<ide> foreach (['', null, [], false] as $address) {
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->to($address);
<ide> $this->assertFalse($mailable->hasTo(new MailableTestUserStub));
<ide> $this->assertFalse($mailable->hasTo($address));
<add> try {
<add> $mailable->assertHasTo($address);
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> if (! is_string($address)) {
<add> $address = json_encode($address);
<add> }
<add> $this->assertSame("Did not see expected recipient [{$address}] in email recipients.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide> }
<ide> }
<ide>
<ide> public function testMailableSetsCcRecipientsCorrectly()
<ide> $mailable->cc('taylor@laravel.com');
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->cc);
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com'));
<add> $mailable->assertHasCc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->cc('taylor@laravel.com', 'Taylor Otwell');
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->cc);
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com'));
<add> $mailable->assertHasCc('taylor@laravel.com', 'Taylor Otwell');
<add> $mailable->assertHasCc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->cc(['taylor@laravel.com']);
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->cc);
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com'));
<ide> $this->assertFalse($mailable->hasCc('taylor@laravel.com', 'Taylor Otwell'));
<add> $mailable->assertHasCc('taylor@laravel.com');
<add> try {
<add> $mailable->assertHasCc('taylor@laravel.com', 'Taylor Otwell');
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> $this->assertSame("Did not see expected recipient [taylor@laravel.com (Taylor Otwell)] in email recipients.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->cc([['name' => 'Taylor Otwell', 'email' => 'taylor@laravel.com']]);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->cc);
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com'));
<add> $mailable->assertHasCc('taylor@laravel.com', 'Taylor Otwell');
<add> $mailable->assertHasCc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->cc(new MailableTestUserStub);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->cc);
<ide> $this->assertTrue($mailable->hasCc(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com'));
<add> $mailable->assertHasCc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->cc(collect([new MailableTestUserStub]));
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->cc);
<ide> $this->assertTrue($mailable->hasCc(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com'));
<add> $mailable->assertHasCc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->cc(collect([new MailableTestUserStub, new MailableTestUserStub]));
<ide> public function testMailableSetsCcRecipientsCorrectly()
<ide> ], $mailable->cc);
<ide> $this->assertTrue($mailable->hasCc(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com'));
<add> $mailable->assertHasCc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->cc(['taylor@laravel.com', 'not-taylor@laravel.com']);
<ide> public function testMailableSetsCcRecipientsCorrectly()
<ide> ], $mailable->cc);
<ide> $this->assertTrue($mailable->hasCc('taylor@laravel.com'));
<ide> $this->assertTrue($mailable->hasCc('not-taylor@laravel.com'));
<add> $mailable->assertHasCc('taylor@laravel.com');
<add> $mailable->assertHasCc('not-taylor@laravel.com');
<ide>
<ide> foreach (['', null, [], false] as $address) {
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->cc($address);
<ide> $this->assertFalse($mailable->hasCc(new MailableTestUserStub));
<ide> $this->assertFalse($mailable->hasCc($address));
<add> try {
<add> $mailable->assertHasCc($address);
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> if (! is_string($address)) {
<add> $address = json_encode($address);
<add> }
<add> $this->assertSame("Did not see expected recipient [{$address}] in email recipients.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide> }
<ide> }
<ide>
<ide> public function testMailableSetsBccRecipientsCorrectly()
<ide> $mailable->bcc('taylor@laravel.com');
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->bcc);
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com'));
<add> $mailable->assertHasBcc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->bcc('taylor@laravel.com', 'Taylor Otwell');
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->bcc);
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com'));
<add> $mailable->assertHasBcc('taylor@laravel.com', 'Taylor Otwell');
<add> $mailable->assertHasBcc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->bcc(['taylor@laravel.com']);
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->bcc);
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com'));
<ide> $this->assertFalse($mailable->hasBcc('taylor@laravel.com', 'Taylor Otwell'));
<add> $mailable->assertHasBcc('taylor@laravel.com');
<add> try {
<add> $mailable->assertHasBcc('taylor@laravel.com', 'Taylor Otwell');
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> $this->assertSame("Did not see expected recipient [taylor@laravel.com (Taylor Otwell)] in email recipients.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->bcc([['name' => 'Taylor Otwell', 'email' => 'taylor@laravel.com']]);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->bcc);
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com'));
<add> $mailable->assertHasBcc('taylor@laravel.com', 'Taylor Otwell');
<add> $mailable->assertHasBcc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->bcc(new MailableTestUserStub);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->bcc);
<ide> $this->assertTrue($mailable->hasBcc(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com'));
<add> $mailable->assertHasBcc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->bcc(collect([new MailableTestUserStub]));
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->bcc);
<ide> $this->assertTrue($mailable->hasBcc(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com'));
<add> $mailable->assertHasBcc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->bcc(collect([new MailableTestUserStub, new MailableTestUserStub]));
<ide> public function testMailableSetsBccRecipientsCorrectly()
<ide> ], $mailable->bcc);
<ide> $this->assertTrue($mailable->hasBcc(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com'));
<add> $mailable->assertHasBcc('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->bcc(['taylor@laravel.com', 'not-taylor@laravel.com']);
<ide> public function testMailableSetsBccRecipientsCorrectly()
<ide> ], $mailable->bcc);
<ide> $this->assertTrue($mailable->hasBcc('taylor@laravel.com'));
<ide> $this->assertTrue($mailable->hasBcc('not-taylor@laravel.com'));
<add> $mailable->assertHasBcc('taylor@laravel.com');
<add> $mailable->assertHasBcc('not-taylor@laravel.com');
<ide>
<ide> foreach (['', null, [], false] as $address) {
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->bcc($address);
<ide> $this->assertFalse($mailable->hasBcc(new MailableTestUserStub));
<ide> $this->assertFalse($mailable->hasBcc($address));
<add> try {
<add> $mailable->assertHasBcc($address);
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> if (! is_string($address)) {
<add> $address = json_encode($address);
<add> }
<add> $this->assertSame("Did not see expected recipient [{$address}] in email recipients.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide> }
<ide> }
<ide>
<ide> public function testMailableSetsReplyToCorrectly()
<ide> $mailable->replyTo('taylor@laravel.com');
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->replyTo);
<ide> $this->assertTrue($mailable->hasReplyTo('taylor@laravel.com'));
<add> $mailable->assertHasReplyTo('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->replyTo('taylor@laravel.com', 'Taylor Otwell');
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->replyTo);
<ide> $this->assertTrue($mailable->hasReplyTo('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasReplyTo('taylor@laravel.com'));
<add> $mailable->assertHasReplyTo('taylor@laravel.com', 'Taylor Otwell');
<add> $mailable->assertHasReplyTo('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->replyTo(['taylor@laravel.com']);
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->replyTo);
<ide> $this->assertTrue($mailable->hasReplyTo('taylor@laravel.com'));
<ide> $this->assertFalse($mailable->hasReplyTo('taylor@laravel.com', 'Taylor Otwell'));
<add> $mailable->assertHasReplyTo('taylor@laravel.com');
<add> try {
<add> $mailable->assertHasReplyTo('taylor@laravel.com', 'Taylor Otwell');
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> $this->assertSame("Did not see expected address [taylor@laravel.com (Taylor Otwell)] as email 'reply to' recipient.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->replyTo([['name' => 'Taylor Otwell', 'email' => 'taylor@laravel.com']]);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->replyTo);
<ide> $this->assertTrue($mailable->hasReplyTo('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasReplyTo('taylor@laravel.com'));
<add> $mailable->assertHasReplyTo('taylor@laravel.com');
<add> $mailable->assertHasReplyTo('taylor@laravel.com', 'Taylor Otwell');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->replyTo(new MailableTestUserStub);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->replyTo);
<ide> $this->assertTrue($mailable->hasReplyTo(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasReplyTo('taylor@laravel.com'));
<add> $mailable->assertHasReplyTo('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->replyTo(collect([new MailableTestUserStub]));
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->replyTo);
<ide> $this->assertTrue($mailable->hasReplyTo(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasReplyTo('taylor@laravel.com'));
<add> $mailable->assertHasReplyTo('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->replyTo(collect([new MailableTestUserStub, new MailableTestUserStub]));
<ide> public function testMailableSetsReplyToCorrectly()
<ide> ], $mailable->replyTo);
<ide> $this->assertTrue($mailable->hasReplyTo(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasReplyTo('taylor@laravel.com'));
<add> $mailable->assertHasReplyTo('taylor@laravel.com');
<ide>
<ide> foreach (['', null, [], false] as $address) {
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->replyTo($address);
<ide> $this->assertFalse($mailable->hasReplyTo(new MailableTestUserStub));
<ide> $this->assertFalse($mailable->hasReplyTo($address));
<add> try {
<add> $mailable->assertHasReplyTo($address);
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> if (! is_string($address)) {
<add> $address = json_encode($address);
<add> }
<add> $this->assertSame("Did not see expected address [{$address}] as email 'reply to' recipient.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide> }
<ide> }
<ide>
<ide> public function testMailableSetsFromCorrectly()
<ide> $mailable->from('taylor@laravel.com');
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->from);
<ide> $this->assertTrue($mailable->hasFrom('taylor@laravel.com'));
<add> $mailable->assertFrom('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->from('taylor@laravel.com', 'Taylor Otwell');
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->from);
<ide> $this->assertTrue($mailable->hasFrom('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasFrom('taylor@laravel.com'));
<add> $mailable->assertFrom('taylor@laravel.com', 'Taylor Otwell');
<add> $mailable->assertFrom('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->from(['taylor@laravel.com']);
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->from);
<ide> $this->assertTrue($mailable->hasFrom('taylor@laravel.com'));
<ide> $this->assertFalse($mailable->hasFrom('taylor@laravel.com', 'Taylor Otwell'));
<add> $mailable->assertFrom('taylor@laravel.com');
<add> try {
<add> $mailable->assertFrom('taylor@laravel.com', 'Taylor Otwell');
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> $this->assertSame("Email was not from expected address [taylor@laravel.com (Taylor Otwell)].\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->from([['name' => 'Taylor Otwell', 'email' => 'taylor@laravel.com']]);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->from);
<ide> $this->assertTrue($mailable->hasFrom('taylor@laravel.com', 'Taylor Otwell'));
<ide> $this->assertTrue($mailable->hasFrom('taylor@laravel.com'));
<add> $mailable->assertFrom('taylor@laravel.com', 'Taylor Otwell');
<add> $mailable->assertFrom('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->from(new MailableTestUserStub);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->from);
<ide> $this->assertTrue($mailable->hasFrom(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasFrom('taylor@laravel.com'));
<add> $mailable->assertFrom('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->from(collect([new MailableTestUserStub]));
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->from);
<ide> $this->assertTrue($mailable->hasFrom(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasFrom('taylor@laravel.com'));
<add> $mailable->assertFrom('taylor@laravel.com');
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->from(collect([new MailableTestUserStub, new MailableTestUserStub]));
<ide> public function testMailableSetsFromCorrectly()
<ide> ], $mailable->from);
<ide> $this->assertTrue($mailable->hasFrom(new MailableTestUserStub));
<ide> $this->assertTrue($mailable->hasFrom('taylor@laravel.com'));
<add> $mailable->assertFrom('taylor@laravel.com');
<ide>
<ide> foreach (['', null, [], false] as $address) {
<ide> $mailable = new WelcomeMailableStub;
<ide> $mailable->from($address);
<ide> $this->assertFalse($mailable->hasFrom(new MailableTestUserStub));
<ide> $this->assertFalse($mailable->hasFrom($address));
<add> try {
<add> $mailable->assertFrom($address);
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> if (! is_string($address)) {
<add> $address = json_encode($address);
<add> }
<add> $this->assertSame("Email was not from expected address [{$address}].\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide> }
<ide> }
<ide>
<ide> public function testMailableMetadataGetsSent()
<ide> $this->assertSame('hello@laravel.com', $sentMessage->getEnvelope()->getRecipients()[0]->getAddress());
<ide> $this->assertStringContainsString('X-Metadata-origin: test-suite', $sentMessage->toString());
<ide> $this->assertStringContainsString('X-Metadata-user_id: 1', $sentMessage->toString());
<add>
<add> $this->assertTrue($mailable->hasMetadata('origin', 'test-suite'));
<add> $this->assertTrue($mailable->hasMetadata('user_id', 1));
<add> $this->assertFalse($mailable->hasMetadata('test', 'test'));
<add> $mailable->assertHasMetadata('origin', 'test-suite');
<add> $mailable->assertHasMetadata('user_id', 1);
<add> try {
<add> $mailable->assertHasMetadata('test', 'test');
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> $this->assertSame("Did not see expected key [test] and value [test] in email metadata.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide> }
<ide>
<ide> public function testMailableTagGetsSent()
<ide> public function testMailableTagGetsSent()
<ide> $this->assertSame('hello@laravel.com', $sentMessage->getEnvelope()->getRecipients()[0]->getAddress());
<ide> $this->assertStringContainsString('X-Tag: test', $sentMessage->toString());
<ide> $this->assertStringContainsString('X-Tag: foo', $sentMessage->toString());
<add>
<add> $this->assertTrue($mailable->hasTag('test'));
<add> $this->assertTrue($mailable->hasTag('foo'));
<add> $this->assertFalse($mailable->hasTag('bar'));
<add> $mailable->assertHasTag('test');
<add> $mailable->assertHasTag('foo');
<add> try {
<add> $mailable->assertHasTag('bar');
<add> $this->fail();
<add> } catch (AssertionFailedError $e) {
<add> $this->assertSame("Did not see expected tag [bar] in email tags.\nFailed asserting that false is true.", $e->getMessage());
<add> }
<ide> }
<ide>
<ide> public function testItCanAttachMultipleFiles()
<ide> public function build()
<ide>
<ide> $mailable->assertHasAttachmentFromStorage('/path/to/foo.jpg');
<ide> }
<add>
<add> public function testAssertHasSubject()
<add> {
<add>
<add> }
<ide> }
<ide>
<ide> class WelcomeMailableStub extends Mailable | 2 |
Python | Python | add missing skipunless(django_filters) | 4cb164b66c0784ce79054925d4744deb5b18d8b2 | <ide><path>tests/test_filters.py
<ide> def setUp(self):
<ide> for d in data:
<ide> DjangoFilterOrderingModel.objects.create(**d)
<ide>
<add> @unittest.skipUnless(django_filters, 'django-filter not installed')
<ide> def test_default_ordering(self):
<ide> class DjangoFilterOrderingView(generics.ListAPIView):
<ide> serializer_class = DjangoFilterOrderingSerializer | 1 |
Python | Python | fix issues with gantt view | 506ee1f06c9771b3459c129266187599b21db05f | <ide><path>airflow/www/views.py
<ide> def gantt(self, session=None):
<ide> )
<ide> )
<ide>
<del> # determine bars to show in the gantt chart
<del> gantt_bar_items = []
<del>
<ide> tasks = []
<ide> for ti in tis:
<del> end_date = ti.end_date or timezone.utcnow()
<ide> # prev_attempted_tries will reflect the currently running try_number
<ide> # or the try_number of the last complete run
<ide> # https://issues.apache.org/jira/browse/AIRFLOW-2143
<del> try_count = ti.prev_attempted_tries
<del> gantt_bar_items.append((ti.task_id, ti.start_date, end_date, ti.state, try_count))
<add> try_count = ti.prev_attempted_tries if ti.prev_attempted_tries != 0 else ti.try_number
<ide> task_dict = alchemy_to_dict(ti)
<add> task_dict['end_date'] = task_dict['end_date'] or timezone.utcnow()
<ide> task_dict['extraLinks'] = dag.get_task(ti.task_id).extra_links
<add> task_dict['try_number'] = try_count
<ide> tasks.append(task_dict)
<ide>
<ide> tf_count = 0
<ide> try_count = 1
<ide> prev_task_id = ""
<ide> for failed_task_instance in ti_fails:
<del> end_date = failed_task_instance.end_date or timezone.utcnow()
<del> start_date = failed_task_instance.start_date or end_date
<ide> if tf_count != 0 and failed_task_instance.task_id == prev_task_id:
<ide> try_count += 1
<ide> else:
<ide> try_count = 1
<ide> prev_task_id = failed_task_instance.task_id
<del> gantt_bar_items.append(
<del> (failed_task_instance.task_id, start_date, end_date, State.FAILED, try_count)
<del> )
<ide> tf_count += 1
<ide> task = dag.get_task(failed_task_instance.task_id)
<ide> task_dict = alchemy_to_dict(failed_task_instance)
<add> end_date = task_dict['end_date'] or timezone.utcnow()
<add> task_dict['end_date'] = end_date
<add> task_dict['start_date'] = task_dict['start_date'] or end_date
<ide> task_dict['state'] = State.FAILED
<ide> task_dict['operator'] = task.task_type
<ide> task_dict['try_number'] = try_count | 1 |
Javascript | Javascript | remove redundant code in doc/html.js | 974df9c2be11910d7aef381d73cb11a4bb547c20 | <ide><path>test/doctool/test-doctool-html.js
<ide> const testData = [
<ide> file: fixtures.path('order_of_end_tags_5873.md'),
<ide> html: '<h3>ClassMethod: Buffer.from(array) <span> ' +
<ide> '<a class="mark" href="#foo_class_method_buffer_from_array" ' +
<del> 'id="foo_class_method_buffer_from_array">#</a> </span> </h3><div' +
<del> 'class="signature"><ul><li><code>array</code><a ' +
<add> 'id="foo_class_method_buffer_from_array">#</a> </span> </h3>' +
<add> '<ul><li><code>array</code><a ' +
<ide> 'href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/' +
<ide> 'Reference/Global_Objects/Array" class="type"><Array></a></li>' +
<del> '</ul></div>'
<add> '</ul>'
<ide> },
<ide> {
<ide> file: fixtures.path('doc_with_yaml.md'),
<ide><path>tools/doc/html.js
<ide> function render(opts, cb) {
<ide> filename = path.basename(filename, '.md');
<ide>
<ide> parseText(lexed);
<del> lexed = parseLists(lexed);
<add> lexed = preprocessElements(lexed);
<ide>
<ide> // Generate the table of contents.
<ide> // This mutates the lexed contents in-place.
<ide> function parseText(lexed) {
<ide> });
<ide> }
<ide>
<del>// Just update the list item text in-place.
<del>// Lists that come right after a heading are what we're after.
<del>function parseLists(input) {
<add>// Preprocess stability blockquotes and YAML blocks.
<add>function preprocessElements(input) {
<ide> var state = null;
<del> const savedState = [];
<del> var depth = 0;
<ide> const output = [];
<ide> let headingIndex = -1;
<ide> let heading = null;
<ide>
<ide> output.links = input.links;
<ide> input.forEach(function(tok, index) {
<add> if (tok.type === 'heading') {
<add> headingIndex = index;
<add> heading = tok;
<add> }
<add> if (tok.type === 'html' && common.isYAMLBlock(tok.text)) {
<add> tok.text = parseYAML(tok.text);
<add> }
<ide> if (tok.type === 'blockquote_start') {
<del> savedState.push(state);
<ide> state = 'MAYBE_STABILITY_BQ';
<ide> return;
<ide> }
<ide> if (tok.type === 'blockquote_end' && state === 'MAYBE_STABILITY_BQ') {
<del> state = savedState.pop();
<add> state = null;
<ide> return;
<ide> }
<ide> if ((tok.type === 'paragraph' && state === 'MAYBE_STABILITY_BQ') ||
<ide> function parseLists(input) {
<ide> return;
<ide> } else if (state === 'MAYBE_STABILITY_BQ') {
<ide> output.push({ type: 'blockquote_start' });
<del> state = savedState.pop();
<del> }
<del> }
<del> if (state === null ||
<del> (state === 'AFTERHEADING' && tok.type === 'heading')) {
<del> if (tok.type === 'heading') {
<del> headingIndex = index;
<del> heading = tok;
<del> state = 'AFTERHEADING';
<del> }
<del> output.push(tok);
<del> return;
<del> }
<del> if (state === 'AFTERHEADING') {
<del> if (tok.type === 'list_start') {
<del> state = 'LIST';
<del> if (depth === 0) {
<del> output.push({ type: 'html', text: '<div class="signature">' });
<del> }
<del> depth++;
<del> output.push(tok);
<del> return;
<del> }
<del> if (tok.type === 'html' && common.isYAMLBlock(tok.text)) {
<del> tok.text = parseYAML(tok.text);
<del> }
<del> state = null;
<del> output.push(tok);
<del> return;
<del> }
<del> if (state === 'LIST') {
<del> if (tok.type === 'list_start') {
<del> depth++;
<del> output.push(tok);
<del> return;
<del> }
<del> if (tok.type === 'list_end') {
<del> depth--;
<del> output.push(tok);
<del> if (depth === 0) {
<del> state = null;
<del> output.push({ type: 'html', text: '</div>' });
<del> }
<del> return;
<add> state = null;
<ide> }
<ide> }
<ide> output.push(tok); | 2 |
Javascript | Javascript | reuse queueitem for module leaving | e66b51b8f710a9bc619ef9458f9e54042cc7fd93 | <ide><path>lib/buildChunkGraph.js
<ide> const visitModules = (
<ide> nextFreeModulePreOrderIndex++;
<ide> }
<ide>
<del> queue.push({
<del> action: LEAVE_MODULE,
<del> block,
<del> module,
<del> chunk,
<del> chunkGroup,
<del> chunkGroupInfo
<del> });
<add> // reuse queueItem
<add> queueItem.action = LEAVE_MODULE;
<add> queue.push(queueItem);
<ide> }
<ide> // fallthrough
<ide> case PROCESS_BLOCK: { | 1 |
Javascript | Javascript | remove beginwork shortcut | 1d437dc9ad11567e8da785534f1111755aff9e3e | <ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>, g
<ide> reconcileChildren(current, workInProgress, workInProgress.pendingProps);
<ide> // A yield component is just a placeholder, we can just run through the
<ide> // next one immediately.
<del> if (workInProgress.child) {
<del> return beginWork(
<del> workInProgress.child.alternate,
<del> workInProgress.child,
<del> priorityLevel
<del> );
<del> }
<del> return null;
<add> return workInProgress.child;
<ide> case HostComponent:
<ide> if (workInProgress.stateNode && config.beginUpdate) {
<ide> config.beginUpdate(workInProgress.stateNode);
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>, g
<ide> updateCoroutineComponent(current, workInProgress);
<ide> // This doesn't take arbitrary time so we could synchronously just begin
<ide> // eagerly do the work of workInProgress.child as an optimization.
<del> if (workInProgress.child) {
<del> return beginWork(
<del> workInProgress.child.alternate,
<del> workInProgress.child,
<del> priorityLevel
<del> );
<del> }
<ide> return workInProgress.child;
<ide> case YieldComponent:
<ide> // A yield component is just a placeholder, we can just run through the
<ide> // next one immediately.
<del> if (workInProgress.sibling) {
<del> return beginWork(
<del> workInProgress.sibling.alternate,
<del> workInProgress.sibling,
<del> priorityLevel
<del> );
<del> }
<ide> return null;
<ide> case Fragment:
<ide> updateFragment(current, workInProgress);
<del> if (workInProgress.child) {
<del> return beginWork(
<del> workInProgress.child.alternate,
<del> workInProgress.child,
<del> priorityLevel
<del> );
<del> }
<del> return null;
<add> return workInProgress.child;
<ide> default:
<ide> throw new Error('Unknown unit of work tag');
<ide> }
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js
<ide> describe('ReactIncremental', () => {
<ide> expect(fooCalled).toBe(false);
<ide> expect(barCalled).toBe(false);
<ide> // Do one step of work.
<del> ReactNoop.flushDeferredPri(7);
<add> ReactNoop.flushDeferredPri(7 + 5);
<ide> expect(fooCalled).toBe(true);
<ide> expect(barCalled).toBe(false);
<ide> // Do the rest of the work.
<ide> describe('ReactIncremental', () => {
<ide>
<ide> ReactNoop.render(<Foo text="bar" />);
<ide> // Flush part of the work
<del> ReactNoop.flushDeferredPri(20);
<add> ReactNoop.flushDeferredPri(20 + 5);
<ide>
<ide> expect(ops).toEqual(['Foo', 'Bar']);
<ide>
<ide> describe('ReactIncremental', () => {
<ide> ReactNoop.render(<Foo text="baz" />);
<ide>
<ide> // Flush part of the new work
<del> ReactNoop.flushDeferredPri(20);
<add> ReactNoop.flushDeferredPri(20 + 5);
<ide>
<ide> expect(ops).toEqual(['Foo', 'Bar']);
<ide>
<ide> describe('ReactIncremental', () => {
<ide>
<ide> // We're now rendering an update that will bail out on updating middle.
<ide> ReactNoop.render(<Foo text="bar" />);
<del> ReactNoop.flushDeferredPri(45);
<add> ReactNoop.flushDeferredPri(45 + 5);
<ide>
<ide> expect(ops).toEqual(['Foo', 'Bar', 'Bar']);
<ide>
<ide> describe('ReactIncremental', () => {
<ide>
<ide> // Init
<ide> ReactNoop.render(<Foo text="foo" />);
<del> ReactNoop.flushDeferredPri(52);
<add> ReactNoop.flushDeferredPri(52 + 5);
<ide>
<ide> expect(ops).toEqual(['Foo', 'Bar', 'Tester', 'Bar']);
<ide>
<ide> describe('ReactIncremental', () => {
<ide>
<ide> // Init
<ide> ReactNoop.render(<Foo text="foo" text2="foo" step={0} />);
<del> ReactNoop.flushDeferredPri(55 + 25);
<add> ReactNoop.flushDeferredPri(55 + 25 + 5);
<ide>
<ide> // We only finish the higher priority work. So the low pri content
<ide> // has not yet finished mounting.
<ide> describe('ReactIncremental', () => {
<ide> // Make a quick update which will schedule low priority work to
<ide> // update the middle content.
<ide> ReactNoop.render(<Foo text="bar" text2="bar" step={1} />);
<del> ReactNoop.flushDeferredPri(30 + 25);
<add> ReactNoop.flushDeferredPri(30 + 25 + 5);
<ide>
<ide> expect(ops).toEqual(['Foo', 'Bar']);
<ide>
<ide> describe('ReactIncremental', () => {
<ide> ops = [];
<ide>
<ide> // The middle content is now pending rendering...
<del> ReactNoop.flushDeferredPri(30 + 25);
<add> ReactNoop.flushDeferredPri(30 + 25 + 5);
<ide> expect(ops).toEqual(['Content', 'Middle', 'Bar']); // One more Middle left.
<ide>
<ide> ops = []; | 2 |
Javascript | Javascript | fix meta jquery.extend issue | 8348aba5031aa8cce8b3bb9a14be94b52af527ec | <ide><path>packages/ember-metal/lib/utils.js
<ide> if (Object.freeze) Object.freeze(EMPTY_META);
<ide>
<ide> var isDefinePropertySimulated = Ember.platform.defineProperty.isSimulated;
<ide>
<add>function Meta(obj) {
<add> this.descs = {};
<add> this.watching = {};
<add> this.cache = {};
<add> this.source = obj;
<add>}
<add>
<add>if (isDefinePropertySimulated) {
<add> // on platforms that don't support enumerable false
<add> // make meta fail jQuery.isPlainObject() to hide from
<add> // jQuery.extend() by having a property that fails
<add> // hasOwnProperty check.
<add> Meta.prototype.__preventPlainObject__ = true;
<add>}
<add>
<ide> /**
<ide> @private
<ide> @function
<ide> Ember.meta = function meta(obj, writable) {
<ide> if (writable===false) return ret || EMPTY_META;
<ide>
<ide> if (!ret) {
<del> o_defineProperty(obj, META_KEY, META_DESC);
<del>
<del> if (isDefinePropertySimulated) {
<del> // on platforms that don't support enumerable false
<del> // make meta fail jQuery.isPlainObject() to hide from
<del> // jQuery.extend() by having a property that fails
<del> // hasOwnProperty check.
<del> ret = o_create({__preventPlainObject__: true});
<del> }
<add> if (!isDefinePropertySimulated) o_defineProperty(obj, META_KEY, META_DESC);
<ide>
<del> ret = {
<del> descs: {},
<del> watching: {},
<del> cache: {},
<del> source: obj
<del> };
<add> ret = new Meta(obj);
<ide>
<ide> if (MANDATORY_SETTER) { ret.values = {}; }
<ide> | 1 |
PHP | PHP | fix unpack error in validationrule | 77209131bafcc91d39807888714ea53b27692425 | <ide><path>src/Validation/ValidationRule.php
<ide> public function process($value, array $providers, array $context = [])
<ide> }
<ide>
<ide> if ($this->_pass) {
<del> $args = array_merge([$value], $this->_pass, [$context]);
<add> $args = array_values(array_merge([$value], $this->_pass, [$context]));
<ide> $result = $callable(...$args);
<ide> } else {
<ide> $result = $callable($value, $context);
<ide><path>tests/TestCase/Validation/ValidationRuleTest.php
<ide> public function testCustomMethods()
<ide> $Rule = new ValidationRule(['rule' => 'willFail']);
<ide> $this->assertFalse($Rule->process($data, $providers, $context));
<ide>
<del> $Rule = new ValidationRule(['rule' => 'willPass']);
<add> $Rule = new ValidationRule(['rule' => 'willPass', 'pass' => ['key' => 'value']]);
<ide> $this->assertTrue($Rule->process($data, $providers, $context));
<ide>
<ide> $Rule = new ValidationRule(['rule' => 'willFail3']); | 2 |
Javascript | Javascript | fix server.listen error message | 47759429578952672ef9d1079412ed56aad77c4d | <ide><path>lib/net.js
<ide> Server.prototype.listen = function() {
<ide> return this;
<ide> }
<ide>
<del> throw new Error('Invalid listen argument: ' + options);
<add> throw new Error('Invalid listen argument: ' + util.inspect(options));
<ide> };
<ide>
<ide> function lookupAndListen(self, port, address, backlog, exclusive) {
<ide><path>test/parallel/test-net-listen-port-option.js
<del>'use strict';
<del>const common = require('../common');
<del>const assert = require('assert');
<del>const net = require('net');
<del>
<del>function close() { this.close(); }
<del>
<del>// From lib/net.js
<del>function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; }
<del>
<del>function isPipeName(s) {
<del> return typeof s === 'string' && toNumber(s) === false;
<del>}
<del>
<del>const listenVariants = [
<del> (port, cb) => net.Server().listen({port}, cb),
<del> (port, cb) => net.Server().listen(port, cb)
<del>];
<del>
<del>listenVariants.forEach((listenVariant, i) => {
<del> listenVariant(undefined, common.mustCall(close));
<del> listenVariant('0', common.mustCall(close));
<del>
<del> [
<del> 'nan',
<del> -1,
<del> 123.456,
<del> 0x10000,
<del> 1 / 0,
<del> -1 / 0,
<del> '+Infinity',
<del> '-Infinity'
<del> ].forEach((port) => {
<del> if (i === 1 && isPipeName(port)) {
<del> // skip this, because listen(port) can also be listen(path)
<del> return;
<del> }
<del> assert.throws(() => listenVariant(port, common.mustNotCall()),
<del> /"port" argument must be >= 0 and < 65536/i);
<del> });
<del>
<del> [null, true, false].forEach((port) =>
<del> assert.throws(() => listenVariant(port, common.mustNotCall()),
<del> /invalid listen argument/i));
<del>});
<ide><path>test/parallel/test-net-server-listen-options.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const net = require('net');
<add>const util = require('util');
<add>
<add>function close() { this.close(); }
<add>
<add>function listenError(literals, ...values) {
<add> let result = literals[0];
<add> for (const [i, value] of values.entries()) {
<add> const str = util.inspect(value);
<add> // Need to escape special characters.
<add> result += str.replace(/[\\^$.*+?()[\]{}|=!<>:-]/g, '\\$&');
<add> result += literals[i + 1];
<add> }
<add> return new RegExp(`Error: Invalid listen argument: ${result}`);
<add>}
<add>
<add>{
<add> // Test listen()
<add> net.createServer().listen().on('listening', common.mustCall(close));
<add> // Test listen(cb)
<add> net.createServer().listen(common.mustCall(close));
<add>}
<add>
<add>// Test listen(port, cb) and listen({port: port}, cb) combinations
<add>const listenOnPort = [
<add> (port, cb) => net.createServer().listen({port}, cb),
<add> (port, cb) => net.createServer().listen(port, cb)
<add>];
<add>
<add>{
<add> const portError = /^RangeError: "port" argument must be >= 0 and < 65536$/;
<add> for (const listen of listenOnPort) {
<add> // Arbitrary unused ports
<add> listen('0', common.mustCall(close));
<add> listen(0, common.mustCall(close));
<add> listen(undefined, common.mustCall(close));
<add> // Test invalid ports
<add> assert.throws(() => listen(-1, common.mustNotCall()), portError);
<add> assert.throws(() => listen(NaN, common.mustNotCall()), portError);
<add> assert.throws(() => listen(123.456, common.mustNotCall()), portError);
<add> assert.throws(() => listen(65536, common.mustNotCall()), portError);
<add> assert.throws(() => listen(1 / 0, common.mustNotCall()), portError);
<add> assert.throws(() => listen(-1 / 0, common.mustNotCall()), portError);
<add> }
<add> // In listen(options, cb), port takes precedence over path
<add> assert.throws(() => {
<add> net.createServer().listen({ port: -1, path: common.PIPE },
<add> common.mustNotCall());
<add> }, portError);
<add>}
<add>
<add>{
<add> function shouldFailToListen(options, optionsInMessage) {
<add> // Plain arguments get normalized into an object before
<add> // formatted in message, options objects don't.
<add> if (arguments.length === 1) {
<add> optionsInMessage = options;
<add> }
<add> const block = () => {
<add> net.createServer().listen(options, common.mustNotCall());
<add> };
<add> assert.throws(block, listenError`${optionsInMessage}`,
<add> `expect listen(${util.inspect(options)}) to throw`);
<add> }
<add>
<add> shouldFailToListen(null, { port: null });
<add> shouldFailToListen({ port: null });
<add> shouldFailToListen(false, { port: false });
<add> shouldFailToListen({ port: false });
<add> shouldFailToListen(true, { port: true });
<add> shouldFailToListen({ port: true });
<add> // Invalid fd as listen(handle)
<add> shouldFailToListen({ fd: -1 });
<add> // Invalid path in listen(options)
<add> shouldFailToListen({ path: -1 });
<add> // Host without port
<add> shouldFailToListen({ host: 'localhost' });
<add>} | 3 |
Python | Python | close some filehandlers and pipes after being done | b831444bee734537daeaffd1455eb88663ee3763 | <ide><path>numpy/distutils/fcompiler/gnu.py
<ide> def _can_target(cmd, arch):
<ide> """Return true if the architecture supports the -arch flag"""
<ide> newcmd = cmd[:]
<ide> fid, filename = tempfile.mkstemp(suffix=".f")
<add> fid.close()
<ide> try:
<ide> d = os.path.dirname(filename)
<ide> output = os.path.splitext(filename)[0] + ".o"
<ide><path>numpy/distutils/system_info.py
<ide> def libpaths(paths, bits):
<ide> # tests are run in debug mode Python 3.
<ide> tmp = open(os.devnull, 'w')
<ide> p = sp.Popen(["gcc", "-print-multiarch"], stdout=sp.PIPE,
<del> stderr=tmp)
<add> stderr=tmp)
<ide> except (OSError, DistutilsError):
<ide> # OSError if gcc is not installed, or SandboxViolation (DistutilsError
<ide> # subclass) if an old setuptools bug is triggered (see gh-3160).
<ide> def get_mkl_rootdir(self):
<ide> paths = os.environ.get('LD_LIBRARY_PATH', '').split(os.pathsep)
<ide> ld_so_conf = '/etc/ld.so.conf'
<ide> if os.path.isfile(ld_so_conf):
<del> for d in open(ld_so_conf, 'r'):
<del> d = d.strip()
<del> if d:
<del> paths.append(d)
<add> with open(ld_so_conf, 'r') as f:
<add> for d in f:
<add> d = d.strip()
<add> if d:
<add> paths.append(d)
<ide> intel_mkl_dirs = []
<ide> for path in paths:
<ide> path_atoms = path.split(os.sep)
<ide><path>numpy/distutils/tests/test_system_info.py
<ide> def have_compiler():
<ide> return False
<ide> cmd = [compiler.cc]
<ide> try:
<del> Popen(cmd, stdout=PIPE, stderr=PIPE)
<add> p = Popen(cmd, stdout=PIPE, stderr=PIPE)
<add> p.stdout.close()
<add> p.stderr.close()
<ide> except OSError:
<ide> return False
<ide> return True | 3 |
Python | Python | check platform.system for npymath | 2a26477c67bf319428ddcb78a5b6a8777754b845 | <ide><path>numpy/core/setup.py
<ide> import copy
<ide> import sysconfig
<ide> import warnings
<add>import platform
<ide> from os.path import join
<del>from numpy.distutils import log, customized_ccompiler
<add>from numpy.distutils import log
<ide> from distutils.dep_util import newer
<ide> from distutils.sysconfig import get_config_var
<ide> from numpy._build_utils.apple_accelerate import (
<ide> def get_mathlib_info(*args):
<ide> join('src', 'npymath', 'halffloat.c')
<ide> ]
<ide>
<del> compiler_type = customized_ccompiler().compiler_type
<del> is_msvc = compiler_type == 'msvc'
<del> is_msvc = is_msvc or (sys.platform == 'win32' and compiler_type in ('clang', 'intel'))
<del>
<add> # Must be true for CRT compilers but not MinGW/cygwin. See gh-9977.
<add> is_msvc = platform.system() == 'Windows'
<ide> config.add_installed_library('npymath',
<ide> sources=npymath_sources + [get_mathlib_info],
<ide> install_dir='lib', | 1 |
Go | Go | remove daemon dependency from api/server | 1af76ef5970202bdbc7024d825c0fcfcc4ec6ede | <ide><path>api/server/router/container/backend.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/api/types/backend"
<del> "github.com/docker/docker/daemon/exec"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/engine-api/types"
<ide> import (
<ide> // execBackend includes functions to implement to provide exec functionality.
<ide> type execBackend interface {
<ide> ContainerExecCreate(config *types.ExecConfig) (string, error)
<del> ContainerExecInspect(id string) (*exec.Config, error)
<add> ContainerExecInspect(id string) (*backend.ExecInspect, error)
<ide> ContainerExecResize(name string, height, width int) error
<ide> ContainerExecStart(name string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) error
<ide> ExecExists(name string) (bool, error)
<ide><path>api/server/server.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/api/server/router"
<del> "github.com/docker/docker/api/server/router/build"
<del> "github.com/docker/docker/api/server/router/container"
<del> "github.com/docker/docker/api/server/router/image"
<del> "github.com/docker/docker/api/server/router/network"
<del> "github.com/docker/docker/api/server/router/system"
<del> "github.com/docker/docker/api/server/router/volume"
<del> "github.com/docker/docker/builder/dockerfile"
<del> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/pkg/authorization"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/go-connections/sockets"
<ide> func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc {
<ide> }
<ide> }
<ide>
<del>// InitRouters initializes a list of routers for the server.
<del>func (s *Server) InitRouters(d *daemon.Daemon) {
<del> s.addRouter(container.NewRouter(d))
<del> s.addRouter(image.NewRouter(d))
<del> s.addRouter(network.NewRouter(d))
<del> s.addRouter(system.NewRouter(d))
<del> s.addRouter(volume.NewRouter(d))
<del> s.addRouter(build.NewRouter(dockerfile.NewBuildManager(d)))
<add>// AddRouters initializes a list of routers for the server.
<add>func (s *Server) AddRouters(routers ...router.Router) {
<add> for _, r := range routers {
<add> s.addRouter(r)
<add> }
<ide> }
<ide>
<ide> // addRouter adds a new router to the server.
<ide> func (s *Server) initRouterSwapper() {
<ide> // Reload reads configuration changes and modifies the
<ide> // server according to those changes.
<ide> // Currently, only the --debug configuration is taken into account.
<del>func (s *Server) Reload(config *daemon.Config) {
<add>func (s *Server) Reload(debug bool) {
<ide> debugEnabled := utils.IsDebugEnabled()
<ide> switch {
<del> case debugEnabled && !config.Debug: // disable debug
<add> case debugEnabled && !debug: // disable debug
<ide> utils.DisableDebug()
<ide> s.routerSwapper.Swap(s.createMux())
<del> case config.Debug && !debugEnabled: // enable debug
<add> case debug && !debugEnabled: // enable debug
<ide> utils.EnableDebug()
<ide> s.routerSwapper.Swap(s.createMux())
<ide> }
<ide><path>api/types/backend/backend.go
<ide> type ContainerStatsConfig struct {
<ide> Stop <-chan bool
<ide> Version string
<ide> }
<add>
<add>// ExecInspect holds information about a running process started
<add>// with docker exec.
<add>type ExecInspect struct {
<add> ID string
<add> Running bool
<add> ExitCode *int
<add> ProcessConfig *ExecProcessConfig
<add> OpenStdin bool
<add> OpenStderr bool
<add> OpenStdout bool
<add> CanRemove bool
<add> ContainerID string
<add> DetachKeys []byte
<add>}
<add>
<add>// ExecProcessConfig holds information about the exec process
<add>// running on the host.
<add>type ExecProcessConfig struct {
<add> Tty bool `json:"tty"`
<add> Entrypoint string `json:"entrypoint"`
<add> Arguments []string `json:"arguments"`
<add> Privileged *bool `json:"privileged,omitempty"`
<add> User string `json:"user,omitempty"`
<add>}
<ide><path>daemon/inspect.go
<ide> import (
<ide> "fmt"
<ide> "time"
<ide>
<add> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/container"
<del> "github.com/docker/docker/daemon/exec"
<ide> "github.com/docker/docker/daemon/network"
<ide> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/engine-api/types"
<ide> func (daemon *Daemon) getInspectData(container *container.Container, size bool)
<ide>
<ide> // ContainerExecInspect returns low-level information about the exec
<ide> // command. An error is returned if the exec cannot be found.
<del>func (daemon *Daemon) ContainerExecInspect(id string) (*exec.Config, error) {
<del> eConfig, err := daemon.getExecConfig(id)
<add>func (daemon *Daemon) ContainerExecInspect(id string) (*backend.ExecInspect, error) {
<add> e, err := daemon.getExecConfig(id)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> return eConfig, nil
<add>
<add> pc := inspectExecProcessConfig(e)
<add>
<add> return &backend.ExecInspect{
<add> ID: e.ID,
<add> Running: e.Running,
<add> ExitCode: e.ExitCode,
<add> ProcessConfig: pc,
<add> OpenStdin: e.OpenStdin,
<add> OpenStdout: e.OpenStdout,
<add> OpenStderr: e.OpenStderr,
<add> CanRemove: e.CanRemove,
<add> ContainerID: e.ContainerID,
<add> DetachKeys: e.DetachKeys,
<add> }, nil
<ide> }
<ide>
<ide> // VolumeInspect looks up a volume by name. An error is returned if
<ide><path>daemon/inspect_unix.go
<ide> package daemon
<ide>
<ide> import (
<add> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/container"
<add> "github.com/docker/docker/daemon/exec"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/versions/v1p19"
<ide> )
<ide> func addMountPoints(container *container.Container) []types.MountPoint {
<ide> }
<ide> return mountPoints
<ide> }
<add>
<add>func inspectExecProcessConfig(e *exec.Config) *backend.ExecProcessConfig {
<add> return &backend.ExecProcessConfig{
<add> Tty: e.ProcessConfig.Tty,
<add> Entrypoint: e.ProcessConfig.Entrypoint,
<add> Arguments: e.ProcessConfig.Arguments,
<add> Privileged: &e.ProcessConfig.Privileged,
<add> User: e.ProcessConfig.User,
<add> }
<add>}
<ide><path>daemon/inspect_windows.go
<ide> package daemon
<ide>
<ide> import (
<add> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/container"
<add> "github.com/docker/docker/daemon/exec"
<ide> "github.com/docker/engine-api/types"
<ide> )
<ide>
<ide> func addMountPoints(container *container.Container) []types.MountPoint {
<ide> func (daemon *Daemon) containerInspectPre120(name string) (*types.ContainerJSON, error) {
<ide> return daemon.containerInspectCurrent(name, false)
<ide> }
<add>
<add>func inspectExecProcessConfig(e *exec.Config) *backend.ExecProcessConfig {
<add> return &backend.ExecProcessConfig{
<add> Tty: e.ProcessConfig.Tty,
<add> Entrypoint: e.ProcessConfig.Entrypoint,
<add> Arguments: e.ProcessConfig.Arguments,
<add> }
<add>}
<ide><path>docker/daemon.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/uuid"
<ide> apiserver "github.com/docker/docker/api/server"
<add> "github.com/docker/docker/api/server/router/build"
<add> "github.com/docker/docker/api/server/router/container"
<add> "github.com/docker/docker/api/server/router/image"
<add> "github.com/docker/docker/api/server/router/network"
<add> systemrouter "github.com/docker/docker/api/server/router/system"
<add> "github.com/docker/docker/api/server/router/volume"
<add> "github.com/docker/docker/builder/dockerfile"
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/daemon"
<ide> func (cli *DaemonCli) CmdDaemon(args ...string) error {
<ide> "graphdriver": d.GraphDriverName(),
<ide> }).Info("Docker daemon")
<ide>
<del> api.InitRouters(d)
<add> initRouters(api, d)
<ide>
<ide> reload := func(config *daemon.Config) {
<ide> if err := d.Reload(config); err != nil {
<ide> logrus.Errorf("Error reconfiguring the daemon: %v", err)
<ide> return
<ide> }
<del> api.Reload(config)
<add> api.Reload(config.Debug)
<ide> }
<ide>
<ide> setupConfigReloadTrap(*configFile, cli.flags, reload)
<ide> func loadDaemonCliConfig(config *daemon.Config, daemonFlags *flag.FlagSet, commo
<ide>
<ide> return config, nil
<ide> }
<add>
<add>func initRouters(s *apiserver.Server, d *daemon.Daemon) {
<add> s.AddRouters(container.NewRouter(d),
<add> image.NewRouter(d),
<add> network.NewRouter(d),
<add> systemrouter.NewRouter(d),
<add> volume.NewRouter(d),
<add> build.NewRouter(dockerfile.NewBuildManager(d)))
<add>} | 7 |
Java | Java | avoid synthesizing annotations unnecessarily | 31fa1569c54649c7f3cbf7ec330e2a7232c7cd3a | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/TypeMappedAnnotation.java
<ide> private <T extends Map<String, Object>> Object adaptValueForMapOptions(Method at
<ide> }
<ide>
<ide> @Override
<add> @SuppressWarnings("unchecked")
<ide> protected A createSynthesized() {
<add> if (this.rootAttributes instanceof Annotation) {
<add> // Nothing to synthesize?
<add> if (this.resolvedRootMirrors.length == 0 && this.resolvedMirrors.length == 0) {
<add> return (A) this.rootAttributes;
<add> }
<add> // Already synthesized?
<add> if (this.rootAttributes instanceof SynthesizedAnnotation) {
<add> return (A) this.rootAttributes;
<add> }
<add> }
<ide> return SynthesizedMergedAnnotationInvocationHandler.createProxy(this, getType());
<ide> }
<ide>
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.util.ReflectionUtils;
<ide>
<add>import static java.lang.annotation.RetentionPolicy.RUNTIME;
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
<ide> import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
<ide> void synthesizeAlreadySynthesized() throws Exception {
<ide> assertThat(synthesizedWebMapping.value()).containsExactly("/test");
<ide> }
<ide>
<add> @Test
<add> void synthesizeShouldNotSynthesizeNonsynthesizableAnnotations() throws Exception {
<add> Method method = getClass().getDeclaredMethod("getId");
<add> Id id = method.getAnnotation(Id.class);
<add> assertThat(id).isNotNull();
<add>
<add> Id synthesizedId = MergedAnnotation.from(id).synthesize();
<add> assertThat(id).isEqualTo(synthesizedId);
<add> // It doesn't make sense to synthesize {@code @Id} since it declares zero attributes.
<add> assertThat(synthesizedId).isNotInstanceOf(SynthesizedAnnotation.class);
<add> assertThat(id).isSameAs(synthesizedId);
<add> }
<add>
<add> /**
<add> * If an attempt is made to synthesize an annotation from an annotation instance
<add> * that has already been synthesized, the original synthesized annotation should
<add> * ideally be returned as-is without creating a new proxy instance with the same
<add> * values.
<add> */
<add> @Test
<add> void synthesizeShouldNotResynthesizeAlreadySynthesizedAnnotations() throws Exception {
<add> Method method = WebController.class.getMethod("handleMappedWithValueAttribute");
<add> RequestMapping webMapping = method.getAnnotation(RequestMapping.class);
<add> assertThat(webMapping).isNotNull();
<add>
<add> MergedAnnotation<RequestMapping> mergedAnnotation1 = MergedAnnotation.from(webMapping);
<add> RequestMapping synthesizedWebMapping1 = mergedAnnotation1.synthesize();
<add> RequestMapping synthesizedWebMapping2 = MergedAnnotation.from(webMapping).synthesize();
<add>
<add> assertThat(synthesizedWebMapping1).isInstanceOf(SynthesizedAnnotation.class);
<add> assertThat(synthesizedWebMapping2).isInstanceOf(SynthesizedAnnotation.class);
<add> assertThat(synthesizedWebMapping1).isEqualTo(synthesizedWebMapping2);
<add>
<add> // Synthesizing an annotation from a different MergedAnnotation results in a different synthesized annotation instance.
<add> assertThat(synthesizedWebMapping1).isNotSameAs(synthesizedWebMapping2);
<add> // Synthesizing an annotation from the same MergedAnnotation results in the same synthesized annotation instance.
<add> assertThat(synthesizedWebMapping1).isSameAs(mergedAnnotation1.synthesize());
<add>
<add> RequestMapping synthesizedAgainWebMapping = MergedAnnotation.from(synthesizedWebMapping1).synthesize();
<add> assertThat(synthesizedWebMapping1).isEqualTo(synthesizedAgainWebMapping);
<add> // Synthesizing an already synthesized annotation results in the original synthesized annotation instance.
<add> assertThat(synthesizedWebMapping1).isSameAs(synthesizedAgainWebMapping);
<add> }
<add>
<ide> @Test
<ide> void synthesizeWhenAliasForIsMissingAttributeDeclaration() throws Exception {
<ide> AliasForWithMissingAttributeDeclaration annotation =
<ide> public void handleMappedWithDifferentPathAndValueAttributes() {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Mimics javax.persistence.Id
<add> */
<add> @Retention(RUNTIME)
<add> @interface Id {
<add> }
<add>
<add> @Id
<add> private Long getId() {
<add> return 42L;
<add> }
<add>
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @interface TestConfiguration {
<ide> | 2 |
Ruby | Ruby | dump config directly | a150403eb9878045696e5860a1a7488838a7a0d2 | <ide><path>Library/Contributions/cmd/brew-gist-logs.rb
<ide> require 'formula'
<add>require 'cmd/config'
<ide> require 'net/http'
<ide> require 'net/https'
<add>require 'stringio'
<ide>
<ide> def gist_logs f
<ide> if ARGV.include? '--new-issue'
<ide> def load_logs name
<ide> end
<ide>
<ide> def append_config files
<del> files['config.out'] = {:content => `brew config 2>&1`}
<add> s = StringIO.new
<add> Homebrew.dump_verbose_config(s)
<add> files["config.out"] = { :content => s.string }
<ide> end
<ide>
<ide> def append_doctor files | 1 |
Javascript | Javascript | update error log | 71cc102af1be92d952ceb29d8e632b1c3edcc4f2 | <ide><path>lib/runtime/PublicPathRuntimeModule.js
<ide> class PublicPathRuntimeModule extends RuntimeModule {
<ide> if ("currentScript" in window.document) {
<ide> return window.document.currentScript.src.replace(/[^\\/]+$/, "");
<ide> } else {
<del> throw new Error("Webpack: Auto public path is not supported in modules or when 'document.currentScript' is unavailable. Set 'publicPath' config explicitly.");
<add> throw new Error("Webpack: Auto public path is not supported in modules or when 'document.currentScript' is unavailable. Use a polyfill or set 'publicPath' config explicitly.");
<ide> }
<ide> })();`;
<ide> } else { | 1 |
Ruby | Ruby | improve check for 'install_name_tool'" | eb137dc9248cf3b975b35fae2226c45d3dd9a0ab | <ide><path>Library/Homebrew/diagnostic.rb
<ide> def check_for_stray_developer_directory
<ide> def check_for_bad_install_name_tool
<ide> return if MacOS.version < "10.9"
<ide>
<del> install_name_tool = OS::Mac.install_name_tool
<del> libs = Pathname.new(install_name_tool).dynamically_linked_libraries
<add> libs = Pathname.new("/usr/bin/install_name_tool").dynamically_linked_libraries
<ide>
<ide> # otool may not work, for example if the Xcode license hasn't been accepted yet
<ide> return if libs.empty?
<ide>
<del> expectedLibs = ["/usr/lib/libSystem.B.dylib", "/usr/lib/libxcselect.dylib"]
<del> if (libs & expectedLibs).empty? then <<-EOS.undent
<del> You have an outdated version of #{install_name_tool} installed.
<add> unless libs.include? "/usr/lib/libxcselect.dylib" then <<-EOS.undent
<add> You have an outdated version of /usr/bin/install_name_tool installed.
<ide> This will cause binary package installations to fail.
<ide> This can happen if you install osx-gcc-installer or RailsInstaller.
<ide> To restore it, you must reinstall OS X or restore the binary from | 1 |
PHP | PHP | fix failing tests for setdefaultoutputtimezone() | 62ae2ba9694d22e41512005c2b79bd3a5f8666fa | <ide><path>src/I18n/DateFormatTrait.php
<ide> public function i18nFormat($format = null, $timezone = null, $locale = null)
<ide> $time = $this;
<ide>
<ide> if ($time instanceof Time || $time instanceof FrozenTime) {
<del> // Remove before merge:
<del> // if ((is_string($time->timezone) && $time->timezone === 'UTC')
<del> // || ($time->timezone instanceof \DateTimeZone && $time->timezone->getName() === '+0:00')
<del> // ) {
<del> // }
<del> // if ($time->getOffset() !== 0) {
<del> // $time = clone $time;
<del> // $time->add(new \DateInterval('PT' . $time->getOffset() / 60 . 'M'));
<del> // }
<ide> $timezone = $timezone ?: static::getDefaultOutputTimezone();
<ide> }
<add> // Detect and prevent null timezone transitions, as datefmt_create will
<add> // doubly apply the TZ offset.
<add> $currentTimezone = $time->getTimezone();
<add> if ($timezone && (
<add> (is_string($timezone) && $currentTimezone->getName() === $timezone) ||
<add> ($timezone instanceof DateTimeZone && $currentTimezone->getName() === $timezone->getName())
<add> )) {
<add> $timezone = null;
<add> }
<ide>
<ide> if ($timezone) {
<ide> // Handle the immutable and mutable object cases.
<ide><path>tests/TestCase/I18n/TimeTest.php
<ide> public function testI18nFormatWithDefaultOutputTimezone($class)
<ide> */
<ide> public function testI18nFormatWithOffsetTimezone($class)
<ide> {
<add> // Default output format is in UTC
<ide> $time = new $class('2014-01-01T00:00:00+00');
<ide> $result = $time->i18nFormat(\IntlDateFormatter::FULL);
<ide> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT';
<ide> $this->assertTimeFormat($expected, $result);
<ide>
<add> $class::setDefaultOutputTimezone('GMT+09:00');
<ide> $time = new $class('2014-01-01T00:00:00+09');
<ide> $result = $time->i18nFormat(\IntlDateFormatter::FULL);
<ide> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT+09:00';
<ide> $this->assertTimeFormat($expected, $result);
<ide>
<add> $class::setDefaultOutputTimezone('GMT-01:30');
<ide> $time = new $class('2014-01-01T00:00:00-01:30');
<ide> $result = $time->i18nFormat(\IntlDateFormatter::FULL);
<ide> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT-01:30';
<ide> public function testI18nFormatWithOffsetTimezone($class)
<ide> */
<ide> public function testI18nFormatWithOffsetTimezoneWithDefaultOutputTimezone($class)
<ide> {
<add> // America/Vancouver is GMT-8 in the winter
<ide> $class::setDefaultOutputTimezone('America/Vancouver');
<ide>
<ide> $time = new $class('2014-01-01T00:00:00+00');
<ide> $result = $time->i18nFormat(\IntlDateFormatter::FULL);
<del> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT';
<del> $this->assertTimeFormat($expected, $result);
<add> $expected = 'Tuesday December 31 2013 4:00:00 PM Pacific Standard Time';
<add> $this->assertTimeFormat($expected, $result, 'GMT to GMT-8 should be 8 hours');
<ide>
<del> $time = new $class('2014-01-01T00:00:00+09');
<add> $time = new $class('2014-01-01T00:00:00+09:00');
<ide> $result = $time->i18nFormat(\IntlDateFormatter::FULL);
<del> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT+09:00';
<del> $this->assertTimeFormat($expected, $result);
<add> $expected = 'Tuesday December 31 2013 7:00:00 AM Pacific Standard Time';
<add> $this->assertTimeFormat($expected, $result, 'GMT+9 to GMT-8 should be 17hrs');
<ide>
<ide> $time = new $class('2014-01-01T00:00:00-01:30');
<ide> $result = $time->i18nFormat(\IntlDateFormatter::FULL);
<del> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT-01:30';
<del> $this->assertTimeFormat($expected, $result);
<add> $expected = 'Tuesday December 31 2013 5:30:00 PM Pacific Standard Time';
<add> $this->assertTimeFormat($expected, $result, 'GMT-1:30 to GMT-8 is 6.5hrs');
<ide> }
<ide>
<ide> /**
<ide> public function testListTimezones($class)
<ide> * @dataProvider classNameProvider
<ide> * @return void
<ide> */
<del> public function testToStringWithdefaultOutputTimezone($class)
<add> public function testToStringWithDefaultOutputTimezone($class)
<ide> {
<ide> $class::setDefaultOutputTimezone('America/Vancouver');
<del> $time = new $class('2014-04-20 22:10');
<add> $time = new $class('2014-04-20 22:10 UTC');
<ide> $class::setDefaultLocale('fr-FR');
<ide> $class::setToStringFormat(\IntlDateFormatter::FULL);
<del> $this->assertTimeFormat('dimanche 20 avril 2014 15:10:00 UTC', (string)$time);
<add> $this->assertTimeFormat('dimanche 20 avril 2014 15:10:00 heure d’été du Pacifique', (string)$time);
<ide> }
<ide>
<ide> /** | 2 |
PHP | PHP | remove trailing whitespace | 14a2badcc5251e2750a898d3eecba957a044183d | <ide><path>src/I18n/Time.php
<ide> public function toUnixString()
<ide> public function timeAgoInWords(array $options = [])
<ide> {
<ide> $time = $this;
<del>
<add>
<ide> $timezone = null;
<ide> $format = static::$wordFormat;
<ide> $end = static::$wordEnd; | 1 |
Text | Text | add polidea as airflow user | a00d0b19b77504d71b01edc92f9e9869b49a75db | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [Plaid](https://www.plaid.com/) [[@plaid](https://github.com/plaid), [@AustinBGibbons](https://github.com/AustinBGibbons) & [@jeeyoungk](https://github.com/jeeyoungk)]
<ide> 1. [Playbuzz](https://www.playbuzz.com/) [[@clintonboys](https://github.com/clintonboys) & [@dbn](https://github.com/dbn)]
<ide> 1. [PMC](https://pmc.com/) [[@andrewm4894](https://github.com/andrewm4894)]
<add>1. [Polidea](https://www.polidea.com/) [[@potiuk](https://github.com/potiuk), [@mschickensoup](https://github.com/mschickensoup), [@mik-laj](https://github.com/mik-laj), [@turbaszek](https://github.com/turbaszek), [@michalslowikowski00](https://github.com/michalslowikowski00), [@olchas](https://github.com/olchas)]
<ide> 1. [Poshmark](https://www.poshmark.com)
<ide> 1. [Postmates](http://www.postmates.com) [[@syeoryn](https://github.com/syeoryn)]
<ide> 1. [Premise](http://www.premise.com) [[@jmccallum-premise](https://github.com/jmccallum-premise)] | 1 |
PHP | PHP | fix memcache tests | 92693ab792b60890e4706ea31a478a4e267cb0ae | <ide><path>lib/Cake/Cache/Engine/MemcacheEngine.php
<ide> <?php
<ide> /**
<del> * Memcache storage engine for cache
<del> *
<del> *
<del> * PHP 5
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://cakephp.org CakePHP(tm) Project
<del> * @package Cake.Cache.Engine
<ide> * @since CakePHP(tm) v 1.2.0.4933
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\Cache\Engine;
<add>
<ide> use Cake\Cache\CacheEngine;
<ide> use Cake\Error;
<ide> use Cake\Utility\Inflector;
<ide><path>lib/Cake/Test/TestCase/Cache/Engine/MemcacheEngineTest.php
<ide> <?php
<ide> /**
<del> * MemcacheEngineTest file
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<add> * CakePHP(tm) <http://book.cakephp.org/2.0/en/development/testing.html>
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> * Licensed under The MIT License
<ide> * Redistributions of files must retain the above copyright notice
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Cache.Engine
<ide> * @since CakePHP(tm) v 1.2.0.5434
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\Test\TestCase\Cache\Engine;
<add>
<ide> use Cake\Cache\Cache;
<ide> use Cake\Cache\Engine\MemcacheEngine;
<ide> use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<ide>
<add>/**
<add> * @package Cake.Test.TestCase.Cache.Engine
<add> */
<ide> class TestMemcacheEngine extends MemcacheEngine {
<ide>
<ide> /**
<ide> public function setMemcache($memcache) {
<ide> /**
<ide> * MemcacheEngineTest class
<ide> *
<del> * @package Cake.Test.Case.Cache.Engine
<add> * @package Cake.Test.TestCase.Cache.Engine
<ide> */
<ide> class MemcacheEngineTest extends TestCase {
<ide>
<ide> public function setUp() {
<ide> parent::setUp();
<ide> $this->skipIf(!class_exists('Memcache'), 'Memcache is not installed or configured properly.');
<ide>
<del> $this->_cacheDisable = Configure::read('Cache.disable');
<ide> Configure::write('Cache.disable', false);
<del> Cache::config('memcache', array(
<add> Configure::write('Cache.memcache', array(
<ide> 'engine' => 'Memcache',
<ide> 'prefix' => 'cake_',
<ide> 'duration' => 3600
<ide> public function setUp() {
<ide> */
<ide> public function tearDown() {
<ide> parent::tearDown();
<del> Configure::write('Cache.disable', $this->_cacheDisable);
<ide> Cache::drop('memcache');
<ide> Cache::drop('memcache_groups');
<ide> Cache::drop('memcache_helper');
<del> Cache::config('default');
<ide> }
<ide>
<ide> /**
<ide> public function testParseServerStringUnix() {
<ide> * @return void
<ide> */
<ide> public function testReadAndWriteCache() {
<del> Cache::set(array('duration' => 1), null, 'memcache');
<del>
<ide> $result = Cache::read('test', 'memcache');
<ide> $expecting = '';
<ide> $this->assertEquals($expecting, $result);
<ide> public function testReadAndWriteCache() {
<ide> * @return void
<ide> */
<ide> public function testExpiry() {
<del> Cache::set(array('duration' => 1), 'memcache');
<add> Cache::set(['duration' => 1], 'memcache');
<ide>
<ide> $result = Cache::read('test', 'memcache');
<ide> $this->assertFalse($result);
<ide> public function testExpiry() {
<ide> $result = Cache::read('other_test', 'memcache');
<ide> $this->assertFalse($result);
<ide>
<del> Cache::set(array('duration' => "+1 second"), 'memcache');
<add> Cache::set(['duration' => "+1 second"], 'memcache');
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<ide> $result = Cache::write('other_test', $data, 'memcache');
<ide> public function testExpiry() {
<ide> $result = Cache::read('other_test', 'memcache');
<ide> $this->assertFalse($result);
<ide>
<del> Cache::config('memcache', array('duration' => '+1 second'));
<add> Cache::set(['duration' => '+1 second'], 'memcache');
<ide> sleep(2);
<ide>
<ide> $result = Cache::read('other_test', 'memcache');
<ide> $this->assertFalse($result);
<ide>
<del> Cache::config('memcache', array('duration' => '+29 days'));
<add> Cache::set(['duration' => '+29 days'], 'memcache');
<ide> $data = 'this is a test of the emergency broadcasting system';
<ide> $result = Cache::write('long_expiry_test', $data, 'memcache');
<ide> $this->assertTrue($result);
<ide> public function testExpiry() {
<ide> $result = Cache::read('long_expiry_test', 'memcache');
<ide> $expecting = $data;
<ide> $this->assertEquals($expecting, $result);
<del>
<del> Cache::config('memcache', array('duration' => 3600));
<ide> }
<ide>
<ide> /**
<ide> public function testIncrement() {
<ide> * @return void
<ide> */
<ide> public function testConfigurationConflict() {
<del> Cache::config('long_memcache', array(
<add> Configure::write('Cache.long_memcache', [
<ide> 'engine' => 'Memcache',
<ide> 'duration' => '+2 seconds',
<del> 'servers' => array('127.0.0.1:11211'),
<del> ));
<del> Cache::config('short_memcache', array(
<add> 'servers' => ['127.0.0.1:11211'],
<add> ]);
<add> Configure::write('Cache.short_memcache', [
<ide> 'engine' => 'Memcache',
<ide> 'duration' => '+1 seconds',
<del> 'servers' => array('127.0.0.1:11211'),
<del> ));
<del> Cache::config('some_file', array('engine' => 'File'));
<add> 'servers' => ['127.0.0.1:11211'],
<add> ]);
<add> Configure::write('Cache.some_file', ['engine' => 'File']);
<ide>
<ide> $this->assertTrue(Cache::write('duration_test', 'yay', 'long_memcache'));
<ide> $this->assertTrue(Cache::write('short_duration_test', 'boo', 'short_memcache'));
<ide> public function testConfigurationConflict() {
<ide> * @return void
<ide> */
<ide> public function testClear() {
<del> Cache::config('memcache2', array(
<add> Configure::write('Cache.memcache2', [
<ide> 'engine' => 'Memcache',
<ide> 'prefix' => 'cake2_',
<ide> 'duration' => 3600
<del> ));
<add> ]);
<ide>
<ide> Cache::write('some_value', 'cache1', 'memcache');
<ide> $result = Cache::clear(true, 'memcache');
<ide> public function testClear() {
<ide> * @return void
<ide> */
<ide> public function testZeroDuration() {
<del> Cache::config('memcache', array('duration' => 0));
<add> Configure::write('Cache.memcache', [
<add> 'engine' => 'Memcache',
<add> 'prefix' => 'cake_',
<add> 'duration' => 0
<add> ]);
<ide> $result = Cache::write('test_key', 'written!', 'memcache');
<ide>
<ide> $this->assertTrue($result);
<ide> public function testLongDurationEqualToZero() {
<ide> * @return void
<ide> */
<ide> public function testGroupReadWrite() {
<del> Cache::config('memcache_groups', array(
<add> Configure::write('Cache.memcache_groups', [
<ide> 'engine' => 'Memcache',
<ide> 'duration' => 3600,
<del> 'groups' => array('group_a', 'group_b'),
<add> 'groups' => ['group_a', 'group_b'],
<ide> 'prefix' => 'test_'
<del> ));
<del> Cache::config('memcache_helper', array(
<add> ]);
<add> Configure::write('Cache.memcache_helper', [
<ide> 'engine' => 'Memcache',
<ide> 'duration' => 3600,
<ide> 'prefix' => 'test_'
<del> ));
<add> ]);
<ide> $this->assertTrue(Cache::write('test_groups', 'value', 'memcache_groups'));
<ide> $this->assertEquals('value', Cache::read('test_groups', 'memcache_groups'));
<ide>
<ide> public function testGroupReadWrite() {
<ide> * @return void
<ide> */
<ide> public function testGroupDelete() {
<del> Cache::config('memcache_groups', array(
<add> Configure::write('Cache.memcache_groups', [
<ide> 'engine' => 'Memcache',
<ide> 'duration' => 3600,
<del> 'groups' => array('group_a', 'group_b')
<del> ));
<add> 'groups' => ['group_a', 'group_b']
<add> ]);
<ide> $this->assertTrue(Cache::write('test_groups', 'value', 'memcache_groups'));
<ide> $this->assertEquals('value', Cache::read('test_groups', 'memcache_groups'));
<ide> $this->assertTrue(Cache::delete('test_groups', 'memcache_groups'));
<ide> public function testGroupDelete() {
<ide> * @return void
<ide> **/
<ide> public function testGroupClear() {
<del> Cache::config('memcache_groups', array(
<add> Configure::write('Cache.memcache_groups', [
<ide> 'engine' => 'Memcache',
<ide> 'duration' => 3600,
<del> 'groups' => array('group_a', 'group_b')
<del> ));
<add> 'groups' => ['group_a', 'group_b']
<add> ]);
<ide>
<ide> $this->assertTrue(Cache::write('test_groups', 'value', 'memcache_groups'));
<ide> $this->assertTrue(Cache::clearGroup('group_a', 'memcache_groups')); | 2 |
Javascript | Javascript | remove duplicated expression | 51d0808c908f33db34382024b8011d27e0943fa7 | <ide><path>lib/_stream_readable.js
<ide> function readableAddChunk(stream, state, chunk, encoding, addToFront) {
<ide> stream.emit('error', er);
<ide> } else if (chunk === null) {
<ide> state.reading = false;
<del> if (!state.ended)
<del> onEofChunk(stream, state);
<add> onEofChunk(stream, state);
<ide> } else if (state.objectMode || chunk && chunk.length > 0) {
<ide> if (state.ended && !addToFront) {
<ide> var e = new Error('stream.push() after EOF');
<ide> function chunkInvalid(state, chunk) {
<ide>
<ide>
<ide> function onEofChunk(stream, state) {
<del> if (state.decoder && !state.ended) {
<add> if (state.ended) return;
<add> if (state.decoder) {
<ide> var chunk = state.decoder.end();
<ide> if (chunk && chunk.length) {
<ide> state.buffer.push(chunk); | 1 |
Ruby | Ruby | dry fake models for testing | 0157608508cdb432b37324e1653b60d6b2e8c692 | <ide><path>actionview/test/actionpack/controller/render_test.rb
<ide> require "abstract_unit"
<ide> require "active_model"
<add>require "controller/fake_models"
<ide>
<ide> class ApplicationController < ActionController::Base
<ide> self.view_paths = File.join(FIXTURE_LOAD_PATH, "actionpack")
<ide> end
<ide>
<del>Customer = Struct.new(:name, :id) do
<del> extend ActiveModel::Naming
<del> include ActiveModel::Conversion
<del>
<del> undef_method :to_json
<del>
<del> def to_xml(options = {})
<del> if options[:builder]
<del> options[:builder].name name
<del> else
<del> "<name>#{name}</name>"
<del> end
<del> end
<del>
<del> def to_js(options = {})
<del> "name: #{name.inspect}"
<del> end
<del> alias :to_text :to_js
<del>
<del> def errors
<del> []
<del> end
<del>
<del> def persisted?
<del> id.present?
<del> end
<del>
<del> def cache_key
<del> name.to_s
<del> end
<del>end
<del>
<ide> module Quiz
<ide> #Models
<ide> Question = Struct.new(:name, :id) do
<ide> def new
<ide> end
<ide> end
<ide>
<del>class BadCustomer < Customer; end
<del>class GoodCustomer < Customer; end
<del>
<ide> module Fun
<ide> class GamesController < ApplicationController
<ide> def hello_world; end
<ide><path>actionview/test/lib/controller/fake_models.rb
<ide> def errors
<ide> def persisted?
<ide> id.present?
<ide> end
<del>end
<ide>
<del>class GoodCustomer < Customer
<add> def cache_key
<add> name.to_s
<add> end
<ide> end
<ide>
<add>class BadCustomer < Customer; end
<add>class GoodCustomer < Customer; end
<add>
<ide> Post = Struct.new(:title, :author_name, :body, :secret, :persisted, :written_on, :cost) do
<ide> extend ActiveModel::Naming
<ide> include ActiveModel::Conversion | 2 |
Text | Text | add a notice about memory accounting overhead | 56b33e9f27fa9dc50cec16392ca01bd4234390f9 | <ide><path>docs/installation/ubuntulinux.md
<ide> When users run Docker, they may see these messages when working with an image:
<ide> WARNING: Your kernel does not support cgroup swap limit. WARNING: Your
<ide> kernel does not support swap limit capabilities. Limitation discarded.
<ide>
<del>To prevent these messages, enable memory and swap accounting on your system. To
<del>enable these on system using GNU GRUB (GNU GRand Unified Bootloader), do the
<del>following.
<add>To prevent these messages, enable memory and swap accounting on your
<add>system. Enabling memory and swap accounting does induce both a memory
<add>overhead and a performance degradation even when Docker is not in
<add>use. The memory overhead is about 1% of the total available
<add>memory. The performance degradation is roughly 10%.
<add>
<add>To enable memory and swap on system using GNU GRUB (GNU GRand Unified
<add>Bootloader), do the following:
<ide>
<ide> 1. Log into Ubuntu as a user with `sudo` privileges.
<ide> | 1 |
Ruby | Ruby | put constant strings in a constant | 7c5e0eb507f65418a8e721fa584de05f8122a7c5 | <ide><path>Library/Homebrew/keg.rb
<ide> def initialize path
<ide> case d when 'LinkedKegs' then HOMEBREW_LIBRARY/d else HOMEBREW_PREFIX/d end
<ide> end
<ide>
<add> # These paths relative to the keg's share directory should always be real
<add> # directories in the prefix, never symlinks.
<add> SHARE_PATHS = %w[
<add> aclocal doc info locale man
<add> man/man1 man/man2 man/man3 man/man4
<add> man/man5 man/man6 man/man7 man/man8
<add> man/cat1 man/cat2 man/cat3 man/cat4
<add> man/cat5 man/cat6 man/cat7 man/cat8
<add> applications gnome gnome/help icons
<add> mime-info pixmaps sounds
<add> ]
<add>
<ide> # if path is a file in a keg then this will return the containing Keg object
<ide> def self.for path
<ide> path = path.realpath
<ide> def link mode=OpenStruct.new
<ide>
<ide> ObserverPathnameExtension.reset_counts!
<ide>
<del> share_mkpaths = %w[aclocal doc info locale man]
<del> share_mkpaths.concat((1..8).map { |i| "man/man#{i}" })
<del> share_mkpaths.concat((1..8).map { |i| "man/cat#{i}" })
<del> # Paths used by Gnome Desktop support
<del> share_mkpaths.concat %w[applications gnome gnome/help icons mime-info pixmaps sounds]
<del>
<ide> # yeah indeed, you have to force anything you need in the main tree into
<ide> # these dirs REMEMBER that *NOT* everything needs to be in the main tree
<ide> link_dir('etc', mode) {:mkpath}
<ide> def link mode=OpenStruct.new
<ide> when 'locale/locale.alias' then :skip_file
<ide> when INFOFILE_RX then :info
<ide> when LOCALEDIR_RX then :mkpath
<del> when *share_mkpaths then :mkpath
<add> when *SHARE_PATHS then :mkpath
<ide> when /^icons\/.*\/icon-theme\.cache$/ then :skip_file
<ide> # all icons subfolders should also mkpath
<ide> when /^icons\// then :mkpath | 1 |
Javascript | Javascript | move toast to oss | 4a4f087a9c17db8a9a329b87d30f982a6b2a3d21 | <ide><path>Libraries/Components/ToastAndroid/ToastAndroid.ios.js
<add>/**
<add> * Copyright (c) 2015-present, 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> * @providesModule ToastAndroid
<add> */
<add>'use strict';
<add>
<add>module.exports = require('UnimplementedView');
<ide><path>Libraries/react-native/react-native.js
<ide> var ReactNative = Object.assign(Object.create(require('React')), {
<ide> TabBarIOS: require('TabBarIOS'),
<ide> Text: require('Text'),
<ide> TextInput: require('TextInput'),
<add> ToastAndroid: require('ToastAndroid'),
<ide> ToolbarAndroid: require('ToolbarAndroid'),
<ide> TouchableHighlight: require('TouchableHighlight'),
<ide> TouchableNativeFeedback: require('TouchableNativeFeedback'), | 2 |
Go | Go | add provenance pull flow for official images | 7c88e8f13d9f0c68de6da0cd467a541231304dd5 | <ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/docker/pkg/sysinfo"
<ide> "github.com/docker/docker/pkg/truncindex"
<ide> "github.com/docker/docker/runconfig"
<add> "github.com/docker/docker/trust"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/docker/volumes"
<ide> )
<ide> type Daemon struct {
<ide> containerGraph *graphdb.Database
<ide> driver graphdriver.Driver
<ide> execDriver execdriver.Driver
<add> trustStore *trust.TrustStore
<ide> }
<ide>
<ide> // Install installs daemon capabilities to eng.
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> if err := daemon.Repositories().Install(eng); err != nil {
<ide> return err
<ide> }
<add> if err := daemon.trustStore.Install(eng); err != nil {
<add> return err
<add> }
<ide> // FIXME: this hack is necessary for legacy integration tests to access
<ide> // the daemon object.
<ide> eng.Hack_SetGlobalVar("httpapi.daemon", daemon)
<ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error)
<ide> return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
<ide> }
<ide>
<add> trustDir := path.Join(config.Root, "trust")
<add> if err := os.MkdirAll(trustDir, 0700); err != nil && !os.IsExist(err) {
<add> return nil, err
<add> }
<add> t, err := trust.NewTrustStore(trustDir)
<add> if err != nil {
<add> return nil, fmt.Errorf("could not create trust store: %s", err)
<add> }
<add>
<ide> if !config.DisableNetwork {
<ide> job := eng.Job("init_networkdriver")
<ide>
<ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error)
<ide> sysInitPath: sysInitPath,
<ide> execDriver: ed,
<ide> eng: eng,
<add> trustStore: t,
<ide> }
<ide> if err := daemon.checkLocaldns(); err != nil {
<ide> return nil, err
<ide><path>graph/pull.go
<ide> package graph
<ide>
<ide> import (
<add> "bytes"
<add> "encoding/json"
<ide> "fmt"
<ide> "io"
<add> "io/ioutil"
<ide> "net"
<ide> "net/url"
<add> "os"
<ide> "strings"
<ide> "time"
<ide>
<ide> import (
<ide> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/utils"
<add> "github.com/docker/libtrust"
<ide> )
<ide>
<add>func (s *TagStore) verifyManifest(eng *engine.Engine, manifestBytes []byte) (*registry.ManifestData, bool, error) {
<add> sig, err := libtrust.ParsePrettySignature(manifestBytes, "signatures")
<add> if err != nil {
<add> return nil, false, fmt.Errorf("error parsing payload: %s", err)
<add> }
<add> keys, err := sig.Verify()
<add> if err != nil {
<add> return nil, false, fmt.Errorf("error verifying payload: %s", err)
<add> }
<add>
<add> payload, err := sig.Payload()
<add> if err != nil {
<add> return nil, false, fmt.Errorf("error retrieving payload: %s", err)
<add> }
<add>
<add> var manifest registry.ManifestData
<add> if err := json.Unmarshal(payload, &manifest); err != nil {
<add> return nil, false, fmt.Errorf("error unmarshalling manifest: %s", err)
<add> }
<add>
<add> var verified bool
<add> for _, key := range keys {
<add> job := eng.Job("trust_key_check")
<add> b, err := key.MarshalJSON()
<add> if err != nil {
<add> return nil, false, fmt.Errorf("error marshalling public key: %s", err)
<add> }
<add> namespace := manifest.Name
<add> if namespace[0] != '/' {
<add> namespace = "/" + namespace
<add> }
<add> stdoutBuffer := bytes.NewBuffer(nil)
<add>
<add> job.Args = append(job.Args, namespace)
<add> job.Setenv("PublicKey", string(b))
<add> job.SetenvInt("Permission", 0x03)
<add> job.Stdout.Add(stdoutBuffer)
<add> if err = job.Run(); err != nil {
<add> return nil, false, fmt.Errorf("error running key check: %s", err)
<add> }
<add> result := engine.Tail(stdoutBuffer, 1)
<add> log.Debugf("Key check result: %q", result)
<add> if result == "verified" {
<add> verified = true
<add> }
<add> }
<add>
<add> return &manifest, verified, nil
<add>}
<add>
<ide> func (s *TagStore) CmdPull(job *engine.Job) engine.Status {
<ide> if n := len(job.Args); n != 1 && n != 2 {
<ide> return job.Errorf("Usage: %s IMAGE [TAG]", job.Name)
<ide> func (s *TagStore) CmdPull(job *engine.Job) engine.Status {
<ide> return job.Error(err)
<ide> }
<ide>
<del> if endpoint.String() == registry.IndexServerAddress() {
<add> var isOfficial bool
<add> if endpoint.VersionString(1) == registry.IndexServerAddress() {
<ide> // If pull "index.docker.io/foo/bar", it's stored locally under "foo/bar"
<ide> localName = remoteName
<ide>
<add> isOfficial = isOfficialName(remoteName)
<add> if isOfficial && strings.IndexRune(remoteName, '/') == -1 {
<add> remoteName = "library/" + remoteName
<add> }
<add>
<ide> // Use provided mirrors, if any
<ide> mirrors = s.mirrors
<ide> }
<ide>
<add> if isOfficial || endpoint.Version == registry.APIVersion2 {
<add> j := job.Eng.Job("trust_update_base")
<add> if err = j.Run(); err != nil {
<add> return job.Errorf("error updating trust base graph: %s", err)
<add> }
<add>
<add> if err := s.pullV2Repository(job.Eng, r, job.Stdout, localName, remoteName, tag, sf, job.GetenvBool("parallel")); err == nil {
<add> return engine.StatusOK
<add> } else if err != registry.ErrDoesNotExist {
<add> log.Errorf("Error from V2 registry: %s", err)
<add> }
<add> }
<ide> if err = s.pullRepository(r, job.Stdout, localName, remoteName, tag, sf, job.GetenvBool("parallel"), mirrors); err != nil {
<ide> return job.Error(err)
<ide> }
<ide> func (s *TagStore) pullImage(r *registry.Session, out io.Writer, imgID, endpoint
<ide> }
<ide> return nil
<ide> }
<add>
<add>// downloadInfo is used to pass information from download to extractor
<add>type downloadInfo struct {
<add> imgJSON []byte
<add> img *image.Image
<add> tmpFile *os.File
<add> length int64
<add> downloaded bool
<add> err chan error
<add>}
<add>
<add>func (s *TagStore) pullV2Repository(eng *engine.Engine, r *registry.Session, out io.Writer, localName, remoteName, tag string, sf *utils.StreamFormatter, parallel bool) error {
<add> if tag == "" {
<add> log.Debugf("Pulling tag list from V2 registry for %s", remoteName)
<add> tags, err := r.GetV2RemoteTags(remoteName, nil)
<add> if err != nil {
<add> return err
<add> }
<add> for _, t := range tags {
<add> if err := s.pullV2Tag(eng, r, out, localName, remoteName, t, sf, parallel); err != nil {
<add> return err
<add> }
<add> }
<add> } else {
<add> if err := s.pullV2Tag(eng, r, out, localName, remoteName, tag, sf, parallel); err != nil {
<add> return err
<add> }
<add> }
<add>
<add> return nil
<add>}
<add>
<add>func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Writer, localName, remoteName, tag string, sf *utils.StreamFormatter, parallel bool) error {
<add> log.Debugf("Pulling tag from V2 registry: %q", tag)
<add> manifestBytes, err := r.GetV2ImageManifest(remoteName, tag, nil)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> manifest, verified, err := s.verifyManifest(eng, manifestBytes)
<add> if err != nil {
<add> return fmt.Errorf("error verifying manifest: %s", err)
<add> }
<add>
<add> if len(manifest.BlobSums) != len(manifest.History) {
<add> return fmt.Errorf("length of history not equal to number of layers")
<add> }
<add>
<add> if verified {
<add> out.Write(sf.FormatStatus("", "The image you are pulling has been digitally signed by Docker, Inc."))
<add> }
<add> out.Write(sf.FormatStatus(tag, "Pulling from %s", localName))
<add>
<add> downloads := make([]downloadInfo, len(manifest.BlobSums))
<add>
<add> for i := len(manifest.BlobSums) - 1; i >= 0; i-- {
<add> var (
<add> sumStr = manifest.BlobSums[i]
<add> imgJSON = []byte(manifest.History[i])
<add> )
<add>
<add> img, err := image.NewImgJSON(imgJSON)
<add> if err != nil {
<add> return fmt.Errorf("failed to parse json: %s", err)
<add> }
<add> downloads[i].img = img
<add>
<add> // Check if exists
<add> if s.graph.Exists(img.ID) {
<add> log.Debugf("Image already exists: %s", img.ID)
<add> continue
<add> }
<add>
<add> chunks := strings.SplitN(sumStr, ":", 2)
<add> if len(chunks) < 2 {
<add> return fmt.Errorf("expected 2 parts in the sumStr, got %#v", chunks)
<add> }
<add> sumType, checksum := chunks[0], chunks[1]
<add> out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Pulling fs layer", nil))
<add>
<add> downloadFunc := func(di *downloadInfo) error {
<add> log.Infof("pulling blob %q to V1 img %s", sumStr, img.ID)
<add>
<add> if c, err := s.poolAdd("pull", "img:"+img.ID); err != nil {
<add> if c != nil {
<add> out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Layer already being pulled by another client. Waiting.", nil))
<add> <-c
<add> out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Download complete", nil))
<add> } else {
<add> log.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err)
<add> }
<add> } else {
<add> tmpFile, err := ioutil.TempFile("", "GetV2ImageBlob")
<add> if err != nil {
<add> return err
<add> }
<add>
<add> r, l, err := r.GetV2ImageBlobReader(remoteName, sumType, checksum, nil)
<add> if err != nil {
<add> return err
<add> }
<add> defer r.Close()
<add> io.Copy(tmpFile, utils.ProgressReader(r, int(l), out, sf, false, utils.TruncateID(img.ID), "Downloading"))
<add>
<add> out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Download complete", nil))
<add>
<add> log.Debugf("Downloaded %s to tempfile %s", img.ID, tmpFile.Name())
<add> di.tmpFile = tmpFile
<add> di.length = l
<add> di.downloaded = true
<add> }
<add> di.imgJSON = imgJSON
<add> defer s.poolRemove("pull", "img:"+img.ID)
<add>
<add> return nil
<add> }
<add>
<add> if parallel {
<add> downloads[i].err = make(chan error)
<add> go func(di *downloadInfo) {
<add> di.err <- downloadFunc(di)
<add> }(&downloads[i])
<add> } else {
<add> err := downloadFunc(&downloads[i])
<add> if err != nil {
<add> return err
<add> }
<add> }
<add> }
<add>
<add> for i := len(downloads) - 1; i >= 0; i-- {
<add> d := &downloads[i]
<add> if d.err != nil {
<add> err := <-d.err
<add> if err != nil {
<add> return err
<add> }
<add> }
<add> if d.downloaded {
<add> // if tmpFile is empty assume download and extracted elsewhere
<add> defer os.Remove(d.tmpFile.Name())
<add> defer d.tmpFile.Close()
<add> d.tmpFile.Seek(0, 0)
<add> if d.tmpFile != nil {
<add> err = s.graph.Register(d.img, d.imgJSON,
<add> utils.ProgressReader(d.tmpFile, int(d.length), out, sf, false, utils.TruncateID(d.img.ID), "Extracting"))
<add> if err != nil {
<add> return err
<add> }
<add>
<add> // FIXME: Pool release here for parallel tag pull (ensures any downloads block until fully extracted)
<add> }
<add> out.Write(sf.FormatProgress(utils.TruncateID(d.img.ID), "Pull complete", nil))
<add>
<add> } else {
<add> out.Write(sf.FormatProgress(utils.TruncateID(d.img.ID), "Already exists", nil))
<add> }
<add>
<add> }
<add>
<add> if err = s.Set(localName, tag, downloads[0].img.ID, true); err != nil {
<add> return err
<add> }
<add>
<add> return nil
<add>}
<ide><path>graph/tags.go
<ide> func (store *TagStore) GetRepoRefs() map[string][]string {
<ide> return reporefs
<ide> }
<ide>
<add>// isOfficialName returns whether a repo name is considered an official
<add>// repository. Official repositories are repos with names within
<add>// the library namespace or which default to the library namespace
<add>// by not providing one.
<add>func isOfficialName(name string) bool {
<add> if strings.HasPrefix(name, "library/") {
<add> return true
<add> }
<add> if strings.IndexRune(name, '/') == -1 {
<add> return true
<add> }
<add> return false
<add>}
<add>
<ide> // Validate the name of a repository
<ide> func validateRepoName(name string) error {
<ide> if name == "" {
<ide><path>graph/tags_unit_test.go
<ide> package graph
<ide>
<ide> import (
<ide> "bytes"
<add> "io"
<add> "os"
<add> "path"
<add> "testing"
<add>
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> _ "github.com/docker/docker/daemon/graphdriver/vfs" // import the vfs driver so it is used in the tests
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<del> "io"
<del> "os"
<del> "path"
<del> "testing"
<ide> )
<ide>
<ide> const (
<ide> func TestInvalidTagName(t *testing.T) {
<ide> }
<ide> }
<ide> }
<add>
<add>func TestOfficialName(t *testing.T) {
<add> names := map[string]bool{
<add> "library/ubuntu": true,
<add> "nonlibrary/ubuntu": false,
<add> "ubuntu": true,
<add> "other/library": false,
<add> }
<add> for name, isOfficial := range names {
<add> result := isOfficialName(name)
<add> if result != isOfficial {
<add> t.Errorf("Unexpected result for %s\n\tExpecting: %v\n\tActual: %v", name, isOfficial, result)
<add> }
<add> }
<add>}
<ide><path>registry/registry.go
<ide> import (
<ide> var (
<ide> ErrAlreadyExists = errors.New("Image already exists")
<ide> ErrInvalidRepositoryName = errors.New("Invalid repository name (ex: \"registry.domain.tld/myrepos\")")
<add> ErrDoesNotExist = errors.New("Image does not exist")
<ide> errLoginRequired = errors.New("Authentication is required.")
<ide> validHex = regexp.MustCompile(`^([a-f0-9]{64})$`)
<ide> validNamespace = regexp.MustCompile(`^([a-z0-9_]{4,30})$`)
<ide><path>registry/registry_mock_test.go
<ide> var (
<ide>
<ide> func init() {
<ide> r := mux.NewRouter()
<add>
<add> // /v1/
<ide> r.HandleFunc("/v1/_ping", handlerGetPing).Methods("GET")
<ide> r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|ancestry}", handlerGetImage).Methods("GET")
<ide> r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|checksum}", handlerPutImage).Methods("PUT")
<ide> func init() {
<ide> r.HandleFunc("/v1/repositories/{repository:.+}{action:/images|/}", handlerImages).Methods("GET", "PUT", "DELETE")
<ide> r.HandleFunc("/v1/repositories/{repository:.+}/auth", handlerAuth).Methods("PUT")
<ide> r.HandleFunc("/v1/search", handlerSearch).Methods("GET")
<add>
<add> // /v2/
<add> r.HandleFunc("/v2/version", handlerGetPing).Methods("GET")
<add>
<ide> testHttpServer = httptest.NewServer(handlerAccessLog(r))
<ide> }
<ide>
<ide><path>registry/session.go
<ide> func NewSession(authConfig *AuthConfig, factory *utils.HTTPRequestFactory, endpo
<ide>
<ide> // If we're working with a standalone private registry over HTTPS, send Basic Auth headers
<ide> // alongside our requests.
<del> if r.indexEndpoint.String() != IndexServerAddress() && r.indexEndpoint.URL.Scheme == "https" {
<add> if r.indexEndpoint.VersionString(1) != IndexServerAddress() && r.indexEndpoint.URL.Scheme == "https" {
<ide> info, err := r.indexEndpoint.Ping()
<ide> if err != nil {
<ide> return nil, err
<ide> func buildEndpointsList(headers []string, indexEp string) ([]string, error) {
<ide> }
<ide>
<ide> func (r *Session) GetRepositoryData(remote string) (*RepositoryData, error) {
<del> repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.String(), remote)
<add> repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.VersionString(1), remote)
<ide>
<ide> log.Debugf("[registry] Calling GET %s", repositoryTarget)
<ide>
<ide> func (r *Session) GetRepositoryData(remote string) (*RepositoryData, error) {
<ide>
<ide> var endpoints []string
<ide> if res.Header.Get("X-Docker-Endpoints") != "" {
<del> endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String())
<add> endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.VersionString(1))
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (r *Session) PushImageJSONIndex(remote string, imgList []*ImgData, validate
<ide> if validate {
<ide> suffix = "images"
<ide> }
<del> u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.String(), remote, suffix)
<add> u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.VersionString(1), remote, suffix)
<ide> log.Debugf("[registry] PUT %s", u)
<ide> log.Debugf("Image list pushed to index:\n%s", imgListJSON)
<ide> req, err := r.reqFactory.NewRequest("PUT", u, bytes.NewReader(imgListJSON))
<ide> func (r *Session) PushImageJSONIndex(remote string, imgList []*ImgData, validate
<ide> }
<ide>
<ide> if res.Header.Get("X-Docker-Endpoints") != "" {
<del> endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String())
<add> endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.VersionString(1))
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (r *Session) PushImageJSONIndex(remote string, imgList []*ImgData, validate
<ide>
<ide> func (r *Session) SearchRepositories(term string) (*SearchResults, error) {
<ide> log.Debugf("Index server: %s", r.indexEndpoint)
<del> u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term)
<add> u := r.indexEndpoint.VersionString(1) + "search?q=" + url.QueryEscape(term)
<ide> req, err := r.reqFactory.NewRequest("GET", u, nil)
<ide> if err != nil {
<ide> return nil, err
<ide><path>registry/session_v2.go
<add>package registry
<add>
<add>import (
<add> "encoding/json"
<add> "fmt"
<add> "io"
<add> "io/ioutil"
<add> "net/url"
<add> "strconv"
<add>
<add> "github.com/docker/docker/pkg/log"
<add> "github.com/docker/docker/utils"
<add> "github.com/gorilla/mux"
<add>)
<add>
<add>func newV2RegistryRouter() *mux.Router {
<add> router := mux.NewRouter()
<add>
<add> v2Router := router.PathPrefix("/v2/").Subrouter()
<add>
<add> // Version Info
<add> v2Router.Path("/version").Name("version")
<add>
<add> // Image Manifests
<add> v2Router.Path("/manifest/{imagename:[a-z0-9-._/]+}/{tagname:[a-zA-Z0-9-._]+}").Name("manifests")
<add>
<add> // List Image Tags
<add> v2Router.Path("/tags/{imagename:[a-z0-9-._/]+}").Name("tags")
<add>
<add> // Download a blob
<add> v2Router.Path("/blob/{imagename:[a-z0-9-._/]+}/{sumtype:[a-z0-9_+-]+}/{sum:[a-fA-F0-9]{4,}}").Name("downloadBlob")
<add>
<add> // Upload a blob
<add> v2Router.Path("/blob/{imagename:[a-z0-9-._/]+}/{sumtype:[a-z0-9_+-]+}").Name("uploadBlob")
<add>
<add> // Mounting a blob in an image
<add> v2Router.Path("/mountblob/{imagename:[a-z0-9-._/]+}/{sumtype:[a-z0-9_+-]+}/{sum:[a-fA-F0-9]{4,}}").Name("mountBlob")
<add>
<add> return router
<add>}
<add>
<add>// APIVersion2 /v2/
<add>var v2HTTPRoutes = newV2RegistryRouter()
<add>
<add>func getV2URL(e *Endpoint, routeName string, vars map[string]string) (*url.URL, error) {
<add> route := v2HTTPRoutes.Get(routeName)
<add> if route == nil {
<add> return nil, fmt.Errorf("unknown regisry v2 route name: %q", routeName)
<add> }
<add>
<add> varReplace := make([]string, 0, len(vars)*2)
<add> for key, val := range vars {
<add> varReplace = append(varReplace, key, val)
<add> }
<add>
<add> routePath, err := route.URLPath(varReplace...)
<add> if err != nil {
<add> return nil, fmt.Errorf("unable to make registry route %q with vars %v: %s", routeName, vars, err)
<add> }
<add>
<add> return &url.URL{
<add> Scheme: e.URL.Scheme,
<add> Host: e.URL.Host,
<add> Path: routePath.Path,
<add> }, nil
<add>}
<add>
<add>// V2 Provenance POC
<add>
<add>func (r *Session) GetV2Version(token []string) (*RegistryInfo, error) {
<add> routeURL, err := getV2URL(r.indexEndpoint, "version", nil)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> method := "GET"
<add> log.Debugf("[registry] Calling %q %s", method, routeURL.String())
<add>
<add> req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil)
<add> if err != nil {
<add> return nil, err
<add> }
<add> setTokenAuth(req, token)
<add> res, _, err := r.doRequest(req)
<add> if err != nil {
<add> return nil, err
<add> }
<add> defer res.Body.Close()
<add> if res.StatusCode != 200 {
<add> return nil, utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d fetching Version", res.StatusCode), res)
<add> }
<add>
<add> decoder := json.NewDecoder(res.Body)
<add> versionInfo := new(RegistryInfo)
<add>
<add> err = decoder.Decode(versionInfo)
<add> if err != nil {
<add> return nil, fmt.Errorf("unable to decode GetV2Version JSON response: %s", err)
<add> }
<add>
<add> return versionInfo, nil
<add>}
<add>
<add>//
<add>// 1) Check if TarSum of each layer exists /v2/
<add>// 1.a) if 200, continue
<add>// 1.b) if 300, then push the
<add>// 1.c) if anything else, err
<add>// 2) PUT the created/signed manifest
<add>//
<add>func (r *Session) GetV2ImageManifest(imageName, tagName string, token []string) ([]byte, error) {
<add> vars := map[string]string{
<add> "imagename": imageName,
<add> "tagname": tagName,
<add> }
<add>
<add> routeURL, err := getV2URL(r.indexEndpoint, "manifests", vars)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> method := "GET"
<add> log.Debugf("[registry] Calling %q %s", method, routeURL.String())
<add>
<add> req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil)
<add> if err != nil {
<add> return nil, err
<add> }
<add> setTokenAuth(req, token)
<add> res, _, err := r.doRequest(req)
<add> if err != nil {
<add> return nil, err
<add> }
<add> defer res.Body.Close()
<add> if res.StatusCode != 200 {
<add> if res.StatusCode == 401 {
<add> return nil, errLoginRequired
<add> } else if res.StatusCode == 404 {
<add> return nil, ErrDoesNotExist
<add> }
<add> return nil, utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to fetch for %s:%s", res.StatusCode, imageName, tagName), res)
<add> }
<add>
<add> buf, err := ioutil.ReadAll(res.Body)
<add> if err != nil {
<add> return nil, fmt.Errorf("Error while reading the http response: %s", err)
<add> }
<add> return buf, nil
<add>}
<add>
<add>// - Succeeded to mount for this image scope
<add>// - Failed with no error (So continue to Push the Blob)
<add>// - Failed with error
<add>func (r *Session) PostV2ImageMountBlob(imageName, sumType, sum string, token []string) (bool, error) {
<add> vars := map[string]string{
<add> "imagename": imageName,
<add> "sumtype": sumType,
<add> "sum": sum,
<add> }
<add>
<add> routeURL, err := getV2URL(r.indexEndpoint, "mountBlob", vars)
<add> if err != nil {
<add> return false, err
<add> }
<add>
<add> method := "POST"
<add> log.Debugf("[registry] Calling %q %s", method, routeURL.String())
<add>
<add> req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil)
<add> if err != nil {
<add> return false, err
<add> }
<add> setTokenAuth(req, token)
<add> res, _, err := r.doRequest(req)
<add> if err != nil {
<add> return false, err
<add> }
<add> res.Body.Close() // close early, since we're not needing a body on this call .. yet?
<add> switch res.StatusCode {
<add> case 200:
<add> // return something indicating no push needed
<add> return true, nil
<add> case 300:
<add> // return something indicating blob push needed
<add> return false, nil
<add> }
<add> return false, fmt.Errorf("Failed to mount %q - %s:%s : %d", imageName, sumType, sum, res.StatusCode)
<add>}
<add>
<add>func (r *Session) GetV2ImageBlob(imageName, sumType, sum string, blobWrtr io.Writer, token []string) error {
<add> vars := map[string]string{
<add> "imagename": imageName,
<add> "sumtype": sumType,
<add> "sum": sum,
<add> }
<add>
<add> routeURL, err := getV2URL(r.indexEndpoint, "downloadBlob", vars)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> method := "GET"
<add> log.Debugf("[registry] Calling %q %s", method, routeURL.String())
<add> req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil)
<add> if err != nil {
<add> return err
<add> }
<add> setTokenAuth(req, token)
<add> res, _, err := r.doRequest(req)
<add> if err != nil {
<add> return err
<add> }
<add> defer res.Body.Close()
<add> if res.StatusCode != 200 {
<add> if res.StatusCode == 401 {
<add> return errLoginRequired
<add> }
<add> return utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to pull %s blob", res.StatusCode, imageName), res)
<add> }
<add>
<add> _, err = io.Copy(blobWrtr, res.Body)
<add> return err
<add>}
<add>
<add>func (r *Session) GetV2ImageBlobReader(imageName, sumType, sum string, token []string) (io.ReadCloser, int64, error) {
<add> vars := map[string]string{
<add> "imagename": imageName,
<add> "sumtype": sumType,
<add> "sum": sum,
<add> }
<add>
<add> routeURL, err := getV2URL(r.indexEndpoint, "downloadBlob", vars)
<add> if err != nil {
<add> return nil, 0, err
<add> }
<add>
<add> method := "GET"
<add> log.Debugf("[registry] Calling %q %s", method, routeURL.String())
<add> req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil)
<add> if err != nil {
<add> return nil, 0, err
<add> }
<add> setTokenAuth(req, token)
<add> res, _, err := r.doRequest(req)
<add> if err != nil {
<add> return nil, 0, err
<add> }
<add> if res.StatusCode != 200 {
<add> if res.StatusCode == 401 {
<add> return nil, 0, errLoginRequired
<add> }
<add> return nil, 0, utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to pull %s blob", res.StatusCode, imageName), res)
<add> }
<add> lenStr := res.Header.Get("Content-Length")
<add> l, err := strconv.ParseInt(lenStr, 10, 64)
<add> if err != nil {
<add> return nil, 0, err
<add> }
<add>
<add> return res.Body, l, err
<add>}
<add>
<add>// Push the image to the server for storage.
<add>// 'layer' is an uncompressed reader of the blob to be pushed.
<add>// The server will generate it's own checksum calculation.
<add>func (r *Session) PutV2ImageBlob(imageName, sumType string, blobRdr io.Reader, token []string) (serverChecksum string, err error) {
<add> vars := map[string]string{
<add> "imagename": imageName,
<add> "sumtype": sumType,
<add> }
<add>
<add> routeURL, err := getV2URL(r.indexEndpoint, "uploadBlob", vars)
<add> if err != nil {
<add> return "", err
<add> }
<add>
<add> method := "PUT"
<add> log.Debugf("[registry] Calling %q %s", method, routeURL.String())
<add> req, err := r.reqFactory.NewRequest(method, routeURL.String(), blobRdr)
<add> if err != nil {
<add> return "", err
<add> }
<add> setTokenAuth(req, token)
<add> res, _, err := r.doRequest(req)
<add> if err != nil {
<add> return "", err
<add> }
<add> defer res.Body.Close()
<add> if res.StatusCode != 201 {
<add> if res.StatusCode == 401 {
<add> return "", errLoginRequired
<add> }
<add> return "", utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to push %s blob", res.StatusCode, imageName), res)
<add> }
<add>
<add> type sumReturn struct {
<add> Checksum string `json:"checksum"`
<add> }
<add>
<add> decoder := json.NewDecoder(res.Body)
<add> var sumInfo sumReturn
<add>
<add> err = decoder.Decode(&sumInfo)
<add> if err != nil {
<add> return "", fmt.Errorf("unable to decode PutV2ImageBlob JSON response: %s", err)
<add> }
<add>
<add> // XXX this is a json struct from the registry, with its checksum
<add> return sumInfo.Checksum, nil
<add>}
<add>
<add>// Finally Push the (signed) manifest of the blobs we've just pushed
<add>func (r *Session) PutV2ImageManifest(imageName, tagName string, manifestRdr io.Reader, token []string) error {
<add> vars := map[string]string{
<add> "imagename": imageName,
<add> "tagname": tagName,
<add> }
<add>
<add> routeURL, err := getV2URL(r.indexEndpoint, "manifests", vars)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> method := "PUT"
<add> log.Debugf("[registry] Calling %q %s", method, routeURL.String())
<add> req, err := r.reqFactory.NewRequest(method, routeURL.String(), manifestRdr)
<add> if err != nil {
<add> return err
<add> }
<add> setTokenAuth(req, token)
<add> res, _, err := r.doRequest(req)
<add> if err != nil {
<add> return err
<add> }
<add> res.Body.Close()
<add> if res.StatusCode != 201 {
<add> if res.StatusCode == 401 {
<add> return errLoginRequired
<add> }
<add> return utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to push %s:%s manifest", res.StatusCode, imageName, tagName), res)
<add> }
<add>
<add> return nil
<add>}
<add>
<add>// Given a repository name, returns a json array of string tags
<add>func (r *Session) GetV2RemoteTags(imageName string, token []string) ([]string, error) {
<add> vars := map[string]string{
<add> "imagename": imageName,
<add> }
<add>
<add> routeURL, err := getV2URL(r.indexEndpoint, "tags", vars)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> method := "GET"
<add> log.Debugf("[registry] Calling %q %s", method, routeURL.String())
<add>
<add> req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil)
<add> if err != nil {
<add> return nil, err
<add> }
<add> setTokenAuth(req, token)
<add> res, _, err := r.doRequest(req)
<add> if err != nil {
<add> return nil, err
<add> }
<add> defer res.Body.Close()
<add> if res.StatusCode != 200 {
<add> if res.StatusCode == 401 {
<add> return nil, errLoginRequired
<add> } else if res.StatusCode == 404 {
<add> return nil, ErrDoesNotExist
<add> }
<add> return nil, utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to fetch for %s", res.StatusCode, imageName), res)
<add> }
<add>
<add> decoder := json.NewDecoder(res.Body)
<add> var tags []string
<add> err = decoder.Decode(&tags)
<add> if err != nil {
<add> return nil, fmt.Errorf("Error while decoding the http response: %s", err)
<add> }
<add> return tags, nil
<add>}
<ide><path>registry/types.go
<ide> type RegistryInfo struct {
<ide> Standalone bool `json:"standalone"`
<ide> }
<ide>
<add>type ManifestData struct {
<add> Name string `json:"name"`
<add> Tag string `json:"tag"`
<add> Architecture string `json:"architecture"`
<add> BlobSums []string `json:"blobSums"`
<add> History []string `json:"history"`
<add> SchemaVersion int `json:"schemaVersion"`
<add>}
<add>
<ide> type APIVersion int
<ide>
<ide> func (av APIVersion) String() string {
<ide> var apiVersions = map[APIVersion]string{
<ide> }
<ide>
<ide> const (
<del> _ = iota
<del> APIVersion1 = iota
<add> APIVersion1 = iota + 1
<ide> APIVersion2
<ide> )
<ide><path>trust/service.go
<add>package trust
<add>
<add>import (
<add> "fmt"
<add> "time"
<add>
<add> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/pkg/log"
<add> "github.com/docker/libtrust"
<add>)
<add>
<add>func (t *TrustStore) Install(eng *engine.Engine) error {
<add> for name, handler := range map[string]engine.Handler{
<add> "trust_key_check": t.CmdCheckKey,
<add> "trust_update_base": t.CmdUpdateBase,
<add> } {
<add> if err := eng.Register(name, handler); err != nil {
<add> return fmt.Errorf("Could not register %q: %v", name, err)
<add> }
<add> }
<add> return nil
<add>}
<add>
<add>func (t *TrustStore) CmdCheckKey(job *engine.Job) engine.Status {
<add> if n := len(job.Args); n != 1 {
<add> return job.Errorf("Usage: %s NAMESPACE", job.Name)
<add> }
<add> var (
<add> namespace = job.Args[0]
<add> keyBytes = job.Getenv("PublicKey")
<add> )
<add>
<add> if keyBytes == "" {
<add> return job.Errorf("Missing PublicKey")
<add> }
<add> pk, err := libtrust.UnmarshalPublicKeyJWK([]byte(keyBytes))
<add> if err != nil {
<add> return job.Errorf("Error unmarshalling public key: %s", err)
<add> }
<add>
<add> permission := uint16(job.GetenvInt("Permission"))
<add> if permission == 0 {
<add> permission = 0x03
<add> }
<add>
<add> t.RLock()
<add> defer t.RUnlock()
<add> if t.graph == nil {
<add> job.Stdout.Write([]byte("no graph"))
<add> return engine.StatusOK
<add> }
<add>
<add> // Check if any expired grants
<add> verified, err := t.graph.Verify(pk, namespace, permission)
<add> if err != nil {
<add> return job.Errorf("Error verifying key to namespace: %s", namespace)
<add> }
<add> if !verified {
<add> log.Debugf("Verification failed for %s using key %s", namespace, pk.KeyID())
<add> job.Stdout.Write([]byte("not verified"))
<add> } else if t.expiration.Before(time.Now()) {
<add> job.Stdout.Write([]byte("expired"))
<add> } else {
<add> job.Stdout.Write([]byte("verified"))
<add> }
<add>
<add> return engine.StatusOK
<add>}
<add>
<add>func (t *TrustStore) CmdUpdateBase(job *engine.Job) engine.Status {
<add> t.fetch()
<add>
<add> return engine.StatusOK
<add>}
<ide><path>trust/trusts.go
<add>package trust
<add>
<add>import (
<add> "crypto/x509"
<add> "errors"
<add> "io/ioutil"
<add> "net/http"
<add> "net/url"
<add> "os"
<add> "path"
<add> "path/filepath"
<add> "sync"
<add> "time"
<add>
<add> "github.com/docker/docker/pkg/log"
<add> "github.com/docker/libtrust/trustgraph"
<add>)
<add>
<add>type TrustStore struct {
<add> path string
<add> caPool *x509.CertPool
<add> graph trustgraph.TrustGraph
<add> expiration time.Time
<add> fetcher *time.Timer
<add> fetchTime time.Duration
<add> autofetch bool
<add> httpClient *http.Client
<add> baseEndpoints map[string]*url.URL
<add>
<add> sync.RWMutex
<add>}
<add>
<add>// defaultFetchtime represents the starting duration to wait between
<add>// fetching sections of the graph. Unsuccessful fetches should
<add>// increase time between fetching.
<add>const defaultFetchtime = 45 * time.Second
<add>
<add>var baseEndpoints = map[string]string{"official": "https://dvjy3tqbc323p.cloudfront.net/trust/official.json"}
<add>
<add>func NewTrustStore(path string) (*TrustStore, error) {
<add> abspath, err := filepath.Abs(path)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> // Create base graph url map
<add> endpoints := map[string]*url.URL{}
<add> for name, endpoint := range baseEndpoints {
<add> u, err := url.Parse(endpoint)
<add> if err != nil {
<add> return nil, err
<add> }
<add> endpoints[name] = u
<add> }
<add>
<add> // Load grant files
<add> t := &TrustStore{
<add> path: abspath,
<add> caPool: nil,
<add> httpClient: &http.Client{},
<add> fetchTime: time.Millisecond,
<add> baseEndpoints: endpoints,
<add> }
<add>
<add> err = t.reload()
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> return t, nil
<add>}
<add>
<add>func (t *TrustStore) reload() error {
<add> t.Lock()
<add> defer t.Unlock()
<add>
<add> matches, err := filepath.Glob(filepath.Join(t.path, "*.json"))
<add> if err != nil {
<add> return err
<add> }
<add> statements := make([]*trustgraph.Statement, len(matches))
<add> for i, match := range matches {
<add> f, err := os.Open(match)
<add> if err != nil {
<add> return err
<add> }
<add> statements[i], err = trustgraph.LoadStatement(f, nil)
<add> if err != nil {
<add> f.Close()
<add> return err
<add> }
<add> f.Close()
<add> }
<add> if len(statements) == 0 {
<add> if t.autofetch {
<add> log.Debugf("No grants, fetching")
<add> t.fetcher = time.AfterFunc(t.fetchTime, t.fetch)
<add> }
<add> return nil
<add> }
<add>
<add> grants, expiration, err := trustgraph.CollapseStatements(statements, true)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> t.expiration = expiration
<add> t.graph = trustgraph.NewMemoryGraph(grants)
<add> log.Debugf("Reloaded graph with %d grants expiring at %s", len(grants), expiration)
<add>
<add> if t.autofetch {
<add> nextFetch := expiration.Sub(time.Now())
<add> if nextFetch < 0 {
<add> nextFetch = defaultFetchtime
<add> } else {
<add> nextFetch = time.Duration(0.8 * (float64)(nextFetch))
<add> }
<add> t.fetcher = time.AfterFunc(nextFetch, t.fetch)
<add> }
<add>
<add> return nil
<add>}
<add>
<add>func (t *TrustStore) fetchBaseGraph(u *url.URL) (*trustgraph.Statement, error) {
<add> req := &http.Request{
<add> Method: "GET",
<add> URL: u,
<add> Proto: "HTTP/1.1",
<add> ProtoMajor: 1,
<add> ProtoMinor: 1,
<add> Header: make(http.Header),
<add> Body: nil,
<add> Host: u.Host,
<add> }
<add>
<add> resp, err := t.httpClient.Do(req)
<add> if err != nil {
<add> return nil, err
<add> }
<add> if resp.StatusCode == 404 {
<add> return nil, errors.New("base graph does not exist")
<add> }
<add>
<add> defer resp.Body.Close()
<add>
<add> return trustgraph.LoadStatement(resp.Body, t.caPool)
<add>}
<add>
<add>// fetch retrieves updated base graphs. This function cannot error, it
<add>// should only log errors
<add>func (t *TrustStore) fetch() {
<add> t.Lock()
<add> defer t.Unlock()
<add>
<add> if t.autofetch && t.fetcher == nil {
<add> // Do nothing ??
<add> return
<add> }
<add>
<add> fetchCount := 0
<add> for bg, ep := range t.baseEndpoints {
<add> statement, err := t.fetchBaseGraph(ep)
<add> if err != nil {
<add> log.Infof("Trust graph fetch failed: %s", err)
<add> continue
<add> }
<add> b, err := statement.Bytes()
<add> if err != nil {
<add> log.Infof("Bad trust graph statement: %s", err)
<add> continue
<add> }
<add> // TODO check if value differs
<add> err = ioutil.WriteFile(path.Join(t.path, bg+".json"), b, 0600)
<add> if err != nil {
<add> log.Infof("Error writing trust graph statement: %s", err)
<add> }
<add> fetchCount++
<add> }
<add> log.Debugf("Fetched %d base graphs at %s", fetchCount, time.Now())
<add>
<add> if fetchCount > 0 {
<add> go func() {
<add> err := t.reload()
<add> if err != nil {
<add> // TODO log
<add> log.Infof("Reload of trust graph failed: %s", err)
<add> }
<add> }()
<add> t.fetchTime = defaultFetchtime
<add> t.fetcher = nil
<add> } else if t.autofetch {
<add> maxTime := 10 * defaultFetchtime
<add> t.fetchTime = time.Duration(1.5 * (float64)(t.fetchTime+time.Second))
<add> if t.fetchTime > maxTime {
<add> t.fetchTime = maxTime
<add> }
<add> t.fetcher = time.AfterFunc(t.fetchTime, t.fetch)
<add> }
<add>} | 11 |
Python | Python | simplify the assertion message | f7d8310a16d4734dd4887f56e13d7d1616acfbdb | <ide><path>celery/concurrency/asynpool.py
<ide> def verify_process_alive(proc):
<ide> if proc._is_alive() and proc in waiting_to_start:
<ide> assert proc.outqR_fd in fileno_to_outq
<ide> assert fileno_to_outq[proc.outqR_fd] is proc
<del> assert proc.outqR_fd in hub.readers, "%s.outqR_fd=%s, hub.readers=%s" % (proc, proc.outqR_fd, hub.readers)
<add> assert proc.outqR_fd in hub.readers, "%s.outqR_fd=%s not in hub.readers !" % (proc, proc.outqR_fd)
<ide> error('Timed out waiting for UP message from %r', proc)
<ide> os.kill(proc.pid, 9)
<ide> | 1 |
Javascript | Javascript | defer error to next tick | f2b01cba7b48c2410a692fe1cb29b2e88a6c5cab | <ide><path>lib/internal/child_process.js
<ide> function setupChannel(target, channel) {
<ide> if (typeof callback === 'function') {
<ide> process.nextTick(callback, ex);
<ide> } else {
<del> this.emit('error', ex); // FIXME(bnoordhuis) Defer to next tick.
<add> process.nextTick(() => this.emit('error', ex));
<ide> }
<ide> return false;
<ide> };
<ide> function setupChannel(target, channel) {
<ide> if (typeof callback === 'function') {
<ide> process.nextTick(callback, ex);
<ide> } else {
<del> this.emit('error', ex); // FIXME(bnoordhuis) Defer to next tick.
<add> process.nextTick(() => this.emit('error', ex));
<ide> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | fix eslint issues | 2130482198ca387a48f02d8ee0126a72b4efd07e | <ide><path>bin/changelog.js
<ide> #!/usr/bin/env node
<add>
<add>/* eslint-disable no-console, node/shebang */
<add>
<ide> 'use strict';
<ide>
<ide> /*
<ide> * bin/changelog.js
<ide> */
<ide>
<del>var RSVP = require('rsvp');
<add>var RSVP = require('rsvp');
<ide> var GitHubApi = require('github');
<del>var execSync = require('child_process').execSync;
<add>var execSync = require('child_process').execSync;
<ide>
<del>var github = new GitHubApi({ version: '3.0.0' });
<add>var github = new GitHubApi({ version: '3.0.0' });
<ide> var compareCommits = RSVP.denodeify(github.repos.compareCommits);
<ide> var currentVersion = process.env.PRIOR_VERSION;
<ide> var head = process.env.HEAD || execSync('git rev-parse HEAD', { encoding: 'UTF-8' });
<ide> compareCommits({
<ide> user: 'emberjs',
<ide> repo: 'ember.js',
<ide> base: currentVersion,
<del> head: head
<add> head: head,
<ide> })
<del>.then(processPages)
<del>.then(console.log)
<del>.catch(function(err) {
<del> console.error(err);
<del>});
<add> .then(processPages)
<add> .then(console.log)
<add> .catch(function(err) {
<add> console.error(err);
<add> });
<ide>
<ide> function getCommitMessage(commitInfo) {
<ide> var message = commitInfo.commit.message;
<ide> function getCommitMessage(commitInfo) {
<ide>
<ide> try {
<ide> // command from http://stackoverflow.com/questions/8475448/find-merge-commit-which-include-a-specific-commit
<del> message = execSync('commit=$((git rev-list ' + originalCommit + '..origin/master --ancestry-path | cat -n; git rev-list ' + originalCommit + '..origin/master --first-parent | cat -n) | sort -k2 | uniq -f1 -d | sort -n | tail -1 | cut -f2) && git show --format="%s\n\n%b" $commit', { encoding: 'utf8' });
<del> } catch (e) { }
<add> message = execSync(
<add> 'commit=$((git rev-list ' +
<add> originalCommit +
<add> '..origin/master --ancestry-path | cat -n; git rev-list ' +
<add> originalCommit +
<add> '..origin/master --first-parent | cat -n) | sort -k2 | uniq -f1 -d | sort -n | tail -1 | cut -f2) && git show --format="%s\n\n%b" $commit',
<add> { encoding: 'utf8' }
<add> );
<add> } catch (e) {
<add> // ignored
<add> }
<ide> }
<ide>
<ide> return message;
<ide> }
<ide>
<ide> function processPages(res) {
<del> var contributions = res.commits.filter(function(commitInfo) {
<del> var message = commitInfo.commit.message;
<del>
<del> return message.indexOf('Merge pull request #') > -1 || message.indexOf('cherry picked from') > -1;
<del> }).map(function(commitInfo) {
<del> var message = getCommitMessage(commitInfo);
<del> var match = message.match(/#(\d+) from (.*)\//);
<del> var result = {
<del> sha: commitInfo.sha
<del> };
<del>
<del> if (match) {
<del> var numAndAuthor = match.slice(1, 3);
<del>
<del> result.number = numAndAuthor[0];
<del> result.title = message.split('\n\n')[1];
<del> } else {
<del> result.title = message.split('\n\n')[0];
<del> }
<add> var contributions = res.commits
<add> .filter(function(commitInfo) {
<add> var message = commitInfo.commit.message;
<ide>
<del> return result;
<del> }).sort(function(a, b) {
<del> return a.number > b.number;
<del> }).map(function(pr) {
<del> var title = pr.title;
<del> var link;
<del> if (pr.number) {
<del> link = '[#' + pr.number + ']' + '(https://github.com/emberjs/ember.js/pull/' + pr.number + ')';
<del> } else {
<del> link = '[' + pr.sha.slice(0, 8) + '](https://github.com/emberjs/ember.js/commit/' + pr.sha + ')';
<del> }
<add> return (
<add> message.indexOf('Merge pull request #') > -1 || message.indexOf('cherry picked from') > -1
<add> );
<add> })
<add> .map(function(commitInfo) {
<add> var message = getCommitMessage(commitInfo);
<add> var match = message.match(/#(\d+) from (.*)\//);
<add> var result = {
<add> sha: commitInfo.sha,
<add> };
<add>
<add> if (match) {
<add> var numAndAuthor = match.slice(1, 3);
<add>
<add> result.number = numAndAuthor[0];
<add> result.title = message.split('\n\n')[1];
<add> } else {
<add> result.title = message.split('\n\n')[0];
<add> }
<add>
<add> return result;
<add> })
<add> .sort(function(a, b) {
<add> return a.number > b.number;
<add> })
<add> .map(function(pr) {
<add> var title = pr.title;
<add> var link;
<add> if (pr.number) {
<add> link =
<add> '[#' + pr.number + ']' + '(https://github.com/emberjs/ember.js/pull/' + pr.number + ')';
<add> } else {
<add> link =
<add> '[' + pr.sha.slice(0, 8) + '](https://github.com/emberjs/ember.js/commit/' + pr.sha + ')';
<add> }
<ide>
<del> return '- ' + link + ' ' + title;
<del> }).join('\n');
<add> return '- ' + link + ' ' + title;
<add> })
<add> .join('\n');
<ide>
<ide> if (github.hasNextPage(res)) {
<del> return github.getNextPage(res)
<del> .then(function(nextPage) {
<del> contributions += processPages(nextPage);
<del> });
<add> return github.getNextPage(res).then(function(nextPage) {
<add> contributions += processPages(nextPage);
<add> });
<ide> } else {
<ide> return RSVP.resolve(contributions);
<ide> } | 1 |
PHP | PHP | remove unneeded code | f1e43d1e55453126bc21747762a7e528a1e1a23b | <ide><path>src/Illuminate/Queue/QueueManager.php
<ide> public function connection($name = null)
<ide> $this->connections[$name] = $this->resolve($name);
<ide>
<ide> $this->connections[$name]->setContainer($this->app);
<del>
<del> $this->connections[$name]->setEncrypter($this->app['encrypter']);
<ide> }
<ide>
<ide> return $this->connections[$name];
<ide><path>tests/Queue/QueueManagerTest.php
<ide> public function testDefaultConnectionCanBeResolved()
<ide> return $connector;
<ide> });
<ide> $queue->shouldReceive('setContainer')->once()->with($app);
<del> $queue->shouldReceive('setEncrypter')->once()->with($encrypter);
<ide>
<ide> $this->assertSame($queue, $manager->connection('sync'));
<ide> }
<ide> public function testOtherConnectionCanBeResolved()
<ide> return $connector;
<ide> });
<ide> $queue->shouldReceive('setContainer')->once()->with($app);
<del> $queue->shouldReceive('setEncrypter')->once()->with($encrypter);
<ide>
<ide> $this->assertSame($queue, $manager->connection('foo'));
<ide> }
<ide> public function testNullConnectionCanBeResolved()
<ide> return $connector;
<ide> });
<ide> $queue->shouldReceive('setContainer')->once()->with($app);
<del> $queue->shouldReceive('setEncrypter')->once()->with($encrypter);
<ide>
<ide> $this->assertSame($queue, $manager->connection('null'));
<ide> } | 2 |
Go | Go | prefix all logs with daemon-id | 2b3957d0b168a697c7f1bb6fcfa4b2c66c9b8ae0 | <ide><path>testutil/daemon/daemon.go
<ide> func (d *Daemon) NewClientT(t testing.TB, extraOpts ...client.Opt) *client.Clien
<ide> t.Helper()
<ide>
<ide> c, err := d.NewClient(extraOpts...)
<del> assert.NilError(t, err, "cannot create daemon client")
<add> assert.NilError(t, err, "[%s] could not create daemon client", d.id)
<ide> return c
<ide> }
<ide>
<ide> func (d *Daemon) NewClient(extraOpts ...client.Opt) (*client.Client, error) {
<ide> func (d *Daemon) Cleanup(t testing.TB) {
<ide> t.Helper()
<ide> cleanupMount(t, d)
<del> // Cleanup swarmkit wal files if present
<del> cleanupRaftDir(t, d.Root)
<del> cleanupNetworkNamespace(t, d.execRoot)
<add> cleanupRaftDir(t, d)
<add> cleanupNetworkNamespace(t, d)
<ide> }
<ide>
<ide> // Start starts the daemon and return once it is ready to receive requests.
<ide> func (d *Daemon) Start(t testing.TB, args ...string) {
<ide> t.Helper()
<ide> if err := d.StartWithError(args...); err != nil {
<del> t.Fatalf("failed to start daemon with arguments %v : %v", args, err)
<add> t.Fatalf("[%s] failed to start daemon with arguments %v : %v", d.id, args, err)
<ide> }
<ide> }
<ide>
<ide> func (d *Daemon) Start(t testing.TB, args ...string) {
<ide> func (d *Daemon) StartWithError(args ...string) error {
<ide> logFile, err := os.OpenFile(filepath.Join(d.Folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
<ide> if err != nil {
<del> return errors.Wrapf(err, "[%s] Could not create %s/docker.log", d.id, d.Folder)
<add> return errors.Wrapf(err, "[%s] failed to create logfile", d.id)
<ide> }
<ide>
<ide> return d.StartWithLogFile(logFile, args...)
<ide> func (d *Daemon) Stop(t testing.TB) {
<ide> err := d.StopWithError()
<ide> if err != nil {
<ide> if err != errDaemonNotStarted {
<del> t.Fatalf("Error while stopping the daemon %s : %v", d.id, err)
<add> t.Fatalf("[%s] error while stopping the daemon: %v", d.id, err)
<ide> } else {
<del> t.Logf("Daemon %s is not started", d.id)
<add> t.Logf("[%s] daemon is not started", d.id)
<ide> }
<ide> }
<ide> }
<ide> func (d *Daemon) StopWithError() (err error) {
<ide> return errDaemonNotStarted
<ide> }
<ide> defer func() {
<del> if err == nil {
<del> d.log.Logf("[%s] Daemon stopped", d.id)
<add> if err != nil {
<add> d.log.Logf("[%s] error while stopping daemon: %v", d.id, err)
<ide> } else {
<del> d.log.Logf("[%s] Error when stopping daemon: %v", d.id, err)
<add> d.log.Logf("[%s] daemon stopped", d.id)
<ide> }
<ide> d.logFile.Close()
<ide> d.cmd = nil
<ide> func (d *Daemon) StopWithError() (err error) {
<ide> defer ticker.Stop()
<ide> tick := ticker.C
<ide>
<del> d.log.Logf("[%s] Stopping daemon", d.id)
<add> d.log.Logf("[%s] stopping daemon", d.id)
<ide>
<ide> if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
<ide> if strings.Contains(err.Error(), "os: process already finished") {
<ide> return errDaemonNotStarted
<ide> }
<del> return errors.Errorf("could not send signal: %v", err)
<add> return errors.Errorf("[%s] could not send signal: %v", d.id, err)
<ide> }
<ide>
<ide> out1:
<ide> out1:
<ide> return err
<ide> case <-time.After(20 * time.Second):
<ide> // time for stopping jobs and run onShutdown hooks
<del> d.log.Logf("[%s] daemon stop timeout", d.id)
<add> d.log.Logf("[%s] daemon stop timed out after 20 seconds", d.id)
<ide> break out1
<ide> }
<ide> }
<ide> out2:
<ide> case <-tick:
<ide> i++
<ide> if i > 5 {
<del> d.log.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
<add> d.log.Logf("[%s] tried to interrupt daemon for %d times, now try to kill it", d.id, i)
<ide> break out2
<ide> }
<del> d.log.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
<add> d.log.Logf("[%d] attempt #%d/5: daemon is still running with pid %d", i, d.cmd.Process.Pid)
<ide> if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
<del> return errors.Errorf("could not send signal: %v", err)
<add> return errors.Errorf("[%s] attempt #%d/5 could not send signal: %v", d.id, i, err)
<ide> }
<ide> }
<ide> }
<ide>
<ide> if err := d.cmd.Process.Kill(); err != nil {
<del> d.log.Logf("Could not kill daemon: %v", err)
<add> d.log.Logf("[%s] failed to kill daemon: %v", d.id, err)
<ide> return err
<ide> }
<ide>
<ide> func (d *Daemon) ReloadConfig() error {
<ide>
<ide> <-started
<ide> if err := signalDaemonReload(d.cmd.Process.Pid); err != nil {
<del> return errors.Errorf("error signaling daemon reload: %v", err)
<add> return errors.Errorf("[%s] error signaling daemon reload: %v", d.id, err)
<ide> }
<ide> select {
<ide> case err := <-errCh:
<ide> if err != nil {
<del> return errors.Errorf("error waiting for daemon reload event: %v", err)
<add> return errors.Wrapf(err, "[%s] error waiting for daemon reload event", d.id)
<ide> }
<ide> case <-time.After(30 * time.Second):
<del> return errors.New("timeout waiting for daemon reload event")
<add> return errors.Errorf("[%s] daemon reload event timed out after 30 seconds", d.id)
<ide> }
<ide> return nil
<ide> }
<ide> func (d *Daemon) ReloadConfig() error {
<ide> func (d *Daemon) LoadBusybox(t testing.TB) {
<ide> t.Helper()
<ide> clientHost, err := client.NewClientWithOpts(client.FromEnv)
<del> assert.NilError(t, err, "failed to create client")
<add> assert.NilError(t, err, "[%s] failed to create client", d.id)
<ide> defer clientHost.Close()
<ide>
<ide> ctx := context.Background()
<ide> reader, err := clientHost.ImageSave(ctx, []string{"busybox:latest"})
<del> assert.NilError(t, err, "failed to download busybox")
<add> assert.NilError(t, err, "[%s] failed to download busybox", d.id)
<ide> defer reader.Close()
<ide>
<ide> c := d.NewClientT(t)
<ide> defer c.Close()
<ide>
<ide> resp, err := c.ImageLoad(ctx, reader, true)
<del> assert.NilError(t, err, "failed to load busybox")
<add> assert.NilError(t, err, "[%s] failed to load busybox", d.id)
<ide> defer resp.Body.Close()
<ide> }
<ide>
<ide> func cleanupMount(t testing.TB, d *Daemon) {
<ide> }
<ide> }
<ide>
<del>func cleanupRaftDir(t testing.TB, rootPath string) {
<add>// cleanupRaftDir removes swarmkit wal files if present
<add>func cleanupRaftDir(t testing.TB, d *Daemon) {
<ide> t.Helper()
<ide> for _, p := range []string{"wal", "wal-v3-encrypted", "snap-v3-encrypted"} {
<del> dir := filepath.Join(rootPath, "swarm/raft", p)
<add> dir := filepath.Join(d.Root, "swarm/raft", p)
<ide> if err := os.RemoveAll(dir); err != nil {
<del> t.Logf("error removing %v: %v", dir, err)
<add> t.Logf("[%s] error removing %v: %v", d.id, dir, err)
<ide> }
<ide> }
<ide> }
<ide><path>testutil/daemon/daemon_unix.go
<ide> import (
<ide> "gotest.tools/assert"
<ide> )
<ide>
<del>func cleanupNetworkNamespace(t testing.TB, execRoot string) {
<add>func cleanupNetworkNamespace(t testing.TB, d *Daemon) {
<ide> t.Helper()
<ide> // Cleanup network namespaces in the exec root of this
<ide> // daemon because this exec root is specific to this
<ide> // daemon instance and has no chance of getting
<ide> // cleaned up when a new daemon is instantiated with a
<ide> // new exec root.
<del> netnsPath := filepath.Join(execRoot, "netns")
<add> netnsPath := filepath.Join(d.execRoot, "netns")
<ide> filepath.Walk(netnsPath, func(path string, info os.FileInfo, err error) error {
<ide> if err := unix.Unmount(path, unix.MNT_DETACH); err != nil && err != unix.EINVAL && err != unix.ENOENT {
<del> t.Logf("unmount of %s failed: %v", path, err)
<add> t.Logf("[%s] unmount of %s failed: %v", d.id, path, err)
<ide> }
<ide> os.Remove(path)
<ide> return nil
<ide><path>testutil/daemon/daemon_windows.go
<ide> func signalDaemonReload(pid int) error {
<ide> return fmt.Errorf("daemon reload not supported")
<ide> }
<ide>
<del>func cleanupNetworkNamespace(t testing.TB, execRoot string) {
<del>}
<add>func cleanupNetworkNamespace(_ testing.TB, _ *Daemon) {}
<ide>
<ide> // CgroupNamespace returns the cgroup namespace the daemon is running in
<ide> func (d *Daemon) CgroupNamespace(t testing.TB) string { | 3 |
Python | Python | increase required cython version on python 3.7 | 323458c4cd80935b61d2021181a47794ba81ccf3 | <ide><path>tools/cythonize.py
<ide> def process_pyx(fromfile, tofile):
<ide> else:
<ide> # check the version, and invoke through python
<ide> from distutils.version import LooseVersion
<del> if LooseVersion(cython_version) < LooseVersion('0.19'):
<del> raise Exception('Building %s requires Cython >= 0.19' % VENDOR)
<add>
<add> # requiring the newest version on all pythons doesn't work, since
<add> # we're relying on the version of the distribution cython. Add new
<add> # versions as they become required for new python versions.
<add> if sys.version_info[:2] < (3, 7):
<add> required_version = LooseVersion('0.19')
<add> else:
<add> required_version = LooseVersion('0.28')
<add>
<add> if LooseVersion(cython_version) < required_version:
<add> raise RuntimeError('Building {} requires Cython >= {}'.format(
<add> VENDOR, required_version))
<ide> subprocess.check_call(
<ide> [sys.executable, '-m', 'cython'] + flags + ["-o", tofile, fromfile])
<ide> | 1 |
Javascript | Javascript | make key of queueconnect a chunkgroupinfo | 35e2e1c97c825ef511f158ecddf98da906fc9191 | <ide><path>lib/buildChunkGraph.js
<ide> const visitModules = (
<ide> // correct order
<ide> queue.reverse();
<ide>
<del> /** @type {Map<ChunkGroup, Set<ChunkGroup>>} */
<add> /** @type {Map<ChunkGroupInfo, Set<ChunkGroup>>} */
<ide> const queueConnect = new Map();
<ide> /** @type {Set<ChunkGroupInfo>} */
<ide> const outdatedChunkGroupInfo = new Set();
<ide> const visitModules = (
<ide> });
<ide>
<ide> // 3. We create/update the chunk group info
<del> let connectList = queueConnect.get(chunkGroup);
<add> let connectList = queueConnect.get(chunkGroupInfo);
<ide> if (connectList === undefined) {
<ide> connectList = new Set();
<del> queueConnect.set(chunkGroup, connectList);
<add> queueConnect.set(chunkGroupInfo, connectList);
<ide> }
<ide> connectList.add(c);
<ide>
<ide> const visitModules = (
<ide>
<ide> // Figure out new parents for chunk groups
<ide> // to get new available modules for these children
<del> for (const [chunkGroup, targets] of queueConnect) {
<del> const info = chunkGroupInfoMap.get(chunkGroup);
<del> let minAvailableModules = info.minAvailableModules;
<add> for (const [chunkGroupInfo, targets] of queueConnect) {
<add> let minAvailableModules = chunkGroupInfo.minAvailableModules;
<ide>
<ide> // 1. Create a new Set of available modules at this point
<ide> const resultingAvailableModules = new Set(minAvailableModules);
<del> for (const chunk of chunkGroup.chunks) {
<add> for (const chunk of chunkGroupInfo.chunkGroup.chunks) {
<ide> for (const m of chunkGraph.getChunkModulesIterable(chunk)) {
<ide> resultingAvailableModules.add(m);
<ide> }
<ide> }
<del> info.resultingAvailableModules = resultingAvailableModules;
<del> if (info.children === undefined) {
<del> info.children = targets;
<add> chunkGroupInfo.resultingAvailableModules = resultingAvailableModules;
<add> if (chunkGroupInfo.children === undefined) {
<add> chunkGroupInfo.children = targets;
<ide> } else {
<ide> for (const target of targets) {
<del> info.children.add(target);
<add> chunkGroupInfo.children.add(target);
<ide> }
<ide> }
<ide>
<ide> const visitModules = (
<ide>
<ide> // 3. Reconsider children chunk groups
<ide> if (info.children !== undefined) {
<del> const chunkGroup = info.chunkGroup;
<ide> for (const c of info.children) {
<del> let connectList = queueConnect.get(chunkGroup);
<add> let connectList = queueConnect.get(info);
<ide> if (connectList === undefined) {
<ide> connectList = new Set();
<del> queueConnect.set(chunkGroup, connectList);
<add> queueConnect.set(info, connectList);
<ide> }
<ide> connectList.add(c);
<ide> } | 1 |
Mixed | Text | move videos and newsletter to support | d662628ee3d7a42c24176344a6f9c6068523ea44 | <ide><path>docs/Newsletter.md
<del>---
<del>id: newsletter
<del>title: Newsletter
<del>layout: docs
<del>category: Community Resources
<del>permalink: http://reactnative.cc/
<del>next: style
<del>---
<ide><path>docs/SampleApplication-F8App.md
<ide> title: F8 2016 App
<ide> layout: docs
<ide> category: Sample Applications
<ide> permalink: http://makeitopen.com/
<del>next: videos
<add>next: style
<ide> ---
<ide><path>docs/Videos.md
<del>---
<del>id: videos
<del>title: Videos
<del>layout: docs
<del>category: Community Resources
<del>permalink: docs/videos.html
<del>next: newsletter
<del>---
<del>
<del>### React.js Conf 2016
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/2Zthnq-hIXA" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/Xnqy_zkBAew" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/RBg2_uQE4KM" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/0MlT74erp60" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/B8J8xn3pLpk" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/f1Sj48rJE3I" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/uBYPqb83C7k" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/09ddrCaLo10" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/d3VVfA9hWjc" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/impQkQOCbMw" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/wuLKELLuwVk" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/Zoerbz5Mu5U" frameborder="0" allowfullscreen></iframe>
<del>
<del>
<del>### React.js Conf 2015
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/KVZ-P-ZI6W4" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/7rDsRXj9-cU" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/X6YbAKiLCLU" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/oWPoW0gIzvs" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/hDviGU-57lU" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/8N4f4h6SThc" frameborder="0" allowfullscreen></iframe>
<del>
<del><iframe width="650" height="315" src="//www.youtube.com/embed/-XxSCi8TKuk" frameborder="0" allowfullscreen></iframe>
<del>
<del>### [The Changelog #149](https://thechangelog.com/149/)
<del>With Christopher "vjeux" Chedeau and Spencer Ahrens
<del>
<del><audio src="http://fdlyr.co/d/changelog/cdn.5by5.tv/audio/broadcasts/changelog/2015/changelog-149.mp3" controls="controls" preload="none"></audio>
<del>
<del>### [JSJabber #146](http://devchat.tv/js-jabber/146-jsj-react-with-christopher-chedeau-and-jordan-walke)
<del>With Christopher "vjeux" Chedeau and Jordan Walke
<del>
<del><audio controls="">
<del><source ng-src="http://www.podtrac.com/pts/redirect.mp3/media.devchat.tv/js-jabber/JSJ146React.mp3?player=true" type="audio/mpeg" src="http://www.podtrac.com/pts/redirect.mp3/media.devchat.tv/js-jabber/JSJ146React.mp3?player=true">
<del><p>
<del>This player is only available in HTML5 enabled browsers. Please update your browser or
<del><a download="146-jsj-react-with-christopher-chedeau-and-jordan-walke.mp3" href="http://www.podtrac.com/pts/redirect.mp3/media.devchat.tv/js-jabber/JSJ146React.mp3?download=true?download=true">download the episode</a>
<del></p>
<del></audio>
<ide><path>website/src/react-native/support.js
<ide> var support = React.createClass({
<ide> <p><a href="https://twitter.com/search?q=%23reactnative"><strong>#reactnative</strong> hash tag on Twitter</a> is used to keep up with the latest React Native news.</p>
<ide>
<ide> <p><center><a className="twitter-timeline" data-dnt="true" data-chrome="nofooter noheader transparent" href="https://twitter.com/search?q=%23reactnative" data-widget-id="565960513457098753"></a></center></p>
<add>
<add> <h2>Newsletter</h2>
<add> <p>Community member Brent Vatne runs an occasional <a href="http://reactnative.cc/">React Native newsletter</a> with news and happenings from the world of React Native.</p>
<add>
<add> <h2>Audio and Video</h2>
<add> <p>Check out various audio and video of those speaking about React Native at conferences, in podcasts, etc.</p>
<add> <h3>React.js Conf 2016</h3>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/2Zthnq-hIXA" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/Xnqy_zkBAew" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/RBg2_uQE4KM" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/0MlT74erp60" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/B8J8xn3pLpk" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/f1Sj48rJE3I" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/uBYPqb83C7k" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/09ddrCaLo10" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/d3VVfA9hWjc" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/impQkQOCbMw" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/wuLKELLuwVk" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/Zoerbz5Mu5U" frameborder="0" allowfullscreen></iframe>
<add>
<add>
<add> <h3>React.js Conf 2015</h3>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/KVZ-P-ZI6W4" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/7rDsRXj9-cU" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/X6YbAKiLCLU" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/oWPoW0gIzvs" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/hDviGU-57lU" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/8N4f4h6SThc" frameborder="0" allowfullscreen></iframe>
<add>
<add> <iframe width="650" height="315" src="//www.youtube.com/embed/-XxSCi8TKuk" frameborder="0" allowfullscreen></iframe>
<add>
<add> <h3><a href="https://thechangelog.com/149/">The Changelog #149</a></h3>
<add> <p>With Christopher "vjeux" Chedeau and Spencer Ahrens</p>
<add>
<add> <audio src="http://fdlyr.co/d/changelog/cdn.5by5.tv/audio/broadcasts/changelog/2015/changelog-149.mp3" controls="controls" preload="none"></audio>
<add>
<add> <h3><a href="http://devchat.tv/js-jabber/146-jsj-react-with-christopher-chedeau-and-jordan-walke">JSJabber #146</a></h3>
<add> <p>With Christopher "vjeux" Chedeau and Jordan Walke</p>
<add>
<add> <audio controls>
<add> <source ng-src="http://www.podtrac.com/pts/redirect.mp3/media.devchat.tv/js-jabber/JSJ146React.mp3?player=true" type="audio/mpeg" src="http://www.podtrac.com/pts/redirect.mp3/media.devchat.tv/js-jabber/JSJ146React.mp3?player=true" />
<add> <p>
<add> This player is only available in HTML5 enabled browsers. Please update your browser or
<add> <a download="146-jsj-react-with-christopher-chedeau-and-jordan-walke.mp3" href="http://www.podtrac.com/pts/redirect.mp3/media.devchat.tv/js-jabber/JSJ146React.mp3?download=true?download=true">download the episode</a>
<add> </p>
<add> </audio>
<ide> </div>
<ide> </section>
<ide> | 4 |
Javascript | Javascript | add missing item type | 7bb81ad97fdb0904373e43148d52abe53ccaa8cb | <ide><path>packages/ember-application/lib/system/application.js
<ide> Ember.Application.reopenClass({
<ide> This allows the application to register default injections in the container
<ide> that could be overridden by the normal naming convention.
<ide>
<add> @method resolverFor
<ide> @param {Ember.Namespace} namespace the namespace to look for classes
<ide> @return {*} the resolved value for a given lookup
<ide> */
<ide><path>packages/ember-handlebars/lib/ext.js
<ide> Ember.Handlebars.registerBoundHelper = function(name, fn) {
<ide>
<ide> Renders the unbound form of an otherwise bound helper function.
<ide>
<add> @method evaluateMultiPropertyBoundHelper
<ide> @param {Function} fn
<ide> @param {Object} context
<ide> @param {Array} normalizedProperties
<ide> function evaluateMultiPropertyBoundHelper(context, fn, normalizedProperties, opt
<ide>
<ide> Renders the unbound form of an otherwise bound helper function.
<ide>
<add> @method evaluateUnboundHelper
<ide> @param {Function} fn
<ide> @param {Object} context
<ide> @param {Array} normalizedProperties
<ide><path>packages/ember-routing/lib/system/route.js
<ide> Ember.Route = Ember.Object.extend({
<ide> @private
<ide>
<ide> Called when the context is changed by router.js.
<add>
<add> @method contextDidChange
<ide> */
<ide> contextDidChange: function() {
<ide> this.currentModel = this.context; | 3 |
PHP | PHP | add serialize option to array cache config | c9cf57a00c76c58afec25a822846f0798661e372 | <ide><path>config/cache.php
<ide>
<ide> 'array' => [
<ide> 'driver' => 'array',
<add> 'serialize' => false,
<ide> ],
<ide>
<ide> 'database' => [ | 1 |
Text | Text | update http method override middleware example | f5470ab9e292c7321377ae1f43f85e311d94975f | <ide><path>docs/topics/browser-enhancements.md
<ide> For example:
<ide>
<ide> METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
<ide>
<del> class MethodOverrideMiddleware(object):
<del> def process_view(self, request, callback, callback_args, callback_kwargs):
<del> if request.method != 'POST':
<del> return
<del> if METHOD_OVERRIDE_HEADER not in request.META:
<del> return
<del> request.method = request.META[METHOD_OVERRIDE_HEADER]
<add> class MethodOverrideMiddleware:
<add>
<add> def __init__(self, get_response):
<add> self.get_response = get_response
<add>
<add> def __call__(self, request):
<add> if request.method == 'POST' and METHOD_OVERRIDE_HEADER in request.META:
<add> request.method = request.META[METHOD_OVERRIDE_HEADER]
<add> return self.get_response(request)
<ide>
<ide> ## URL based accept headers
<ide> | 1 |
Javascript | Javascript | improve validatedomnesting message for whitespace | 6a659606415d4853026df6e6d525274fdc7d35ea | <ide><path>src/renderers/dom/client/validateDOMNesting.js
<ide> if (__DEV__) {
<ide>
<ide> var didWarn = {};
<ide>
<del> validateDOMNesting = function(childTag, childInstance, ancestorInfo) {
<add> validateDOMNesting = function(
<add> childTag,
<add> childText,
<add> childInstance,
<add> ancestorInfo
<add> ) {
<ide> ancestorInfo = ancestorInfo || emptyAncestorInfo;
<ide> var parentInfo = ancestorInfo.current;
<ide> var parentTag = parentInfo && parentInfo.tag;
<ide>
<add> if (childText != null) {
<add> warning(
<add> childTag == null,
<add> 'validateDOMNesting: when childText is passed, childTag should be null'
<add> );
<add> childTag = '#text';
<add> }
<add>
<ide> var invalidParent =
<ide> isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
<ide> var invalidAncestor =
<ide> if (__DEV__) {
<ide> didWarn[warnKey] = true;
<ide>
<ide> var tagDisplayName = childTag;
<del> if (childTag !== '#text') {
<add> var whitespaceInfo = '';
<add> if (childTag === '#text') {
<add> if (/\S/.test(childText)) {
<add> tagDisplayName = 'Text nodes';
<add> } else {
<add> tagDisplayName = 'Whitespace text nodes';
<add> whitespaceInfo =
<add> ' Make sure you don\'t have any extra whitespace between tags on ' +
<add> 'each line of your source code.';
<add> }
<add> } else {
<ide> tagDisplayName = '<' + childTag + '>';
<ide> }
<ide>
<ide> if (__DEV__) {
<ide> }
<ide> warning(
<ide> false,
<del> 'validateDOMNesting(...): %s cannot appear as a child of <%s>. ' +
<add> 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s ' +
<ide> 'See %s.%s',
<ide> tagDisplayName,
<ide> ancestorTag,
<add> whitespaceInfo,
<ide> ownerInfo,
<ide> info
<ide> );
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> function optionPostMount() {
<ide> ReactDOMOption.postMountWrapper(inst);
<ide> }
<ide>
<del>var setContentChildForInstrumentation = emptyFunction;
<add>var setAndValidateContentChildDev = emptyFunction;
<ide> if (__DEV__) {
<del> setContentChildForInstrumentation = function(content) {
<add> setAndValidateContentChildDev = function(content) {
<ide> var hasExistingContent = this._contentDebugID != null;
<ide> var debugID = this._debugID;
<ide> // This ID represents the inlined child that has no backing instance:
<ide> if (__DEV__) {
<ide> return;
<ide> }
<ide>
<add> validateDOMNesting(null, String(content), this, this._ancestorInfo);
<ide> this._contentDebugID = contentDebugID;
<ide> if (hasExistingContent) {
<ide> ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content);
<ide> function ReactDOMComponent(element) {
<ide> this._flags = 0;
<ide> if (__DEV__) {
<ide> this._ancestorInfo = null;
<del> setContentChildForInstrumentation.call(this, null);
<add> setAndValidateContentChildDev.call(this, null);
<ide> }
<ide> }
<ide>
<ide> ReactDOMComponent.Mixin = {
<ide> if (parentInfo) {
<ide> // parentInfo should always be present except for the top-level
<ide> // component when server rendering
<del> validateDOMNesting(this._tag, this, parentInfo);
<add> validateDOMNesting(this._tag, null, this, parentInfo);
<ide> }
<ide> this._ancestorInfo =
<ide> validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this);
<ide> ReactDOMComponent.Mixin = {
<ide> // TODO: Validate that text is allowed as a child of this node
<ide> ret = escapeTextContentForBrowser(contentToUse);
<ide> if (__DEV__) {
<del> setContentChildForInstrumentation.call(this, contentToUse);
<add> setAndValidateContentChildDev.call(this, contentToUse);
<ide> }
<ide> } else if (childrenToUse != null) {
<ide> var mountImages = this.mountChildren(
<ide> ReactDOMComponent.Mixin = {
<ide> if (contentToUse != null) {
<ide> // TODO: Validate that text is allowed as a child of this node
<ide> if (__DEV__) {
<del> setContentChildForInstrumentation.call(this, contentToUse);
<add> setAndValidateContentChildDev.call(this, contentToUse);
<ide> }
<ide> DOMLazyTree.queueText(lazyTree, contentToUse);
<ide> } else if (childrenToUse != null) {
<ide> ReactDOMComponent.Mixin = {
<ide> if (lastContent !== nextContent) {
<ide> this.updateTextContent('' + nextContent);
<ide> if (__DEV__) {
<del> setContentChildForInstrumentation.call(this, nextContent);
<add> setAndValidateContentChildDev.call(this, nextContent);
<ide> }
<ide> }
<ide> } else if (nextHtml != null) {
<ide> ReactDOMComponent.Mixin = {
<ide> }
<ide> } else if (nextChildren != null) {
<ide> if (__DEV__) {
<del> setContentChildForInstrumentation.call(this, null);
<add> setAndValidateContentChildDev.call(this, null);
<ide> }
<ide>
<ide> this.updateChildren(nextChildren, transaction, context);
<ide> ReactDOMComponent.Mixin = {
<ide> this._wrapperState = null;
<ide>
<ide> if (__DEV__) {
<del> setContentChildForInstrumentation.call(this, null);
<add> setAndValidateContentChildDev.call(this, null);
<ide> }
<ide> },
<ide>
<ide><path>src/renderers/dom/shared/ReactDOMTextComponent.js
<ide> Object.assign(ReactDOMTextComponent.prototype, {
<ide> if (parentInfo) {
<ide> // parentInfo should always be present except for the top-level
<ide> // component when server rendering
<del> validateDOMNesting('#text', this, parentInfo);
<add> validateDOMNesting(null, this._stringText, this, parentInfo);
<ide> }
<ide> }
<ide>
<ide><path>src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', function() {
<ide> });
<ide>
<ide> it('should work error event on <source> element', function() {
<del> spyOn(console, 'error');
<add> spyOn(console, 'error');
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(
<ide> <video>
<ide> describe('ReactDOMComponent', function() {
<ide>
<ide> class Row extends React.Component {
<ide> render() {
<del> return <tr />;
<add> return <tr>x</tr>;
<ide> }
<ide> }
<ide>
<ide> describe('ReactDOMComponent', function() {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Foo />);
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<add> expect(console.error.calls.count()).toBe(3);
<ide> expect(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' +
<ide> '<table>. See Foo > table > Row > tr. Add a <tbody> to your code to ' +
<ide> 'match the DOM tree generated by the browser.'
<ide> );
<ide> expect(console.error.calls.argsFor(1)[0]).toBe(
<del> 'Warning: validateDOMNesting(...): #text cannot appear as a child ' +
<del> 'of <table>. See Foo > table > #text.'
<add> 'Warning: validateDOMNesting(...): Text nodes cannot appear as a ' +
<add> 'child of <tr>. See Row > tr > #text.'
<add> );
<add> expect(console.error.calls.argsFor(2)[0]).toBe(
<add> 'Warning: validateDOMNesting(...): Whitespace text nodes cannot ' +
<add> 'appear as a child of <table>. Make sure you don\'t have any extra ' +
<add> 'whitespace between tags on each line of your source code. See Foo > ' +
<add> 'table > #text.'
<ide> );
<ide> });
<ide> | 4 |
Python | Python | remove django 1.5 urlvalidator fallback | e625cff8a5e4e4353d280fdd4c305dc6dbeed999 | <ide><path>rest_framework/compat.py
<ide> def __init__(self, *args, **kwargs):
<ide> super(MaxLengthValidator, self).__init__(*args, **kwargs)
<ide>
<ide>
<del># URLValidator only accepts `message` in 1.6+
<del>if django.VERSION >= (1, 6):
<del> from django.core.validators import URLValidator
<del>else:
<del> from django.core.validators import URLValidator as DjangoURLValidator
<del>
<del>
<del> class URLValidator(DjangoURLValidator):
<del> def __init__(self, *args, **kwargs):
<del> self.message = kwargs.pop('message', self.message)
<del> super(URLValidator, self).__init__(*args, **kwargs)
<del>
<del>
<ide> # PATCH method is not implemented by Django
<ide> if 'patch' not in View.http_method_names:
<ide> View.http_method_names = View.http_method_names + ['patch']
<ide><path>rest_framework/fields.py
<ide> from django.conf import settings
<ide> from django.core.exceptions import ValidationError as DjangoValidationError
<ide> from django.core.exceptions import ObjectDoesNotExist
<del>from django.core.validators import EmailValidator, RegexValidator, ip_address_validators
<add>from django.core.validators import EmailValidator, RegexValidator, ip_address_validators, URLValidator
<ide> from django.forms import FilePathField as DjangoFilePathField
<ide> from django.forms import ImageField as DjangoImageField
<ide> from django.utils import six, timezone
<ide> from rest_framework import ISO_8601
<ide> from rest_framework.compat import (
<ide> MaxLengthValidator, MaxValueValidator, MinLengthValidator,
<del> MinValueValidator, OrderedDict, URLValidator, duration_string,
<add> MinValueValidator, OrderedDict, duration_string,
<ide> parse_duration, unicode_repr, unicode_to_repr
<ide> )
<ide> from rest_framework.exceptions import ValidationError | 2 |
Java | Java | fix various typos | e9f78f6043d8391121ba93d496b66beaa13a1dca | <ide><path>spring-aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java
<ide> public class DelegatePerTargetObjectIntroductionInterceptor extends Introduction
<ide> public DelegatePerTargetObjectIntroductionInterceptor(Class<?> defaultImplType, Class<?> interfaceType) {
<ide> this.defaultImplType = defaultImplType;
<ide> this.interfaceType = interfaceType;
<del> // cCeate a new delegate now (but don't store it in the map).
<add> // Create a new delegate now (but don't store it in the map).
<ide> // We do this for two reasons:
<ide> // 1) to fail early if there is a problem instantiating delegates
<ide> // 2) to populate the interface map once and once only
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandler.java
<ide> * it encounters a custom tag directly under a {@code <bean>} tag.
<ide> *
<ide> * <p>Developers writing their own custom element extensions typically will
<del> * not implement this interface drectly, but rather make use of the provided
<add> * not implement this interface directly, but rather make use of the provided
<ide> * {@link NamespaceHandlerSupport} class.
<ide> *
<ide> * @author Rob Harrop
<ide><path>spring-core/src/main/java/org/springframework/asm/Frame.java
<ide> private void push(final int type) {
<ide> }
<ide> // pushes the type on the output stack
<ide> outputStack[outputStackTop++] = type;
<del> // updates the maximun height reached by the output stack, if needed
<add> // updates the maximum height reached by the output stack, if needed
<ide> int top = owner.inputStackTop + outputStackTop;
<ide> if (top > owner.outputStackMax) {
<ide> owner.outputStackMax = top;
<ide><path>spring-core/src/main/java/org/springframework/util/AutoPopulatingList.java
<ide> public ElementInstantiationException(String msg) {
<ide> private final Class<? extends E> elementClass;
<ide>
<ide> public ReflectiveElementFactory(Class<? extends E> elementClass) {
<del> Assert.notNull(elementClass, "Element clas must not be null");
<add> Assert.notNull(elementClass, "Element class must not be null");
<ide> Assert.isTrue(!elementClass.isInterface(), "Element class must not be an interface type");
<ide> Assert.isTrue(!Modifier.isAbstract(elementClass.getModifiers()), "Element class cannot be an abstract class");
<ide> this.elementClass = elementClass;
<ide><path>spring-core/src/main/java/org/springframework/util/CompositeIterator.java
<ide> public E next() {
<ide> return iterator.next();
<ide> }
<ide> }
<del> throw new NoSuchElementException("Exhaused all iterators");
<add> throw new NoSuchElementException("Exhausted all iterators");
<ide> }
<ide>
<ide> @Override
<ide><path>spring-core/src/main/java/org/springframework/util/StringUtils.java
<ide> public static String trimWhitespace(String str) {
<ide>
<ide> /**
<ide> * Trim <i>all</i> whitespace from the given String:
<del> * leading, trailing, and inbetween characters.
<add> * leading, trailing, and in between characters.
<ide> * @param str the String to check
<ide> * @return the trimmed String
<ide> * @see java.lang.Character#isWhitespace
<ide> public static String trimTrailingWhitespace(String str) {
<ide> }
<ide>
<ide> /**
<del> * Trim all occurences of the supplied leading character from the given String.
<add> * Trim all occurrences of the supplied leading character from the given String.
<ide> * @param str the String to check
<ide> * @param leadingCharacter the leading character to be trimmed
<ide> * @return the trimmed String
<ide> public static String trimLeadingCharacter(String str, char leadingCharacter) {
<ide> }
<ide>
<ide> /**
<del> * Trim all occurences of the supplied trailing character from the given String.
<add> * Trim all occurrences of the supplied trailing character from the given String.
<ide> * @param str the String to check
<ide> * @param trailingCharacter the trailing character to be trimmed
<ide> * @return the trimmed String
<ide> public static int countOccurrencesOf(String str, String sub) {
<ide> }
<ide>
<ide> /**
<del> * Replace all occurences of a substring within a string with
<add> * Replace all occurrences of a substring within a string with
<ide> * another string.
<ide> * @param inString String to examine
<ide> * @param oldPattern String to replace
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataProvider.java
<ide> public interface CallMetaDataProvider {
<ide>
<ide> /**
<ide> * Initialize the database specific management of procedure column meta data.
<del> * This is only called for databases that are supported. This initalization
<add> * This is only called for databases that are supported. This initialization
<ide> * can be turned off by specifying that column meta data should not be used.
<ide> * @param databaseMetaData used to retrieve database specific information
<ide> * @param catalogName name of catalog to use or null
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataProviderFactory.java
<ide> public class CallMetaDataProviderFactory {
<ide> );
<ide>
<ide> /**
<del> * Create a CallMetaDataProvider based on the database metedata
<del> * @param dataSource used to retrieve metedata
<del> * @param context the class that holds configuration and metedata
<add> * Create a CallMetaDataProvider based on the database metadata
<add> * @param dataSource used to retrieve metadata
<add> * @param context the class that holds configuration and metadata
<ide> * @return instance of the CallMetaDataProvider implementation to be used
<ide> */
<ide> static public CallMetaDataProvider createMetaDataProvider(DataSource dataSource, final CallMetaDataContext context) {
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/GenericTableMetaDataProvider.java
<ide> private void locateTableAndProcessMetaData(DatabaseMetaData databaseMetaData, St
<ide> try {
<ide> tables.close();
<ide> } catch (SQLException e) {
<del> logger.warn("Error while closing table meta data reults" + e.getMessage());
<add> logger.warn("Error while closing table meta data results" + e.getMessage());
<ide> }
<ide> }
<ide> }
<ide> private void locateTableAndProcessMetaData(DatabaseMetaData databaseMetaData, St
<ide> }
<ide>
<ide> /**
<del> * Method supporting the metedata processing for a table's columns
<add> * Method supporting the metadata processing for a table's columns
<ide> */
<ide> private void processTableColumns(DatabaseMetaData databaseMetaData, TableMetaData tmd) {
<ide> ResultSet tableColumns = null;
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/ParsedSql.java
<ide> void addNamedParameter(String parameterName, int startIndex, int endIndex) {
<ide>
<ide> /**
<ide> * Return all of the parameters (bind variables) in the parsed SQL statement.
<del> * Repeated occurences of the same parameter name are included here.
<add> * Repeated occurrences of the same parameter name are included here.
<ide> */
<ide> List<String> getParameterNames() {
<ide> return this.parameterNames;
<ide> int[] getParameterIndexes(int parameterPosition) {
<ide>
<ide> /**
<ide> * Set the count of named parameters in the SQL statement.
<del> * Each parameter name counts once; repeated occurences do not count here.
<add> * Each parameter name counts once; repeated occurrences do not count here.
<ide> */
<ide> void setNamedParameterCount(int namedParameterCount) {
<ide> this.namedParameterCount = namedParameterCount;
<ide> }
<ide>
<ide> /**
<ide> * Return the count of named parameters in the SQL statement.
<del> * Each parameter name counts once; repeated occurences do not count here.
<add> * Each parameter name counts once; repeated occurrences do not count here.
<ide> */
<ide> int getNamedParameterCount() {
<ide> return this.namedParameterCount;
<ide> int getUnnamedParameterCount() {
<ide>
<ide> /**
<ide> * Set the total count of all of the parameters in the SQL statement.
<del> * Repeated occurences of the same parameter name do count here.
<add> * Repeated occurrences of the same parameter name do count here.
<ide> */
<ide> void setTotalParameterCount(int totalParameterCount) {
<ide> this.totalParameterCount = totalParameterCount;
<ide> }
<ide>
<ide> /**
<ide> * Return the total count of all of the parameters in the SQL statement.
<del> * Repeated occurences of the same parameter name do count here.
<add> * Repeated occurrences of the same parameter name do count here.
<ide> */
<ide> int getTotalParameterCount() {
<ide> return this.totalParameterCount;
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcInsert.java
<ide> protected void checkCompiled() {
<ide> }
<ide>
<ide> /**
<del> * Method to check whether we are allowd to make any configuration changes at this time.
<add> * Method to check whether we are allowed to make any configuration changes at this time.
<ide> * If the class has been compiled, then no further changes to the configuration are allowed.
<ide> */
<ide> protected void checkIfConfigurationModificationIsAllowed() {
<ide> public PreparedStatement createPreparedStatement(Connection con) throws SQLExcep
<ide> "The getGeneratedKeys feature is not supported by this database");
<ide> }
<ide> if (getGeneratedKeyNames().length < 1) {
<del> throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specificed. " +
<add> throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specified. " +
<ide> "Using the generated keys features requires specifying the name(s) of the generated column(s)");
<ide> }
<ide> if (getGeneratedKeyNames().length > 1) {
<ide> throw new InvalidDataAccessApiUsageException(
<del> "Current database only supports retreiving the key for a single column. There are " +
<add> "Current database only supports retrieving the key for a single column. There are " +
<ide> getGeneratedKeyNames().length + " columns specified: " + Arrays.asList(getGeneratedKeyNames()));
<ide> }
<ide> // This is a hack to be able to get the generated key from a database that doesn't support
<ide> private void setParameterValues(PreparedStatement preparedStatement, List<Object
<ide> }
<ide>
<ide> /**
<del> * Match the provided in parameter values with regitered parameters and parameters defined
<add> * Match the provided in parameter values with registered parameters and parameters defined
<ide> * via metadata processing.
<del> * @param parameterSource the parameter vakues provided as a {@link SqlParameterSource}
<add> * @param parameterSource the parameter values provided as a {@link SqlParameterSource}
<ide> * @return Map with parameter names and values
<ide> */
<ide> protected List<Object> matchInParameterValuesWithInsertColumns(SqlParameterSource parameterSource) {
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcInsertOperations.java
<ide> public interface SimpleJdbcInsertOperations {
<ide> SimpleJdbcInsertOperations withTableName(String tableName);
<ide>
<ide> /**
<del> * Specify the shema name, if any, to be used for the insert.
<add> * Specify the schema name, if any, to be used for the insert.
<ide> * @param schemaName the name of the schema
<ide> * @return the instance of this SimpleJdbcInsert
<ide> */
<ide><path>spring-jms/src/main/java/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.java
<ide> *
<ide> * <p>This listener container variant is built for repeated polling attempts,
<ide> * each invoking the {@link #receiveAndExecute} method. The MessageConsumer used
<del> * may be reobtained fo reach attempt or cached inbetween attempts; this is up
<add> * may be reobtained fo reach attempt or cached in between attempts; this is up
<ide> * to the concrete implementation. The receive timeout for each attempt can be
<ide> * configured through the {@link #setReceiveTimeout "receiveTimeout"} property.
<ide> *
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/handler/SimpleBrokerMessageHandler.java
<ide> protected void handleMessageInternal(Message<?> message) {
<ide>
<ide> if (!checkDestinationPrefix(destination)) {
<ide> if (logger.isTraceEnabled()) {
<del> logger.trace("Ingoring message to destination=" + destination);
<add> logger.trace("Ignoring message to destination=" + destination);
<ide> }
<ide> return;
<ide> }
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java
<ide> private Object doUnmarshal(HierarchicalStreamReader streamReader, DataHolder dat
<ide> * {@code org.springframework.oxm} hierarchy.
<ide> * <p>A boolean flag is used to indicate whether this exception occurs during marshalling or
<ide> * unmarshalling, since XStream itself does not make this distinction in its exception hierarchy.
<del> * @param ex XStream exception that occured
<add> * @param ex XStream exception that occurred
<ide> * @param marshalling indicates whether the exception occurs during marshalling ({@code true}),
<ide> * or unmarshalling ({@code false})
<ide> * @return the corresponding {@code XmlMappingException}
<ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/CallableProcessingInterceptor.java
<ide> public interface CallableProcessingInterceptor {
<ide> * <p>
<ide> * This is useful for capturing the state of the current thread just prior to
<ide> * invoking the {@link Callable}. Once the state is captured, it can then be
<del> * transfered to the new {@link Thread} in
<add> * transferred to the new {@link Thread} in
<ide> * {@link #preProcess(NativeWebRequest, Callable)}. Capturing the state of
<ide> * Spring Security's SecurityContextHolder and migrating it to the new Thread
<ide> * is a concrete example of where this is useful.
<ide><path>spring-web/src/main/java/org/springframework/web/context/support/ServletContextAwareProcessor.java
<ide> public class ServletContextAwareProcessor implements BeanPostProcessor {
<ide> /**
<ide> * Create a new ServletContextAwareProcessor without an initial context or config.
<ide> * When this constructor is used the {@link #getServletContext()} and/or
<del> * {@link #getServletConfig()} methods should be overriden.
<add> * {@link #getServletConfig()} methods should be overridden.
<ide> */
<ide> protected ServletContextAwareProcessor() {
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/filter/OncePerRequestFilter.java
<ide> * should be involved in async dispatches. However, in some cases servlet
<ide> * containers assume different default configuration. Therefore sub-classes can
<ide> * override the method {@link #shouldNotFilterAsyncDispatch()} to declare
<del> * statically if they shouuld indeed be invoked, <em>once</em>, during both types
<add> * statically if they should indeed be invoked, <em>once</em>, during both types
<ide> * of dispatches in order to provide thread initialization, logging, security,
<ide> * and so on. This mechanism complements and does not replace the need to
<ide> * configure a filter in {@code web.xml} with dispatcher types.
<ide><path>spring-web/src/main/java/org/springframework/web/jsf/DecoratingNavigationHandler.java
<ide> public abstract void handleNavigation(
<ide> * <p>If no decorated NavigationHandler specified as constructor argument,
<ide> * this instance is the last element in the chain. Hence, this method will
<ide> * call the original NavigationHandler as passed into this method. If no
<del> * original NavigantionHandler has been passed in (for example if this
<add> * original NavigationHandler has been passed in (for example if this
<ide> * instance is the last element in a chain with standard NavigationHandlers
<ide> * as earlier elements), this method corresponds to a no-op.
<ide> * @param facesContext the current JSF context
<ide><path>spring-web/src/main/java/org/springframework/web/util/WebAppRootListener.java
<ide> * parameter at the servlet context level (i.e. context-param in web.xml),
<ide> * the default key is "webapp.root".
<ide> *
<del> * <p>Can be used for toolkits that support substition with system properties
<add> * <p>Can be used for toolkits that support substitution with system properties
<ide> * (i.e. System.getProperty values), like log4j's "${key}" syntax within log
<ide> * file locations.
<ide> *
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/ResourceServlet.java
<ide> private void doInclude(HttpServletRequest request, HttpServletResponse response,
<ide> * to allow for message resolution etc that influences JSP contents,
<ide> * assuming that those background resources might have changed on restart.
<ide> * <p>Returns the startup time of this servlet if the file that corresponds
<del> * to the target resource URL coudln't be resolved (for example, because
<add> * to the target resource URL couldn't be resolved (for example, because
<ide> * the WAR is not expanded).
<ide> * @see #determineResourceUrl
<ide> * @see #getFileTimestamp
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerExceptionResolver.java
<ide> protected void logException(Exception ex, HttpServletRequest request) {
<ide> }
<ide>
<ide> /**
<del> * Build a log message for the given exception, occured during processing the given request.
<add> * Build a log message for the given exception, occurred during processing the given request.
<ide> * @param ex the exception that got thrown during handler execution
<ide> * @param request current HTTP request (useful for obtaining metadata)
<ide> * @return the log message to use
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
<ide> protected HttpInputMessage createHttpInputMessage(HttpServletRequest servletRequ
<ide> }
<ide>
<ide> /**
<del> * Template method for creating a new HttpOuputMessage instance.
<add> * Template method for creating a new HttpOutputMessage instance.
<ide> * <p>The default implementation creates a standard {@link ServletServerHttpResponse}.
<ide> * This can be overridden for custom {@code HttpOutputMessage} implementations
<ide> * @param servletResponse current HTTP response
<ide> public String bestMatchedPattern() {
<ide> * sorting a list with this comparator will result in:
<ide> * <ul>
<ide> * <li>RHIs with {@linkplain AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo#matchedPatterns better matched paths}
<del> * take prescedence over those with a weaker match (as expressed by the {@linkplain PathMatcher#getPatternComparator(String)
<add> * take precedence over those with a weaker match (as expressed by the {@linkplain PathMatcher#getPatternComparator(String)
<ide> * path pattern comparator}.) Typically, this means that patterns without wild cards and uri templates
<ide> * will be ordered before those without.</li>
<ide> * <li>RHIs with one single {@linkplain RequestMappingInfo#methods request method} will be
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java
<ide> public static ServletUriComponentsBuilder fromServletMapping(HttpServletRequest
<ide>
<ide> /**
<ide> * Prepare a builder from the host, port, scheme, and path of
<del> * an HttpSevletRequest.
<add> * an HttpServletRequest.
<ide> */
<ide> public static ServletUriComponentsBuilder fromRequestUri(HttpServletRequest request) {
<ide> ServletUriComponentsBuilder builder = fromRequest(request);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java
<ide> public void setAlwaysMustRevalidate(boolean mustRevalidate) {
<ide> }
<ide>
<ide> /**
<del> * Return whether 'must-revaliate' is added to every Cache-Control header.
<add> * Return whether 'must-revalidate' is added to every Cache-Control header.
<ide> */
<ide> public boolean isAlwaysMustRevalidate() {
<ide> return alwaysMustRevalidate;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/BeanNameViewResolver.java
<ide> * application beans - such a separation will make this clear.
<ide> *
<ide> * <p>This ViewResolver does not support internationalization.
<del> * Conside ResourceBundleViewResolver if you need to apply different
<add> * Consider ResourceBundleViewResolver if you need to apply different
<ide> * view resources per locale.
<ide> *
<ide> * <p>Note: This ViewResolver implements the Ordered interface to allow for
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
<ide> * with the view's {@linkplain View#getContentType() content type}). The most compatible view is returned.
<ide> *
<ide> * <p>Additionally, this view resolver exposes the {@link #setDefaultViews(List) defaultViews} property, allowing you to
<del> * override the views provided by the view resolvers. Note that these default views are offered as candicates, and
<add> * override the views provided by the view resolvers. Note that these default views are offered as candidates, and
<ide> * still need have the content type requested (via file extension, parameter, or {@code Accept} header, described above).
<ide> * You can also set the {@linkplain #setDefaultContentType(MediaType) default content type} directly, which will be
<ide> * returned when the other mechanisms ({@code Accept} header, file extension or parameter) do not result in a match.
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfStamperView.java
<ide> protected PdfReader readPdfResource() throws IOException {
<ide> * e.g. setting the "formFlattening" property.
<ide> * @param request in case we need locale etc. Shouldn't look at attributes.
<ide> * @param response in case we need to set cookies. Shouldn't write to it.
<del> * @throws Exception any exception that occured during document building
<add> * @throws Exception any exception that occurred during document building
<ide> */
<ide> protected abstract void mergePdfDocument(Map<String, Object> model, PdfStamper stamper,
<ide> HttpServletRequest request, HttpServletResponse response) throws Exception;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfView.java
<ide> protected void buildPdfMetadata(Map<String, Object> model, Document document, Ht
<ide> * @param writer the PdfWriter to use
<ide> * @param request in case we need locale etc. Shouldn't look at attributes.
<ide> * @param response in case we need to set cookies. Shouldn't write to it.
<del> * @throws Exception any exception that occured during document building
<add> * @throws Exception any exception that occurred during document building
<ide> * @see com.lowagie.text.Document#open()
<ide> * @see com.lowagie.text.Document#close()
<ide> */
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/feed/AbstractAtomFeedView.java
<ide> protected final void buildFeedEntries(Map<String, Object> model, Feed feed,
<ide> * @param request in case we need locale etc. Shouldn't look at attributes.
<ide> * @param response in case we need to set cookies. Shouldn't write to it.
<ide> * @return the feed entries to be added to the feed
<del> * @throws Exception any exception that occured during document building
<add> * @throws Exception any exception that occurred during document building
<ide> * @see Entry
<ide> */
<ide> protected abstract List<Entry> buildFeedEntries(
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/feed/AbstractFeedView.java
<ide> protected void buildFeedMetadata(Map<String, Object> model, T feed, HttpServletR
<ide> * @param feed the feed to add entries to
<ide> * @param request in case we need locale etc. Shouldn't look at attributes.
<ide> * @param response in case we need to set cookies. Shouldn't write to it.
<del> * @throws Exception any exception that occured during building
<add> * @throws Exception any exception that occurred during building
<ide> */
<ide> protected abstract void buildFeedEntries(Map<String, Object> model, T feed,
<ide> HttpServletRequest request, HttpServletResponse response) throws Exception;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/feed/AbstractRssFeedView.java
<ide> protected final void buildFeedEntries(Map<String, Object> model, Channel channel
<ide> * @param request in case we need locale etc. Shouldn't look at attributes.
<ide> * @param response in case we need to set cookies. Shouldn't write to it.
<ide> * @return the feed items to be added to the feed
<del> * @throws Exception any exception that occured during document building
<add> * @throws Exception any exception that occurred during document building
<ide> * @see Item
<ide> */
<ide> protected abstract List<Item> buildFeedItems(
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsView.java
<ide> public void setSubReportUrls(Properties subReports) {
<ide> * <p>The name specified in the list should correspond to an attribute in the
<ide> * model Map, and to a sub-report data source parameter in your report file.
<ide> * If you pass in {@code JRDataSource} objects as model attributes,
<del> * specifing this list of keys is not required.
<add> * specifying this list of keys is not required.
<ide> * <p>If you specify a list of sub-report data keys, it is required to also
<ide> * specify a {@code reportDataKey} for the main report, to avoid confusion
<ide> * between the data source objects for the various reports involved.
<ide> else if (filename.endsWith(".jrxml")) {
<ide> * {@link #renderReport} method that should be implemented by the subclass.
<ide> * @param model the model map, as passed in for view rendering. Must contain
<ide> * a report data value that can be converted to a {@code JRDataSource},
<del> * acccording to the rules of the {@link #fillReport} method.
<add> * according to the rules of the {@link #fillReport} method.
<ide> */
<ide> @Override
<ide> protected void renderMergedOutputModel(
<ide> protected void postProcessReport(JasperPrint populatedReport, Map<String, Object
<ide>
<ide> /**
<ide> * Subclasses should implement this method to perform the actual rendering process.
<del> * <p>Note that the content type has not been set yet: Implementors should build
<add> * <p>Note that the content type has not been set yet: Implementers should build
<ide> * a content type String and set it via {@code response.setContentType}.
<ide> * If necessary, this can include a charset clause for a specific encoding.
<ide> * The latter will only be necessary for textual output onto a Writer, and only
<ide> * in case of the encoding being specified in the JasperReports exporter parameters.
<del> * <p><b>WARNING:</b> Implementors should not use {@code response.setCharacterEncoding}
<add> * <p><b>WARNING:</b> Implementers should not use {@code response.setCharacterEncoding}
<ide> * unless they are willing to depend on Servlet API 2.4 or higher. Prefer a
<ide> * concatenated content type String with a charset clause instead.
<ide> * @param populatedReport the populated {@code JasperPrint} to render
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/velocity/VelocityToolboxView.java
<ide> public class VelocityToolboxView extends VelocityView {
<ide> * to automatically load a Velocity Tools toolbox definition file and expose
<ide> * all defined tools in the specified scopes. If no config location is
<ide> * specified, no toolbox will be loaded and exposed.
<del> * <p>The specfied location string needs to refer to a ServletContext
<add> * <p>The specified location string needs to refer to a ServletContext
<ide> * resource, as expected by ServletToolboxManager which is part of
<ide> * the view package of Velocity Tools.
<ide> * @see org.apache.velocity.tools.view.servlet.ServletToolboxManager#getInstance
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/velocity/VelocityViewResolver.java
<ide> public void setNumberToolAttribute(String numberToolAttribute) {
<ide> * to automatically load a Velocity Tools toolbox definition file and expose
<ide> * all defined tools in the specified scopes. If no config location is
<ide> * specified, no toolbox will be loaded and exposed.
<del> * <p>The specfied location string needs to refer to a ServletContext
<add> * <p>The specified location string needs to refer to a ServletContext
<ide> * resource, as expected by ServletToolboxManager which is part of
<ide> * the view package of Velocity Tools.
<ide> * <p><b>Note:</b> Specifying a toolbox config location will lead to
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java
<ide> protected Result createResult(HttpServletResponse response) throws Exception {
<ide> * an object of {@link #getSourceTypes() supported type}.
<ide> * @param model the merged model Map
<ide> * @return the XSLT Source object (or {@code null} if none found)
<del> * @throws Exception if an error occured during locating the source
<add> * @throws Exception if an error occurred during locating the source
<ide> * @see #setSourceKey
<ide> * @see #convertSource
<ide> */
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/endpoint/ServerEndpointRegistration.java
<ide> public ServerEndpointRegistration(String path, Class<? extends Endpoint> endpoin
<ide>
<ide> /**
<ide> * Create a new {@link ServerEndpointRegistration} instance from an
<del> * {@code javax.webscoket.Endpoint} instance.
<add> * {@code javax.websocket.Endpoint} instance.
<ide> * @param path the endpoint path
<ide> * @param endpoint the endpoint instance
<ide> */ | 37 |
Java | Java | get ripple drawables by id | c8ed2dbbb287deed05a8782fb8665c1edf45bbac | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.java
<ide> import android.os.Build;
<ide> import android.util.TypedValue;
<ide> import androidx.annotation.Nullable;
<add>
<ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.bridge.SoftAssertions;
<ide> public static Drawable createDrawableFromJSDescription(
<ide> String type = drawableDescriptionDict.getString("type");
<ide> if ("ThemeAttrAndroid".equals(type)) {
<ide> String attr = drawableDescriptionDict.getString("attribute");
<del> SoftAssertions.assertNotNull(attr);
<del> int attrID = context.getResources().getIdentifier(attr, "attr", "android");
<del> if (attrID == 0) {
<del> throw new JSApplicationIllegalArgumentException(
<del> "Attribute " + attr + " couldn't be found in the resource list");
<del> }
<del> if (!context.getTheme().resolveAttribute(attrID, sResolveOutValue, true)) {
<add> int attrId = getAttrId(context, attr);
<add> if (!context.getTheme().resolveAttribute(attrId, sResolveOutValue, true)) {
<ide> throw new JSApplicationIllegalArgumentException(
<del> "Attribute " + attr + " couldn't be resolved into a drawable");
<add> "Attribute " + attr + " with id " + attrId + " couldn't be resolved into a drawable");
<ide> }
<ide> Drawable drawable = getDefaultThemeDrawable(context);
<ide> return setRadius(drawableDescriptionDict, drawable);
<ide> public static Drawable createDrawableFromJSDescription(
<ide> }
<ide> }
<ide>
<add> @TargetApi(Build.VERSION_CODES.LOLLIPOP)
<add> private static int getAttrId(Context context, String attr) {
<add> SoftAssertions.assertNotNull(attr);
<add> if ("selectableItemBackground".equals(attr)) {
<add> return android.R.attr.selectableItemBackground;
<add> } else if ("selectableItemBackgroundBorderless".equals(attr)) {
<add> return android.R.attr.selectableItemBackgroundBorderless;
<add> } else {
<add> return context.getResources().getIdentifier(attr, "attr", "android");
<add> }
<add> }
<add>
<ide> private static Drawable getDefaultThemeDrawable(Context context) {
<ide> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
<ide> return context.getResources().getDrawable(sResolveOutValue.resourceId, context.getTheme()); | 1 |
Ruby | Ruby | remove stray ## | ccd1c21fe52a8183dc4470f08dd9c85f4b53afec | <ide><path>lib/active_job/enqueuing.rb
<ide>
<ide> module ActiveJob
<ide> module Enqueuing
<del> ##
<ide> # Push a job onto the queue. The arguments must be legal JSON types
<ide> # (string, int, float, nil, true, false, hash or array) or
<ide> # ActiveModel::GlobalIdentication instances. Arbitrary Ruby objects | 1 |
Text | Text | strengthen isbinarysearchtree test | 5f956e9a16b45186aa7f3ed8590c1d23ba997624 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/data-structures/check-if-binary-search-tree.md
<ide> In this challenge, you will create a utility for your tree. Write a JavaScript m
<ide> ```yml
<ide> tests:
<ide> - text: Your Binary Search Tree should return true when checked with <code>isBinarySearchTree()</code>.
<del> testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; test.push(3); test.push(4); test.push(5); return isBinarySearchTree(test) == true})());
<add> testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; test.push(1); test.push(5); test.push(3); test.push(2); test.push(4); return isBinarySearchTree(test) == true})());
<ide> ```
<ide>
<ide> </section> | 1 |
Python | Python | enable external api use when running cpychecker | 92fbc04cee0c1024bc76b95a3a33e5a54c9a1fb9 | <ide><path>numpy/core/code_generators/generate_numpy_api.py
<ide>
<ide> import numpy_api
<ide>
<add># use annotated api when running under cpychecker
<ide> h_template = r"""
<del>#ifdef _MULTIARRAYMODULE
<add>#if defined(_MULTIARRAYMODULE) || defined(WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE)
<ide>
<ide> typedef struct {
<ide> PyObject_HEAD | 1 |
Ruby | Ruby | assign plain metadata for now | 97aa328bb1e9d43bba1bcae2c8ddbaed397770c0 | <ide><path>lib/active_vault/blob.rb
<ide> def build_after_upload(io:, filename:, content_type: nil, metadata: nil)
<ide> new.tap do |blob|
<ide> blob.filename = filename
<ide> blob.content_type = content_type
<add> blob.metadata = metadata
<ide>
<ide> blob.upload io
<ide> end | 1 |
Text | Text | fix eventemitter#eventnames() example | c1f2df9782f76733b93ff6fcb590058f370eb826 | <ide><path>doc/api/events.md
<ide> myEE.on('bar', () => {});
<ide> const sym = Symbol('symbol');
<ide> myEE.on(sym, () => {});
<ide>
<del>console.log(myErr.eventNames());
<del> // Prints ['foo', 'bar', Symbol('symbol')]
<add>console.log(myEE.eventNames());
<add> // Prints [ 'foo', 'bar', Symbol(symbol) ]
<ide> ```
<ide>
<ide> ### emitter.getMaxListeners() | 1 |
Javascript | Javascript | fix validation test | 6023bb7a11de3db0c6ad542e9b75ee217b3a3a35 | <ide><path>test/Validation.test.js
<ide> describe("Validation", () => {
<ide> },
<ide> message: [
<ide> " - configuration.entry should be one of these:",
<del> " object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
<add> " function | object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]",
<ide> " -> The entry point(s) of the compilation.",
<ide> " Details:",
<add> " * configuration.entry should be an instance of function",
<add> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
<ide> " * configuration.entry should be an object.",
<ide> " -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
<ide> " * configuration.entry should not be empty.",
<ide> " -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
<ide> " * configuration.entry should be an array:",
<del> " [non-empty string]",
<del> " * configuration.entry should be an instance of function",
<del> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things."
<add> " [non-empty string]"
<ide> ]
<ide> },
<ide> {
<ide> describe("Validation", () => {
<ide> },
<ide> message: [
<ide> " - configuration.entry should be one of these:",
<del> " object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
<add> " function | object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]",
<ide> " -> The entry point(s) of the compilation.",
<ide> " Details:",
<add> " * configuration.entry should be an instance of function",
<add> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
<ide> " * configuration.entry['bundle'] should be a string.",
<ide> " -> The string is resolved to a module which is loaded upon startup.",
<ide> " * configuration.entry['bundle'] should not be empty.",
<ide> " * configuration.entry should be a string.",
<ide> " -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
<ide> " * configuration.entry should be an array:",
<del> " [non-empty string]",
<del> " * configuration.entry should be an instance of function",
<del> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things."
<add> " [non-empty string]"
<ide> ]
<ide> },
<ide> {
<ide> describe("Validation", () => {
<ide> },
<ide> message: [
<ide> " - configuration.entry should be one of these:",
<del> " object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
<add> " function | object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]",
<ide> " -> The entry point(s) of the compilation.",
<ide> " Details:",
<add> " * configuration.entry should be an instance of function",
<add> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
<ide> " * configuration.entry should be an object.",
<ide> " -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
<ide> " * configuration.entry should be a string.",
<ide> " -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
<del> " * configuration.entry should not contain the item 'abc' twice.",
<del> " * configuration.entry should be an instance of function",
<del> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things."
<add> " * configuration.entry should not contain the item 'abc' twice."
<ide> ]
<ide> },
<ide> {
<ide> describe("Validation", () => {
<ide> },
<ide> message: [
<ide> " - configuration.entry should be one of these:",
<del> " object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
<add> " function | object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]",
<ide> " -> The entry point(s) of the compilation.",
<ide> " Details:",
<add> " * configuration.entry should be an instance of function",
<add> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
<ide> " * configuration.entry should be an object.",
<ide> " -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
<ide> " * configuration.entry should be a string.",
<ide> " -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
<ide> " * configuration.entry[0] should be a string.",
<ide> " -> A non-empty string",
<del> " * configuration.entry should be an instance of function",
<del> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
<ide> " - configuration.output.filename should be one of these:",
<ide> " string | function",
<ide> " -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.",
<ide> describe("Validation", () => {
<ide> ],
<ide> message: [
<ide> " - configuration[0].entry should be one of these:",
<del> " object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
<add> " function | object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]",
<ide> " -> The entry point(s) of the compilation.",
<ide> " Details:",
<add> " * configuration[0].entry should be an instance of function",
<add> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
<ide> " * configuration[0].entry should be an object.",
<ide> " -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
<ide> " * configuration[0].entry should be a string.",
<ide> " -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
<ide> " * configuration[0].entry[0] should be a string.",
<ide> " -> A non-empty string",
<del> " * configuration[0].entry should be an instance of function",
<del> " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
<ide> " - configuration[1].output.filename should be one of these:",
<ide> " string | function",
<ide> " -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.",
<ide> describe("Validation", () => {
<ide> },
<ide> message: [
<ide> " - configuration.module.rules[0].oneOf[0] has an unknown property 'passer'. These properties are valid:",
<del> " object { enforce?, exclude?, include?, issuer?, loader?, loaders?, oneOf?, options?, parser?, resolve?, sideEffects?, query?, type?, resource?, resourceQuery?, compiler?, rules?, test?, use? }",
<add> " object { compiler?, enforce?, exclude?, include?, issuer?, loader?, loaders?, oneOf?, options?, parser?, query?, resolve?, resource?, resourceQuery?, rules?, sideEffects?, test?, type?, use? }",
<ide> " -> A rule"
<ide> ]
<ide> },
<ide> describe("Validation", () => {
<ide> },
<ide> message: [
<ide> " - configuration has an unknown property 'postcss'. These properties are valid:",
<del> " object { mode?, amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, externals?, " +
<del> "loader?, module?, name?, node?, output?, optimization?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, " +
<del> "recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, serve?, stats?, target?, watch?, watchOptions? }",
<add> " object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, externals?, loader?, mode?, module?, " +
<add> "name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, " +
<add> "recordsPath?, resolve?, resolveLoader?, serve?, stats?, target?, watch?, watchOptions? }",
<ide> " For typos: please correct them.",
<ide> " For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.",
<ide> " Loaders should be updated to allow passing options via loader options in module.rules.", | 1 |
Go | Go | remove hardcoded error | 8b02d85e1728b48729b2fb8553b2ec4b56a30d37 | <ide><path>builder/evaluator.go
<ide> package builder
<ide>
<ide> import (
<del> "errors"
<ide> "fmt"
<ide> "io"
<ide> "os"
<ide> import (
<ide> "github.com/docker/docker/utils"
<ide> )
<ide>
<del>var (
<del> ErrDockerfileEmpty = errors.New("Dockerfile cannot be empty")
<del>)
<del>
<ide> // Environment variable interpolation will happen on these statements only.
<ide> var replaceEnvAllowed = map[string]struct{}{
<ide> command.Env: {},
<ide> func (b *Builder) readDockerfile() error {
<ide> return fmt.Errorf("Cannot locate specified Dockerfile: %s", origFile)
<ide> }
<ide> if fi.Size() == 0 {
<del> return ErrDockerfileEmpty
<add> return fmt.Errorf("The Dockerfile (%s) cannot be empty", origFile)
<ide> }
<ide>
<ide> f, err := os.Open(filename)
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func TestBuildFailsDockerfileEmpty(t *testing.T) {
<ide> defer deleteImages(name)
<ide> _, err := buildImage(name, ``, true)
<ide> if err != nil {
<del> if !strings.Contains(err.Error(), "Dockerfile cannot be empty") {
<add> if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") {
<ide> t.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
<ide> }
<ide> } else { | 2 |
Text | Text | add reference to docker-reg-client | 48354301659d870bd23e643c6e916a5a652ae93c | <ide><path>docs/sources/reference/api/registry_api_client_libraries.md
<ide> page_keywords: API, Docker, index, registry, REST, documentation, clients, C#, E
<ide>
<ide> These libraries have not been tested by the Docker maintainers for
<ide> compatibility. Please file issues with the library owners. If you find
<del>more library implementations, please list them in Docker doc bugs and we
<del>will add the libraries here.
<add>more library implementations, please submit a PR with an update to this page
<add>or open an issue in the [Docker](https://github.com/docker/docker/issues)
<add>project and we will add the libraries here.
<ide>
<ide>
<ide> <table border="1" class="docutils">
<ide> will add the libraries here.
<ide> <td><a class="reference external" href="https://github.com/kwk/docker-registry-frontend">https://github.com/kwk/docker-registry-frontend</a></td>
<ide> <td>Active</td>
<ide> </tr>
<add> <tr class="row-odd">
<add> <td>Go</td>
<add> <td>docker-reg-client</td>
<add> <td><a class="reference external" href="https://github.com/CenturyLinkLabs/docker-reg-client">https://github.com/CenturyLinkLabs/docker-reg-client</a></td>
<add> <td>Active</td>
<add> </tr>
<ide> </tbody>
<ide> </table> | 1 |
Text | Text | improve changelog entries in ar | 01e67316d8c802df3928b53d0e0ce9153044f5ad | <ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<del>* Change behaviour with empty array in where clause,
<del> the SQL generated when when were passed an empty array was insecure in some cases
<add>* Raise `ArgumentError` instead of generating `column IN (NULL)` SQL when
<add> empty array is used in where clause value.
<ide>
<del> Roberto Miranda
<add> *Roberto Miranda*
<ide>
<del>* Raise ArgumentError instead of generate invalid SQL when empty hash is used in where clause value
<add>* Raise `ArgumentError` instead of generating invalid SQL when empty hash is
<add> used in where clause value.
<ide>
<del> Roberto Miranda
<add> *Roberto Miranda*
<ide>
<ide> * Quote numeric values being compared to non-numeric columns. Otherwise,
<ide> in some database, the string column values will be coerced to a numeric | 1 |
Text | Text | add visual studio 2010 sp1 download url | 124c517056279ba8ae76756391b9d8a146ae1567 | <ide><path>docs/build-instructions/windows.md
<ide> ## Requirements
<ide>
<ide> * Windows 7 or later
<del> * [Visual C++ 2010 SP1 Express](http://www.visualstudio.com/en-us/downloads/download-visual-studio-vs#DownloadFamilies_4)
<add> * [Visual C++ 2010 Express](http://www.visualstudio.com/en-us/downloads/download-visual-studio-vs#DownloadFamilies_4) and [SP1](http://www.microsoft.com/en-us/download/details.aspx?id=23691)
<ide> * [node.js - 32bit](http://nodejs.org/download/) v0.10.x
<ide> * [Python 2.7.x](http://www.python.org/download/)
<ide> * [GitHub for Windows](http://windows.github.com/) | 1 |
Javascript | Javascript | prefer require.cache over native module cache | e27418ca3f1f4700a457145de899c0d67343ee77 | <ide><path>src/node.js
<ide> var id = resolved[0];
<ide> var filename = resolved[1];
<ide>
<add> var cachedModule = moduleCache[filename];
<add> if (cachedModule) return cachedModule.exports;
<add>
<ide> // With natives id === request
<ide> // We deal with these first
<ide> if (natives[id]) {
<ide> return requireNative(id);
<ide> }
<ide>
<del> var cachedModule = moduleCache[filename];
<del> if (cachedModule) return cachedModule.exports;
<del>
<ide> var module = new Module(id, parent);
<ide> moduleCache[filename] = module;
<ide> module.load(filename);
<ide><path>test/simple/test-require-cache.js
<add>var common = require('../common');
<add>var assert = require('assert');
<add>
<add>(function testInjectFakeModule() {
<add> var relativePath = '../fixtures/semicolon';
<add> var absolutePath = require.resolve(relativePath);
<add> var fakeModule = {};
<add>
<add> require.cache[absolutePath] = {exports: fakeModule};
<add>
<add> assert.strictEqual(require(relativePath), fakeModule);
<add>})();
<add>
<add>
<add>(function testInjectFakeNativeModule() {
<add> var relativePath = 'fs';
<add> var fakeModule = {};
<add>
<add> require.cache[relativePath] = {exports: fakeModule};
<add>
<add> assert.strictEqual(require(relativePath), fakeModule);
<add>})(); | 2 |
Java | Java | introduce dedicated 'cache' subpackage in the tcf | 5cbe4b948d15fceb98ba2800d7309a632db163d6 | <ide><path>spring-test/src/main/java/org/springframework/test/context/BootstrapUtils.java
<ide> abstract class BootstrapUtils {
<ide>
<ide> private static final String DEFAULT_BOOTSTRAP_CONTEXT_CLASS_NAME = "org.springframework.test.context.support.DefaultBootstrapContext";
<ide>
<del> private static final String DEFAULT_CACHE_AWARE_CONTEXT_LOADER_DELEGATE_CLASS_NAME = "org.springframework.test.context.support.DefaultCacheAwareContextLoaderDelegate";
<add> private static final String DEFAULT_CACHE_AWARE_CONTEXT_LOADER_DELEGATE_CLASS_NAME = "org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate";
<ide>
<ide> private static final String DEFAULT_TEST_CONTEXT_BOOTSTRAPPER_CLASS_NAME = "org.springframework.test.context.support.DefaultTestContextBootstrapper";
<ide>
<ide> private BootstrapUtils() {
<ide> * Create the {@code BootstrapContext} for the specified {@linkplain Class test class}.
<ide> *
<ide> * <p>Uses reflection to create a {@link org.springframework.test.context.support.DefaultBootstrapContext}
<del> * that uses a {@link org.springframework.test.context.support.DefaultCacheAwareContextLoaderDelegate}.
<add> * that uses a {@link org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate}.
<ide> *
<ide> * @param testClass the test class for which the bootstrap context should be created
<ide> * @return a new {@code BootstrapContext}; never {@code null}
<ide><path>spring-test/src/main/java/org/springframework/test/context/CacheAwareContextLoaderDelegate.java
<ide> /**
<ide> * A {@code CacheAwareContextLoaderDelegate} is responsible for {@linkplain
<ide> * #loadContext loading} and {@linkplain #closeContext closing} application
<del> * contexts, interacting transparently with a {@link ContextCache} behind
<del> * the scenes.
<add> * contexts, interacting transparently with a
<add> * {@link org.springframework.test.context.cache.ContextCache ContextCache}
<add> * behind the scenes.
<ide> *
<ide> * <p>Note: {@code CacheAwareContextLoaderDelegate} does not extend the
<ide> * {@link ContextLoader} or {@link SmartContextLoader} interface.
<ide> public interface CacheAwareContextLoaderDelegate {
<ide> * <p>If the context is present in the {@code ContextCache} it will simply
<ide> * be returned; otherwise, it will be loaded, stored in the cache, and returned.
<ide> * <p>The cache statistics should be logged by invoking
<del> * {@link ContextCache#logStatistics()}.
<add> * {@link org.springframework.test.context.cache.ContextCache#logStatistics()}.
<ide> * @param mergedContextConfiguration the merged context configuration to use
<ide> * to load the application context; never {@code null}
<ide> * @return the application context
<add><path>spring-test/src/main/java/org/springframework/test/context/cache/ContextCache.java
<del><path>spring-test/src/main/java/org/springframework/test/context/ContextCache.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.test.context;
<add>package org.springframework.test.context.cache;
<ide>
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.test.annotation.DirtiesContext.HierarchyMode;
<add>import org.springframework.test.context.MergedContextConfiguration;
<ide>
<ide> /**
<ide> * {@code ContextCache} defines the SPI for caching Spring
<add><path>spring-test/src/main/java/org/springframework/test/context/cache/DefaultCacheAwareContextLoaderDelegate.java
<del><path>spring-test/src/main/java/org/springframework/test/context/support/DefaultCacheAwareContextLoaderDelegate.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.test.context.support;
<add>package org.springframework.test.context.cache;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.test.annotation.DirtiesContext.HierarchyMode;
<ide> import org.springframework.test.context.CacheAwareContextLoaderDelegate;
<del>import org.springframework.test.context.ContextCache;
<ide> import org.springframework.test.context.ContextLoader;
<ide> import org.springframework.test.context.MergedContextConfiguration;
<ide> import org.springframework.test.context.SmartContextLoader;
<add><path>spring-test/src/main/java/org/springframework/test/context/cache/DefaultContextCache.java
<del><path>spring-test/src/main/java/org/springframework/test/context/support/DefaultContextCache.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.test.context.support;
<add>package org.springframework.test.context.cache;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.HashSet;
<ide> import org.springframework.context.ConfigurableApplicationContext;
<ide> import org.springframework.core.style.ToStringCreator;
<ide> import org.springframework.test.annotation.DirtiesContext.HierarchyMode;
<del>import org.springframework.test.context.ContextCache;
<ide> import org.springframework.test.context.MergedContextConfiguration;
<ide> import org.springframework.util.Assert;
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/AbstractTestContextBootstrapper.java
<ide> import org.springframework.core.io.support.SpringFactoriesLoader;
<ide> import org.springframework.test.context.BootstrapContext;
<ide> import org.springframework.test.context.CacheAwareContextLoaderDelegate;
<del>import org.springframework.test.context.ContextCache;
<ide> import org.springframework.test.context.ContextConfiguration;
<ide> import org.springframework.test.context.ContextConfigurationAttributes;
<ide> import org.springframework.test.context.ContextHierarchy;
<ide> * <li>{@link #processMergedContextConfiguration}
<ide> * </ul>
<ide> *
<del> * <p>To plug in custom {@link ContextCache} support, override
<del> * {@link #getCacheAwareContextLoaderDelegate()}.
<add> * <p>To plug in custom
<add> * {@link org.springframework.test.context.cache.ContextCache ContextCache}
<add> * support, override {@link #getCacheAwareContextLoaderDelegate()}.
<ide> *
<ide> * @author Sam Brannen
<ide> * @author Juergen Hoeller
<ide> protected Class<? extends ContextLoader> resolveExplicitContextLoaderClass(
<ide> * <p>The default implementation simply delegates to
<ide> * {@code getBootstrapContext().getCacheAwareContextLoaderDelegate()}.
<ide> * <p>Concrete subclasses may choose to override this method to return a
<del> * custom {@code CacheAwareContextLoaderDelegate} implementation with
<del> * custom {@link ContextCache} support.
<add> * custom {@code CacheAwareContextLoaderDelegate} implementation with custom
<add> * {@link org.springframework.test.context.cache.ContextCache ContextCache}
<add> * support.
<ide> * @return the context loader delegate (never {@code null})
<ide> */
<ide> protected CacheAwareContextLoaderDelegate getCacheAwareContextLoaderDelegate() {
<ide><path>spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * Unit tests for {@link MergedContextConfiguration}.
<ide> *
<ide> * <p>These tests primarily exist to ensure that {@code MergedContextConfiguration}
<del> * can safely be used as the cache key for {@link ContextCache}.
<add> * can safely be used as the cache key for
<add> * {@link org.springframework.test.context.cache.ContextCache ContextCache}.
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 3.1
<ide><path>spring-test/src/test/java/org/springframework/test/context/TestContextTestUtils.java
<ide>
<ide> package org.springframework.test.context;
<ide>
<add>import org.springframework.test.context.cache.ContextCache;
<add>import org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate;
<ide> import org.springframework.test.context.support.DefaultBootstrapContext;
<del>import org.springframework.test.context.support.DefaultCacheAwareContextLoaderDelegate;
<ide>
<ide> /**
<ide> * Collection of test-related utility methods for working with {@link TestContext TestContexts}.
<add><path>spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTestNGTests.java
<del><path>spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTestNGTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.test.context;
<add>package org.springframework.test.context.cache;
<ide>
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.test.annotation.DirtiesContext;
<ide> import org.springframework.test.annotation.DirtiesContext.ClassMode;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.TestExecutionListeners;
<ide> import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
<ide> import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
<ide> import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
<ide> import org.testng.TestNG;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.springframework.test.context.support.ContextCacheTestUtils.*;
<add>import static org.springframework.test.context.cache.ContextCacheTestUtils.*;
<ide>
<ide> /**
<ide> * JUnit 4 based integration test which verifies correct {@linkplain ContextCache
<add><path>spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTests.java
<del><path>spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.test.context;
<add>package org.springframework.test.context.cache;
<ide>
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.test.annotation.DirtiesContext;
<ide> import org.springframework.test.annotation.DirtiesContext.ClassMode;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.TestExecutionListeners;
<ide> import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<ide> import org.springframework.test.context.junit4.TrackingRunListener;
<ide> import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
<ide> import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.springframework.test.context.support.ContextCacheTestUtils.*;
<add>import static org.springframework.test.context.cache.ContextCacheTestUtils.*;
<ide>
<ide> /**
<ide> * JUnit 4 based integration test which verifies correct {@linkplain ContextCache
<add><path>spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTestUtils.java
<del><path>spring-test/src/test/java/org/springframework/test/context/support/ContextCacheTestUtils.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.test.context.support;
<del>
<del>import org.springframework.test.context.ContextCache;
<add>package org.springframework.test.context.cache;
<ide>
<ide> import static org.junit.Assert.*;
<ide>
<add><path>spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTests.java
<del><path>spring-test/src/test/java/org/springframework/test/context/ContextCacheTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.test.context;
<add>package org.springframework.test.context.cache;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.test.annotation.DirtiesContext.HierarchyMode;
<add>import org.springframework.test.context.ActiveProfiles;
<add>import org.springframework.test.context.ActiveProfilesResolver;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.ContextHierarchy;
<add>import org.springframework.test.context.MergedContextConfiguration;
<add>import org.springframework.test.context.TestContext;
<add>import org.springframework.test.context.TestContextTestUtils;
<ide> import org.springframework.test.context.support.AnnotationConfigContextLoader;
<del>import org.springframework.test.context.support.DefaultContextCache;
<ide> import org.springframework.test.util.ReflectionTestUtils;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.springframework.test.context.support.ContextCacheTestUtils.*;
<add>import static org.springframework.test.context.cache.ContextCacheTestUtils.*;
<ide>
<ide> /**
<ide> * Integration tests for verifying proper behavior of the {@link ContextCache} in
<add><path>spring-test/src/test/java/org/springframework/test/context/cache/SpringRunnerContextCacheTests.java
<del><path>spring-test/src/test/java/org/springframework/test/context/SpringRunnerContextCacheTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.test.context;
<add>package org.springframework.test.context.cache;
<ide>
<ide> import org.junit.AfterClass;
<ide> import org.junit.BeforeClass;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.test.annotation.DirtiesContext;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.TestExecutionListeners;
<ide> import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<ide> import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
<ide> import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.springframework.test.context.support.ContextCacheTestUtils.*;
<add>import static org.springframework.test.context.cache.ContextCacheTestUtils.*;
<ide>
<ide> /**
<ide> * JUnit 4 based unit test which verifies correct {@link ContextCache
<ide> @RunWith(SpringJUnit4ClassRunner.class)
<ide> @FixMethodOrder(MethodSorters.NAME_ASCENDING)
<ide> @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class })
<del>@ContextConfiguration("junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml")
<add>@ContextConfiguration("../junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml")
<ide> public class SpringRunnerContextCacheTests {
<ide>
<ide> private static ApplicationContext dirtiedApplicationContext;
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4TestSuite.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.junit.runner.RunWith;
<ide> import org.junit.runners.Suite;
<ide> import org.junit.runners.Suite.SuiteClasses;
<del>
<del>import org.springframework.test.context.ClassLevelDirtiesContextTests;
<del>import org.springframework.test.context.SpringRunnerContextCacheTests;
<add>import org.springframework.test.context.cache.ClassLevelDirtiesContextTests;
<add>import org.springframework.test.context.cache.SpringRunnerContextCacheTests;
<ide> import org.springframework.test.context.junit4.annotation.AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests;
<ide> import org.springframework.test.context.junit4.annotation.BeanOverridingDefaultConfigClassesInheritedTests;
<ide> import org.springframework.test.context.junit4.annotation.BeanOverridingExplicitConfigClassesInheritedTests; | 14 |
Javascript | Javascript | use smart scrolling | 403f150ade08082c6d2bc5a5104e59e045fe8189 | <ide><path>src/devtools/views/Components/Tree.js
<ide> export default function Tree(props: Props) {
<ide> // This is helpful for things like the owners list and search.
<ide> useLayoutEffect(() => {
<ide> if (selectedElementIndex !== null && listRef.current != null) {
<del> listRef.current.scrollToItem(selectedElementIndex);
<add> listRef.current.scrollToItem(selectedElementIndex, 'smart');
<ide> // Note this autoscroll only works for rows.
<ide> // There's another autoscroll inside the elements
<ide> // that ensures the component name is visible horizontally. | 1 |
PHP | PHP | add use exception | 2edeb3ac8d840d26948df7f1a4362d11f0fb11a2 | <ide><path>tests/Integration/Cache/RedisCacheLockTest.php
<ide>
<ide> namespace Illuminate\Tests\Integration\Cache;
<ide>
<add>use Exception;
<ide> use Illuminate\Support\Carbon;
<ide> use Orchestra\Testbench\TestCase;
<ide> use Illuminate\Support\Facades\Cache;
<ide> public function test_redis_locks_with_failed_block_callback_are_released()
<ide>
<ide> try {
<ide> $firstLock->block(1, function () {
<del> throw new \Exception('failed');
<add> throw new Exception('failed');
<ide> });
<del> } catch (\Exception $e) {
<add> } catch (Exception $e) {
<ide> // Not testing the exception, just testing the lock
<ide> // is released regardless of the how the exception
<ide> // thrown by the callback was handled. | 1 |
Javascript | Javascript | add support for disabling an option | da9eac8660343b1cd9fdcf9d2d1bda06067142d7 | <ide><path>src/ng/directive/ngOptions.js
<ide> var ngOptionsMinErr = minErr('ngOptions');
<ide> * * `label` **`for`** `value` **`in`** `array`
<ide> * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
<ide> * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
<add> * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
<ide> * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
<add> * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
<ide> * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
<ide> * (for including a filter with `track by`)
<ide> * * for object data sources:
<ide> * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
<ide> * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
<ide> * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
<add> * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
<ide> * * `select` **`as`** `label` **`group by`** `group`
<ide> * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
<add> * * `select` **`as`** `label` **`disable when`** `disable`
<add> * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
<ide> *
<ide> * Where:
<ide> *
<ide> var ngOptionsMinErr = minErr('ngOptions');
<ide> * element. If not specified, `select` expression will default to `value`.
<ide> * * `group`: The result of this expression will be used to group options using the `<optgroup>`
<ide> * DOM element.
<add> * * `disable`: The result of this expression will be used to disable the rendered `<option>`
<add> * element. Return `true` to disable.
<ide> * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
<ide> * used to identify the objects in the array. The `trackexpr` will most likely refer to the
<ide> * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
<ide> var ngOptionsMinErr = minErr('ngOptions');
<ide> .controller('ExampleController', ['$scope', function($scope) {
<ide> $scope.colors = [
<ide> {name:'black', shade:'dark'},
<del> {name:'white', shade:'light'},
<add> {name:'white', shade:'light', notAnOption: true},
<ide> {name:'red', shade:'dark'},
<del> {name:'blue', shade:'dark'},
<del> {name:'yellow', shade:'light'}
<add> {name:'blue', shade:'dark', notAnOption: true},
<add> {name:'yellow', shade:'light', notAnOption: false}
<ide> ];
<ide> $scope.myColor = $scope.colors[2]; // red
<ide> }]);
<ide> var ngOptionsMinErr = minErr('ngOptions');
<ide> <ul>
<ide> <li ng-repeat="color in colors">
<ide> Name: <input ng-model="color.name">
<add> <input type="checkbox" ng-model="color.notAnOption"> Disabled?
<ide> [<a href ng-click="colors.splice($index, 1)">X</a>]
<ide> </li>
<ide> <li>
<ide> var ngOptionsMinErr = minErr('ngOptions');
<ide> <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
<ide> </select><br/>
<ide>
<add> Color grouped by shade, with some disabled:
<add> <select ng-model="myColor"
<add> ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
<add> </select><br/>
<add>
<add>
<ide>
<ide> Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
<ide> <hr/>
<ide> var ngOptionsMinErr = minErr('ngOptions');
<ide> */
<ide>
<ide> // jshint maxlen: false
<del> //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
<del>var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
<add>// //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
<add>var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
<ide> // 1: value expression (valueFn)
<ide> // 2: label expression (displayFn)
<ide> // 3: group by expression (groupByFn)
<del> // 4: array item variable name
<del> // 5: object item key variable name
<del> // 6: object item value variable name
<del> // 7: collection expression
<del> // 8: track by expression
<add> // 4: disable when expression (disableWhenFn)
<add> // 5: array item variable name
<add> // 6: object item key variable name
<add> // 7: object item value variable name
<add> // 8: collection expression
<add> // 9: track by expression
<ide> // jshint maxlen: 100
<ide>
<ide>
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> // Extract the parts from the ngOptions expression
<ide>
<ide> // The variable name for the value of the item in the collection
<del> var valueName = match[4] || match[6];
<add> var valueName = match[5] || match[7];
<ide> // The variable name for the key of the item in the collection
<del> var keyName = match[5];
<add> var keyName = match[6];
<ide>
<ide> // An expression that generates the viewValue for an option if there is a label expression
<ide> var selectAs = / as /.test(match[0]) && match[1];
<ide> // An expression that is used to track the id of each object in the options collection
<del> var trackBy = match[8];
<add> var trackBy = match[9];
<ide> // An expression that generates the viewValue for an option if there is no label expression
<ide> var valueFn = $parse(match[2] ? match[1] : valueName);
<ide> var selectAsFn = selectAs && $parse(selectAs);
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> function getHashOfValue(viewValue) { return hashKey(viewValue); };
<ide> var displayFn = $parse(match[2] || match[1]);
<ide> var groupByFn = $parse(match[3] || '');
<del> var valuesFn = $parse(match[7]);
<add> var disableWhenFn = $parse(match[4] || '');
<add> var valuesFn = $parse(match[8]);
<ide>
<ide> var locals = {};
<ide> var getLocals = keyName ? function(value, key) {
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> };
<ide>
<ide>
<del> function Option(selectValue, viewValue, label, group) {
<add> function Option(selectValue, viewValue, label, group, disabled) {
<ide> this.selectValue = selectValue;
<ide> this.viewValue = viewValue;
<ide> this.label = label;
<ide> this.group = group;
<add> this.disabled = disabled;
<ide> }
<ide>
<ide> return {
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> var label = displayFn(scope, locals);
<ide> watchedArray.push(label);
<ide> }
<add>
<add> // Only need to watch the disableWhenFn if there is a specific disable expression
<add> if (match[4]) {
<add> var disableWhen = disableWhenFn(scope, locals);
<add> watchedArray.push(disableWhen);
<add> }
<ide> });
<ide> return watchedArray;
<ide> }),
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> var selectValue = getTrackByValue(viewValue, locals);
<ide> var label = displayFn(scope, locals);
<ide> var group = groupByFn(scope, locals);
<del> var optionItem = new Option(selectValue, viewValue, label, group);
<add> var disabled = disableWhenFn(scope, locals);
<add> var optionItem = new Option(selectValue, viewValue, label, group, disabled);
<ide>
<ide> optionItems.push(optionItem);
<ide> selectValueMap[selectValue] = optionItem;
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> return {
<ide> restrict: 'A',
<ide> terminal: true,
<del> require: ['select', '?ngModel'],
<add> require: ['select', 'ngModel'],
<ide> link: function(scope, selectElement, attr, ctrls) {
<ide>
<ide> // if ngModel is not defined, we don't need to do anything
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> selectCtrl.writeValue = function writeNgOptionsValue(value) {
<ide> var option = options.getOptionFromViewValue(value);
<ide>
<del> if (option) {
<add> if (option && !option.disabled) {
<ide> if (selectElement[0].value !== option.selectValue) {
<ide> removeUnknownOption();
<ide> removeEmptyOption();
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide>
<ide> var selectedOption = options.selectValueMap[selectElement.val()];
<ide>
<del> if (selectedOption) {
<add> if (selectedOption && !selectedOption.disabled) {
<ide> removeEmptyOption();
<ide> removeUnknownOption();
<ide> return selectedOption.viewValue;
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> if (value) {
<ide> value.forEach(function(item) {
<ide> var option = options.getOptionFromViewValue(item);
<del> if (option) option.element.selected = true;
<add> if (option && !option.disabled) option.element.selected = true;
<ide> });
<ide> }
<ide> };
<ide>
<ide>
<ide> selectCtrl.readValue = function readNgOptionsMultiple() {
<del> var selectedValues = selectElement.val() || [];
<del> return selectedValues.map(function(selectedKey) {
<del> var option = options.selectValueMap[selectedKey];
<del> return option.viewValue;
<add> var selectedValues = selectElement.val() || [],
<add> selections = [];
<add>
<add> forEach(selectedValues, function(value) {
<add> var option = options.selectValueMap[value];
<add> if (!option.disabled) selections.push(option.viewValue);
<ide> });
<add>
<add> return selections;
<ide> };
<ide> }
<ide>
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide>
<ide> function updateOptionElement(option, element) {
<ide> option.element = element;
<add> element.disabled = option.disabled;
<ide> if (option.value !== element.value) element.value = option.selectValue;
<ide> if (option.label !== element.label) {
<ide> element.label = option.label;
<ide><path>test/ng/directive/ngOptionsSpec.js
<ide> describe('ngOptions', function() {
<ide> });
<ide>
<ide>
<add> describe('disableWhen expression', function() {
<add>
<add> describe('on single select', function() {
<add>
<add> it('should disable options', function() {
<add>
<add> scope.selected = '';
<add> scope.options = [
<add> { name: 'white', value: '#FFFFFF' },
<add> { name: 'one', value: 1, unavailable: true },
<add> { name: 'notTrue', value: false },
<add> { name: 'thirty', value: 30, unavailable: false }
<add> ];
<add> createSelect({
<add> 'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
<add> 'ng-model': 'selected'
<add> });
<add> var options = element.find('option');
<add>
<add> expect(options.length).toEqual(5);
<add> expect(options.eq(1).prop('disabled')).toEqual(false);
<add> expect(options.eq(2).prop('disabled')).toEqual(true);
<add> expect(options.eq(3).prop('disabled')).toEqual(false);
<add> expect(options.eq(4).prop('disabled')).toEqual(false);
<add> });
<add>
<add>
<add> it('should not select disabled options when model changes', function() {
<add> scope.options = [
<add> { name: 'white', value: '#FFFFFF' },
<add> { name: 'one', value: 1, unavailable: true },
<add> { name: 'notTrue', value: false },
<add> { name: 'thirty', value: 30, unavailable: false }
<add> ];
<add> createSelect({
<add> 'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
<add> 'ng-model': 'selected'
<add> });
<add>
<add> // Initially the model is set to an enabled option
<add> scope.$apply('selected = 30');
<add> var options = element.find('option');
<add> expect(options.eq(3).prop('selected')).toEqual(true);
<add>
<add> // Now set the model to a disabled option
<add> scope.$apply('selected = 1');
<add> options = element.find('option');
<add>
<add> expect(element.val()).toEqualUnknownValue('?');
<add> expect(options.length).toEqual(5);
<add> expect(options.eq(0).prop('selected')).toEqual(true);
<add> expect(options.eq(2).prop('selected')).toEqual(false);
<add> expect(options.eq(4).prop('selected')).toEqual(false);
<add> });
<add>
<add>
<add> it('should select options in model when they become enabled', function() {
<add> scope.options = [
<add> { name: 'white', value: '#FFFFFF' },
<add> { name: 'one', value: 1, unavailable: true },
<add> { name: 'notTrue', value: false },
<add> { name: 'thirty', value: 30, unavailable: false }
<add> ];
<add> createSelect({
<add> 'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
<add> 'ng-model': 'selected'
<add> });
<add>
<add> // Set the model to a disabled option
<add> scope.$apply('selected = 1');
<add> var options = element.find('option');
<add>
<add> expect(element.val()).toEqualUnknownValue('?');
<add> expect(options.length).toEqual(5);
<add> expect(options.eq(0).prop('selected')).toEqual(true);
<add> expect(options.eq(2).prop('selected')).toEqual(false);
<add> expect(options.eq(4).prop('selected')).toEqual(false);
<add>
<add> // Now enable that option
<add> scope.$apply(function() {
<add> scope.options[1].unavailable = false;
<add> });
<add>
<add> expect(element).toEqualSelectValue(1);
<add> options = element.find('option');
<add> expect(options.length).toEqual(4);
<add> expect(options.eq(1).prop('selected')).toEqual(true);
<add> expect(options.eq(3).prop('selected')).toEqual(false);
<add> });
<add> });
<add>
<add>
<add> describe('on multi select', function() {
<add>
<add> it('should disable options', function() {
<add>
<add> scope.selected = [];
<add> scope.options = [
<add> { name: 'a', value: 0 },
<add> { name: 'b', value: 1, unavailable: true },
<add> { name: 'c', value: 2 },
<add> { name: 'd', value: 3, unavailable: false }
<add> ];
<add> createSelect({
<add> 'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
<add> 'multiple': true,
<add> 'ng-model': 'selected'
<add> });
<add> var options = element.find('option');
<add>
<add> expect(options.eq(0).prop('disabled')).toEqual(false);
<add> expect(options.eq(1).prop('disabled')).toEqual(true);
<add> expect(options.eq(2).prop('disabled')).toEqual(false);
<add> expect(options.eq(3).prop('disabled')).toEqual(false);
<add> });
<add>
<add>
<add> it('should not select disabled options when model changes', function() {
<add> scope.options = [
<add> { name: 'a', value: 0 },
<add> { name: 'b', value: 1, unavailable: true },
<add> { name: 'c', value: 2 },
<add> { name: 'd', value: 3, unavailable: false }
<add> ];
<add> createSelect({
<add> 'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
<add> 'multiple': true,
<add> 'ng-model': 'selected'
<add> });
<add>
<add> // Initially the model is set to an enabled option
<add> scope.$apply('selected = [3]');
<add> var options = element.find('option');
<add> expect(options.eq(0).prop('selected')).toEqual(false);
<add> expect(options.eq(1).prop('selected')).toEqual(false);
<add> expect(options.eq(2).prop('selected')).toEqual(false);
<add> expect(options.eq(3).prop('selected')).toEqual(true);
<add>
<add> // Now add a disabled option
<add> scope.$apply('selected = [1,3]');
<add> options = element.find('option');
<add> expect(options.eq(0).prop('selected')).toEqual(false);
<add> expect(options.eq(1).prop('selected')).toEqual(false);
<add> expect(options.eq(2).prop('selected')).toEqual(false);
<add> expect(options.eq(3).prop('selected')).toEqual(true);
<add>
<add> // Now only select the disabled option
<add> scope.$apply('selected = [1]');
<add> expect(options.eq(0).prop('selected')).toEqual(false);
<add> expect(options.eq(1).prop('selected')).toEqual(false);
<add> expect(options.eq(2).prop('selected')).toEqual(false);
<add> expect(options.eq(3).prop('selected')).toEqual(false);
<add> });
<add>
<add>
<add> it('should select options in model when they become enabled', function() {
<add> scope.options = [
<add> { name: 'a', value: 0 },
<add> { name: 'b', value: 1, unavailable: true },
<add> { name: 'c', value: 2 },
<add> { name: 'd', value: 3, unavailable: false }
<add> ];
<add> createSelect({
<add> 'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
<add> 'multiple': true,
<add> 'ng-model': 'selected'
<add> });
<add>
<add> // Set the model to a disabled option
<add> scope.$apply('selected = [1]');
<add> var options = element.find('option');
<add>
<add> expect(options.eq(0).prop('selected')).toEqual(false);
<add> expect(options.eq(1).prop('selected')).toEqual(false);
<add> expect(options.eq(2).prop('selected')).toEqual(false);
<add> expect(options.eq(3).prop('selected')).toEqual(false);
<add>
<add> // Now enable that option
<add> scope.$apply(function() {
<add> scope.options[1].unavailable = false;
<add> });
<add>
<add> expect(element).toEqualSelectValue([1], true);
<add> options = element.find('option');
<add> expect(options.eq(0).prop('selected')).toEqual(false);
<add> expect(options.eq(1).prop('selected')).toEqual(true);
<add> expect(options.eq(2).prop('selected')).toEqual(false);
<add> expect(options.eq(3).prop('selected')).toEqual(false);
<add> });
<add> });
<add> });
<add>
<add>
<ide> describe('selectAs expression', function() {
<ide> beforeEach(function() {
<ide> scope.arr = [{id: 10, label: 'ten'}, {id:20, label: 'twenty'}];
<ide> describe('ngOptions', function() {
<ide> expect(element).toEqualSelectValue(scope.selected);
<ide> });
<ide>
<add> it('should bind to object disabled', function() {
<add> scope.selected = 30;
<add> scope.options = [
<add> { name: 'white', value: '#FFFFFF' },
<add> { name: 'one', value: 1, unavailable: true },
<add> { name: 'notTrue', value: false },
<add> { name: 'thirty', value: 30, unavailable: false }
<add> ];
<add> createSelect({
<add> 'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
<add> 'ng-model': 'selected'
<add> });
<add>
<add> var options = element.find('option');
<add>
<add> expect(scope.options[1].unavailable).toEqual(true);
<add> expect(options.eq(1).prop('disabled')).toEqual(true);
<add>
<add> scope.$apply(function() {
<add> scope.options[1].unavailable = false;
<add> });
<add>
<add> expect(scope.options[1].unavailable).toEqual(false);
<add> expect(options.eq(1).prop('disabled')).toEqual(false);
<add> });
<ide>
<ide> it('should insert a blank option if bound to null', function() {
<ide> createSingleSelect();
<ide> describe('ngOptions', function() {
<ide> expect(element.find('option')[1].selected).toBeTruthy();
<ide> });
<ide>
<add> it('should not write disabled selections from model', function() {
<add> scope.selected = [30];
<add> scope.options = [
<add> { name: 'white', value: '#FFFFFF' },
<add> { name: 'one', value: 1, unavailable: true },
<add> { name: 'notTrue', value: false },
<add> { name: 'thirty', value: 30, unavailable: false }
<add> ];
<add> createSelect({
<add> 'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
<add> 'ng-model': 'selected',
<add> 'multiple': true
<add> });
<add>
<add> var options = element.find('option');
<add>
<add> expect(options.eq(0).prop('selected')).toEqual(false);
<add> expect(options.eq(1).prop('selected')).toEqual(false);
<add> expect(options.eq(2).prop('selected')).toEqual(false);
<add> expect(options.eq(3).prop('selected')).toEqual(true);
<add>
<add> scope.$apply(function() {
<add> scope.selected.push(1);
<add> });
<add>
<add> expect(options.eq(0).prop('selected')).toEqual(false);
<add> expect(options.eq(1).prop('selected')).toEqual(false);
<add> expect(options.eq(2).prop('selected')).toEqual(false);
<add> expect(options.eq(3).prop('selected')).toEqual(true);
<add> });
<add>
<ide>
<ide> it('should update model on change', function() {
<ide> createMultiSelect(); | 2 |
Javascript | Javascript | remove side-effects of one attributes test | f9ea869ab5e887dad28088f6b477fa2ecac747a9 | <ide><path>test/unit/attributes.js
<ide> QUnit.test( "attr(non-ASCII)", function( assert ) {
<ide> QUnit.test( "attr - extending the boolean attrHandle", function( assert ) {
<ide> assert.expect( 1 );
<ide> var called = false,
<del> _handle = jQuery.expr.attrHandle.checked || $.noop;
<add> origAttrHandleHadChecked = "checked" in jQuery.expr.attrHandle,
<add> origAttrHandleChecked = jQuery.expr.attrHandle.checked,
<add> _handle = origAttrHandleChecked || $.noop;
<ide> jQuery.expr.attrHandle.checked = function() {
<ide> called = true;
<ide> _handle.apply( this, arguments );
<ide> QUnit.test( "attr - extending the boolean attrHandle", function( assert ) {
<ide> called = false;
<ide> jQuery( "#qunit-fixture input" ).attr( "checked" );
<ide> assert.ok( called, "The boolean attrHandle does not drop custom attrHandles" );
<add>
<add> if ( origAttrHandleHadChecked ) {
<add> jQuery.expr.attrHandle.checked = origAttrHandleChecked;
<add> } else {
<add> delete jQuery.expr.attrHandle.checked;
<add> }
<add>
<ide> } );
<ide>
<ide> QUnit.test( "attr(String, Object) - Loaded via XML document", function( assert ) { | 1 |
Ruby | Ruby | upgrade virtualenv to 16.4.3 | 9dbd04ac094c8b47aeba242165fbb810c79de9ed | <ide><path>Library/Homebrew/language/python_virtualenv_constants.rb
<ide> PYTHON_VIRTUALENV_URL =
<del> "https://files.pythonhosted.org/packages/51/aa" \
<del> "/c395a6e6eaaedfa5a04723b6446a1df783b16cca6fec66e671cede514688" \
<del> "/virtualenv-16.4.0.tar.gz".freeze
<add> "https://files.pythonhosted.org/packages/37/db" \
<add> "/89d6b043b22052109da35416abc3c397655e4bd3cff031446ba02b9654fa" \
<add> "/virtualenv-16.4.3.tar.gz".freeze
<ide> PYTHON_VIRTUALENV_SHA256 =
<del> "cceab52aa7d4df1e1871a70236eb2b89fcfe29b6b43510d9738689787c513261".freeze
<add> "984d7e607b0a5d1329425dd8845bd971b957424b5ba664729fab51ab8c11bc39".freeze | 1 |
Javascript | Javascript | update the copyright from 2009 to 2010 | 25ee9cee26c9c4170693908fbe233154e8158d69 | <ide><path>src/intro.js
<ide> * jQuery JavaScript Library v@VERSION
<ide> * http://jquery.com/
<ide> *
<del> * Copyright 2009, John Resig
<add> * Copyright 2010, John Resig
<ide> * Dual licensed under the MIT or GPL Version 2 licenses.
<ide> * http://docs.jquery.com/License
<ide> *
<ide> * Includes Sizzle.js
<ide> * http://sizzlejs.com/
<del> * Copyright 2009, The Dojo Foundation
<add> * Copyright 2010, The Dojo Foundation
<ide> * Released under the MIT, BSD, and GPL Licenses.
<ide> *
<ide> * Date: | 1 |
Ruby | Ruby | fix one line formatting bug | 8b5eb2bacc9e61c6a23b85c03933ef6e2071fab8 | <ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb
<ide> def ago(seconds)
<ide> end
<ide>
<ide> # Returns a new Time representing the time a number of seconds since the instance time, this is basically a wrapper around
<del> #the Numeric extension. Do not use this method in combination with x.months, use months_since instead!
<add> # the Numeric extension. Do not use this method in combination with x.months, use months_since instead!
<ide> def since(seconds)
<ide> initial_dst = self.dst? ? 1 : 0
<ide> f = seconds.since(self) | 1 |
PHP | PHP | fix code style 4 | b3a61698a6455dc9ff4e0134bed9a8239d8b9d70 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function qualifyColumn($column)
<ide> public function qualifyColumns($columns)
<ide> {
<ide> $columns = is_array($columns) ? $columns : func_get_args();
<del>
<ide> $qualifiedArray = [];
<ide>
<ide> foreach ($columns as $column) {
<ide> $qualifiedArray[] = $this->qualifyColumn($column);
<del> }
<del>
<add> }
<ide> return $qualifiedArray;
<ide> }
<ide> | 1 |
PHP | PHP | change visiblity of properties on pluralizer | 4fb411ec9ac803073065a5c6e56c43f9656ed2e8 | <ide><path>src/Illuminate/Support/Pluralizer.php
<ide> class Pluralizer {
<ide> *
<ide> * @var array
<ide> */
<del> protected static $plural = array(
<add> public static $plural = array(
<ide> '/(quiz)$/i' => "$1zes",
<ide> '/^(ox)$/i' => "$1en",
<ide> '/([m|l])ouse$/i' => "$1ice",
<ide> class Pluralizer {
<ide> *
<ide> * @var array
<ide> */
<del> protected static $singular = array(
<add> public static $singular = array(
<ide> '/(quiz)zes$/i' => "$1",
<ide> '/(matr)ices$/i' => "$1ix",
<ide> '/(vert|ind)ices$/i' => "$1ex",
<ide> class Pluralizer {
<ide> *
<ide> * @var array
<ide> */
<del> protected static $irregular = array(
<add> public static $irregular = array(
<ide> 'child' => 'children',
<ide> 'foot' => 'feet',
<ide> 'goose' => 'geese',
<ide> class Pluralizer {
<ide> *
<ide> * @var array
<ide> */
<del> protected static $uncountable = array(
<add> public static $uncountable = array(
<ide> 'audio',
<ide> 'equipment',
<ide> 'deer',
<ide> protected static function inflect($value, $source, $irregular)
<ide> if (preg_match($pattern = '/'.$pattern.'$/i', $value))
<ide> {
<ide> $irregular = static::matchCase($irregular, $value);
<del>
<add>
<ide> return preg_replace($pattern, $irregular, $value);
<ide> }
<ide> } | 1 |
Javascript | Javascript | remove trycatch in canvas fill | 063ca95f5fb829d930733926c65c0fbeedaffe11 | <ide><path>src/display/canvas.js
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> ctx.fill();
<ide> ctx.mozFillRule = 'nonzero';
<ide> } else {
<del> try {
<del> ctx.fill('evenodd');
<del> } catch (ex) {
<del> // shouldn't really happen, but browsers might think differently
<del> ctx.fill();
<del> }
<add> ctx.fill('evenodd');
<ide> }
<ide> this.pendingEOFill = false;
<ide> } else {
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> ctx.clip();
<ide> ctx.mozFillRule = 'nonzero';
<ide> } else {
<del> try {
<del> ctx.clip('evenodd');
<del> } catch (ex) {
<del> // shouldn't really happen, but browsers might think differently
<del> ctx.clip();
<del> }
<add> ctx.clip('evenodd');
<ide> }
<ide> } else {
<ide> ctx.clip();
<ide><path>web/compatibility.js
<ide> if (typeof PDFJS === 'undefined') {
<ide>
<ide> if (polyfill) {
<ide> var contextPrototype = window.CanvasRenderingContext2D.prototype;
<del> contextPrototype._createImageData = contextPrototype.createImageData;
<add> var createImageData = contextPrototype.createImageData;
<ide> contextPrototype.createImageData = function(w, h) {
<del> var imageData = this._createImageData(w, h);
<add> var imageData = createImageData.call(this, w, h);
<ide> imageData.data.set = function(arr) {
<ide> for (var i = 0, ii = this.length; i < ii; i++) {
<ide> this[i] = arr[i];
<ide> }
<ide> };
<ide> return imageData;
<ide> };
<add> // this closure will be kept referenced, so clear its vars
<add> contextPrototype = null;
<ide> }
<ide> }
<ide> })(); | 2 |
Java | Java | fix amb backpressure problems | 9585c6e2a54d89f032ab9f2082395eada69b3512 | <ide><path>src/main/java/rx/internal/operators/OnSubscribeAmb.java
<ide> public static <T> OnSubscribe<T> amb(final Iterable<? extends Observable<? exten
<ide>
<ide> private final Subscriber<? super T> subscriber;
<ide> private final Selection<T> selection;
<add> private boolean chosen;
<ide>
<ide> private AmbSubscriber(long requested, Subscriber<? super T> subscriber, Selection<T> selection) {
<ide> this.subscriber = subscriber;
<ide> private final void requestMore(long n) {
<ide> }
<ide>
<ide> @Override
<del> public void onNext(T args) {
<add> public void onNext(T t) {
<ide> if (!isSelected()) {
<ide> return;
<ide> }
<del> subscriber.onNext(args);
<add> subscriber.onNext(t);
<ide> }
<ide>
<ide> @Override
<ide> public void onError(Throwable e) {
<ide> }
<ide>
<ide> private boolean isSelected() {
<add> if (chosen) {
<add> return true;
<add> }
<ide> if (selection.choice.get() == this) {
<ide> // fast-path
<add> chosen = true;
<ide> return true;
<ide> } else {
<ide> if (selection.choice.compareAndSet(null, this)) {
<ide> selection.unsubscribeOthers(this);
<add> chosen = true;
<ide> return true;
<ide> } else {
<ide> // we lost so unsubscribe ... and force cleanup again due to possible race conditions
<ide> public void unsubscribeOthers(AmbSubscriber<T> notThis) {
<ide> }
<ide>
<ide> }
<del>
<del> private final Iterable<? extends Observable<? extends T>> sources;
<del> private final Selection<T> selection = new Selection<T>();
<del>
<add>
<add> //give default access instead of private as a micro-optimization
<add> //for access from anonymous classes below
<add> final Iterable<? extends Observable<? extends T>> sources;
<add> final Selection<T> selection = new Selection<T>();
<add> final AtomicReference<AmbSubscriber<T>> choice = selection.choice;
<add>
<ide> private OnSubscribeAmb(Iterable<? extends Observable<? extends T>> sources) {
<ide> this.sources = sources;
<ide> }
<ide>
<ide> @Override
<ide> public void call(final Subscriber<? super T> subscriber) {
<add>
<add> //setup unsubscription of all the subscribers to the sources
<ide> subscriber.add(Subscriptions.create(new Action0() {
<ide>
<ide> @Override
<ide> public void call() {
<del> if (selection.choice.get() != null) {
<add> AmbSubscriber<T> c;
<add> if ((c = choice.get()) != null) {
<ide> // there is a single winner so we unsubscribe it
<del> selection.choice.get().unsubscribe();
<add> c.unsubscribe();
<ide> }
<ide> // if we are racing with others still existing, we'll also unsubscribe them
<del> if(!selection.ambSubscribers.isEmpty()) {
<del> for (AmbSubscriber<T> other : selection.ambSubscribers) {
<del> other.unsubscribe();
<del> }
<del> selection.ambSubscribers.clear();
<del> }
<add> // if subscriptions are occurring as this is happening then this call may not
<add> // unsubscribe everything. We protect ourselves though by doing another unsubscribe check
<add> // after the subscription loop below
<add> unsubscribeAmbSubscribers(selection.ambSubscribers);
<ide> }
<del>
<add>
<ide> }));
<add>
<add> //need to subscribe to all the sources
<add> for (Observable<? extends T> source : sources) {
<add> if (subscriber.isUnsubscribed()) {
<add> break;
<add> }
<add> AmbSubscriber<T> ambSubscriber = new AmbSubscriber<T>(0, subscriber, selection);
<add> selection.ambSubscribers.add(ambSubscriber);
<add> // check again if choice has been made so can stop subscribing
<add> // if all sources were backpressure aware then this check
<add> // would be pointless given that 0 was requested above from each ambSubscriber
<add> AmbSubscriber<T> c;
<add> if ((c = choice.get()) != null) {
<add> // Already chose one, the rest can be skipped and we can clean up
<add> selection.unsubscribeOthers(c);
<add> return;
<add> }
<add> source.unsafeSubscribe(ambSubscriber);
<add> }
<add> // while subscribing unsubscription may have occurred so we clean up after
<add> if (subscriber.isUnsubscribed()) {
<add> unsubscribeAmbSubscribers(selection.ambSubscribers);
<add> }
<add>
<ide> subscriber.setProducer(new Producer() {
<ide>
<ide> @Override
<ide> public void request(long n) {
<del> if (selection.choice.get() != null) {
<add> final AmbSubscriber<T> c;
<add> if ((c = choice.get()) != null) {
<ide> // propagate the request to that single Subscriber that won
<del> selection.choice.get().requestMore(n);
<add> c.requestMore(n);
<ide> } else {
<del> for (Observable<? extends T> source : sources) {
<del> if (subscriber.isUnsubscribed()) {
<del> break;
<del> }
<del> AmbSubscriber<T> ambSubscriber = new AmbSubscriber<T>(n, subscriber, selection);
<del> selection.ambSubscribers.add(ambSubscriber);
<del> // possible race condition in previous lines ... a choice may have been made so double check (instead of synchronizing)
<del> if (selection.choice.get() != null) {
<del> // Already chose one, the rest can be skipped and we can clean up
<del> selection.unsubscribeOthers(selection.choice.get());
<del> break;
<add> //propagate the request to all the amb subscribers
<add> for (AmbSubscriber<T> ambSubscriber: selection.ambSubscribers) {
<add> if (!ambSubscriber.isUnsubscribed()) {
<add> // make a best endeavours check to not waste requests
<add> // if first emission has already occurred
<add> if (choice.get() == ambSubscriber) {
<add> ambSubscriber.requestMore(n);
<add> // don't need to request from other subscribers because choice has been made
<add> // and request has gone to choice
<add> return;
<add> } else {
<add> ambSubscriber.requestMore(n);
<add> }
<ide> }
<del> source.unsafeSubscribe(ambSubscriber);
<ide> }
<ide> }
<ide> }
<ide> });
<ide> }
<ide>
<add> private static <T> void unsubscribeAmbSubscribers(Collection<AmbSubscriber<T>> ambSubscribers) {
<add> if(!ambSubscribers.isEmpty()) {
<add> for (AmbSubscriber<T> other : ambSubscribers) {
<add> other.unsubscribe();
<add> }
<add> ambSubscribers.clear();
<add> }
<add> }
<ide> }
<ide><path>src/test/java/rx/internal/operators/OnSubscribeAmbTest.java
<ide> import static rx.internal.operators.OnSubscribeAmb.amb;
<ide>
<ide> import java.io.IOException;
<add>import java.util.Arrays;
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.atomic.AtomicLong;
<ide>
<ide> import rx.Scheduler;
<ide> import rx.Subscriber;
<ide> import rx.functions.Action0;
<add>import rx.functions.Action1;
<ide> import rx.internal.util.RxRingBuffer;
<ide> import rx.observers.TestSubscriber;
<ide> import rx.schedulers.Schedulers;
<ide> public void testBackpressure() {
<ide> ts.assertNoErrors();
<ide> assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size());
<ide> }
<add>
<add>
<add> @Test
<add> public void testSubscriptionOnlyHappensOnce() throws InterruptedException {
<add> final AtomicLong count = new AtomicLong();
<add> Action0 incrementer = new Action0() {
<add> @Override
<add> public void call() {
<add> count.incrementAndGet();
<add> }
<add> };
<add> //this aync stream should emit first
<add> Observable<Integer> o1 = Observable.just(1).doOnSubscribe(incrementer)
<add> .delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation());
<add> //this stream emits second
<add> Observable<Integer> o2 = Observable.just(1).doOnSubscribe(incrementer)
<add> .delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation());
<add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add> Observable.amb(o1, o2).subscribe(ts);
<add> ts.requestMore(1);
<add> ts.awaitTerminalEvent(5, TimeUnit.SECONDS);
<add> ts.assertNoErrors();
<add> assertEquals(2, count.get());
<add> }
<add>
<add> @Test
<add> public void testSecondaryRequestsPropagatedToChildren() throws InterruptedException {
<add> //this aync stream should emit first
<add> Observable<Integer> o1 = Observable.from(Arrays.asList(1, 2, 3))
<add> .delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation());
<add> //this stream emits second
<add> Observable<Integer> o2 = Observable.from(Arrays.asList(4, 5, 6))
<add> .delay(200, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation());
<add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>() {
<add> @Override
<add> public void onStart() {
<add> request(1);
<add> }};
<add> Observable.amb(o1, o2).subscribe(ts);
<add> // before first emission request 20 more
<add> // this request should suffice to emit all
<add> ts.requestMore(20);
<add> //ensure stream does not hang
<add> ts.awaitTerminalEvent(5, TimeUnit.SECONDS);
<add> ts.assertNoErrors();
<add> }
<add>
<add> @Test
<add> public void testSynchronousSources() {
<add> // under async subscription the second observable would complete before
<add> // the first but because this is a synchronous subscription to sources
<add> // then second observable does not get subscribed to before first
<add> // subscription completes hence first observable emits result through
<add> // amb
<add> int result = Observable.just(1).doOnNext(new Action1<Object>() {
<add>
<add> @Override
<add> public void call(Object t) {
<add> try {
<add> Thread.sleep(100);
<add> } catch (InterruptedException e) {
<add> //
<add> }
<add> }
<add> }).ambWith(Observable.just(2)).toBlocking().single();
<add> assertEquals(1, result);
<add> }
<add>
<ide> } | 2 |
Mixed | Javascript | remove malfunctioning linux manpage linker | cc9ac42111c3a9aed4b191f8d6d56929d7b50519 | <ide><path>doc/api/os.md
<ide> added: v0.3.3
<ide> Returns the operating system as a string.
<ide>
<ide> On POSIX systems, the operating system release is determined by calling
<del>[uname(3)][]. On Windows, `GetVersionExW()` is used. See
<add>[`uname(3)`][]. On Windows, `GetVersionExW()` is used. See
<ide> <https://en.wikipedia.org/wiki/Uname#Examples> for more information.
<ide>
<ide> ## `os.setPriority([pid, ]priority)`
<ide> added: v0.3.3
<ide>
<ide> * Returns: {string}
<ide>
<del>Returns the operating system name as returned by [uname(3)][]. For example, it
<add>Returns the operating system name as returned by [`uname(3)`][]. For example, it
<ide> returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows.
<ide>
<ide> See <https://en.wikipedia.org/wiki/Uname#Examples> for additional information
<del>about the output of running [uname(3)][] on various operating systems.
<add>about the output of running [`uname(3)`][] on various operating systems.
<ide>
<ide> ## `os.uptime()`
<ide> <!-- YAML
<ide> added:
<ide> Returns a string identifying the kernel version.
<ide>
<ide> On POSIX systems, the operating system release is determined by calling
<del>[uname(3)][]. On Windows, `RtlGetVersion()` is used, and if it is not available,
<del>`GetVersionExW()` will be used. See
<add>[`uname(3)`][]. On Windows, `RtlGetVersion()` is used, and if it is not
<add>available, `GetVersionExW()` will be used. See
<ide> <https://en.wikipedia.org/wiki/Uname#Examples> for more information.
<ide>
<ide> ## OS constants
<ide> The following process scheduling constants are exported by
<ide> [`SystemError`]: errors.html#errors_class_systemerror
<ide> [`process.arch`]: process.html#process_process_arch
<ide> [`process.platform`]: process.html#process_process_platform
<add>[`uname(3)`]: https://linux.die.net/man/3/uname
<ide> [Android building]: https://github.com/nodejs/node/blob/master/BUILDING.md#androidandroid-based-devices-eg-firefox-os
<ide> [EUID]: https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID
<del>[uname(3)]: https://linux.die.net/man/3/uname
<ide><path>tools/doc/html.js
<ide> function preprocessText({ nodeVersion }) {
<ide>
<ide> // Syscalls which appear in the docs, but which only exist in BSD / macOS.
<ide> const BSD_ONLY_SYSCALLS = new Set(['lchmod']);
<del>const LINUX_DIE_ONLY_SYSCALLS = new Set(['uname']);
<ide> const HAXX_ONLY_SYSCALLS = new Set(['curl']);
<ide> const MAN_PAGE = /(^|\s)([a-z.]+)\((\d)([a-z]?)\)/gm;
<ide>
<ide> function linkManPages(text) {
<ide> return `${beginning}<a href="https://www.freebsd.org/cgi/man.cgi` +
<ide> `?query=${name}&sektion=${number}">${displayAs}</a>`;
<ide> }
<del> if (LINUX_DIE_ONLY_SYSCALLS.has(name)) {
<del> return `${beginning}<a href="https://linux.die.net/man/` +
<del> `${number}/${name}">${displayAs}</a>`;
<del> }
<ide> if (HAXX_ONLY_SYSCALLS.has(name)) {
<ide> return `${beginning}<a href="https://${name}.haxx.se/docs/manpage.html">${displayAs}</a>`;
<ide> } | 2 |
Javascript | Javascript | fix race condition in unrefd interval test | 6de82c69a00a1515dbf4019c4f27bb1f82c508e0 | <ide><path>test/parallel/test-timers-unrefd-interval-still-fires.js
<ide> /*
<ide> * This test is a regression test for joyent/node#8900.
<ide> */
<del>require('../common');
<del>var assert = require('assert');
<add>const common = require('../common');
<add>const assert = require('assert');
<ide>
<del>var N = 5;
<add>const TEST_DURATION = common.platformTimeout(100);
<add>const N = 5;
<ide> var nbIntervalFired = 0;
<del>var timer = setInterval(function() {
<add>
<add>const keepOpen = setTimeout(() => {
<add> console.error('[FAIL] Interval fired %d/%d times.', nbIntervalFired, N);
<add> throw new Error('Test timed out. keepOpen was not canceled.');
<add>}, TEST_DURATION);
<add>
<add>const timer = setInterval(() => {
<ide> ++nbIntervalFired;
<del> if (nbIntervalFired === N)
<add> if (nbIntervalFired === N) {
<ide> clearInterval(timer);
<add> timer._onTimeout = () => {
<add> throw new Error('Unrefd interval fired after being cleared.');
<add> };
<add> setImmediate(() => clearTimeout(keepOpen));
<add> }
<ide> }, 1);
<ide>
<ide> timer.unref();
<del>
<del>setTimeout(function onTimeout() {
<del> assert.strictEqual(nbIntervalFired, N);
<del>}, 100); | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.