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 standalone paginator class
8a6e88983b07d1ef11191e959c540abaf07b5d53
<ide><path>src/Controller/Component/PaginatorComponent.php <ide> namespace Cake\Controller\Component; <ide> <ide> use Cake\Controller\Component; <del>use Cake\Datasource\QueryInterface; <del>use Cake\Datasource\RepositoryInterface; <add>use Cake\Controller\ComponentRegistry; <add>use Cake\Core\InstanceConfigTrait; <ide> use Cake\Network\Exception\NotFoundException; <del>use Cake\Utility\Hash; <add>use Cake\ORM\Paginator; <ide> <ide> /** <ide> * This component is used to handle automatic model data pagination. The primary way to use this <ide> */ <ide> class PaginatorComponent extends Component <ide> { <add> use InstanceConfigTrait { <add> setConfig as protected _setConfig; <add> configShallow as protected _configShallow; <add> } <ide> <ide> /** <ide> * Default pagination settings. <ide> class PaginatorComponent extends Component <ide> 'whitelist' => ['limit', 'sort', 'page', 'direction'] <ide> ]; <ide> <add> protected $_paginator; <add> <add> public function __construct(ComponentRegistry $registry, array $config = []) <add> { <add> $this->_paginator = new Paginator(); <add> <add> parent::__construct($registry, $config); <add> } <add> <ide> /** <ide> * Events supported by this component. <ide> * <ide> public function implementedEvents() <ide> */ <ide> public function paginate($object, array $settings = []) <ide> { <del> $query = null; <del> if ($object instanceof QueryInterface) { <del> $query = $object; <del> $object = $query->repository(); <del> } <del> <del> $alias = $object->alias(); <del> $options = $this->mergeOptions($alias, $settings); <del> $options = $this->validateSort($object, $options); <del> $options = $this->checkLimit($options); <del> <del> $options += ['page' => 1, 'scope' => null]; <del> $options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page']; <del> list($finder, $options) = $this->_extractFinder($options); <del> <del> /* @var \Cake\Datasource\RepositoryInterface $object */ <del> if (empty($query)) { <del> $query = $object->find($finder, $options); <del> } else { <del> $query->applyOptions($options); <del> } <del> <del> $results = $query->all(); <del> $numResults = count($results); <del> $count = $numResults ? $query->count() : 0; <del> <del> $defaults = $this->getDefaults($alias, $settings); <del> unset($defaults[0]); <del> <del> $page = $options['page']; <del> $limit = $options['limit']; <del> $pageCount = (int)ceil($count / $limit); <del> $requestedPage = $page; <del> $page = max(min($page, $pageCount), 1); <ide> $request = $this->_registry->getController()->request; <ide> <del> $order = (array)$options['order']; <del> $sortDefault = $directionDefault = false; <del> if (!empty($defaults['order']) && count($defaults['order']) == 1) { <del> $sortDefault = key($defaults['order']); <del> $directionDefault = current($defaults['order']); <del> } <del> <del> $paging = [ <del> 'finder' => $finder, <del> 'page' => $page, <del> 'current' => $numResults, <del> 'count' => $count, <del> 'perPage' => $limit, <del> 'prevPage' => $page > 1, <del> 'nextPage' => $count > ($page * $limit), <del> 'pageCount' => $pageCount, <del> 'sort' => key($order), <del> 'direction' => current($order), <del> 'limit' => $defaults['limit'] != $limit ? $limit : null, <del> 'sortDefault' => $sortDefault, <del> 'directionDefault' => $directionDefault, <del> 'scope' => $options['scope'], <del> ]; <add> try { <add> $results = $this->_paginator->paginate( <add> $object, <add> $request->getQueryParams(), <add> $settings <add> ); <ide> <del> if (!$request->getParam('paging')) { <del> $request->params['paging'] = []; <del> } <del> $request->params['paging'] = [$alias => $paging] + (array)$request->getParam('paging'); <add> $this->_setPagingParams(); <add> } catch (NotFoundException $e) { <add> $this->_setPagingParams(); <ide> <del> if ($requestedPage > $page) { <del> throw new NotFoundException(); <add> throw $e; <ide> } <ide> <ide> return $results; <ide> } <ide> <del> /** <del> * Extracts the finder name and options out of the provided pagination options <del> * <del> * @param array $options the pagination options <del> * @return array An array containing in the first position the finder name and <del> * in the second the options to be passed to it <del> */ <del> protected function _extractFinder($options) <del> { <del> $type = !empty($options['finder']) ? $options['finder'] : 'all'; <del> unset($options['finder'], $options['maxLimit']); <del> <del> if (is_array($type)) { <del> $options = (array)current($type) + $options; <del> $type = key($type); <del> } <del> <del> return [$type, $options]; <del> } <del> <del> /** <del> * Merges the various options that Pagination uses. <del> * Pulls settings together from the following places: <del> * <del> * - General pagination settings <del> * - Model specific settings. <del> * - Request parameters <del> * <del> * The result of this method is the aggregate of all the option sets combined together. You can change <del> * config value `whitelist` to modify which options/values can be set using request parameters. <del> * <del> * @param string $alias Model alias being paginated, if the general settings has a key with this value <del> * that key's settings will be used for pagination instead of the general ones. <del> * @param array $settings The settings to merge with the request data. <del> * @return array Array of merged options. <del> */ <ide> public function mergeOptions($alias, $settings) <ide> { <del> $defaults = $this->getDefaults($alias, $settings); <ide> $request = $this->_registry->getController()->request; <del> $scope = Hash::get($settings, 'scope', null); <del> $query = $request->getQueryParams(); <del> if ($scope) { <del> $query = Hash::get($request->getQueryParams(), $scope, []); <del> } <del> $request = array_intersect_key($query, array_flip($this->_config['whitelist'])); <add> $this->_paginator->setParams($request->getQueryParams()); <ide> <del> return array_merge($defaults, $request); <add> return $this->_paginator->mergeOptions($alias, $settings); <ide> } <ide> <del> /** <del> * Get the settings for a $model. If there are no settings for a specific model, the general settings <del> * will be used. <del> * <del> * @param string $alias Model name to get settings for. <del> * @param array $settings The settings which is used for combining. <del> * @return array An array of pagination settings for a model, or the general settings. <del> */ <del> public function getDefaults($alias, $settings) <add> protected function _setPagingParams() <ide> { <del> if (isset($settings[$alias])) { <del> $settings = $settings[$alias]; <del> } <del> <del> $defaults = $this->getConfig(); <del> $maxLimit = isset($settings['maxLimit']) ? $settings['maxLimit'] : $defaults['maxLimit']; <del> $limit = isset($settings['limit']) ? $settings['limit'] : $defaults['limit']; <add> $request = $this->_registry->getController()->request; <ide> <del> if ($limit > $maxLimit) { <del> $limit = $maxLimit; <add> if (!$request->getParam('paging')) { <add> $request->params['paging'] = []; <ide> } <ide> <del> $settings['maxLimit'] = $maxLimit; <del> $settings['limit'] = $limit; <del> <del> return $settings + $defaults; <add> $request->params['paging'] = $this->_paginator->getPagingParams() <add> + (array)$request->getParam('paging'); <ide> } <ide> <del> /** <del> * Validate that the desired sorting can be performed on the $object. Only fields or <del> * virtualFields can be sorted on. The direction param will also be sanitized. Lastly <del> * sort + direction keys will be converted into the model friendly order key. <del> * <del> * You can use the whitelist parameter to control which columns/fields are available for sorting. <del> * This helps prevent users from ordering large result sets on un-indexed values. <del> * <del> * If you need to sort on associated columns or synthetic properties you will need to use a whitelist. <del> * <del> * Any columns listed in the sort whitelist will be implicitly trusted. You can use this to sort <del> * on synthetic columns, or columns added in custom find operations that may not exist in the schema. <del> * <del> * @param \Cake\Datasource\RepositoryInterface $object Repository object. <del> * @param array $options The pagination options being used for this request. <del> * @return array An array of options with sort + direction removed and replaced with order if possible. <del> */ <del> public function validateSort(RepositoryInterface $object, array $options) <add> public function setConfig($key, $value = null, $merge = true) <ide> { <del> if (isset($options['sort'])) { <del> $direction = null; <del> if (isset($options['direction'])) { <del> $direction = strtolower($options['direction']); <del> } <del> if (!in_array($direction, ['asc', 'desc'])) { <del> $direction = 'asc'; <del> } <del> $options['order'] = [$options['sort'] => $direction]; <del> } <del> unset($options['sort'], $options['direction']); <del> <del> if (empty($options['order'])) { <del> $options['order'] = []; <del> } <del> if (!is_array($options['order'])) { <del> return $options; <del> } <del> <del> $inWhitelist = false; <del> if (isset($options['sortWhitelist'])) { <del> $field = key($options['order']); <del> $inWhitelist = in_array($field, $options['sortWhitelist'], true); <del> if (!$inWhitelist) { <del> $options['order'] = []; <del> <del> return $options; <del> } <del> } <add> $this->_paginator->setConfig($key, $value, $merge); <ide> <del> $options['order'] = $this->_prefix($object, $options['order'], $inWhitelist); <del> <del> return $options; <add> return $this->_setConfig($key, $value, $merge); <ide> } <ide> <del> /** <del> * Prefixes the field with the table alias if possible. <del> * <del> * @param \Cake\Datasource\RepositoryInterface $object Repository object. <del> * @param array $order Order array. <del> * @param bool $whitelisted Whether or not the field was whitelisted <del> * @return array Final order array. <del> */ <del> protected function _prefix(RepositoryInterface $object, $order, $whitelisted = false) <add> public function configShallow($key, $value = null) <ide> { <del> $tableAlias = $object->alias(); <del> $tableOrder = []; <del> foreach ($order as $key => $value) { <del> if (is_numeric($key)) { <del> $tableOrder[] = $value; <del> continue; <del> } <del> $field = $key; <del> $alias = $tableAlias; <add> $this->_paginator->configShallow($key, $value = null); <ide> <del> if (strpos($key, '.') !== false) { <del> list($alias, $field) = explode('.', $key); <del> } <del> $correctAlias = ($tableAlias === $alias); <del> <del> if ($correctAlias && $whitelisted) { <del> // Disambiguate fields in schema. As id is quite common. <del> if ($object->hasField($field)) { <del> $field = $alias . '.' . $field; <del> } <del> $tableOrder[$field] = $value; <del> } elseif ($correctAlias && $object->hasField($field)) { <del> $tableOrder[$tableAlias . '.' . $field] = $value; <del> } elseif (!$correctAlias && $whitelisted) { <del> $tableOrder[$alias . '.' . $field] = $value; <del> } <del> } <del> <del> return $tableOrder; <add> return $this->_configShallow($key, $value = null); <ide> } <ide> <del> /** <del> * Check the limit parameter and ensure it's within the maxLimit bounds. <del> * <del> * @param array $options An array of options with a limit key to be checked. <del> * @return array An array of options for pagination <del> */ <del> public function checkLimit(array $options) <add> public function __call($method, $args) <ide> { <del> $options['limit'] = (int)$options['limit']; <del> if (empty($options['limit']) || $options['limit'] < 1) { <del> $options['limit'] = 1; <del> } <del> $options['limit'] = max(min($options['limit'], $options['maxLimit']), 1); <del> <del> return $options; <add> return call_user_func_array([$this->_paginator, $method], $args); <ide> } <ide> } <ide><path>src/ORM/Paginator.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since 3.4.8 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\ORM; <add> <add>use Cake\Core\InstanceConfigTrait; <add>use Cake\Datasource\QueryInterface; <add>use Cake\Datasource\RepositoryInterface; <add>use Cake\Network\Exception\NotFoundException; <add>use Cake\Utility\Hash; <add> <add>/** <add> * This component is used to handle automatic model data pagination. The primary way to use this <add> * component is to call the paginate() method. There is a convenience wrapper on Controller as well. <add> * <add> * ### Configuring pagination <add> * <add> * You configure pagination when calling paginate(). See that method for more details. <add> * <add> * @link http://book.cakephp.org/3.0/en/controllers/components/pagination.html <add> */ <add>class Paginator <add>{ <add> use InstanceConfigTrait; <add> <add> /** <add> * Default pagination settings. <add> * <add> * When calling paginate() these settings will be merged with the configuration <add> * you provide. <add> * <add> * - `maxLimit` - The maximum limit users can choose to view. Defaults to 100 <add> * - `limit` - The initial number of items per page. Defaults to 20. <add> * - `page` - The starting page, defaults to 1. <add> * - `whitelist` - A list of parameters users are allowed to set using request <add> * parameters. Modifying this list will allow users to have more influence <add> * over pagination, be careful with what you permit. <add> * <add> * @var array <add> */ <add> protected $_defaultConfig = [ <add> 'page' => 1, <add> 'limit' => 20, <add> 'maxLimit' => 100, <add> 'whitelist' => ['limit', 'sort', 'page', 'direction'] <add> ]; <add> <add> protected $_params = []; <add> <add> protected $_pagingParams = []; <add> <add> /** <add> * Handles automatic pagination of model records. <add> * <add> * ### Configuring pagination <add> * <add> * When calling `paginate()` you can use the $settings parameter to pass in pagination settings. <add> * These settings are used to build the queries made and control other pagination settings. <add> * <add> * If your settings contain a key with the current table's alias. The data inside that key will be used. <add> * Otherwise the top level configuration will be used. <add> * <add> * ``` <add> * $settings = [ <add> * 'limit' => 20, <add> * 'maxLimit' => 100 <add> * ]; <add> * $results = $paginator->paginate($table, $settings); <add> * ``` <add> * <add> * The above settings will be used to paginate any Table. You can configure Table specific settings by <add> * keying the settings with the Table alias. <add> * <add> * ``` <add> * $settings = [ <add> * 'Articles' => [ <add> * 'limit' => 20, <add> * 'maxLimit' => 100 <add> * ], <add> * 'Comments' => [ ... ] <add> * ]; <add> * $results = $paginator->paginate($table, $settings); <add> * ``` <add> * <add> * This would allow you to have different pagination settings for `Articles` and `Comments` tables. <add> * <add> * ### Controlling sort fields <add> * <add> * By default CakePHP will automatically allow sorting on any column on the table object being <add> * paginated. Often times you will want to allow sorting on either associated columns or calculated <add> * fields. In these cases you will need to define a whitelist of all the columns you wish to allow <add> * sorting on. You can define the whitelist in the `$settings` parameter: <add> * <add> * ``` <add> * $settings = [ <add> * 'Articles' => [ <add> * 'finder' => 'custom', <add> * 'sortWhitelist' => ['title', 'author_id', 'comment_count'], <add> * ] <add> * ]; <add> * ``` <add> * <add> * Passing an empty array as whitelist disallows sorting altogether. <add> * <add> * ### Paginating with custom finders <add> * <add> * You can paginate with any find type defined on your table using the `finder` option. <add> * <add> * ``` <add> * $settings = [ <add> * 'Articles' => [ <add> * 'finder' => 'popular' <add> * ] <add> * ]; <add> * $results = $paginator->paginate($table, $settings); <add> * ``` <add> * <add> * Would paginate using the `find('popular')` method. <add> * <add> * You can also pass an already created instance of a query to this method: <add> * <add> * ``` <add> * $query = $this->Articles->find('popular')->matching('Tags', function ($q) { <add> * return $q->where(['name' => 'CakePHP']) <add> * }); <add> * $results = $paginator->paginate($query); <add> * ``` <add> * <add> * ### Scoping Request parameters <add> * <add> * By using request parameter scopes you can paginate multiple queries in the same controller action: <add> * <add> * ``` <add> * $articles = $paginator->paginate($articlesQuery, ['scope' => 'articles']); <add> * $tags = $paginator->paginate($tagsQuery, ['scope' => 'tags']); <add> * ``` <add> * <add> * Each of the above queries will use different query string parameter sets <add> * for pagination data. An example URL paginating both results would be: <add> * <add> * ``` <add> * /dashboard?articles[page]=1&tags[page]=2 <add> * ``` <add> * <add> * @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object The table or query to paginate. <add> * @param array $params Request params <add> * @param array $settings The settings/configuration used for pagination. <add> * @return \Cake\Datasource\ResultSetInterface Query results <add> * @throws \Cake\Network\Exception\NotFoundException <add> */ <add> public function paginate($object, array $params = null, array $settings = []) <add> { <add> $query = null; <add> if ($object instanceof QueryInterface) { <add> $query = $object; <add> $object = $query->repository(); <add> } <add> <add> if ($params !== null) { <add> $this->_params = $params; <add> } <add> <add> $alias = $object->alias(); <add> $options = $this->mergeOptions($alias, $settings); <add> $options = $this->validateSort($object, $options); <add> $options = $this->checkLimit($options); <add> <add> $options += ['page' => 1, 'scope' => null]; <add> $options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page']; <add> list($finder, $options) = $this->_extractFinder($options); <add> <add> /* @var \Cake\Datasource\RepositoryInterface $object */ <add> if (empty($query)) { <add> $query = $object->find($finder, $options); <add> } else { <add> $query->applyOptions($options); <add> } <add> <add> $results = $query->all(); <add> $numResults = count($results); <add> $count = $numResults ? $query->count() : 0; <add> <add> $defaults = $this->getDefaults($alias, $settings); <add> unset($defaults[0]); <add> <add> $page = $options['page']; <add> $limit = $options['limit']; <add> $pageCount = (int)ceil($count / $limit); <add> $requestedPage = $page; <add> $page = max(min($page, $pageCount), 1); <add> <add> $order = (array)$options['order']; <add> $sortDefault = $directionDefault = false; <add> if (!empty($defaults['order']) && count($defaults['order']) == 1) { <add> $sortDefault = key($defaults['order']); <add> $directionDefault = current($defaults['order']); <add> } <add> <add> $paging = [ <add> 'finder' => $finder, <add> 'page' => $page, <add> 'current' => $numResults, <add> 'count' => $count, <add> 'perPage' => $limit, <add> 'prevPage' => $page > 1, <add> 'nextPage' => $count > ($page * $limit), <add> 'pageCount' => $pageCount, <add> 'sort' => key($order), <add> 'direction' => current($order), <add> 'limit' => $defaults['limit'] != $limit ? $limit : null, <add> 'sortDefault' => $sortDefault, <add> 'directionDefault' => $directionDefault, <add> 'scope' => $options['scope'], <add> ]; <add> <add> $this->_pagingParams = [$alias => $paging]; <add> <add> if ($requestedPage > $page) { <add> throw new NotFoundException(); <add> } <add> <add> return $results; <add> } <add> <add> /** <add> * Extracts the finder name and options out of the provided pagination options <add> * <add> * @param array $options the pagination options <add> * @return array An array containing in the first position the finder name and <add> * in the second the options to be passed to it <add> */ <add> protected function _extractFinder($options) <add> { <add> $type = !empty($options['finder']) ? $options['finder'] : 'all'; <add> unset($options['finder'], $options['maxLimit']); <add> <add> if (is_array($type)) { <add> $options = (array)current($type) + $options; <add> $type = key($type); <add> } <add> <add> return [$type, $options]; <add> } <add> <add> public function setParams($params) <add> { <add> $this->_params = $params; <add> } <add> <add> public function getPagingParams() <add> { <add> return $this->_pagingParams; <add> } <add> <add> /** <add> * Merges the various options that Pagination uses. <add> * Pulls settings together from the following places: <add> * <add> * - General pagination settings <add> * - Model specific settings. <add> * - Request parameters <add> * <add> * The result of this method is the aggregate of all the option sets combined together. You can change <add> * config value `whitelist` to modify which options/values can be set using request parameters. <add> * <add> * @param string $alias Model alias being paginated, if the general settings has a key with this value <add> * that key's settings will be used for pagination instead of the general ones. <add> * @param array $settings The settings to merge with the request data. <add> * @return array Array of merged options. <add> */ <add> public function mergeOptions($alias, $settings) <add> { <add> $defaults = $this->getDefaults($alias, $settings); <add> $scope = Hash::get($settings, 'scope', null); <add> $query = $this->_params; <add> if ($scope) { <add> $query = Hash::get($query, $scope, []); <add> } <add> $query = array_intersect_key($query, array_flip($this->_config['whitelist'])); <add> <add> return array_merge($defaults, $query); <add> } <add> <add> /** <add> * Get the settings for a $model. If there are no settings for a specific model, the general settings <add> * will be used. <add> * <add> * @param string $alias Model name to get settings for. <add> * @param array $settings The settings which is used for combining. <add> * @return array An array of pagination settings for a model, or the general settings. <add> */ <add> public function getDefaults($alias, $settings) <add> { <add> if (isset($settings[$alias])) { <add> $settings = $settings[$alias]; <add> } <add> <add> $defaults = $this->getConfig(); <add> $maxLimit = isset($settings['maxLimit']) ? $settings['maxLimit'] : $defaults['maxLimit']; <add> $limit = isset($settings['limit']) ? $settings['limit'] : $defaults['limit']; <add> <add> if ($limit > $maxLimit) { <add> $limit = $maxLimit; <add> } <add> <add> $settings['maxLimit'] = $maxLimit; <add> $settings['limit'] = $limit; <add> <add> return $settings + $defaults; <add> } <add> <add> /** <add> * Validate that the desired sorting can be performed on the $object. Only fields or <add> * virtualFields can be sorted on. The direction param will also be sanitized. Lastly <add> * sort + direction keys will be converted into the model friendly order key. <add> * <add> * You can use the whitelist parameter to control which columns/fields are available for sorting. <add> * This helps prevent users from ordering large result sets on un-indexed values. <add> * <add> * If you need to sort on associated columns or synthetic properties you will need to use a whitelist. <add> * <add> * Any columns listed in the sort whitelist will be implicitly trusted. You can use this to sort <add> * on synthetic columns, or columns added in custom find operations that may not exist in the schema. <add> * <add> * @param \Cake\Datasource\RepositoryInterface $object Repository object. <add> * @param array $options The pagination options being used for this request. <add> * @return array An array of options with sort + direction removed and replaced with order if possible. <add> */ <add> public function validateSort(RepositoryInterface $object, array $options) <add> { <add> if (isset($options['sort'])) { <add> $direction = null; <add> if (isset($options['direction'])) { <add> $direction = strtolower($options['direction']); <add> } <add> if (!in_array($direction, ['asc', 'desc'])) { <add> $direction = 'asc'; <add> } <add> $options['order'] = [$options['sort'] => $direction]; <add> } <add> unset($options['sort'], $options['direction']); <add> <add> if (empty($options['order'])) { <add> $options['order'] = []; <add> } <add> if (!is_array($options['order'])) { <add> return $options; <add> } <add> <add> $inWhitelist = false; <add> if (isset($options['sortWhitelist'])) { <add> $field = key($options['order']); <add> $inWhitelist = in_array($field, $options['sortWhitelist'], true); <add> if (!$inWhitelist) { <add> $options['order'] = []; <add> <add> return $options; <add> } <add> } <add> <add> $options['order'] = $this->_prefix($object, $options['order'], $inWhitelist); <add> <add> return $options; <add> } <add> <add> /** <add> * Prefixes the field with the table alias if possible. <add> * <add> * @param \Cake\Datasource\RepositoryInterface $object Repository object. <add> * @param array $order Order array. <add> * @param bool $whitelisted Whether or not the field was whitelisted <add> * @return array Final order array. <add> */ <add> protected function _prefix(RepositoryInterface $object, $order, $whitelisted = false) <add> { <add> $tableAlias = $object->alias(); <add> $tableOrder = []; <add> foreach ($order as $key => $value) { <add> if (is_numeric($key)) { <add> $tableOrder[] = $value; <add> continue; <add> } <add> $field = $key; <add> $alias = $tableAlias; <add> <add> if (strpos($key, '.') !== false) { <add> list($alias, $field) = explode('.', $key); <add> } <add> $correctAlias = ($tableAlias === $alias); <add> <add> if ($correctAlias && $whitelisted) { <add> // Disambiguate fields in schema. As id is quite common. <add> if ($object->hasField($field)) { <add> $field = $alias . '.' . $field; <add> } <add> $tableOrder[$field] = $value; <add> } elseif ($correctAlias && $object->hasField($field)) { <add> $tableOrder[$tableAlias . '.' . $field] = $value; <add> } elseif (!$correctAlias && $whitelisted) { <add> $tableOrder[$alias . '.' . $field] = $value; <add> } <add> } <add> <add> return $tableOrder; <add> } <add> <add> /** <add> * Check the limit parameter and ensure it's within the maxLimit bounds. <add> * <add> * @param array $options An array of options with a limit key to be checked. <add> * @return array An array of options for pagination <add> */ <add> public function checkLimit(array $options) <add> { <add> $options['limit'] = (int)$options['limit']; <add> if (empty($options['limit']) || $options['limit'] < 1) { <add> $options['limit'] = 1; <add> } <add> $options['limit'] = max(min($options['limit'], $options['maxLimit']), 1); <add> <add> return $options; <add> } <add>}
2
Text
Text
remove beta label from netlify plugins
6ca00bfe312c8d3fc5c20d25a9cd8d2741a29332
<ide><path>errors/no-cache.md <ide> cache: <ide> <ide> #### Netlify CI <ide> <del>Use [Netlify Plugins (beta)](https://www.netlify.com/build/plugins-beta/) with [`netlify-plugin-cache-nextjs`](https://www.npmjs.com/package/netlify-plugin-cache-nextjs). <add>Use [Netlify Plugins](https://www.netlify.com/products/build/plugins/) with [`netlify-plugin-cache-nextjs`](https://www.npmjs.com/package/netlify-plugin-cache-nextjs). <ide> <ide> #### AWS CodeBuild <ide>
1
Ruby
Ruby
update to_sql.rb. slightly performance improment
47d89b18aef0125179386274c4445b90f66fa3c9
<ide><path>lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_Values o, collector <ide> collector << quote(value, attr && column_for(attr)).to_s <ide> end <ide> unless i == len <del> collector << ', ' <add> collector << COMMA <ide> end <ide> } <ide>
1
PHP
PHP
fix breaking change
969f1014ec07efba803f887a33fde29e305c9cb1
<ide><path>src/Illuminate/Auth/Notifications/ResetPassword.php <ide> public function via($notifiable) <ide> */ <ide> public function toMail($notifiable) <ide> { <del> $resetUrl = $this->resetUrl($notifiable); <del> <ide> if (static::$toMailCallback) { <del> return call_user_func(static::$toMailCallback, $notifiable, $this->token, $resetUrl); <add> return call_user_func(static::$toMailCallback, $notifiable, $this->token); <ide> } <ide> <del> return $this->buildMailMessage($resetUrl); <add> return $this->buildMailMessage($this->resetUrl($notifiable)); <ide> } <ide> <ide> /**
1
PHP
PHP
fix overwrite() not replacing longer content
938fba08c9135d2e7974a07e2c77dc9652e826e1
<ide><path>src/Console/ConsoleIo.php <ide> public function overwrite($message, $newlines = 1, $size = null) <ide> if ($newlines) { <ide> $this->out($this->nl($newlines), 0); <ide> } <add> <add> // Store length of content + fill so if the new content <add> // is shorter than the old content the next overwrite <add> // will work. <add> if ($fill > 0) { <add> $this->_lastWritten = $newBytes + $fill; <add> } <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Console/ConsoleIoTest.php <ide> public function testOverwrite() <ide> $this->io->overwrite('Less text'); <ide> } <ide> <add> /** <add> * Test overwriting content with shorter content <add> * <add> * @return void <add> */ <add> public function testOverwriteShorterContent() <add> { <add> $number = strlen('12345'); <add> <add> $this->out->expects($this->at(0)) <add> ->method('write') <add> ->with('12345') <add> ->will($this->returnValue($number)); <add> <add> // Backspaces <add> $this->out->expects($this->at(1)) <add> ->method('write') <add> ->with(str_repeat("\x08", $number), 0) <add> ->will($this->returnValue($number)); <add> <add> $this->out->expects($this->at(2)) <add> ->method('write') <add> ->with('123', 0) <add> ->will($this->returnValue(3)); <add> <add> // 2 spaces output to pad up to 5 bytes <add> $this->out->expects($this->at(3)) <add> ->method('write') <add> ->with(str_repeat(' ', $number - 3), 0) <add> ->will($this->returnValue($number - 3)); <add> <add> // Backspaces <add> $this->out->expects($this->at(4)) <add> ->method('write') <add> ->with(str_repeat("\x08", $number), 0) <add> ->will($this->returnValue($number)); <add> <add> $this->out->expects($this->at(5)) <add> ->method('write') <add> ->with('12', 0) <add> ->will($this->returnValue(2)); <add> <add> $this->out->expects($this->at(6)) <add> ->method('write') <add> ->with(str_repeat(' ', $number - 2), 0); <add> <add> $this->io->out('12345'); <add> $this->io->overwrite('123', 0); <add> $this->io->overwrite('12', 0); <add> } <add> <ide> /** <ide> * Tests that setLoggers works properly <ide> *
2
Go
Go
increase coverage of pkg/idtools
00c0ee885c671942f9bc751c80cbc45b7f6404f3
<ide><path>pkg/idtools/idtools_unix_test.go <ide> import ( <ide> "fmt" <ide> "io/ioutil" <ide> "os" <add> "os/user" <ide> "path/filepath" <ide> "testing" <ide> <add> "github.com/gotestyourself/gotestyourself/skip" <add> "github.com/stretchr/testify/assert" <ide> "github.com/stretchr/testify/require" <ide> "golang.org/x/sys/unix" <ide> ) <ide> <add>const ( <add> tempUser = "tempuser" <add>) <add> <ide> type node struct { <ide> uid int <ide> gid int <ide> } <ide> <ide> func TestMkdirAllAs(t *testing.T) { <add> RequiresRoot(t) <ide> dirName, err := ioutil.TempDir("", "mkdirall") <ide> if err != nil { <ide> t.Fatalf("Couldn't create temp dir: %v", err) <ide> func TestMkdirAllAs(t *testing.T) { <ide> } <ide> <ide> func TestMkdirAllAndChownNew(t *testing.T) { <add> RequiresRoot(t) <ide> dirName, err := ioutil.TempDir("", "mkdirnew") <ide> require.NoError(t, err) <ide> defer os.RemoveAll(dirName) <ide> func TestMkdirAllAndChownNew(t *testing.T) { <ide> } <ide> <ide> func TestMkdirAs(t *testing.T) { <del> <add> RequiresRoot(t) <ide> dirName, err := ioutil.TempDir("", "mkdir") <ide> if err != nil { <ide> t.Fatalf("Couldn't create temp dir: %v", err) <ide> func compareTrees(left, right map[string]node) error { <ide> return nil <ide> } <ide> <add>func delUser(t *testing.T, name string) { <add> _, err := execCmd("userdel", name) <add> assert.NoError(t, err) <add>} <add> <ide> func TestParseSubidFileWithNewlinesAndComments(t *testing.T) { <ide> tmpDir, err := ioutil.TempDir("", "parsesubid") <ide> if err != nil { <ide> dockremap:231072:65536` <ide> t.Fatalf("wanted 65536, got %d instead", ranges[0].Length) <ide> } <ide> } <add> <add>func TestGetRootUIDGID(t *testing.T) { <add> uidMap := []IDMap{ <add> { <add> ContainerID: 0, <add> HostID: os.Getuid(), <add> Size: 1, <add> }, <add> } <add> gidMap := []IDMap{ <add> { <add> ContainerID: 0, <add> HostID: os.Getgid(), <add> Size: 1, <add> }, <add> } <add> <add> uid, gid, err := GetRootUIDGID(uidMap, gidMap) <add> assert.NoError(t, err) <add> assert.Equal(t, os.Getegid(), uid) <add> assert.Equal(t, os.Getegid(), gid) <add> <add> uidMapError := []IDMap{ <add> { <add> ContainerID: 1, <add> HostID: os.Getuid(), <add> Size: 1, <add> }, <add> } <add> _, _, err = GetRootUIDGID(uidMapError, gidMap) <add> assert.EqualError(t, err, "Container ID 0 cannot be mapped to a host ID") <add>} <add> <add>func TestToContainer(t *testing.T) { <add> uidMap := []IDMap{ <add> { <add> ContainerID: 2, <add> HostID: 2, <add> Size: 1, <add> }, <add> } <add> <add> containerID, err := toContainer(2, uidMap) <add> assert.NoError(t, err) <add> assert.Equal(t, uidMap[0].ContainerID, containerID) <add>} <add> <add>func TestNewIDMappings(t *testing.T) { <add> RequiresRoot(t) <add> _, _, err := AddNamespaceRangesUser(tempUser) <add> assert.NoError(t, err) <add> defer delUser(t, tempUser) <add> <add> tempUser, err := user.Lookup(tempUser) <add> assert.NoError(t, err) <add> <add> gids, err := tempUser.GroupIds() <add> assert.NoError(t, err) <add> group, err := user.LookupGroupId(string(gids[0])) <add> assert.NoError(t, err) <add> <add> idMappings, err := NewIDMappings(tempUser.Username, group.Name) <add> assert.NoError(t, err) <add> <add> rootUID, rootGID, err := GetRootUIDGID(idMappings.UIDs(), idMappings.GIDs()) <add> assert.NoError(t, err) <add> <add> dirName, err := ioutil.TempDir("", "mkdirall") <add> assert.NoError(t, err, "Couldn't create temp directory") <add> defer os.RemoveAll(dirName) <add> <add> err = MkdirAllAs(dirName, 0700, rootUID, rootGID) <add> assert.NoError(t, err, "Couldn't change ownership of file path. Got error") <add> assert.True(t, CanAccess(dirName, idMappings.RootPair()), fmt.Sprintf("Unable to access %s directory with user UID:%d and GID:%d", dirName, rootUID, rootGID)) <add>} <add> <add>func TestLookupUserAndGroup(t *testing.T) { <add> RequiresRoot(t) <add> uid, gid, err := AddNamespaceRangesUser(tempUser) <add> assert.NoError(t, err) <add> defer delUser(t, tempUser) <add> <add> fetchedUser, err := LookupUser(tempUser) <add> assert.NoError(t, err) <add> <add> fetchedUserByID, err := LookupUID(uid) <add> assert.NoError(t, err) <add> assert.Equal(t, fetchedUserByID, fetchedUser) <add> <add> fetchedGroup, err := LookupGroup(tempUser) <add> assert.NoError(t, err) <add> <add> fetchedGroupByID, err := LookupGID(gid) <add> assert.NoError(t, err) <add> assert.Equal(t, fetchedGroupByID, fetchedGroup) <add>} <add> <add>func TestLookupUserAndGroupThatDoesNotExist(t *testing.T) { <add> fakeUser := "fakeuser" <add> _, err := LookupUser(fakeUser) <add> assert.EqualError(t, err, "getent unable to find entry \""+fakeUser+"\" in passwd database") <add> <add> _, err = LookupUID(-1) <add> assert.Error(t, err) <add> <add> fakeGroup := "fakegroup" <add> _, err = LookupGroup(fakeGroup) <add> assert.EqualError(t, err, "getent unable to find entry \""+fakeGroup+"\" in group database") <add> <add> _, err = LookupGID(-1) <add> assert.Error(t, err) <add>} <add> <add>func RequiresRoot(t *testing.T) { <add> skip.IfCondition(t, os.Getuid() != 0, "skipping test that requires root") <add>}
1
Javascript
Javascript
remove obsolete encoding check
751c92d9728da6f6f86e443783a61253791cfc2f
<ide><path>lib/internal/crypto/util.js <ide> function getDefaultEncoding() { <ide> // This is here because many functions accepted binary strings without <ide> // any explicit encoding in older versions of node, and we don't want <ide> // to break them unnecessarily. <del>function toBuf(str, encoding) { <del> if (typeof str === 'string') { <del> if (encoding === 'buffer' || !encoding) <add>function toBuf(val, encoding) { <add> if (typeof val === 'string') { <add> if (encoding === 'buffer') <ide> encoding = 'utf8'; <del> return Buffer.from(str, encoding); <add> return Buffer.from(val, encoding); <ide> } <del> return str; <add> return val; <ide> } <ide> <ide> const getCiphers = cachedResult(() => filterDuplicateStrings(_getCiphers()));
1
PHP
PHP
support custom urls for aws storage
7a322477934115b86dbd73953d15e61a929246f9
<ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php <ide> public function url($path) <ide> */ <ide> protected function getAwsUrl($adapter, $path) <ide> { <add> $config = $this->driver->getConfig(); <add> <add> // If an explicit base URL has been set on the disk configuration then we will use <add> // it as the base URL instead of the default path. This allows the developer to <add> // have full control over the base path for this filesystem's generated URLs. <add> if (! is_null($url = $config->get('url'))) { <add> return $this->concatPathToUrl($url, $path); <add> } <add> <ide> return $adapter->getClient()->getObjectUrl( <ide> $adapter->getBucket(), $adapter->getPathPrefix().$path <ide> ); <ide> protected function getLocalUrl($path) <ide> // it as the base URL instead of the default path. This allows the developer to <ide> // have full control over the base path for this filesystem's generated URLs. <ide> if ($config->has('url')) { <del> return rtrim($config->get('url'), '/').'/'.ltrim($path, '/'); <add> return $this->concatPathToUrl($config->get('url'), $path); <ide> } <ide> <ide> $path = '/storage/'.$path; <ide> public function getRackspaceTemporaryUrl($adapter, $path, $expiration, $options) <ide> ); <ide> } <ide> <add> /** <add> * Concatenate a path to a URL. <add> * <add> * @param string $url <add> * @param string $path <add> * @return string <add> */ <add> protected function concatPathToUrl($url, $path) <add> { <add> return rtrim($url, '/').'/'.ltrim($path, '/'); <add> } <add> <ide> /** <ide> * Get an array of all files in a directory. <ide> *
1
Ruby
Ruby
add a new constructor that runs load hooks
8121eefc222fbd8979ab70d89725a2e330f5a9b2
<ide><path>railties/lib/rails/application.rb <ide> def instance <ide> super.run_load_hooks! <ide> end <ide> <add> def create(initial_variable_values = {}, &block) <add> new(initial_variable_values, &block).run_load_hooks! <add> end <add> <ide> # Makes the +new+ method public. <ide> # <ide> # Note that Rails::Application inherits from Rails::Engine, which <ide><path>railties/test/application/multiple_applications_test.rb <ide> def test_initialization_of_multiple_copies_of_same_application <ide> end <ide> <ide> def test_initialization_of_application_with_previous_config <del> application1 = AppTemplate::Application.new(config: Rails.application.config) <del> application2 = AppTemplate::Application.new <add> application1 = AppTemplate::Application.create(config: Rails.application.config) <add> application2 = AppTemplate::Application.create <ide> <ide> assert_equal Rails.application.config, application1.config, "Creating a new application while setting an initial config should result in the same config" <ide> assert_not_equal Rails.application.config, application2.config, "New applications without setting an initial config should not have the same config" <ide> end <ide> <ide> def test_initialization_of_application_with_previous_railties <del> application1 = AppTemplate::Application.new(railties: Rails.application.railties) <del> application2 = AppTemplate::Application.new <add> application1 = AppTemplate::Application.create(railties: Rails.application.railties) <add> application2 = AppTemplate::Application.create <ide> <ide> assert_equal Rails.application.railties, application1.railties <ide> assert_not_equal Rails.application.railties, application2.railties <ide> end <ide> <ide> def test_initialize_new_application_with_all_previous_initialization_variables <del> application1 = AppTemplate::Application.new( <add> application1 = AppTemplate::Application.create( <ide> config: Rails.application.config, <ide> railties: Rails.application.railties, <ide> routes_reloader: Rails.application.routes_reloader,
2
Ruby
Ruby
remove explicit return
1b531b7ee2054beadb23853d79b15d588b9ffd88
<ide><path>activerecord/lib/active_record/associations/has_many_association.rb <ide> def count_records <ide> count = [ @reflection.options[:limit], count ].min <ide> end <ide> <del> return count <add> count <ide> end <ide> <ide> def has_cached_counter?
1
Go
Go
send error without headers when using chunks
fe0c0c208c0e816419b668a6fd6567520698c2d2
<ide><path>api.go <ide> func postBuild(srv *Server, version float64, w http.ResponseWriter, r *http.Requ <ide> return err <ide> } <ide> <del> file, _, err := r.FormFile("Dockerfile") <add> dockerfile, _, err := r.FormFile("Dockerfile") <ide> if err != nil { <ide> return err <ide> } <ide> func postBuild(srv *Server, version float64, w http.ResponseWriter, r *http.Requ <ide> } <ide> <ide> b := NewBuildFile(srv, utils.NewWriteFlusher(w)) <del> if _, err := b.Build(file, context); err != nil { <del> return err <add> if _, err := b.Build(dockerfile, context); err != nil { <add> fmt.Fprintf(w, "Error build: %s\n", err) <ide> } <ide> return nil <ide> }
1
Ruby
Ruby
simplify select_one method
19291bff34ce8e36117f07e6e1d546d8ee47529f
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def select_all(arel, name = nil, binds = []) <ide> # Returns a record hash with the column names as keys and column values <ide> # as values. <ide> def select_one(arel, name = nil, binds = []) <del> result = select_all(arel, name, binds) <del> result.first if result <add> select_all(arel, name, binds).first <ide> end <ide> <ide> # Returns a single value from a record
1
Ruby
Ruby
deduplicate multiple values when assigning
29874cc4e220edadfdf50ba93db57d2df396e395
<ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def select(*fields) <ide> end <ide> <ide> def _select!(*fields) # :nodoc: <del> self.select_values += fields <add> self.select_values |= fields <ide> self <ide> end <ide> <ide> def order(*args) <ide> # Same as #order but operates on relation in-place instead of copying. <ide> def order!(*args) # :nodoc: <ide> preprocess_order_args(args) unless args.empty? <del> self.order_values += args <add> self.order_values |= args <ide> self <ide> end <ide> <ide> def reverse_order <ide> end <ide> <ide> def reverse_order! # :nodoc: <del> orders = order_values.uniq <del> orders.compact_blank! <add> orders = order_values.compact_blank <ide> self.order_values = reverse_sql_order(orders) <ide> self <ide> end <ide> def build_joins(manager, aliases) <ide> <ide> def build_select(arel) <ide> if select_values.any? <del> arel.project(*arel_columns(select_values.uniq)) <add> arel.project(*arel_columns(select_values)) <ide> elsif klass.ignored_columns.any? <ide> arel.project(*klass.column_names.map { |field| table[field] }) <ide> else <ide> def does_not_support_reverse?(order) <ide> end <ide> <ide> def build_order(arel) <del> orders = order_values.uniq <del> orders.compact_blank! <del> <add> orders = order_values.compact_blank <ide> arel.order(*orders) unless orders.empty? <ide> end <ide>
1
Javascript
Javascript
unify another duplicated test
93ae5ab1c7055edc455562cbab15cd7e8418612e
<ide><path>packages/ember-glimmer/tests/integration/components/attrs-lookup-test.js <ide> moduleFor('Components test: attrs lookup', class extends RenderingTest { <ide> assert.equal(instance.get('woot'), 'yes', 'component found attr after reset'); <ide> } <ide> <del> // HTMLBars runs `didReceiveAttrs` on `rerender` <del> ['@htmlbars getAttr() should return the same value as get()'](assert) { <del> assert.expect(20); <del> let instance; <del> let FooBarComponent = Component.extend({ <del> init() { <del> this._super(...arguments); <del> instance = this; <del> }, <del> <del> didReceiveAttrs() { <del> let rootFirst = this.get('first'); <del> let rootSecond = this.get('second'); <del> let attrFirst = this.getAttr('first'); <del> let attrSecond = this.getAttr('second'); <del> <del> equal(rootFirst, attrFirst, 'root property matches attrs value'); <del> equal(rootSecond, attrSecond, 'root property matches attrs value'); <del> } <del> }); <del> this.registerComponent('foo-bar', { ComponentClass: FooBarComponent }); <del> <del> this.render(`{{foo-bar first=first second=second}}`, { <del> first: 'first', <del> second: 'second' <del> }); <del> <del> assert.equal(instance.get('first'), 'first', 'matches known value'); <del> assert.equal(instance.get('second'), 'second', 'matches known value'); <del> <del> this.runTask(() => this.rerender()); <del> <del> assert.equal(instance.get('first'), 'first', 'matches known value'); <del> assert.equal(instance.get('second'), 'second', 'matches known value'); <del> <del> this.runTask(() => { <del> set(this.context, 'first', 'third'); <del> }); <del> <del> assert.equal(instance.get('first'), 'third', 'matches known value'); <del> assert.equal(instance.get('second'), 'second', 'matches known value'); <del> <del> this.runTask(() => { <del> set(this.context, 'second', 'fourth'); <del> }); <del> <del> assert.equal(instance.get('first'), 'third', 'matches known value'); <del> assert.equal(instance.get('second'), 'fourth', 'matches known value'); <del> <del> this.runTask(() => { <del> set(this.context, 'first', 'first'); <del> set(this.context, 'second', 'second'); <del> }); <del> <del> assert.equal(instance.get('first'), 'first', 'matches known value'); <del> assert.equal(instance.get('second'), 'second', 'matches known value'); <del> } <add> ['@test getAttr() should return the same value as get()'](assert) { <add> if (this.isGlimmer) { <add> assert.expect(18); <add> } else { <add> // HTMLBars runs `didReceiveAttrs` on `rerender` <add> assert.expect(20); <add> } <ide> <del> ['@glimmer getAttr() should return the same value as get()'](assert) { <del> assert.expect(18); <ide> let instance; <ide> let FooBarComponent = Component.extend({ <ide> init() {
1
Javascript
Javascript
improve assertionerror in case of "errors"
2e8217c64e7bca1e982c82565faa7190cf01c355
<ide><path>lib/internal/errors.js <ide> class AssertionError extends Error { <ide> if (typeof options !== 'object' || options === null) { <ide> throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object'); <ide> } <del> if (options.message) { <del> super(options.message); <add> var { actual, expected, message, operator, stackStartFunction } = options; <add> if (message) { <add> super(message); <ide> } else { <add> if (actual && actual.stack && actual instanceof Error) <add> actual = `${actual.name}: ${actual.message}`; <add> if (expected && expected.stack && expected instanceof Error) <add> expected = `${expected.name}: ${expected.message}`; <ide> if (util === null) util = require('util'); <del> super(`${util.inspect(options.actual).slice(0, 128)} ` + <del> `${options.operator} ${util.inspect(options.expected).slice(0, 128)}`); <add> super(`${util.inspect(actual).slice(0, 128)} ` + <add> `${operator} ${util.inspect(expected).slice(0, 128)}`); <ide> } <ide> <del> this.generatedMessage = !options.message; <add> this.generatedMessage = !message; <ide> this.name = 'AssertionError [ERR_ASSERTION]'; <ide> this.code = 'ERR_ASSERTION'; <del> this.actual = options.actual; <del> this.expected = options.expected; <del> this.operator = options.operator; <del> Error.captureStackTrace(this, options.stackStartFunction); <add> this.actual = actual; <add> this.expected = expected; <add> this.operator = operator; <add> Error.captureStackTrace(this, stackStartFunction); <ide> } <ide> } <ide> <ide><path>test/parallel/test-assert.js <ide> assert.throws(() => { <ide> })); <ide> }); <ide> } <add> <add>common.expectsError( <add> () => assert.strictEqual(new Error('foo'), new Error('foobar')), <add> { <add> code: 'ERR_ASSERTION', <add> type: assert.AssertionError, <add> message: /^'Error: foo' === 'Error: foobar'$/ <add> } <add>);
2
Ruby
Ruby
reduce number of strings a bit
3c21237c37fed9d726bcf2816bf1adc4635f4956
<ide><path>actionpack/lib/action_controller/metal/mime_responds.rb <ide> def respond_to(*mimes, &block) <ide> # 2. <tt>:action</tt> - overwrites the default render action used after an <ide> # unsuccessful html +post+ request. <ide> def respond_with(*resources, &block) <del> raise "In order to use respond_with, first you need to declare the formats your " << <add> raise "In order to use respond_with, first you need to declare the formats your " \ <ide> "controller responds to in the class level" if self.class.mimes_for_respond_to.empty? <ide> <ide> if collector = retrieve_collector_from_mimes(&block) <ide><path>actionpack/lib/action_dispatch/middleware/show_exceptions.rb <ide> module ActionDispatch <ide> # catches the exceptions and returns a FAILSAFE_RESPONSE. <ide> class ShowExceptions <ide> FAILSAFE_RESPONSE = [500, { 'Content-Type' => 'text/plain' }, <del> ["500 Internal Server Error\n" << <del> "If you are the administrator of this website, then please read this web " << <del> "application's log file and/or the web server's log file to find out what " << <add> ["500 Internal Server Error\n" \ <add> "If you are the administrator of this website, then please read this web " \ <add> "application's log file and/or the web server's log file to find out what " \ <ide> "went wrong."]] <ide> <ide> def initialize(app, exceptions_app) <ide><path>activemodel/lib/active_model/validations/clusivity.rb <ide> module ActiveModel <ide> module Validations <ide> module Clusivity #:nodoc: <del> ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " << <add> ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " \ <ide> "and must be supplied as the :in (or :within) option of the configuration hash" <ide> <ide> def check_validity! <ide><path>activemodel/lib/active_model/validations/numericality.rb <ide> def check_validity! <ide> end <ide> <ide> def validate_each(record, attr_name, value) <del> before_type_cast = "#{attr_name}_before_type_cast" <add> before_type_cast = :"#{attr_name}_before_type_cast" <ide> <del> raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast.to_sym) <add> raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast) <ide> raw_value ||= value <ide> <ide> return if options[:allow_nil] && raw_value.nil?
4
Ruby
Ruby
pass section to the constructor
87f29857f0d5a8c862ed90b1740e192d5312c0db
<ide><path>Library/Homebrew/cask/artifact/manpage.rb <ide> module Cask <ide> module Artifact <ide> class Manpage < Symlinked <add> attr_reader :section <add> <ide> def self.from_args(cask, source) <del> section = source.split(".").last <add> section = source.to_s[/\.([1-8]|n|l)$/, 1] <ide> <del> raise CaskInvalidError, "section should be a positive number" unless section.to_i.positive? <add> raise CaskInvalidError, "'#{source}' is not a valid man page name" unless section <ide> <del> new(cask, source) <add> new(cask, source, section) <ide> end <ide> <del> def initialize(cask, source) <del> super <add> def initialize(cask, source, section) <add> @section = section <add> <add> super(cask, source) <ide> end <ide> <ide> def resolve_target(_target) <ide> config.manpagedir.join("man#{section}", target_name) <ide> end <ide> <del> def section <del> @source.extname.downcase[1..-1].to_s.to_i <del> end <del> <ide> def target_name <ide> "#{@source.basename(@source.extname)}.#{section}" <ide> end <ide><path>Library/Homebrew/test/cask/artifact/manpage_spec.rb <ide> let(:cask_token) { "invalid/invalid-manpage-no-section" } <ide> <ide> it "fails to load a cask without section" do <del> expect { cask }.to raise_error(Cask::CaskInvalidError, /section should be a positive number/) <add> expect { cask }.to raise_error(Cask::CaskInvalidError, /is not a valid man page name/) <ide> end <ide> end <ide>
2
Python
Python
use ast.literal_eval in safe_eval
727655193aa9b4d4068650a3f8a9b49a6a2e0cb4
<ide><path>numpy/lib/utils.py <ide> class SafeEval(object): <ide> This includes strings with lists, dicts and tuples using the abstract <ide> syntax tree created by ``compiler.parse``. <ide> <del> For an example of usage, see `safe_eval`. <del> <ide> See Also <ide> -------- <ide> safe_eval <ide> def safe_eval(source): <ide> >>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()') <ide> Traceback (most recent call last): <ide> ... <del> SyntaxError: Unsupported source construct: <class '_ast.Call'> <add> SyntaxError: Unsupported source construct: compiler.ast.CallFunc <ide> <ide> """ <del> # Local imports to speed up numpy's import time. <del> import warnings <add> # Local import to speed up numpy's import time. <ide> import ast <ide> <del> walker = SafeEval() <del> try: <del> res = ast.parse(source, mode="eval") <del> except SyntaxError: <del> raise <del> try: <del> return walker.visit(res) <del> except SyntaxError: <del> raise <del> <add> return ast.literal_eval(source) <ide> #-----------------------------------------------------------------------------
1
Ruby
Ruby
avoid string allocations in backtracecleaner
9a959a0c454448353d2d9c00511a353f874d8d9d
<ide><path>railties/lib/rails/backtrace_cleaner.rb <ide> <ide> module Rails <ide> class BacktraceCleaner < ActiveSupport::BacktraceCleaner <del> APP_DIRS_PATTERN = /^\/?(app|config|lib|test|\(\w*\))/ <add> APP_DIRS_PATTERN = /\A\/?(?:app|config|lib|test|\(\w*\))/ <ide> RENDER_TEMPLATE_PATTERN = /:in `.*_\w+_{2,3}\d+_\d+'/ <del> EMPTY_STRING = "" <del> SLASH = "/" <del> DOT_SLASH = "./" <ide> <ide> def initialize <ide> super <ide> @root = "#{Rails.root}/" <del> add_filter { |line| line.sub(@root, EMPTY_STRING) } <del> add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, EMPTY_STRING) } <del> add_filter { |line| line.sub(DOT_SLASH, SLASH) } # for tests <add> add_filter do |line| <add> line.start_with?(@root) ? line.from(@root.size) : line <add> end <add> add_filter do |line| <add> if RENDER_TEMPLATE_PATTERN.match?(line) <add> line.sub(RENDER_TEMPLATE_PATTERN, "") <add> else <add> line <add> end <add> end <add> add_filter do |line| <add> line.start_with?("./") ? line.from(1) : line <add> end <ide> add_silencer { |line| !APP_DIRS_PATTERN.match?(line) } <ide> end <ide> end
1
Javascript
Javascript
exclude watch test cases
8ddcfb59e5a9a1a301fc8c9a5abe354bfa2d4885
<ide><path>test/RemoveFiles.test.js <ide> const createSingleCompiler = () => { <ide> }; <ide> <ide> describe("RemovedFiles", () => { <add> if (process.env.NO_WATCH_TESTS) { <add> it.skip("watch tests excluded", () => {}); <add> return; <add> } <add> <ide> jest.setTimeout(20000); <ide> <ide> function cleanup() {
1
Ruby
Ruby
remove a redundant test assertion
e49b7dea48e3c5011c8a5cd0256e96251e5798f0
<ide><path>activerecord/test/cases/associations/eager_test.rb <ide> def test_eager_loading_with_conditions_on_joined_table_preloads <ide> assert_equal [posts(:welcome)], posts <ide> assert_equal authors(:david), assert_no_queries { posts[0].author } <ide> <del> posts = assert_queries(2) do <del> Post.all.merge!(select: "distinct posts.*", includes: :author, joins: [:comments], where: "comments.body like 'Thank you%'", order: "posts.id").to_a <del> end <del> assert_equal [posts(:welcome)], posts <del> assert_equal authors(:david), assert_no_queries { posts[0].author } <del> <ide> posts = assert_queries(2) do <ide> Post.all.merge!(includes: :author, joins: { taggings: :tag }, where: "tags.name = 'General'", order: "posts.id").to_a <ide> end
1
Ruby
Ruby
expose inreplace as a class method
4fd63dc4f8670df9b0ded98eb9a30f004069e4b8
<ide><path>Library/Homebrew/cmd/bottle.rb <ide> EOS <ide> <ide> module Homebrew extend self <del> class << self <del> include Utils::Inreplace <del> end <del> <ide> def keg_contains string, keg <ide> if not ARGV.homebrew_developer? <ide> return quiet_system 'fgrep', '--recursive', '--quiet', '--max-count=1', string, keg <ide> def merge <ide> f = Formula.factory formula_name <ide> update_or_add = nil <ide> <del> inreplace f.path do |s| <add> Utils::Inreplace.inreplace(f.path) do |s| <ide> if s.include? 'bottle do' <ide> update_or_add = 'update' <ide> string = s.sub!(/ bottle do.+?end\n/m, output) <ide><path>Library/Homebrew/utils/inreplace.rb <ide> def inreplace paths, before=nil, after=nil <ide> Pathname(path).atomic_write(s) <ide> end <ide> end <add> module_function :inreplace <ide> end <ide> end
2
Text
Text
move upstream information to onboarding doc
dce6d53e6b0c8dfc72eaaf096f7a2ebed775e5b7
<ide><path>doc/onboarding-extras.md <ide> need to be attached anymore, as only important bugfixes will be included. <ide> * Architecture labels <ide> * `arm`, `mips`, `s390`, `ppc` <ide> * No x86{_64}, since that is the implied default <del> <del>## Updating Node.js from Upstream <del> <del>* `git remote add upstream git://github.com/nodejs/node.git` <del> <del>to update from nodejs/node: <del> <del>* `git checkout master` <del>* `git remote update -p` OR `git fetch --all` <del>* `git merge --ff-only upstream/master` (or `REMOTENAME/BRANCH`) <ide><path>doc/onboarding.md <ide> onboarding session. <ide> apply.whitespace fix` <ide> * Always continue to PR from your own GitHub fork <ide> * Branches in the `nodejs/node` repository are only for release lines <del> * See [Updating Node.js from Upstream][] <add> * Add the canonical nodejs repository as `upstream` remote: <add> * `git remote add upstream git://github.com/nodejs/node.git` <add> * To update from `upstream`: <add> * `git checkout master` <add> * `git remote update -p` OR `git fetch --all` <add> * `git merge --ff-only upstream/master` (or `REMOTENAME/BRANCH`) <ide> * Make a new branch for each PR you submit. <ide> * Membership: Consider making your membership in the Node.js GitHub <ide> organization public. This makes it easier to identify Collaborators. <ide> needs to be pointed out separately during the onboarding. <ide> [Publicizing or hiding organization membership]: https://help.github.com/articles/publicizing-or-hiding-organization-membership/ <ide> [set up the credentials]: https://github.com/nodejs/node-core-utils#setting-up-credentials <ide> [two-factor authentication]: https://help.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/ <del>[Updating Node.js from Upstream]: ./onboarding-extras.md#updating-nodejs-from-upstream <ide> [using a TOTP mobile app]: https://help.github.com/articles/configuring-two-factor-authentication-via-a-totp-mobile-app/ <ide> [who-to-cc]: ../COLLABORATOR_GUIDE.md#who-to-cc-in-the-issue-tracker
2
Text
Text
update abort signal in fs promise api example
ceae1b47b771911718d87ffab0f03622634aae25
<ide><path>doc/api/fs.md <ide> import { readFile } from 'fs/promises'; <ide> <ide> try { <ide> const controller = new AbortController(); <del> const signal = controller.signal; <del> readFile(fileName, { signal }); <add> const { signal } = controller; <add> const promise = readFile(fileName, { signal }); <ide> <del> // Abort the request <add> // Abort the request before the promise settles. <ide> controller.abort(); <add> <add> await promise; <ide> } catch (err) { <add> // When a request is aborted - err is an AbortError <ide> console.error(err); <ide> } <ide> ``` <ide> Any specified {FileHandle} has to support reading. <ide> <!-- YAML <ide> added: v10.0.0 <ide> --> <del> <ide> * `path` {string|Buffer|URL} <ide> * `options` {string|Object} <ide> * `encoding` {string} **Default:** `'utf8'` <ide> try { <ide> const controller = new AbortController(); <ide> const { signal } = controller; <ide> const data = new Uint8Array(Buffer.from('Hello Node.js')); <del> writeFile('message.txt', data, { signal }); <add> const promise = writeFile('message.txt', data, { signal }); <add> <add> // Abort the request before the promise settles. <ide> controller.abort(); <add> <add> await promise; <ide> } catch (err) { <ide> // When a request is aborted - err is an AbortError <ide> console.error(err);
1
Python
Python
fix failing test
1c7585a5639970837a3e37b5c87ac8fe0f2ae212
<ide><path>tests/auto/test_tasks.py <ide> def test_vector_clf(self): <ide> model.add(Dense(y_train.shape[-1])) <ide> model.add(Activation('softmax')) <ide> model.compile(loss='categorical_crossentropy', optimizer='rmsprop') <del> history = model.fit(X_train, y_train, nb_epoch=12, batch_size=16, validation_data=(X_test, y_test), show_accuracy=True, verbose=2) <add> history = model.fit(X_train, y_train, nb_epoch=15, batch_size=16, validation_data=(X_test, y_test), show_accuracy=True, verbose=2) <ide> print(history.history) <ide> self.assertTrue(history.history['val_acc'][-1] > 0.9) <ide>
1
Go
Go
handle escapes without swallowing all of them
2dac82eb82b469f94ef26a153d2679663b048ad3
<ide><path>builder/support.go <ide> func (b *Builder) replaceEnv(str string) string { <ide> continue <ide> } <ide> <add> prefix := match[:idx] <ide> stripped := match[idx+2:] <del> str = strings.Replace(str, match, "$"+stripped, -1) <add> str = strings.Replace(str, match, prefix+"$"+stripped, -1) <ide> continue <ide> } <ide> <ide><path>integration-cli/docker_cli_build_test.go <ide> import ( <ide> "github.com/docker/docker/pkg/archive" <ide> ) <ide> <add>func TestBuildHandleEscapes(t *testing.T) { <add> name := "testbuildhandleescapes" <add> <add> defer deleteImages(name) <add> <add> _, err := buildImage(name, <add> ` <add> FROM scratch <add> ENV FOO bar <add> VOLUME ${FOO} <add> `, true) <add> <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> var result map[string]map[string]struct{} <add> <add> res, err := inspectFieldJSON(name, "Config.Volumes") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if err = unmarshalJSON([]byte(res), &result); err != nil { <add> t.Fatal(err) <add> } <add> <add> if _, ok := result["bar"]; !ok { <add> t.Fatal("Could not find volume bar set from env foo in volumes table") <add> } <add> <add> _, err = buildImage(name, <add> ` <add> FROM scratch <add> ENV FOO bar <add> VOLUME \${FOO} <add> `, true) <add> <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> res, err = inspectFieldJSON(name, "Config.Volumes") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if err = unmarshalJSON([]byte(res), &result); err != nil { <add> t.Fatal(err) <add> } <add> <add> if _, ok := result["${FOO}"]; !ok { <add> t.Fatal("Could not find volume ${FOO} set from env foo in volumes table") <add> } <add> <add> // this test in particular provides *7* backslashes and expects 6 to come back. <add> // Like above, the first escape is swallowed and the rest are treated as <add> // literals, this one is just less obvious because of all the character noise. <add> <add> _, err = buildImage(name, <add> ` <add> FROM scratch <add> ENV FOO bar <add> VOLUME \\\\\\\${FOO} <add> `, true) <add> <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> res, err = inspectFieldJSON(name, "Config.Volumes") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if err = unmarshalJSON([]byte(res), &result); err != nil { <add> t.Fatal(err) <add> } <add> <add> if _, ok := result[`\\\\\\${FOO}`]; !ok { <add> t.Fatal(`Could not find volume \\\\\\${FOO} set from env foo in volumes table`) <add> } <add> <add> logDone("build - handle escapes") <add>} <add> <ide> func TestBuildOnBuildLowercase(t *testing.T) { <ide> name := "testbuildonbuildlowercase" <ide> name2 := "testbuildonbuildlowercase2"
2
Text
Text
ignore domains option when loader is set
d33d1dd00a6a7c65ca7158b83c787902afcac237
<ide><path>docs/basic-features/image-optimization.md <ide> In addition to [using properties](/docs/api-reference/next/image.md) available t <ide> ### Domains <ide> <ide> To enable Image Optimization for images hosted on an external website, use an absolute url for the Image `src` and specify which <del>`domains` are allowed to be optimized. This is needed to ensure that external urls can't be abused. <add>`domains` are allowed to be optimized. This is needed to ensure that external urls can't be abused. When `loader` is set to an external image service, this option is ignored. <ide> <ide> ```js <ide> module.exports = {
1
Javascript
Javascript
fix modal auto-submitting
2186f360678bbc5ee6f73e8d4d379dce10402421
<ide><path>client/commonFramework.js <ide> var testSuccess = function() { <ide> function ctrlEnterClickHandler(e) { <ide> // ctrl + enter <ide> if (e.ctrlKey && e.keyCode === 13) { <add> $('#complete-courseware-dialog').off('keydown', ctrlEnterClickHandler); <ide> $('#submit-challenge').click(); <ide> } <ide> } <ide> function showCompletion() { <ide> var bonfireSolution = myCodeMirror.getValue(); <ide> var didCompleteWith = $('#completed-with').val() || null; <ide> <del> <ide> $('#complete-courseware-dialog').modal('show'); <ide> $('#complete-courseware-dialog .modal-header').click(); <ide> <del> $('#complete-courseware-dialog').keyup(function(e) { <del> // ctrl + enter <del> if (e.ctrlKey && e.keyCode === 13) { <del> $('#submit-challenge').click(); <del> } <del> }); <del> <ide> $('#submit-challenge').click(function(e) { <ide> e.preventDefault(); <ide> <ide> $(document).ready(function() { <ide> <ide> // init modal keybindings on open <ide> $('#complete-courseware-dialog').on('shown.bs.modal', function() { <del> $('#complete-courseware-dialog').keyup(ctrlEnterClickHandler); <add> $('#complete-courseware-dialog').keydown(ctrlEnterClickHandler); <ide> }); <ide> <ide> // remove modal keybinds on close <ide> $('#complete-courseware-dialog').on('hidden.bs.modal', function() { <del> $('#complete-courseware-dialog').unbind('keyup', ctrlEnterClickHandler); <add> $('#complete-courseware-dialog').off('keydown', ctrlEnterClickHandler); <ide> }); <ide> <ide> var $preview = $('#preview');
1
PHP
PHP
handle optgroups with integer values better
3d6eb08e0c34477661a94eebf49b576ea488aa6e
<ide><path>src/View/Widget/SelectBoxWidget.php <ide> protected function _renderOptions($options, $disabled, $selected, $escape) <ide> // Option groups <ide> $arrayVal = (is_array($val) || $val instanceof Traversable); <ide> if ((!is_int($key) && $arrayVal) || <del> (is_int($key) && $arrayVal && isset($val['options'])) <add> (is_int($key) && $arrayVal && (isset($val['options']) || !isset($val['value']))) <ide> ) { <ide> $out[] = $this->_renderOptgroup($key, $val, $disabled, $selected, $escape); <ide> continue; <ide> protected function _renderOptions($options, $disabled, $selected, $escape) <ide> 'value' => $key, <ide> 'text' => $val, <ide> ]; <del> if (is_array($val) && isset($optAttrs['text'], $optAttrs['value'])) { <add> if (is_array($val) && isset($val['text'], $val['value'])) { <ide> $optAttrs = $val; <ide> $key = $optAttrs['value']; <ide> } <ide><path>tests/TestCase/View/Widget/SelectBoxWidgetTest.php <ide> public function testRenderOptionGroups() <ide> $this->assertHtml($expected, $result); <ide> } <ide> <add> /** <add> * test rendering with numeric option group keys <add> * <add> * @return void <add> */ <add> public function testRenderOptionGroupsIntegerKeys() <add> { <add> $select = new SelectBoxWidget($this->templates); <add> $data = [ <add> 'name' => 'Year[key]', <add> 'options' => [ <add> 2014 => [ <add> 'key' => 'value' <add> ], <add> 2013 => [ <add> 'text' => '2013-text', <add> 'options' => [ <add> 'key2' => 'value2' <add> ] <add> ] <add> ] <add> ]; <add> $result = $select->render($data, $this->context); <add> $expected = [ <add> 'select' => [ <add> 'name' => 'Year[key]', <add> ], <add> ['optgroup' => ['label' => '2014']], <add> ['option' => ['value' => 'key']], <add> 'value', <add> '/option', <add> '/optgroup', <add> ['optgroup' => ['label' => '2013-text']], <add> ['option' => ['value' => 'key2']], <add> 'value2', <add> '/option', <add> '/optgroup', <add> '/select' <add> ]; <add> $this->assertHtml($expected, $result); <add> } <add> <ide> /** <ide> * test rendering with option groups and escaping <ide> *
2
Javascript
Javascript
fix code comment at `ember.textfield`
ef48e0fbcad620406bd5201cc6381332ff985ec8
<ide><path>packages/ember-handlebars/lib/controls/text_field.js <ide> Ember.TextField = Ember.View.extend(Ember.TextSupport, <ide> * `enter`: the user pressed enter <ide> * `keypress`: the user pressed a key <ide> <del> @property on <add> @property onEvent <ide> @type String <ide> @default enter <ide> */
1
Python
Python
add decode function to base16.py
6fcefc04535357776124806f0fac40c005b35d1a
<ide><path>ciphers/base16.py <ide> def encode_to_b16(inp: str) -> bytes: <ide> """ <ide> Encodes a given utf-8 string into base-16. <add> <ide> >>> encode_to_b16('Hello World!') <ide> b'48656C6C6F20576F726C6421' <ide> >>> encode_to_b16('HELLO WORLD!') <ide> b'48454C4C4F20574F524C4421' <ide> >>> encode_to_b16('') <ide> b'' <ide> """ <del> encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) <del> b16encoded = base64.b16encode(encoded) # b16encoded the encoded string <del> return b16encoded <add> # encode the input into a bytes-like object and then encode b16encode that <add> return base64.b16encode(inp.encode("utf-8")) <add> <add> <add>def decode_from_b16(b16encoded: bytes) -> str: <add> """ <add> Decodes from base-16 to a utf-8 string. <add> <add> >>> decode_from_b16(b'48656C6C6F20576F726C6421') <add> 'Hello World!' <add> >>> decode_from_b16(b'48454C4C4F20574F524C4421') <add> 'HELLO WORLD!' <add> >>> decode_from_b16(b'') <add> '' <add> """ <add> # b16decode the input into bytes and decode that into a human readable string <add> return base64.b16decode(b16encoded).decode("utf-8") <ide> <ide> <ide> if __name__ == "__main__":
1
Java
Java
allow registration of rsocket metadata extractors
848804a22713e36b6198c3bed2f3d94827e4ee70
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultMetadataExtractor.java <ide> * @author Rossen Stoyanchev <ide> * @since 5.2 <ide> */ <del>public class DefaultMetadataExtractor implements MetadataExtractor { <add>public class DefaultMetadataExtractor implements MetadataExtractor, MetadataExtractorRegistry { <ide> <ide> private final List<Decoder<?>> decoders; <ide> <ide> public List<? extends Decoder<?>> getDecoders() { <ide> return this.decoders; <ide> } <ide> <del> <del> /** <del> * Decode metadata entries with the given {@link MimeType} to the specified <del> * target class, and store the decoded value in the output map under the <del> * given name. <del> * @param mimeType the mime type of metadata entries to extract <del> * @param targetType the target value type to decode to <del> * @param name assign a name for the decoded value; if not provided, then <del> * the mime type is used as the key <del> */ <del> public void metadataToExtract(MimeType mimeType, Class<?> targetType, @Nullable String name) { <del> String key = name != null ? name : mimeType.toString(); <del> metadataToExtract(mimeType, targetType, (value, map) -> map.put(key, value)); <del> } <del> <del> /** <del> * Variant of {@link #metadataToExtract(MimeType, Class, String)} that accepts <del> * {@link ParameterizedTypeReference} instead of {@link Class} for <del> * specifying a target type with generic parameters. <del> * @param mimeType the mime type of metadata entries to extract <del> * @param targetType the target value type to decode to <del> */ <del> public void metadataToExtract( <del> MimeType mimeType, ParameterizedTypeReference<?> targetType, @Nullable String name) { <del> <del> String key = name != null ? name : mimeType.toString(); <del> metadataToExtract(mimeType, targetType, (value, map) -> map.put(key, value)); <del> } <del> <del> /** <del> * Variant of {@link #metadataToExtract(MimeType, Class, String)} that allows <del> * custom logic to be used to map the decoded value to any number of values <del> * in the output map. <del> * @param mimeType the mime type of metadata entries to extract <del> * @param targetType the target value type to decode to <del> * @param mapper custom logic to add the decoded value to the output map <del> * @param <T> the target value type <del> */ <add> @Override <ide> public <T> void metadataToExtract( <ide> MimeType mimeType, Class<T> targetType, BiConsumer<T, Map<String, Object>> mapper) { <ide> <ide> registerMetadata(mimeType, ResolvableType.forClass(targetType), mapper); <ide> } <ide> <del> /** <del> * Variant of {@link #metadataToExtract(MimeType, Class, BiConsumer)} that <del> * accepts {@link ParameterizedTypeReference} instead of {@link Class} for <del> * specifying a target type with generic parameters. <del> * @param mimeType the mime type of metadata entries to extract <del> * @param type the target value type to decode to <del> * @param mapper custom logic to add the decoded value to the output map <del> * @param <T> the target value type <del> */ <add> @Override <ide> public <T> void metadataToExtract( <ide> MimeType mimeType, ParameterizedTypeReference<T> type, BiConsumer<T, Map<String, Object>> mapper) { <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketStrategies.java <ide> * Default implementation of {@link RSocketStrategies}. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Brian Clozel <ide> * @since 5.2 <ide> */ <ide> final class DefaultRSocketStrategies implements RSocketStrategies { <ide> static class DefaultRSocketStrategiesBuilder implements RSocketStrategies.Builde <ide> @Nullable <ide> private MetadataExtractor metadataExtractor; <ide> <add> private final List<Consumer<MetadataExtractorRegistry>> metadataExtractors = new ArrayList<>(); <add> <ide> DefaultRSocketStrategiesBuilder() { <ide> this.encoders.add(CharSequenceEncoder.allMimeTypes()); <ide> this.encoders.add(new ByteBufferEncoder()); <ide> public Builder metadataExtractor(@Nullable MetadataExtractor metadataExtractor) <ide> return this; <ide> } <ide> <add> @Override <add> public Builder metadataExtractors(Consumer<MetadataExtractorRegistry> consumer) { <add> this.metadataExtractors.add(consumer); <add> return this; <add> } <add> <ide> @Override <ide> public RSocketStrategies build() { <ide> RouteMatcher matcher = (this.routeMatcher != null ? this.routeMatcher : initRouteMatcher()); <ide> public RSocketStrategies build() { <ide> MetadataExtractor extractor = (this.metadataExtractor != null ? <ide> this.metadataExtractor : new DefaultMetadataExtractor(this.decoders)); <ide> <add> if (extractor instanceof MetadataExtractorRegistry) { <add> this.metadataExtractors.forEach(consumer -> consumer.accept((MetadataExtractorRegistry) extractor)); <add> } <add> <ide> return new DefaultRSocketStrategies( <ide> this.encoders, this.decoders, matcher, registry, factory, extractor); <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataExtractor.java <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 5.2 <add> * @see MetadataExtractorRegistry <ide> */ <ide> public interface MetadataExtractor { <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataExtractorRegistry.java <add>/* <add> * Copyright 2002-2019 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket; <add> <add>import java.util.Map; <add>import java.util.function.BiConsumer; <add> <add>import org.springframework.core.ParameterizedTypeReference; <add>import org.springframework.lang.Nullable; <add>import org.springframework.util.MimeType; <add> <add>/** <add> * Stores registrations of extractors for metadata entries. <add> * Each metadata entry is decoded based on its {@code MimeType} and a name <add> * is assigned to the decoded value. <add> * <add> * @author Rossen Stoyanchev <add> * @author Brian Clozel <add> * @since 5.2 <add> * @see MetadataExtractor <add> */ <add>public interface MetadataExtractorRegistry { <add> <add> /** <add> * Decode metadata entries with the given {@link MimeType} to the specified <add> * target class, and store the decoded value in the output map under the <add> * given name. <add> * @param mimeType the mime type of metadata entries to extract <add> * @param targetType the target value type to decode to <add> * @param name assign a name for the decoded value; if not provided, then <add> * the mime type is used as the key <add> */ <add> default void metadataToExtract(MimeType mimeType, Class<?> targetType, @Nullable String name) { <add> String key = name != null ? name : mimeType.toString(); <add> metadataToExtract(mimeType, targetType, (value, map) -> map.put(key, value)); <add> } <add> <add> /** <add> * Variant of {@link #metadataToExtract(MimeType, Class, String)} that accepts <add> * {@link ParameterizedTypeReference} instead of {@link Class} for <add> * specifying a target type with generic parameters. <add> * @param mimeType the mime type of metadata entries to extract <add> * @param targetType the target value type to decode to <add> */ <add> default void metadataToExtract( <add> MimeType mimeType, ParameterizedTypeReference<?> targetType, @Nullable String name) { <add> <add> String key = name != null ? name : mimeType.toString(); <add> metadataToExtract(mimeType, targetType, (value, map) -> map.put(key, value)); <add> } <add> <add> /** <add> * Variant of {@link #metadataToExtract(MimeType, Class, String)} that allows <add> * custom logic to be used to map the decoded value to any number of values <add> * in the output map. <add> * @param mimeType the mime type of metadata entries to extract <add> * @param targetType the target value type to decode to <add> * @param mapper custom logic to add the decoded value to the output map <add> * @param <T> the target value type <add> */ <add> <T> void metadataToExtract( <add> MimeType mimeType, Class<T> targetType, BiConsumer<T, Map<String, Object>> mapper); <add> <add> /** <add> * Variant of {@link #metadataToExtract(MimeType, Class, BiConsumer)} that <add> * accepts {@link ParameterizedTypeReference} instead of {@link Class} for <add> * specifying a target type with generic parameters. <add> * @param mimeType the mime type of metadata entries to extract <add> * @param type the target value type to decode to <add> * @param mapper custom logic to add the decoded value to the output map <add> * @param <T> the target value type <add> */ <add> <T> void metadataToExtract( <add> MimeType mimeType, ParameterizedTypeReference<T> type, BiConsumer<T, Map<String, Object>> mapper); <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketStrategies.java <ide> interface Builder { <ide> */ <ide> Builder metadataExtractor(@Nullable MetadataExtractor metadataExtractor); <ide> <add> /** <add> * Apply the consumer to the {@link MetadataExtractorRegistry} in order <add> * to register extra metadata entry extractors. <add> */ <add> Builder metadataExtractors(Consumer<MetadataExtractorRegistry> extractorRegistry); <add> <ide> /** <ide> * Build the {@code RSocketStrategies} instance. <ide> */ <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketStrategiesTests.java <ide> */ <ide> package org.springframework.messaging.rsocket; <ide> <add>import java.util.function.Consumer; <add> <ide> import org.junit.jupiter.api.Test; <ide> <ide> import org.springframework.core.ReactiveAdapterRegistry; <ide> import org.springframework.util.SimpleRouteMatcher; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <add>import static org.mockito.ArgumentMatchers.any; <add>import static org.mockito.Mockito.mock; <add>import static org.mockito.Mockito.times; <add>import static org.mockito.Mockito.verify; <ide> <ide> /** <ide> * Unit tests for {@link RSocketStrategies}. <ide> * @author Rossen Stoyanchev <ide> * @since 5.2 <ide> */ <del>public class DefaultRSocketStrategiesTests { <add>class DefaultRSocketStrategiesTests { <ide> <ide> @Test <del> public void defaultSettings() { <add> void defaultSettings() { <ide> RSocketStrategies strategies = RSocketStrategies.create(); <ide> <ide> assertThat(strategies.encoders()).hasSize(4).hasOnlyElementsOfTypes( <ide> public void defaultSettings() { <ide> } <ide> <ide> @Test <del> public void explicitValues() { <del> <add> void explicitValues() { <ide> SimpleRouteMatcher matcher = new SimpleRouteMatcher(new AntPathMatcher()); <ide> DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(); <ide> ReactiveAdapterRegistry registry = new ReactiveAdapterRegistry(); <ide> public void explicitValues() { <ide> } <ide> <ide> @Test <del> public void copyConstructor() { <add> void copyConstructor() { <ide> RSocketStrategies strategies1 = RSocketStrategies.create(); <ide> RSocketStrategies strategies2 = strategies1.mutate().build(); <ide> <ide> public void copyConstructor() { <ide> assertThat(strategies1.reactiveAdapterRegistry()).isSameAs(strategies2.reactiveAdapterRegistry()); <ide> } <ide> <add> @Test <add> @SuppressWarnings("unchecked") <add> void applyMetadataExtractors() { <add> Consumer<MetadataExtractorRegistry> consumer = (Consumer<MetadataExtractorRegistry>) mock(Consumer.class); <add> RSocketStrategies strategies = RSocketStrategies.builder().metadataExtractors(consumer).build(); <add> verify(consumer, times(1)).accept(any()); <add> } <add> <ide> }
6
Javascript
Javascript
render error as errorhtml
8e55adf4ecf35d1edb105b2817a42d144645d46c
<ide><path>server/render.js <ide> async function doRender (req, res, pathname, query, { <ide> let html <ide> let head <ide> let errorHtml = '' <add> <ide> try { <del> html = render(app) <add> if (err && dev) { <add> errorHtml = render(createElement(ErrorDebug, { error: err })) <add> } else if (err) { <add> errorHtml = render(app) <add> } else { <add> html = render(app) <add> } <ide> } finally { <ide> head = Head.rewind() || defaultHead() <ide> } <ide> const chunks = loadChunks({ dev, dir, dist, availableChunks }) <ide> <del> if (err && dev) { <del> errorHtml = render(createElement(ErrorDebug, { error: err })) <del> } <del> <ide> return { html, head, errorHtml, chunks } <ide> } <ide>
1
Javascript
Javascript
add missing semicolon
fc65d29dda72776d960529bab3fe6a547fb77615
<ide><path>lib/DelegatedModule.js <ide> class DelegatedModule extends Module { <ide> str += `[${JSON.stringify(this.request)}]`; <ide> break; <ide> } <add> <add> str += ";"; <ide> } <ide> <ide> if(this.useSourceMap) {
1
Python
Python
improve tensorboard callback tests
5656e39f0fb9fea23376a297175fd4cfa58b36ef
<ide><path>keras/callbacks.py <ide> def set_model(self, model): <ide> self.sess = K.get_session() <ide> if self.histogram_freq and self.merged is None: <ide> for layer in self.model.layers: <del> <del> for weight in layer.trainable_weights: <add> for weight in layer.weights: <ide> mapped_weight_name = weight.name.replace(':', '_') <ide> tf.summary.histogram(mapped_weight_name, weight) <ide> if self.write_grads: <ide><path>tests/keras/test_callbacks.py <ide> from keras import callbacks <ide> from keras.models import Sequential, Model <ide> from keras.layers import Input, Dense, Dropout, add, dot, Lambda, Layer <del>from keras.layers.convolutional import Conv2D <del>from keras.layers.pooling import MaxPooling2D <del>from keras.layers.pooling import GlobalAveragePooling1D <del>from keras.layers.pooling import GlobalAveragePooling2D <add>from keras.layers import Conv2D <add>from keras.layers import MaxPooling2D <add>from keras.layers import GlobalAveragePooling1D <add>from keras.layers import GlobalAveragePooling2D <add>from keras.layers import BatchNormalization <ide> from keras.utils.test_utils import get_test_data <ide> from keras.utils.generic_utils import to_list <ide> from keras.utils.generic_utils import unpack_singleton <ide> def __call__(self, y_true, y_pred): <ide> inp = Input((input_dim,)) <ide> hidden = Dense(num_hidden, activation='relu')(inp) <ide> hidden = Dropout(0.1)(hidden) <add> hidden = BatchNormalization()(hidden) <ide> output = Dense(num_classes, activation='softmax')(hidden) <ide> model = Model(inputs=inp, outputs=output) <ide> model.compile(loss='categorical_crossentropy',
2
Javascript
Javascript
add support for {{input type="checkbox"}}
cb648d37cce2efeda180e08b374a0d2eaadd226c
<ide><path>packages/ember-handlebars/lib/controls.js <ide> Ember.Handlebars.registerHelper('input', function(options) { <ide> <ide> normalizeHash(hash, types); <ide> <del> return Ember.Handlebars.helpers.view.call(this, Ember.TextField, options); <add> if (inputType === 'checkbox') { <add> return Ember.Handlebars.helpers.view.call(this, Ember.Checkbox, options); <add> } else { <add> return Ember.Handlebars.helpers.view.call(this, Ember.TextField, options); <add> } <ide> }); <ide>\ No newline at end of file <ide><path>packages/ember-handlebars/tests/controls/checkbox_test.js <del>var get = Ember.get, set = Ember.set, <del> isInternetExplorer = window.navigator.userAgent.match(/msie/i), <del> checkboxView, dispatcher; <add>var get = Ember.get, set = function(obj, key, value) { <add> Ember.run(function() { Ember.set(obj, key, value); }); <add>}; <add> <add>var isInternetExplorer = window.navigator.userAgent.match(/msie/i), <add> checkboxView, dispatcher, controller; <add> <add> <add>var compile = Ember.Handlebars.compile; <add> <add>function destroy(view) { <add> Ember.run(function() { <add> view.destroy(); <add> }); <add>} <add> <add>module("{{input type='checkbox'}}", { <add> setup: function() { <add> controller = { <add> tab: 6, <add> name: 'hello', <add> val: false <add> }; <add> <add> checkboxView = Ember.View.extend({ <add> controller: controller, <add> template: compile('{{input type="checkbox" disabled=disabled tabindex=tab name=name checked=val}}') <add> }).create(); <add> <add> append(); <add> }, <add> <add> teardown: function() { <add> destroy(checkboxView); <add> } <add>}); <add> <add>test("should append a checkbox", function() { <add> equal(checkboxView.$('input[type=checkbox]').length, 1, "A single checkbox is added"); <add>}); <add> <add>test("should begin disabled if the disabled attribute is true", function() { <add> equal(checkboxView.$('input[type=checkbox]:disabled').length, 0, "The checkbox isn't disabled"); <add> set(controller, 'disabled', true); <add> equal(checkboxView.$('input[type=checkbox]:disabled').length, 1, "The checkbox is now disabled"); <add>}); <add> <add>test("should support the tabindex property", function() { <add> equal(checkboxView.$('input').prop('tabindex'), '6', 'the initial checkbox tabindex is set in the DOM'); <add> set(controller, 'tab', 3); <add> equal(checkboxView.$('input').prop('tabindex'), '3', 'the checkbox tabindex changes when it is changed in the view'); <add>}); <add> <add>test("checkbox name is updated", function() { <add> equal(checkboxView.$('input').attr('name'), "hello", "renders checkbox with the name"); <add> set(controller, 'name', 'bye'); <add> equal(checkboxView.$('input').attr('name'), "bye", "updates checkbox after name changes"); <add>}); <add> <add>test("checkbox checked property is updated", function() { <add> equal(checkboxView.$('input').prop('checked'), false, "the checkbox isn't checked yet"); <add> set(controller, 'val', true); <add> equal(checkboxView.$('input').prop('checked'), true, "the checkbox is checked now"); <add>}); <add> <add>module("{{input type='checkbox'}} - static values", { <add> setup: function() { <add> controller = { <add> tab: 6, <add> name: 'hello', <add> val: false <add> }; <add> <add> checkboxView = Ember.View.extend({ <add> controller: controller, <add> template: compile('{{input type="checkbox" disabled=true tabindex=6 name="hello" checked=false}}') <add> }).create(); <add> <add> append(); <add> }, <add> <add> teardown: function() { <add> destroy(checkboxView); <add> } <add>}); <add> <add>test("should begin disabled if the disabled attribute is true", function() { <add> equal(checkboxView.$('input[type=checkbox]:disabled').length, 1, "The checkbox isn't disabled"); <add>}); <add> <add>test("should support the tabindex property", function() { <add> equal(checkboxView.$('input').prop('tabindex'), '6', 'the initial checkbox tabindex is set in the DOM'); <add>}); <add> <add>test("checkbox name is updated", function() { <add> equal(checkboxView.$('input').attr('name'), "hello", "renders checkbox with the name"); <add>}); <add> <add>test("checkbox checked property is updated", function() { <add> equal(checkboxView.$('input').prop('checked'), false, "the checkbox isn't checked yet"); <add>}); <ide> <ide> module("Ember.Checkbox", { <ide> setup: function() { <ide> dispatcher = Ember.EventDispatcher.create(); <ide> dispatcher.setup(); <ide> }, <add> <ide> teardown: function() { <ide> Ember.run(function() { <ide> dispatcher.destroy();
2
PHP
PHP
add validation guess for not null + text types
70bb839de9fde351cb2a1379fe8b89788204fe36
<ide><path>lib/Cake/Console/Command/Task/ModelTask.php <ide> public function fieldValidation($fieldName, $metaData, $primaryKey = 'id') { <ide> $guess = $methods['uuid']; <ide> } elseif ($metaData['type'] == 'string') { <ide> $guess = $methods['notempty']; <add> } elseif ($metaData['type'] == 'text') { <add> $guess = $methods['notempty']; <ide> } elseif ($metaData['type'] == 'integer') { <ide> $guess = $methods['numeric']; <ide> } elseif ($metaData['type'] == 'boolean') {
1
Ruby
Ruby
restore some things to failed install config dump
a8c05c9772636b334aa2421ac830a0212d919c74
<ide><path>Library/Homebrew/cmd/--config.rb <ide> def describe_clt <ide> @describe_clt ||= if MacOS.clt_installed? then MacOS.clt_version else 'N/A' end <ide> end <ide> <del> def sha <del> sha = HOMEBREW_REPOSITORY.cd do <add> def head <add> head = HOMEBREW_REPOSITORY.cd do <ide> `git rev-parse --verify -q HEAD 2>/dev/null`.chomp <ide> end <del> if sha.empty? then "(none)" else sha end <add> if head.empty? then "(none)" else head end <ide> end <ide> <ide> def describe_path path <ide> def kernel <ide> <ide> # we try to keep output minimal <ide> def dump_build_config <add> puts "HOMEBREW_VERSION: #{HOMEBREW_VERSION}" <add> puts "HEAD: #{head}" <ide> puts "HOMEBREW_PREFIX: #{HOMEBREW_PREFIX}" if HOMEBREW_PREFIX.to_s != "/usr/local" <ide> puts "HOMEBREW_CELLAR: #{HOMEBREW_CELLAR}" if HOMEBREW_CELLAR.to_s != "#{HOMEBREW_PREFIX}/Cellar" <ide> puts hardware <ide> puts "OS X: #{MACOS_FULL_VERSION}-#{kernel}" <ide> puts "Xcode: #{describe_xcode}" <add> puts "CLT: #{describe_clt}" if MacOS.xcode_version.to_f >= 4.3 <ide> puts "/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby:\n #{RUBY_VERSION}-#{RUBY_PATCHLEVEL}" if RUBY_VERSION.to_f != 1.8 <ide> <ide> unless MacOS.compilers_standard? <ide> def dump_build_config <ide> def config_s <ide> config_s = <<-EOS.undent <ide> HOMEBREW_VERSION: #{HOMEBREW_VERSION} <del> HEAD: #{sha} <add> HEAD: #{head} <ide> HOMEBREW_PREFIX: #{HOMEBREW_PREFIX} <ide> HOMEBREW_CELLAR: #{HOMEBREW_CELLAR} <ide> #{hardware}
1
Ruby
Ruby
do real transformations in a safe way
76395e3c1b997da7b3853b1b3e94b712b1a29ecf
<ide><path>lib/active_storage/variant.rb <ide> require "active_storage/blob" <add>require "active_support/core_ext/object/inclusion" <ide> require "mini_magick" <ide> <ide> class ActiveStorage::Variant <ide> class_attribute :verifier <ide> <add> ALLOWED_TRANSFORMATIONS = %i( <add> resize rotate format flip fill monochrome orient quality roll scale sharpen shave shear size thumbnail <add> transparent transpose transverse trim background bordercolor compress crop <add> ) <add> <ide> attr_reader :blob, :variation <ide> delegate :service, to: :blob <ide> <ide> def upload_variant(variation) <ide> end <ide> <ide> def transform(io) <del> # FIXME: Actually do a variant based on the variation <del> File.open MiniMagick::Image.read(io).resize("500x500").path <add> File.open \ <add> MiniMagick::Image.read(io).tap { |transforming_image| <add> variation.each do |(method, argument)| <add> if method = allowed_transformational_method(method.to_sym) <add> if argument.present? <add> transforming_image.public_send(method, argument) <add> else <add> transforming_image.public_send(method) <add> end <add> end <add> end <add> }.path <ide> end <ide> <del> def exist? <del> service.exist?(key) <add> def allowed_transformational_method(method) <add> method.presence_in(ALLOWED_TRANSFORMATIONS) <ide> end <ide> end
1
Javascript
Javascript
move work to compile fn
bdd853cb83839eef9901af164293611eaa23ee2c
<ide><path>src/ng/directive/ngRepeat.js <ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { <ide> priority: 1000, <ide> terminal: true, <ide> $$tlb: true, <del> link: function($scope, $element, $attr, ctrl, $transclude){ <del> var expression = $attr.ngRepeat; <del> var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/), <del> trackByExp, trackByExpGetter, aliasAs, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn, <del> lhs, rhs, valueIdentifier, keyIdentifier, <del> hashFnLocals = {$id: hashKey}; <add> compile: function ngRepeatCompile($element, $attr) { <add> var expression = $attr.ngRepeat; <add> var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' '); <ide> <del> var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' '); <add> var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); <ide> <del> if (!match) { <del> throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", <add> if (!match) { <add> throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", <ide> expression); <del> } <add> } <ide> <del> lhs = match[1]; <del> rhs = match[2]; <del> aliasAs = match[3]; <del> trackByExp = match[4]; <add> var lhs = match[1]; <add> var rhs = match[2]; <add> var aliasAs = match[3]; <add> var trackByExp = match[4]; <ide> <del> if (trackByExp) { <del> trackByExpGetter = $parse(trackByExp); <add> match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); <add> <add> if (!match) { <add> throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", <add> lhs); <add> } <add> var valueIdentifier = match[3] || match[1]; <add> var keyIdentifier = match[2]; <add> <add> var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn; <add> var hashFnLocals = {$id: hashKey}; <add> <add> if (trackByExp) { <add> trackByExpGetter = $parse(trackByExp); <add> } else { <add> trackByIdArrayFn = function (key, value) { <add> return hashKey(value); <add> }; <add> trackByIdObjFn = function (key) { <add> return key; <add> }; <add> } <add> <add> return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) { <add> <add> if (trackByExpGetter) { <ide> trackByIdExpFn = function(key, value, index) { <ide> // assign key, value, and $index to the locals so that they can be used in hash functions <ide> if (keyIdentifier) hashFnLocals[keyIdentifier] = key; <ide> hashFnLocals[valueIdentifier] = value; <ide> hashFnLocals.$index = index; <ide> return trackByExpGetter($scope, hashFnLocals); <ide> }; <del> } else { <del> trackByIdArrayFn = function(key, value) { <del> return hashKey(value); <del> }; <del> trackByIdObjFn = function(key) { <del> return key; <del> }; <del> } <del> <del> match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); <del> if (!match) { <del> throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", <del> lhs); <ide> } <del> valueIdentifier = match[3] || match[1]; <del> keyIdentifier = match[2]; <ide> <ide> // Store a list of elements from previous run. This is a hash where key is the item from the <ide> // iterator, and the value is objects with following properties. <ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { <ide> } <ide> lastBlockMap = nextBlockMap; <ide> }); <add> }; <ide> } <ide> }; <ide>
1
Javascript
Javascript
add source for three.extend method
baa928e5814f9170346d14088e711a26d1376b68
<ide><path>src/Three.js <ide> String.prototype.trim = String.prototype.trim || function () { <ide> <ide> }; <ide> <del> <add>// based on http://stackoverflow.com/a/12317051 <ide> THREE.extend = function ( target, other ) { <ide> <ide> target = target || {}; <ide> THREE.extend = function ( target, other ) { <ide> } <ide> <ide> return target; <del> <add> <ide> }; <ide> <ide> // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
1
Go
Go
use args in cobra.command to validate args
fc5a4514fbe1b402d2a0bff170486ac3de4bf8cc
<ide><path>api/client/volume/cmd.go <ide> func NewVolumeCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> cmd := &cobra.Command{ <ide> Use: "volume", <ide> Short: "Manage Docker volumes", <del> // TODO: remove once cobra is patched to handle this <del> RunE: func(cmd *cobra.Command, args []string) error { <del> fmt.Fprintf(dockerCli.Err(), "\n%s", cmd.UsageString()) <del> if len(args) > 0 { <del> return cli.StatusError{StatusCode: 1} <del> } <del> return nil <add> Args: cli.NoArgs, <add> Run: func(cmd *cobra.Command, args []string) { <add> fmt.Fprintf(dockerCli.Err(), "\n"+cmd.UsageString()) <ide> }, <ide> } <ide> cmd.AddCommand( <ide><path>api/client/volume/create.go <ide> func newCreateCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> cmd := &cobra.Command{ <ide> Use: "create", <ide> Short: "Create a volume", <add> Args: cli.NoArgs, <ide> RunE: func(cmd *cobra.Command, args []string) error { <del> // TODO: remove once cobra is patched to handle this <del> if err := cli.AcceptsNoArgs(args, cmd); err != nil { <del> return err <del> } <ide> return runCreate(dockerCli, opts) <ide> }, <ide> } <ide><path>api/client/volume/inspect.go <ide> func newInspectCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> cmd := &cobra.Command{ <ide> Use: "inspect [OPTIONS] VOLUME [VOLUME...]", <ide> Short: "Return low-level information on a volume", <add> Args: cli.RequiresMinArgs(1), <ide> RunE: func(cmd *cobra.Command, args []string) error { <del> if err := cli.MinRequiredArgs(args, 1, cmd); err != nil { <del> return err <del> } <ide> opts.names = args <ide> return runInspect(dockerCli, opts) <ide> }, <ide><path>api/client/volume/list.go <ide> func newListCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> Use: "ls", <ide> Aliases: []string{"list"}, <ide> Short: "List volumes", <add> Args: cli.NoArgs, <ide> RunE: func(cmd *cobra.Command, args []string) error { <del> // TODO: remove once cobra is patched to handle this <del> if err := cli.AcceptsNoArgs(args, cmd); err != nil { <del> return err <del> } <ide> return runList(dockerCli, opts) <ide> }, <ide> } <ide><path>api/client/volume/remove.go <ide> func newRemoveCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> Use: "rm VOLUME [VOLUME]...", <ide> Aliases: []string{"remove"}, <ide> Short: "Remove a volume", <add> Args: cli.RequiresMinArgs(1), <ide> RunE: func(cmd *cobra.Command, args []string) error { <del> if err := cli.MinRequiredArgs(args, 1, cmd); err != nil { <del> return err <del> } <ide> return runRemove(dockerCli, args) <ide> }, <ide> } <ide> } <ide> <ide> func runRemove(dockerCli *client.DockerCli, volumes []string) error { <ide> client := dockerCli.Client() <del> var status = 0 <add> ctx := context.Background() <add> status := 0 <ide> <ide> for _, name := range volumes { <del> if err := client.VolumeRemove(context.Background(), name); err != nil { <add> if err := client.VolumeRemove(ctx, name); err != nil { <ide> fmt.Fprintf(dockerCli.Err(), "%s\n", err) <ide> status = 1 <ide> continue <ide><path>cli/required.go <ide> package cli <ide> <ide> import ( <ide> "fmt" <add> "strings" <ide> <ide> "github.com/spf13/cobra" <ide> ) <ide> <del>// MinRequiredArgs checks if the minimum number of args exists, and returns an <del>// error if they do not. <del>func MinRequiredArgs(args []string, min int, cmd *cobra.Command) error { <del> if len(args) >= min { <add>// NoArgs validate args and returns an error if there are any args <add>func NoArgs(cmd *cobra.Command, args []string) error { <add> if len(args) == 0 { <ide> return nil <ide> } <ide> <del> return fmt.Errorf( <del> "\"%s\" requires at least %d argument(s).\n\nUsage: %s\n\n%s", <del> cmd.CommandPath(), <del> min, <del> cmd.UseLine(), <del> cmd.Short, <del> ) <del>} <del> <del>// AcceptsNoArgs returns an error message if there are args <del>func AcceptsNoArgs(args []string, cmd *cobra.Command) error { <del> if len(args) == 0 { <del> return nil <add> if cmd.HasSubCommands() { <add> return fmt.Errorf("\n" + strings.TrimRight(cmd.UsageString(), "\n")) <ide> } <ide> <ide> return fmt.Errorf( <ide> func AcceptsNoArgs(args []string, cmd *cobra.Command) error { <ide> cmd.Short, <ide> ) <ide> } <add> <add>// RequiresMinArgs returns an error if there is not at least min args <add>func RequiresMinArgs(min int) cobra.PositionalArgs { <add> return func(cmd *cobra.Command, args []string) error { <add> if len(args) >= min { <add> return nil <add> } <add> return fmt.Errorf( <add> "\"%s\" requires at least %d argument(s).\n\nUsage: %s\n\n%s", <add> cmd.CommandPath(), <add> min, <add> cmd.UseLine(), <add> cmd.Short, <add> ) <add> } <add>} <ide><path>integration-cli/docker_cli_help_test.go <ide> func testCommand(cmd string, newEnvs []string, scanForHome bool, home string) er <ide> return fmt.Errorf("Should not have full usage on %q\n", args) <ide> } <ide> if strings.HasSuffix(stderr, "\n\n") { <del> return fmt.Errorf("Should not have a blank line on %q\n", args) <add> return fmt.Errorf("Should not have a blank line on %q\n%v", args, stderr) <ide> } <ide> } <ide>
7
Ruby
Ruby
remove some mocha stubs
273054d6e1dbc9ee610a28f6349e48e76324fde1
<ide><path>activesupport/test/time_zone_test.rb <ide> def test_from_duration_to_map <ide> <ide> def test_now <ide> with_env_tz 'US/Eastern' do <del> Time.stubs(:now).returns(Time.local(2000)) <del> zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] <add> zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].dup <add> def zone.time_now; Time.local(2000); end <ide> assert_instance_of ActiveSupport::TimeWithZone, zone.now <ide> assert_equal Time.utc(2000,1,1,5), zone.now.utc <ide> assert_equal Time.utc(2000), zone.now.time <ide> def test_now <ide> <ide> def test_now_enforces_spring_dst_rules <ide> with_env_tz 'US/Eastern' do <del> Time.stubs(:now).returns(Time.local(2006,4,2,2)) # 2AM springs forward to 3AM <del> zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] <add> zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].dup <add> def zone.time_now <add> Time.local(2006,4,2,2) # 2AM springs forward to 3AM <add> end <add> <ide> assert_equal Time.utc(2006,4,2,3), zone.now.time <ide> assert_equal true, zone.now.dst? <ide> end <ide> end <ide> <ide> def test_now_enforces_fall_dst_rules <ide> with_env_tz 'US/Eastern' do <del> Time.stubs(:now).returns(Time.at(1162098000)) # equivalent to 1AM DST <del> zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] <add> zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].dup <add> def zone.time_now <add> Time.at(1162098000) # equivalent to 1AM DST <add> end <ide> assert_equal Time.utc(2006,10,29,1), zone.now.time <ide> assert_equal true, zone.now.dst? <ide> end
1
PHP
PHP
improve api docs for a few table methods
83f0c80dca6f12d18e87beabce391852c279a7d2
<ide><path>src/ORM/Table.php <ide> public function removeBehavior($name) <ide> /** <ide> * Returns the behavior registry for this table. <ide> * <del> * @return \Cake\ORM\BehaviorRegistry <add> * @return \Cake\ORM\BehaviorRegistry The BehaviorRegistry instance. <ide> */ <ide> public function behaviors() <ide> { <ide> public function behaviors() <ide> * Check if a behavior with the given alias has been loaded. <ide> * <ide> * @param string $name The behavior alias to check. <del> * @return bool <add> * @return bool Whether or not the behavior exists. <ide> */ <ide> public function hasBehavior($name) <ide> { <ide> public function hasBehavior($name) <ide> /** <ide> * Returns an association object configured for the specified alias if any <ide> * <del> * @param string $name the alias used for the association <del> * @return \Cake\ORM\Association <add> * @param string $name the alias used for the association. <add> * @return \Cake\ORM\Association|null Either the association or null. <ide> */ <ide> public function association($name) <ide> { <ide> public function association($name) <ide> /** <ide> * Get the associations collection for this table. <ide> * <del> * @return \Cake\ORM\AssociationCollection <add> * @return \Cake\ORM\AssociationCollection The collection of association objects. <ide> */ <ide> public function associations() <ide> { <ide> public function belongsToMany($associated, array $options = []) <ide> /** <ide> * {@inheritDoc} <ide> * <add> * ### Model.beforeFind event <add> * <add> * Each find() will trigger a `Model.beforeFind` event for all attached <add> * listeners. Any listener can set a valid result set using $query <add> * <ide> * By default, `$options` will recognize the following keys: <ide> * <ide> * - fields <ide> public function belongsToMany($associated, array $options = []) <ide> * - having <ide> * - contain <ide> * - join <del> * @return \Cake\ORM\Query <add> * <add> * ### Usage <add> * <add> * Using the options array: <add> * <add> * ``` <add> * $query = $articles->find('all', [ <add> * 'conditions' => ['published' => 1], <add> * 'limit' => 10, <add> * 'contain' => ['Users', 'Comments'] <add> * ]); <add> * ``` <add> * <add> * Using the builder interface: <add> * <add> * ``` <add> * $query = $articles->find() <add> * ->where(['published' => 1]) <add> * ->limit(10) <add> * ->contain(['Users', 'Comments']); <add> * ``` <add> * <add> * ### Calling finders <add> * <add> * The find() method is the entry point for custom finder methods. <add> * You can invoke a finder by specifying the type: <add> * <add> * ``` <add> * $query = $articles->find('published'); <add> * ``` <add> * <add> * Would invoke the `findPublished` method. <add> * <add> * @return \Cake\ORM\Query The query builder <ide> */ <ide> public function find($type = 'all', $options = []) <ide> { <ide> public function find($type = 'all', $options = []) <ide> } <ide> <ide> /** <del> * Returns the query as passed <add> * Returns the query as passed. <add> * <add> * By default findAll() applies no conditions, you <add> * can override this method in subclasses to modify how `find('all')` works. <ide> * <ide> * @param \Cake\ORM\Query $query The query to find with <ide> * @param array $options The options to use for the find <del> * @return \Cake\ORM\Query <add> * @return \Cake\ORM\Query The query builder <ide> */ <ide> public function findAll(Query $query, array $options) <ide> { <ide> public function findAll(Query $query, array $options) <ide> * <ide> * @param \Cake\ORM\Query $query The query to find with <ide> * @param array $options The options for the find <del> * @return \Cake\ORM\Query <add> * @return \Cake\ORM\Query The query builder <ide> */ <ide> public function findList(Query $query, array $options) <ide> { <ide> public function findList(Query $query, array $options) <ide> * <ide> * @param \Cake\ORM\Query $query The query to find with <ide> * @param array $options The options to find with <del> * @return \Cake\ORM\Query <add> * @return \Cake\ORM\Query The qury builder <ide> */ <ide> public function findThreaded(Query $query, array $options) <ide> { <ide> protected function _setFieldMatchers($options, $keys) <ide> /** <ide> * {@inheritDoc} <ide> * <add> * ### Usage <add> * <add> * Get an article and some relationships: <add> * <add> * ``` <add> * $article = $articles->get(1, ['contain' => ['Users', 'Comments']]); <add> * ``` <add> * <ide> * @throws \Cake\Datasource\Exception\InvalidPrimaryKeyException When $primaryKey has an <ide> * incorrect number of elements. <ide> */ <ide> public function get($primaryKey, $options = []) <ide> * Finds an existing record or creates a new one. <ide> * <ide> * Using the attributes defined in $search a find() will be done to locate <del> * an existing record. If that record exists it will be returned. If it does <del> * not exist, a new entity will be created with the $search properties, and <del> * the $defaults. When a new entity is created, it will be saved. <add> * an existing record. If records matches the conditions, the first record <add> * will be returned. <add> * <add> * If no record can be found, a new entity will be created <add> * with the $search properties. If a callback is provided, it will be <add> * called allowing you to define additional default values. The new <add> * entity will be saved and returned. <ide> * <ide> * @param array $search The criteria to find existing records by. <ide> * @param callable|null $callback A callback that will be invoked for newly <ide> public function exists($conditions) <ide> * <ide> * ### Options <ide> * <del> * The options array can receive the following keys: <add> * The options array accepts the following keys: <ide> * <ide> * - atomic: Whether to execute the save and callbacks inside a database <ide> * transaction (default: true) <ide> public function exists($conditions) <ide> * - Model.beforeRules: Will be triggered right before any rule checking is done <ide> * for the passed entity if the `checkRules` key in $options is not set to false. <ide> * Listeners will receive as arguments the entity, options array and the operation type. <del> * If the event is stopped the checking result will be set to the result of the event itself. <add> * If the event is stopped the rules check result will be set to the result of the event itself. <ide> * - Model.afterRules: Will be triggered right after the `checkRules()` method is <ide> * called for the entity. Listeners will receive as arguments the entity, <ide> * options array, the result of checking the rules and the operation type. <ide> public function validateUnique($value, array $options, array $context = null) <ide> * Override this method if you need to add non-conventional event listeners. <ide> * Or if you want you table to listen to non-standard events. <ide> * <add> * The conventional method map is: <add> * <add> * - Model.beforeMarshal => beforeMarshal <add> * - Model.beforeFind => beforeFind <add> * - Model.beforeSave => beforeSave <add> * - Model.afterSave => afterSave <add> * - Model.afterSaveCommit => afterSaveCommit <add> * - Model.beforeDelete => beforeDelete <add> * - Model.afterDelete => afterDelete <add> * - Model.afterDeleteCommit => afterDeleteCommit <add> * - Model.beforeRules => beforeRules <add> * - Model.afterRules => afterRules <add> * <ide> * @return array <ide> */ <ide> public function implementedEvents()
1
Python
Python
remove trailing whitespace
2012acb11b4666ba45b5f30e9d1c864cef32792d
<ide><path>libcloud/drivers/elastichosts.py <ide> def success(self): <ide> raise InvalidCredsError() <ide> <ide> return self.status >= 200 and self.status <= 299 <del> <add> <ide> def parse_body(self): <ide> if not self.body: <ide> return self.body <del> <add> <ide> try: <ide> data = json.loads(self.body) <ide> except: <ide> raise MalformedResponseError("Failed to parse JSON", body=self.body, driver=ElasticHostsBaseNodeDriver) <ide> <ide> return data <del> <add> <ide> def parse_error(self): <ide> error_header = self.headers.get('x-elastic-error', '') <ide> return 'X-Elastic-Error: %s (%s)' % (error_header, self.body.strip()) <del> <add> <ide> class ElasticHostsNodeSize(NodeSize): <ide> def __init__(self, id, name, cpu, ram, disk, bandwidth, price, driver): <ide> self.id = id <ide> class ElasticHostsBaseConnection(ConnectionUserAndKey): <ide> """ <ide> Base connection class for the ElasticHosts driver <ide> """ <del> <add> <ide> host = API_ENDPOINTS[DEFAULT_ENDPOINT]['host'] <ide> responseCls = ElasticHostsResponse <ide> <ide> def create_node(self, **kwargs): <ide> <ide> @keyword name: String with a name for this new node (required) <ide> @type name: C{string} <del> <add> <ide> @keyword smp: Number of virtual processors or None to calculate based on the cpu speed <ide> @type smp: C{int} <del> <add> <ide> @keyword nic_model: e1000, rtl8139 or virtio (is not specified, e1000 is used) <ide> @type nic_model: C{string} <ide> <ide> class ElasticHostsUS1NodeDriver(ElasticHostsBaseNodeDriver): <ide> ElasticHosts node driver for the San Antonio Peer 1 end-point <ide> """ <ide> connectionCls = ElasticHostsUS1Connection <del> <del>
1
Javascript
Javascript
upgrade release dependencies
967af73203378db0cc3637adee85c442e246e05a
<ide><path>build/release.js <ide> module.exports = function( Release ) { <ide> }; <ide> <ide> module.exports.dependencies = [ <del> "[email protected]", <del> "[email protected]", <del> "[email protected]", <del> "[email protected]" <add> "[email protected]", <add> "[email protected]", <add> "[email protected]" <ide> ];
1
Javascript
Javascript
fix typo in invariant message
9c353b5ab060be9392a7aaf437bba4ffc56d78ca
<ide><path>Libraries/ActionSheetIOS/ActionSheetIOS.js <ide> const ActionSheetIOS = { <ide> 'Options must be a valid object', <ide> ); <ide> invariant(typeof callback === 'function', 'Must provide a valid callback'); <del> invariant(RCTActionSheetManager, "ActionSheetManager does't exist"); <add> invariant(RCTActionSheetManager, "ActionSheetManager doesn't exist"); <ide> <ide> const {tintColor, destructiveButtonIndex, ...remainingOptions} = options; <ide> let destructiveButtonIndices = null; <ide> const ActionSheetIOS = { <ide> typeof successCallback === 'function', <ide> 'Must provide a valid successCallback', <ide> ); <del> invariant(RCTActionSheetManager, "ActionSheetManager does't exist"); <add> invariant(RCTActionSheetManager, "ActionSheetManager doesn't exist"); <ide> RCTActionSheetManager.showShareActionSheetWithOptions( <ide> {...options, tintColor: processColor(options.tintColor)}, <ide> failureCallback,
1
Python
Python
remove tag from da/sv tokenizer exceptions
07639dd6ac9db6f874d1f01ccb5e37a910924feb
<ide><path>spacy/lang/da/tokenizer_exceptions.py <ide> <ide> from __future__ import unicode_literals <ide> <del>from ...symbols import ORTH, LEMMA, NORM, TAG, PUNCT <add>from ...symbols import ORTH, LEMMA, NORM <ide> <ide> <ide> _exc = {} <ide> {ORTH: "Ons.", LEMMA: "onsdag"}, <ide> {ORTH: "Fre.", LEMMA: "fredag"}, <ide> {ORTH: "Lรธr.", LEMMA: "lรธrdag"}, <del> {ORTH: "og/eller", LEMMA: "og/eller", NORM: "og/eller", TAG: "CC"}, <add> {ORTH: "og/eller", LEMMA: "og/eller", NORM: "og/eller"}, <ide> ]: <ide> _exc[exc_data[ORTH]] = [exc_data] <ide> <ide> for period in ["."]: <ide> _exc["%d%s" % (h, period)] = [{ORTH: "%d." % h}] <ide> <del>_custom_base_exc = {"i.": [{ORTH: "i", LEMMA: "i", NORM: "i"}, {ORTH: ".", TAG: PUNCT}]} <add>_custom_base_exc = {"i.": [{ORTH: "i", LEMMA: "i", NORM: "i"}, {ORTH: "."}]} <ide> _exc.update(_custom_base_exc) <ide> <ide> TOKENIZER_EXCEPTIONS = _exc <ide><path>spacy/lang/sv/tokenizer_exceptions.py <ide> # coding: utf8 <ide> from __future__ import unicode_literals <ide> <del>from ...symbols import LEMMA, NORM, ORTH, PRON_LEMMA, PUNCT, TAG <add>from ...symbols import LEMMA, NORM, ORTH, PRON_LEMMA <ide> <ide> _exc = {} <ide> <ide> # Sentences ending in "i." (as in "... peka i."), "m." (as in "...รคn 2000 m."), <ide> # should be tokenized as two separate tokens. <ide> for orth in ["i", "m"]: <del> _exc[orth + "."] = [{ORTH: orth, LEMMA: orth, NORM: orth}, {ORTH: ".", TAG: PUNCT}] <add> _exc[orth + "."] = [{ORTH: orth, LEMMA: orth, NORM: orth}, {ORTH: "."}] <ide> <ide> TOKENIZER_EXCEPTIONS = _exc
2
Text
Text
fix code block in `readme.md`
b521160c92783b9d2a76d6bc3fa30df10d7251ac
<ide><path>README.md <ide> Install using `pip`... <ide> pip install djangorestframework <ide> <ide> Add `'rest_framework'` to your `INSTALLED_APPS` setting. <del> <del> INSTALLED_APPS = [ <del> ... <del> 'rest_framework', <del> ] <add>```python <add>INSTALLED_APPS = [ <add> ... <add> 'rest_framework', <add>] <add>``` <ide> <ide> # Example <ide>
1
Javascript
Javascript
fix suspense fixture
d42ed600266302034085551a465ee479e4ade9d1
<ide><path>fixtures/unstable-async/suspense/src/cache.js <del>import {createCache} from 'react-cache'; <del> <del>export let cache; <del>function initCache() { <del> cache = createCache(initCache); <del>} <del>initCache(); <ide><path>fixtures/unstable-async/suspense/src/components/ContributorListPage.js <ide> import React, {Fragment} from 'react'; <ide> import {unstable_createResource} from 'react-cache'; <del>import {cache} from '../cache'; <ide> import Spinner from './Spinner'; <ide> import {fetchCoreContributorListJSON} from '../api'; <ide> <ide> const ContributorListPage = ({loadingId, onUserClick}) => ( <ide> padding: 0, <ide> margin: 0, <ide> }}> <del> {ContributorListResource.read(cache).map(user => ( <add> {ContributorListResource.read().map(user => ( <ide> <ContributorListItem <ide> key={user.id} <ide> onClick={() => onUserClick(user.id)} <ide><path>fixtures/unstable-async/suspense/src/components/UserPage.js <ide> import React, {Suspense} from 'react'; <ide> import {unstable_createResource} from 'react-cache'; <ide> import Spinner from './Spinner'; <del>import {cache} from '../cache'; <ide> import {fetchUserProfileJSON, fetchUserRepositoriesListJSON} from '../api'; <ide> <ide> export default function UserPage({id}) { <ide> export default function UserPage({id}) { <ide> const UserDetailsResource = unstable_createResource(fetchUserProfileJSON); <ide> <ide> function UserDetails({id}) { <del> const user = UserDetailsResource.read(cache, id); <add> const user = UserDetailsResource.read(id); <ide> return ( <ide> <div <ide> style={{ <ide> const ImageResource = unstable_createResource( <ide> ); <ide> <ide> function Img({src, alt, ...rest}) { <del> return <img src={ImageResource.read(cache, src)} alt={alt} {...rest} />; <add> return <img src={ImageResource.read(src)} alt={alt} {...rest} />; <ide> } <ide> <ide> function UserPicture({source}) { <ide> const UserRepositoriesResource = unstable_createResource( <ide> ); <ide> <ide> function Repositories({id}) { <del> const repos = UserRepositoriesResource.read(cache, id); <add> const repos = UserRepositoriesResource.read(id); <ide> return ( <ide> <ul <ide> style={{ <ide><path>fixtures/unstable-async/suspense/src/index.js <ide> import React, {Fragment, PureComponent} from 'react'; <ide> import {unstable_createRoot, render} from 'react-dom'; <ide> import {unstable_trace as trace} from 'scheduler/tracing'; <del>import {cache} from './cache'; <ide> import { <ide> setFakeRequestTime, <ide> setPaused, <ide> class Debugger extends PureComponent { <ide> <ide> handleReset = () => { <ide> trace('Clear cache', performance.now(), () => { <del> cache.invalidate(); <add> // TODO: this is not implemented. <add> // cache.invalidate(); <ide> this.setState(state => ({ <ide> requests: {}, <ide> }));
4
Javascript
Javascript
add strict equalities in src/shared/util.js
ccd71e0a94971dbb175f34e879d0998edcf2f2b9
<ide><path>src/shared/util.js <ide> <ide> var globalScope = (typeof window === 'undefined') ? this : window; <ide> <del>var isWorker = (typeof window == 'undefined'); <add>var isWorker = (typeof window === 'undefined'); <ide> <ide> var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; <ide> <ide> function combineUrl(baseUrl, url) { <ide> return url; <ide> } <ide> var i; <del> if (url.charAt(0) == '/') { <add> if (url.charAt(0) === '/') { <ide> // absolute path <ide> i = baseUrl.indexOf('://'); <ide> if (url.charAt(1) === '/') { <ide> function isEmptyObj(obj) { <ide> } <ide> <ide> function isBool(v) { <del> return typeof v == 'boolean'; <add> return typeof v === 'boolean'; <ide> } <ide> <ide> function isInt(v) { <ide> PDFJS.createPromiseCapability = createPromiseCapability; <ide> pendingRejectionCheck: false, <ide> <ide> scheduleHandlers: function scheduleHandlers(promise) { <del> if (promise._status == STATUS_PENDING) { <add> if (promise._status === STATUS_PENDING) { <ide> return; <ide> } <ide> <ide> PDFJS.createPromiseCapability = createPromiseCapability; <ide> <ide> try { <ide> if (nextStatus === STATUS_RESOLVED) { <del> if (typeof(handler.onResolve) == 'function') { <add> if (typeof handler.onResolve === 'function') { <ide> nextValue = handler.onResolve(nextValue); <ide> } <del> } else if (typeof(handler.onReject) === 'function') { <add> } else if (typeof handler.onReject === 'function') { <ide> nextValue = handler.onReject(nextValue); <ide> nextStatus = STATUS_RESOLVED; <ide> <ide> PDFJS.createPromiseCapability = createPromiseCapability; <ide> return; <ide> } <ide> <del> if (status == STATUS_RESOLVED && <add> if (status === STATUS_RESOLVED && <ide> Promise.isPromise(value)) { <ide> value.then(this._updateStatus.bind(this, STATUS_RESOLVED), <ide> this._updateStatus.bind(this, STATUS_REJECTED));
1
Text
Text
add html to example readme
03b4dc1a1c356fdff80c43ae630a8a0f24f31871
<ide><path>examples/module-federation/README.md <ide> const App = () => ( <ide> export default App; <ide> ``` <ide> <add># index.html <add> <add>```html <add><html> <add> <head> <add> <style> <add> .spinner { <add> font-size: 10px; <add> margin: 50px auto; <add> text-indent: -9999em; <add> width: 11em; <add> height: 11em; <add> border-radius: 50%; <add> background: #595959; <add> background: linear-gradient( <add> to right, <add> #595959 10%, <add> rgba(89, 89, 89, 0) 42% <add> ); <add> position: relative; <add> animation: spin 1.4s infinite linear; <add> transform: translateZ(0); <add> } <add> .spinner:before { <add> width: 50%; <add> height: 50%; <add> background: #595959; <add> border-radius: 100% 0 0 0; <add> position: absolute; <add> top: 0; <add> left: 0; <add> content: ""; <add> } <add> .spinner:after { <add> background: white; <add> width: 75%; <add> height: 75%; <add> border-radius: 50%; <add> content: ""; <add> margin: auto; <add> position: absolute; <add> top: 0; <add> left: 0; <add> bottom: 0; <add> right: 0; <add> } <add> @-webkit-keyframes spin { <add> 0% { <add> -webkit-transform: rotate(0deg); <add> transform: rotate(0deg); <add> } <add> 100% { <add> -webkit-transform: rotate(360deg); <add> transform: rotate(360deg); <add> } <add> } <add> @keyframes spin { <add> 0% { <add> -webkit-transform: rotate(0deg); <add> transform: rotate(0deg); <add> } <add> 100% { <add> -webkit-transform: rotate(360deg); <add> transform: rotate(360deg); <add> } <add> } <add> </style> <add> </head> <add> <body> <add> <!-- A spinner --> <add> <div class="spinner"></div> <add> <add> <!-- This script only contains boostrapping logic --> <add> <!-- It will load all other scripts if neccessary --> <add> <script src="/dist/aaa/app.js" async></script> <add> <add> <!-- These script tags are optional --> <add> <!-- They improve loading performance --> <add> <!-- Omitting them will add an additional round trip --> <add> <script src="/dist/bbb/mfeBBB.js" async></script> <add> <script src="/dist/ccc/mfeCCC.js" async></script> <add> <add> <!-- All these scripts are pretty small ~5kb --> <add> <!-- For optimal performance they can be inlined --> <add> </body> <add></html> <add>``` <add> <ide> # src-b/Component.js <ide> <ide> ```jsx <ide> __webpack_require__.d(exports, { <ide> /******/ var promises = []; <ide> /******/ switch(name) { <ide> /******/ case "default": { <del>/******/ register("lodash", [4,17,15], () => __webpack_require__.e("vendors-node_modules_lodash_lodash_js").then(() => () => __webpack_require__(/*! lodash */ 9))); <del>/******/ register("react", [16,13,1], () => __webpack_require__.e("node_modules_react_index_js").then(() => () => __webpack_require__(/*! react */ 10))); <add>/******/ register("react", [16,13,1], () => __webpack_require__.e("node_modules_react_index_js").then(() => () => __webpack_require__(/*! react */ 9))); <add>/******/ register("lodash", [4,17,15], () => __webpack_require__.e("vendors-node_modules_lodash_lodash_js").then(() => () => __webpack_require__(/*! lodash */ 12))); <ide> /******/ register("date-fns", [2,14,0], () => __webpack_require__.e("vendors-node_modules_date-fns_esm_index_js").then(() => () => __webpack_require__(/*! date-fns */ 13))); <ide> /******/ } <ide> /******/ break; <ide> __webpack_require__.d(exports, { <ide> /******/ }; <ide> /******/ var installedModules = {}; <ide> /******/ var moduleToHandlerMapping = { <del>/******/ 5: () => loadSingletonVersionCheckFallback("default", "react", ["16",8,0], () => __webpack_require__.e("node_modules_react_index_js").then(() => () => __webpack_require__(/*! react */ 10))), <add>/******/ 5: () => loadSingletonVersionCheckFallback("default", "react", ["16",8,0], () => __webpack_require__.e("node_modules_react_index_js").then(() => () => __webpack_require__(/*! react */ 9))), <ide> /******/ 6: () => loadStrictVersionCheckFallback("default", "date-fns", ["2",12,0], () => __webpack_require__.e("vendors-node_modules_date-fns_esm_index_js").then(() => () => __webpack_require__(/*! date-fns */ 13))), <del>/******/ 8: () => loadStrictVersionCheckFallback("default", "lodash", ["4",17,4], () => __webpack_require__.e("vendors-node_modules_lodash_lodash_js").then(() => () => __webpack_require__(/*! lodash */ 9))) <add>/******/ 8: () => loadStrictVersionCheckFallback("default", "lodash", ["4",17,4], () => __webpack_require__.e("vendors-node_modules_lodash_lodash_js").then(() => () => __webpack_require__(/*! lodash */ 12))) <ide> /******/ }; <ide> /******/ // no consumes in initial chunks <ide> /******/ var chunkMapping = { <ide><path>examples/module-federation/template.md <ide> _{{src/bootstrap.js}}_ <ide> _{{src/App.js}}_ <ide> ``` <ide> <add># index.html <add> <add>```html <add>_{{index.html}}_ <add>``` <add> <ide> # src-b/Component.js <ide> <ide> ```jsx
2
Ruby
Ruby
fix inappropriate linking of info files
bc7469c819e18afa07f4c719d895e3c3c80f8c3f
<ide><path>Library/Homebrew/keg.rb <ide> def link <ide> link_dir('share') do |path| <ide> case path.to_s <ide> when 'locale/locale.alias' then :skip_file <del> when INFOFILE_RX then :info if ENV['HOMEBREW_KEEP_INFO'] <add> when INFOFILE_RX then ENV['HOMEBREW_KEEP_INFO'] ? :info : :skip_file <ide> when LOCALEDIR_RX then :mkpath <ide> when *share_mkpaths then :mkpath <ide> else :link <ide> def link_dir foo <ide> Find.prune if File.basename(src) == '.DS_Store' <ide> <ide> case yield src.relative_path_from(root) <del> when :skip_file <add> when :skip_file, nil <ide> Find.prune <ide> when :info <ide> make_relative_symlink dst, src
1
PHP
PHP
add cloud() method
6e759658a78a5461e446c2efd047a175119b6365
<ide><path>src/Illuminate/Filesystem/FilesystemManager.php <ide> public function disk($name = null) <ide> return $this->disks[$name] = $this->get($name); <ide> } <ide> <add> /** <add> * Get a default cloud filesystem instance. <add> * <add> * @return \Illuminate\Contracts\Filesystem\Filesystem <add> */ <add> public function cloud() <add> { <add> $name = $this->getDefaultCloudDriver(); <add> <add> return $this->disks[$name] = $this->get($name); <add> } <add> <ide> /** <ide> * Attempt to get the disk from the local cache. <ide> * <ide> public function getDefaultDriver() <ide> return $this->app['config']['filesystems.default']; <ide> } <ide> <add> /** <add> * Get the default cloud driver name. <add> * <add> * @return string <add> */ <add> public function getDefaultCloudDriver() <add> { <add> return $this->app['config']['filesystems.cloud']; <add> } <add> <ide> /** <ide> * Register a custom driver creator Closure. <ide> *
1
Text
Text
update documentation #any? #many?
5d985f2ed15b91ba30298a67c68583d8c0165293
<ide><path>guides/source/active_record_querying.md <ide> You can also use `any?` and `many?` to check for existence on a model or relatio <ide> <ide> ```ruby <ide> # via a model <del>Order.any? # => SELECT 1 AS one FROM orders <del>Order.many? # => SELECT COUNT(*) FROM orders <add>Order.any? <add># => SELECT 1 FROM orders LIMIT 1 <add>Order.many? <add># => SELECT COUNT(*) FROM (SELECT 1 FROM orders LIMIT 2) <ide> <ide> # via a named scope <del>Order.shipped.any? # => SELECT 1 AS one FROM orders WHERE orders.status = 0 <del>Order.shipped.many? # => SELECT COUNT(*) FROM orders WHERE orders.status = 0 <add>Order.shipped.any? <add># => SELECT 1 FROM orders WHERE orders.status = 0 LIMIT 1 <add>Order.shipped.many? <add># => SELECT COUNT(*) FROM (SELECT 1 FROM orders WHERE orders.status = 0 LIMIT 2) <ide> <ide> # via a relation <ide> Book.where(out_of_print: true).any?
1
Text
Text
simplify some steps of the overlay network guide
db5ded0dfc28c71276acf8500fabe3c64c15fbe1
<ide><path>docs/userguide/networking/get-started-overlay.md <ide> key-value stores. This example uses Consul. <ide> instance using the [consul image from Docker <ide> Hub](https://hub.docker.com/r/progrium/consul/). You'll do this in the next step. <ide> <del>3. Start a `progrium/consul` container running on the `mh-keystore` machine. <add>3. Set your local environment to the `mh-keystore` machine. <ide> <del> $ docker $(docker-machine config mh-keystore) run -d \ <add> $ eval "$(docker-machine env mh-keystore)" <add> <add>4. Start a `progrium/consul` container running on the `mh-keystore` machine. <add> <add> $ docker run -d \ <ide> -p "8500:8500" \ <ide> -h "consul" \ <ide> progrium/consul -server -bootstrap <ide> <del> A bash expansion `$(docker-machine config mh-keystore)` is used to pass the <del> connection configuration to the `docker run` command. The client starts a <del> `progrium/consul` image running in the `mh-keystore` machine. The server is <del> called `consul` and is listening on port `8500`. <del> <del>4. Set your local environment to the `mh-keystore` machine. <del> <del> $ eval "$(docker-machine env mh-keystore)" <add> The client starts a `progrium/consul` image running in the <add> `mh-keystore` machine. The server is called `consul` and is <add> listening on port `8500`. <ide> <ide> 5. Run the `docker ps` command to see the `consul` container. <ide>
1
Ruby
Ruby
fix exit logic
d6d857c154fb9cdb7dc1f81a1cc8a2302b9a3996
<ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade <ide> opoo "#{f.full_specified_name} #{version} already installed" <ide> end <ide> end <del> exit <add> return if outdated.empty? <ide> end <ide> <ide> pinned = outdated.select(&:pinned?)
1
Text
Text
add example of using filter with cctest
b56f65e28c02249359f4f8b682522c7d8d7c5eff
<ide><path>doc/guides/writing-tests.md <ide> The test can be executed by running the `cctest` target: <ide> $ make cctest <ide> ``` <ide> <add>A filter can be applied to run single/multiple test cases: <add>```console <add>$ make cctest GTEST_FILTER=EnvironmentTest.AtExitWithArgument <add>``` <add> <add>`cctest` can also be run directly which can be useful when debugging: <add>```console <add>$ out/Release/cctest --gtest_filter=EnvironmentTest.AtExit* <add>``` <add> <ide> ### Node.js test fixture <ide> There is a [test fixture][] named `node_test_fixture.h` which can be included by <ide> unit tests. The fixture takes care of setting up the Node.js environment
1
PHP
PHP
remove unneeded alias
5d409fe0d5f724ba110b6ec15c0e22610581a4a3
<ide><path>app/config/app.php <ide> 'DB' => 'Illuminate\Support\Facades\DB', <ide> 'Eloquent' => 'Illuminate\Database\Eloquent\Model', <ide> 'Event' => 'Illuminate\Support\Facades\Event', <del> 'EventSubscriber' => 'Illuminate\Events\Subscriber', <ide> 'File' => 'Illuminate\Support\Facades\File', <ide> 'Hash' => 'Illuminate\Support\Facades\Hash', <ide> 'Input' => 'Illuminate\Support\Facades\Input',
1
Javascript
Javascript
add unit tests for aborted life-cycles
37ca3874af3e94f6d108d31779adaee742cb4684
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js <ide> describe('ReactIncremental', () => { <ide> it('can call sCU while resuming a partly mounted component', () => { <ide> var ops = []; <ide> <add> var instances = new Set(); <add> <ide> class Bar extends React.Component { <ide> state = { y: 'A' }; <add> constructor() { <add> super(); <add> instances.add(this); <add> } <ide> shouldComponentUpdate(newProps, newState) { <ide> return this.props.x !== newProps.x || <ide> this.state.y !== newState.y; <ide> describe('ReactIncremental', () => { <ide> ops.push('Foo'); <ide> return [ <ide> <Bar key="a" x="A" />, <del> <Bar key="b" x="B" />, <add> <Bar key="b" x={props.step === 0 ? 'B' : 'B2'} />, <ide> <Bar key="c" x="C" />, <add> <Bar key="d" x="D" />, <ide> ]; <ide> } <ide> <del> ReactNoop.render(<Foo />); <del> ReactNoop.flushDeferredPri(30); <del> expect(ops).toEqual(['Foo', 'Bar:A', 'Bar:B']); <add> ReactNoop.render(<Foo step={0} />); <add> ReactNoop.flushDeferredPri(40); <add> expect(ops).toEqual(['Foo', 'Bar:A', 'Bar:B', 'Bar:C']); <add> <add> expect(instances.size).toBe(3); <ide> <ide> ops = []; <ide> <del> ReactNoop.render(<Foo />); <del> ReactNoop.flushDeferredPri(40); <del> expect(ops).toEqual(['Foo', 'Bar:B', 'Bar:C']); <add> ReactNoop.render(<Foo step={1} />); <add> ReactNoop.flushDeferredPri(50); <add> // A completed and was reused. B completed but couldn't be reused because <add> // props differences. C didn't complete and therefore couldn't be reused. <add> // D never even started so it needed a new instance. <add> expect(ops).toEqual(['Foo', 'Bar:B2', 'Bar:C', 'Bar:D']); <add> <add> // We expect each rerender to correspond to a new instance. <add> expect(instances.size).toBe(6); <ide> }); <ide> <ide> it('gets new props when setting state on a partly updated component', () => { <ide> describe('ReactIncremental', () => { <ide> expect(ops).toEqual(['Bar:A-1', 'Baz', 'Baz']); <ide> }); <ide> <add> it('calls componentWillMount twice if the initial render is aborted', () => { <add> var ops = []; <add> <add> class LifeCycle extends React.Component { <add> state = { x: this.props.x }; <add> componentWillMount() { <add> ops.push('componentWillMount:' + this.state.x + '-' + this.props.x); <add> } <add> componentDidMount() { <add> ops.push('componentDidMount:' + this.state.x + '-' + this.props.x); <add> } <add> render() { <add> return <span />; <add> } <add> } <add> <add> function Trail() { <add> ops.push('Trail'); <add> } <add> <add> function App(props) { <add> ops.push('App'); <add> return ( <add> <div> <add> <LifeCycle x={props.x} /> <add> <Trail /> <add> </div> <add> ); <add> } <add> <add> ReactNoop.render(<App x={0} />); <add> ReactNoop.flushDeferredPri(30); <add> <add> expect(ops).toEqual([ <add> 'App', <add> 'componentWillMount:0-0', <add> ]); <add> <add> ops = []; <add> <add> ReactNoop.render(<App x={1} />); <add> ReactNoop.flush(); <add> <add> expect(ops).toEqual([ <add> 'App', <add> 'componentWillMount:1-1', <add> 'Trail', <add> 'componentDidMount:1-1', <add> ]); <add> }); <add> <add> it('calls componentWill* twice if an update render is aborted', () => { <add> var ops = []; <add> <add> class LifeCycle extends React.Component { <add> componentWillMount() { <add> ops.push('componentWillMount:' + this.props.x); <add> } <add> componentDidMount() { <add> ops.push('componentDidMount:' + this.props.x); <add> } <add> componentWillReceiveProps(nextProps) { <add> ops.push('componentWillReceiveProps:' + this.props.x + '-' + nextProps.x); <add> } <add> shouldComponentUpdate(nextProps) { <add> ops.push('shouldComponentUpdate:' + this.props.x + '-' + nextProps.x); <add> return true; <add> } <add> componentWillUpdate(nextProps) { <add> ops.push('componentWillUpdate:' + this.props.x + '-' + nextProps.x); <add> } <add> componentDidUpdate(prevProps) { <add> ops.push('componentDidUpdate:' + this.props.x + '-' + prevProps.x); <add> } <add> render() { <add> ops.push('render:' + this.props.x); <add> return <span />; <add> } <add> } <add> <add> function Sibling() { <add> // The sibling is used to confirm that we've completed the first child, <add> // but not yet flushed. <add> ops.push('Sibling'); <add> return <span />; <add> } <add> <add> function App(props) { <add> ops.push('App'); <add> <add> return [ <add> <LifeCycle key="a" x={props.x} />, <add> <Sibling key="b" />, <add> ]; <add> } <add> <add> ReactNoop.render(<App x={0} />); <add> ReactNoop.flush(); <add> <add> expect(ops).toEqual([ <add> 'App', <add> 'componentWillMount:0', <add> 'render:0', <add> 'Sibling', <add> 'componentDidMount:0', <add> ]); <add> <add> ops = []; <add> <add> ReactNoop.render(<App x={1} />); <add> ReactNoop.flushDeferredPri(30); <add> <add> expect(ops).toEqual([ <add> 'App', <add> 'componentWillReceiveProps:0-1', <add> 'shouldComponentUpdate:0-1', <add> 'componentWillUpdate:0-1', <add> 'render:1', <add> 'Sibling', <add> // no componentDidUpdate <add> ]); <add> <add> ops = []; <add> <add> ReactNoop.render(<App x={2} />); <add> ReactNoop.flush(); <add> <add> expect(ops).toEqual([ <add> 'App', <add> 'componentWillReceiveProps:1-2', <add> 'shouldComponentUpdate:1-2', <add> 'componentWillUpdate:1-2', <add> 'render:2', <add> 'Sibling', <add> // When componentDidUpdate finally gets called, it covers both updates. <add> 'componentDidUpdate:2-0', <add> ]); <add> }); <add> <add> it('does not call componentWillReceiveProps for state-only updates', () => { <add> var ops = []; <add> <add> var instances = []; <add> <add> class LifeCycle extends React.Component { <add> state = { x: 0 }; <add> tick() { <add> this.setState({ <add> x: this.state.x + 1, <add> }); <add> } <add> componentWillMount() { <add> instances.push(this); <add> ops.push('componentWillMount:' + this.state.x); <add> } <add> componentDidMount() { <add> ops.push('componentDidMount:' + this.state.x); <add> } <add> componentWillReceiveProps(nextProps) { <add> ops.push('componentWillReceiveProps'); <add> } <add> shouldComponentUpdate(nextProps, nextState) { <add> ops.push('shouldComponentUpdate:' + this.state.x + '-' + nextState.x); <add> return true; <add> } <add> componentWillUpdate(nextProps, nextState) { <add> ops.push('componentWillUpdate:' + this.state.x + '-' + nextState.x); <add> } <add> componentDidUpdate(prevProps, prevState) { <add> ops.push('componentDidUpdate:' + this.state.x + '-' + prevState.x); <add> } <add> render() { <add> ops.push('render:' + this.state.x); <add> return <span />; <add> } <add> } <add> <add> // This wrap is a bit contrived because we can't pause a completed root and <add> // there is currently an issue where a component can't reuse its render <add> // output unless it fully completed. <add> class Wrap extends React.Component { <add> state = { y: 0 }; <add> componentWillMount() { <add> instances.push(this); <add> } <add> tick() { <add> this.setState({ <add> y: this.state.y + 1, <add> }); <add> } <add> render() { <add> ops.push('Wrap'); <add> return <LifeCycle y={this.state.y} />; <add> } <add> } <add> <add> function Sibling() { <add> // The sibling is used to confirm that we've completed the first child, <add> // but not yet flushed. <add> ops.push('Sibling'); <add> return <span />; <add> } <add> <add> function App(props) { <add> ops.push('App'); <add> return [ <add> <Wrap key="a" />, <add> <Sibling key="b" />, <add> ]; <add> } <add> <add> ReactNoop.render(<App y={0} />); <add> ReactNoop.flush(); <add> <add> expect(ops).toEqual([ <add> 'App', <add> 'Wrap', <add> 'componentWillMount:0', <add> 'render:0', <add> 'Sibling', <add> 'componentDidMount:0', <add> ]); <add> <add> ops = []; <add> <add> // LifeCycle <add> instances[1].tick(); <add> <add> ReactNoop.flushDeferredPri(25); <add> <add> expect(ops).toEqual([ <add> // no componentWillReceiveProps <add> 'shouldComponentUpdate:0-1', <add> 'componentWillUpdate:0-1', <add> 'render:1', <add> // no componentDidUpdate <add> ]); <add> <add> ops = []; <add> <add> // LifeCycle <add> instances[1].tick(); <add> <add> ReactNoop.flush(); <add> <add> expect(ops).toEqual([ <add> // no componentWillReceiveProps <add> 'shouldComponentUpdate:1-2', <add> 'componentWillUpdate:1-2', <add> 'render:2', <add> // When componentDidUpdate finally gets called, it covers both updates. <add> 'componentDidUpdate:2-0', <add> ]); <add> <add> ops = []; <add> <add> // Next we will update props of LifeCycle by updating its parent. <add> <add> instances[0].tick(); <add> <add> ReactNoop.flushDeferredPri(30); <add> <add> expect(ops).toEqual([ <add> 'Wrap', <add> 'componentWillReceiveProps', <add> 'shouldComponentUpdate:2-2', <add> 'componentWillUpdate:2-2', <add> 'render:2', <add> // no componentDidUpdate <add> ]); <add> <add> ops = []; <add> <add> // Next we will update LifeCycle directly but not with new props. <add> instances[1].tick(); <add> <add> ReactNoop.flush(); <add> <add> expect(ops).toEqual([ <add> // This should not trigger another componentWillReceiveProps because <add> // we never got new props. <add> 'shouldComponentUpdate:2-3', <add> 'componentWillUpdate:2-3', <add> 'render:3', <add> 'componentDidUpdate:3-2', <add> ]); <add> <add> // TODO: Test that we get the expected values for the same scenario with <add> // incomplete parents. <add> <add> }); <add> <ide> });
1
Javascript
Javascript
follow ups to bundler configs
fc91508c1ffd7a00c261a567536b169989e5fab4
<ide><path>packages/react-client/src/ReactFlightClient.js <ide> <ide> import {REACT_ELEMENT_TYPE} from 'shared/ReactSymbols'; <ide> <del>// import type {ModuleMetaData} from './ReactFlightClientHostConfig'; <add>// import type { <add>// ModuleReference, <add>// ModuleMetaData, <add>// } from './ReactFlightClientHostConfig'; <ide> <ide> // import { <add>// resolveModuleReference, <ide> // preloadModule, <add>// loadModule, <ide> // requireModule, <ide> // } from './ReactFlightClientHostConfig'; <ide> <ide><path>packages/react-flight-dom-relay/src/ReactFlightDOMRelayClientHostConfig.js <ide> */ <ide> <ide> export { <add> resolveModuleReference, <ide> preloadModule, <add> loadModule, <ide> requireModule, <ide> } from 'ReactFlightDOMRelayClientIntegration'; <ide> <del>export type {ModuleMetaData} from 'ReactFlightDOMRelayClientIntegration'; <add>export type { <add> ModuleReference, <add> ModuleMetaData, <add>} from 'ReactFlightDOMRelayClientIntegration'; <ide><path>packages/react-flight-dom-relay/src/ReactFlightDOMRelayServerHostConfig.js <ide> import {resolveModelToJSON} from 'react-server/src/ReactFlightServer'; <ide> import { <ide> emitModel, <ide> emitError, <del> resolveResourceMetaData, <add> resolveModuleMetaData as resolveModuleMetaDataImpl, <ide> } from 'ReactFlightDOMRelayServerIntegration'; <ide> <ide> export type { <ide> export function resolveModuleMetaData( <ide> config: BundlerConfig, <ide> resource: ModuleReference, <ide> ): ModuleMetaData { <del> return resolveResourceMetaData(resource); <add> return resolveModuleMetaDataImpl(resource); <ide> } <ide> <ide> type JSONValue = <ide><path>packages/react-flight-dom-relay/src/__mocks__/ReactFlightDOMRelayClientIntegration.js <ide> function getFakeModule() { <ide> } <ide> <ide> const ReactFlightDOMRelayClientIntegration = { <del> preloadModule(jsResource) { <add> resolveModuleReference(moduleData) { <add> return moduleData; <add> }, <add> preloadModule(moduleReference) {}, <add> loadModule(moduleReference) { <ide> return null; <ide> }, <del> requireModule(jsResource) { <add> requireModule(moduleReference) { <ide> return getFakeModule(); <ide> }, <ide> }; <ide><path>packages/react-flight-dom-relay/src/__mocks__/ReactFlightDOMRelayServerIntegration.js <ide> const ReactFlightDOMRelayServerIntegration = { <ide> }); <ide> }, <ide> close(destination) {}, <del> resolveResourceMetaData(resource) { <add> resolveModuleMetaDataImpl(resource) { <ide> return resource; <ide> }, <ide> }; <ide><path>packages/react-flight-dom-webpack/src/ReactFlightClientWebpackBundlerConfig.js <ide> export type ModuleMetaData = { <ide> id: string, <ide> chunks: Array<string>, <add> name: string, <ide> }; <ide> <add>// eslint-disable-next-line no-unused-vars <add>export type ModuleReference<T> = ModuleMetaData; <add> <add>export function resolveModuleReference<T>( <add> moduleData: ModuleMetaData, <add>): ModuleReference<T> { <add> return moduleData; <add>} <add> <ide> type Thenable = { <ide> then(resolve: () => mixed, reject: (mixed) => mixed): mixed, <ide> ... <ide> const chunkCache: Map<string, null | Thenable> = new Map(); <ide> // Returning null means that all dependencies are fulfilled and we <ide> // can synchronously require the module now. A thenable is returned <ide> // that when resolved, means we can try again. <del>export function preloadModule(moduleData: ModuleMetaData): null | Thenable { <del> let moduleEntry = require.cache[moduleData.id]; <del> if (moduleEntry) { <del> // Fast exit if this module has already been loaded. <del> return null; <del> } <add>export function preloadModule<T>(moduleData: ModuleReference<T>): void { <add> loadModule(moduleData); <add>} <add> <add>export function loadModule<T>(moduleData: ModuleReference<T>): null | Thenable { <ide> let chunks = moduleData.chunks; <ide> let anyRemainingThenable = null; <ide> for (let i = 0; i < chunks.length; i++) { <ide> export function preloadModule(moduleData: ModuleMetaData): null | Thenable { <ide> return anyRemainingThenable; <ide> } <ide> <del>export function requireModule<T>(moduleData: ModuleMetaData): T { <del> return __webpack_require__(moduleData.id).default; <add>export function requireModule<T>(moduleData: ModuleReference<T>): T { <add> return __webpack_require__(moduleData.id)[moduleData.name]; <ide> } <ide><path>scripts/flow/react-relay-hooks.js <ide> declare module 'ReactFlightDOMRelayServerIntegration' { <ide> <ide> declare export opaque type ModuleReference; <ide> declare export opaque type ModuleMetaData; <del> declare export function resolveResourceMetaData( <del> resource: ModuleReference, <add> declare export function resolveModuleMetaData( <add> resourceReference: ModuleReference, <ide> ): ModuleMetaData; <ide> } <ide> <ide> declare module 'ReactFlightDOMRelayClientIntegration' { <add> declare export opaque type ModuleReference; <ide> declare export opaque type ModuleMetaData; <del> declare export function preloadModule( <add> declare export function resolveModuleReference<T>( <ide> moduleData: ModuleMetaData, <add> ): ModuleReference<T>; <add> declare export function preloadModule<T>( <add> moduleReference: ModuleReference<T>, <add> ): void; <add> declare export function loadModule<T>( <add> moduleReference: ModuleReference<T>, <ide> ): null | Thenable; <del> declare export function requireModule<T>(moduleData: ModuleMetaData): T; <add> declare export function requireModule<T>( <add> moduleReference: ModuleReference<T>, <add> ): T; <ide> }
7
Text
Text
update changelog with release notes for 1.7.6
c7671edbfdcdc161507fb57cff12523f4400b5ac
<ide><path>CHANGELOG.md <add><a name="1.7.6"></a> <add># 1.7.6 gravity-manipulation (2019-01-17) <add> <add>## Bug Fixes <add>- **$compile:** fix ng-prop-* with undefined values <add> ([772440](https://github.com/angular/angular.js/commit/772440cdaf9a9bfa40de1675e20a5f0e356089ed), <add> [#16797](https://github.com/angular/angular.js/issues/16797), <add> [#16798](https://github.com/angular/angular.js/issues/16798)) <add>- **compile:** properly handle false value for boolean attrs with jQuery <add> ([27486b](https://github.com/angular/angular.js/commit/27486bd15e70946ece2ba713e4e8654b7f9bddad), <add> [#16778](https://github.com/angular/angular.js/issues/16778), <add> [#16779](https://github.com/angular/angular.js/issues/16779)) <add>- **ngRepeat:** <add> - fix reference to last collection value remaining across linkages <add> ([cf919a](https://github.com/angular/angular.js/commit/cf919a6fb7fc655f3fa37a74899a797ea5b8073e)) <add> - fix trackBy function being invoked with incorrect scope <add> ([d4d103](https://github.com/angular/angular.js/commit/d4d1031bcd9b30ae6a58bd60a79bcc9d20f0f2b7), <add> [#16776](https://github.com/angular/angular.js/issues/16776), <add> [#16777](https://github.com/angular/angular.js/issues/16777)) <add>- **aria/ngClick:** check if element is `contenteditable` before blocking spacebar <add> ([289374](https://github.com/angular/angular.js/commit/289374a43c1b2fd715ddf7455db225b17afebbaf), <add> [#16762](https://github.com/angular/angular.js/issues/16762)) <add>- **input:** prevent browsers from autofilling hidden inputs <add> ([7cbb10](https://github.com/angular/angular.js/commit/7cbb1044fcb3576cdad791bd22ebea3dfd533ff8)) <add>- **Angular:** add workaround for Safari / Webdriver problem <add> ([eb49f6](https://github.com/angular/angular.js/commit/eb49f6b7555cfd7ab03fd35581adb6b4bd49044e)) <add>- **$browser:** normalize inputted URLs <add> ([2f72a6](https://github.com/angular/angular.js/commit/2f72a69ded53a122afad3ec28d91f9bd2f41eb4f), <add> [#16606](https://github.com/angular/angular.js/issues/16606)) <add>- **interpolate:** do not create directives for constant media URL attributes <add> ([90a41d](https://github.com/angular/angular.js/commit/90a41d415c83abdbf28317f49df0fd0a7e07db86), <add> [#16734](https://github.com/angular/angular.js/issues/16734)) <add>- **$q:** allow third-party promise libraries <add> ([eefaa7](https://github.com/angular/angular.js/commit/eefaa76a90dbef08fdc7d734a205cc2de50d9f91), <add> [#16164](https://github.com/angular/angular.js/issues/16164), <add> [#16471](https://github.com/angular/angular.js/issues/16471)) <add>- **urlUtils:** make IPv6 URL's hostname wrapped in square brackets in IE/Edge <add> ([0e1bd7](https://github.com/angular/angular.js/commit/0e1bd7822e61822a48b8fd7ba5913a8702e6dabf), <add> [#16692](https://github.com/angular/angular.js/issues/16692), <add> [#16715](https://github.com/angular/angular.js/issues/16715)) <add>- **ngAnimateSwap:** make it compatible with `ngIf` on the same element <add> ([b27080](https://github.com/angular/angular.js/commit/b27080d52546409fb4e483f212f03616e2ca8037), <add> [#16616](https://github.com/angular/angular.js/issues/16616), <add> [#16729](https://github.com/angular/angular.js/issues/16729)) <add>- **ngMock:** make matchLatestDefinitionEnabled work <add> ([3cdffc](https://github.com/angular/angular.js/commit/3cdffcecbae71189b4db69b57fadda6608a23b61), <add> [#16702](https://github.com/angular/angular.js/issues/16702)) <add>- **ngStyle:** skip setting empty value when new style has the property <add> ([d6098e](https://github.com/angular/angular.js/commit/d6098eeb1c9510d599e9bd3cfdba7dd21e7a55a5), <add> [#16709](https://github.com/angular/angular.js/issues/16709)) <add> <add>## Performance Improvements <add>- **input:** prevent multiple validations on initialization <add> ([692622](https://github.com/angular/angular.js/commit/69262239632027b373258e75c670b89132ad9edb), <add> [#14691](https://github.com/angular/angular.js/issues/14691), <add> [#16760](https://github.com/angular/angular.js/issues/16760)) <add> <add> <add> <ide> <a name="1.7.5"></a> <ide> # 1.7.5 anti-prettification (2018-10-04) <ide>
1
Java
Java
use contentnegotiationmanager for static resources
f1622569065374352b44a8e8dee9a16bbacef5a7
<ide><path>spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManager.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public List<ContentNegotiationStrategy> getStrategies() { <ide> return this.strategies; <ide> } <ide> <add> /** <add> * Find a {@code ContentNegotiationStrategy} of the given type. <add> * @param strategyType the strategy type <add> * @return the first matching strategy or {@code null}. <add> * @since 4.3 <add> */ <add> @SuppressWarnings("unchecked") <add> public <T extends ContentNegotiationStrategy> T getStrategy(Class<T> strategyType) { <add> for (ContentNegotiationStrategy strategy : getStrategies()) { <add> if (strategyType.isInstance(strategy)) { <add> return (T) strategy; <add> } <add> } <add> return null; <add> } <add> <ide> /** <ide> * Register more {@code MediaTypeFileExtensionResolver} instances in addition <ide> * to those detected at construction. <ide><path>spring-web/src/main/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategy.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 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.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.http.MediaType; <add>import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.HttpMediaTypeNotAcceptableException; <ide> protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension) <ide> throw new HttpMediaTypeNotAcceptableException(getAllMediaTypes()); <ide> } <ide> <add> /** <add> * A public method exposing the knowledge of the path extension strategy to <add> * resolve file extensions to a MediaType in this case for a given <add> * {@link Resource}. The method first looks up any explicitly registered <add> * file extensions first and then falls back on JAF if available. <add> * @param resource the resource to look up <add> * @return the MediaType for the extension or {@code null}. <add> * @since 4.3 <add> */ <add> public MediaType getMediaTypeForResource(Resource resource) { <add> Assert.notNull(resource); <add> MediaType mediaType = null; <add> String filename = resource.getFilename(); <add> String extension = StringUtils.getFilenameExtension(filename); <add> if (extension != null) { <add> mediaType = lookupMediaType(extension); <add> } <add> if (mediaType == null && JAF_PRESENT) { <add> mediaType = JafMediaTypeFactory.getMediaType(filename); <add> } <add> if (MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) { <add> mediaType = null; <add> } <add> return mediaType; <add> } <add> <ide> <ide> /** <ide> * Inner class to avoid hard-coded dependency on JAF. <ide><path>spring-web/src/main/java/org/springframework/web/accept/ServletPathExtensionContentNegotiationStrategy.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.util.Map; <ide> import javax.servlet.ServletContext; <ide> <add>import org.springframework.core.io.Resource; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.StringUtils; <ide> protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension) <ide> return mediaType; <ide> } <ide> <add> /** <add> * Extends the base class <add> * {@link PathExtensionContentNegotiationStrategy#getMediaTypeForResource} <add> * with the ability to also look up through the ServletContext. <add> * @param resource the resource to look up <add> * @return the MediaType for the extension or {@code null}. <add> * @since 4.3 <add> */ <add> public MediaType getMediaTypeForResource(Resource resource) { <add> MediaType mediaType = super.getMediaTypeForResource(resource); <add> if (mediaType == null) { <add> String mimeType = this.servletContext.getMimeType(resource.getFilename()); <add> if (StringUtils.hasText(mimeType)) { <add> mediaType = MediaType.parseMediaType(mimeType); <add> } <add> } <add> if (MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) { <add> mediaType = null; <add> } <add> return mediaType; <add> } <add> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.HttpMediaTypeNotAcceptableException; <ide> import org.springframework.web.accept.ContentNegotiationManager; <del>import org.springframework.web.accept.ContentNegotiationStrategy; <ide> import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; <ide> import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.ServletWebRequest; <ide> protected AbstractMessageConverterMethodProcessor(List<HttpMessageConverter<?>> <ide> } <ide> <ide> private static PathExtensionContentNegotiationStrategy initPathStrategy(ContentNegotiationManager manager) { <del> for (ContentNegotiationStrategy strategy : manager.getStrategies()) { <del> if (strategy instanceof PathExtensionContentNegotiationStrategy) { <del> return (PathExtensionContentNegotiationStrategy) strategy; <del> } <del> } <del> return new PathExtensionContentNegotiationStrategy(); <add> Class<PathExtensionContentNegotiationStrategy> clazz = PathExtensionContentNegotiationStrategy.class; <add> PathExtensionContentNegotiationStrategy strategy = manager.getStrategy(clazz); <add> return (strategy != null ? strategy : new PathExtensionContentNegotiationStrategy()); <ide> } <ide> <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java <ide> import java.net.URLDecoder; <ide> import java.util.ArrayList; <ide> import java.util.List; <del>import javax.activation.FileTypeMap; <del>import javax.activation.MimetypesFileTypeMap; <ide> import javax.servlet.ServletException; <ide> import javax.servlet.ServletOutputStream; <ide> import javax.servlet.http.HttpServletRequest; <ide> import org.apache.commons.logging.LogFactory; <ide> <ide> import org.springframework.beans.factory.InitializingBean; <del>import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.util.ResourceUtils; <ide> import org.springframework.util.StreamUtils; <ide> import org.springframework.util.StringUtils; <add>import org.springframework.web.HttpMediaTypeNotAcceptableException; <ide> import org.springframework.web.HttpRequestHandler; <add>import org.springframework.web.accept.ContentNegotiationManager; <add>import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; <add>import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; <ide> import org.springframework.web.context.request.ServletWebRequest; <ide> import org.springframework.web.cors.CorsConfiguration; <ide> import org.springframework.web.cors.CorsConfigurationSource; <ide> public class ResourceHttpRequestHandler extends WebContentGenerator <ide> <ide> private final List<ResourceTransformer> resourceTransformers = new ArrayList<ResourceTransformer>(4); <ide> <add> private ContentNegotiationManager contentNegotiationManager; <add> <ide> private CorsConfiguration corsConfiguration; <ide> <ide> <ide> public List<ResourceTransformer> getResourceTransformers() { <ide> return this.resourceTransformers; <ide> } <ide> <add> /** <add> * Configure a {@code ContentNegotiationManager} to determine the media types <add> * for resources being served. If the manager contains a path <add> * extension strategy it will be used to look up the file extension <add> * of resources being served via <add> * {@link PathExtensionContentNegotiationStrategy#getMediaTypeForResource <add> * getMediaTypeForResource}. If that fails the check is then expanded <add> * to use any configured content negotiation strategy against the request. <add> * <p>By default a {@link ContentNegotiationManagerFactoryBean} with default <add> * settings is used to create the manager. See the Javadoc of <add> * {@code ContentNegotiationManagerFactoryBean} for details <add> * @param contentNegotiationManager the manager to use <add> * @since 4.3 <add> */ <add> public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { <add> this.contentNegotiationManager = contentNegotiationManager; <add> } <add> <add> public ContentNegotiationManager getContentNegotiationManager() { <add> return this.contentNegotiationManager; <add> } <add> <ide> /** <ide> * Specify the CORS configuration for resources served by this handler. <ide> * <p>By default this is not set in which allows cross-origin requests. <ide> public void afterPropertiesSet() throws Exception { <ide> this.resourceResolvers.add(new PathResourceResolver()); <ide> } <ide> initAllowedLocations(); <add> <add> if (this.contentNegotiationManager == null) { <add> this.contentNegotiationManager = initContentNegotiationManager(); <add> } <ide> } <ide> <ide> /** <ide> protected void initAllowedLocations() { <ide> } <ide> } <ide> <add> /** <add> * Create the {@code ContentNegotiationManager} to use to resolve the <add> * {@link MediaType} for requests. This implementation delegates to <add> * {@link ContentNegotiationManagerFactoryBean} with default settings. <add> */ <add> protected ContentNegotiationManager initContentNegotiationManager() { <add> ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean(); <add> factory.afterPropertiesSet(); <add> return factory.getObject(); <add> } <add> <ide> <ide> /** <ide> * Processes a resource request. <ide> public void handleRequest(HttpServletRequest request, HttpServletResponse respon <ide> // Apply cache settings, if any <ide> prepareResponse(response); <ide> <del> // Check the resource's media type <del> MediaType mediaType = getMediaType(resource); <add> // Check the media type for the resource <add> MediaType mediaType = getMediaType(request, resource); <ide> if (mediaType != null) { <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Determined media type '" + mediaType + "' for " + resource); <ide> protected boolean isInvalidPath(String path) { <ide> } <ide> <ide> /** <del> * Determine an appropriate media type for the given resource. <add> * Determine the media type for the given request and the resource matched <add> * to it. This implementation first tries to determine the MediaType based <add> * strictly on the file extension of the Resource via <add> * {@link PathExtensionContentNegotiationStrategy#getMediaTypeForResource} <add> * and then expands to check against the request via <add> * {@link ContentNegotiationManager#resolveMediaTypes}. <add> * @param request the current request <ide> * @param resource the resource to check <ide> * @return the corresponding media type, or {@code null} if none found <ide> */ <del> protected MediaType getMediaType(Resource resource) { <del> MediaType mediaType = null; <del> String mimeType = getServletContext().getMimeType(resource.getFilename()); <del> if (StringUtils.hasText(mimeType)) { <del> mediaType = MediaType.parseMediaType(mimeType); <del> } <del> if (jafPresent && (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType))) { <del> MediaType jafMediaType = ActivationMediaTypeFactory.getMediaType(resource.getFilename()); <del> if (jafMediaType != null && !MediaType.APPLICATION_OCTET_STREAM.equals(jafMediaType)) { <del> mediaType = jafMediaType; <add> @SuppressWarnings("deprecation") <add> protected MediaType getMediaType(HttpServletRequest request, Resource resource) { <add> <add> // For backwards compatibility <add> MediaType mediaType = getMediaType(resource); <add> if (mediaType != null) { <add> return mediaType; <add> } <add> <add> Class<PathExtensionContentNegotiationStrategy> clazz = PathExtensionContentNegotiationStrategy.class; <add> PathExtensionContentNegotiationStrategy strategy = this.contentNegotiationManager.getStrategy(clazz); <add> if (strategy != null) { <add> mediaType = strategy.getMediaTypeForResource(resource); <add> } <add> <add> if (mediaType == null) { <add> ServletWebRequest webRequest = new ServletWebRequest(request); <add> try { <add> getContentNegotiationManager().resolveMediaTypes(webRequest); <add> } <add> catch (HttpMediaTypeNotAcceptableException ex) { <add> // Ignore <ide> } <ide> } <add> <ide> return mediaType; <ide> } <ide> <add> /** <add> * Determine an appropriate media type for the given resource. <add> * @param resource the resource to check <add> * @return the corresponding media type, or {@code null} if none found <add> * @deprecated as of 4.3 this method is deprecated; please override <add> * {@link #getMediaType(HttpServletRequest, Resource)} instead. <add> */ <add> @Deprecated <add> protected MediaType getMediaType(Resource resource) { <add> return null; <add> } <add> <ide> /** <ide> * Set headers on the given servlet response. <ide> * Called for GET requests as well as HEAD requests. <ide> public String toString() { <ide> return "ResourceHttpRequestHandler [locations=" + getLocations() + ", resolvers=" + getResourceResolvers() + "]"; <ide> } <ide> <del> <del> /** <del> * Inner class to avoid a hard-coded JAF dependency. <del> */ <del> private static class ActivationMediaTypeFactory { <del> <del> private static final FileTypeMap fileTypeMap; <del> <del> static { <del> fileTypeMap = loadFileTypeMapFromContextSupportModule(); <del> } <del> <del> private static FileTypeMap loadFileTypeMapFromContextSupportModule() { <del> // See if we can find the extended mime.types from the context-support module... <del> Resource mappingLocation = new ClassPathResource("org/springframework/mail/javamail/mime.types"); <del> if (mappingLocation.exists()) { <del> InputStream inputStream = null; <del> try { <del> inputStream = mappingLocation.getInputStream(); <del> return new MimetypesFileTypeMap(inputStream); <del> } <del> catch (IOException ex) { <del> // ignore <del> } <del> finally { <del> if (inputStream != null) { <del> try { <del> inputStream.close(); <del> } <del> catch (IOException ex) { <del> // ignore <del> } <del> } <del> } <del> } <del> return FileTypeMap.getDefaultFileTypeMap(); <del> } <del> <del> public static MediaType getMediaType(String filename) { <del> String mediaType = fileTypeMap.getContentType(filename); <del> return (StringUtils.hasText(mediaType) ? MediaType.parseMediaType(mediaType) : null); <del> } <del> } <del> <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java <ide> import org.springframework.core.io.UrlResource; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.HttpStatus; <add>import org.springframework.http.MediaType; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.mock.web.test.MockHttpServletResponse; <ide> import org.springframework.mock.web.test.MockServletContext; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.HttpRequestMethodNotSupportedException; <add>import org.springframework.web.accept.ContentNegotiationManager; <add>import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; <ide> import org.springframework.web.servlet.HandlerMapping; <ide> <ide> /** <ide> public void getResourceFromSubDirectoryOfAlternatePath() throws Exception { <ide> assertEquals("function foo() { console.log(\"hello world\"); }", this.response.getContentAsString()); <ide> } <ide> <add> @Test // SPR-13658 <add> public void getResourceWithRegisteredMediaType() throws Exception { <add> ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean(); <add> factory.addMediaType("css", new MediaType("foo", "bar")); <add> factory.afterPropertiesSet(); <add> ContentNegotiationManager manager = factory.getObject(); <add> <add> List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass())); <add> this.handler = new ResourceHttpRequestHandler(); <add> this.handler.setLocations(paths); <add> this.handler.setContentNegotiationManager(manager); <add> this.handler.afterPropertiesSet(); <add> <add> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); <add> this.handler.handleRequest(this.request, this.response); <add> <add> assertEquals("foo/bar", this.response.getContentType()); <add> assertEquals("h1 { color:red; }", this.response.getContentAsString()); <add> } <add> <ide> @Test <ide> public void invalidPath() throws Exception { <ide> for (HttpMethod method : HttpMethod.values()) {
6
Javascript
Javascript
add tests for eventemitter.
871bc4e06b4cede9060972423c06e71d0d3ade22
<ide><path>lib/EventEmitter.js <ide> export default class EventEmitter { <ide> this.listeners[event] = new Set() <ide> } <ide> <add> if (this.listeners[event].has(cb)) { <add> throw new Error(`The listener already exising in event: ${event}`) <add> } <add> <ide> this.listeners[event].add(cb) <ide> } <ide> <ide> export default class EventEmitter { <ide> } <ide> <ide> off (event, cb) { <del> if (!this.listeners[event]) return <ide> this.listeners[event].delete(cb) <ide> } <ide> } <ide><path>test/unit/EventEmitter.test.js <add>/* global describe, it, expect */ <add>import EventEmitter from '../../dist/lib/EventEmitter' <add> <add>describe('EventEmitter', () => { <add> describe('With listeners', () => { <add> it('should listen to a event', (done) => { <add> const ev = new EventEmitter() <add> ev.on('sample', done) <add> ev.emit('sample') <add> }) <add> <add> it('should listen to multiple listeners', () => { <add> const ev = new EventEmitter() <add> let cnt = 0 <add> <add> ev.on('sample', () => { cnt += 1 }) <add> ev.on('sample', () => { cnt += 1 }) <add> <add> ev.emit('sample') <add> <add> expect(cnt).toBe(2) <add> }) <add> <add> it('should listen to multiple events', () => { <add> const ev = new EventEmitter() <add> const data = [] <add> const cb = (name) => { data.push(name) } <add> <add> ev.on('sample1', cb) <add> ev.on('sample2', cb) <add> <add> ev.emit('sample1', 'one') <add> ev.emit('sample2', 'two') <add> <add> expect(data).toEqual(['one', 'two']) <add> }) <add> <add> it('should support multiple arguments', () => { <add> const ev = new EventEmitter() <add> let data <add> <add> ev.on('sample', (...args) => { data = args }) <add> ev.emit('sample', 'one', 'two') <add> <add> expect(data).toEqual(['one', 'two']) <add> }) <add> <add> it('should possible to stop listening an event', () => { <add> const ev = new EventEmitter() <add> let cnt = 0 <add> const cb = () => { cnt += 1 } <add> <add> ev.on('sample', cb) <add> <add> ev.emit('sample') <add> expect(cnt).toBe(1) <add> <add> ev.off('sample', cb) <add> <add> ev.emit('sample') <add> expect(cnt).toBe(1) <add> }) <add> <add> it('should throw when try to add the same listener multiple times', () => { <add> const ev = new EventEmitter() <add> const cb = () => {} <add> <add> ev.on('sample', cb) <add> <add> const run = () => ev.on('sample', cb) <add> <add> expect(run).toThrow(/The listener already exising in event: sample/) <add> }) <add> }) <add> <add> describe('Without a listener', () => { <add> it('should not fail to emit', () => { <add> const ev = new EventEmitter() <add> ev.emit('aaaa', 10, 20) <add> }) <add> }) <add>})
2
Python
Python
make training work with directories
2efdbc08ffecba1555fea5b7af6444eed968d009
<ide><path>spacy/cli/train.py <ide> def evaluate(Language, gold_tuples, output_path): <ide> def check_dirs(output_path, train_path, dev_path): <ide> if not output_path.exists(): <ide> util.sys_exit(output_path.as_posix(), title="Output directory not found") <del> if not train_path.exists() or not train_path.is_file(): <add> if not train_path.exists(): <ide> util.sys_exit(train_path.as_posix(), title="Training data not found") <ide> if dev_path and not dev_path.exists(): <ide> util.sys_exit(dev_path.as_posix(), title="Development data not found")
1
Python
Python
fix typo kill( -> os.kill(
3ec624467e27c9c779fa399c313a1cdbf122eb13
<ide><path>celery/pool.py <ide> <ide> def pid_is_dead(pid): <ide> try: <del> return kill(pid, 0) <add> return os.kill(pid, 0) <ide> except OSError, err: <ide> if err.errno == errno.ESRCH: <ide> return True # No such process. <ide> def is_dead(self, process): <ide> return True <ide> <ide> # Then try to ping the process using its pipe. <del> return not process.is_alive() <add> try: <add> proc_is_alive = process.is_alive() <add> except OSError: <add> return True <add> else: <add> return not proc_is_alive <ide> <ide> def replace_dead_workers(self): <ide> dead_processes = filter(self.is_dead, self._pool)
1
Ruby
Ruby
require xcode 13.1 on monterey
5d670728f153c16583c08b43c18e2c9547eed084
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> module Xcode <ide> def latest_version(macos: MacOS.version) <ide> latest_stable = "13.0" <ide> case macos <del> when "12" then "13.0" <add> when "12" then "13.1" <ide> when "11" then latest_stable <ide> when "10.15" then "12.4" <ide> when "10.14" then "11.3.1" <ide> def latest_version(macos: MacOS.version) <ide> sig { returns(String) } <ide> def minimum_version <ide> case MacOS.version <del> when "12" then "13.0" <add> when "12" then "13.1" <ide> when "11" then "12.2" <ide> when "10.15" then "11.0" <ide> when "10.14" then "10.2"
1
PHP
PHP
implement console command for clearing the cache
13a27926dacc4c8683ead862de3fc31d8c7e1c78
<ide><path>src/Illuminate/Cache/CommandsServiceProvider.php <add><?php namespace Illuminate\Cache; <add> <add>use Illuminate\Support\ServiceProvider; <add> <add>class CommandsServiceProvider extends ServiceProvider { <add> <add> /** <add> * Indicates if loading of the provider is deferred. <add> * <add> * @var bool <add> */ <add> protected $defer = true; <add> <add> /** <add> * Register the service provider. <add> * <add> * @return void <add> */ <add> public function register() <add> { <add> $app = $this->app; <add> <add> $app['command.cache.clear'] = $app->share(function($app) <add> { <add> return new Console\ClearCommand($app['cache']); <add> }); <add> <add> $this->commands('command.cache.clear'); <add> } <add> <add> /** <add> * Get the services provided by the provider. <add> * <add> * @return array <add> */ <add> public function provides() <add> { <add> return array('command.cache.clear'); <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>src/Illuminate/Cache/Console/ClearCommand.php <add><?php namespace Illuminate\Cache\Console; <add> <add>use Illuminate\Console\Command; <add> <add>class ClearCommand extends Command { <add> <add> /** <add> * The console command name. <add> * <add> * @var string <add> */ <add> protected $name = 'cache:clear'; <add> <add> /** <add> * The console command description. <add> * <add> * @var string <add> */ <add> protected $description = "Flush the entire cache."; <add> <add> /** <add> * The cache manager instance. <add> * <add> * @var \Illuminate\Cache\CacheManager <add> */ <add> protected $cache; <add> <add> /** <add> * Create a new cache clear command instance. <add> * <add> * @param \Illuminate\Cache\CacheManager $cache <add> * @return void <add> */ <add> public function __construct(CacheManager $cache) <add> { <add> parent::__construct(); <add> <add> $this->cache = $cache; <add> } <add> <add> /** <add> * Execute the console command. <add> * <add> * @return void <add> */ <add> public function fire() <add> { <add> $this->cache->flush(); <add> } <add> <add>} <ide>\ No newline at end of file
2
Python
Python
replace xrange => range
5fa4857530bcf5c0af7140109117449b54c000dd
<ide><path>examples/mnist_net2net.py <ide> ''' <ide> <ide> from __future__ import print_function <del>from six.moves import xrange <ide> import numpy as np <ide> import keras <ide> from keras.models import Sequential <ide> def deeper2net_conv2d(teacher_w): <ide> ''' <ide> filters, num_channel, kh, kw = teacher_w.shape <ide> student_w = np.zeros((filters, filters, kh, kw)) <del> for i in xrange(filters): <add> for i in range(filters): <ide> student_w[i, i, (kh - 1) / 2, (kw - 1) / 2] = 1. <ide> student_b = np.zeros(filters) <ide> return student_w, student_b
1
Go
Go
add support for host port publishmode in services
14ac9f60d0174256e0713701ebffaf5ca827da71
<ide><path>api/types/swarm/network.go <ide> type PortConfig struct { <ide> TargetPort uint32 `json:",omitempty"` <ide> // PublishedPort is the port on the swarm hosts <ide> PublishedPort uint32 `json:",omitempty"` <add> // PublishMode is the mode in which port is published <add> PublishMode PortConfigPublishMode `json:",omitempty"` <ide> } <ide> <add>// PortConfigPublishMode represents the mode in which the port is to <add>// be published. <add>type PortConfigPublishMode string <add> <add>const ( <add> // PortConfigPublishModeIngress is used for ports published <add> // for ingress load balancing using routing mesh. <add> PortConfigPublishModeIngress PortConfigPublishMode = "ingress" <add> // PortConfigPublishModeHost is used for ports published <add> // for direct host level access on the host where the task is running. <add> PortConfigPublishModeHost PortConfigPublishMode = "host" <add>) <add> <ide> // PortConfigProtocol represents the protocol of a port. <ide> type PortConfigProtocol string <ide> <ide><path>api/types/swarm/task.go <ide> type TaskStatus struct { <ide> Message string `json:",omitempty"` <ide> Err string `json:",omitempty"` <ide> ContainerStatus ContainerStatus `json:",omitempty"` <add> PortStatus PortStatus `json:",omitempty"` <ide> } <ide> <ide> // ContainerStatus represents the status of a container. <ide> type ContainerStatus struct { <ide> PID int `json:",omitempty"` <ide> ExitCode int `json:",omitempty"` <ide> } <add> <add>// PortStatus represents the port status of a task's host ports whose <add>// service has published host ports <add>type PortStatus struct { <add> Ports []PortConfig `json:",omitempty"` <add>} <ide><path>cli/command/service/create.go <ide> func newCreateCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> flags.Var(&opts.constraints, flagConstraint, "Placement constraints") <ide> flags.Var(&opts.networks, flagNetwork, "Network attachments") <ide> flags.Var(&opts.secrets, flagSecret, "Specify secrets to expose to the service") <del> flags.VarP(&opts.endpoint.ports, flagPublish, "p", "Publish a port as a node port") <add> flags.VarP(&opts.endpoint.publishPorts, flagPublish, "p", "Publish a port as a node port") <add> flags.MarkHidden(flagPublish) <ide> flags.Var(&opts.groups, flagGroup, "Set one or more supplementary user groups for the container") <ide> flags.Var(&opts.dns, flagDNS, "Set custom DNS servers") <ide> flags.Var(&opts.dnsOption, flagDNSOption, "Set DNS options") <ide> flags.Var(&opts.dnsSearch, flagDNSSearch, "Set custom DNS search domains") <ide> flags.Var(&opts.hosts, flagHost, "Set one or more custom host-to-IP mappings (host:ip)") <add> flags.Var(&opts.endpoint.expandedPorts, flagPort, "Publish a port") <ide> <ide> flags.SetInterspersed(false) <ide> return cmd <ide><path>cli/command/service/opts.go <ide> func convertNetworks(networks []string) []swarm.NetworkAttachmentConfig { <ide> } <ide> <ide> type endpointOptions struct { <del> mode string <del> ports opts.ListOpts <add> mode string <add> publishPorts opts.ListOpts <add> expandedPorts opts.PortOpt <ide> } <ide> <ide> func (e *endpointOptions) ToEndpointSpec() *swarm.EndpointSpec { <ide> portConfigs := []swarm.PortConfig{} <ide> // We can ignore errors because the format was already validated by ValidatePort <del> ports, portBindings, _ := nat.ParsePortSpecs(e.ports.GetAll()) <add> ports, portBindings, _ := nat.ParsePortSpecs(e.publishPorts.GetAll()) <ide> <ide> for port := range ports { <ide> portConfigs = append(portConfigs, ConvertPortToPortConfig(port, portBindings)...) <ide> } <ide> <ide> return &swarm.EndpointSpec{ <ide> Mode: swarm.ResolutionMode(strings.ToLower(e.mode)), <del> Ports: portConfigs, <add> Ports: append(portConfigs, e.expandedPorts.Value()...), <ide> } <ide> } <ide> <ide> func newServiceOptions() *serviceOptions { <ide> env: opts.NewListOpts(runconfigopts.ValidateEnv), <ide> envFile: opts.NewListOpts(nil), <ide> endpoint: endpointOptions{ <del> ports: opts.NewListOpts(ValidatePort), <add> publishPorts: opts.NewListOpts(ValidatePort), <ide> }, <ide> groups: opts.NewListOpts(nil), <ide> logDriver: newLogDriverOptions(), <ide> const ( <ide> flagPublish = "publish" <ide> flagPublishRemove = "publish-rm" <ide> flagPublishAdd = "publish-add" <add> flagPort = "port" <add> flagPortAdd = "port-add" <add> flagPortRemove = "port-rm" <ide> flagReplicas = "replicas" <ide> flagReserveCPU = "reserve-cpu" <ide> flagReserveMemory = "reserve-memory" <ide><path>cli/command/service/update.go <ide> func newUpdateCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> flags.Var(newListOptsVar(), flagContainerLabelRemove, "Remove a container label by its key") <ide> flags.Var(newListOptsVar(), flagMountRemove, "Remove a mount by its target path") <ide> flags.Var(newListOptsVar(), flagPublishRemove, "Remove a published port by its target port") <add> flags.MarkHidden(flagPublishRemove) <add> flags.Var(newListOptsVar(), flagPortRemove, "Remove a port(target-port mandatory)") <ide> flags.Var(newListOptsVar(), flagConstraintRemove, "Remove a constraint") <ide> flags.Var(newListOptsVar(), flagDNSRemove, "Remove a custom DNS server") <ide> flags.Var(newListOptsVar(), flagDNSOptionRemove, "Remove a DNS option") <ide> func newUpdateCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> flags.Var(&opts.secrets, flagSecretAdd, "Add or update a secret on a service") <ide> flags.Var(&opts.mounts, flagMountAdd, "Add or update a mount on a service") <ide> flags.Var(&opts.constraints, flagConstraintAdd, "Add or update a placement constraint") <del> flags.Var(&opts.endpoint.ports, flagPublishAdd, "Add or update a published port") <add> flags.Var(&opts.endpoint.publishPorts, flagPublishAdd, "Add or update a published port") <add> flags.MarkHidden(flagPublishAdd) <add> flags.Var(&opts.endpoint.expandedPorts, flagPortAdd, "Add or update a port") <ide> flags.Var(&opts.groups, flagGroupAdd, "Add an additional supplementary user group to the container") <ide> flags.Var(&opts.dns, flagDNSAdd, "Add or update a custom DNS server") <ide> flags.Var(&opts.dnsOption, flagDNSOptionAdd, "Add or update a DNS option") <ide> func updateService(flags *pflag.FlagSet, spec *swarm.ServiceSpec) error { <ide> } <ide> } <ide> <del> if anyChanged(flags, flagPublishAdd, flagPublishRemove) { <add> if anyChanged(flags, flagPublishAdd, flagPublishRemove, flagPortAdd, flagPortRemove) { <ide> if spec.EndpointSpec == nil { <ide> spec.EndpointSpec = &swarm.EndpointSpec{} <ide> } <ide> func portConfigToString(portConfig *swarm.PortConfig) string { <ide> if protocol == "" { <ide> protocol = "tcp" <ide> } <del> return fmt.Sprintf("%v/%s", portConfig.PublishedPort, protocol) <add> <add> mode := portConfig.PublishMode <add> if mode == "" { <add> mode = "ingress" <add> } <add> <add> return fmt.Sprintf("%v:%v/%s/%s", portConfig.PublishedPort, portConfig.TargetPort, protocol, mode) <ide> } <ide> <ide> func updatePorts(flags *pflag.FlagSet, portConfig *[]swarm.PortConfig) error { <ide> func updatePorts(flags *pflag.FlagSet, portConfig *[]swarm.PortConfig) error { <ide> } <ide> } <ide> <add> if flags.Changed(flagPortAdd) { <add> for _, entry := range flags.Lookup(flagPortAdd).Value.(*opts.PortOpt).Value() { <add> if v, ok := portSet[portConfigToString(&entry)]; ok && v != entry { <add> return fmt.Errorf("conflicting port mapping between %v:%v/%s and %v:%v/%s", entry.PublishedPort, entry.TargetPort, entry.Protocol, v.PublishedPort, v.TargetPort, v.Protocol) <add> } <add> portSet[portConfigToString(&entry)] = entry <add> } <add> } <add> <ide> // Override previous PortConfig in service if there is any duplicate <ide> for _, entry := range *portConfig { <ide> if _, ok := portSet[portConfigToString(&entry)]; !ok { <ide> func updatePorts(flags *pflag.FlagSet, portConfig *[]swarm.PortConfig) error { <ide> } <ide> <ide> toRemove := flags.Lookup(flagPublishRemove).Value.(*opts.ListOpts).GetAll() <add> removePortCSV := flags.Lookup(flagPortRemove).Value.(*opts.ListOpts).GetAll() <add> removePortOpts := &opts.PortOpt{} <add> for _, portCSV := range removePortCSV { <add> if err := removePortOpts.Set(portCSV); err != nil { <add> return err <add> } <add> } <add> <ide> newPorts := []swarm.PortConfig{} <ide> portLoop: <ide> for _, port := range portSet { <ide> portLoop: <ide> continue portLoop <ide> } <ide> } <add> <add> for _, pConfig := range removePortOpts.Value() { <add> if equalProtocol(port.Protocol, pConfig.Protocol) && <add> port.TargetPort == pConfig.TargetPort && <add> equalPublishMode(port.PublishMode, pConfig.PublishMode) { <add> continue portLoop <add> } <add> } <add> <ide> newPorts = append(newPorts, port) <ide> } <add> <ide> // Sort the PortConfig to avoid unnecessary updates <ide> sort.Sort(byPortConfig(newPorts)) <ide> *portConfig = newPorts <ide> return nil <ide> } <ide> <add>func equalProtocol(prot1, prot2 swarm.PortConfigProtocol) bool { <add> return prot1 == prot2 || <add> (prot1 == swarm.PortConfigProtocol("") && prot2 == swarm.PortConfigProtocolTCP) || <add> (prot2 == swarm.PortConfigProtocol("") && prot1 == swarm.PortConfigProtocolTCP) <add>} <add> <add>func equalPublishMode(mode1, mode2 swarm.PortConfigPublishMode) bool { <add> return mode1 == mode2 || <add> (mode1 == swarm.PortConfigPublishMode("") && mode2 == swarm.PortConfigPublishModeIngress) || <add> (mode2 == swarm.PortConfigPublishMode("") && mode1 == swarm.PortConfigPublishModeIngress) <add>} <add> <ide> func equalPort(targetPort nat.Port, port swarm.PortConfig) bool { <ide> return (string(port.Protocol) == targetPort.Proto() && <ide> port.TargetPort == uint32(targetPort.Int())) <ide><path>cli/command/service/update_test.go <ide> func TestUpdatePortsDuplicateEntries(t *testing.T) { <ide> func TestUpdatePortsDuplicateKeys(t *testing.T) { <ide> // Test case for #25375 <ide> flags := newUpdateCommand(nil).Flags() <del> flags.Set("publish-add", "80:20") <add> flags.Set("publish-add", "80:80") <ide> <ide> portConfigs := []swarm.PortConfig{ <ide> {TargetPort: 80, PublishedPort: 80}, <ide> func TestUpdatePortsDuplicateKeys(t *testing.T) { <ide> err := updatePorts(flags, &portConfigs) <ide> assert.Equal(t, err, nil) <ide> assert.Equal(t, len(portConfigs), 1) <del> assert.Equal(t, portConfigs[0].TargetPort, uint32(20)) <del>} <del> <del>func TestUpdatePortsConflictingFlags(t *testing.T) { <del> // Test case for #25375 <del> flags := newUpdateCommand(nil).Flags() <del> flags.Set("publish-add", "80:80") <del> flags.Set("publish-add", "80:20") <del> <del> portConfigs := []swarm.PortConfig{ <del> {TargetPort: 80, PublishedPort: 80}, <del> } <del> <del> err := updatePorts(flags, &portConfigs) <del> assert.Error(t, err, "conflicting port mapping") <add> assert.Equal(t, portConfigs[0].TargetPort, uint32(80)) <ide> } <ide> <ide> func TestUpdateHealthcheckTable(t *testing.T) { <ide><path>cli/command/task/print.go <ide> import ( <ide> ) <ide> <ide> const ( <del> psTaskItemFmt = "%s\t%s\t%s\t%s\t%s %s ago\t%s\n" <add> psTaskItemFmt = "%s\t%s\t%s\t%s\t%s %s ago\t%s\t%s\n" <ide> maxErrLength = 30 <ide> ) <ide> <add>type portStatus swarm.PortStatus <add> <add>func (ps portStatus) String() string { <add> if len(ps.Ports) == 0 { <add> return "" <add> } <add> <add> str := fmt.Sprintf("*:%d->%d/%s", ps.Ports[0].PublishedPort, ps.Ports[0].TargetPort, ps.Ports[0].Protocol) <add> for _, pConfig := range ps.Ports[1:] { <add> str += fmt.Sprintf(",*:%d->%d/%s", pConfig.PublishedPort, pConfig.TargetPort, pConfig.Protocol) <add> } <add> <add> return str <add>} <add> <ide> type tasksBySlot []swarm.Task <ide> <ide> func (t tasksBySlot) Len() int { <ide> func Print(dockerCli *command.DockerCli, ctx context.Context, tasks []swarm.Task <ide> <ide> // Ignore flushing errors <ide> defer writer.Flush() <del> fmt.Fprintln(writer, strings.Join([]string{"NAME", "IMAGE", "NODE", "DESIRED STATE", "CURRENT STATE", "ERROR"}, "\t")) <add> fmt.Fprintln(writer, strings.Join([]string{"NAME", "IMAGE", "NODE", "DESIRED STATE", "CURRENT STATE", "ERROR", "PORTS"}, "\t")) <ide> <ide> if err := print(writer, ctx, tasks, resolver, noTrunc); err != nil { <ide> return err <ide> func print(out io.Writer, ctx context.Context, tasks []swarm.Task, resolver *idr <ide> command.PrettyPrint(task.Status.State), <ide> strings.ToLower(units.HumanDuration(time.Since(task.Status.Timestamp))), <ide> taskErr, <add> portStatus(task.Status.PortStatus), <ide> ) <ide> } <ide> return nil <ide><path>daemon/cluster/convert/network.go <ide> func endpointSpecFromGRPC(es *swarmapi.EndpointSpec) *types.EndpointSpec { <ide> endpointSpec.Ports = append(endpointSpec.Ports, types.PortConfig{ <ide> Name: portState.Name, <ide> Protocol: types.PortConfigProtocol(strings.ToLower(swarmapi.PortConfig_Protocol_name[int32(portState.Protocol)])), <add> PublishMode: types.PortConfigPublishMode(strings.ToLower(swarmapi.PortConfig_PublishMode_name[int32(portState.PublishMode)])), <ide> TargetPort: portState.TargetPort, <ide> PublishedPort: portState.PublishedPort, <ide> }) <ide> func endpointFromGRPC(e *swarmapi.Endpoint) types.Endpoint { <ide> endpoint.Ports = append(endpoint.Ports, types.PortConfig{ <ide> Name: portState.Name, <ide> Protocol: types.PortConfigProtocol(strings.ToLower(swarmapi.PortConfig_Protocol_name[int32(portState.Protocol)])), <add> PublishMode: types.PortConfigPublishMode(strings.ToLower(swarmapi.PortConfig_PublishMode_name[int32(portState.PublishMode)])), <ide> TargetPort: portState.TargetPort, <ide> PublishedPort: portState.PublishedPort, <ide> }) <ide><path>daemon/cluster/convert/service.go <ide> func ServiceSpecToGRPC(s types.ServiceSpec) (swarmapi.ServiceSpec, error) { <ide> spec.Endpoint.Ports = append(spec.Endpoint.Ports, &swarmapi.PortConfig{ <ide> Name: portConfig.Name, <ide> Protocol: swarmapi.PortConfig_Protocol(swarmapi.PortConfig_Protocol_value[strings.ToUpper(string(portConfig.Protocol))]), <add> PublishMode: swarmapi.PortConfig_PublishMode(swarmapi.PortConfig_PublishMode_value[strings.ToUpper(string(portConfig.PublishMode))]), <ide> TargetPort: portConfig.TargetPort, <ide> PublishedPort: portConfig.PublishedPort, <ide> }) <ide><path>daemon/cluster/convert/task.go <ide> func TaskFromGRPC(t swarmapi.Task) types.Task { <ide> task.NetworksAttachments = append(task.NetworksAttachments, networkAttachementFromGRPC(na)) <ide> } <ide> <add> if t.Status.PortStatus == nil { <add> return task <add> } <add> <add> for _, p := range t.Status.PortStatus.Ports { <add> task.Status.PortStatus.Ports = append(task.Status.PortStatus.Ports, types.PortConfig{ <add> Name: p.Name, <add> Protocol: types.PortConfigProtocol(strings.ToLower(swarmapi.PortConfig_Protocol_name[int32(p.Protocol)])), <add> PublishMode: types.PortConfigPublishMode(strings.ToLower(swarmapi.PortConfig_PublishMode_name[int32(p.PublishMode)])), <add> TargetPort: p.TargetPort, <add> PublishedPort: p.PublishedPort, <add> }) <add> } <add> <ide> return task <ide> } <ide><path>daemon/cluster/executor/container/container.go <ide> import ( <ide> "errors" <ide> "fmt" <ide> "net" <add> "strconv" <ide> "strings" <ide> "time" <ide> <ide> import ( <ide> volumetypes "github.com/docker/docker/api/types/volume" <ide> clustertypes "github.com/docker/docker/daemon/cluster/provider" <ide> "github.com/docker/docker/reference" <add> "github.com/docker/go-connections/nat" <ide> "github.com/docker/swarmkit/agent/exec" <ide> "github.com/docker/swarmkit/api" <ide> "github.com/docker/swarmkit/protobuf/ptypes" <ide> func (c *containerConfig) image() string { <ide> return reference.WithDefaultTag(ref).String() <ide> } <ide> <add>func (c *containerConfig) portBindings() nat.PortMap { <add> portBindings := nat.PortMap{} <add> if c.task.Endpoint == nil { <add> return portBindings <add> } <add> <add> for _, portConfig := range c.task.Endpoint.Ports { <add> if portConfig.PublishMode != api.PublishModeHost { <add> continue <add> } <add> <add> port := nat.Port(fmt.Sprintf("%d/%s", portConfig.TargetPort, strings.ToLower(portConfig.Protocol.String()))) <add> binding := []nat.PortBinding{ <add> {}, <add> } <add> <add> if portConfig.PublishedPort != 0 { <add> binding[0].HostPort = strconv.Itoa(int(portConfig.PublishedPort)) <add> } <add> portBindings[port] = binding <add> } <add> <add> return portBindings <add>} <add> <add>func (c *containerConfig) exposedPorts() map[nat.Port]struct{} { <add> exposedPorts := make(map[nat.Port]struct{}) <add> if c.task.Endpoint == nil { <add> return exposedPorts <add> } <add> <add> for _, portConfig := range c.task.Endpoint.Ports { <add> if portConfig.PublishMode != api.PublishModeHost { <add> continue <add> } <add> <add> port := nat.Port(fmt.Sprintf("%d/%s", portConfig.TargetPort, strings.ToLower(portConfig.Protocol.String()))) <add> exposedPorts[port] = struct{}{} <add> } <add> <add> return exposedPorts <add>} <add> <ide> func (c *containerConfig) config() *enginecontainer.Config { <ide> config := &enginecontainer.Config{ <del> Labels: c.labels(), <del> Tty: c.spec().TTY, <del> User: c.spec().User, <del> Env: c.spec().Env, <del> Hostname: c.spec().Hostname, <del> WorkingDir: c.spec().Dir, <del> Image: c.image(), <del> Volumes: c.volumes(), <del> Healthcheck: c.healthcheck(), <add> Labels: c.labels(), <add> Tty: c.spec().TTY, <add> User: c.spec().User, <add> Env: c.spec().Env, <add> Hostname: c.spec().Hostname, <add> WorkingDir: c.spec().Dir, <add> Image: c.image(), <add> Volumes: c.volumes(), <add> ExposedPorts: c.exposedPorts(), <add> Healthcheck: c.healthcheck(), <ide> } <ide> <ide> if len(c.spec().Command) > 0 { <ide> func getMountMask(m *api.Mount) string { <ide> <ide> func (c *containerConfig) hostConfig() *enginecontainer.HostConfig { <ide> hc := &enginecontainer.HostConfig{ <del> Resources: c.resources(), <del> Binds: c.binds(), <del> Tmpfs: c.tmpfs(), <del> GroupAdd: c.spec().Groups, <add> Resources: c.resources(), <add> Binds: c.binds(), <add> Tmpfs: c.tmpfs(), <add> GroupAdd: c.spec().Groups, <add> PortBindings: c.portBindings(), <ide> } <ide> <ide> if c.spec().DNSConfig != nil { <ide> func (c *containerConfig) serviceConfig() *clustertypes.ServiceConfig { <ide> <ide> if c.task.Endpoint != nil { <ide> for _, ePort := range c.task.Endpoint.Ports { <add> if ePort.PublishMode != api.PublishModeIngress { <add> continue <add> } <add> <ide> svcCfg.ExposedPorts = append(svcCfg.ExposedPorts, &clustertypes.PortConfig{ <ide> Name: ePort.Name, <ide> Protocol: int32(ePort.Protocol), <ide><path>daemon/cluster/executor/container/controller.go <ide> import ( <ide> "fmt" <ide> "io" <ide> "os" <add> "strconv" <add> "strings" <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/events" <ide> executorpkg "github.com/docker/docker/daemon/cluster/executor" <add> "github.com/docker/go-connections/nat" <ide> "github.com/docker/libnetwork" <ide> "github.com/docker/swarmkit/agent/exec" <ide> "github.com/docker/swarmkit/api" <ide> func (r *controller) ContainerStatus(ctx context.Context) (*api.ContainerStatus, <ide> return parseContainerStatus(ctnr) <ide> } <ide> <add>func (r *controller) PortStatus(ctx context.Context) (*api.PortStatus, error) { <add> ctnr, err := r.adapter.inspect(ctx) <add> if err != nil { <add> if isUnknownContainer(err) { <add> return nil, nil <add> } <add> <add> return nil, err <add> } <add> <add> return parsePortStatus(ctnr) <add>} <add> <ide> // Update tasks a recent task update and applies it to the container. <ide> func (r *controller) Update(ctx context.Context, t *api.Task) error { <ide> // TODO(stevvooe): While assignment of tasks is idempotent, we do allow <ide> func parseContainerStatus(ctnr types.ContainerJSON) (*api.ContainerStatus, error <ide> return status, nil <ide> } <ide> <add>func parsePortStatus(ctnr types.ContainerJSON) (*api.PortStatus, error) { <add> status := &api.PortStatus{} <add> <add> if ctnr.NetworkSettings != nil && len(ctnr.NetworkSettings.Ports) > 0 { <add> exposedPorts, err := parsePortMap(ctnr.NetworkSettings.Ports) <add> if err != nil { <add> return nil, err <add> } <add> status.Ports = exposedPorts <add> } <add> <add> return status, nil <add>} <add> <add>func parsePortMap(portMap nat.PortMap) ([]*api.PortConfig, error) { <add> exposedPorts := make([]*api.PortConfig, 0, len(portMap)) <add> <add> for portProtocol, mapping := range portMap { <add> parts := strings.SplitN(string(portProtocol), "/", 2) <add> if len(parts) != 2 { <add> return nil, fmt.Errorf("invalid port mapping: %s", portProtocol) <add> } <add> <add> port, err := strconv.ParseUint(parts[0], 10, 16) <add> if err != nil { <add> return nil, err <add> } <add> <add> protocol := api.ProtocolTCP <add> switch strings.ToLower(parts[1]) { <add> case "tcp": <add> protocol = api.ProtocolTCP <add> case "udp": <add> protocol = api.ProtocolUDP <add> default: <add> return nil, fmt.Errorf("invalid protocol: %s", parts[1]) <add> } <add> <add> for _, binding := range mapping { <add> hostPort, err := strconv.ParseUint(binding.HostPort, 10, 16) <add> if err != nil { <add> return nil, err <add> } <add> <add> // TODO(aluzzardi): We're losing the port `name` here since <add> // there's no way to retrieve it back from the Engine. <add> exposedPorts = append(exposedPorts, &api.PortConfig{ <add> PublishMode: api.PublishModeHost, <add> Protocol: protocol, <add> TargetPort: uint32(port), <add> PublishedPort: uint32(hostPort), <add> }) <add> } <add> } <add> <add> return exposedPorts, nil <add>} <add> <ide> type exitError struct { <ide> code int <ide> cause error <ide><path>integration-cli/docker_cli_service_update_test.go <ide> func (s *DockerSwarmSuite) TestServiceUpdatePort(c *check.C) { <ide> Protocol: "tcp", <ide> PublishedPort: 8082, <ide> TargetPort: 8083, <add> PublishMode: "ingress", <ide> }, <ide> } <ide> <ide><path>integration-cli/docker_cli_swarm_test.go <ide> func (s *DockerSwarmSuite) TestSwarmPublishAdd(c *check.C) { <ide> out, err = d.cmdRetryOutOfSequence("service", "update", "--publish-add", "80:80", "--publish-add", "80:20", name) <ide> c.Assert(err, checker.NotNil) <ide> <del> out, err = d.cmdRetryOutOfSequence("service", "update", "--publish-add", "80:20", name) <del> c.Assert(err, checker.IsNil) <del> <ide> out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.EndpointSpec.Ports }}", name) <ide> c.Assert(err, checker.IsNil) <del> c.Assert(strings.TrimSpace(out), checker.Equals, "[{ tcp 20 80}]") <add> c.Assert(strings.TrimSpace(out), checker.Equals, "[{ tcp 80 80 ingress}]") <ide> } <ide> <ide> func (s *DockerSwarmSuite) TestSwarmServiceWithGroup(c *check.C) { <ide><path>opts/port.go <add>package opts <add> <add>import ( <add> "encoding/csv" <add> "fmt" <add> "strconv" <add> "strings" <add> <add> "github.com/docker/docker/api/types/swarm" <add>) <add> <add>const ( <add> portOptTargetPort = "target" <add> portOptPublishedPort = "published" <add> portOptProtocol = "protocol" <add> portOptMode = "mode" <add>) <add> <add>type PortOpt struct { <add> ports []swarm.PortConfig <add>} <add> <add>// Set a new port value <add>func (p *PortOpt) Set(value string) error { <add> csvReader := csv.NewReader(strings.NewReader(value)) <add> fields, err := csvReader.Read() <add> if err != nil { <add> return err <add> } <add> <add> pConfig := swarm.PortConfig{} <add> for _, field := range fields { <add> parts := strings.SplitN(field, "=", 2) <add> if len(parts) != 2 { <add> return fmt.Errorf("invalid field %s", field) <add> } <add> <add> key := strings.ToLower(parts[0]) <add> value := strings.ToLower(parts[1]) <add> <add> switch key { <add> case portOptProtocol: <add> if value != string(swarm.PortConfigProtocolTCP) && value != string(swarm.PortConfigProtocolUDP) { <add> return fmt.Errorf("invalid protocol value %s", value) <add> } <add> <add> pConfig.Protocol = swarm.PortConfigProtocol(value) <add> case portOptMode: <add> if value != string(swarm.PortConfigPublishModeIngress) && value != string(swarm.PortConfigPublishModeHost) { <add> return fmt.Errorf("invalid publish mode value %s", value) <add> } <add> <add> pConfig.PublishMode = swarm.PortConfigPublishMode(value) <add> case portOptTargetPort: <add> tPort, err := strconv.ParseUint(value, 10, 16) <add> if err != nil { <add> return err <add> } <add> <add> pConfig.TargetPort = uint32(tPort) <add> case portOptPublishedPort: <add> pPort, err := strconv.ParseUint(value, 10, 16) <add> if err != nil { <add> return err <add> } <add> <add> pConfig.PublishedPort = uint32(pPort) <add> default: <add> return fmt.Errorf("invalid field key %s", key) <add> } <add> } <add> <add> if pConfig.TargetPort == 0 { <add> return fmt.Errorf("missing mandatory field %q", portOptTargetPort) <add> } <add> <add> p.ports = append(p.ports, pConfig) <add> return nil <add>} <add> <add>// Type returns the type of this option <add>func (p *PortOpt) Type() string { <add> return "port" <add>} <add> <add>// String returns a string repr of this option <add>func (p *PortOpt) String() string { <add> ports := []string{} <add> for _, port := range p.ports { <add> repr := fmt.Sprintf("%v:%v/%s/%s", port.PublishedPort, port.TargetPort, port.Protocol, port.PublishMode) <add> ports = append(ports, repr) <add> } <add> return strings.Join(ports, ", ") <add>} <add> <add>// Value returns the ports <add>func (p *PortOpt) Value() []swarm.PortConfig { <add> return p.ports <add>}
15
Javascript
Javascript
prevent next tick when force.stop is called
4f37a4869b54063b3376a10be7e696b25dbfa6c2
<ide><path>d3.layout.js <ide> d3.layout.force = function() { <ide> } <ide> <ide> function tick() { <add> // simulated annealing, basically <add> if ((alpha *= .99) < .005) return true; <add> <ide> var n = nodes.length, <ide> m = links.length, <ide> q, <ide> d3.layout.force = function() { <ide> } <ide> <ide> event.tick({type: "tick", alpha: alpha}); <del> <del> // simulated annealing, basically <del> return (alpha *= .99) < .005; <ide> } <ide> <ide> force.nodes = function(x) { <ide><path>d3.layout.min.js <del>(function(){function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;return b.push(a),b}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function g(a){a.fixed|=2}function h(a){a!==f&&(a.fixed&=1)}function i(){j(),f.fixed&=1,e=f=null}function j(){f.px=d3.event.x,f.py=d3.event.y,e.resume()}function k(a,b,c){var d=0,e=0;a.charge=0;if(!a.leaf){var f=a.nodes,g=f.length,h=-1,i;while(++h<g){i=f[h];if(i==null)continue;k(i,b,c),a.charge+=i.charge,d+=i.charge*i.cx,e+=i.charge*i.cy}}if(a.point){a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5);var j=b*c[a.point.index];a.charge+=a.pointCharge=j,d+=j*a.point.x,e+=j*a.point.y}a.cx=d/a.charge,a.cy=e/a.charge}function l(a){return 20}function m(a){return 1}function o(a){return a.x}function p(a){return a.y}function q(a,b,c){a.y0=b,a.y=c}function t(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function u(a){return a.reduce(v,0)}function v(a,b){return a+b[1]}function w(a,b){return x(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function x(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function y(a){return[d3.min(a),d3.max(a)]}function z(a,b){return d3.rebind(a,b,"sort","children","value"),a.links=D,a.nodes=function(b){return E=!0,(a.nodes=a)(b)},a}function A(a){return a.children}function B(a){return a.value}function C(a,b){return b.value-a.value}function D(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function F(a,b){return a.value-b.value}function G(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function H(a,b){a._pack_next=b,b._pack_prev=a}function I(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function J(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(K),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],O(g,h,i),l(i),G(g,i),g._pack_prev=i,G(i,h),h=g._pack_next;for(var m=3;m<f;m++){O(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(I(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(I(k,i))break;n?(o<p||o==p&&h.r<g.r?H(g,h=j):H(g=k,h),m--):(G(g,i),h=i,l(i))}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}return a.forEach(L),s}function K(a){a._pack_next=a._pack_prev=a}function L(a){delete a._pack_next,delete a._pack_prev}function M(a){var b=a.children;b&&b.length?(b.forEach(M),a.r=J(b)):a.r=Math.sqrt(a.value)}function N(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)N(e[f],b,c,d)}}function O(a,b,c){var d=a.r+c.r,e=b.x-a.x,f=b.y-a.y;if(d&&(e||f)){var g=b.r+c.r,h=Math.sqrt(e*e+f*f),i=Math.max(-1,Math.min(1,(d*d+h*h-g*g)/(2*d*h))),j=Math.acos(i),k=i*(d/=h),l=Math.sin(j)*d;c.x=a.x+k*e+l*f,c.y=a.y+k*f-l*e}else c.x=a.x+d,c.y=a.y}function P(a){return 1+d3.max(a,function(a){return a.y})}function Q(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function R(a){var b=a.children;return b&&b.length?R(b[0]):a}function S(a){var b=a.children,c;return b&&(c=b.length)?S(b[c-1]):a}function T(a,b){return a.parent==b.parent?1:2}function U(a){var b=a.children;return b&&b.length?b[0]:a._tree.thread}function V(a){var b=a.children,c;return b&&(c=b.length)?b[c-1]:a._tree.thread}function W(a,b){var c=a.children;if(c&&(e=c.length)){var d,e,f=-1;while(++f<e)b(d=W(c[f],b),a)>0&&(a=d)}return a}function X(a,b){return a.x-b.x}function Y(a,b){return b.x-a.x}function Z(a,b){return a.depth-b.depth}function $(a,b){function c(a,d){var e=a.children;if(e&&(i=e.length)){var f,g=null,h=-1,i;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function _(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function ba(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function bb(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function bc(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function bd(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];return e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0),{x:c,y:d,dx:e,dy:f}}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[s][r],u=d[s][t],v=o,w=o+=u*n;a[s+"-"+t]={index:s,subindex:t,startAngle:v,endAngle:w,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var x=a[q+"-"+r],y=a[r+"-"+q];(x.value||y.value)&&b.push(x.value<y.value?{source:y,target:x}:{source:x,target:y})}}i&&k()}function k(){b.sort(function(a,b){return i((a.source.value+a.target.value)/2,(b.source.value+b.target.value)/2)})}var a={},b,c,d,e,f=0,g,h,i;return a.matrix=function(f){return arguments.length?(e=(d=f)&&d.length,b=c=null,a):d},a.padding=function(d){return arguments.length?(f=d,b=c=null,a):f},a.sortGroups=function(d){return arguments.length?(g=d,b=c=null,a):g},a.sortSubgroups=function(c){return arguments.length?(h=c,b=null,a):h},a.sortChords=function(c){return arguments.length?(i=c,b&&k(),a):i},a.chords=function(){return b||j(),b},a.groups=function(){return c||j(),c},a},d3.layout.force=function(){function A(a){return function(b,c,d,e,f){if(b.point!==a){var g=b.cx-a.x,h=b.cy-a.y,i=1/Math.sqrt(g*g+h*h);if((e-c)*i<t){var j=b.charge*i*i;return a.px-=g*j,a.py-=h*j,!0}if(b.point&&isFinite(i)){var j=b.pointCharge*i*i;a.px-=g*j,a.py-=h*j}}return!b.charge}}function B(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(r){k(e=d3.geom.quadtree(v),n,z),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(A(g))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);return b.tick({type:"tick",alpha:n}),(n*=.99)<.005}function C(b){g(f=b),e=a}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y,z;return a.nodes=function(b){return arguments.length?(v=b,a):v},a.links=function(b){return arguments.length?(w=b,a):w},a.size=function(b){return arguments.length?(c=b,a):c},a.linkDistance=function(b){return arguments.length?(p=d3.functor(b),a):p},a.distance=a.linkDistance,a.linkStrength=function(b){return arguments.length?(q=d3.functor(b),a):q},a.friction=function(b){return arguments.length?(o=b,a):o},a.charge=function(b){return arguments.length?(r=typeof b=="function"?b:+b,a):r},a.gravity=function(b){return arguments.length?(s=b,a):s},a.theta=function(b){return arguments.length?(t=b,a):t},a.start=function(){function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);z=[];if(typeof r=="function")for(b=0;b<e;++b)z[b]=+r.call(this,v[b],b);else for(b=0;b<e;++b)z[b]=r;return a.resume()},a.resume=function(){return n=.1,d3.timer(B),a},a.stop=function(){return n=0,a},a.drag=function(){d||(d=d3.behavior.drag().origin(Object).on("dragstart",C).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)},d3.rebind(a,b,"on")};var e,f;d3.layout.partition=function(){function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f&&(h=f.length)){var g=-1,h,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}function d(a){var b=a.children,c=0;if(b&&(f=b.length)){var e=-1,f;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function e(e,f){var g=a.call(this,e,f);return c(g[0],0,b[0],b[1]/d(g[0])),g}var a=d3.layout.hierarchy(),b=[1,1];return e.size=function(a){return arguments.length?(b=a,e):b},z(e,a)},d3.layout.pie=function(){function f(g,h){var i=g.map(function(b,c){return+a.call(f,b,c)}),j=+(typeof c=="function"?c.apply(this,arguments):c),k=((typeof e=="function"?e.apply(this,arguments):e)-c)/d3.sum(i),l=d3.range(g.length);b!=null&&l.sort(b===n?function(a,b){return i[b]-i[a]}:function(a,c){return b(g[a],g[c])});var m=[];return l.forEach(function(a){m[a]={data:g[a],value:d=i[a],startAngle:j,endAngle:j+=d*k}}),m}var a=Number,b=n,c=0,e=2*Math.PI;return f.value=function(b){return arguments.length?(a=b,f):a},f.sort=function(a){return arguments.length?(b=a,f):b},f.startAngle=function(a){return arguments.length?(c=a,f):c},f.endAngle=function(a){return arguments.length?(e=a,f):e},f};var n={};d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=r["default"],c=s.zero,d=q,e=o,f=p;return g.values=function(b){return arguments.length?(a=b,g):a},g.order=function(a){return arguments.length?(b=typeof a=="function"?a:r[a],g):b},g.offset=function(a){return arguments.length?(c=typeof a=="function"?a:s[a],g):c},g.x=function(a){return arguments.length?(e=a,g):e},g.y=function(a){return arguments.length?(f=a,g):f},g.out=function(a){return arguments.length?(d=a,g):d},g};var r={"inside-out":function(a){var b=a.length,c,d,e=a.map(t),f=a.map(u),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},s={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=y,d=w;return e.value=function(a){return arguments.length?(b=a,e):b},e.range=function(a){return arguments.length?(c=d3.functor(a),e):c},e.bins=function(a){return arguments.length?(d=typeof a=="number"?function(b){return x(b,a)}:d3.functor(a),e):d},e.frequency=function(b){return arguments.length?(a=!!b,e):a},e},d3.layout.hierarchy=function(){function e(f,h,i){var j=b.call(g,f,h),k=E?f:{data:f};k.depth=h,i.push(k);if(j&&(m=j.length)){var l=-1,m,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}function f(a,b){var d=a.children,e=0;if(d&&(i=d.length)){var h=-1,i,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,E?a:a.data,b)||0);return c&&(a.value=e),e}function g(a){var b=[];return e(a,0,b),b}var a=C,b=A,c=B;return g.sort=function(b){return arguments.length?(a=b,g):a},g.children=function(a){return arguments.length?(b=a,g):b},g.value=function(a){return arguments.length?(c=a,g):c},g.revalue=function(a){return f(a,0),a},g};var E=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,M(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);return N(f,g/2,h/2,i),e}var a=d3.layout.hierarchy().sort(F),b=[1,1];return c.size=function(a){return arguments.length?(b=a,c):b},z(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;$(g,function(a){var c=a.children;c&&c.length?(a.x=Q(c),a.y=P(c)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=R(g),m=S(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;return $(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-(g.y?a.y/g.y:1))*c[1]}),f}var a=d3.layout.hierarchy().sort(null).value(null),b=T,c=[1,1];return d.separation=function(a){return arguments.length?(b=a,d):b},d.size=function(a){return arguments.length?(c=a,d):c},z(d,a)},d3.layout.tree=function(){function d(d,e){function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;_(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c&&(e=c.length)){var d=-1,e;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=V(g),e=U(e),g&&e)h=U(h),f=V(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(ba(bb(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!V(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!U(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}var f=a.call(this,d,e),g=f[0];$(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=W(g,Y),l=W(g,X),m=W(g,Z),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;return $(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree}),f}var a=d3.layout.hierarchy().sort(null).value(null),b=T,c=[1,1];return d.separation=function(a){return arguments.length?(b=a,d):b},d.size=function(a){return arguments.length?(c=a,d):c},z(d,a)},d3.layout.treemap=function(){function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}function j(a){var b=a.children;if(b&&b.length){var c=e(a),d=[],f=b.slice(),g,h=Infinity,k,n=Math.min(c.dx,c.dy),o;i(f,c.dx*c.dy/a.value),d.area=0;while((o=f.length)>0)d.push(g=f[o-1]),d.area+=g.area,(k=l(d,n))<=h?(f.pop(),h=k):(d.area-=d.pop().area,m(d,n,c,!1),n=Math.min(c.dx,c.dy),d.length=d.area=0,h=Infinity);d.length&&(m(d,n,c,!0),d.length=d.area=0),b.forEach(j)}}function k(a){var b=a.children;if(b&&b.length){var c=e(a),d=b.slice(),f,g=[];i(d,c.dx*c.dy/a.value),g.area=0;while(f=d.pop())g.push(f),g.area+=f.area,f.z!=null&&(m(g,f.z?c.dx:c.dy,c,!d.length),g.length=g.area=0);b.forEach(k)}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}return c*=c,b*=b,c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=Math.min(d.x+d.dx-h,j?b(k.area/j):0);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=Math.min(d.y+d.dy-i,j?b(k.area/j):0);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function n(b){var d=g||a(b),e=d[0];return e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d),d}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bc,f=!1,g,h=.5*(1+Math.sqrt(5));return n.size=function(a){return arguments.length?(c=a,n):c},n.padding=function(a){function b(b){var c=a.call(n,b,b.depth);return c==null?bc(b):bd(b,typeof c=="number"?[c,c,c,c]:c)}function c(b){return bd(b,a)}if(!arguments.length)return d;var f;return e=(d=a)==null?bc:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c,n},n.round=function(a){return arguments.length?(b=a?Math.round:Number,n):b!=Number},n.sticky=function(a){return arguments.length?(f=a,g=null,n):f},n.ratio=function(a){return arguments.length?(h=a,n):h},z(n,a)}})(); <ide>\ No newline at end of file <add>(function(){function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;return b.push(a),b}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function g(a){a.fixed|=2}function h(a){a!==f&&(a.fixed&=1)}function i(){j(),f.fixed&=1,e=f=null}function j(){f.px=d3.event.x,f.py=d3.event.y,e.resume()}function k(a,b,c){var d=0,e=0;a.charge=0;if(!a.leaf){var f=a.nodes,g=f.length,h=-1,i;while(++h<g){i=f[h];if(i==null)continue;k(i,b,c),a.charge+=i.charge,d+=i.charge*i.cx,e+=i.charge*i.cy}}if(a.point){a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5);var j=b*c[a.point.index];a.charge+=a.pointCharge=j,d+=j*a.point.x,e+=j*a.point.y}a.cx=d/a.charge,a.cy=e/a.charge}function l(a){return 20}function m(a){return 1}function o(a){return a.x}function p(a){return a.y}function q(a,b,c){a.y0=b,a.y=c}function t(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function u(a){return a.reduce(v,0)}function v(a,b){return a+b[1]}function w(a,b){return x(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function x(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function y(a){return[d3.min(a),d3.max(a)]}function z(a,b){return d3.rebind(a,b,"sort","children","value"),a.links=D,a.nodes=function(b){return E=!0,(a.nodes=a)(b)},a}function A(a){return a.children}function B(a){return a.value}function C(a,b){return b.value-a.value}function D(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function F(a,b){return a.value-b.value}function G(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function H(a,b){a._pack_next=b,b._pack_prev=a}function I(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function J(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(K),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],O(g,h,i),l(i),G(g,i),g._pack_prev=i,G(i,h),h=g._pack_next;for(var m=3;m<f;m++){O(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(I(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(I(k,i))break;n?(o<p||o==p&&h.r<g.r?H(g,h=j):H(g=k,h),m--):(G(g,i),h=i,l(i))}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}return a.forEach(L),s}function K(a){a._pack_next=a._pack_prev=a}function L(a){delete a._pack_next,delete a._pack_prev}function M(a){var b=a.children;b&&b.length?(b.forEach(M),a.r=J(b)):a.r=Math.sqrt(a.value)}function N(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)N(e[f],b,c,d)}}function O(a,b,c){var d=a.r+c.r,e=b.x-a.x,f=b.y-a.y;if(d&&(e||f)){var g=b.r+c.r,h=Math.sqrt(e*e+f*f),i=Math.max(-1,Math.min(1,(d*d+h*h-g*g)/(2*d*h))),j=Math.acos(i),k=i*(d/=h),l=Math.sin(j)*d;c.x=a.x+k*e+l*f,c.y=a.y+k*f-l*e}else c.x=a.x+d,c.y=a.y}function P(a){return 1+d3.max(a,function(a){return a.y})}function Q(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function R(a){var b=a.children;return b&&b.length?R(b[0]):a}function S(a){var b=a.children,c;return b&&(c=b.length)?S(b[c-1]):a}function T(a,b){return a.parent==b.parent?1:2}function U(a){var b=a.children;return b&&b.length?b[0]:a._tree.thread}function V(a){var b=a.children,c;return b&&(c=b.length)?b[c-1]:a._tree.thread}function W(a,b){var c=a.children;if(c&&(e=c.length)){var d,e,f=-1;while(++f<e)b(d=W(c[f],b),a)>0&&(a=d)}return a}function X(a,b){return a.x-b.x}function Y(a,b){return b.x-a.x}function Z(a,b){return a.depth-b.depth}function $(a,b){function c(a,d){var e=a.children;if(e&&(i=e.length)){var f,g=null,h=-1,i;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function _(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function ba(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function bb(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function bc(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function bd(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];return e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0),{x:c,y:d,dx:e,dy:f}}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[s][r],u=d[s][t],v=o,w=o+=u*n;a[s+"-"+t]={index:s,subindex:t,startAngle:v,endAngle:w,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var x=a[q+"-"+r],y=a[r+"-"+q];(x.value||y.value)&&b.push(x.value<y.value?{source:y,target:x}:{source:x,target:y})}}i&&k()}function k(){b.sort(function(a,b){return i((a.source.value+a.target.value)/2,(b.source.value+b.target.value)/2)})}var a={},b,c,d,e,f=0,g,h,i;return a.matrix=function(f){return arguments.length?(e=(d=f)&&d.length,b=c=null,a):d},a.padding=function(d){return arguments.length?(f=d,b=c=null,a):f},a.sortGroups=function(d){return arguments.length?(g=d,b=c=null,a):g},a.sortSubgroups=function(c){return arguments.length?(h=c,b=null,a):h},a.sortChords=function(c){return arguments.length?(i=c,b&&k(),a):i},a.chords=function(){return b||j(),b},a.groups=function(){return c||j(),c},a},d3.layout.force=function(){function A(a){return function(b,c,d,e,f){if(b.point!==a){var g=b.cx-a.x,h=b.cy-a.y,i=1/Math.sqrt(g*g+h*h);if((e-c)*i<t){var j=b.charge*i*i;return a.px-=g*j,a.py-=h*j,!0}if(b.point&&isFinite(i)){var j=b.pointCharge*i*i;a.px-=g*j,a.py-=h*j}}return!b.charge}}function B(){if((n*=.99)<.005)return!0;var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(r){k(e=d3.geom.quadtree(v),n,z),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(A(g))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);b.tick({type:"tick",alpha:n})}function C(b){g(f=b),e=a}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y,z;return a.nodes=function(b){return arguments.length?(v=b,a):v},a.links=function(b){return arguments.length?(w=b,a):w},a.size=function(b){return arguments.length?(c=b,a):c},a.linkDistance=function(b){return arguments.length?(p=d3.functor(b),a):p},a.distance=a.linkDistance,a.linkStrength=function(b){return arguments.length?(q=d3.functor(b),a):q},a.friction=function(b){return arguments.length?(o=b,a):o},a.charge=function(b){return arguments.length?(r=typeof b=="function"?b:+b,a):r},a.gravity=function(b){return arguments.length?(s=b,a):s},a.theta=function(b){return arguments.length?(t=b,a):t},a.start=function(){function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);z=[];if(typeof r=="function")for(b=0;b<e;++b)z[b]=+r.call(this,v[b],b);else for(b=0;b<e;++b)z[b]=r;return a.resume()},a.resume=function(){return n=.1,d3.timer(B),a},a.stop=function(){return n=0,a},a.drag=function(){d||(d=d3.behavior.drag().origin(Object).on("dragstart",C).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)},d3.rebind(a,b,"on")};var e,f;d3.layout.partition=function(){function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f&&(h=f.length)){var g=-1,h,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}function d(a){var b=a.children,c=0;if(b&&(f=b.length)){var e=-1,f;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function e(e,f){var g=a.call(this,e,f);return c(g[0],0,b[0],b[1]/d(g[0])),g}var a=d3.layout.hierarchy(),b=[1,1];return e.size=function(a){return arguments.length?(b=a,e):b},z(e,a)},d3.layout.pie=function(){function f(g,h){var i=g.map(function(b,c){return+a.call(f,b,c)}),j=+(typeof c=="function"?c.apply(this,arguments):c),k=((typeof e=="function"?e.apply(this,arguments):e)-c)/d3.sum(i),l=d3.range(g.length);b!=null&&l.sort(b===n?function(a,b){return i[b]-i[a]}:function(a,c){return b(g[a],g[c])});var m=[];return l.forEach(function(a){m[a]={data:g[a],value:d=i[a],startAngle:j,endAngle:j+=d*k}}),m}var a=Number,b=n,c=0,e=2*Math.PI;return f.value=function(b){return arguments.length?(a=b,f):a},f.sort=function(a){return arguments.length?(b=a,f):b},f.startAngle=function(a){return arguments.length?(c=a,f):c},f.endAngle=function(a){return arguments.length?(e=a,f):e},f};var n={};d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=r["default"],c=s.zero,d=q,e=o,f=p;return g.values=function(b){return arguments.length?(a=b,g):a},g.order=function(a){return arguments.length?(b=typeof a=="function"?a:r[a],g):b},g.offset=function(a){return arguments.length?(c=typeof a=="function"?a:s[a],g):c},g.x=function(a){return arguments.length?(e=a,g):e},g.y=function(a){return arguments.length?(f=a,g):f},g.out=function(a){return arguments.length?(d=a,g):d},g};var r={"inside-out":function(a){var b=a.length,c,d,e=a.map(t),f=a.map(u),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},s={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=y,d=w;return e.value=function(a){return arguments.length?(b=a,e):b},e.range=function(a){return arguments.length?(c=d3.functor(a),e):c},e.bins=function(a){return arguments.length?(d=typeof a=="number"?function(b){return x(b,a)}:d3.functor(a),e):d},e.frequency=function(b){return arguments.length?(a=!!b,e):a},e},d3.layout.hierarchy=function(){function e(f,h,i){var j=b.call(g,f,h),k=E?f:{data:f};k.depth=h,i.push(k);if(j&&(m=j.length)){var l=-1,m,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}function f(a,b){var d=a.children,e=0;if(d&&(i=d.length)){var h=-1,i,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,E?a:a.data,b)||0);return c&&(a.value=e),e}function g(a){var b=[];return e(a,0,b),b}var a=C,b=A,c=B;return g.sort=function(b){return arguments.length?(a=b,g):a},g.children=function(a){return arguments.length?(b=a,g):b},g.value=function(a){return arguments.length?(c=a,g):c},g.revalue=function(a){return f(a,0),a},g};var E=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,M(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);return N(f,g/2,h/2,i),e}var a=d3.layout.hierarchy().sort(F),b=[1,1];return c.size=function(a){return arguments.length?(b=a,c):b},z(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;$(g,function(a){var c=a.children;c&&c.length?(a.x=Q(c),a.y=P(c)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=R(g),m=S(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;return $(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-(g.y?a.y/g.y:1))*c[1]}),f}var a=d3.layout.hierarchy().sort(null).value(null),b=T,c=[1,1];return d.separation=function(a){return arguments.length?(b=a,d):b},d.size=function(a){return arguments.length?(c=a,d):c},z(d,a)},d3.layout.tree=function(){function d(d,e){function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;_(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c&&(e=c.length)){var d=-1,e;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=V(g),e=U(e),g&&e)h=U(h),f=V(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(ba(bb(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!V(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!U(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}var f=a.call(this,d,e),g=f[0];$(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=W(g,Y),l=W(g,X),m=W(g,Z),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;return $(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree}),f}var a=d3.layout.hierarchy().sort(null).value(null),b=T,c=[1,1];return d.separation=function(a){return arguments.length?(b=a,d):b},d.size=function(a){return arguments.length?(c=a,d):c},z(d,a)},d3.layout.treemap=function(){function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}function j(a){var b=a.children;if(b&&b.length){var c=e(a),d=[],f=b.slice(),g,h=Infinity,k,n=Math.min(c.dx,c.dy),o;i(f,c.dx*c.dy/a.value),d.area=0;while((o=f.length)>0)d.push(g=f[o-1]),d.area+=g.area,(k=l(d,n))<=h?(f.pop(),h=k):(d.area-=d.pop().area,m(d,n,c,!1),n=Math.min(c.dx,c.dy),d.length=d.area=0,h=Infinity);d.length&&(m(d,n,c,!0),d.length=d.area=0),b.forEach(j)}}function k(a){var b=a.children;if(b&&b.length){var c=e(a),d=b.slice(),f,g=[];i(d,c.dx*c.dy/a.value),g.area=0;while(f=d.pop())g.push(f),g.area+=f.area,f.z!=null&&(m(g,f.z?c.dx:c.dy,c,!d.length),g.length=g.area=0);b.forEach(k)}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}return c*=c,b*=b,c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=Math.min(d.x+d.dx-h,j?b(k.area/j):0);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=Math.min(d.y+d.dy-i,j?b(k.area/j):0);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function n(b){var d=g||a(b),e=d[0];return e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d),d}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bc,f=!1,g,h=.5*(1+Math.sqrt(5));return n.size=function(a){return arguments.length?(c=a,n):c},n.padding=function(a){function b(b){var c=a.call(n,b,b.depth);return c==null?bc(b):bd(b,typeof c=="number"?[c,c,c,c]:c)}function c(b){return bd(b,a)}if(!arguments.length)return d;var f;return e=(d=a)==null?bc:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c,n},n.round=function(a){return arguments.length?(b=a?Math.round:Number,n):b!=Number},n.sticky=function(a){return arguments.length?(f=a,g=null,n):f},n.ratio=function(a){return arguments.length?(h=a,n):h},z(n,a)}})(); <ide>\ No newline at end of file <ide><path>src/layout/force.js <ide> d3.layout.force = function() { <ide> } <ide> <ide> function tick() { <add> // simulated annealing, basically <add> if ((alpha *= .99) < .005) return true; <add> <ide> var n = nodes.length, <ide> m = links.length, <ide> q, <ide> d3.layout.force = function() { <ide> } <ide> <ide> event.tick({type: "tick", alpha: alpha}); <del> <del> // simulated annealing, basically <del> return (alpha *= .99) < .005; <ide> } <ide> <ide> force.nodes = function(x) {
3
Go
Go
resolve race conditions in attach api call
84d6240cfe7cc66a7d3f6ac78ea6faad0e3108b9
<ide><path>container/container.go <ide> func (container *Container) GetExecIDs() []string { <ide> return container.ExecCommands.List() <ide> } <ide> <del>// Attach connects to the container's stdio to the client streams <del>func (container *Container) Attach(cfg *stream.AttachConfig) chan error { <del> ctx := container.InitAttachContext() <del> <del> cfg.TTY = container.Config.Tty <del> if !container.Config.OpenStdin { <del> cfg.Stdin = nil <del> } <del> cfg.CloseStdin = cfg.Stdin != nil && container.Config.StdinOnce <del> <del> return container.StreamConfig.Attach(ctx, cfg) <del>} <del> <ide> // ShouldRestart decides whether the daemon should restart the container or not. <ide> // This is based on the container's restart policy. <ide> func (container *Container) ShouldRestart() bool { <ide><path>container/stream/attach.go <ide> type AttachConfig struct { <ide> // For example, this would close the attached container's stdin. <ide> CloseStdin bool <ide> <add> // UseStd* indicate whether the client has requested to be connected to the <add> // given stream or not. These flags are used instead of checking Std* != nil <add> // at points before the client streams Std* are wired up. <add> UseStdin, UseStdout, UseStderr bool <add> <add> // CStd* are the streams directly connected to the container <add> CStdin io.WriteCloser <add> CStdout, CStderr io.ReadCloser <add> <ide> // Provide client streams to wire up to <ide> Stdin io.ReadCloser <ide> Stdout, Stderr io.Writer <ide> } <ide> <del>// Attach attaches the stream config to the streams specified in <del>// the AttachOptions <del>func (c *Config) Attach(ctx context.Context, cfg *AttachConfig) chan error { <add>// AttachStreams attaches the container's streams to the AttachConfig <add>func (c *Config) AttachStreams(cfg *AttachConfig) { <add> if cfg.UseStdin { <add> cfg.CStdin = c.StdinPipe() <add> } <add> <add> if cfg.UseStdout { <add> cfg.CStdout = c.StdoutPipe() <add> } <add> <add> if cfg.UseStderr { <add> cfg.CStderr = c.StderrPipe() <add> } <add>} <add> <add>// CopyStreams starts goroutines to copy data in and out to/from the container <add>func (c *Config) CopyStreams(ctx context.Context, cfg *AttachConfig) chan error { <ide> var ( <del> cStdout, cStderr io.ReadCloser <del> cStdin io.WriteCloser <del> wg sync.WaitGroup <del> errors = make(chan error, 3) <add> wg sync.WaitGroup <add> errors = make(chan error, 3) <ide> ) <ide> <ide> if cfg.Stdin != nil { <del> cStdin = c.StdinPipe() <ide> wg.Add(1) <ide> } <ide> <ide> if cfg.Stdout != nil { <del> cStdout = c.StdoutPipe() <ide> wg.Add(1) <ide> } <ide> <ide> if cfg.Stderr != nil { <del> cStderr = c.StderrPipe() <ide> wg.Add(1) <ide> } <ide> <ide> func (c *Config) Attach(ctx context.Context, cfg *AttachConfig) chan error { <ide> <ide> var err error <ide> if cfg.TTY { <del> _, err = copyEscapable(cStdin, cfg.Stdin, cfg.DetachKeys) <add> _, err = copyEscapable(cfg.CStdin, cfg.Stdin, cfg.DetachKeys) <ide> } else { <del> _, err = io.Copy(cStdin, cfg.Stdin) <add> _, err = io.Copy(cfg.CStdin, cfg.Stdin) <ide> } <ide> if err == io.ErrClosedPipe { <ide> err = nil <ide> func (c *Config) Attach(ctx context.Context, cfg *AttachConfig) chan error { <ide> errors <- err <ide> } <ide> if cfg.CloseStdin && !cfg.TTY { <del> cStdin.Close() <add> cfg.CStdin.Close() <ide> } else { <ide> // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr <del> if cStdout != nil { <del> cStdout.Close() <add> if cfg.CStdout != nil { <add> cfg.CStdout.Close() <ide> } <del> if cStderr != nil { <del> cStderr.Close() <add> if cfg.CStderr != nil { <add> cfg.CStderr.Close() <ide> } <ide> } <ide> logrus.Debug("attach: stdin: end") <ide> func (c *Config) Attach(ctx context.Context, cfg *AttachConfig) chan error { <ide> wg.Done() <ide> } <ide> <del> go attachStream("stdout", cfg.Stdout, cStdout) <del> go attachStream("stderr", cfg.Stderr, cStderr) <add> go attachStream("stdout", cfg.Stdout, cfg.CStdout) <add> go attachStream("stderr", cfg.Stderr, cfg.CStderr) <ide> <ide> return promise.Go(func() error { <ide> done := make(chan struct{}) <ide> func (c *Config) Attach(ctx context.Context, cfg *AttachConfig) chan error { <ide> case <-done: <ide> case <-ctx.Done(): <ide> // close all pipes <del> if cStdin != nil { <del> cStdin.Close() <add> if cfg.CStdin != nil { <add> cfg.CStdin.Close() <ide> } <del> if cStdout != nil { <del> cStdout.Close() <add> if cfg.CStdout != nil { <add> cfg.CStdout.Close() <ide> } <del> if cStderr != nil { <del> cStderr.Close() <add> if cfg.CStderr != nil { <add> cfg.CStderr.Close() <ide> } <ide> <-done <ide> } <ide><path>daemon/attach.go <ide> import ( <ide> "github.com/docker/docker/pkg/term" <ide> ) <ide> <del>type containerAttachConfig struct { <del> detachKeys []byte <del> stdin io.ReadCloser <del> stdout, stderr io.Writer <del> showHistory bool <del> stream bool <del>} <del> <ide> // ContainerAttach attaches to logs according to the config passed in. See ContainerAttachConfig. <ide> func (daemon *Daemon) ContainerAttach(prefixOrName string, c *backend.ContainerAttachConfig) error { <ide> keys := []byte{} <ide> func (daemon *Daemon) ContainerAttach(prefixOrName string, c *backend.ContainerA <ide> return errors.NewRequestConflictError(err) <ide> } <ide> <add> cfg := stream.AttachConfig{ <add> UseStdin: c.UseStdin && container.Config.OpenStdin, <add> UseStdout: c.UseStdout, <add> UseStderr: c.UseStderr, <add> TTY: container.Config.Tty, <add> CloseStdin: container.Config.StdinOnce, <add> DetachKeys: keys, <add> } <add> container.StreamConfig.AttachStreams(&cfg) <add> <ide> inStream, outStream, errStream, err := c.GetStreams() <ide> if err != nil { <ide> return err <ide> func (daemon *Daemon) ContainerAttach(prefixOrName string, c *backend.ContainerA <ide> outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout) <ide> } <ide> <del> var cfg containerAttachConfig <del> <del> if c.UseStdin { <del> cfg.stdin = inStream <add> if cfg.UseStdin { <add> cfg.Stdin = inStream <ide> } <del> if c.UseStdout { <del> cfg.stdout = outStream <add> if cfg.UseStdout { <add> cfg.Stdout = outStream <ide> } <del> if c.UseStderr { <del> cfg.stderr = errStream <add> if cfg.UseStderr { <add> cfg.Stderr = errStream <ide> } <ide> <del> cfg.showHistory = c.Logs <del> cfg.stream = c.Stream <del> cfg.detachKeys = keys <del> <del> if err := daemon.containerAttach(container, &cfg); err != nil { <add> if err := daemon.containerAttach(container, &cfg, c.Logs, c.Stream); err != nil { <ide> fmt.Fprintf(outStream, "Error attaching: %s\n", err) <ide> } <ide> return nil <ide> } <ide> <ide> // ContainerAttachRaw attaches the provided streams to the container's stdio <del>func (daemon *Daemon) ContainerAttachRaw(prefixOrName string, stdin io.ReadCloser, stdout, stderr io.Writer, stream bool) error { <add>func (daemon *Daemon) ContainerAttachRaw(prefixOrName string, stdin io.ReadCloser, stdout, stderr io.Writer, doStream bool) error { <ide> container, err := daemon.GetContainer(prefixOrName) <ide> if err != nil { <ide> return err <ide> } <del> cfg := &containerAttachConfig{ <del> stdin: stdin, <del> stdout: stdout, <del> stderr: stderr, <del> stream: stream, <add> cfg := stream.AttachConfig{ <add> UseStdin: stdin != nil && container.Config.OpenStdin, <add> UseStdout: stdout != nil, <add> UseStderr: stderr != nil, <add> TTY: container.Config.Tty, <add> CloseStdin: container.Config.StdinOnce, <add> } <add> container.StreamConfig.AttachStreams(&cfg) <add> if cfg.UseStdin { <add> cfg.Stdin = stdin <ide> } <del> return daemon.containerAttach(container, cfg) <add> if cfg.UseStdout { <add> cfg.Stdout = stdout <add> } <add> if cfg.UseStderr { <add> cfg.Stderr = stderr <add> } <add> <add> return daemon.containerAttach(container, &cfg, false, doStream) <ide> } <ide> <del>func (daemon *Daemon) containerAttach(c *container.Container, cfg *containerAttachConfig) error { <del> stdin := cfg.stdin <del> stdout := cfg.stdout <del> stderr := cfg.stderr <del> if cfg.showHistory { <add>func (daemon *Daemon) containerAttach(c *container.Container, cfg *stream.AttachConfig, logs, doStream bool) error { <add> if logs { <ide> logDriver, err := daemon.getLogger(c) <ide> if err != nil { <ide> return err <ide> func (daemon *Daemon) containerAttach(c *container.Container, cfg *containerAtta <ide> if !ok { <ide> break LogLoop <ide> } <del> if msg.Source == "stdout" && stdout != nil { <del> stdout.Write(msg.Line) <add> if msg.Source == "stdout" && cfg.Stdout != nil { <add> cfg.Stdout.Write(msg.Line) <ide> } <del> if msg.Source == "stderr" && stderr != nil { <del> stderr.Write(msg.Line) <add> if msg.Source == "stderr" && cfg.Stderr != nil { <add> cfg.Stderr.Write(msg.Line) <ide> } <ide> case err := <-logs.Err: <ide> logrus.Errorf("Error streaming logs: %v", err) <ide> func (daemon *Daemon) containerAttach(c *container.Container, cfg *containerAtta <ide> <ide> daemon.LogContainerEvent(c, "attach") <ide> <del> if !cfg.stream { <add> if !doStream { <ide> return nil <ide> } <ide> <del> var stdinPipe io.ReadCloser <del> if stdin != nil { <add> if cfg.Stdin != nil { <ide> r, w := io.Pipe() <del> go func() { <add> go func(stdin io.ReadCloser) { <ide> defer w.Close() <ide> defer logrus.Debug("Closing buffered stdin pipe") <ide> io.Copy(w, stdin) <del> }() <del> stdinPipe = r <add> }(cfg.Stdin) <add> cfg.Stdin = r <ide> } <ide> <ide> waitChan := make(chan struct{}) <ide> func (daemon *Daemon) containerAttach(c *container.Container, cfg *containerAtta <ide> }() <ide> } <ide> <del> aCfg := &stream.AttachConfig{ <del> Stdin: stdinPipe, <del> Stdout: stdout, <del> Stderr: stderr, <del> DetachKeys: cfg.detachKeys, <del> } <del> <del> err := <-c.Attach(aCfg) <add> ctx := c.InitAttachContext() <add> err := <-c.StreamConfig.CopyStreams(ctx, cfg) <ide> if err != nil { <ide> if _, ok := err.(stream.DetachError); ok { <ide> daemon.LogContainerEvent(c, "detach") <ide><path>daemon/exec.go <ide> func (d *Daemon) ContainerExecStart(ctx context.Context, name string, stdin io.R <ide> return err <ide> } <ide> <del> attachConfig := &stream.AttachConfig{ <add> attachConfig := stream.AttachConfig{ <ide> TTY: ec.Tty, <add> UseStdin: cStdin != nil, <add> UseStdout: cStdout != nil, <add> UseStderr: cStderr != nil, <ide> Stdin: cStdin, <ide> Stdout: cStdout, <ide> Stderr: cStderr, <ide> DetachKeys: ec.DetachKeys, <ide> CloseStdin: true, <ide> } <del> attachErr := ec.StreamConfig.Attach(ctx, attachConfig) <add> ec.StreamConfig.AttachStreams(&attachConfig) <add> attachErr := ec.StreamConfig.CopyStreams(ctx, &attachConfig) <ide> <ide> systemPid, err := d.containerd.AddProcess(ctx, c.ID, name, p, ec.InitializeStdio) <ide> if err != nil {
4
Go
Go
simplify reading of resolv.conf
0f0fce5dccee23a7de80db9a47edb23d498b4f6e
<ide><path>libnetwork/netutils/utils_linux.go <ide> package netutils <ide> <ide> import ( <del> "fmt" <ide> "net" <add> "os" <ide> "strings" <ide> <ide> "github.com/docker/docker/libnetwork/ipamutils" <ide> import ( <ide> "github.com/vishvananda/netlink" <ide> ) <ide> <del>var ( <del> networkGetRoutesFct func(netlink.Link, int) ([]netlink.Route, error) <del>) <add>var networkGetRoutesFct func(netlink.Link, int) ([]netlink.Route, error) <ide> <ide> // CheckRouteOverlaps checks whether the passed network overlaps with any existing routes <ide> func CheckRouteOverlaps(toCheck *net.IPNet) error { <ide> func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) { <ide> // can't read /etc/resolv.conf. So instead we skip the append if resolvConf <ide> // is nil. It either doesn't exist, or we can't read it for some reason. <ide> var nameservers []string <del> if rc, err := resolvconf.Get(); err == nil { <del> nameservers = resolvconf.GetNameserversAsCIDR(rc.Content) <add> if rc, err := os.ReadFile(resolvconf.Path()); err == nil { <add> nameservers = resolvconf.GetNameserversAsCIDR(rc) <ide> } <ide> for _, nw := range list { <ide> if err := CheckNameserverOverlaps(nameservers, nw); err == nil { <ide> func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) { <ide> } <ide> } <ide> } <del> return nil, fmt.Errorf("no available network") <add> return nil, errors.New("no available network") <ide> } <ide><path>libnetwork/netutils/utils_windows.go <ide> func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error) { <ide> <ide> // FindAvailableNetwork returns a network from the passed list which does not <ide> // overlap with existing interfaces in the system <del> <add>// <ide> // TODO : Use appropriate windows APIs to identify non-overlapping subnets <ide> func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) { <ide> return nil, nil
2
Python
Python
fix doc string
27f0781e545b892f9393bad35fec149ed0718864
<ide><path>numpy/core/numeric.py <ide> def filled(shape, val, dtype=None, order='C'): <ide> <ide> def filled_like(a, val, dtype=None, order='K', subok=True): <ide> """ <del> Return an array of nans with the same shape and type as a given array. <del> <del> With default parameters, is equivalent to ``a.copy().fill(np.nan)``. <add> Return a filled array with the same shape and type as a given array. <ide> <ide> Parameters <ide> ----------
1
Text
Text
fix addons documentation of development only part
a9115134b5b6d866b68cfd734b4c90abc596e792
<ide><path>docs/docs/10-addons.md <ide> next: animation.html <ide> - [`TransitionGroup` and `CSSTransitionGroup`](animation.html), for dealing with animations and transitions that are usually not simple to implement, such as before a component's removal. <ide> - [`LinkedStateMixin`](two-way-binding-helpers.html), to simplify the coordination between user's form input data and the component's state. <ide> - [`classSet`](class-name-manipulation.html), for manipulating the DOM `class` string a bit more cleanly. <del>- [`TestUtils`](test-utils.html), simple helpers for writing test cases (unminified build only). <ide> - [`cloneWithProps`](clone-with-props.html), to make shallow copies of React components and change their props. <ide> - [`update`](update.html), a helper function that makes dealing with immutable data in JavaScript easier. <add>- [`PureRenderMixin`](pure-render-mixin.html), a performance booster under certain situations. <ide> <ide> The add-ons below are in the development (unminified) version of React only: <ide> <del>- [`PureRenderMixin`](pure-render-mixin.html), a performance booster under certain situations. <add>- [`TestUtils`](test-utils.html), simple helpers for writing test cases (unminified build only). <ide> - [`Perf`](perf.html), for measuring performance and giving you hint where to optimize. <ide> <ide> To get the add-ons, use `react-with-addons.js` (and its minified counterpart) rather than the common `react.js`.
1
PHP
PHP
add the ability add a sub query select
9cb116d9f7d810b71f3e878db8ec9d27af148ada
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> protected function parseSub($query) <ide> * Add a new select column to the query. <ide> * <ide> * @param array|mixed $column <add> * @param \Closure|\Illuminate\Database\Query\Builder|string|null $query <ide> * @return $this <ide> */ <del> public function addSelect($column) <add> public function addSelect($column, $query = null) <ide> { <add> if (is_string($column) && ( <add> $query instanceof self || <add> $query instanceof EloquentBuilder || <add> $query instanceof Closure <add> )) { <add> if (is_null($this->columns)) { <add> $this->select($this->from.'.*'); <add> } <add> <add> return $this->selectSub($query, $column); <add> } <add> <ide> $column = is_array($column) ? $column : func_get_args(); <ide> <ide> $this->columns = array_merge((array) $this->columns, $column); <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testAddingSelects() <ide> $builder = $this->getBuilder(); <ide> $builder->select('foo')->addSelect('bar')->addSelect(['baz', 'boom'])->from('users'); <ide> $this->assertEquals('select "foo", "bar", "baz", "boom" from "users"', $builder->toSql()); <add> <add> $builder = $this->getBuilder(); <add> $builder->select('foo')->addSelect('bar')->addSelect('baz', 'boom')->from('users'); <add> $this->assertEquals('select "foo", "bar", "baz", "boom" from "users"', $builder->toSql()); <add> <add> $builder = $this->getBuilder(); <add> $builder->from('sub')->select(['foo', 'bar'])->addSelect('sub', function ($query) { <add> $query->from('two')->select('baz')->where('subkey', '=', 'subval'); <add> }); <add> $this->assertEquals('select "foo", "bar", (select "baz" from "two" where "subkey" = ?) as "sub" from "sub"', $builder->toSql()); <add> $this->assertEquals(['subval'], $builder->getBindings()); <add> <add> $builder = $this->getBuilder(); <add> $builder->from('sub')->addSelect('sub', function ($query) { <add> $query->from('two')->select('baz')->where('subkey', '=', 'subval'); <add> }); <add> $this->assertEquals('select "sub".*, (select "baz" from "two" where "subkey" = ?) as "sub" from "sub"', $builder->toSql()); <add> $this->assertEquals(['subval'], $builder->getBindings()); <ide> } <ide> <ide> public function testBasicSelectWithPrefix()
2
Javascript
Javascript
use singleline if for uuid validation
f2e3a813b2b533145b80be1febd5db7a41447e28
<ide><path>src/loaders/ObjectLoader.js <ide> Object.assign( ObjectLoader.prototype, { <ide> <ide> for ( var i = 0; i < json.length; i ++ ) { <ide> <del> var clip = AnimationClip.parse( json[ i ] ); <add> var data = json[ i ]; <ide> <del> if ( json[ i ].uuid !== undefined ) { <add> var clip = AnimationClip.parse( data ); <ide> <del> clip.uuid = json[ i ].uuid; <del> <del> } <add> if ( data.uuid !== undefined ) clip.uuid = data.uuid; <ide> <ide> animations.push( clip ); <ide>
1
Python
Python
fix lint issue
9db6f5706fa54f7e3302e8a6e443d6c4e27270d1
<ide><path>libcloud/compute/drivers/ec2.py <ide> def _to_node(self, element, groups=None): <ide> 'status': findattr(element=element, xpath="instanceState/name", <ide> namespace=NAMESPACE), <ide> 'key_name': findattr(element=element, xpath="keyName", <del> namespace=NAMESPACE), <add> namespace=NAMESPACE), <ide> 'launchindex': findattr(element=element, <ide> xpath="amiLaunchIndex", <ide> namespace=NAMESPACE),
1
Mixed
Javascript
add isreadable helper
a698c49993050491c00d1127236d714c9e8ce2eb
<ide><path>doc/api/stream.md <ide> added: v17.3.0 <ide> <ide> Returns whether the stream has encountered an error. <ide> <add>### `stream.isReadable(stream)` <add> <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>> Stability: 1 - Experimental <add> <add>* `stream` {Readable|Duplex|ReadableStream} <add>* Returns: {boolean} <add> <add>Returns whether the stream is readable. <add> <ide> ### `stream.Readable.toWeb(streamReadable)` <ide> <ide> <!-- YAML <ide><path>lib/internal/streams/utils.js <ide> const { <ide> <ide> const kDestroyed = Symbol('kDestroyed'); <ide> const kIsErrored = Symbol('kIsErrored'); <add>const kIsReadable = Symbol('kIsReadable'); <ide> const kIsDisturbed = Symbol('kIsDisturbed'); <ide> <ide> function isReadableNodeStream(obj, strict = false) { <ide> function isReadableFinished(stream, strict) { <ide> } <ide> <ide> function isReadable(stream) { <add> if (stream && stream[kIsReadable] != null) return stream[kIsReadable]; <ide> const r = isReadableNodeStream(stream); <ide> if (r === null || typeof stream?.readable !== 'boolean') return null; <ide> if (isDestroyed(stream)) return false; <ide> function isErrored(stream) { <ide> module.exports = { <ide> kDestroyed, <ide> isDisturbed, <del> isErrored, <ide> kIsDisturbed, <add> isErrored, <ide> kIsErrored, <add> isReadable, <add> kIsReadable, <ide> isClosed, <ide> isDestroyed, <ide> isDuplexNodeStream, <ide> isFinished, <ide> isIterable, <del> isReadable, <ide> isReadableNodeStream, <ide> isReadableEnded, <ide> isReadableFinished, <ide><path>lib/internal/webstreams/readablestream.js <ide> const { <ide> const { <ide> kIsDisturbed, <ide> kIsErrored, <add> kIsReadable, <ide> } = require('internal/streams/utils'); <ide> <ide> const { <ide> class ReadableStream { <ide> return this[kState].state === 'errored'; <ide> } <ide> <add> get [kIsReadable]() { <add> return this[kState].state === 'readable'; <add> } <add> <ide> /** <ide> * @readonly <ide> * @type {boolean} <ide><path>lib/stream.js <ide> const utils = require('internal/streams/utils'); <ide> const Stream = module.exports = require('internal/streams/legacy').Stream; <ide> Stream.isDisturbed = utils.isDisturbed; <ide> Stream.isErrored = utils.isErrored; <add>Stream.isReadable = utils.isReadable; <ide> Stream.Readable = require('internal/streams/readable'); <ide> for (const key of ObjectKeys(operators)) { <ide> const op = operators[key]; <ide><path>test/parallel/test-whatwg-readablestream.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const { isDisturbed, isErrored } = require('stream'); <add>const { isDisturbed, isErrored, isReadable } = require('stream'); <ide> const assert = require('assert'); <ide> const { <ide> isPromise, <ide> class Source { <ide> })().then(common.mustCall()); <ide> } <ide> <del> <ide> { <ide> const stream = new ReadableStream({ <ide> pull: common.mustCall((controller) => { <ide> class Source { <ide> isErrored(stream, true); <ide> })().then(common.mustCall()); <ide> } <add> <add>{ <add> const stream = new ReadableStream({ <add> pull: common.mustCall((controller) => { <add> controller.error(new Error()); <add> }), <add> }); <add> <add> const reader = stream.getReader(); <add> (async () => { <add> isReadable(stream, true); <add> await reader.read().catch(common.mustCall()); <add> isReadable(stream, false); <add> })().then(common.mustCall()); <add>}
5
PHP
PHP
apply fixes from styleci
a0707c2f82da6a5320d68018d301887f4696b936
<ide><path>src/Illuminate/Database/Eloquent/Relations/Pivot.php <ide> protected function getDeleteQuery() <ide> { <ide> return $this->newQuery()->where([ <ide> $this->foreignKey => $this->getAttribute($this->foreignKey), <del> $this->otherKey => $this->getAttribute($this->otherKey) <add> $this->otherKey => $this->getAttribute($this->otherKey), <ide> ]); <ide> } <ide>
1
Python
Python
fix typo in bert tokenization file
f778edb739a1ef2ff96b09cf6b9e80fa3824a6ba
<ide><path>src/transformers/models/bert/tokenization_bert.py <ide> class BertTokenizer(PreTrainedTokenizer): <ide> <ide> This should likely be deactivated for Japanese (see this <ide> [issue](https://github.com/huggingface/transformers/issues/328)). <del> strip_accents: (`bool`, *optional*): <add> strip_accents (`bool`, *optional*): <ide> Whether or not to strip all accents. If this option is not specified, then it will be determined by the <ide> value for `lowercase` (as in the original BERT). <ide> """ <ide> def tokenize(self, text, never_split=None): <ide> WordPieceTokenizer. <ide> <ide> Args: <del> never_split (`LIst[str]`, *optional*) <add> never_split (`List[str]`, *optional*) <ide> Kept for backward compatibility purposes. Now implemented directly at the base class level (see <ide> [`PreTrainedTokenizer.tokenize`]) List of token not to split. <ide> """ <ide><path>src/transformers/models/bert/tokenization_bert_fast.py <ide> class BertTokenizerFast(PreTrainedTokenizerFast): <ide> tokenize_chinese_chars (`bool`, *optional*, defaults to `True`): <ide> Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this <ide> issue](https://github.com/huggingface/transformers/issues/328)). <del> strip_accents: (`bool`, *optional*): <add> strip_accents (`bool`, *optional*): <ide> Whether or not to strip all accents. If this option is not specified, then it will be determined by the <ide> value for `lowercase` (as in the original BERT). <del> wordpieces_prefix: (`str`, *optional*, defaults to `"##"`): <add> wordpieces_prefix (`str`, *optional*, defaults to `"##"`): <ide> The prefix for subwords. <ide> """ <ide> <ide><path>src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py <ide> def tokenize(self, text, never_split=None): <ide> WordPieceTokenizer. <ide> <ide> Args: <del> never_split (`LIst[str]`, *optional*) <add> never_split (`List[str]`, *optional*) <ide> Kept for backward compatibility purposes. Now implemented directly at the base class level (see <ide> [`PreTrainedTokenizer.tokenize`]) List of token not to split. <ide> """ <ide><path>src/transformers/models/mpnet/tokenization_mpnet.py <ide> def tokenize(self, text, never_split=None): <ide> WordPieceTokenizer. <ide> <ide> Args: <del> never_split (`LIst[str]`, *optional*) <add> never_split (`List[str]`, *optional*) <ide> Kept for backward compatibility purposes. Now implemented directly at the base class level (see <ide> [`PreTrainedTokenizer.tokenize`]) List of token not to split. <ide> """ <ide><path>src/transformers/models/tapas/tokenization_tapas.py <ide> def tokenize(self, text, never_split=None): <ide> WordPieceTokenizer. <ide> <ide> Args: <del> never_split (`LIst[str]`, *optional*) <add> never_split (`List[str]`, *optional*) <ide> Kept for backward compatibility purposes. Now implemented directly at the base class level (see <ide> [`PreTrainedTokenizer.tokenize`]) List of token not to split. <ide> """
5
Python
Python
remove unused variables
34ebad029c59bf47d8fff7164c80779e02650df7
<ide><path>celery/backends/dynamodb.py <ide> from celery.exceptions import ImproperlyConfigured <ide> from celery.five import string <ide> from celery.utils.log import get_logger <del> <ide> from .base import KeyValueStoreBackend <ide> <ide> try: <ide> def _get_table_ttl_description(self): <ide> description = self._client.describe_time_to_live( <ide> TableName=self.table_name <ide> ) <del> status = description['TimeToLiveDescription']['TimeToLiveStatus'] <ide> except ClientError as e: <ide> error_code = e.response['Error'].get('Code', 'Unknown') <ide> error_message = e.response['Error'].get('Message', 'Unknown') <ide> def _set_table_ttl(self): <ide> 'DynamoDB Time to Live is {situation} ' <ide> 'on table {table}' <ide> ).format( <del> situation='already enabled' \ <del> if status == 'ENABLED' \ <del> else 'currently being enabled', <add> situation='already enabled' <add> if status == 'ENABLED' <add> else 'currently being enabled', <ide> table=self.table_name <ide> )) <ide> return description <ide> def _set_table_ttl(self): <ide> 'DynamoDB Time to Live is {situation} ' <ide> 'on table {table}' <ide> ).format( <del> situation='already disabled' \ <del> if status == 'DISABLED' \ <del> else 'currently being disabled', <add> situation='already disabled' <add> if status == 'DISABLED' <add> else 'currently being disabled', <ide> table=self.table_name <ide> )) <ide> return description <ide> <ide> # The state shouldn't ever have any value beyond the four handled <ide> # above, but to ease troubleshooting of potential future changes, emit <ide> # a log showing the unknown state. <del> else: # pragma: no cover <add> else: # pragma: no cover <ide> logger.warning(( <ide> 'Unknown DynamoDB Time to Live status {status} ' <ide> 'on table {table}. Attempting to continue.' <ide><path>t/integration/test_canvas.py <ide> def test_link_error_using_signature_eager(self): <ide> <ide> exception = ExpectedException("Task expected to fail", "test") <ide> assert (fail.apply().get(timeout=TIMEOUT, propagate=False), True) == ( <del> exception, True) <add> exception, True) <ide> <ide> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception) <ide> def test_link_error_using_signature(self): <ide> def test_link_error_using_signature(self): <ide> <ide> exception = ExpectedException("Task expected to fail", "test") <ide> assert (fail.delay().get(timeout=TIMEOUT, propagate=False), True) == ( <del> exception, True) <add> exception, True) <ide> <ide> <ide> class test_chain: <ide> def test_single_chain(self, manager): <ide> def test_complex_chain(self, manager): <ide> c = ( <ide> add.s(2, 2) | ( <del> add.s(4) | add_replaced.s(8) | add.s(16) | add.s(32) <del> ) | <add> add.s(4) | add_replaced.s(8) | add.s(16) | add.s(32) <add> ) | <ide> group(add.s(i) for i in range(4)) <ide> ) <ide> res = c() <ide> def test_redis_subscribed_channels_leak(self, manager): <ide> # (existing from previous tests). <ide> chord_header_task_count = 2 <ide> assert channels_before_count <= \ <del> chord_header_task_count * total_chords + initial_channels_count <add> chord_header_task_count * total_chords + initial_channels_count <ide> <ide> result_values = [ <ide> result.get(timeout=TIMEOUT) <ide><path>t/unit/backends/test_dynamodb.py <ide> def test_get_client_time_to_live_called( <ide> app=self.app, <ide> url='dynamodb://key:secret@test?ttl_seconds=30' <ide> ) <del> client = backend._get_client() <add> backend._get_client() <ide> <ide> mock_validate_ttl_methods.assert_called_once() <ide> mock_set_table_ttl.assert_called_once() <ide> def test_set_table_ttl_enable_when_disabled_succeeds(self): <ide> } <ide> } <ide> <del> res = self.backend._set_table_ttl() <add> self.backend._set_table_ttl() <ide> mock_describe_time_to_live.assert_called_once_with( <ide> TableName=self.backend.table_name <ide> ) <ide> def test_set_table_ttl_enable_when_disabled_succeeds(self): <ide> def test_set_table_ttl_enable_when_enabled_with_correct_attr_succeeds(self): <ide> self.backend.time_to_live_seconds = 30 <ide> self.backend._client = MagicMock() <del> mock_update_time_to_live = self.backend._client.update_time_to_live = \ <del> MagicMock() <add> self.backend._client.update_time_to_live = MagicMock() <ide> <ide> mock_describe_time_to_live = \ <ide> self.backend._client.describe_time_to_live = MagicMock() <ide> def test_set_table_ttl_enable_when_enabled_with_wrong_attr_raises(self): <ide> def test_set_table_ttl_disable_when_disabled_succeeds(self): <ide> self.backend.time_to_live_seconds = -1 <ide> self.backend._client = MagicMock() <del> mock_update_time_to_live = self.backend._client.update_time_to_live = \ <del> MagicMock() <add> self.backend._client.update_time_to_live = MagicMock() <ide> mock_describe_time_to_live = \ <ide> self.backend._client.describe_time_to_live = MagicMock() <ide>
3
Ruby
Ruby
remove chain delegate
a8775bba58fb9dd3b0a51a812fa6ec43d8084ff6
<ide><path>activerecord/lib/active_record/associations/association_scope.rb <ide> class AssociationScope #:nodoc: <ide> attr_reader :association, :alias_tracker <ide> <ide> delegate :klass, :reflection, :to => :association <del> delegate :chain, :to => :reflection <ide> <ide> def initialize(association) <ide> @association = association <ide> def scope <ide> scope.extending! Array(reflection.options[:extend]) <ide> <ide> owner = association.owner <del> add_constraints(scope, owner, reflection.scope_chain) <add> scope_chain = reflection.scope_chain <add> chain = reflection.chain <add> add_constraints(scope, owner, scope_chain, chain) <ide> end <ide> <ide> def join_type <ide> def join_type <ide> <ide> private <ide> <del> def construct_tables <add> def construct_tables(chain) <ide> chain.map do |reflection| <ide> alias_tracker.aliased_table_for( <ide> table_name_for(reflection), <ide> def bind(scope, table_name, column_name, value) <ide> bind_value scope, column, value <ide> end <ide> <del> def add_constraints(scope, owner, scope_chain) <del> tables = construct_tables <add> def add_constraints(scope, owner, scope_chain, chain) <add> tables = construct_tables(chain) <ide> <ide> chain.each_with_index do |reflection, i| <ide> table, foreign_table = tables.shift, tables.first
1
Python
Python
add unit test
f646f1c78188a92b0fbdad67a1bd51224460c7fb
<ide><path>libcloud/test/compute/test_ecs.py <ide> def _create_node_CreateInstance(self, method, url, body, headers): <ide> 'InternetMaxBandwidthIn': '200', <ide> 'HostName': 'hostname', <ide> 'Password': 'password', <del> 'IoOptimized': 'true', <add> 'IoOptimized': 'optimized', <ide> 'SystemDisk.Category': 'cloud', <ide> 'SystemDisk.DiskName': 'root', <ide> 'SystemDisk.Description': 'sys',
1
Mixed
Javascript
add setnativevalue command to reactcheckboxmanager
cd1e34d4a27b32d33a636f16c1184e100aab9707
<ide><path>Libraries/Components/CheckBox/AndroidCheckBoxNativeComponent.js <ide> <ide> 'use strict'; <ide> <add>import * as React from 'react'; <add> <add>import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands'; <add> <ide> const requireNativeComponent = require('../../ReactNative/requireNativeComponent'); <ide> <ide> import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes'; <ide> type NativeProps = $ReadOnly<{| <ide> tintColors: {|true: ?number, false: ?number|} | typeof undefined, <ide> |}>; <ide> <del>const AndroidCheckBoxNativeComponent: HostComponent<NativeProps> = requireNativeComponent<NativeProps>( <del> 'AndroidCheckBox', <del>); <add>type NativeType = HostComponent<NativeProps>; <ide> <del>module.exports = AndroidCheckBoxNativeComponent; <add>interface NativeCommands { <add> +setNativeValue: ( <add> viewRef: React.ElementRef<NativeType>, <add> value: boolean, <add> ) => void; <add>} <add> <add>export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({ <add> supportedCommands: ['setNativeValue'], <add>}); <add> <add>export default (requireNativeComponent<NativeProps>( <add> 'AndroidCheckBox', <add>): NativeType); <ide><path>Libraries/Components/CheckBox/CheckBox.android.js <ide> const React = require('react'); <ide> const StyleSheet = require('../../StyleSheet/StyleSheet'); <ide> const processColor = require('../../StyleSheet/processColor'); <ide> <del>const AndroidCheckBoxNativeComponent = require('./AndroidCheckBoxNativeComponent'); <ide> const nullthrows = require('nullthrows'); <ide> const setAndForwardRef = require('../../Utilities/setAndForwardRef'); <ide> <add>import AndroidCheckBoxNativeComponent from './AndroidCheckBoxNativeComponent'; <add> <ide> import type {ViewProps} from '../View/ViewPropTypes'; <ide> import type {SyntheticEvent} from '../../Types/CoreEventTypes'; <ide> import type {ColorValue} from '../../StyleSheet/StyleSheetTypes'; <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxManager.java <ide> import android.content.res.ColorStateList; <ide> import android.util.TypedValue; <ide> import android.widget.CompoundButton; <add>import androidx.annotation.NonNull; <ide> import androidx.annotation.Nullable; <ide> import androidx.appcompat.widget.TintContextWrapper; <ide> import androidx.core.widget.CompoundButtonCompat; <ide> import com.facebook.react.bridge.ReactContext; <add>import com.facebook.react.bridge.ReadableArray; <ide> import com.facebook.react.bridge.ReadableMap; <ide> import com.facebook.react.uimanager.SimpleViewManager; <ide> import com.facebook.react.uimanager.ThemedReactContext; <ide> public void setOn(ReactCheckBox view, boolean on) { <ide> view.setOnCheckedChangeListener(ON_CHECKED_CHANGE_LISTENER); <ide> } <ide> <add> @Override <add> public void receiveCommand( <add> @NonNull ReactCheckBox root, String commandId, @Nullable ReadableArray args) { <add> switch (commandId) { <add> case "setNativeValue": <add> if (args != null) { <add> setOn(root, args.getBoolean(0)); <add> break; <add> } <add> } <add> } <add> <ide> private static int getThemeColor(final Context context, String colorId) { <ide> final TypedValue value = new TypedValue(); <ide> context.getTheme().resolveAttribute(getIdentifier(context, colorId), value, true);
3
Java
Java
fix precondition assertions
9e4cddf5db33a44675bba2a00cd25032b84ab87d
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/support/InjectionCodeGenerator.java <ide> class InjectionCodeGenerator { <ide> <ide> <ide> InjectionCodeGenerator(ClassName targetClassName, RuntimeHints hints) { <del> Assert.notNull(hints, "ClassName must not be null"); <add> Assert.notNull(targetClassName, "ClassName must not be null"); <ide> Assert.notNull(hints, "RuntimeHints must not be null"); <ide> this.targetClassName = targetClassName; <ide> this.hints = hints; <ide><path>spring-web/src/main/java/org/springframework/http/ContentDisposition.java <ide> private static boolean isRFC5987AttrChar(byte c) { <ide> * @see <a href="https://tools.ietf.org/html/rfc2047">RFC 2047</a> <ide> */ <ide> private static String decodeQuotedPrintableFilename(String filename, Charset charset) { <del> Assert.notNull(filename, "'input' String should not be null"); <del> Assert.notNull(charset, "'charset' should not be null"); <add> Assert.notNull(filename, "'filename' must not be null"); <add> Assert.notNull(charset, "'charset' must not be null"); <ide> <ide> byte[] value = filename.getBytes(US_ASCII); <ide> ByteArrayOutputStream baos = new ByteArrayOutputStream();
2
Text
Text
remove align from tables
73f4dc8464bbcf7423304a3304b2c9fe18f49dd8
<ide><path>doc/api/n-api.md <ide> to recompile for new versions of Node.js which are <ide> listed as supporting a later version. <ide> <ide> | | 1 | 2 | 3 | 4 | 5 | <del>|:-----:|:-------:|:--------:|:--------:|:--------:|:---------:| <add>|-------|---------|----------|----------|----------|-----------| <ide> | v6.x | | | v6.14.2* | | | <ide> | v8.x | v8.0.0* | v8.10.0* | v8.11.2 | v8.16.0 | | <ide> | v9.x | v9.0.0* | v9.3.0* | v9.11.0* | | | <ide><path>doc/api/url.md <ide> The port value can be an empty string in which case the port depends on <ide> the protocol/scheme: <ide> <ide> | protocol | port | <del>| :------- | :--- | <add>| -------- | ---- | <ide> | "ftp" | 21 | <ide> | "file" | | <ide> | "gopher" | 70 |
2
Javascript
Javascript
adjust highlighting on window resize
6d53a2ec100c8d30ddb4ac180ab90a4320144a94
<ide><path>src/devtools/views/Components/Tree.js <ide> function InnerElementType({ style, ...rest }) { <ide> // What we can do instead, is passively measure the width of the current rows, <ide> // and ensure that once we've grown to a new max size, we don't shrink below it. <ide> // This improves the user experience when scrolling between wide and narrow rows. <del> // We shouldn't retain this width across different conceptual trees though, <del> // so when the user opens the "owners tree" view, we should discard the previous width. <ide> const divRef = useRef<HTMLDivElement | null>(null); <del> const minWidthRef = useRef<number | null>(null); <del> const minWidth = <del> ownerStack.length > 0 || minWidthRef.current === null <del> ? '100%' <del> : minWidthRef.current; <add> const [minWidth, setMinWidth] = useState(null); <ide> useEffect(() => { <ide> if (divRef.current !== null) { <del> minWidthRef.current = Math.max( <del> minWidthRef.current || 0, <del> divRef.current.offsetWidth <del> ); <add> const measuredWidth = divRef.current.offsetWidth; <add> setMinWidth(w => Math.max(w || 0, measuredWidth)); <ide> } <ide> }); <ide> <add> // When the window is resized, forget the specific min width. <add> // This will cause a render with 100% min-width, a measurement <add> // in an effect, and a second render where we know the width. <add> useEffect(() => { <add> const invalidateMinWidth = () => setMinWidth(null); <add> window.addEventListener('resize', invalidateMinWidth); <add> return () => window.removeEventListener('resize', invalidateMinWidth); <add> }, []); <add> <add> // We shouldn't retain this width across different conceptual trees though, <add> // so when the user opens the "owners tree" view, we should discard the previous width. <add> const hasOwnerStack = ownerStack.length > 0; <add> const [prevHasOwnerStack, setPrevHasOwnerStack] = useState(hasOwnerStack); <add> if (hasOwnerStack !== prevHasOwnerStack) { <add> setPrevHasOwnerStack(hasOwnerStack); <add> setMinWidth(null); <add> } <add> <ide> // This style override enables the background color to fill the full visible width, <ide> // when combined with the CSS tweaks in Element. <ide> // A lot of options were considered; this seemed the one that requires the least code. <ide> function InnerElementType({ style, ...rest }) { <ide> style={{ <ide> ...style, <ide> display: 'inline-block', <del> minWidth, <add> minWidth: minWidth || '100%', <ide> width: undefined, <ide> }} <ide> ref={divRef}
1
Python
Python
add defensive check
89c903c6a994817240910c30037f87af6ce0ed87
<ide><path>libcloud/compute/drivers/openstack.py <ide> def _create_args_to_params(self, node, **kwargs): <ide> name = security_group.name <ide> server_params['security_groups'].append({'name': name}) <ide> <del> if 'ex_blockdevicemappings' in kwargs: <add> if 'ex_blockdevicemappings' in kwargs \ <add> and kwargs['ex_blockdevicemappings']: <ide> if kwargs['ex_blockdevicemappings'][0].get('volume_id'): <ide> server_params['block_device_mapping'] = \ <ide> kwargs['ex_blockdevicemappings']
1
Text
Text
translate 10.4 to korean
d3ad46a461c70b51c294782949fdc29c0957d7b4
<ide><path>docs/docs/10.4-test-utils.ko-KR.md <add>--- <add>id: test-utils-ko-KR <add>title: ํ…Œ์ŠคํŠธ ์œ ํ‹ธ๋ฆฌํ‹ฐ <add>permalink: test-utils-ko-KR.html <add>prev: class-name-manipulation-ko-KR.html <add>next: clone-with-props-ko-KR.html <add>--- <add> <add>`React.addons.TestUtils`๋Š” ์„ ํƒํ•œ ํ…Œ์ŠคํŠธ ํ”„๋ ˆ์ž„์›Œํฌ(React๋Š” [Jest](http://facebook.github.io/jest/)๋ฅผ ์‚ฌ์šฉ)์—์„œ React ์ปดํฌ๋„ŒํŠธ๋ฅผ ํ…Œ์ŠคํŠธํ•˜๊ธฐ ์‰ฝ๊ฒŒ ํ•ฉ๋‹ˆ๋‹ค. <add> <add>### Simulate <add> <add>```javascript <add>Simulate.{eventName}(DOMElement element, object eventData) <add>``` <add> <add>DOM ๋…ธ๋“œ์— ์ด๋ฒคํŠธ ๋””์ŠคํŒจ์น˜ํ•˜๋Š” ๊ฒƒ์„ ์‹œ๋ฎฌ๋ ˆ์ดํŠธํ•ฉ๋‹ˆ๋‹ค. ์„ ํƒ์ ์œผ๋กœ `eventData`๋ฅผ ํ†ตํ•ด ์ด๋ฒคํŠธ ๋ฐ์ดํ„ฐ๋„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. **์•„๋งˆ `ReactTestUtils`์—์„œ ๊ฐ€์žฅ ์œ ์šฉํ•œ ์œ ํ‹ธ๋ฆฌํ‹ฐ์ผ ๊ฒƒ ์ž…๋‹ˆ๋‹ค.** <add> <add>์‚ฌ์šฉ ์˜ˆ: <add> <add>```javascript <add>var node = this.refs.input.getDOMNode(); <add>React.addons.TestUtils.Simulate.click(node); <add>React.addons.TestUtils.Simulate.change(node, {target: {value: 'Hello, world'}}); <add>React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter"}); <add>``` <add> <add>`Simulate`์—๋Š” React๊ฐ€ ์ดํ•ดํ•˜๋Š” ๋ชจ๋“  ์ด๋ฒคํŠธ์— ๋Œ€ํ•ด ๋ฉ”์†Œ๋“œ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. <add> <add>### renderIntoDocument <add> <add>```javascript <add>ReactComponent renderIntoDocument(ReactComponent instance) <add>``` <add> <add>๋ฌธ์„œ์˜ detach๋œ DOM ๋…ธ๋“œ์— ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ Œ๋”ํ•ฉ๋‹ˆ๋‹ค. **์ด ๊ธฐ๋Šฅ์€ DOM์„ ํ•„์š”๋กœ ํ•ฉ๋‹ˆ๋‹ค.** <add> <add>### mockComponent <add> <add>```javascript <add>object mockComponent(function componentClass, string? mockTagName) <add>``` <add> <add>๋ชฉ ์ปดํฌ๋„ŒํŠธ ๋ชจ๋“ˆ์„ ์ด ๋ฉ”์†Œ๋“œ์— ๋„˜๊ฒจ ๋”๋ฏธ React ์ปดํฌ๋„ŒํŠธ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ฉ๋‹ˆ๋‹ค. ์ด ๋”๋ฏธ๋Š” ์œ ์šฉํ•œ ๋ฉ”์†Œ๋“œ์™€ ํ•จ๊ป˜ ์‚ฌ์šฉํ•ด ๊ธฐ๋Šฅ์„ ๋ณด๊ฐ•ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ผ๋ฐ˜์ ์ธ ๋ Œ๋”๋ง๊ณผ๋Š” ๋‹ค๋ฅด๊ฒŒ, ์ปดํฌ๋„ŒํŠธ๋Š” ์ œ๊ณต๋œ ์ž์‹์„ ํฌํ•จํ•˜๋Š” ํ‰๋ฒ”ํ•œ `<div>`๊ฐ€ ๋ฉ๋‹ˆ๋‹ค. (`mockTagName`์„ ํ†ตํ•ด div๊ฐ€ ์•„๋‹Œ ๋‹ค๋ฅธ ํƒœ๊ทธ๋ฅผ ์ง€์ •ํ•ด ์ค„ ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.) <add> <add>### isElement <add> <add>```javascript <add>boolean isElement(ReactElement element) <add>``` <add> <add>`element`๊ฐ€ ReactElement๋ฉด true๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค. <add> <add>### isElementOfType <add> <add>```javascript <add>boolean isElementOfType(ReactElement element, function componentClass) <add>``` <add> <add>`element`๊ฐ€ React `componentClass` ํƒ€์ž…์ธ ReactElement๋ฉด true๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค. <add> <add>### isDOMComponent <add> <add>```javascript <add>boolean isDOMComponent(ReactComponent instance) <add>``` <add> <add>`instance`๊ฐ€ (`<div>`๋‚˜ `<span>`๊ฐ™์€) DOM ์ปดํฌ๋„ŒํŠธ๋ฉด true๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค. <add> <add>### isCompositeComponent <add> <add>```javascript <add>boolean isCompositeComponent(ReactComponent instance)` <add>``` <add> <add>`instance`๊ฐ€ (`React.createClass()`๋กœ ์ƒ์„ฑ๋œ) ๋ณตํ•ฉ ์ปดํฌ๋„ŒํŠธ๋ฉด true๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค. <add> <add>### isCompositeComponentWithType <add> <add>```javascript <add>boolean isCompositeComponentWithType(ReactComponent instance, function componentClass) <add>``` <add> <add>`instance`๊ฐ€ (`React.createClass()`๋กœ ์ƒ์„ฑ๋œ) ๋ณตํ•ฉ ์ปดํฌ๋„ŒํŠธ๊ณ  React `componentClass` ํƒ€์ž…์ด๋ฉด true๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค. <add> <add>### findAllInRenderedTree <add> <add>```javascript <add>array findAllInRenderedTree(ReactComponent tree, function test) <add>``` <add> <add>`tree`์•ˆ์˜ ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ์—์„œ `test(component)`๊ฐ€ true์ธ ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ชจ์๋‹ˆ๋‹ค. ์ด๊ฒƒ๋งŒ์œผ๋กœ๋Š” ๊ทธ๋ ‡๊ฒŒ ์œ ์šฉํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค๋งŒ, ๋‹ค๋ฅธ ํ…Œ์ŠคํŠธ ์œ ํ‹ธ์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. <add> <add>### scryRenderedDOMComponentsWithClass <add> <add>```javascript <add>array scryRenderedDOMComponentsWithClass(ReactComponent tree, string className) <add>``` <add>๋ Œ๋”๋œ ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ ์ธ์Šคํ„ด์Šค ์ค‘์—์„œ ํด๋ž˜์Šค ์ด๋ฆ„์ด `className`์ธ DOM ์ปดํฌ๋„ŒํŠธ๋“ค์„ ์ฐพ์Šต๋‹ˆ๋‹ค. <add> <add>### findRenderedDOMComponentWithClass <add> <add>```javascript <add>ReactComponent findRenderedDOMComponentWithClass(ReactComponent tree, string className) <add>``` <add> <add>`scryRenderedDOMComponentsWithClass()`์™€ ๋น„์Šทํ•˜์ง€๋งŒ ํ•˜๋‚˜์˜ ๊ฒฐ๊ณผ๋งŒ ๊ธฐ๋Œ€๋  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ํ•˜๋‚˜์˜ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•˜๊ฑฐ๋‚˜ ํ•œ๊ฐœ ์ด์ƒ์˜ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ ๊ฒฝ์šฐ์—๋Š” ์˜ˆ์™ธ๋ฅผ ๋˜์ง‘๋‹ˆ๋‹ค. <add> <add>### scryRenderedDOMComponentsWithTag <add> <add>```javascript <add>array scryRenderedDOMComponentsWithTag(ReactComponent tree, string tagName) <add>``` <add> <add>๋ Œ๋”๋œ ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ ์ธ์Šคํ„ด์Šค์ค‘์—์„œ ํƒœ๊ทธ ์ด๋ฆ„์ด `tagName`์ธ DOM ์ปดํฌ๋„ŒํŠธ๋“ค์„ ์ฐพ์Šต๋‹ˆ๋‹ค. <add> <add>### findRenderedDOMComponentWithTag <add> <add>```javascript <add>ReactComponent findRenderedDOMComponentWithTag(ReactComponent tree, string tagName) <add>``` <add> <add>`scryRenderedDOMComponentsWithTag()`์™€ ๋น„์Šทํ•˜์ง€๋งŒ ํ•˜๋‚˜์˜ ๊ฒฐ๊ณผ๋งŒ ๊ธฐ๋Œ€๋  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ํ•˜๋‚˜์˜ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•˜๊ฑฐ๋‚˜ ํ•œ๊ฐœ ์ด์ƒ์˜ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ ๊ฒฝ์šฐ์—๋Š” ์˜ˆ์™ธ๋ฅผ ๋˜์ง‘๋‹ˆ๋‹ค. <add> <add>### scryRenderedComponentsWithType <add> <add>```javascript <add>array scryRenderedComponentsWithType(ReactComponent tree, function componentClass) <add>``` <add> <add>ํƒ€์ž…์ด `componentClass`์ธ ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ ์ธ์Šคํ„ด์Šค๋ฅผ ์ฐพ์Šต๋‹ˆ๋‹ค. <add> <add>### findRenderedComponentWithType <add> <add>```javascript <add>ReactComponent findRenderedComponentWithType(ReactComponent tree, function componentClass) <add>``` <add> <add>`scryRenderedComponentsWithType()`์™€ ๋น„์Šทํ•˜์ง€๋งŒ ํ•˜๋‚˜์˜ ๊ฒฐ๊ณผ๋งŒ ๊ธฐ๋Œ€๋  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ํ•˜๋‚˜์˜ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•˜๊ฑฐ๋‚˜ ํ•œ๊ฐœ ์ด์ƒ์˜ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ ๊ฒฝ์šฐ์—๋Š” ์˜ˆ์™ธ๋ฅผ ๋˜์ง‘๋‹ˆ๋‹ค.
1
Ruby
Ruby
fix implicit ordering expectation
9047c9809deeb1aaa3735472287265720e5cd37f
<ide><path>actionpack/test/dispatch/test_request_test.rb <ide> class TestRequestTest < ActiveSupport::TestCase <ide> <ide> req.cookies["login"] = "XJ-122" <ide> assert_equal({"user_name" => "david", "login" => "XJ-122"}, req.cookies) <del> assert_equal "login=XJ-122; user_name=david;", req.env["HTTP_COOKIE"] <add> assert_equal %w(login=XJ-122 user_name=david), req.env["HTTP_COOKIE"].split(/; ?/).sort <ide> end <ide> end
1
Python
Python
fix parser names in docstring
d417c6d1b9fb779f86b11e7526337f4101af414f
<ide><path>rest_framework/settings.py <ide> ) <ide> 'DEFAULT_PARSER_CLASSES': ( <ide> 'rest_framework.parsers.JSONParser', <del> 'rest_framework.parsers.TemplateHTMLParser', <add> 'rest_framework.parsers.FormParser', <add> 'rest_framework.parsers.MultiPartParser' <ide> ) <ide> } <ide>
1
PHP
PHP
set security token as separate request attribute
c58bc97f573e4fc12a2bbd6689ec6d8fb46e66ca
<ide><path>src/Controller/Component/SecurityComponent.php <ide> public function generateToken(ServerRequest $request): ServerRequest <ide> { <ide> if ($request->is('requested')) { <ide> if ($request->getSession()->check('_Token')) { <del> $request = $request->withParam('_Token', $request->getSession()->read('_Token')); <add> $request = $request->withAttribute('securityToken', $request->getSession()->read('_Token')); <ide> } <ide> <ide> return $request; <ide> } <add> <ide> $token = [ <ide> 'allowedControllers' => $this->_config['allowedControllers'], <ide> 'allowedActions' => $this->_config['allowedActions'], <ide> public function generateToken(ServerRequest $request): ServerRequest <ide> <ide> $request->getSession()->write('_Token', $token); <ide> <del> return $request->withParam('_Token', [ <add> return $request->withAttribute('securityToken', [ <ide> 'unlockedFields' => $token['unlockedFields'], <ide> ]); <ide> } <ide><path>src/Routing/Router.php <ide> public static function reverseToArray($params): array <ide> unset( <ide> $params['pass'], <ide> $params['paging'], <del> $params['_Token'], <ide> $params['_matchedRoute'], <ide> $params['_name'] <ide> ); <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> public function testGenerateToken(): void <ide> $request = $this->Controller->getRequest(); <ide> $request = $this->Security->generateToken($request); <ide> <del> $this->assertNotEmpty($request->getParam('_Token')); <del> $this->assertSame([], $request->getParam('_Token.unlockedFields')); <add> $securityToken = $request->getAttribute('securityToken'); <add> $this->assertNotEmpty($securityToken); <add> $this->assertSame([], $securityToken['unlockedFields']); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testReverseToken() <ide> 'bare' => 1, <ide> 'return' => 1, <ide> 'requested' => 1, <del> '_Token' => ['key' => 'sekret'], <ide> ]; <ide> $result = Router::reverse($params); <ide> $this->assertSame('/posts/view/1', $result);
4
Text
Text
add @annthurium weekly focus
0306638abb123fafb1756bb768890bc0159db840
<ide><path>docs/focus/2018-04-16.md <ide> - GitHub Package <ide> - Completed, merged, and shipped "Create pull request" [atom/github#1376](https://github.com/atom/github/pull/1376), which I used to open this pull request :wink: <ide> - Updated to Enzyme 3 [atom/github#1386](https://github.com/atom/github/pull/1386) which paves the way for us to upgrade React. <add> - Started investigating code coverage to better understand what code lies untested. <ide> - Teletype <ide> - Fixed an issue that could occur when attempting to join a portal that no longer exists while also trying to share a portal ([atom/teletype#357](https://github.com/atom/teletypeissues/atom/teletype/357)) <ide> - Fixed an issue that could occur when existing portal participants are performing actions while a new participant is joining ([atom/teletype#360](https://github.com/atom/teletypeissues/atom/teletype/360)) <ide> - GitHub Package <ide> - Update React to 16.3 (@smashwilson) <ide> - Get [atom/squeegpg](https://github.com/atom/squeegpg) to the point where we can use it to sign a commit from atom/github (without needing to override the pinentry yet). (@smashwilson) <add> - Get code coverage working. (@annthurium) <ide> - Teletype <ide> - Publish RFC for more quickly collaborating with coworkers and friends ([atom/teletype#344](https://github.com/atom/teletype/pull/344)) <ide> - Improve ability to tell which cursor belongs to which collaborator ([atom/teletype#338](https://github.com/atom/teletype/issues/338))
1
Text
Text
move sam-github to tsc emeriti
1aa847f7438407b78cc0d1f9eab96adcfe9ff9df
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Matheus Marchini** &lt;[email protected]&gt; <ide> * [MylesBorins](https://github.com/MylesBorins) - <ide> **Myles Borins** &lt;[email protected]&gt; (he/him) <del>* [sam-github](https://github.com/sam-github) - <del>**Sam Roberts** &lt;[email protected]&gt; <ide> * [targos](https://github.com/targos) - <ide> **Michaรซl Zasso** &lt;[email protected]&gt; (he/him) <ide> * [tniessen](https://github.com/tniessen) - <ide> For information about the governance of the Node.js project, see <ide> **Bert Belder** &lt;[email protected]&gt; <ide> * [rvagg](https://github.com/rvagg) - <ide> **Rod Vagg** &lt;[email protected]&gt; <add>* [sam-github](https://github.com/sam-github) - <add>**Sam Roberts** &lt;[email protected]&gt; <ide> * [shigeki](https://github.com/shigeki) - <ide> **Shigeki Ohtsu** &lt;[email protected]&gt; (he/him) <ide> * [thefourtheye](https://github.com/thefourtheye) - <ide> For information about the governance of the Node.js project, see <ide> **Ujjwal Sharma** &lt;[email protected]&gt; (he/him) <ide> * [saghul](https://github.com/saghul) - <ide> **Saรบl Ibarra Corretgรฉ** &lt;[email protected]&gt; <del>* [sam-github](https://github.com/sam-github) - <del>**Sam Roberts** &lt;[email protected]&gt; <ide> * [santigimeno](https://github.com/santigimeno) - <ide> **Santiago Gimeno** &lt;[email protected]&gt; <ide> * [sebdeckers](https://github.com/sebdeckers) - <ide> For information about the governance of the Node.js project, see <ide> **Roman Klauke** &lt;[email protected]&gt; <ide> * [RReverser](https://github.com/RReverser) - <ide> **Ingvar Stepanyan** &lt;[email protected]&gt; <add>* [sam-github](https://github.com/sam-github) - <add>**Sam Roberts** &lt;[email protected]&gt; <ide> * [stefanmb](https://github.com/stefanmb) - <ide> **Stefan Budeanu** &lt;[email protected]&gt; <ide> * [tellnes](https://github.com/tellnes) -
1
PHP
PHP
add contextfactory class
5625bc4454a8a55c5ef204ca2e3113cb53355a99
<ide><path>src/View/Form/ContextFactory.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 3.5.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\View\Form; <add> <add>use Cake\Collection\Collection; <add>use Cake\Datasource\EntityInterface; <add>use Cake\Form\Form; <add>use Cake\Http\ServerRequest; <add>use RuntimeException; <add>use Traversable; <add> <add>/** <add> * Factory for getting form context instance based on provided data. <add> */ <add>class ContextFactory <add>{ <add> /** <add> * Context provider methods. <add> * <add> * @var array <add> */ <add> protected $contextProviders = []; <add> <add> /** <add> * Constructor. <add> * <add> * @param array $providers Array of provider callables. Each element should <add> * be of form `['type' => 'a-string', 'callable' => ..]` <add> * @param bool $addDefaults Whether default providers should be added. <add> */ <add> public function __construct(array $providers = [], $addDefaults = true) <add> { <add> if ($addDefaults) { <add> $this->addDefaultProviders(); <add> } <add> <add> foreach ($providers as $provider) { <add> $this->addProvider($provider['type'], $provider); <add> } <add> } <add> <add> /** <add> * Add a new context type. <add> * <add> * Form context types allow FormHelper to interact with <add> * data providers that come from outside CakePHP. For example <add> * if you wanted to use an alternative ORM like Doctrine you could <add> * create and connect a new context class to allow FormHelper to <add> * read metadata from doctrine. <add> * <add> * @param string $type The type of context. This key <add> * can be used to overwrite existing providers. <add> * @param callable $check A callable that returns an object <add> * when the form context is the correct type. <add> * @return void <add> */ <add> public function addProvider($type, callable $check) <add> { <add> $this->contextProviders = [$type => ['type' => $type, 'callable' => $check]] <add> + $this->contextProviders; <add> } <add> <add> /** <add> * Find the matching context for the data. <add> * <add> * If no type can be matched a NullContext will be returned. <add> * <add> * @param \Cake\Http\ServerRequest $request Request instance. <add> * @param array $data The data to get a context provider for. <add> * @return \Cake\View\Form\ContextInterface Context provider. <add> * @throws \RuntimeException when the context class does not implement the <add> * ContextInterface. <add> */ <add> public function get(ServerRequest $request, array $data = []) <add> { <add> $data += ['entity' => null]; <add> <add> foreach ($this->contextProviders as $provider) { <add> $check = $provider['callable']; <add> $context = $check($request, $data); <add> if ($context) { <add> break; <add> } <add> } <add> if (!isset($context)) { <add> $context = new NullContext($request, $data); <add> } <add> if (!($context instanceof ContextInterface)) { <add> throw new RuntimeException( <add> 'Context objects must implement Cake\View\Form\ContextInterface' <add> ); <add> } <add> <add> return $context; <add> } <add> <add> /** <add> * Add the default suite of context providers. <add> * <add> * @return void <add> */ <add> protected function addDefaultProviders() <add> { <add> $this->addProvider('orm', function ($request, $data) { <add> if (is_array($data['entity']) || $data['entity'] instanceof Traversable) { <add> $pass = (new Collection($data['entity']))->first() !== null; <add> if ($pass) { <add> return new EntityContext($request, $data); <add> } <add> } <add> if ($data['entity'] instanceof EntityInterface) { <add> return new EntityContext($request, $data); <add> } <add> if (is_array($data['entity']) && empty($data['entity']['schema'])) { <add> return new EntityContext($request, $data); <add> } <add> }); <add> <add> $this->addProvider('form', function ($request, $data) { <add> if ($data['entity'] instanceof Form) { <add> return new FormContext($request, $data); <add> } <add> }); <add> <add> $this->addProvider('array', function ($request, $data) { <add> if (is_array($data['entity']) && isset($data['entity']['schema'])) { <add> return new ArrayContext($request, $data['entity']); <add> } <add> }); <add> } <add>} <ide><path>src/View/Helper/FormHelper.php <ide> */ <ide> namespace Cake\View\Helper; <ide> <del>use Cake\Collection\Collection; <ide> use Cake\Core\Configure; <ide> use Cake\Core\Exception\Exception; <del>use Cake\Datasource\EntityInterface; <ide> use Cake\Form\Form; <ide> use Cake\Routing\Router; <ide> use Cake\Utility\Hash; <ide> use Cake\Utility\Inflector; <del>use Cake\View\Form\ArrayContext; <add>use Cake\View\Form\ContextFactory; <ide> use Cake\View\Form\ContextInterface; <del>use Cake\View\Form\EntityContext; <del>use Cake\View\Form\FormContext; <del>use Cake\View\Form\NullContext; <ide> use Cake\View\Helper; <ide> use Cake\View\StringTemplateTrait; <ide> use Cake\View\View; <ide> class FormHelper extends Helper <ide> protected $_context; <ide> <ide> /** <del> * Context provider methods. <add> * Context factory. <ide> * <del> * @var array <del> * @see \Cake\View\Helper\FormHelper::addContextProvider() <add> * @var \Cake\View\FormContextFactory <ide> */ <del> protected $_contextProviders = []; <add> protected $_contextFactory; <ide> <ide> /** <ide> * The action attribute value of the last created form. <ide> public function __construct(View $View, array $config = []) <ide> parent::__construct($View, $config); <ide> <ide> $this->widgetRegistry($registry, $widgets); <del> $this->_addDefaultContextProviders(); <ide> $this->_idPrefix = $this->getConfig('idPrefix'); <ide> } <ide> <ide> public function widgetRegistry(WidgetRegistry $instance = null, $widgets = []) <ide> } <ide> <ide> /** <del> * Add the default suite of context providers provided by CakePHP. <add> * Set the context factory the helper will use. <ide> * <del> * @return void <add> * @param \Cake\View\Form\ContextFactory|null $instance The context factory instance to set. <add> * @param array $contexts An array of context providers. <add> * @return \Cake\View\Form\ContextFactory <ide> */ <del> protected function _addDefaultContextProviders() <add> public function contextFactory(ContextFactory $instance = null, array $contexts = []) <ide> { <del> $this->addContextProvider('orm', function ($request, $data) { <del> if (is_array($data['entity']) || $data['entity'] instanceof Traversable) { <del> $pass = (new Collection($data['entity']))->first() !== null; <del> if ($pass) { <del> return new EntityContext($request, $data); <del> } <del> } <del> if ($data['entity'] instanceof EntityInterface) { <del> return new EntityContext($request, $data); <del> } <del> if (is_array($data['entity']) && empty($data['entity']['schema'])) { <del> return new EntityContext($request, $data); <add> if ($instance === null) { <add> if ($this->_contextFactory === null) { <add> $this->_contextFactory = new ContextFactory($contexts); <ide> } <del> }); <ide> <del> $this->addContextProvider('form', function ($request, $data) { <del> if ($data['entity'] instanceof Form) { <del> return new FormContext($request, $data); <del> } <del> }); <add> return $this->_contextFactory; <add> } <add> $this->_contextFactory = $instance; <ide> <del> $this->addContextProvider('array', function ($request, $data) { <del> if (is_array($data['entity']) && isset($data['entity']['schema'])) { <del> return new ArrayContext($request, $data['entity']); <del> } <del> }); <add> return $this->_contextFactory; <ide> } <ide> <ide> /** <ide> protected function _secureFieldName($name) <ide> */ <ide> public function addContextProvider($type, callable $check) <ide> { <del> foreach ($this->_contextProviders as $i => $provider) { <del> if ($provider['type'] === $type) { <del> unset($this->_contextProviders[$i]); <del> } <del> } <del> array_unshift($this->_contextProviders, ['type' => $type, 'callable' => $check]); <add> $this->contextFactory()->addProvider($type, $check); <ide> } <ide> <ide> /** <ide> protected function _getContext($data = []) <ide> } <ide> $data += ['entity' => null]; <ide> <del> foreach ($this->_contextProviders as $provider) { <del> $check = $provider['callable']; <del> $context = $check($this->request, $data); <del> if ($context) { <del> break; <del> } <del> } <del> if (!isset($context)) { <del> $context = new NullContext($this->request, $data); <del> } <del> if (!($context instanceof ContextInterface)) { <del> throw new RuntimeException( <del> 'Context objects must implement Cake\View\Form\ContextInterface' <del> ); <del> } <del> <del> return $this->_context = $context; <add> return $this->_context = $this->contextFactory()->get($this->request, $data); <ide> } <ide> <ide> /**
2
Go
Go
improve the debug function
6576b19a28a688f00dbe21318b4073826001cf3c
<ide><path>utils.go <ide> import ( <ide> "fmt" <ide> "github.com/dotcloud/docker/rcli" <ide> "io" <del> "log" <ide> "net/http" <ide> "os" <ide> "os/exec" <ide> "path/filepath" <add> "runtime" <add> "strings" <ide> "sync" <ide> "time" <ide> ) <ide> func Download(url string, stderr io.Writer) (*http.Response, error) { <ide> // If Docker is in damon mode, also send the debug info on the socket <ide> func Debugf(format string, a ...interface{}) { <ide> if rcli.DEBUG_FLAG { <del> log.Printf(format, a...) <add> <add> // Retrieve the stack infos <add> _, file, line, ok := runtime.Caller(1) <add> if !ok { <add> file = "<unknown>" <add> line = -1 <add> } else { <add> file = file[strings.LastIndex(file, "/")+1:] <add> } <add> <add> fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...) <ide> if rcli.CLIENT_SOCKET != nil { <del> fmt.Fprintf(rcli.CLIENT_SOCKET, log.Prefix()+format, a...) <add> fmt.Fprintf(rcli.CLIENT_SOCKET, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...) <ide> } <ide> } <ide> }
1
Text
Text
fix movinet colab link
862f8ca36d60d2a3277b46730e5a9ae3f82c55f0
<ide><path>official/vision/beta/projects/movinet/README.md <ide> # Mobile Video Networks (MoViNets) <ide> <del>[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/tensorflow/models/tree/master/official/vision/beta/projects/movinet/movinet_tutorial.ipynb) <add>[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/tensorflow/models/blob/master/official/vision/beta/projects/movinet/movinet_tutorial.ipynb) <ide> [![TensorFlow Hub](https://img.shields.io/badge/TF%20Hub-Models-FF6F00?logo=tensorflow)](https://tfhub.dev/google/collections/movinet) <ide> [![Paper](http://img.shields.io/badge/Paper-arXiv.2103.11511-B3181B?logo=arXiv)](https://arxiv.org/abs/2103.11511) <ide>
1
Javascript
Javascript
add more information
ff64c6722f03cb442859bb7f1bfef8a3adf09119
<ide><path>lib/repl.js <ide> function REPLServer(prompt, <ide> sawSIGINT = false; <ide> return; <ide> } <del> self.output.write('(To exit, press ^C again or type .exit)\n'); <add> self.output.write('(To exit, press ^C again or ^D or type .exit)\n'); <ide> sawSIGINT = true; <ide> } else { <ide> sawSIGINT = false; <ide> function defineDefaultCommands(repl) { <ide> var line = `.${name}${cmd.help ? spaces + cmd.help : ''}\n`; <ide> this.outputStream.write(line); <ide> } <add> this.outputStream.write('\nPress ^C to abort current expression, ' + <add> '^D to exit the repl\n'); <ide> this.displayPrompt(); <ide> } <ide> }); <ide><path>test/parallel/test-repl-editor.js <ide> function run({ input, output, event, checkTerminalCodes = true }) { <ide> const tests = [ <ide> { <ide> input: '', <del> output: '\n(To exit, press ^C again or type .exit)', <add> output: '\n(To exit, press ^C again or ^D or type .exit)', <ide> event: { ctrl: true, name: 'c' } <ide> }, <ide> { <ide><path>test/parallel/test-repl.js <ide> const errorTests = [ <ide> /\.help/, <ide> /\.load/, <ide> /\.save/, <add> '', <add> 'Press ^C to abort current expression, ^D to exit the repl', <ide> /'thefourtheye'/ <ide> ] <ide> },
3
PHP
PHP
fix some docblocks params
e558d8b5d91276fa377b5da46ebc072f8a3ac226
<ide><path>src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php <ide> public function setPivotKeys($foreignKey, $relatedKey) <ide> /** <ide> * Determine if the pivot model or given attributes has timestamp attributes. <ide> * <del> * @param $attributes array|null <add> * @param array|null $attributes <ide> * @return bool <ide> */ <ide> public function hasTimestampAttributes($attributes = null) <ide><path>src/Illuminate/Redis/Connections/PhpRedisConnection.php <ide> public function hsetnx($hash, $key, $value) <ide> * <ide> * @param string $key <ide> * @param int $count <del> * @param $value $value <add> * @param mixed $value <ide> * @return int|false <ide> */ <ide> public function lrem($key, $count, $value) <ide><path>tests/Http/HttpJsonResponseTest.php <ide> class HttpJsonResponseTest extends TestCase <ide> /** <ide> * @dataProvider setAndRetrieveDataProvider <ide> * <del> * @param $data <add> * @param mixed $data <ide> */ <ide> public function testSetAndRetrieveData($data): void <ide> { <ide><path>tests/Queue/RedisQueueIntegrationTest.php <ide> public function testExpiredJobsArePopped($driver) <ide> /** <ide> * @dataProvider redisDriverProvider <ide> * <del> * @param $driver <add> * @param mixed $driver <ide> * <ide> * @throws \Exception <ide> */
4