content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | remove additional certification from certs | 85d3587e592850820e46ec3ad1108647c57159dc | <ide><path>client/src/client-only-routes/ShowCertification.js
<ide> class ShowCertification extends Component {
<ide> </h1>
<ide> <h3>has successfully completed the freeCodeCamp.org</h3>
<ide> <h1>
<del> <strong>{certTitle} Certification</strong>
<add> <strong>{certTitle}</strong>
<ide> </h1>
<ide> <h4>
<ide> Developer Certification, representing approximately{' '} | 1 |
Java | Java | add firstelement to collectionutils | d503bc2804b7bdbb9e9c46081a7fa454ac81c8d7 | <ide><path>spring-core/src/main/java/org/springframework/util/CollectionUtils.java
<ide> public static <T> T lastElement(@Nullable List<T> list) {
<ide> return list.get(list.size() - 1);
<ide> }
<ide>
<add> /**
<add> * Retrieve the first element of the given Set, using {@link SortedSet#first()}
<add> * or otherwise using the iterator.
<add> * @param set the Set to check (may be {@code null} or empty)
<add> * @return the first element, or {@code null} if none
<add> * @see SortedSet
<add> * @see LinkedHashMap#keySet()
<add> * @see java.util.LinkedHashSet
<add> */
<add> @Nullable
<add> public static <T> T firstElement(@Nullable Set<T> set) {
<add> if (isEmpty(set)) {
<add> return null;
<add> }
<add> if (set instanceof SortedSet) {
<add> return ((SortedSet<T>) set).first();
<add> }
<add>
<add> Iterator<T> it = set.iterator();
<add> T first = null;
<add> if (it.hasNext()) {
<add> first = it.next();
<add> }
<add> return first;
<add> }
<add>
<add> /**
<add> * Retrieve the first element of the given List, accessing the zero index.
<add> * @param list the List to check (may be {@code null} or empty)
<add> * @return the first element, or {@code null} if none
<add> */
<add> @Nullable
<add> public static <T> T firstElement(@Nullable List<T> list) {
<add> if (isEmpty(list)) {
<add> return null;
<add> }
<add> return list.get(0);
<add> }
<add>
<ide> /**
<ide> * Marshal the elements from the given enumeration into an array of the given type.
<ide> * Enumeration elements must be assignable to the type of the given array. The array | 1 |
PHP | PHP | add doc blocks | d590d78dc286c88fcf38588f3e0f1d4fbcc45989 | <ide><path>src/Illuminate/View/AppendableAttributeValue.php
<ide>
<ide> class AppendableAttributeValue
<ide> {
<add> /**
<add> * The attribute value.
<add> *
<add> * @var mixed
<add> */
<ide> public $value;
<ide>
<add> /**
<add> * Create a new appendable attribute value.
<add> *
<add> * @param mixed $value
<add> * @return void
<add> */
<ide> public function __construct($value)
<ide> {
<ide> $this->value = $value; | 1 |
Python | Python | replace deprecated functions | f653bd2340b15ce2a22669ba136b77b2751e462e | <ide><path>im2txt/im2txt/ops/image_embedding_test.py
<ide> def setUp(self):
<ide> def _countInceptionParameters(self):
<ide> """Counts the number of parameters in the inception model at top scope."""
<ide> counter = {}
<del> for v in tf.all_variables():
<add> for v in tf.global_variables():
<ide> name_tokens = v.op.name.split("/")
<ide> if name_tokens[0] == "InceptionV3":
<ide> name = "InceptionV3/" + name_tokens[1] | 1 |
PHP | PHP | fix psr2 cs | dee3130a4bf21bc56578e16bce67a0370f3e4cea | <ide><path>src/Controller/Component/SecurityComponent.php
<ide> protected function _authRequired(Controller $controller)
<ide> if ($this->session->check('_Token')) {
<ide> $tData = $this->session->read('_Token');
<ide>
<del> if (
<del> !empty($tData['allowedControllers']) &&
<add> if (!empty($tData['allowedControllers']) &&
<ide> !in_array($this->request->params['controller'], $tData['allowedControllers']) ||
<ide> !empty($tData['allowedActions']) &&
<ide> !in_array($this->request->params['action'], $tData['allowedActions'])
<ide><path>src/Database/Expression/ValuesExpression.php
<ide> public function __construct(array $columns, $typeMap)
<ide> */
<ide> public function add($data)
<ide> {
<del> if (
<del> (count($this->_values) && $data instanceof Query) ||
<add> if ((count($this->_values) && $data instanceof Query) ||
<ide> ($this->_query && is_array($data))
<ide> ) {
<ide> throw new Exception(
<ide><path>src/Database/Schema/MysqlSchema.php
<ide> public function columnSql(Table $table, $name)
<ide> }
<ide>
<ide> $hasPrecision = ['float', 'decimal'];
<del> if (
<del> in_array($data['type'], $hasPrecision, true) &&
<add> if (in_array($data['type'], $hasPrecision, true) &&
<ide> (isset($data['length']) || isset($data['precision']))
<ide> ) {
<ide> $out .= '(' . (int)$data['length'] . ',' . (int)$data['precision'] . ')';
<ide> }
<ide>
<ide> $hasUnsigned = ['float', 'decimal', 'integer', 'biginteger'];
<del> if (
<del> in_array($data['type'], $hasUnsigned, true) &&
<add> if (in_array($data['type'], $hasUnsigned, true) &&
<ide> isset($data['unsigned']) && $data['unsigned'] === true
<ide> ) {
<ide> $out .= ' UNSIGNED';
<ide> public function columnSql(Table $table, $name)
<ide> if (isset($data['null']) && $data['null'] === false) {
<ide> $out .= ' NOT NULL';
<ide> }
<del> if (
<del> in_array($data['type'], ['integer', 'biginteger']) &&
<add> if (in_array($data['type'], ['integer', 'biginteger']) &&
<ide> ([$name] == (array)$table->primaryKey() || $data['autoIncrement'] === true)
<ide> ) {
<ide> $out .= ' AUTO_INCREMENT';
<ide> public function columnSql(Table $table, $name)
<ide> if (isset($data['default']) && $data['type'] !== 'timestamp') {
<ide> $out .= ' DEFAULT ' . $this->_driver->schemaValue($data['default']);
<ide> }
<del> if (
<del> isset($data['default']) &&
<add> if (isset($data['default']) &&
<ide> $data['type'] === 'timestamp' &&
<ide> strtolower($data['default']) === 'current_timestamp'
<ide> ) {
<ide><path>src/Database/Schema/PostgresSchema.php
<ide> protected function _convertColumn($column)
<ide> if ($col === 'real' || strpos($col, 'double') !== false) {
<ide> return ['type' => 'float', 'length' => null];
<ide> }
<del> if (
<del> strpos($col, 'numeric') !== false ||
<add> if (strpos($col, 'numeric') !== false ||
<ide> strpos($col, 'money') !== false ||
<ide> strpos($col, 'decimal') !== false
<ide> ) {
<ide> public function convertIndexDescription(Table $table, $row)
<ide> // If there is only one column in the primary key and it is integery,
<ide> // make it autoincrement.
<ide> $columnDef = $table->column($columns[0]);
<del> if (
<del> count($columns) === 1 &&
<add> if (count($columns) === 1 &&
<ide> in_array($columnDef['type'], ['integer', 'biginteger']) &&
<ide> $type === Table::CONSTRAINT_PRIMARY
<ide> ) {
<ide><path>src/Database/Schema/SqliteSchema.php
<ide> public function columnSql(Table $table, $name)
<ide> $out = $this->_driver->quoteIdentifier($name);
<ide> $hasUnsigned = ['biginteger', 'integer', 'float', 'decimal'];
<ide>
<del> if (
<del> in_array($data['type'], $hasUnsigned, true) &&
<add> if (in_array($data['type'], $hasUnsigned, true) &&
<ide> isset($data['unsigned']) && $data['unsigned'] === true
<ide> ) {
<ide> $out .= ' UNSIGNED';
<ide> public function columnSql(Table $table, $name)
<ide> $out .= '(' . (int)$data['length'] . ')';
<ide> }
<ide> $hasPrecision = ['float', 'decimal'];
<del> if (
<del> in_array($data['type'], $hasPrecision, true) &&
<add> if (in_array($data['type'], $hasPrecision, true) &&
<ide> (isset($data['length']) || isset($data['precision']))
<ide> ) {
<ide> $out .= '(' . (int)$data['length'] . ',' . (int)$data['precision'] . ')';
<ide> public function columnSql(Table $table, $name)
<ide> public function constraintSql(Table $table, $name)
<ide> {
<ide> $data = $table->constraint($name);
<del> if (
<del> $data['type'] === Table::CONSTRAINT_PRIMARY &&
<add> if ($data['type'] === Table::CONSTRAINT_PRIMARY &&
<ide> count($data['columns']) === 1 &&
<ide> $table->column($data['columns'][0])['type'] === 'integer'
<ide> ) {
<ide><path>src/Database/Schema/SqlserverSchema.php
<ide> protected function _convertColumn($col, $length = null, $precision = null, $scal
<ide> if ($col === 'bit') {
<ide> return ['type' => 'boolean', 'length' => null];
<ide> }
<del> if (
<del> strpos($col, 'numeric') !== false ||
<add> if (strpos($col, 'numeric') !== false ||
<ide> strpos($col, 'money') !== false ||
<ide> strpos($col, 'decimal') !== false
<ide> ) {
<ide><path>src/Database/Type/DateTimeType.php
<ide> public function marshal($value)
<ide> $value += ['hour' => 0, 'minute' => 0, 'second' => 0];
<ide>
<ide> $format = '';
<del> if (
<del> isset($value['year'], $value['month'], $value['day']) &&
<add> if (isset($value['year'], $value['month'], $value['day']) &&
<ide> (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
<ide> ) {
<ide> $format .= sprintf('%d-%02d-%02d', $value['year'], $value['month'], $value['day']);
<ide> public function useLocaleParser($enable = true)
<ide> $this->_useLocaleParser = $enable;
<ide> return $this;
<ide> }
<del> if (
<del> static::$dateTimeClass === 'Cake\I18n\Time' ||
<add> if (static::$dateTimeClass === 'Cake\I18n\Time' ||
<ide> is_subclass_of(static::$dateTimeClass, 'Cake\I18n\Time')
<ide> ) {
<ide> $this->_useLocaleParser = $enable;
<ide><path>src/Datasource/EntityTrait.php
<ide> protected function _nestedErrors($field)
<ide> $val = isset($entity[$part]) ? $entity[$part] : false;
<ide> }
<ide>
<del> if (
<del> is_array($val) ||
<add> if (is_array($val) ||
<ide> $val instanceof Traversable ||
<ide> $val instanceof EntityInterface
<ide> ) {
<ide><path>src/Network/Email/Email.php
<ide> protected function _checkViewVars(&$item, $key)
<ide> $item = (string)$item;
<ide> }
<ide>
<del> if (
<del> is_resource($item) ||
<add> if (is_resource($item) ||
<ide> $item instanceof Closure ||
<ide> $item instanceof PDO
<ide> ) {
<ide><path>src/ORM/Behavior/TimestampBehavior.php
<ide> public function handleEvent(Event $event, Entity $entity)
<ide> sprintf('When should be one of "always", "new" or "existing". The passed value "%s" is invalid', $when)
<ide> );
<ide> }
<del> if (
<del> $when === 'always' ||
<add> if ($when === 'always' ||
<ide> ($when === 'new' && $new) ||
<ide> ($when === 'existing' && !$new)
<ide> ) {
<ide><path>src/ORM/Marshaller.php
<ide> public function merge(EntityInterface $entity, array $data, array $options = [])
<ide> $converter = Type::build($columnType);
<ide> $value = $converter->marshal($value);
<ide> $isObject = is_object($value);
<del> if (
<del> (!$isObject && $original === $value) ||
<add> if ((!$isObject && $original === $value) ||
<ide> ($isObject && $original == $value)
<ide> ) {
<ide> continue;
<ide><path>src/Routing/Route/Route.php
<ide> public function match(array $url, array $context = [])
<ide>
<ide> // Check for properties that will cause an
<ide> // absolute url. Copy the other properties over.
<del> if (
<del> isset($hostOptions['_scheme']) ||
<add> if (isset($hostOptions['_scheme']) ||
<ide> isset($hostOptions['_port']) ||
<ide> isset($hostOptions['_host'])
<ide> ) {
<ide> protected function _writeUrl($params, $pass = [], $query = [])
<ide> }
<ide>
<ide> $out = str_replace('//', '/', $out);
<del> if (
<del> isset($params['_scheme']) ||
<add> if (isset($params['_scheme']) ||
<ide> isset($params['_host']) ||
<ide> isset($params['_port'])
<ide> ) {
<ide><path>src/Routing/Router.php
<ide> public static function url($url = null, $full = false)
<ide>
<ide> if (!isset($url['_name'])) {
<ide> // Copy the current action if the controller is the current one.
<del> if (
<del> empty($url['action']) &&
<add> if (empty($url['action']) &&
<ide> (empty($url['controller']) || $params['controller'] === $url['controller'])
<ide> ) {
<ide> $url['action'] = $params['action'];
<ide><path>src/Utility/MergeVariablesTrait.php
<ide> protected function _mergeProperty($property, $parentClasses, $options)
<ide> {
<ide> $thisValue = $this->{$property};
<ide> $isAssoc = false;
<del> if (
<del> isset($options['associative']) &&
<add> if (isset($options['associative']) &&
<ide> in_array($property, (array)$options['associative'])
<ide> ) {
<ide> $isAssoc = true;
<ide><path>src/Validation/Validation.php
<ide> public static function uploadedFile($file, $options = [])
<ide> protected static function _getDateString($value)
<ide> {
<ide> $formatted = '';
<del> if (
<del> isset($value['year'], $value['month'], $value['day']) &&
<add> if (isset($value['year'], $value['month'], $value['day']) &&
<ide> (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
<ide> ) {
<ide> $formatted .= sprintf('%d-%02d-%02d ', $value['year'], $value['month'], $value['day']);
<ide><path>src/View/Form/ArrayContext.php
<ide> public function __construct(Request $request, array $context)
<ide> */
<ide> public function primaryKey()
<ide> {
<del> if (
<del> empty($this->_context['schema']['_constraints']) ||
<add> if (empty($this->_context['schema']['_constraints']) ||
<ide> !is_array($this->_context['schema']['_constraints'])
<ide> ) {
<ide> return [];
<ide><path>src/View/Helper/FormHelper.php
<ide> protected function _csrfField()
<ide> public function end($secureAttributes = [])
<ide> {
<ide> $out = '';
<del> if (
<del> $this->requestType !== 'get' &&
<add> if ($this->requestType !== 'get' &&
<ide> !empty($this->request['_Token'])
<ide> ) {
<ide> $out .= $this->secure($this->fields, $secureAttributes);
<ide> public function select($fieldName, $options = [], array $attributes = [])
<ide>
<ide> // Secure the field if there are options, or it's a multi select.
<ide> // Single selects with no options don't submit, but multiselects do.
<del> if (
<del> $attributes['secure'] &&
<add> if ($attributes['secure'] &&
<ide> empty($options) &&
<ide> empty($attributes['empty']) &&
<ide> empty($attributes['multiple'])
<ide> protected function _datetimeOptions($options)
<ide> }
<ide>
<ide> // Pass empty boolean to each type.
<del> if (
<del> !empty($options['empty']) &&
<add> if (!empty($options['empty']) &&
<ide> is_bool($options['empty']) &&
<ide> is_array($options[$type])
<ide> ) {
<ide> public function addWidget($name, $spec)
<ide> public function widget($name, array $data = [])
<ide> {
<ide> $widget = $this->_registry->get($name);
<del> if (
<del> isset($data['secure'], $data['name']) &&
<add> if (isset($data['secure'], $data['name']) &&
<ide> $data['secure'] !== self::SECURE_SKIP
<ide> ) {
<ide> foreach ($widget->secureFields($data) as $field) {
<ide><path>src/View/Helper/PaginatorHelper.php
<ide> public function generateUrl(array $options = [], $model = null, $full = false)
<ide> if (!empty($url['page']) && $url['page'] == 1) {
<ide> $url['page'] = null;
<ide> }
<del> if (
<del> isset($paging['sortDefault'], $paging['directionDefault'], $url['sort'], $url['direction']) &&
<add> if (isset($paging['sortDefault'], $paging['directionDefault'], $url['sort'], $url['direction']) &&
<ide> $url['sort'] === $paging['sortDefault'] &&
<ide> $url['direction'] === $paging['directionDefault']
<ide> ) {
<ide><path>src/View/Helper/UrlHelper.php
<ide> public function assetUrl($path, array $options = [])
<ide> if (!empty($options['pathPrefix']) && $path[0] !== '/') {
<ide> $path = $options['pathPrefix'] . $path;
<ide> }
<del> if (
<del> !empty($options['ext']) &&
<add> if (!empty($options['ext']) &&
<ide> strpos($path, '?') === false &&
<ide> substr($path, -strlen($options['ext'])) !== $options['ext']
<ide> ) {
<ide><path>src/View/Widget/RadioWidget.php
<ide> protected function _renderInput($val, $text, $data, $context)
<ide> $escape
<ide> );
<ide>
<del> if (
<del> $label === false &&
<add> if ($label === false &&
<ide> strpos($this->_templates->get('radioWrapper'), '{{input}}') === false
<ide> ) {
<ide> $label = $input;
<ide><path>src/View/Widget/SelectBoxWidget.php
<ide> protected function _renderOptions($options, $disabled, $selected, $escape)
<ide> foreach ($options as $key => $val) {
<ide> // Option groups
<ide> $arrayVal = (is_array($val) || $val instanceof Traversable);
<del> if (
<del> (!is_int($key) && $arrayVal) ||
<add> if ((!is_int($key) && $arrayVal) ||
<ide> (is_int($key) && $arrayVal && isset($val['options']))
<ide> ) {
<ide> $out[] = $this->_renderOptgroup($key, $val, $disabled, $selected, $escape);
<ide><path>tests/TestCase/Collection/Iterator/TreeIteratorTest.php
<ide> public function testPrinter()
<ide> */
<ide> public function testPrinterCustomKeyAndSpacer()
<ide> {
<del> $items = [
<add> $items = [
<ide> [
<ide> 'id' => 1,
<ide> 'name' => 'a',
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> protected function _createTables($connection)
<ide>
<ide> $schema = new SchemaCollection($connection);
<ide> $result = $schema->listTables();
<del> if (
<del> in_array('schema_articles', $result) &&
<add> if (in_array('schema_articles', $result) &&
<ide> in_array('schema_authors', $result)
<ide> ) {
<ide> return;
<ide><path>tests/TestCase/Log/Engine/ConsoleLogTest.php
<ide> public function testlogToFileStream()
<ide> */
<ide> public function testDefaultOutputAs()
<ide> {
<del> if (
<del> (DS === '\\' && !(bool)env('ANSICON')) ||
<add> if ((DS === '\\' && !(bool)env('ANSICON')) ||
<ide> (function_exists('posix_isatty') && !posix_isatty(null))
<ide> ) {
<ide> $expected = ConsoleOutput::PLAIN;
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testRadioInputInsideLabel()
<ide> ]);
<ide>
<ide> $result = $this->Form->radio('Model.field', ['option A', 'option B']);
<add> //@codingStandardsIgnoreStart
<ide> $expected = [
<ide> ['input' => [
<ide> 'type' => 'hidden',
<ide> public function testRadioInputInsideLabel()
<ide> 'option B',
<ide> '/label',
<ide> ];
<add> //@codingStandardsIgnoreEnd
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide>
<ide> public function testMultiRecordForm()
<ide> $article = new Article(['comments' => [$comment]]);
<ide> $this->Form->create([$article]);
<ide> $result = $this->Form->input('0.comments.1.comment');
<add> //@codingStandardsIgnoreStart
<ide> $expected = [
<ide> 'div' => ['class' => 'input textarea'],
<ide> 'label' => ['for' => '0-comments-1-comment'],
<ide> public function testMultiRecordForm()
<ide> '/textarea',
<ide> '/div'
<ide> ];
<add> //@codingStandardsIgnoreEnd
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> $result = $this->Form->input('0.comments.0.comment');
<add> //@codingStandardsIgnoreStart
<ide> $expected = [
<ide> 'div' => ['class' => 'input textarea'],
<ide> 'label' => ['for' => '0-comments-0-comment'],
<ide> public function testMultiRecordForm()
<ide> '/textarea',
<ide> '/div'
<ide> ];
<add> //@codingStandardsIgnoreEnd
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> $comment->errors('comment', ['Not valid']);
<ide> $result = $this->Form->input('0.comments.0.comment');
<add> //@codingStandardsIgnoreStart
<ide> $expected = [
<ide> 'div' => ['class' => 'input textarea error'],
<ide> 'label' => ['for' => '0-comments-0-comment'],
<ide> public function testMultiRecordForm()
<ide> '/div',
<ide> '/div'
<ide> ];
<add> //@codingStandardsIgnoreEnd
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> TableRegistry::get('Comments')
<ide> ->validator('default')
<ide> ->allowEmpty('comment', false);
<ide> $result = $this->Form->input('0.comments.1.comment');
<add> //@codingStandardsIgnoreStart
<ide> $expected = [
<ide> 'div' => ['class' => 'input textarea required'],
<ide> 'label' => ['for' => '0-comments-1-comment'],
<ide> public function testMultiRecordForm()
<ide> '/textarea',
<ide> '/div'
<ide> ];
<add> //@codingStandardsIgnoreEnd
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide>
<ide><path>tests/TestCase/View/Helper/RssHelperTest.php
<ide> public function testChannelElements()
<ide> ];
<ide> $content = 'content-here';
<ide> $result = $this->Rss->channel($attrib, $elements, $content);
<add> //@codingStandardsIgnoreStart
<ide> $expected = [
<ide> '<channel',
<ide> '<title', 'Title of RSS Feed', '/title',
<ide> public function testChannelElements()
<ide> 'content-here',
<ide> '/channel',
<ide> ];
<add> //@codingStandardsIgnoreEnd
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide>
<ide> public function testChannelElementAttributes()
<ide> ];
<ide> $content = 'content-here';
<ide> $result = $this->Rss->channel($attrib, $elements, $content);
<add> //@codingStandardsIgnoreStart
<ide> $expected = [
<ide> '<channel',
<ide> '<title', 'Title of RSS Feed', '/title',
<ide> public function testChannelElementAttributes()
<ide> 'content-here',
<ide> '/channel',
<ide> ];
<add> //@codingStandardsIgnoreEnd
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide> | 26 |
Python | Python | attempt workaround 2 for pylint bug on travis ci | d2486ec8437c7bdf209bc1cf6990c565065f7e6a | <ide><path>libcloud/common/dimensiondata.py
<ide> from base64 import b64encode
<ide> from time import sleep
<ide>
<del>from distutils.version import LooseVersion # pylint: disable=import-error
<add>from distutils.version import LooseVersion # pylint: disable-msg=E0611
<ide> from libcloud.utils.py3 import httplib
<ide> from libcloud.utils.py3 import b
<ide> from libcloud.common.base import ConnectionUserAndKey, XmlResponse, RawResponse | 1 |
Python | Python | allow extraction of chord results on error | 97fd3acac6515a9b783c73d9ab5575644a79449c | <ide><path>celery/backends/base.py
<ide> def _store_result(self, task_id, result, state,
<ide> 'children': self.current_task_children(request),
<ide> 'task_id': bytes_to_str(task_id),
<ide> }
<add> if request and getattr(request, 'group', None):
<add> meta['group_id'] = request.group
<ide> self.set(self.get_key_for_task(task_id), self.encode(meta))
<ide> return result
<ide>
<ide><path>celery/backends/redis.py
<ide> def on_chord_part_return(self, request, state, result,
<ide> if readycount == total:
<ide> decode, unpack = self.decode, self._unpack_chord_result
<ide> with client.pipeline() as pipe:
<del> resl, _, _ = pipe \
<add> resl, = pipe \
<ide> .lrange(jkey, 0, total) \
<del> .delete(jkey) \
<del> .delete(tkey) \
<ide> .execute()
<ide> try:
<ide> callback.delay([unpack(tup, decode) for tup in resl])
<add> with client.pipeline() as pipe:
<add> _, _ = pipe \
<add> .delete(jkey) \
<add> .delete(tkey) \
<add> .execute()
<ide> except Exception as exc: # pylint: disable=broad-except
<ide> logger.exception(
<ide> 'Chord callback for %r raised: %r', request.group, exc)
<ide><path>celery/worker/request.py
<ide> def errbacks(self):
<ide> def group(self):
<ide> # used by backend.on_chord_part_return when failures reported
<ide> # by parent process
<del> return self.request_dict['group']
<add> return self.request_dict.get('group')
<ide>
<ide>
<ide> def create_request_cls(base, task, pool, hostname, eventer,
<ide><path>t/integration/tasks.py
<ide> def build_chain_inside_task(self):
<ide> )
<ide> result = test_chain()
<ide> return result
<add>
<add>
<add>class ExpectedException(Exception):
<add> pass
<add>
<add>
<add>@shared_task
<add>def fail(*args):
<add> raise ExpectedException('Task expected to fail')
<add>
<add>
<add>@shared_task
<add>def chord_error(*args):
<add> return args
<ide><path>t/integration/test_canvas.py
<ide>
<ide> from .conftest import flaky, get_active_redis_channels, get_redis_connection
<ide> from .tasks import (add, add_chord_to_chord, add_replaced, add_to_all,
<del> add_to_all_to_chord, build_chain_inside_task, collect_ids,
<del> delayed_sum, delayed_sum_with_soft_guard, identity, ids,
<del> print_unicode, redis_echo, second_order_replace1, tsum)
<add> add_to_all_to_chord, build_chain_inside_task, chord_error,
<add> collect_ids, delayed_sum, delayed_sum_with_soft_guard,
<add> fail, identity, ids, print_unicode, redis_echo,
<add> second_order_replace1, tsum)
<ide>
<ide> TIMEOUT = 120
<ide>
<ide> def assert_parentids_chord(self, res, expected_root_id):
<ide> assert value == 1
<ide> assert root_id == expected_root_id
<ide> assert parent_id is None
<add>
<add> def test_chord_on_error(self, manager):
<add> from celery import states
<add> from .tasks import ExpectedException
<add> import time
<add>
<add> if not manager.app.conf.result_backend.startswith('redis'):
<add> raise pytest.skip('Requires redis result backend.')
<add>
<add> # Run the chord and wait for the error callback to finish.
<add> c1 = chord(
<add> header=[add.s(1, 2), add.s(3, 4), fail.s()],
<add> body=print_unicode.s('This should not be called').on_error(
<add> chord_error.s()),
<add> )
<add> res = c1()
<add> try:
<add> res.wait(propagate=False)
<add> except ExpectedException:
<add> pass
<add> # Got to wait for children to populate.
<add> while not res.children:
<add> time.sleep(0.1)
<add> try:
<add> res.children[0].children[0].wait(propagate=False)
<add> except ExpectedException:
<add> pass
<add>
<add> # Extract the results of the successful tasks from the chord.
<add> #
<add> # We could do this inside the error handler, and probably would in a
<add> # real system, but for the purposes of the test it's obnoxious to get
<add> # data out of the error handler.
<add> #
<add> # So for clarity of our test, we instead do it here.
<add>
<add> # Use the error callback's result to find the failed task.
<add> error_callback_result = AsyncResult(
<add> res.children[0].children[0].result[0])
<add> failed_task_id = error_callback_result.result.args[0].split()[3]
<add>
<add> # Use new group_id result metadata to get group ID.
<add> failed_task_result = AsyncResult(failed_task_id)
<add> original_group_id = failed_task_result._get_task_meta()['group_id']
<add>
<add> # Use group ID to get preserved group result.
<add> backend = fail.app.backend
<add> j_key = backend.get_key_for_group(original_group_id, '.j')
<add> redis_connection = get_redis_connection()
<add> chord_results = [backend.decode(t) for t in
<add> redis_connection.lrange(j_key, 0, 3)]
<add>
<add> # Validate group result
<add> assert [cr[3] for cr in chord_results if cr[2] == states.SUCCESS] == \
<add> [3, 7]
<add>
<add> assert len([cr for cr in chord_results if cr[2] != states.SUCCESS]
<add> ) == 1
<ide><path>t/unit/backends/test_base.py
<ide> def test_get_store_delete_result(self):
<ide> self.b.forget(tid)
<ide> assert self.b.get_state(tid) == states.PENDING
<ide>
<add> def test_store_result_group_id(self):
<add> tid = uuid()
<add> state = 'SUCCESS'
<add> result = 10
<add> request = Mock()
<add> request.group = 'gid'
<add> request.children = []
<add> self.b.store_result(
<add> tid, state=state, result=result, request=request,
<add> )
<add> stored_meta = self.b.decode(self.b.get(self.b.get_key_for_task(tid)))
<add> assert stored_meta['group_id'] == request.group
<add>
<ide> def test_strip_prefix(self):
<ide> x = self.b.get_key_for_task('x1b34')
<ide> assert self.b._strip_prefix(x) == 'x1b34' | 6 |
Javascript | Javascript | reduce duplication of code | 31d6d9d0f7cc8e39bc183d66961ec09033a621c2 | <ide><path>lib/internal/quic/core.js
<ide> const {
<ide> IDX_QUIC_SESSION_STATS_STREAMS_OUT_COUNT,
<ide> IDX_QUIC_SESSION_STATS_KEYUPDATE_COUNT,
<ide> IDX_QUIC_SESSION_STATS_LOSS_RETRANSMIT_COUNT,
<add> IDX_QUIC_SESSION_STATS_HANDSHAKE_COMPLETED_AT,
<ide> IDX_QUIC_SESSION_STATS_ACK_DELAY_RETRANSMIT_COUNT,
<ide> IDX_QUIC_SESSION_STATS_MAX_BYTES_IN_FLIGHT,
<ide> IDX_QUIC_SESSION_STATS_BLOCK_COUNT,
<ide> function onRemoveListener(event) {
<ide> toggleListeners(this[kHandle], event, false);
<ide> }
<ide>
<add>function getStats(obj, idx) {
<add> const stats = obj[kHandle]?.stats || obj[kInternalState].stats;
<add> // If stats is undefined at this point, it's just a bug
<add> assert(stats);
<add> return stats[idx];
<add>}
<add>
<ide> // QuicEndpoint wraps a UDP socket and is owned
<ide> // by a QuicSocket. It does not exist independently
<ide> // of the QuicSocket.
<ide> class QuicSocket extends EventEmitter {
<ide> this[kHandle].setServerBusy(on);
<ide> }
<ide>
<add> get serverBusy() {
<add> return this[kInternalState].serverBusy;
<add> }
<add>
<ide> get duration() {
<ide> // TODO(@jasnell): If the object is destroyed, it should
<ide> // use a fixed duration rather than calculating from now
<del> const now = process.hrtime.bigint();
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return now - stats[IDX_QUIC_SOCKET_STATS_CREATED_AT];
<add> return process.hrtime.bigint() -
<add> getStats(this, IDX_QUIC_SOCKET_STATS_CREATED_AT);
<ide> }
<ide>
<ide> get boundDuration() {
<ide> // TODO(@jasnell): If the object is destroyed, it should
<ide> // use a fixed duration rather than calculating from now
<del> const now = process.hrtime.bigint();
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return now - stats[IDX_QUIC_SOCKET_STATS_BOUND_AT];
<add> return process.hrtime.bigint() -
<add> getStats(this, IDX_QUIC_SOCKET_STATS_BOUND_AT);
<ide> }
<ide>
<ide> get listenDuration() {
<ide> // TODO(@jasnell): If the object is destroyed, it should
<ide> // use a fixed duration rather than calculating from now
<del> const now = process.hrtime.bigint();
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return now - stats[IDX_QUIC_SOCKET_STATS_LISTEN_AT];
<add> return process.hrtime.bigint() -
<add> getStats(this, IDX_QUIC_SOCKET_STATS_LISTEN_AT);
<ide> }
<ide>
<ide> get bytesReceived() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SOCKET_STATS_BYTES_RECEIVED];
<add> return getStats(this, IDX_QUIC_SOCKET_STATS_BYTES_RECEIVED);
<ide> }
<ide>
<ide> get bytesSent() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SOCKET_STATS_BYTES_SENT];
<add> return getStats(this, IDX_QUIC_SOCKET_STATS_BYTES_SENT);
<ide> }
<ide>
<ide> get packetsReceived() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SOCKET_STATS_PACKETS_RECEIVED];
<add> return getStats(this, IDX_QUIC_SOCKET_STATS_PACKETS_RECEIVED);
<ide> }
<ide>
<ide> get packetsSent() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SOCKET_STATS_PACKETS_SENT];
<add> return getStats(this, IDX_QUIC_SOCKET_STATS_PACKETS_SENT);
<ide> }
<ide>
<ide> get packetsIgnored() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SOCKET_STATS_PACKETS_IGNORED];
<del> }
<del>
<del> get serverBusy() {
<del> return this[kInternalState].serverBusy;
<add> return getStats(this, IDX_QUIC_SOCKET_STATS_PACKETS_IGNORED);
<ide> }
<ide>
<ide> get serverSessions() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SOCKET_STATS_SERVER_SESSIONS];
<add> return getStats(this, IDX_QUIC_SOCKET_STATS_SERVER_SESSIONS);
<ide> }
<ide>
<ide> get clientSessions() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SOCKET_STATS_CLIENT_SESSIONS];
<add> return getStats(this, IDX_QUIC_SOCKET_STATS_CLIENT_SESSIONS);
<ide> }
<ide>
<ide> get statelessResetCount() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SOCKET_STATS_STATELESS_RESET_COUNT];
<add> return getStats(this, IDX_QUIC_SOCKET_STATS_STATELESS_RESET_COUNT);
<ide> }
<ide>
<ide> get serverBusyCount() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SOCKET_STATS_SERVER_BUSY_COUNT];
<add> return getStats(this, IDX_QUIC_SOCKET_STATS_SERVER_BUSY_COUNT);
<ide> }
<ide>
<ide> // Diagnostic packet loss is a testing mechanism that allows simulating
<ide> class QuicSession extends EventEmitter {
<ide> }
<ide>
<ide> get duration() {
<del> const now = process.hrtime.bigint();
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return now - stats[IDX_QUIC_SESSION_STATS_CREATED_AT];
<add> return process.hrtime.bigint() -
<add> getStats(this, IDX_QUIC_SESSION_STATS_CREATED_AT);
<ide> }
<ide>
<ide> get handshakeDuration() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<ide> const end =
<ide> this.handshakeComplete ?
<del> stats[4] : process.hrtime.bigint();
<del> return end - stats[IDX_QUIC_SESSION_STATS_HANDSHAKE_START_AT];
<add> getStats(this, IDX_QUIC_SESSION_STATS_HANDSHAKE_COMPLETED_AT) :
<add> process.hrtime.bigint();
<add> return end - getStats(this, IDX_QUIC_SESSION_STATS_HANDSHAKE_START_AT);
<ide> }
<ide>
<ide> get bytesReceived() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_BYTES_RECEIVED];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_BYTES_RECEIVED);
<ide> }
<ide>
<ide> get bytesSent() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_BYTES_SENT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_BYTES_SENT);
<ide> }
<ide>
<ide> get bidiStreamCount() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_BIDI_STREAM_COUNT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_BIDI_STREAM_COUNT);
<ide> }
<ide>
<ide> get uniStreamCount() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_UNI_STREAM_COUNT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_UNI_STREAM_COUNT);
<ide> }
<ide>
<ide> get maxInFlightBytes() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_MAX_BYTES_IN_FLIGHT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_MAX_BYTES_IN_FLIGHT);
<ide> }
<ide>
<ide> get lossRetransmitCount() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_LOSS_RETRANSMIT_COUNT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_LOSS_RETRANSMIT_COUNT);
<ide> }
<ide>
<ide> get ackDelayRetransmitCount() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_ACK_DELAY_RETRANSMIT_COUNT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_ACK_DELAY_RETRANSMIT_COUNT);
<ide> }
<ide>
<ide> get peerInitiatedStreamCount() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_STREAMS_IN_COUNT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_STREAMS_IN_COUNT);
<ide> }
<ide>
<ide> get selfInitiatedStreamCount() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_STREAMS_OUT_COUNT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_STREAMS_OUT_COUNT);
<ide> }
<ide>
<ide> get keyUpdateCount() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_KEYUPDATE_COUNT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_KEYUPDATE_COUNT);
<ide> }
<ide>
<ide> get minRTT() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_MIN_RTT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_MIN_RTT);
<ide> }
<ide>
<ide> get latestRTT() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_LATEST_RTT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_LATEST_RTT);
<ide> }
<ide>
<ide> get smoothedRTT() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_SESSION_STATS_SMOOTHED_RTT];
<add> return getStats(this, IDX_QUIC_SESSION_STATS_SMOOTHED_RTT);
<ide> }
<ide>
<ide> updateKey() {
<ide> class QuicStream extends Duplex {
<ide> }
<ide>
<ide> get duration() {
<del> const now = process.hrtime.bigint();
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return now - stats[IDX_QUIC_STREAM_STATS_CREATED_AT];
<add> return process.hrtime.bigint() -
<add> getStats(this, IDX_QUIC_STREAM_STATS_CREATED_AT);
<ide> }
<ide>
<ide> get bytesReceived() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_STREAM_STATS_BYTES_RECEIVED];
<add> return getStats(this, IDX_QUIC_STREAM_STATS_BYTES_RECEIVED);
<ide> }
<ide>
<ide> get bytesSent() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_STREAM_STATS_BYTES_SENT];
<add> return getStats(this, IDX_QUIC_STREAM_STATS_BYTES_SENT);
<ide> }
<ide>
<ide> get maxExtendedOffset() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_STREAM_STATS_MAX_OFFSET];
<add> return getStats(this, IDX_QUIC_STREAM_STATS_MAX_OFFSET);
<ide> }
<ide>
<ide> get finalSize() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_STREAM_STATS_FINAL_SIZE];
<add> return getStats(this, IDX_QUIC_STREAM_STATS_FINAL_SIZE);
<ide> }
<ide>
<ide> get maxAcknowledgedOffset() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_STREAM_STATS_MAX_OFFSET_ACK];
<add> return getStats(this, IDX_QUIC_STREAM_STATS_MAX_OFFSET_ACK);
<ide> }
<ide>
<ide> get maxReceivedOffset() {
<del> const stats = this[kInternalState].stats || this[kHandle].stats;
<del> return stats[IDX_QUIC_STREAM_STATS_MAX_OFFSET_RECV];
<add> return getStats(this, IDX_QUIC_STREAM_STATS_MAX_OFFSET_RECV);
<ide> }
<ide> }
<ide> | 1 |
Go | Go | fix microsecond -> milisecond | 5d818213ff3b9f8cda8e4fb3b071bef8fab782ad | <ide><path>internal/test/daemon/daemon.go
<ide> func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
<ide>
<ide> select {
<ide> case <-ctx.Done():
<del> case <-time.After(500 * time.Microsecond):
<add> case <-time.After(500 * time.Millisecond):
<ide> }
<ide> continue
<ide> } | 1 |
Javascript | Javascript | update imports in container package tests | cde76c52bdb8094ce072eacc0cd82176d1c72bde | <ide><path>packages/container/tests/container_test.js
<ide> import { ENV } from 'ember-environment';
<del>import { get } from 'ember-metal/property_get';
<add>import { get } from 'ember-metal';
<ide> import {
<ide> Registry,
<ide> getOwner,
<ide> OWNER
<del>} from 'container';
<del>import factory from 'container/tests/test-helpers/factory';
<add>} from '../index';
<add>import factory from './test-helpers/factory';
<ide>
<ide> let originalModelInjections;
<ide>
<ide><path>packages/container/tests/owner_test.js
<del>import { getOwner, setOwner, OWNER } from 'container';
<add>import { getOwner, setOwner, OWNER } from '../index';
<ide>
<ide> QUnit.module('Owner', {});
<ide>
<ide><path>packages/container/tests/registry_test.js
<del>import { Registry } from 'container';
<del>import factory from 'container/tests/test-helpers/factory';
<add>import { Registry } from '../index';
<add>import factory from './test-helpers/factory';
<ide>
<ide> QUnit.module('Registry');
<ide>
<ide><path>packages/container/tests/test-helpers/build-owner.js
<del>import EmberObject from 'ember-runtime/system/object';
<del>import { Registry } from 'container';
<del>import RegistryProxy from 'ember-runtime/mixins/registry_proxy';
<del>import ContainerProxy from 'ember-runtime/mixins/container_proxy';
<add>import {
<add> Object as EmberObject,
<add> RegistryProxy,
<add> ContainerProxy
<add>} from 'ember-runtime';
<add>import { Registry } from '../../index';
<ide>
<ide> export default function buildOwner(props) {
<ide> let Owner = EmberObject.extend(RegistryProxy, ContainerProxy, { | 4 |
Javascript | Javascript | remove erroneous dropmembership() call | 9037decb28e324b78a310d2557dc12c177cbaee1 | <ide><path>test/simple/test-dgram-broadcast-multi-process.js
<ide> if (!cluster.isMaster) {
<ide> process.send({ message : buf.toString() });
<ide>
<ide> if (receivedMessages.length == messages.length) {
<del> listenSocket.dropMembership(LOCAL_BROADCAST_HOST);
<del> process.nextTick(function() { // TODO should be changed to below.
<del> // listenSocket.dropMembership(LOCAL_BROADCAST_HOST, function() {
<add> process.nextTick(function() {
<ide> listenSocket.close();
<ide> });
<ide> } | 1 |
Ruby | Ruby | add generic codesign_patched_binary method | 3b089ee90195c9ce024b4b820c85d9368af34b86 | <ide><path>Library/Homebrew/keg.rb
<ide> def binary_executable_or_library_files
<ide> elf_files
<ide> end
<ide>
<add> def codesign_patched_binary(file); end
<add>
<ide> private
<ide>
<ide> def resolve_any_conflicts(dst, dry_run: false, verbose: false, overwrite: false) | 1 |
PHP | PHP | add missing docblock | b3e091e290c1e09a50ee62bf586770e82d2ba89d | <ide><path>src/Datasource/QueryTrait.php
<ide> trait QueryTrait
<ide> * @var bool
<ide> */
<ide> protected $_eagerLoaded = false;
<add>
<ide> /**
<ide> * Returns the default table object that will be used by this query,
<ide> * that is, the table that will appear in the from clause.
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> protected function _getMockPosts(array $methods = [])
<ide> */
<ide> protected function _getMockFindQuery(?RepositoryInterface $table = null)
<ide> {
<add> /** @var \Cake\ORM\Query|\PHPUnit_Framework_MockObject_MockObject $query */
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<ide> ->setMethods(['total', 'all', 'count', 'applyOptions'])
<ide> ->disableOriginalConstructor() | 2 |
Python | Python | fix regression on np.dtype(ctypes.c_void_p) | af95739054cb3707447834861820c4231b1bc5e1 | <ide><path>numpy/core/_dtype_ctypes.py
<ide> def _from_ctypes_scalar(t):
<ide> """
<ide> Return the dtype type with endianness included if it's the case
<ide> """
<del> if t.__ctype_be__ is t:
<add> if getattr(t, '__ctype_be__', None) is t:
<ide> return np.dtype('>' + t._type_)
<del> elif t.__ctype_le__ is t:
<add> elif getattr(t, '__ctype_le__', None) is t:
<ide> return np.dtype('<' + t._type_)
<ide> else:
<ide> return np.dtype(t._type_)
<ide> def dtype_from_ctypes_type(t):
<ide> return _from_ctypes_structure(t)
<ide> elif issubclass(t, _ctypes.Union):
<ide> return _from_ctypes_union(t)
<del> elif isinstance(t._type_, str):
<add> elif isinstance(getattr(t, '_type_', None), str):
<ide> return _from_ctypes_scalar(t)
<ide> else:
<ide> raise NotImplementedError(
<ide><path>numpy/core/tests/test_dtype.py
<ide> def test_pointer(self):
<ide> p_uint8 = ctypes.POINTER(ctypes.c_uint8)
<ide> assert_raises(TypeError, np.dtype, p_uint8)
<ide>
<add> def test_void_pointer(self):
<add> self.check(ctypes.c_void_p, np.uintp)
<add>
<ide> def test_union(self):
<ide> class Union(ctypes.Union):
<ide> _fields_ = [ | 2 |
Text | Text | add redux-little-router to ecosysme | de94043033fdd13dc4fa3cede2943143c6d28942 | <ide><path>docs/introduction/Ecosystem.md
<ide> On this page we will only feature a few of them that the Redux maintainers have
<ide>
<ide> * [react-router-redux](https://github.com/reactjs/react-router-redux) — Ruthlessly simple bindings to keep React Router and Redux in sync
<ide> * [redial](https://github.com/markdalgleish/redial) — Universal data fetching and route lifecycle management for React that works great with Redux
<add>* [redux-little-router](https://github.com/FormidableLabs/redux-little-router) — A tiny router for Redux that lets the URL do the talking
<ide>
<ide> ### Components
<ide> | 1 |
PHP | PHP | add observer mapping | ca53127994dda58a2dc4a4fe70f1528a1631bb02 | <ide><path>src/Illuminate/Foundation/Support/Providers/EventServiceProvider.php
<ide> class EventServiceProvider extends ServiceProvider
<ide> */
<ide> protected $subscribe = [];
<ide>
<add> /**
<add> * The observers mapping for the application models.
<add> *
<add> * @var array
<add> */
<add> protected $observers = [];
<add>
<ide> /**
<ide> * Register the application's event listeners.
<ide> *
<ide> public function register()
<ide> foreach ($this->subscribe as $subscriber) {
<ide> Event::subscribe($subscriber);
<ide> }
<add>
<add> $this->registerObservers();
<ide> });
<ide> }
<ide>
<ide> protected function eventDiscoveryBasePath()
<ide> {
<ide> return base_path();
<ide> }
<add>
<add> /**
<add> * Get the observers defined on the provider.
<add> *
<add> * @return array
<add> */
<add> public function observers()
<add> {
<add> return $this->observers;
<add> }
<add>
<add> /**
<add> * Register the application model's observers.
<add> *
<add> * @return void
<add> */
<add> public function registerObservers()
<add> {
<add> foreach ($this->observers() as $model => $observers) {
<add> $model::observe($observers);
<add> }
<add> }
<ide> } | 1 |
Python | Python | remove unused code from test.py | 53c88fa4111c05c3a4ad47c00eaa0fd7220b527a | <ide><path>tools/test.py
<ide> def __init__(self, cases, flaky_tests_mode):
<ide> self.failed = [ ]
<ide> self.flaky_failed = [ ]
<ide> self.crashed = 0
<del> self.flaky_crashed = 0
<ide> self.lock = threading.Lock()
<ide> self.shutdown_event = threading.Event()
<ide>
<ide> def RunSingle(self, parallel, thread_id):
<ide> if output.UnexpectedOutput():
<ide> if FLAKY in output.test.outcomes and self.flaky_tests_mode == DONTCARE:
<ide> self.flaky_failed.append(output)
<del> if output.HasCrashed():
<del> self.flaky_crashed += 1
<ide> else:
<ide> self.failed.append(output)
<ide> if output.HasCrashed():
<ide> def UnexpectedOutput(self):
<ide> outcome = PASS
<ide> return not outcome in self.test.outcomes
<ide>
<del> def HasPreciousOutput(self):
<del> return self.UnexpectedOutput() and self.store_unexpected_output
<del>
<ide> def HasCrashed(self):
<ide> if utils.IsWindows():
<ide> return 0x80000000 & self.output.exit_code and not (0x3FFFFF00 & self.output.exit_code)
<ide> def GetName(self):
<ide> return self.name
<ide>
<ide>
<del># Use this to run several variants of the tests, e.g.:
<del># VARIANT_FLAGS = [[], ['--always_compact', '--noflush_code']]
<del>VARIANT_FLAGS = [[]]
<del>
<del>
<ide> class TestRepository(TestSuite):
<ide>
<ide> def __init__(self, path):
<ide> def GetConfiguration(self, context):
<ide> (file, pathname, description) = imp.find_module('testcfg', [ self.path ])
<ide> module = imp.load_module('testcfg', file, pathname, description)
<ide> self.config = module.GetConfiguration(context, self.path)
<del> if hasattr(self.config, 'additional_flags'):
<del> self.config.additional_flags += context.node_args
<del> else:
<del> self.config.additional_flags = context.node_args
<ide> finally:
<ide> if file:
<ide> file.close()
<ide> def GetBuildRequirements(self, path, context):
<ide> return self.GetConfiguration(context).GetBuildRequirements()
<ide>
<ide> def AddTestsToList(self, result, current_path, path, context, arch, mode):
<del> for v in VARIANT_FLAGS:
<del> tests = self.GetConfiguration(context).ListTests(current_path, path,
<del> arch, mode)
<del> for t in tests: t.variant_flags = v
<del> result += tests
<del> for i in range(1, context.repeat):
<del> result += copy.deepcopy(tests)
<add> tests = self.GetConfiguration(context).ListTests(current_path, path,
<add> arch, mode)
<add> result += tests
<add> for i in range(1, context.repeat):
<add> result += copy.deepcopy(tests)
<ide>
<ide> def GetTestStatus(self, context, sections, defs):
<ide> self.GetConfiguration(context).GetTestStatus(sections, defs)
<ide> def GetTestStatus(self, context, sections, defs):
<ide> test.GetTestStatus(context, sections, defs)
<ide>
<ide>
<del>SUFFIX = {
<del> 'debug' : '_g',
<del> 'release' : '' }
<del>FLAGS = {
<del> 'debug' : ['--enable-slow-asserts', '--debug-code', '--verify-heap'],
<del> 'release' : []}
<ide> TIMEOUT_SCALEFACTOR = {
<ide> 'armv6' : { 'debug' : 12, 'release' : 3 }, # The ARM buildbots are slow.
<ide> 'arm' : { 'debug' : 8, 'release' : 2 },
<ide> def __init__(self, workspace, buildspace, verbose, vm, args, expect_fail,
<ide> self.workspace = workspace
<ide> self.buildspace = buildspace
<ide> self.verbose = verbose
<del> self.vm_root = vm
<ide> self.node_args = args
<ide> self.expect_fail = expect_fail
<ide> self.timeout = timeout
<ide> def GetVm(self, arch, mode):
<ide>
<ide> return name
<ide>
<del> def GetVmFlags(self, testcase, mode):
<del> return testcase.variant_flags + FLAGS[mode]
<del>
<ide> def GetTimeout(self, mode):
<ide> return self.timeout * TIMEOUT_SCALEFACTOR[ARCH_GUESS or 'ia32'][mode]
<ide>
<ide> def IsEmpty(self):
<ide> return len(self.elms) == 0
<ide>
<ide>
<del>class Everything(Set):
<del>
<del> def Intersect(self, that):
<del> return that
<del>
<del> def Union(self, that):
<del> return self
<del>
<del> def IsEmpty(self):
<del> return False
<del>
<del>
<ide> class Nothing(Set):
<ide>
<ide> def Intersect(self, that): | 1 |
Javascript | Javascript | fix packager breakages on node4 | 9a4e4e8ee8dc05341878f97c3b1735c6bf2757b9 | <ide><path>packager/react-packager/react-packager.js
<ide> const Logger = require('./src/Logger');
<ide>
<ide> const debug = require('debug');
<del>const invariant = require('invariant');
<add>const invariant = require('fbjs/lib/invariant');
<ide>
<ide> import type {Reporter} from './src/lib/reporting';
<ide>
<ide><path>packager/react-packager/src/JSTransformer/worker/inline.js
<ide> 'use strict';
<ide>
<ide> const babel = require('babel-core');
<del>const invariant = require('invariant');
<add>const invariant = require('fbjs/lib/invariant');
<ide>
<ide> import type {Ast, SourceMap} from 'babel-core';
<ide> const t = babel.types;
<ide><path>packager/react-packager/src/JSTransformer/worker/worker.js
<ide> const constantFolding = require('./constant-folding');
<ide> const extractDependencies = require('./extract-dependencies');
<ide> const inline = require('./inline');
<del>const invariant = require('invariant');
<add>const invariant = require('fbjs/lib/invariant');
<ide> const minify = require('./minify');
<ide>
<ide> import type {LogEntry} from '../../Logger/Types';
<ide><path>packager/react-packager/src/lib/GlobalTransformCache.js
<ide>
<ide> const crypto = require('crypto');
<ide> const imurmurhash = require('imurmurhash');
<del>const invariant = require('invariant');
<add>const invariant = require('fbjs/lib/invariant');
<ide> const jsonStableStringify = require('json-stable-stringify');
<ide> const path = require('path');
<ide> const request = require('request');
<ide><path>packager/react-packager/src/node-haste/Module.js
<ide> const TransformCache = require('../lib/TransformCache');
<ide> const crypto = require('crypto');
<ide> const docblock = require('./DependencyGraph/docblock');
<ide> const fs = require('fs');
<del>const invariant = require('invariant');
<add>const invariant = require('fbjs/lib/invariant');
<ide> const isAbsolutePath = require('absolute-path');
<ide> const jsonStableStringify = require('json-stable-stringify');
<ide>
<ide><path>setupBabel.js
<ide> const path = require('path');
<ide> const BABEL_ENABLED_PATHS = [
<ide> 'packager/react-packager/react-packager.js',
<ide> 'packager/react-packager/src',
<add> 'packager/transformer.js',
<ide> 'local-cli',
<ide> ];
<ide> | 6 |
Java | Java | expose request id at the serverhttprequest level | bc3cf0eeb8b96a75a7a8a6351665975ed8b5081d | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpRequest.java
<ide> public abstract class AbstractServerHttpRequest implements ServerHttpRequest {
<ide> private SslInfo sslInfo;
<ide>
<ide> @Nullable
<del> private String connectionId;
<add> private String id;
<ide>
<ide> @Nullable
<ide> private String logPrefix;
<ide> public AbstractServerHttpRequest(URI uri, @Nullable String contextPath, HttpHead
<ide> }
<ide>
<ide>
<add> public String getId() {
<add> if (this.id == null) {
<add> this.id = initId();
<add> if (this.id == null) {
<add> this.id = ObjectUtils.getIdentityHexString(this);
<add> }
<add> }
<add> return this.id;
<add> }
<add>
<add> /**
<add> * Obtain the request id to use, or {@code null} in which case the Object
<add> * identity of this request instance is used.
<add> * @since 5.1
<add> */
<add> @Nullable
<add> protected String initId() {
<add> return null;
<add> }
<add>
<ide> @Override
<ide> public URI getURI() {
<ide> return this.uri;
<ide> public SslInfo getSslInfo() {
<ide> */
<ide> public abstract <T> T getNativeRequest();
<ide>
<del> /**
<del> * Return an id representing the underlying connection, if available, or
<del> * otherwise the identify of the request object.
<del> * @since 5.1
<del> */
<del> public String getConnectionId() {
<del> if (this.connectionId == null) {
<del> this.connectionId = initConnectionId();
<del> if (this.connectionId == null) {
<del> this.connectionId = ObjectUtils.getIdentityHexString(this);
<del> }
<del> }
<del> return this.connectionId;
<del> }
<del>
<del> /**
<del> * Obtain the connection id, if available.
<del> * @since 5.1
<del> */
<del> @Nullable
<del> protected String initConnectionId() {
<del> return null;
<del> }
<del>
<ide> /**
<ide> * For internal use in logging at the HTTP adapter layer.
<ide> * @since 5.1
<ide> */
<ide> String getLogPrefix() {
<ide> if (this.logPrefix == null) {
<del> this.logPrefix = "[" + getConnectionId() + "] ";
<add> this.logPrefix = "[" + getId() + "] ";
<ide> }
<ide> return this.logPrefix;
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultServerHttpRequestBuilder.java
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<del>import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> private static class MutatedServerHttpRequest extends AbstractServerHttpRequest
<ide>
<ide> private final ServerHttpRequest originalRequest;
<ide>
<del> private final String requestId;
<del>
<ide>
<ide> public MutatedServerHttpRequest(URI uri, @Nullable String contextPath,
<ide> HttpHeaders headers, String methodValue, MultiValueMap<String, HttpCookie> cookies,
<ide> public MutatedServerHttpRequest(URI uri, @Nullable String contextPath,
<ide> this.sslInfo = sslInfo != null ? sslInfo : originalRequest.getSslInfo();
<ide> this.body = body;
<ide> this.originalRequest = originalRequest;
<del> this.requestId = originalRequest instanceof AbstractServerHttpRequest ?
<del> ((AbstractServerHttpRequest) originalRequest).getConnectionId() :
<del> ObjectUtils.getIdentityHexString(originalRequest);
<ide> }
<ide>
<ide> @Override
<ide> public <T> T getNativeRequest() {
<ide> }
<ide>
<ide> @Override
<del> public String getConnectionId() {
<del> return this.requestId;
<add> public String getId() {
<add> return this.originalRequest.getId();
<ide> }
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpRequest.java
<ide> public <T> T getNativeRequest() {
<ide>
<ide> @Override
<ide> @Nullable
<del> protected String initConnectionId() {
<add> protected String initId() {
<ide> return this.request instanceof Connection ?
<ide> ((Connection) this.request).channel().id().asShortText() : null;
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpRequest.java
<ide> */
<ide> public interface ServerHttpRequest extends HttpRequest, ReactiveHttpInputMessage {
<ide>
<add> /**
<add> * Return an id that represents the underlying connection, if available, or
<add> * the request, for the purpose of correlating log messages.
<add> * @since 5.1
<add> * @see org.springframework.web.server.ServerWebExchange#getLogPrefix()
<add> */
<add> String getId();
<add>
<ide> /**
<ide> * Returns a structured representation of the request path including the
<ide> * context path + path within application portions, path segments with
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpRequestDecorator.java
<ide> public ServerHttpRequest getDelegate() {
<ide>
<ide> // ServerHttpRequest delegation methods...
<ide>
<add> @Override
<add> public String getId() {
<add> return getDelegate().getId();
<add> }
<add>
<ide> @Override
<ide> @Nullable
<ide> public HttpMethod getMethod() {
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java
<ide> public <T> T getNativeRequest() {
<ide> }
<ide>
<ide> @Override
<del> protected String initConnectionId() {
<add> protected String initId() {
<ide> return ObjectUtils.getIdentityHexString(this.exchange.getConnection());
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/HttpWebHandlerAdapter.java
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.codec.LoggingCodecSupport;
<ide> import org.springframework.http.codec.ServerCodecConfigurer;
<del>import org.springframework.http.server.reactive.AbstractServerHttpRequest;
<ide> import org.springframework.http.server.reactive.HttpHandler;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.WebHandler;
<ide> public void afterPropertiesSet() {
<ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<ide>
<ide> ServerWebExchange exchange = createExchange(request, response);
<del> exchange.getAttributes().put(ServerWebExchange.LOG_ID_ATTRIBUTE, initLogId(request));
<add> exchange.getAttributes().put(ServerWebExchange.LOG_ID_ATTRIBUTE, request.getId());
<ide> logExchange(exchange);
<ide>
<ide> return getDelegate().handle(exchange)
<ide> protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttp
<ide> getCodecConfigurer(), getLocaleContextResolver(), this.applicationContext);
<ide> }
<ide>
<del> private String initLogId(ServerHttpRequest request) {
<del> return request instanceof AbstractServerHttpRequest ?
<del> ((AbstractServerHttpRequest) request).getConnectionId() : ObjectUtils.getIdentityHexString(request);
<del> }
<del>
<ide> private void logExchange(ServerWebExchange exchange) {
<ide> if (logger.isDebugEnabled()) {
<ide> String logPrefix = exchange.getLogPrefix();
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultServerRequestBuilder.java
<ide> public ServerRequest.Builder attributes(Consumer<Map<String, Object>> attributes
<ide>
<ide> @Override
<ide> public ServerRequest build() {
<del> ServerHttpRequest serverHttpRequest = new BuiltServerHttpRequest(
<add> ServerHttpRequest serverHttpRequest = new BuiltServerHttpRequest(this.exchange.getRequest().getId(),
<ide> this.methodName, this.uri, this.headers, this.cookies, this.body);
<ide> ServerWebExchange exchange = new DelegatingServerWebExchange(
<ide> serverHttpRequest, this.exchange, this.messageReaders);
<ide> private static class BuiltServerHttpRequest implements ServerHttpRequest {
<ide>
<ide> private static final Pattern QUERY_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
<ide>
<add> private final String id;
<add>
<ide> private final String method;
<ide>
<ide> private final URI uri;
<ide> private static class BuiltServerHttpRequest implements ServerHttpRequest {
<ide>
<ide> private final Flux<DataBuffer> body;
<ide>
<del> public BuiltServerHttpRequest(String method, URI uri, HttpHeaders headers,
<add> public BuiltServerHttpRequest(String id, String method, URI uri, HttpHeaders headers,
<ide> MultiValueMap<String, HttpCookie> cookies, Flux<DataBuffer> body) {
<ide>
<add> this.id = id;
<ide> this.method = method;
<ide> this.uri = uri;
<ide> this.path = RequestPath.parse(uri, null);
<ide> private static MultiValueMap<String, String> parseQueryParams(URI uri) {
<ide> return queryParams;
<ide> }
<ide>
<add> @Override
<add> public String getId() {
<add> return this.id;
<add> }
<add>
<ide> @Override
<ide> public String getMethodValue() {
<ide> return this.method; | 8 |
Text | Text | add model card for the ner model | 4c3be2e71809f606b42b8af4486e6277d855c012 | <ide><path>model_cards/jplu/tf-xlm-r-ner-40-lang/README.md
<add># XLM-R + NER
<add>
<add>This model is a fine-tuned [XLM-Roberta-base](https://arxiv.org/abs/1911.02116) over the 40 languages proposed in [XTREME]([https://github.com/google-research/xtreme](https://github.com/google-research/xtreme)) from [Wikiann](https://aclweb.org/anthology/P17-1178). This is still an on-going work and the results will be updated everytime an improvement is reached.
<add>
<add>The covered labels are:
<add>```
<add>LOC
<add>ORG
<add>PER
<add>O
<add>```
<add>
<add>## Metrics on evaluation set:
<add>### Average over the 40 languages
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.81 0.81 0.81 102452
<add> PER 0.90 0.91 0.91 108978
<add> LOC 0.86 0.89 0.87 121868
<add>
<add>micro avg 0.86 0.87 0.87 333298
<add>macro avg 0.86 0.87 0.87 333298
<add>```
<add>
<add>### Afrikaans
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.89 0.88 0.88 582
<add> PER 0.89 0.97 0.93 369
<add> LOC 0.84 0.90 0.86 518
<add>
<add>micro avg 0.87 0.91 0.89 1469
<add>macro avg 0.87 0.91 0.89 1469
<add>```
<add>
<add>### Arabic
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.83 0.84 0.84 3507
<add> PER 0.90 0.91 0.91 3643
<add> LOC 0.88 0.89 0.88 3604
<add>
<add>micro avg 0.87 0.88 0.88 10754
<add>macro avg 0.87 0.88 0.88 10754
<add>```
<add>
<add>### Basque
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.88 0.93 0.91 5228
<add> ORG 0.86 0.81 0.83 3654
<add> PER 0.91 0.91 0.91 4072
<add>
<add>micro avg 0.89 0.89 0.89 12954
<add>macro avg 0.89 0.89 0.89 12954
<add>```
<add>
<add>### Bengali
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.86 0.89 0.87 325
<add> LOC 0.91 0.91 0.91 406
<add> PER 0.96 0.95 0.95 364
<add>
<add>micro avg 0.91 0.92 0.91 1095
<add>macro avg 0.91 0.92 0.91 1095
<add>```
<add>
<add>### Bulgarian
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.86 0.83 0.84 3661
<add> PER 0.92 0.95 0.94 4006
<add> LOC 0.92 0.95 0.94 6449
<add>
<add>micro avg 0.91 0.92 0.91 14116
<add>macro avg 0.91 0.92 0.91 14116
<add>```
<add>
<add>### Burmese
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.60 0.86 0.71 37
<add> ORG 0.68 0.63 0.66 30
<add> PER 0.44 0.44 0.44 36
<add>
<add>micro avg 0.57 0.65 0.61 103
<add>macro avg 0.57 0.65 0.60 103
<add>```
<add>
<add>### Chinese
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.70 0.69 0.70 4022
<add> LOC 0.76 0.81 0.78 3830
<add> PER 0.84 0.84 0.84 3706
<add>
<add>micro avg 0.76 0.78 0.77 11558
<add>macro avg 0.76 0.78 0.77 11558
<add>```
<add>
<add>### Dutch
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.87 0.87 0.87 3930
<add> PER 0.95 0.95 0.95 4377
<add> LOC 0.91 0.92 0.91 4813
<add>
<add>micro avg 0.91 0.92 0.91 13120
<add>macro avg 0.91 0.92 0.91 13120
<add>```
<add>
<add>### English
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.83 0.84 0.84 4781
<add> PER 0.89 0.90 0.89 4559
<add> ORG 0.75 0.75 0.75 4633
<add>
<add>micro avg 0.82 0.83 0.83 13973
<add>macro avg 0.82 0.83 0.83 13973
<add>```
<add>
<add>### Estonian
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.89 0.92 0.91 5654
<add> ORG 0.85 0.85 0.85 3878
<add> PER 0.94 0.94 0.94 4026
<add>
<add>micro avg 0.90 0.91 0.90 13558
<add>macro avg 0.90 0.91 0.90 13558
<add>```
<add>
<add>### Finnish
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.84 0.83 0.84 4104
<add> LOC 0.88 0.90 0.89 5307
<add> PER 0.95 0.94 0.94 4519
<add>
<add>micro avg 0.89 0.89 0.89 13930
<add>macro avg 0.89 0.89 0.89 13930
<add>```
<add>
<add>### French
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.90 0.89 0.89 4808
<add> ORG 0.84 0.87 0.85 3876
<add> PER 0.94 0.93 0.94 4249
<add>
<add>micro avg 0.89 0.90 0.90 12933
<add>macro avg 0.89 0.90 0.90 12933
<add>```
<add>
<add>### Georgian
<add>```
<add> precision recall f1-score support
<add>
<add> PER 0.90 0.91 0.90 3964
<add> ORG 0.83 0.77 0.80 3757
<add> LOC 0.82 0.88 0.85 4894
<add>
<add>micro avg 0.84 0.86 0.85 12615
<add>macro avg 0.84 0.86 0.85 12615
<add>```
<add>
<add>### German
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.85 0.90 0.87 4939
<add> PER 0.94 0.91 0.92 4452
<add> ORG 0.79 0.78 0.79 4247
<add>
<add>micro avg 0.86 0.86 0.86 13638
<add>macro avg 0.86 0.86 0.86 13638
<add>```
<add>
<add>### Greek
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.86 0.85 0.85 3771
<add> LOC 0.88 0.91 0.90 4436
<add> PER 0.91 0.93 0.92 3894
<add>
<add>micro avg 0.88 0.90 0.89 12101
<add>macro avg 0.88 0.90 0.89 12101
<add>```
<add>
<add>### Hebrew
<add>```
<add> precision recall f1-score support
<add>
<add> PER 0.87 0.88 0.87 4206
<add> ORG 0.76 0.75 0.76 4190
<add> LOC 0.85 0.85 0.85 4538
<add>
<add>micro avg 0.83 0.83 0.83 12934
<add>macro avg 0.82 0.83 0.83 12934
<add>```
<add>
<add>### Hindi
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.78 0.81 0.79 362
<add> LOC 0.83 0.85 0.84 422
<add> PER 0.90 0.95 0.92 427
<add>
<add>micro avg 0.84 0.87 0.85 1211
<add>macro avg 0.84 0.87 0.85 1211
<add>```
<add>
<add>### Hungarian
<add>```
<add> precision recall f1-score support
<add>
<add> PER 0.95 0.95 0.95 4347
<add> ORG 0.87 0.88 0.87 3988
<add> LOC 0.90 0.92 0.91 5544
<add>
<add>micro avg 0.91 0.92 0.91 13879
<add>macro avg 0.91 0.92 0.91 13879
<add>```
<add>
<add>### Indonesian
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.88 0.89 0.88 3735
<add> LOC 0.93 0.95 0.94 3694
<add> PER 0.93 0.93 0.93 3947
<add>
<add>micro avg 0.91 0.92 0.92 11376
<add>macro avg 0.91 0.92 0.92 11376
<add>```
<add>
<add>### Italian
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.88 0.88 0.88 4592
<add> ORG 0.86 0.86 0.86 4088
<add> PER 0.96 0.96 0.96 4732
<add>
<add>micro avg 0.90 0.90 0.90 13412
<add>macro avg 0.90 0.90 0.90 13412
<add>```
<add>
<add>### Japanese
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.62 0.61 0.62 4184
<add> PER 0.76 0.81 0.78 3812
<add> LOC 0.68 0.74 0.71 4281
<add>
<add>micro avg 0.69 0.72 0.70 12277
<add>macro avg 0.69 0.72 0.70 12277
<add>```
<add>
<add>### Javanese
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.79 0.80 0.80 46
<add> PER 0.81 0.96 0.88 26
<add> LOC 0.75 0.75 0.75 40
<add>
<add>micro avg 0.78 0.82 0.80 112
<add>macro avg 0.78 0.82 0.80 112
<add>```
<add>
<add>### Kazakh
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.76 0.61 0.68 307
<add> LOC 0.78 0.90 0.84 461
<add> PER 0.87 0.91 0.89 367
<add>
<add>micro avg 0.81 0.83 0.82 1135
<add>macro avg 0.81 0.83 0.81 1135
<add>```
<add>
<add>### Korean
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.86 0.89 0.88 5097
<add> ORG 0.79 0.74 0.77 4218
<add> PER 0.83 0.86 0.84 4014
<add>
<add>micro avg 0.83 0.83 0.83 13329
<add>macro avg 0.83 0.83 0.83 13329
<add>```
<add>
<add>### Malay
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.87 0.89 0.88 368
<add> PER 0.92 0.91 0.91 366
<add> LOC 0.94 0.95 0.95 354
<add>
<add>micro avg 0.91 0.92 0.91 1088
<add>macro avg 0.91 0.92 0.91 1088
<add>```
<add>
<add>### Malayalam
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.75 0.74 0.75 347
<add> PER 0.84 0.89 0.86 417
<add> LOC 0.74 0.75 0.75 391
<add>
<add>micro avg 0.78 0.80 0.79 1155
<add>macro avg 0.78 0.80 0.79 1155
<add>```
<add>
<add>### Marathi
<add>```
<add> precision recall f1-score support
<add>
<add> PER 0.89 0.94 0.92 394
<add> LOC 0.82 0.84 0.83 457
<add> ORG 0.84 0.78 0.81 339
<add>
<add>micro avg 0.85 0.86 0.85 1190
<add>macro avg 0.85 0.86 0.85 1190
<add>```
<add>
<add>### Persian
<add>```
<add> precision recall f1-score support
<add>
<add> PER 0.93 0.92 0.93 3540
<add> LOC 0.93 0.93 0.93 3584
<add> ORG 0.89 0.92 0.90 3370
<add>
<add>micro avg 0.92 0.92 0.92 10494
<add>macro avg 0.92 0.92 0.92 10494
<add>```
<add>
<add>### Portuguese
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.90 0.91 0.91 4819
<add> PER 0.94 0.92 0.93 4184
<add> ORG 0.84 0.88 0.86 3670
<add>
<add>micro avg 0.89 0.91 0.90 12673
<add>macro avg 0.90 0.91 0.90 12673
<add>```
<add>
<add>### Russian
<add>```
<add> precision recall f1-score support
<add>
<add> PER 0.93 0.96 0.95 3574
<add> LOC 0.87 0.89 0.88 4619
<add> ORG 0.82 0.80 0.81 3858
<add>
<add>micro avg 0.87 0.88 0.88 12051
<add>macro avg 0.87 0.88 0.88 12051
<add>```
<add>
<add>### Spanish
<add>```
<add> precision recall f1-score support
<add>
<add> PER 0.95 0.93 0.94 3891
<add> ORG 0.86 0.88 0.87 3709
<add> LOC 0.89 0.91 0.90 4553
<add>
<add>micro avg 0.90 0.91 0.90 12153
<add>macro avg 0.90 0.91 0.90 12153
<add>```
<add>
<add>### Swahili
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.82 0.85 0.83 349
<add> PER 0.95 0.92 0.94 403
<add> LOC 0.86 0.89 0.88 450
<add>
<add>micro avg 0.88 0.89 0.88 1202
<add>macro avg 0.88 0.89 0.88 1202
<add>```
<add>
<add>### Tagalog
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.90 0.91 0.90 338
<add> ORG 0.83 0.91 0.87 339
<add> PER 0.96 0.93 0.95 350
<add>
<add>micro avg 0.90 0.92 0.91 1027
<add>macro avg 0.90 0.92 0.91 1027
<add>```
<add>
<add>### Tamil
<add>```
<add> precision recall f1-score support
<add>
<add> PER 0.90 0.92 0.91 392
<add> ORG 0.77 0.76 0.76 370
<add> LOC 0.78 0.81 0.79 421
<add>
<add>micro avg 0.82 0.83 0.82 1183
<add>macro avg 0.82 0.83 0.82 1183
<add>```
<add>
<add>### Telugu
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.67 0.55 0.61 347
<add> LOC 0.78 0.87 0.82 453
<add> PER 0.73 0.86 0.79 393
<add>
<add>micro avg 0.74 0.77 0.76 1193
<add>macro avg 0.73 0.77 0.75 1193
<add>```
<add>
<add>### Thai
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.63 0.76 0.69 3928
<add> PER 0.78 0.83 0.80 6537
<add> ORG 0.59 0.59 0.59 4257
<add>
<add>micro avg 0.68 0.74 0.71 14722
<add>macro avg 0.68 0.74 0.71 14722
<add>```
<add>
<add>### Turkish
<add>```
<add> precision recall f1-score support
<add>
<add> PER 0.94 0.94 0.94 4337
<add> ORG 0.88 0.89 0.88 4094
<add> LOC 0.90 0.92 0.91 4929
<add>
<add>micro avg 0.90 0.92 0.91 13360
<add>macro avg 0.91 0.92 0.91 13360
<add>```
<add>
<add>### Urdu
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.90 0.95 0.93 352
<add> PER 0.96 0.96 0.96 333
<add> ORG 0.91 0.90 0.90 326
<add>
<add>micro avg 0.92 0.94 0.93 1011
<add>macro avg 0.92 0.94 0.93 1011
<add>```
<add>
<add>### Vietnamese
<add>```
<add> precision recall f1-score support
<add>
<add> ORG 0.86 0.87 0.86 3579
<add> LOC 0.88 0.91 0.90 3811
<add> PER 0.92 0.93 0.93 3717
<add>
<add>micro avg 0.89 0.90 0.90 11107
<add>macro avg 0.89 0.90 0.90 11107
<add>```
<add>
<add>### Yoruba
<add>```
<add> precision recall f1-score support
<add>
<add> LOC 0.54 0.72 0.62 36
<add> ORG 0.58 0.31 0.41 35
<add> PER 0.77 1.00 0.87 36
<add>
<add>micro avg 0.64 0.68 0.66 107
<add>macro avg 0.63 0.68 0.63 107
<add>```
<add>
<add>## Reproduce the results
<add>Download and prepare the dataset from the [[https://github.com/google-research/xtreme#download-the-data](https://github.com/google-research/xtreme#download-the-data)](XTREME repo). Next, from the root of the transformers repo run:
<add>```
<add>cd examples/ner
<add>python run_tf_ner.py \
<add>--data_dir . \
<add>--labels ./labels.txt \
<add>--model_name_or_path jplu/tf-xlm-roberta-base \
<add>--output_dir model \
<add>--max-seq-length 128 \
<add>--num_train_epochs 2 \
<add>--per_gpu_train_batch_size 16 \
<add>--per_gpu_eval_batch_size 32 \
<add>--do_train \
<add>--do_eval \
<add>--logging_dir logs \
<add>--mode token-classification \
<add>--evaluate_during_training \
<add>--optimizer_name adamw
<add>```
<add>
<add>## Usage with pipelines
<add>```python
<add>from transformers import pipeline
<add>
<add>nlp_ner = pipeline(
<add> "ner",
<add> model="jplu/tf-xlm-r-ner-40-lang",
<add> tokenizer=(
<add> 'jplu/tf-xlm-r-ner-40-lang',
<add> {"use_fast": True}
<add>))
<add>
<add>text_fr = "Barack Obama est né à Hawaï."
<add>text_en = "Barack Obama was born in Hawaii."
<add>text_es = "Barack Obama nació en Hawai."
<add>text_zh = "巴拉克·奧巴馬(Barack Obama)出生於夏威夷。"
<add>text_ar = "ولد باراك أوباما في هاواي."
<add>
<add>nlp_ner(text_fr)
<add>#Output: [{'word': '▁Barack', 'score': 0.9894659519195557, 'entity': 'PER'}, {'word': '▁Obama', 'score': 0.9888848662376404, 'entity': 'PER'}, {'word': '▁Hawa', 'score': 0.998701810836792, 'entity': 'LOC'}, {'word': 'ï', 'score': 0.9987035989761353, 'entity': 'LOC'}]
<add>nlp_ner(text_en)
<add>#Output: [{'word': '▁Barack', 'score': 0.9929141998291016, 'entity': 'PER'}, {'word': '▁Obama', 'score': 0.9930834174156189, 'entity': 'PER'}, {'word': '▁Hawaii', 'score': 0.9986202120780945, 'entity': 'LOC'}]
<add>nlp_ner(test_es)
<add>#Output: [{'word': '▁Barack', 'score': 0.9944776296615601, 'entity': 'PER'}, {'word': '▁Obama', 'score': 0.9949177503585815, 'entity': 'PER'}, {'word': '▁Hawa', 'score': 0.9987911581993103, 'entity': 'LOC'}, {'word': 'i', 'score': 0.9984861612319946, 'entity': 'LOC'}]
<add>nlp_ner(test_zh)
<add>#Output: [{'word': '夏威夷', 'score': 0.9988449215888977, 'entity': 'LOC'}]
<add>nlp_ner(test_ar)
<add>#Output: [{'word': '▁با', 'score': 0.9903655648231506, 'entity': 'PER'}, {'word': 'راك', 'score': 0.9850614666938782, 'entity': 'PER'}, {'word': '▁أوباما', 'score': 0.9850308299064636, 'entity': 'PER'}, {'word': '▁ها', 'score': 0.9477543234825134, 'entity': 'LOC'}, {'word': 'وا', 'score': 0.9428229928016663, 'entity': 'LOC'}, {'word': 'ي', 'score': 0.9319471716880798, 'entity': 'LOC'}]
<add>
<add>``` | 1 |
Text | Text | add link to risc-v toolchain | 15875ade9341f29bc2e3f240db077df3a16a0914 | <ide><path>share/doc/homebrew/Custom-GCC-and-cross-compilers.md
<ide> Rather than merging in brews for either of these cases at this time, we're listi
<ide> * [MSP430 development](https://github.com/Homebrew/homebrew/issues/issue/2336)
<ide> * [OS161 development](https://github.com/maxpow4h/homebrew-os161) Your university probably uses a different version, replacing the URLs with your university's URLs will probably work.
<ide> * [ARM-EABI](https://github.com/paxswill/homebrew-paxswill) provides an arm-none-eabi toolchain formula.
<add>* [RISC-V](https://github.com/riscv/homebrew-riscv) provides the RISC-V toolchain including binutils and gcc. | 1 |
Python | Python | fix nn.dataparallel compatibility with pytorch 1.5 | 0578a913005ed1b92de87ccb2b9c3d630f168d13 | <ide><path>src/transformers/modeling_lxmert.py
<ide> def forward(
<ide> # Process the visual attention mask
<ide> if visual_attention_mask is not None:
<ide> extended_visual_attention_mask = visual_attention_mask.unsqueeze(1).unsqueeze(2)
<del> extended_visual_attention_mask = extended_visual_attention_mask.to(dtype=next(self.parameters()).dtype)
<add> extended_visual_attention_mask = extended_visual_attention_mask.to(dtype=self.dtype)
<ide> extended_visual_attention_mask = (1.0 - extended_visual_attention_mask) * -10000.0
<ide> else:
<ide> extended_visual_attention_mask = None | 1 |
Text | Text | update chinese documentation | c6d3daba54b9c67a4696eeeea919c185a5fa4e6e | <ide><path>README_zh-hans.md
<ide> checkpoint: 检查点
<ide> - 对所有模型统一的API
<ide>
<ide> 1. 更低计算开销,更少的碳排放:
<del> - 研究人员可以分享亿训练的模型而非次次从头开始训练
<add> - 研究人员可以分享已训练的模型而非每次从头开始训练
<ide> - 工程师可以减少计算用时和生产环境开销
<ide> - 数十种模型架构、两千多个预训练模型、100多种语言支持
<ide>
<ide><path>README_zh-hant.md
<ide> Tokenizer 為所有的預訓練模型提供了預處理,並可以直接轉換
<ide> - 對所有模型使用的制式化API
<ide>
<ide> 1. 更低的運算成本,更少的碳排放:
<del> - 研究人員可以分享預訓練的模型而非從頭開始訓練
<add> - 研究人員可以分享已訓練的模型而非每次從頭開始訓練
<ide> - 工程師可以減少計算時間以及生產成本
<ide> - 數十種模型架構、兩千多個預訓練模型、100多種語言支援
<ide> | 2 |
Text | Text | fix typos for redux thunk | 9c12dfce4f166dae3181510783a16d6f00689873 | <ide><path>guide/english/redux/redux-thunk/index.md
<ide> title: Redux Thunk
<ide>
<ide> Redux Thunk is middleware that allows you to return functions, rather than just actions, within Redux<sup>1</sup>. This allows for delayed actions, including working with promises.
<ide>
<del>The reason we use this middleware is for the reason that not all the actions we perform will be synchronus and some are bound to be non synchronous, like using axios to send a get request. This will take a bit of time and simple redux does not take into to account this behavious. So, Redux-thunk comes to the rescue by allowing us to dispatch actions asynchronously, so that we can allow these promises to get resolved.
<add>The reason we use this middleware is for the reason that not all the actions we perform will be synchronus and some are bound to be non synchronous, like using axios to send a GET request. This will take a bit of time and simple redux does not take into to account this behaviour. So, Redux Thunk comes to the rescue by allowing us to dispatch actions asynchronously, so that we can allow these promises to get resolved.
<ide>
<ide>
<ide> Example 1: | 1 |
Javascript | Javascript | add onerror function to chunkedstreammanager | b6ff4aea2b8fa12395852adf21545d9ea5d16210 | <ide><path>src/core/chunked_stream.js
<ide> var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {
<ide> });
<ide> },
<ide>
<add> onError: function ChunkedStreamManager_onError(err) {
<add> this._loadedStreamCapability.reject(err);
<add> },
<add>
<ide> getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {
<ide> var chunk = Math.floor(begin / this.chunkSize);
<ide> return chunk; | 1 |
Javascript | Javascript | fix wrong order of the 'div' command | a705db84b02532e2504ade095297bd152041c6b7 | <ide><path>fonts.js
<ide> CFF.prototype = {
<ide> case "div":
<ide> var num2 = aCharstring[i - 1];
<ide> var num1 = aCharstring[i - 2];
<del> aCharstring.splice(i - 2, 3, num2 / num1);
<add> aCharstring.splice(i - 2, 3, num1 / num2);
<ide> i -= 2;
<ide> break;
<ide>
<ide> CFF.prototype = {
<ide> }
<ide>
<ide> var charstringsIndex = this.createCFFIndexHeader([[0x40, 0x0E]].concat(glyphs), true);
<del> charstringsIndex = charstringsIndex.join(" ").split(" "); // XXX why?
<ide>
<ide> //Top Dict Index
<ide> var topDictIndex = [
<ide> CFF.prototype = {
<ide> var privateOffset = charstringsOffset + charstringsIndex.length;
<ide> topDictIndex = topDictIndex.concat(this.encodeNumber(privateOffset));
<ide> topDictIndex.push(18); // Private
<del> topDictIndex = topDictIndex.join(" ").split(" ");
<ide>
<ide> var indexes = [
<ide> topDictIndex, stringsIndex,
<ide> CFF.prototype = {
<ide> 139, 12, 14,
<ide> 28, 0, 55, 19
<ide> ]);
<del> privateData = privateData.join(" ").split(" ");
<ide> cff.set(privateData, currentOffset);
<ide> currentOffset += privateData.length;
<ide> | 1 |
PHP | PHP | add marker interface for authentication middleware | a7523c5bcfaa0c48dbca0d16e8134de7d89c61c3 | <ide><path>src/Illuminate/Auth/Middleware/Authenticate.php
<ide> use Closure;
<ide> use Illuminate\Auth\AuthenticationException;
<ide> use Illuminate\Contracts\Auth\Factory as Auth;
<add>use Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests;
<ide>
<del>class Authenticate
<add>class Authenticate implements AuthenticatesRequests
<ide> {
<ide> /**
<ide> * The authentication factory instance.
<ide><path>src/Illuminate/Contracts/Auth/Middleware/AuthenticatesRequests.php
<add><?php
<add>
<add>namespace Illuminate\Contracts\Auth\Middleware;
<add>
<add>interface AuthenticatesRequests
<add>{
<add> //
<add>}
<ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> class Kernel implements KernelContract
<ide> protected $middlewarePriority = [
<ide> \Illuminate\Session\Middleware\StartSession::class,
<ide> \Illuminate\View\Middleware\ShareErrorsFromSession::class,
<del> \Illuminate\Auth\Middleware\Authenticate::class,
<add> \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
<add> \Illuminate\Routing\Middleware\ThrottleRequests::class,
<ide> \Illuminate\Session\Middleware\AuthenticateSession::class,
<ide> \Illuminate\Routing\Middleware\SubstituteBindings::class,
<ide> \Illuminate\Auth\Middleware\Authorize::class, | 3 |
PHP | PHP | fix example test | b64d1e3dc89f940ef36f8b14490620b9bd54c870 | <ide><path>tests/Feature/ExampleTest.php
<ide> class ExampleTest extends TestCase
<ide> */
<ide> public function testBasicTest()
<ide> {
<del> $this->visit('/')
<del> ->see('Laravel');
<add> $response = $this->get('/');
<add>
<add> $response->assertHasStatus(200);
<ide> }
<ide> } | 1 |
Python | Python | add test for array2string unexpected kwarg | 616017dc89d3d42f748d8fe1eb819b0f728862f7 | <ide><path>numpy/core/tests/test_arrayprint.py
<ide> import numpy as np
<ide> from numpy.testing import (
<ide> assert_, assert_equal, assert_raises, assert_warns, HAS_REFCOUNT,
<add> assert_raises_regex,
<ide> )
<ide> import textwrap
<ide>
<ide> def test_basic(self):
<ide> assert_(np.array2string(a, max_line_width=4, legacy='1.13') == '[0 1\n 2]')
<ide> assert_(np.array2string(a, max_line_width=4) == '[0\n 1\n 2]')
<ide>
<add> def test_unexpected_kwarg(self):
<add> # ensure than an appropriate TypeError
<add> # is raised when array2string receives
<add> # an unexpected kwarg
<add>
<add> with assert_raises_regex(TypeError, 'nonsense'):
<add> np.array2string(np.array([1, 2, 3]),
<add> nonsense=None)
<add>
<ide> def test_format_function(self):
<ide> """Test custom format function for each element in array."""
<ide> def _format_function(x): | 1 |
Javascript | Javascript | prevent assignment on constructor properties | 5a674f3bb9d1118d11b333e3b966c01a571c09e6 | <ide><path>src/ng/parse.js
<ide> ASTCompiler.prototype = {
<ide> intoId = intoId || this.nextId();
<ide> self.recurse(ast.object, left, undefined, function() {
<ide> self.if_(self.notNull(left), function() {
<add> if (create && create !== 1) {
<add> self.addEnsureSafeAssignContext(left);
<add> }
<ide> if (ast.computed) {
<ide> right = self.nextId();
<ide> self.recurse(ast.property, right);
<ide> ASTInterpreter.prototype = {
<ide> rhs = right(scope, locals, assign, inputs);
<ide> rhs = getStringValue(rhs);
<ide> ensureSafeMemberName(rhs, expression);
<del> if (create && create !== 1 && lhs && !(lhs[rhs])) {
<del> lhs[rhs] = {};
<add> if (create && create !== 1) {
<add> ensureSafeAssignContext(lhs);
<add> if (lhs && !(lhs[rhs])) {
<add> lhs[rhs] = {};
<add> }
<ide> }
<ide> value = lhs[rhs];
<ide> ensureSafeObject(value, expression);
<ide> ASTInterpreter.prototype = {
<ide> nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
<ide> return function(scope, locals, assign, inputs) {
<ide> var lhs = left(scope, locals, assign, inputs);
<del> if (create && create !== 1 && lhs && !(lhs[right])) {
<del> lhs[right] = {};
<add> if (create && create !== 1) {
<add> ensureSafeAssignContext(lhs);
<add> if (lhs && !(lhs[right])) {
<add> lhs[right] = {};
<add> }
<ide> }
<ide> var value = lhs != null ? lhs[right] : undefined;
<ide> if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
<ide><path>test/ng/parseSpec.js
<ide> describe('parser', function() {
<ide> expect(function() {
<ide> scope.$eval("objConstructor = {}.constructor; objConstructor.join = ''");
<ide> }).toThrow();
<add> expect(function() {
<add> scope.$eval("'a'.constructor.prototype.charAt=[].join");
<add> }).toThrow();
<add> expect(function() {
<add> scope.$eval("'a'.constructor.prototype.charCodeAt=[].concat");
<add> }).toThrow();
<ide> });
<ide> });
<ide> | 2 |
Text | Text | update delete example using turbo | 58d66cfc75754c167a435d04fb4077ae6dde2d70 | <ide><path>guides/source/getting_started.md
<ide> we can delete an article from its own page:
<ide> <ul>
<ide> <li><%= link_to "Edit", edit_article_path(@article) %></li>
<ide> <li><%= link_to "Destroy", article_path(@article),
<del> method: :delete,
<del> data: { confirm: "Are you sure?" } %></li>
<add> data: { turbo_method: :delete, turbo_confirm: "Are you sure?" } %></li>
<ide> </ul>
<ide> ```
<ide>
<del>In the above code, we're passing a few additional options to `link_to`. The
<del>`method: :delete` option causes the link to make a `DELETE` request instead of a
<del>`GET` request. The `data: { confirm: "Are you sure?" }` option causes a
<add>In the above code, we're passing the `data` attribute with some options to `link_to`.
<add>The `turbo_method: :delete` option causes the link to make a `DELETE` request instead
<add>of a `GET` request. The `turbo_confirm: { confirm: "Are you sure?" }` option causes a
<ide> confirmation dialog to appear when the link is clicked. If the user cancels the
<del>dialog, the request is aborted. Both of these options are powered by a feature
<del>of Rails called *Unobtrusive JavaScript* (UJS). The JavaScript file that
<add>dialog, the request is aborted. Both of these options are powered by (Turbo)[https://turbo.hotwired.dev/]
<add>called *Performing Visits*. The JavaScript file that
<ide> implements these behaviors is included by default in fresh Rails applications.
<ide>
<ide> TIP: To learn more about Unobtrusive JavaScript, see [Working With JavaScript in
<ide> So first, we'll wire up the Article show template
<ide> <ul>
<ide> <li><%= link_to "Edit", edit_article_path(@article) %></li>
<ide> <li><%= link_to "Destroy", article_path(@article),
<del> method: :delete,
<del> data: { confirm: "Are you sure?" } %></li>
<add> data: { turbo_method: :delete, turbo_confirm: "Are you sure?" } %></li>
<ide> </ul>
<ide>
<ide> <h2>Add a comment:</h2>
<ide> add that to the `app/views/articles/show.html.erb`.
<ide> <ul>
<ide> <li><%= link_to "Edit", edit_article_path(@article) %></li>
<ide> <li><%= link_to "Destroy", article_path(@article),
<del> method: :delete,
<del> data: { confirm: "Are you sure?" } %></li>
<add> data: { turbo_method: :delete, turbo_confirm: "Are you sure?" } %></li>
<ide> </ul>
<ide>
<ide> <h2>Comments</h2>
<ide> following:
<ide> <ul>
<ide> <li><%= link_to "Edit", edit_article_path(@article) %></li>
<ide> <li><%= link_to "Destroy", article_path(@article),
<del> method: :delete,
<del> data: { confirm: "Are you sure?" } %></li>
<add> data: { turbo_method: :delete, turbo_confirm: "Are you sure?" } %></li>
<ide> </ul>
<ide>
<ide> <h2>Comments</h2>
<ide> Then you make the `app/views/articles/show.html.erb` look like the following:
<ide> <ul>
<ide> <li><%= link_to "Edit", edit_article_path(@article) %></li>
<ide> <li><%= link_to "Destroy", article_path(@article),
<del> method: :delete,
<del> data: { confirm: "Are you sure?" } %></li>
<add> data: { turbo_method: :delete, turbo_confirm: "Are you sure?" } %></li>
<ide> </ul>
<ide>
<ide> <h2>Comments</h2> | 1 |
Javascript | Javascript | add uncaught exception handler | d8bf99708d4288ca994f53c68a64affcbffafb2e | <ide><path>app.js
<ide> if (process.env.NODE_ENV !== 'development') {
<ide> require('newrelic');
<ide> }
<ide> require('dotenv').load();
<del>/**
<del> * Module dependencies.
<del> */
<add>// handle uncaught exceptions. Forever will restart process on shutdown
<add>process.on('uncaughtException', function (err) {
<add> console.error(
<add> (new Date()).toUTCString() + ' uncaughtException:',
<add> err.message
<add> );
<add> console.error(err.stack);
<add> /* eslint-disable no-process-exit */
<add> process.exit(1);
<add> /* eslint-enable no-process-exit */
<add>});
<ide>
<ide> var express = require('express'),
<ide> cookieParser = require('cookie-parser'), | 1 |
Text | Text | fix typo in src/readme.md | 37b4f4799a3851208e427ec27d4bca7c1ae0d489 | <ide><path>src/README.md
<ide> v8::Maybe<double> SumNumbers(v8::Local<v8::Context> context,
<ide>
<ide> for (uint32_t i = 0; i < array_of_integers->Length(); i++) {
<ide> v8::Local<v8::Value> entry;
<del> if (array_of_integers->Get(context, i).ToLocal(&entry)) {
<add> if (!array_of_integers->Get(context, i).ToLocal(&entry)) {
<ide> // Oops, we might have hit a getter that throws an exception!
<ide> // It's better to not continue return an empty (“nothing”) Maybe.
<ide> return v8::Nothing<double>(); | 1 |
Python | Python | remove redundant parenthesis | a7272f47f67bb607198731fa69efe3f42f256ce0 | <ide><path>airflow/www/views.py
<ide> def _clear_dag_tis(
<ide>
<ide> response = self.render_template(
<ide> 'airflow/confirm.html',
<del> message=("Here's the list of task instances you are about to clear:"),
<add> message="Here's the list of task instances you are about to clear:",
<ide> details=details,
<ide> )
<ide>
<ide> def _mark_task_instance_state( # pylint: disable=too-many-arguments
<ide>
<ide> response = self.render_template(
<ide> "airflow/confirm.html",
<del> message=(f"Here's the list of task instances you are about to mark as {state}:"),
<add> message=f"Here's the list of task instances you are about to mark as {state}:",
<ide> details=details,
<ide> )
<ide> | 1 |
Javascript | Javascript | fix syntax highlighting on the javascript | b6bc6c2ddf1ae1523ec7e4cb92db209cd6501181 | <ide><path>docs/spec/ngdocSpec.js
<ide> describe('ngdoc', function(){
<ide>
<ide> describe('@description', function(){
<ide> it('should support pre blocks', function(){
<del> var doc = new Doc("@description <pre>abc</pre>");
<add> var doc = new Doc("@description <pre><b>abc</b></pre>");
<ide> doc.parse();
<ide> expect(doc.description).
<del> toBe('<div ng:non-bindable><pre class="brush: js; html-script: true;">abc</pre></div>');
<add> toBe('<div ng:non-bindable><pre class="brush: js; html-script: true;"><b>abc</b></pre></div>');
<ide> });
<ide>
<ide> it('should support multiple pre blocks', function() {
<ide> var doc = new Doc("@description foo \n<pre>abc</pre>\n#bah\nfoo \n<pre>cba</pre>");
<ide> doc.parse();
<ide> expect(doc.description).
<ide> toBe('<p>foo </p>' +
<del> '<div ng:non-bindable><pre class="brush: js; html-script: true;">abc</pre></div>' +
<add> '<div ng:non-bindable><pre class="brush: js;">abc</pre></div>' +
<ide> '<h1>bah</h1>\n\n' +
<ide> '<p>foo </p>' +
<del> '<div ng:non-bindable><pre class="brush: js; html-script: true;">cba</pre></div>');
<add> '<div ng:non-bindable><pre class="brush: js;">cba</pre></div>');
<ide>
<ide> });
<ide>
<ide><path>docs/src/ngdoc.js
<ide> Doc.prototype = {
<ide> parts.forEach(function(text, i){
<ide> if (text.match(/^<pre>/)) {
<ide> text = text.replace(/^<pre>([\s\S]*)<\/pre>/mi, function(_, content){
<del> return '<div ng:non-bindable><pre class="brush: js; html-script: true;">' +
<add> var clazz = 'brush: js;'
<add> if (content.match(/\<\w/)) {
<add> // we are HTML
<add> clazz += ' html-script: true;';
<add> }
<add> return '<div ng:non-bindable><pre class="' + clazz +'">' +
<ide> content.replace(/</g, '<').replace(/>/g, '>') +
<ide> '</pre></div>';
<ide> }); | 2 |
PHP | PHP | implement remaining tests for inputregistry | 64a932da51a25f394190e9ce6c69763e496e9c1b | <ide><path>tests/TestCase/View/Input/InputRegistryTest.php
<ide> public function setUp() {
<ide> $this->templates = new StringTemplate();
<ide> }
<ide>
<add>/**
<add> * Test adding new widgets.
<add> *
<add> * @return void
<add> */
<add> public function testAddInConstructor() {
<add> $widgets = [
<add> 'text' => ['Cake\View\Input\Text'],
<add> ];
<add> $inputs = new InputRegistry($this->templates, $widgets);
<add> $result = $inputs->get('text');
<add> $this->assertInstanceOf('Cake\View\Input\Text', $result);
<add> }
<add>
<ide> /**
<ide> * Test adding new widgets.
<ide> *
<ide> * @return void
<ide> */
<ide> public function testAdd() {
<del> $this->markTestIncomplete();
<add> $inputs = new InputRegistry($this->templates);
<add> $result = $inputs->add([
<add> 'text' => ['Cake\View\Input\Text'],
<add> ]);
<add> $this->assertNull($result);
<ide> }
<ide>
<ide> /**
<ide> public function testAdd() {
<ide> * @return void
<ide> */
<ide> public function testGet() {
<del> $this->markTestIncomplete();
<add> $inputs = new InputRegistry($this->templates);
<add> $inputs->add([
<add> 'text' => ['Cake\View\Input\Text'],
<add> ]);
<add> $result = $inputs->get('text');
<add> $this->assertInstanceOf('Cake\View\Input\Text', $result);
<add> $this->assertSame($result, $inputs->get('text'));
<ide> }
<ide>
<ide> /**
<ide> public function testGet() {
<ide> * @return void
<ide> */
<ide> public function testGetFallback() {
<del> $this->markTestIncomplete();
<add> $inputs = new InputRegistry($this->templates);
<add> $inputs->add([
<add> '_default' => ['Cake\View\Input\Text'],
<add> ]);
<add> $result = $inputs->get('text');
<add> $this->assertInstanceOf('Cake\View\Input\Text', $result);
<add>
<add> $result2 = $inputs->get('hidden');
<add> $this->assertSame($result, $result2);
<ide> }
<ide>
<ide> /**
<ide> public function testGetResolveDependency() {
<ide> 'multicheckbox' => ['Cake\View\Input\MultiCheckbox', 'label']
<ide> ]);
<ide> $result = $inputs->get('multicheckbox');
<del> $this->assertInstanceOf('CakeView\Input\MultiCheckbox', $result);
<add> $this->assertInstanceOf('Cake\View\Input\MultiCheckbox', $result);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | add path require to top | 025967193ad4ccc53b9e3f1c89efabd381f0bd93 | <ide><path>static/index.js
<ide> window.onload = function() {
<ide> try {
<add> var path = require('path');
<add>
<ide> var startTime = Date.now();
<ide>
<ide> // Skip "?loadSettings=".
<ide> window.onload = function() {
<ide> // Normalize to make sure drive letter case is consistent on Windows
<ide> process.resourcesPath = path.normalize(process.resourcesPath);
<ide>
<del> var devMode = loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + require('path').sep);
<add> var devMode = loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep);
<ide>
<ide> // Require before the module cache in dev mode
<ide> if (devMode) { | 1 |
Ruby | Ruby | return result of last rake task | e889f315c8af6d67bf605069a0ffb8848aea145d | <ide><path>ci/ci_build.rb
<ide> def root_dir
<ide> end
<ide>
<ide> def rake(*tasks)
<del> tasks.map { |task| system "#{root_dir}/bin/rake", task }.join("\n")
<add> result = nil
<add> tasks.each { |task| result = system("#{root_dir}/bin/rake", task) }
<add> result
<ide> end
<ide>
<ide> puts "[CruiseControl] Rails build" | 1 |
Go | Go | support a proxy in splunk log driver | 3c4537d5b33d951237ea5e4cc123953eda7a37e7 | <ide><path>daemon/logger/splunk/splunk.go
<ide> func New(info logger.Info) (logger.Logger, error) {
<ide>
<ide> transport := &http.Transport{
<ide> TLSClientConfig: tlsConfig,
<add> Proxy: http.ProxyFromEnvironment,
<ide> }
<ide> client := &http.Client{
<ide> Transport: transport,
<ide><path>daemon/logger/splunk/splunk_test.go
<ide> import (
<ide> "compress/gzip"
<ide> "context"
<ide> "fmt"
<add> "net/http"
<ide> "os"
<ide> "runtime"
<ide> "testing"
<ide> "time"
<ide>
<ide> "github.com/docker/docker/daemon/logger"
<add> "github.com/gotestyourself/gotestyourself/env"
<ide> "github.com/stretchr/testify/require"
<ide> )
<ide>
<ide> func TestNewMissedToken(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func TestNewWithProxy(t *testing.T) {
<add> proxy := "http://proxy.testing:8888"
<add> reset := env.Patch(t, "HTTP_PROXY", proxy)
<add> defer reset()
<add>
<add> // must not be localhost
<add> splunkURL := "http://example.com:12345"
<add> logger, err := New(logger.Info{
<add> Config: map[string]string{
<add> splunkURLKey: splunkURL,
<add> splunkTokenKey: "token",
<add> splunkVerifyConnectionKey: "false",
<add> },
<add> ContainerID: "containeriid",
<add> })
<add> require.NoError(t, err)
<add> splunkLogger := logger.(*splunkLoggerInline)
<add>
<add> proxyFunc := splunkLogger.transport.Proxy
<add> require.NotNil(t, proxyFunc)
<add>
<add> req, err := http.NewRequest("GET", splunkURL, nil)
<add> require.NoError(t, err)
<add>
<add> proxyURL, err := proxyFunc(req)
<add> require.NoError(t, err)
<add> require.NotNil(t, proxyURL)
<add> require.Equal(t, proxy, proxyURL.String())
<add>}
<add>
<ide> // Test default settings
<ide> func TestDefault(t *testing.T) {
<ide> hec := NewHTTPEventCollectorMock(t) | 2 |
Javascript | Javascript | fix typos in read-buffer tests | 48a777287d1e0b4e199efe2137d5513c3edfc85d | <ide><path>test/parallel/test-buffer-read.js
<ide> read(buf, 'readUIntBE', [2, 0], 0xfd);
<ide> read(buf, 'readUIntLE', [2, 0], 0x48);
<ide>
<ide> // attempt to overflow buffers, similar to previous bug in array buffers
<del>assert.throws(() => Buffer.allocUnsafe(8).readFloatLE(0xffffffff),
<add>assert.throws(() => Buffer.allocUnsafe(8).readFloatBE(0xffffffff),
<ide> RangeError);
<ide> assert.throws(() => Buffer.allocUnsafe(8).readFloatLE(0xffffffff),
<ide> RangeError);
<ide>
<ide> // ensure negative values can't get past offset
<del>assert.throws(() => Buffer.allocUnsafe(8).readFloatLE(-1), RangeError);
<add>assert.throws(() => Buffer.allocUnsafe(8).readFloatBE(-1), RangeError);
<ide> assert.throws(() => Buffer.allocUnsafe(8).readFloatLE(-1), RangeError);
<ide>
<ide> // offset checks | 1 |
Python | Python | deprecate the decorators in np.testing.dec | f5579746f07a4f40d8b9391336fac0ee79659d22 | <ide><path>numpy/testing/_private/decorators.py
<ide>
<ide> """
<ide> import collections.abc
<add>import warnings
<ide>
<ide> from .utils import SkipTest, assert_warns, HAS_REFCOUNT
<ide>
<ide>
<ide> def slow(t):
<ide> """
<add> .. deprecated:: 1.20
<add> This decorator is retained for compatibility with the nose testing framework, which is being phased out.
<add> Please use the nose2 or pytest frameworks instead.
<add>
<ide> Label a test as 'slow'.
<ide>
<ide> The exact definition of a slow test is obviously both subjective and
<ide> def test_big(self):
<ide> print('Big, slow test')
<ide>
<ide> """
<add> warnings.warn('the np.testing.dec decorators are included for nose support, and are '
<add> 'deprecated since NumPy v1.20. Use the nose2 or pytest frameworks instead.', DeprecationWarning, stacklevel=2)
<ide>
<ide> t.slow = True
<ide> return t
<ide>
<ide> def setastest(tf=True):
<ide> """
<add> .. deprecated:: 1.20
<add> This decorator is retained for compatibility with the nose testing framework, which is being phased out.
<add> Please use the nose2 or pytest frameworks instead.
<add>
<ide> Signals to nose that this function is or is not a test.
<ide>
<ide> Parameters
<ide> def func_with_test_in_name(arg1, arg2):
<ide> pass
<ide>
<ide> """
<add> warnings.warn('the np.testing.dec decorators are included for nose support, and are '
<add> 'deprecated since NumPy v1.20. Use the nose2 or pytest frameworks instead.', DeprecationWarning, stacklevel=2)
<ide> def set_test(t):
<ide> t.__test__ = tf
<ide> return t
<ide> return set_test
<ide>
<ide> def skipif(skip_condition, msg=None):
<ide> """
<add> .. deprecated:: 1.20
<add> This decorator is retained for compatibility with the nose testing framework, which is being phased out.
<add> Please use the nose2 or pytest frameworks instead.
<add>
<ide> Make function raise SkipTest exception if a given condition is true.
<ide>
<ide> If the condition is a callable, it is used at runtime to dynamically
<ide> def skip_decorator(f):
<ide> # import time overhead at actual test-time.
<ide> import nose
<ide>
<add> warnings.warn('the np.testing.dec decorators are included for nose support, and are '
<add> 'deprecated since NumPy v1.20. Use the nose2 or pytest frameworks instead.', DeprecationWarning, stacklevel=2)
<add>
<ide> # Allow for both boolean or callable skip conditions.
<ide> if isinstance(skip_condition, collections.abc.Callable):
<ide> skip_val = lambda: skip_condition()
<ide> def skipper_gen(*args, **kwargs):
<ide>
<ide> def knownfailureif(fail_condition, msg=None):
<ide> """
<add> .. deprecated:: 1.20
<add> This decorator is retained for compatibility with the nose testing framework, which is being phased out.
<add> Please use the nose2 or pytest frameworks instead.
<add>
<ide> Make function raise KnownFailureException exception if given condition is true.
<ide>
<ide> If the condition is a callable, it is used at runtime to dynamically
<ide> def knownfailureif(fail_condition, msg=None):
<ide> function in order to transmit function name, and various other metadata.
<ide>
<ide> """
<add> warnings.warn('the np.testing.dec decorators are included for nose support, and are '
<add> 'deprecated since NumPy v1.20. Use the nose2 or pytest frameworks instead.', DeprecationWarning, stacklevel=2)
<add>
<ide> if msg is None:
<ide> msg = 'Test skipped due to known failure'
<ide>
<ide> def knownfailer(*args, **kwargs):
<ide>
<ide> def deprecated(conditional=True):
<ide> """
<add> .. deprecated:: 1.20
<add> This decorator is retained for compatibility with the nose testing framework, which is being phased out.
<add> Please use the nose2 or pytest frameworks instead.
<add>
<ide> Filter deprecation warnings while running the test suite.
<ide>
<ide> This decorator can be used to filter DeprecationWarning's, to avoid
<ide> def deprecate_decorator(f):
<ide> # import time overhead at actual test-time.
<ide> import nose
<ide>
<add> warnings.warn('the np.testing.dec decorators are included for nose support, and are '
<add> 'deprecated since NumPy v1.20. Use the nose2 or pytest frameworks instead.', DeprecationWarning, stacklevel=2)
<add>
<ide> def _deprecated_imp(*args, **kwargs):
<ide> # Poor man's replacement for the with statement
<ide> with assert_warns(DeprecationWarning):
<ide> def _deprecated_imp(*args, **kwargs):
<ide>
<ide> def parametrize(vars, input):
<ide> """
<add> .. deprecated:: 1.20
<add> This decorator is retained for compatibility with the nose testing framework, which is being phased out.
<add> Please use the nose2 or pytest frameworks instead.
<add>
<ide> Pytest compatibility class. This implements the simplest level of
<ide> pytest.mark.parametrize for use in nose as an aid in making the transition
<ide> to pytest. It achieves that by adding a dummy var parameter and ignoring
<ide> def parametrize(vars, input):
<ide> """
<ide> from .parameterized import parameterized
<ide>
<add> warnings.warn('the np.testing.dec decorators are included for nose support, and are '
<add> 'deprecated since NumPy v1.20. Use the nose2 or pytest frameworks instead.', DeprecationWarning, stacklevel=2)
<add>
<ide> return parameterized(input)
<ide>
<ide> _needs_refcount = skipif(not HAS_REFCOUNT, "python has no sys.getrefcount") | 1 |
Text | Text | fix err_synthetic issue on v11.x | f31794bf1467eb156dad077647e2f075eb3757c7 | <ide><path>doc/api/errors.md
<ide> An attempt has been made to create a string longer than the maximum allowed
<ide> length.
<ide>
<ide> <a id="ERR_SYNTHETIC"></a>
<del>#### ERR_SYNTHETIC
<add>### ERR_SYNTHETIC
<ide>
<ide> An artificial error object used to capture the call stack for diagnostic
<ide> reports. | 1 |
Ruby | Ruby | add missing type to number_field_tag documentation | 07c4297282c9c2d0768922722ad2ab08dedf4d8d | <ide><path>actionpack/lib/action_view/helpers/form_tag_helper.rb
<ide> def email_field_tag(name, value = nil, options = {})
<ide> #
<ide> # ==== Examples
<ide> # number_field_tag 'quantity', nil, :in => 1...10
<del> # => <input id="quantity" name="quantity" min="1" max="9" />
<add> # => <input id="quantity" name="quantity" min="1" max="9" type="number" />
<ide> def number_field_tag(name, value = nil, options = {})
<ide> options = options.stringify_keys
<ide> options["type"] ||= "number" | 1 |
PHP | PHP | remove unused use statements | 4dc1e9d86052982b55a138433e222c4cdad4c052 | <ide><path>src/Database/Type/ExpressionTypeCasterTrait.php
<ide> namespace Cake\Database\Type;
<ide>
<ide> use Cake\Database\Type;
<del>use Cake\Database\Type\ExpressionTypeInterface;
<ide>
<ide> /**
<ide> * Offers a method to convert values to ExpressionInterface objects
<ide><path>src/Database/Type/JsonType.php
<ide> use Cake\Database\Type;
<ide> use Cake\Database\TypeInterface;
<ide> use InvalidArgumentException;
<del>use JsonSerializable;
<ide> use PDO;
<ide>
<ide> /**
<ide><path>src/Http/ActionDispatcher.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Event\EventDispatcherTrait;
<ide> use Cake\Event\EventListenerInterface;
<del>use Cake\Http\ControllerFactory;
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide> use Cake\Routing\Router;
<ide><path>src/Http/ResponseTransformer.php
<ide> */
<ide> namespace Cake\Http;
<ide>
<del>use Cake\Http\CallbackStream;
<ide> use Cake\Network\Response as CakeResponse;
<ide> use Psr\Http\Message\ResponseInterface as PsrResponse;
<ide> use Zend\Diactoros\Response as DiactorosResponse;
<ide><path>src/Http/Server.php
<ide> use UnexpectedValueException;
<ide> use Zend\Diactoros\Response;
<ide> use Zend\Diactoros\Response\EmitterInterface;
<del>use Zend\Diactoros\Response\SapiEmitter;
<del>use Zend\Diactoros\Response\SapiStreamEmitter;
<ide>
<ide> /**
<ide> * Runs an application invoking all the PSR7 middleware and the registered application.
<ide><path>src/ORM/Marshaller.php
<ide> use Cake\Database\Type;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Datasource\InvalidPropertyInterface;
<del>use Cake\ORM\PropertyMarshalInterface;
<ide> use RuntimeException;
<ide>
<ide> /**
<ide><path>src/ORM/Query.php
<ide> use Cake\Datasource\QueryTrait;
<ide> use JsonSerializable;
<ide> use RuntimeException;
<del>use Traversable;
<ide>
<ide> /**
<ide> * Extends the base Query class to provide new methods related to association
<ide><path>src/ORM/Rule/ValidCount.php
<ide> namespace Cake\ORM\Rule;
<ide>
<ide> use Cake\Datasource\EntityInterface;
<del>use Cake\ORM\Association;
<ide> use Cake\Validation\Validation;
<ide> use Countable;
<ide>
<ide><path>src/TestSuite/IntegrationTestCase.php
<ide> use Cake\Database\Exception as DatabaseException;
<ide> use Cake\Network\Session;
<ide> use Cake\Routing\Router;
<del>use Cake\TestSuite\LegacyRequestDispatcher;
<del>use Cake\TestSuite\MiddlewareDispatcher;
<ide> use Cake\Utility\CookieCryptTrait;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security; | 9 |
Ruby | Ruby | check git version | d73df34bc6ee5cbd989d11c6a927e2ca083b951c | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_leopard_ssl
<ide> end
<ide> end
<ide>
<add>def check_git_version
<add> # see https://github.com/blog/642-smart-http-support
<add> return unless system "/usr/bin/which -s git"
<add> `git --version`.chomp =~ /git version (\d)\.(\d)\.(\d)/
<add>
<add> if $2.to_i > 6
<add> return
<add> elsif $2.to_i == 6 and $3.to_i == 6
<add> return
<add> else
<add> puts <<-EOS.undent
<add> An outdated version of Git was detected in your PATH.
<add>
<add> Git 1.6.6 or newer is required to perform checkouts over HTTP from GitHub.
<add>
<add> You may want to upgrade:
<add> brew upgrade git
<add>
<add> EOS
<add> end
<add>end
<add>
<ide> module Homebrew extend self
<ide> def doctor
<ide> old_stdout = $stdout
<ide> def doctor
<ide> check_missing_deps
<ide> check_git_status
<ide> check_for_leopard_ssl
<add> check_git_version
<ide> ensure
<ide> $stdout = old_stdout
<ide> end | 1 |
Python | Python | add test for gh-11221 | 84286e6f728b2c852a1ed21e2d40765f3c625fa5 | <ide><path>numpy/core/tests/test_einsum.py
<ide> import numpy as np
<ide> from numpy.testing import (
<ide> assert_, assert_equal, assert_array_equal, assert_almost_equal,
<del> assert_raises, suppress_warnings
<add> assert_raises, suppress_warnings, assert_raises_regex
<ide> )
<ide>
<ide> # Setup for optimize einsum
<ide> def test_einsum_errors(self):
<ide> optimize=do_opt)
<ide> assert_raises(ValueError, np.einsum, "i->i", [[0, 1], [0, 1]],
<ide> out=np.arange(4).reshape(2, 2), optimize=do_opt)
<add> with assert_raises_regex(ValueError, "'b'"):
<add> # gh-11221 - 'c' erroneously appeared in the error message
<add> a = np.ones((3, 3, 4, 5, 6))
<add> b = np.ones((3, 4, 5))
<add> np.einsum('aabcb,abc', a, b)
<ide>
<ide> def test_einsum_views(self):
<ide> # pass-through | 1 |
Javascript | Javascript | add ability to unregister gestures from the system | 8282f906e183143095f6fcbf2aa991089dd4b216 | <ide><path>packages/sproutcore-touch/lib/system/gestures.js
<ide> SC.Gestures = SC.Object.create(
<ide> registeredGestures[name] = recognizer;
<ide> },
<ide>
<add> unregister: function(name) {
<add> var registeredGestures = this._registeredGestures;
<add>
<add> if (registeredGestures[name] !== undefined) {
<add> registeredGestures[name] = undefined;
<add> }
<add> },
<add>
<ide> /**
<ide> Registers a gesture recognizer to the system. The gesture recognizer is
<ide> identified by the name parameter, which must be unique across the system.
<ide><path>packages/sproutcore-touch/tests/system/gestures_test.js
<ide> test("register new gestures", function() {
<ide> ok(caught);
<ide> });
<ide>
<add>test("unregister a gesture", function() {
<add> var myGesture = SC.Gesture.create({
<add> isMyGesture: true
<add> });
<add>
<add> SC.Gestures.register('myGesture2',myGesture);
<add>
<add> var newGestures = SC.Gestures.knownGestures();
<add>
<add> equals(newGestures['myGesture2'],myGesture, "registered gesture is added");
<add>
<add> SC.Gestures.unregister('myGesture2');
<add>
<add> newGestures = SC.Gestures.knownGestures();
<add> equals(newGestures['myGesture2'],undefined, "registered gesture is unregistered");
<add>});
<add> | 2 |
Text | Text | update the readme | 3e3b5de71eb6465319c25d1fe7424af036e948e4 | <ide><path>README.md
<ide> 2. Unzip and open the app
<ide>
<ide> ## Basic Keyboard shortcuts
<add>Atom doesn't have much in the way of menus yet. Use these keyboard shortcuts to
<add>explore features.
<ide>
<ide> `cmd-o` : open file/directory
<ide>
<ide> `cmd-n` : new window
<ide>
<add>`cmd-r` : reload the current window
<add>
<ide> `cmd-alt-ctrl-s` : run specs
<ide>
<del>`cmd-t` : open fuzzy finder
<add>`cmd-t` : open fuzzy file finder
<ide>
<ide> `cmd-:` : open command prompt
<ide>
<ide> `cmd-f` : open command prompt with /
<ide>
<ide> `cmd-g` : repeat the last search
<ide>
<add>`cmd-alt-arrows` : split screen in direction of arrow
<add>
<ide> `cmd-alt-w` : toggle word wrap
<ide>
<ide> `cmd-alt-f` : fold selected lines
<ide>
<ide> Most default OS X keybindings also work.
<ide>
<add>## Init Script
<add>
<add>Atom will require `~/.atom/atom.coffee` whenever a window is opened or reloaded if it is present in your
<add>home directory. This is a rudimentary jumping off point for your own customizations.
<add>
<ide> ## Command Panel
<ide>
<ide> A partial implementation of the [Sam command language](http://man.cat-v.org/plan_9/1/sam)
<ide> A partial implementation of the [Sam command language](http://man.cat-v.org/plan
<ide>
<ide> `,x/pattern1/ x/pattern2` "structural regex" - selects all matches of pattern2 inside matches of pattern1
<ide>
<add>## Key Bindings
<add>
<add>Atom has a CSS based key binding scheme. We will add a nicer loading mechanism, but for now you can bind
<add>keys by calling `window.keymap.bindKeys` with a CSS selector and a hash of key-pattern -> event mappings.
<add>
<add>```coffeescript
<add>window.keymap.bindKeys '.editor'
<add> 'ctrl-p': 'party-time'
<add> 'ctrl-q': 'open-dialog-q'
<add>```
<add>
<add>When a keypress matches a pattern on an element that matches the selector, it will be translated to the
<add>named event, which will bubble up the DOM from the site of the keypress. Extension code can listen for
<add>the named event and react to it.
<add>
<add>
<ide> ## Build from source
<ide>
<ide> 1. Get [xcode 4.2](http://itunes.apple.com/us/app/xcode/id448457090?mt=12)
<ide> A partial implementation of the [Sam command language](http://man.cat-v.org/plan
<ide>
<ide> 4. `cd atom`
<ide>
<del>5. `rake run`
<ide>\ No newline at end of file
<add>5. `rake run` | 1 |
Javascript | Javascript | use assert regexp in tls no cert test | cfe7b34058716d9c9dfb143ecc865a30f433db5c | <ide><path>test/parallel/test-tls-no-cert-required.js
<ide> tls.createServer(assert.fail)
<ide> tls.createServer({})
<ide> .listen(0, common.mustCall(close));
<ide>
<del>assert.throws(() => tls.createServer('this is not valid'), TypeError);
<add>assert.throws(() => tls.createServer('this is not valid'),
<add> /^TypeError: options must be an object$/);
<ide>
<ide> tls.createServer()
<ide> .listen(0, common.mustCall(close)); | 1 |
Python | Python | fix some test bugs | 259fff8f08dabd8198d2ec0f5abe99a05a5477d5 | <ide><path>numpy/core/tests/test_print.py
<ide> def test_complex_types():
<ide>
<ide> def test_complex_inf_nan():
<ide> """Check inf/nan formatting of complex types."""
<del> if sys.version_info >= (2, 6):
<add> if sys.version_info[:2] >= (2, 6):
<ide> TESTS = {
<ide> complex(np.inf, 0): "(inf+0j)",
<ide> complex(0, np.inf): "inf*j",
<ide> def test_complex_type_print():
<ide> for t in [np.complex64, np.cdouble, np.clongdouble] :
<ide> yield check_complex_type_print, t
<ide>
<del>@dec.skipif(sys.version_info < (2,6))
<add>@dec.skipif(sys.version_info[:2] < (2, 6))
<ide> def test_scalar_format():
<ide> """Test the str.format method with NumPy scalar types"""
<ide> tests = [('{0}', True, np.bool_),
<ide> def test_scalar_format():
<ide> ('{0:g}', 1.5, np.float64),
<ide> ('{0:g}', 1.5, np.longdouble)]
<ide> # Python 2.6 doesn't implement complex.__format__
<del> if sys.version_info <= (2,6):
<add> if sys.version_info[:2] > (2, 6):
<ide> tests += [('{0:g}', 1.5+0.5j, np.complex64),
<ide> ('{0:g}', 1.5+0.5j, np.complex128),
<ide> ('{0:g}', 1.5+0.5j, np.clongdouble)]
<ide><path>numpy/lib/tests/test_io.py
<ide> from nose import SkipTest
<ide> from numpy.ma.testutils import (TestCase, assert_equal, assert_array_equal,
<ide> assert_raises, run_module_suite)
<del>from numpy.testing import assert_warns, assert_
<add>from numpy.testing import assert_warns, assert_, build_err_msg
<ide>
<ide> if sys.version_info[0] >= 3:
<ide> from io import BytesIO
<ide> def _assert_floatstr_lines_equal(actual_lines, expected_lines):
<ide> of this function.
<ide> """
<ide> for actual, expected in zip(actual_lines, expected_lines):
<del> if not actual == expected:
<add> if actual != expected:
<ide> expected_win25 = expected.replace("e+00", "e+000")
<del> if not actual == expected_win25:
<del> msg = build_err_msg([actual, desired], verbose=True)
<add> if actual != expected_win25:
<add> msg = build_err_msg([actual, expected], '', verbose=True)
<ide> raise AssertionError(msg)
<ide>
<ide> | 2 |
Java | Java | react edit text changes | c0c5e2276dd82f088d357a272633984787a8632e | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java
<ide> private static boolean sameTextForSpan(
<ide> return true;
<ide> }
<ide>
<del> private boolean showSoftKeyboard() {
<add> protected boolean showSoftKeyboard() {
<ide> return mInputMethodManager.showSoftInput(this, 0);
<ide> }
<ide>
<del> private void hideSoftKeyboard() {
<add> protected void hideSoftKeyboard() {
<ide> mInputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
<ide> }
<ide> | 1 |
Ruby | Ruby | use the correct reference to the redis connection | 2bc0c7ca023e5ea90312139066268fed16ff17c5 | <ide><path>actioncable/lib/action_cable/subscription_adapter/redis.rb
<ide> def subscribe(channel, message_callback, success_callback = nil)
<ide> end
<ide>
<ide> def unsubscribe(channel, message_callback)
<del> hi_redis_conn.pubsub.unsubscribe_proc(channel, message_callback)
<add> redis_connection_for_subscriptions.pubsub.unsubscribe_proc(channel, message_callback)
<ide> end
<ide>
<ide> private | 1 |
Python | Python | fix long double printing of nas | 4c88ab3e0020861488d77b6930d32474a7cce709 | <ide><path>numpy/core/arrayprint.py
<ide> def __init__(self, precision, sign=False):
<ide> self.sign = sign
<ide>
<ide> def __call__(self, x):
<del> if isnan(x):
<add> if isna(x):
<add> return str(x).replace('NA', _na_str, 1)
<add> elif isnan(x):
<ide> if self.sign:
<ide> return '+' + _nan_str
<ide> else:
<ide> def __call__(self, x):
<ide> return ' ' + _inf_str
<ide> else:
<ide> return '-' + _inf_str
<del> elif isna(x):
<del> return str(x).replace('NA', _na_str, 1)
<ide> elif x >= 0:
<ide> if self.sign:
<ide> return '+' + format_longfloat(x, self.precision) | 1 |
Javascript | Javascript | inform devtools of commit priority level | 50b50c26f6724c559a3550b903d2cc2eeffdf092 | <ide><path>packages/react-reconciler/src/ReactFiberDevToolsHook.js
<ide> * @flow
<ide> */
<ide>
<add>import {enableProfilerTimer} from 'shared/ReactFeatureFlags';
<add>import {requestCurrentTime} from './ReactFiberScheduler';
<add>import {inferPriorityFromExpirationTime} from './ReactFiberExpirationTime';
<add>
<ide> import type {Fiber} from './ReactFiber';
<ide> import type {FiberRoot} from './ReactFiberRoot';
<add>import type {ExpirationTime} from './ReactFiberExpirationTime';
<ide>
<ide> import warningWithoutStack from 'shared/warningWithoutStack';
<ide>
<ide> let onCommitFiberRoot = null;
<ide> let onCommitFiberUnmount = null;
<ide> let hasLoggedError = false;
<ide>
<del>function catchErrors(fn) {
<del> return function(arg) {
<del> try {
<del> return fn(arg);
<del> } catch (err) {
<del> if (__DEV__ && !hasLoggedError) {
<del> hasLoggedError = true;
<del> warningWithoutStack(
<del> false,
<del> 'React DevTools encountered an error: %s',
<del> err,
<del> );
<del> }
<del> }
<del> };
<del>}
<del>
<ide> export const isDevToolsPresent =
<ide> typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
<ide>
<ide> export function injectInternals(internals: Object): boolean {
<ide> try {
<ide> const rendererID = hook.inject(internals);
<ide> // We have successfully injected, so now it is safe to set up hooks.
<del> onCommitFiberRoot = catchErrors(root =>
<del> hook.onCommitFiberRoot(rendererID, root),
<del> );
<del> onCommitFiberUnmount = catchErrors(fiber =>
<del> hook.onCommitFiberUnmount(rendererID, fiber),
<del> );
<add> onCommitFiberRoot = (root, expirationTime) => {
<add> try {
<add> if (enableProfilerTimer) {
<add> const currentTime = requestCurrentTime();
<add> const priorityLevel = inferPriorityFromExpirationTime(
<add> currentTime,
<add> expirationTime,
<add> );
<add> hook.onCommitFiberRoot(rendererID, root, priorityLevel);
<add> } else {
<add> hook.onCommitFiberRoot(rendererID, root);
<add> }
<add> } catch (err) {
<add> if (__DEV__ && !hasLoggedError) {
<add> hasLoggedError = true;
<add> warningWithoutStack(
<add> false,
<add> 'React DevTools encountered an error: %s',
<add> err,
<add> );
<add> }
<add> }
<add> };
<add> onCommitFiberUnmount = fiber => {
<add> try {
<add> hook.onCommitFiberUnmount(rendererID, fiber);
<add> } catch (err) {
<add> if (__DEV__ && !hasLoggedError) {
<add> hasLoggedError = true;
<add> warningWithoutStack(
<add> false,
<add> 'React DevTools encountered an error: %s',
<add> err,
<add> );
<add> }
<add> }
<add> };
<ide> } catch (err) {
<ide> // Catch all errors because it is unsafe to throw during initialization.
<ide> if (__DEV__) {
<ide> export function injectInternals(internals: Object): boolean {
<ide> return true;
<ide> }
<ide>
<del>export function onCommitRoot(root: FiberRoot) {
<add>export function onCommitRoot(root: FiberRoot, expirationTime: ExpirationTime) {
<ide> if (typeof onCommitFiberRoot === 'function') {
<del> onCommitFiberRoot(root);
<add> onCommitFiberRoot(root, expirationTime);
<ide> }
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberScheduler.js
<ide> function commitRootImpl(root) {
<ide> legacyErrorBoundariesThatAlreadyFailed = null;
<ide> }
<ide>
<del> onCommitRoot(finishedWork.stateNode);
<add> onCommitRoot(finishedWork.stateNode, expirationTime);
<ide>
<ide> if (remainingExpirationTime === Sync) {
<ide> // Count the number of times the root synchronously re-renders without | 2 |
Ruby | Ruby | fix typo in nodoc | 2114e6bf29f35e8bd01b4c49c55355c50b8946c0 | <ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def get_builder_class
<ide> #
<ide> # This class should be called before the AppGenerator is required and started
<ide> # since it configures and mutates ARGV correctly.
<del> class ARGVScrubber # :nodoc
<add> class ARGVScrubber # :nodoc:
<ide> def initialize(argv = ARGV)
<ide> @argv = argv
<ide> end | 1 |
Javascript | Javascript | remove memory leak of anonymous subclasses | fd4e1067999e6d9428ff86e8941863102ed57819 | <ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> var ClassMixin = Ember.Mixin.create(
<ide> Ember.generateGuid(proto, 'ember');
<ide> meta(proto).proto = proto; // this will disable observers on prototype
<ide>
<del>
<del> Class.subclasses = Ember.Set ? new Ember.Set() : null;
<del> if (this.subclasses) { this.subclasses.add(Class); }
<del>
<ide> Class.ClassMixin.apply(Class);
<ide> return Class;
<ide> },
<ide><path>packages/ember-runtime/lib/system/object.js
<ide> require('ember-runtime/mixins/observable');
<ide> require('ember-runtime/system/core_object');
<ide> require('ember-runtime/system/set');
<ide>
<del>Ember.CoreObject.subclasses = new Ember.Set();
<del>
<ide> /**
<ide> @class
<ide>
<ide> Ember.CoreObject.subclasses = new Ember.Set();
<ide> @extends Ember.Observable
<ide> */
<ide> Ember.Object = Ember.CoreObject.extend(Ember.Observable);
<del>
<del>
<del>
<ide><path>packages/ember-runtime/tests/legacy_1x/system/object/base_test.js
<ide> test("Checking the detectInstance() function on an object and its subclass", fun
<ide> ok(Ember.Object.detectInstance(obj.create()));
<ide> ok(obj.detectInstance(obj.create()));
<ide> });
<del>
<del>test("subclasses should contain defined subclasses", function() {
<del> ok(inArray(obj1, obj.subclasses) > -1, 'obj.subclasses should contain obj1');
<del>
<del> equal(get(obj1.subclasses, 'length'),0,'obj1.subclasses should be empty');
<del>
<del> var kls2 = obj1.extend();
<del> ok(inArray(kls2, obj1.subclasses) > -1, 'obj1.subclasses should contain kls2');
<del>});
<ide><path>packages/ember-runtime/tests/system/object/subclasses_test.js
<ide>
<ide> module('system/object/subclasses');
<ide>
<del>test('Ember.Object should have a subclass set', function() {
<del> ok(Ember.Object.subclasses instanceof Ember.Set);
<del>});
<del>
<del>test('defining a new subclass should add it to set of parent', function() {
<del> var Subclass = Ember.Object.extend();
<del> ok(Ember.Object.subclasses.contains(Subclass));
<del>});
<del>
<del>test('defining sub-sub class should only go to parent', function() {
<del> var Sub = Ember.Object.extend();
<del> var SubSub = Sub.extend();
<del>
<del> ok(Ember.Object.subclasses.contains(Sub), 'Ember.Object contains Sub');
<del> ok(Sub.subclasses.contains(SubSub), 'Sub contains SubSub');
<del>});
<del>
<ide> // TEST lazy prototype and Em.rewatch(prototype)
<ide> test('chains should copy forward to subclasses when prototype created', function () {
<ide> var ObjectWithChains, objWithChains, SubWithChains, SubSub, subSub; | 4 |
PHP | PHP | add empty test methods | 0601ea16a4de8f93c9a63569843ef0b3ee28e5e1 | <ide><path>tests/TestCase/View/Input/DateTimeTest.php
<ide> public function testRenderSelected($selected) {
<ide> $this->assertContains('<option value="45" selected="selected">45</option>', $result);
<ide> }
<ide>
<add> public function testRenderEmptyValues() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderYearWidget() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderYearWidgetOrdering() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderYearWidgetMinAndMax() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderYearWidgetValueOutOfBounds() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderMonthWidget() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderMonthWidgetWithNames() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderDayWidget() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderHourWidget() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderHourWidget24() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderMinuteWidget() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderMinuteWidgetInterval() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderMinuteWidgetIntervalRounding() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderSecondsWidget() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add> public function testRenderMeridianWidget() {
<add> $this->markTestIncomplete();
<add> }
<add>
<add>
<ide> /**
<ide> * testGenerateNumbers
<ide> *
<ide> public function testGenerateNumbers() {
<ide> $this->assertEquals($result, $expected);
<ide> }
<ide>
<del>/**
<del> * testYearSelect
<del> *
<del> * @return void
<del> */
<del> public function testYearSelect() {
<del> $result = $this->DateTime->yearSelect();
<del> $this->markTestIncomplete();
<del> }
<del>
<del>/**
<del> * testMonthSelect
<del> *
<del> * @return void
<del> */
<del> public function testMonthSelect() {
<del> $result = $this->DateTime->monthSelect();
<del> $expected = '<select name="data[month]"><option value="01">01</option><option value="02">02</option><option value="03">03</option><option value="04">04</option><option value="05">05</option><option value="06">06</option><option value="07">07</option><option value="08">08</option><option value="09">09</option><option value="10">10</option><option value="11">11</option><option value="12">12</option></select>';
<del> $this->assertEquals($result, $expected);
<del>
<del> $result = $this->DateTime->monthSelect([
<del> 'names' => true,
<del> ]);
<del> $this->markTestIncomplete();
<del> }
<del>
<del>/**
<del> * testDaySelect
<del> *
<del> * @return void
<del> */
<del> public function testDaySelect() {
<del> $result = $this->DateTime->daySelect();
<del> $expected = '<select name="data[day]"><option value="01" selected="selected">01</option><option value="02">02</option><option value="03">03</option><option value="04">04</option><option value="05">05</option><option value="06">06</option><option value="07">07</option></select>';
<del> $this->markTestIncomplete();
<del> }
<del>
<del>/**
<del> * testHourSelect
<del> *
<del> * @return void
<del> */
<del> public function testHourSelect() {
<del> $result = $this->DateTime->hourSelect();
<del> $this->markTestIncomplete();
<del> }
<del>
<del>/**
<del> * testHourSelect
<del> *
<del> * @return void
<del> */
<del> public function testMinuteSelect() {
<del> $result = $this->DateTime->minuteSelect();
<del> $this->markTestIncomplete();
<del> }
<del>
<del>/**
<del> * testHourSelect
<del> *
<del> * @return void
<del> */
<del> public function testSecondSelect() {
<del> $result = $this->DateTime->secondSelect();
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> } | 1 |
Go | Go | reduce memory allocation and remove channels | 816d602059f9fd0e0df816c5a55e7f1dc437c8d9 | <ide><path>docker/docker.go
<ide> const (
<ide> )
<ide>
<ide> func main() {
<add> if reexec.Init() {
<add> return
<add> }
<add>
<ide> // Set terminal emulation based on platform as required.
<ide> stdout, stderr, stdin := term.StdStreams()
<ide>
<ide> initLogging(stderr)
<ide>
<del> if reexec.Init() {
<del> return
<del> }
<del>
<ide> flag.Parse()
<ide> // FIXME: validate daemon flags here
<ide>
<ide><path>pkg/term/winconsole/console_windows.go
<ide> const (
<ide>
<ide> ANSI_MAX_CMD_LENGTH = 256
<ide>
<add> MAX_INPUT_EVENTS = 128
<ide> MAX_INPUT_BUFFER = 1024
<ide> DEFAULT_WIDTH = 80
<ide> DEFAULT_HEIGHT = 24
<ide> type (
<ide> type WindowsTerminal struct {
<ide> outMutex sync.Mutex
<ide> inMutex sync.Mutex
<del> inputBuffer chan byte
<add> inputBuffer []byte
<add> inputSize int
<add> inputEvents []INPUT_RECORD
<ide> screenBufferInfo *CONSOLE_SCREEN_BUFFER_INFO
<ide> inputEscapeSequence []byte
<ide> }
<ide>
<ide> func StdStreams() (stdOut io.Writer, stdErr io.Writer, stdIn io.ReadCloser) {
<ide> handler := &WindowsTerminal{
<del> inputBuffer: make(chan byte, MAX_INPUT_BUFFER),
<add> inputBuffer: make([]byte, MAX_INPUT_BUFFER),
<ide> inputEscapeSequence: []byte(KEY_ESC_CSI),
<add> inputEvents: make([]INPUT_RECORD, MAX_INPUT_EVENTS),
<ide> }
<ide>
<ide> // Save current screen buffer info
<ide> func StdStreams() (stdOut io.Writer, stdErr io.Writer, stdIn io.ReadCloser) {
<ide>
<ide> // Set the window size
<ide> SetWindowSize(uintptr(handle), DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_HEIGHT)
<add> buffer = make([]CHAR_INFO, screenBufferInfo.MaximumWindowSize.X*screenBufferInfo.MaximumWindowSize.Y)
<add>
<ide> if IsTerminal(os.Stdout.Fd()) {
<ide> stdOut = &terminalWriter{
<ide> wrappedWriter: os.Stdout,
<ide> func getNumberOfChars(fromCoord COORD, toCoord COORD, screenSize COORD) uint32 {
<ide> return 0
<ide> }
<ide>
<add>var buffer []CHAR_INFO
<add>
<ide> func clearDisplayRect(fileDesc uintptr, fillChar rune, attributes WORD, fromCoord COORD, toCoord COORD, windowSize COORD) (bool, uint32, error) {
<ide> var writeRegion SMALL_RECT
<ide> writeRegion.Top = fromCoord.Y
<ide> func clearDisplayRect(fileDesc uintptr, fillChar rune, attributes WORD, fromCoor
<ide> height := toCoord.Y - fromCoord.Y + 1
<ide> size := width * height
<ide> if size > 0 {
<del> buffer := make([]CHAR_INFO, size)
<del> for i := 0; i < len(buffer); i++ {
<add> for i := 0; i < int(size); i++ {
<ide> buffer[i].UnicodeChar = WCHAR(fillChar)
<ide> buffer[i].Attributes = attributes
<ide> }
<ide>
<ide> // Write to buffer
<del> r, err := writeConsoleOutput(fileDesc, buffer, windowSize, COORD{X: 0, Y: 0}, &writeRegion)
<add> r, err := writeConsoleOutput(fileDesc, buffer[:size], windowSize, COORD{X: 0, Y: 0}, &writeRegion)
<ide> if !r {
<ide> if err != nil {
<ide> return false, 0, err
<ide> func (term *WindowsTerminal) HandleOutputCommand(fd uintptr, command []byte) (n
<ide>
<ide> // WriteChars writes the bytes to given writer.
<ide> func (term *WindowsTerminal) WriteChars(fd uintptr, w io.Writer, p []byte) (n int, err error) {
<add> if len(p) == 0 {
<add> return 0, nil
<add> }
<ide> return w.Write(p)
<ide> }
<ide>
<ide> func mapKeystokeToTerminalString(keyEvent *KEY_EVENT_RECORD, escapeSequence []by
<ide>
<ide> // getAvailableInputEvents polls the console for availble events
<ide> // The function does not return until at least one input record has been read.
<del>func getAvailableInputEvents(fd uintptr) (inputEvents []INPUT_RECORD, err error) {
<add>func getAvailableInputEvents(fd uintptr, inputEvents []INPUT_RECORD) (n int, err error) {
<ide> handle := syscall.Handle(fd)
<ide> if nil != err {
<del> return nil, err
<add> return 0, err
<ide> }
<ide> for {
<ide> // Read number of console events available
<del> tempBuffer := make([]INPUT_RECORD, MAX_INPUT_BUFFER)
<del> nr, err := readConsoleInputKey(uintptr(handle), tempBuffer)
<add> nr, err := readConsoleInputKey(uintptr(handle), inputEvents)
<ide> if nr == 0 {
<del> return nil, err
<add> return 0, err
<ide> }
<ide> if 0 < nr {
<del> retValue := make([]INPUT_RECORD, nr)
<del> for i := 0; i < nr; i++ {
<del> retValue[i] = tempBuffer[i]
<del> }
<del> return retValue, nil
<add> return nr, nil
<ide> }
<ide> }
<ide> }
<ide> func getTranslatedKeyCodes(inputEvents []INPUT_RECORD, escapeSequence []byte) st
<ide> }
<ide>
<ide> // ReadChars reads the characters from the given reader
<del>func (term *WindowsTerminal) ReadChars(fd uintptr, w io.Reader, p []byte) (n int, err error) {
<del> n = 0
<del> for n < len(p) {
<del> select {
<del> case b := <-term.inputBuffer:
<del> p[n] = b
<del> n++
<del> default:
<del> // Read at least one byte read
<del> if n > 0 {
<del> return n, nil
<del> }
<del> inputEvents, _ := getAvailableInputEvents(fd)
<del> if inputEvents != nil {
<del> if len(inputEvents) == 0 && nil != err {
<del> return n, err
<del> }
<del> if len(inputEvents) != 0 {
<del> keyCodes := getTranslatedKeyCodes(inputEvents, term.inputEscapeSequence)
<del> for _, b := range []byte(keyCodes) {
<del> term.inputBuffer <- b
<del> }
<del> }
<del> }
<add>func (term *WindowsTerminal) ReadChars(fd uintptr, r io.Reader, p []byte) (n int, err error) {
<add> for term.inputSize == 0 {
<add> nr, err := getAvailableInputEvents(fd, term.inputEvents)
<add> if nr == 0 && nil != err {
<add> return n, err
<add> }
<add> if nr > 0 {
<add> keyCodes := getTranslatedKeyCodes(term.inputEvents[:nr], term.inputEscapeSequence)
<add> term.inputSize = copy(term.inputBuffer, keyCodes)
<ide> }
<ide> }
<add> n = copy(p, term.inputBuffer[:term.inputSize])
<add> term.inputSize -= n
<ide> return n, nil
<ide> }
<ide> | 2 |
PHP | PHP | add strict parameter to inlist() and multiple() | fe0c7d348a8d4cb0ec6ce2bf083d6b9f9c6aa928 | <ide><path>lib/Cake/Test/Case/Utility/ValidationTest.php
<ide> public function testInList() {
<ide> $this->assertFalse(Validation::inList('three', array('one', 'two')));
<ide> $this->assertFalse(Validation::inList('1one', array(0, 1, 2, 3)));
<ide> $this->assertFalse(Validation::inList('one', array(0, 1, 2, 3)));
<add> $this->assertFalse(Validation::inList('2', array(1, 2, 3)));
<add> $this->assertTrue(Validation::inList('2', array(1, 2, 3), false));
<ide> }
<ide>
<ide> /**
<ide> public function testMultiple() {
<ide> $this->assertFalse(Validation::multiple(array('foo', 'bar', 'baz', 'squirrel'), array('min' => 10)));
<ide>
<ide> $this->assertTrue(Validation::multiple(array(0, 5, 9), array('in' => range(0, 10), 'max' => 5)));
<add> $this->assertFalse(Validation::multiple(array('0', '5', '9'), array('in' => range(0, 10), 'max' => 5)));
<add> $this->assertTrue(Validation::multiple(array('0', '5', '9'), array('in' => range(0, 10), 'max' => 5), false));
<ide> $this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 6, 2, 1), array('in' => range(0, 10), 'max' => 5)));
<ide> $this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 11), array('in' => range(0, 10), 'max' => 5)));
<ide>
<ide><path>lib/Cake/Utility/Validation.php
<ide> public static function money($check, $symbolPosition = 'left') {
<ide> *
<ide> * @param mixed $check Value to check
<ide> * @param mixed $options Options for the check.
<add> * @param boolean $strict Defaults to true, set to false to disable strict type check
<ide> * @return boolean Success
<ide> */
<del> public static function multiple($check, $options = array()) {
<add> public static function multiple($check, $options = array(), $strict = true) {
<ide> $defaults = array('in' => null, 'max' => null, 'min' => null);
<ide> $options = array_merge($defaults, $options);
<ide> $check = array_filter((array)$check);
<ide> public static function multiple($check, $options = array()) {
<ide> }
<ide> if ($options['in'] && is_array($options['in'])) {
<ide> foreach ($check as $val) {
<del> if (!in_array($val, $options['in'], true)) {
<add> if (!in_array($val, $options['in'], $strict)) {
<ide> return false;
<ide> }
<ide> }
<ide> public static function url($check, $strict = false) {
<ide> *
<ide> * @param string $check Value to check
<ide> * @param array $list List to check against
<add> * @param boolean $strict Defaults to true, set to false to disable strict type check
<ide> * @return boolean Success
<ide> */
<del> public static function inList($check, $list) {
<del> return in_array($check, $list, true);
<add> public static function inList($check, $list, $strict = true) {
<add> return in_array($check, $list, $strict);
<ide> }
<ide>
<ide> /** | 2 |
Mixed | Javascript | add unknownprotocol timeout | 47d6cedd8582764c20ffd55b0efa62e3730028c1 | <ide><path>doc/api/http2.md
<ide> added: v8.4.0
<ide> The `'unknownProtocol'` event is emitted when a connecting client fails to
<ide> negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler
<ide> receives the socket for handling. If no listener is registered for this event,
<del>the connection is terminated. See the [Compatibility API][].
<add>the connection is terminated. A timeout may be specified using the
<add>`'unknownProtocolTimeout'` option passed to [`http2.createSecureServer()`][].
<add>See the [Compatibility API][].
<ide>
<ide> #### `server.close([callback])`
<ide> <!-- YAML
<ide> Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument.
<ide> <!-- YAML
<ide> added: v8.4.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs-private/node-private/pull/246
<add> description: Added `unknownProtocolTimeout` option with a default of 10000.
<ide> - version:
<ide> - v14.4.0
<ide> - v12.18.0
<ide> changes:
<ide> `Http2ServerResponse` class to use.
<ide> Useful for extending the original `Http2ServerResponse`.
<ide> **Default:** `Http2ServerResponse`.
<add> * `unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that
<add> a server should wait when an [`'unknownProtocol'`][] is emitted. If the
<add> socket has not been destroyed by that time the server will destroy it.
<add> **Default:** `10000`.
<ide> * ...: Any [`net.createServer()`][] option can be provided.
<ide> * `onRequestHandler` {Function} See [Compatibility API][]
<ide> * Returns: {Http2Server}
<ide> server.listen(80);
<ide> <!-- YAML
<ide> added: v8.4.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs-private/node-private/pull/246
<add> description: Added `unknownProtocolTimeout` option with a default of 10000.
<ide> - version:
<ide> - v14.4.0
<ide> - v12.18.0
<ide> changes:
<ide> servers, the identity options (`pfx` or `key`/`cert`) are usually required.
<ide> * `origins` {string[]} An array of origin strings to send within an `ORIGIN`
<ide> frame immediately following creation of a new server `Http2Session`.
<add> * `unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that
<add> a server should wait when an [`'unknownProtocol'`][] event is emitted. If
<add> the socket has not been destroyed by that time the server will destroy it.
<add> **Default:** `10000`.
<ide> * `onRequestHandler` {Function} See [Compatibility API][]
<ide> * Returns: {Http2SecureServer}
<ide>
<ide> server.listen(80);
<ide> <!-- YAML
<ide> added: v8.4.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs-private/node-private/pull/246
<add> description: Added `unknownProtocolTimeout` option with a default of 10000.
<ide> - version:
<ide> - v14.4.0
<ide> - v12.18.0
<ide> changes:
<ide> instance passed to `connect` and the `options` object, and returns any
<ide> [`Duplex`][] stream that is to be used as the connection for this session.
<ide> * ...: Any [`net.connect()`][] or [`tls.connect()`][] options can be provided.
<add> * `unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that
<add> a server should wait when an [`'unknownProtocol'`][] event is emitted. If
<add> the socket has not been destroyed by that time the server will destroy it.
<add> **Default:** `10000`.
<ide> * `listener` {Function} Will be registered as a one-time listener of the
<ide> [`'connect'`][] event.
<ide> * Returns: {ClientHttp2Session}
<ide><path>lib/internal/http2/core.js
<ide> const { URL } = require('internal/url');
<ide> const net = require('net');
<ide> const { Duplex } = require('stream');
<ide> const tls = require('tls');
<del>const { setImmediate } = require('timers');
<add>const { setImmediate, setTimeout, clearTimeout } = require('timers');
<ide>
<ide> const {
<ide> kIncomingMessage,
<ide> function handleHeaderContinue(headers) {
<ide> this.emit('continue');
<ide> }
<ide>
<del>const setTimeout = {
<add>const setTimeoutValue = {
<ide> configurable: true,
<ide> enumerable: true,
<ide> writable: true,
<ide> value: setStreamTimeout
<ide> };
<del>ObjectDefineProperty(Http2Stream.prototype, 'setTimeout', setTimeout);
<del>ObjectDefineProperty(Http2Session.prototype, 'setTimeout', setTimeout);
<add>ObjectDefineProperty(Http2Stream.prototype, 'setTimeout', setTimeoutValue);
<add>ObjectDefineProperty(Http2Session.prototype, 'setTimeout', setTimeoutValue);
<ide>
<ide>
<ide> // When the socket emits an error, destroy the associated Http2Session and
<ide> function connectionListener(socket) {
<ide> debug('Unknown protocol from %s:%s',
<ide> socket.remoteAddress, socket.remotePort);
<ide> if (!this.emit('unknownProtocol', socket)) {
<add> debug('Unknown protocol timeout: %s', options.unknownProtocolTimeout);
<add> // Install a timeout if the socket was not successfully closed, then
<add> // destroy the socket to ensure that the underlying resources are
<add> // released.
<add> const timer = setTimeout(() => {
<add> if (!socket.destroyed) {
<add> debug('UnknownProtocol socket timeout, destroy socket');
<add> socket.destroy();
<add> }
<add> }, options.unknownProtocolTimeout);
<add> // Un-reference the timer to avoid blocking of application shutdown and
<add> // clear the timeout if the socket was successfully closed.
<add> timer.unref();
<add>
<add> socket.once('close', () => clearTimeout(timer));
<add>
<ide> // We don't know what to do, so let's just tell the other side what's
<ide> // going on in a format that they *might* understand.
<ide> socket.end('HTTP/1.0 403 Forbidden\r\n' +
<ide> function initializeOptions(options) {
<ide> );
<ide> }
<ide>
<add> if (options.unknownProtocolTimeout !== undefined)
<add> validateUint32(options.unknownProtocolTimeout, 'unknownProtocolTimeout');
<add> else
<add> // TODO(danbev): is this a good default value?
<add> options.unknownProtocolTimeout = 10000;
<add>
<add>
<ide> // Used only with allowHTTP1
<ide> options.Http1IncomingMessage = options.Http1IncomingMessage ||
<ide> http.IncomingMessage;
<ide><path>test/parallel/test-http2-server-unknown-protocol.js
<add>'use strict';
<add>const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<add>
<add>// This test verifies that when a server receives an unknownProtocol it will
<add>// not leave the socket open if the client does not close it.
<add>
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<add>const h2 = require('http2');
<add>const tls = require('tls');
<add>
<add>const server = h2.createSecureServer({
<add> key: fixtures.readKey('rsa_private.pem'),
<add> cert: fixtures.readKey('rsa_cert.crt'),
<add> unknownProtocolTimeout: 500,
<add> allowHalfOpen: true
<add>});
<add>
<add>server.on('connection', (socket) => {
<add> socket.on('close', common.mustCall(() => {
<add> server.close();
<add> }));
<add>});
<add>
<add>server.listen(0, function() {
<add> tls.connect({
<add> port: server.address().port,
<add> rejectUnauthorized: false,
<add> ALPNProtocols: ['bogus']
<add> });
<add>}); | 3 |
Ruby | Ruby | remove duplicated test | 7e7a60bd3fbfac9b02884f404bd31f3456f4022d | <ide><path>activestorage/test/service/gcs_service_test.rb
<ide> class ActiveStorage::Service::GCSServiceTest < ActiveSupport::TestCase
<ide> assert_match(/storage\.googleapis\.com\/.*response-content-disposition=inline.*test\.txt.*response-content-type=text%2Fplain/,
<ide> @service.url(@key, expires_in: 2.minutes, disposition: :inline, filename: ActiveStorage::Filename.new("test.txt"), content_type: "text/plain"))
<ide> end
<del>
<del> test "signed URL response headers" do
<del> begin
<del> key = SecureRandom.base58(24)
<del> data = "Something else entirely!"
<del> @service.upload(key, StringIO.new(data), checksum: Digest::MD5.base64digest(data))
<del>
<del> url = @service.url(key, expires_in: 2.minutes, disposition: :inline, filename: ActiveStorage::Filename.new("test.txt"), content_type: "text/plain")
<del> response = Net::HTTP.get_response(URI(url))
<del> assert_equal "text/plain", response.content_type
<del> ensure
<del> @service.delete key
<del> end
<del> end
<ide> end
<ide> else
<ide> puts "Skipping GCS Service tests because no GCS configuration was supplied" | 1 |
Text | Text | add a changelog entry for [ci skip] | cbb32ec24449bb4716551dee3392f9981cc6117b | <ide><path>actionpack/CHANGELOG.md
<add>* Don't let strong parameters mutate the given hash via `fetch`
<add>
<add> Create a new instance if the given parameter is a `Hash` instead of
<add> passing it to the `convert_hashes_to_parameters` method since it is
<add> overriding its default value.
<add>
<add> *Brendon Murphy*, *Doug Cole*
<add>
<ide> * Add `params` option to `button_to` form helper, which renders the given hash
<ide> as hidden form fields.
<ide> | 1 |
Go | Go | convert inspect to cobra | 851c388ad9aec0547ca7fde24c307b262eaab599 | <ide><path>api/client/commands.go
<ide> package client
<ide>
<ide> // Command returns a cli command handler if one exists
<ide> func (cli *DockerCli) Command(name string) func(...string) error {
<del> return map[string]func(...string) error{
<del> "inspect": cli.CmdInspect,
<del> }[name]
<add> return map[string]func(...string) error{}[name]
<ide> }
<ide><path>api/client/inspect.go
<del>package client
<del>
<del>import (
<del> "fmt"
<del>
<del> "golang.org/x/net/context"
<del>
<del> "github.com/docker/docker/api/client/inspect"
<del> Cli "github.com/docker/docker/cli"
<del> flag "github.com/docker/docker/pkg/mflag"
<del> "github.com/docker/engine-api/client"
<del>)
<del>
<del>// CmdInspect displays low-level information on one or more containers, images or tasks.
<del>//
<del>// Usage: docker inspect [OPTIONS] CONTAINER|IMAGE|TASK [CONTAINER|IMAGE|TASK...]
<del>func (cli *DockerCli) CmdInspect(args ...string) error {
<del> cmd := Cli.Subcmd("inspect", []string{"[OPTIONS] CONTAINER|IMAGE|TASK [CONTAINER|IMAGE|TASK...]"}, Cli.DockerCommands["inspect"].Description, true)
<del> tmplStr := cmd.String([]string{"f", "-format"}, "", "Format the output using the given go template")
<del> inspectType := cmd.String([]string{"-type"}, "", "Return JSON for specified type, (e.g image, container or task)")
<del> size := cmd.Bool([]string{"s", "-size"}, false, "Display total file sizes if the type is container")
<del> cmd.Require(flag.Min, 1)
<del>
<del> cmd.ParseFlags(args, true)
<del>
<del> if *inspectType != "" && *inspectType != "container" && *inspectType != "image" && *inspectType != "task" {
<del> return fmt.Errorf("%q is not a valid value for --type", *inspectType)
<del> }
<del>
<del> ctx := context.Background()
<del>
<del> var elementSearcher inspect.GetRefFunc
<del> switch *inspectType {
<del> case "container":
<del> elementSearcher = cli.inspectContainers(ctx, *size)
<del> case "image":
<del> elementSearcher = cli.inspectImages(ctx, *size)
<del> case "task":
<del> if *size {
<del> fmt.Fprintln(cli.err, "WARNING: --size ignored for tasks")
<del> }
<del> elementSearcher = cli.inspectTasks(ctx)
<del> default:
<del> elementSearcher = cli.inspectAll(ctx, *size)
<del> }
<del>
<del> return inspect.Inspect(cli.out, cmd.Args(), *tmplStr, elementSearcher)
<del>}
<del>
<del>func (cli *DockerCli) inspectContainers(ctx context.Context, getSize bool) inspect.GetRefFunc {
<del> return func(ref string) (interface{}, []byte, error) {
<del> return cli.client.ContainerInspectWithRaw(ctx, ref, getSize)
<del> }
<del>}
<del>
<del>func (cli *DockerCli) inspectImages(ctx context.Context, getSize bool) inspect.GetRefFunc {
<del> return func(ref string) (interface{}, []byte, error) {
<del> return cli.client.ImageInspectWithRaw(ctx, ref, getSize)
<del> }
<del>}
<del>
<del>func (cli *DockerCli) inspectTasks(ctx context.Context) inspect.GetRefFunc {
<del> return func(ref string) (interface{}, []byte, error) {
<del> return cli.client.TaskInspectWithRaw(ctx, ref)
<del> }
<del>}
<del>
<del>func (cli *DockerCli) inspectAll(ctx context.Context, getSize bool) inspect.GetRefFunc {
<del> return func(ref string) (interface{}, []byte, error) {
<del> c, rawContainer, err := cli.client.ContainerInspectWithRaw(ctx, ref, getSize)
<del> if err != nil {
<del> // Search for image with that id if a container doesn't exist.
<del> if client.IsErrContainerNotFound(err) {
<del> i, rawImage, err := cli.client.ImageInspectWithRaw(ctx, ref, getSize)
<del> if err != nil {
<del> if client.IsErrImageNotFound(err) {
<del> // Search for task with that id if an image doesn't exists.
<del> t, rawTask, err := cli.client.TaskInspectWithRaw(ctx, ref)
<del> if err != nil {
<del> return nil, nil, fmt.Errorf("Error: No such image, container or task: %s", ref)
<del> }
<del> if getSize {
<del> fmt.Fprintln(cli.err, "WARNING: --size ignored for tasks")
<del> }
<del> return t, rawTask, nil
<del> }
<del> return nil, nil, err
<del> }
<del> return i, rawImage, nil
<del> }
<del> return nil, nil, err
<del> }
<del> return c, rawContainer, nil
<del> }
<del>}
<ide><path>api/client/system/inspect.go
<add>package system
<add>
<add>import (
<add> "fmt"
<add>
<add> "golang.org/x/net/context"
<add>
<add> "github.com/docker/docker/api/client"
<add> "github.com/docker/docker/api/client/inspect"
<add> "github.com/docker/docker/cli"
<add> apiclient "github.com/docker/engine-api/client"
<add> "github.com/spf13/cobra"
<add>)
<add>
<add>type inspectOptions struct {
<add> format string
<add> inspectType string
<add> size bool
<add> ids []string
<add>}
<add>
<add>// NewInspectCommand creates a new cobra.Command for `docker inspect`
<add>func NewInspectCommand(dockerCli *client.DockerCli) *cobra.Command {
<add> var opts inspectOptions
<add>
<add> cmd := &cobra.Command{
<add> Use: "inspect [OPTIONS] CONTAINER|IMAGE|TASK [CONTAINER|IMAGE|TASK...]",
<add> Short: "Return low-level information on a container, image or task",
<add> Args: cli.RequiresMinArgs(1),
<add> RunE: func(cmd *cobra.Command, args []string) error {
<add> opts.ids = args
<add> return runInspect(dockerCli, opts)
<add> },
<add> }
<add>
<add> flags := cmd.Flags()
<add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template")
<add> flags.StringVar(&opts.inspectType, "type", "", "Return JSON for specified type, (e.g image, container or task)")
<add> flags.BoolVarP(&opts.size, "size", "s", false, "Display total file sizes if the type is container")
<add>
<add> return cmd
<add>}
<add>
<add>func runInspect(dockerCli *client.DockerCli, opts inspectOptions) error {
<add> ctx := context.Background()
<add> client := dockerCli.Client()
<add>
<add> var getRefFunc inspect.GetRefFunc
<add> switch opts.inspectType {
<add> case "container":
<add> getRefFunc = func(ref string) (interface{}, []byte, error) {
<add> return client.ContainerInspectWithRaw(ctx, ref, opts.size)
<add> }
<add> case "image":
<add> getRefFunc = func(ref string) (interface{}, []byte, error) {
<add> return client.ImageInspectWithRaw(ctx, ref, opts.size)
<add> }
<add> case "task":
<add> if opts.size {
<add> fmt.Fprintln(dockerCli.Err(), "WARNING: --size ignored for tasks")
<add> }
<add> getRefFunc = func(ref string) (interface{}, []byte, error) {
<add> return client.TaskInspectWithRaw(ctx, ref)
<add> }
<add> case "":
<add> getRefFunc = inspectAll(ctx, dockerCli, opts.size)
<add> default:
<add> return fmt.Errorf("%q is not a valid value for --type", opts.inspectType)
<add> }
<add>
<add> return inspect.Inspect(dockerCli.Out(), opts.ids, opts.format, getRefFunc)
<add>}
<add>
<add>func inspectAll(ctx context.Context, dockerCli *client.DockerCli, getSize bool) inspect.GetRefFunc {
<add> client := dockerCli.Client()
<add>
<add> return func(ref string) (interface{}, []byte, error) {
<add> c, rawContainer, err := client.ContainerInspectWithRaw(ctx, ref, getSize)
<add> if err == nil || !apiclient.IsErrNotFound(err) {
<add> return c, rawContainer, err
<add> }
<add> // Search for image with that id if a container doesn't exist.
<add> i, rawImage, err := client.ImageInspectWithRaw(ctx, ref, getSize)
<add> if err == nil || !apiclient.IsErrNotFound(err) {
<add> return i, rawImage, err
<add> }
<add>
<add> // Search for task with that id if an image doesn't exists.
<add> t, rawTask, err := client.TaskInspectWithRaw(ctx, ref)
<add> if err == nil || !apiclient.IsErrNotFound(err) {
<add> if getSize {
<add> fmt.Fprintln(dockerCli.Err(), "WARNING: --size ignored for tasks")
<add> }
<add> return t, rawTask, err
<add> }
<add> return nil, nil, fmt.Errorf("Error: No such image, container or task: %s", ref)
<add> }
<add>}
<ide><path>cli/cobraadaptor/adaptor.go
<ide> func NewCobraAdaptor(clientFlags *cliflags.ClientFlags) CobraAdaptor {
<ide> image.NewTagCommand(dockerCli),
<ide> network.NewNetworkCommand(dockerCli),
<ide> system.NewEventsCommand(dockerCli),
<add> system.NewInspectCommand(dockerCli),
<ide> registry.NewLoginCommand(dockerCli),
<ide> registry.NewLogoutCommand(dockerCli),
<ide> system.NewVersionCommand(dockerCli),
<ide><path>cli/usage.go
<ide> type Command struct {
<ide> }
<ide>
<ide> // DockerCommandUsage lists the top level docker commands and their short usage
<del>var DockerCommandUsage = []Command{
<del> {"inspect", "Return low-level information on a container, image or task"},
<del>}
<add>var DockerCommandUsage = []Command{}
<ide>
<ide> // DockerCommands stores all the docker command
<ide> var DockerCommands = make(map[string]Command) | 5 |
Text | Text | update changelog for 1.3.0-rc.4 and 1.2.26 | 84912134d5253be72079396099ab4322eb6b8f9a | <ide><path>CHANGELOG.md
<add><a name="1.3.0-rc.4"></a>
<add># 1.3.0-rc.4 unicorn-hydrafication (2014-10-01)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$compile:**
<add> - get $$observe listeners array as own property
<add> ([a27d827c](https://github.com/angular/angular.js/commit/a27d827c22b0b6b3ba6b7495cf4fc338c6934b37),
<add> [#9343](https://github.com/angular/angular.js/issues/9343), [#9345](https://github.com/angular/angular.js/issues/9345))
<add> - Resolve leak with asynchronous compilation
<add> ([6303c3dc](https://github.com/angular/angular.js/commit/6303c3dcf64685458fc84aa12289f5c9d57f4e47),
<add> [#9199](https://github.com/angular/angular.js/issues/9199), [#9079](https://github.com/angular/angular.js/issues/9079), [#8504](https://github.com/angular/angular.js/issues/8504), [#9197](https://github.com/angular/angular.js/issues/9197))
<add> - connect transclude scopes to their containing scope to prevent memory leaks
<add> ([fb0c77f0](https://github.com/angular/angular.js/commit/fb0c77f0b66ed757a56af13f81b943419fdcbd7f),
<add> [#9095](https://github.com/angular/angular.js/issues/9095), [#9281](https://github.com/angular/angular.js/issues/9281))
<add> - sanitize srcset attribute
<add> ([ab80cd90](https://github.com/angular/angular.js/commit/ab80cd90661396dbb1c94c5f4dd2d11ee8f6b6af))
<add>- **input:**
<add> - register builtin parsers/formatters before anyone else
<add> ([10644432](https://github.com/angular/angular.js/commit/10644432ca9d5da69ce790a8d9e691640f333711),
<add> [#9218](https://github.com/angular/angular.js/issues/9218), [#9358](https://github.com/angular/angular.js/issues/9358))
<add> - correctly handle invalid model values for `input[date/time/…]`
<add> ([a0bfdd0d](https://github.com/angular/angular.js/commit/a0bfdd0d60882125f614a91c321f12f730735e7b),
<add> [#8949](https://github.com/angular/angular.js/issues/8949), [#9375](https://github.com/angular/angular.js/issues/9375))
<add>- **ngModel:** do not parse undefined viewValue when validating
<add> ([92f05e5a](https://github.com/angular/angular.js/commit/92f05e5a5900713301e64373d7b7daa45a88278b),
<add> [#9106](https://github.com/angular/angular.js/issues/9106), [#9260](https://github.com/angular/angular.js/issues/9260))
<add>- **ngView:** use animation promises ensure that only one leave animation occurs at a time
<add> ([3624e380](https://github.com/angular/angular.js/commit/3624e3800fb3ccd2e9ea361a763e20131fd42c29),
<add> [#9355](https://github.com/angular/angular.js/issues/9355), [#7606](https://github.com/angular/angular.js/issues/7606), [#9374](https://github.com/angular/angular.js/issues/9374))
<add>- **select:** make ctrl.hasOption method consistent
<add> ([2bcd02dc](https://github.com/angular/angular.js/commit/2bcd02dc1a6b28b357d47c83be3bed5c9a38417c),
<add> [#8761](https://github.com/angular/angular.js/issues/8761))
<add>
<add>
<add>## Features
<add>
<add>- **$compile:** optionally get controllers from ancestors only
<add> ([07e3abc7](https://github.com/angular/angular.js/commit/07e3abc7dda872adc3fb25cb3e133f86f494b35d),
<add> [#4518](https://github.com/angular/angular.js/issues/4518), [#4540](https://github.com/angular/angular.js/issues/4540), [#8240](https://github.com/angular/angular.js/issues/8240), [#8511](https://github.com/angular/angular.js/issues/8511))
<add>- **Scope:** allow the parent of a new scope to be specified on creation
<add> ([6417a3e9](https://github.com/angular/angular.js/commit/6417a3e9eb7ab0011cefada8db855aa929a64ff8))
<add>
<add>
<add>## Performance Improvements
<add>
<add>- **$rootScope:** moving internal queues out of the Scope instances
<add> ([b1192518](https://github.com/angular/angular.js/commit/b119251827cea670051198e1b48af7ee0c9f2a1b),
<add> [#9071](https://github.com/angular/angular.js/issues/9071))
<add>- **benchmark:** add ngBindOnce benchmarks to largetable-bp
<add> ([2c8b4648](https://github.com/angular/angular.js/commit/2c8b4648526acf5c2645de8408a6d9ace2144b5f))
<add>- **ngForm,ngModel:** move initial addClass to the compile phase
<add> ([b1ee5386](https://github.com/angular/angular.js/commit/b1ee5386d584f208bce6d3b613afdb3bae9df76a),
<add> [#8268](https://github.com/angular/angular.js/issues/8268))
<add>
<add>
<add>## Breaking Changes
<add>
<add>- **$compile:** due to [fb0c77f0](https://github.com/angular/angular.js/commit/fb0c77f0b66ed757a56af13f81b943419fdcbd7f),
<add>
<add>
<add>`$transclude` functions no longer attach `$destroy` event handlers to the
<add>transcluded content, and so the associated transclude scope will not automatically
<add>be destroyed if you remove a transcluded element from the DOM using direct DOM
<add>manipulation such as the jquery `remove()` method.
<add>
<add>If you want to explicitly remove DOM elements inside your directive that have
<add>been compiled, and so potentially contain child (and transcluded) scopes, then
<add>it is your responsibility to get hold of the scope and destroy it at the same time.
<add>
<add>The suggested approach is to create a new child scope of your own around any DOM
<add>elements that you wish to manipulate in this way and destroy those scopes if you
<add>remove their contents - any child scopes will then be destroyed and cleaned up
<add>automatically.
<add>
<add>Note that all the built-in directives that manipulate the DOM (ngIf, ngRepeat,
<add>ngSwitch, etc) already follow this best practice, so if you only use these for
<add>manipulating the DOM then you do not have to worry about this change.
<add>
<add>Closes #9095
<add>Closes #9281
<add>
<add>- **$parse:** due to [5572b40b](https://github.com/angular/angular.js/commit/5572b40b15ed06969c8e0e92866c5afd088484b4),
<add>
<add>- $scope['this'] no longer exits on the $scope object
<add>- $parse-ed expressions no longer allow chaining 'this' such as this['this'] or $parent['this']
<add>- 'this' in $parse-ed expressions can no longer be overriden, if a variable named 'this' is put on the scope it must be accessed using this['this']
<add>
<add>Closes #9105
<add>
<add>- **input:** due to [1eda1836](https://github.com/angular/angular.js/commit/1eda18365a348c9597aafba9d195d345e4f13d1e),
<add>
<add>(Note: this change landed in 1.3.0-rc.3, but was not considered a breaking change at the time).
<add>
<add>For text based inputs (text, email, url), the `$viewValue` will now always be converted to a string,
<add>regardless of what type the value is on the model.
<add>
<add>To migrate, any code or expressions that expect the `$viewValue` to be anything other than string
<add>should be updated to expect a string.
<add>
<add>
<add>- **input:** due to a0bfdd0d60882125f614a91c321f12f730735e7b (see #8949),
<add>
<add>Similar to `input[number]` Angular will now throw if the model value
<add>for a `input[date]` is not a `Date` object. Previously, Angular only
<add>showed an empty string instead.
<add>Angular does not set validation errors on the `<input>` in this case
<add>as those errors are shown to the user, but the erroneous state was
<add>caused by incorrect application logic and not by the user.
<add>
<ide> <a name="1.2.26"></a>
<ide> # 1.2.26 zucchini-expansion (2014-10-01)
<ide>
<del>
<ide> ## Bug Fixes
<ide>
<add>
<ide> - **$compile:** Resolve leak with asynchronous compilation
<ide> ([5c9c1973](https://github.com/angular/angular.js/commit/5c9c19730526d5df6f16c523e578e5305f3796d0),
<ide> [#9199](https://github.com/angular/angular.js/issues/9199), [#9079](https://github.com/angular/angular.js/issues/9079), [#8504](https://github.com/angular/angular.js/issues/8504), [#9197](https://github.com/angular/angular.js/issues/9197)) | 1 |
Javascript | Javascript | add more comments | 80eff968292ab1024efbba6f55114ae2bba66579 | <ide><path>lib/string_decoder.js
<ide> function assertEncoding(encoding) {
<ide> }
<ide> }
<ide>
<add>// StringDecoder provides an interface for efficiently splitting a series of
<add>// buffers into a series of JS strings without breaking apart multi-byte
<add>// characters. CESU-8 is handled as part of the UTF-8 encoding.
<add>//
<add>// @TODO Handling all encodings inside a single object makes it very difficult
<add>// to reason about this code, so it should be split up in the future.
<add>// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
<add>// points as used by CESU-8.
<ide> var StringDecoder = exports.StringDecoder = function(encoding) {
<ide> this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
<ide> assertEncoding(encoding);
<ide> var StringDecoder = exports.StringDecoder = function(encoding) {
<ide> return;
<ide> }
<ide>
<add> // Enough space to store all bytes of a single character. UTF-8 needs 4
<add> // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
<ide> this.charBuffer = new Buffer(6);
<add> // Number of bytes received for the current incomplete multi-byte character.
<ide> this.charReceived = 0;
<add> // Number of bytes expected for the current incomplete multi-byte character.
<ide> this.charLength = 0;
<ide> };
<ide>
<ide>
<add>// write decodes the given buffer and returns it as JS string that is
<add>// guaranteed to not contain any partial multi-byte characters. Any partial
<add>// character found at the end of the buffer is buffered up, and will be
<add>// returned when calling write again with the remaining bytes.
<add>//
<add>// Note: Converting a Buffer containing an orphan surrogate to a String
<add>// currently works, but converting a String to a Buffer (via `new Buffer`, or
<add>// Buffer#write) will replace incomplete surrogates with the unicode
<add>// replacement character. See https://codereview.chromium.org/121173009/ .
<ide> StringDecoder.prototype.write = function(buffer) {
<ide> var charStr = '';
<ide> // if our last write ended with an incomplete multibyte character
<ide> StringDecoder.prototype.write = function(buffer) {
<ide> return charStr;
<ide> };
<ide>
<add>// detectIncompleteChar determines if there is an incomplete UTF-8 character at
<add>// the end of the given buffer. If so, it sets this.charLength to the byte
<add>// length that character, and sets this.charReceived to the number of bytes
<add>// that are available for this character.
<ide> StringDecoder.prototype.detectIncompleteChar = function(buffer) {
<ide> // determine how many bytes we have to check at the end of this buffer
<ide> var i = (buffer.length >= 3) ? 3 : buffer.length; | 1 |
Javascript | Javascript | kill reactmount.getnode/getid/purgeid with fire | 4ba0e95a96507abbcb2819be328fc3d1ed3cc80f | <ide><path>src/renderers/dom/client/ReactMount.js
<ide> var ReactUpdateQueue = require('ReactUpdateQueue');
<ide> var ReactUpdates = require('ReactUpdates');
<ide>
<ide> var emptyObject = require('emptyObject');
<del>var containsNode = require('containsNode');
<ide> var instantiateReactComponent = require('instantiateReactComponent');
<ide> var invariant = require('invariant');
<ide> var setInnerHTML = require('setInnerHTML');
<ide> var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
<ide> var warning = require('warning');
<ide>
<ide> var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
<del>var nodeCache = {};
<ide>
<ide> var ELEMENT_NODE_TYPE = 1;
<ide> var DOC_NODE_TYPE = 9;
<ide> if (__DEV__) {
<ide> var rootElementsByReactRootID = {};
<ide> }
<ide>
<del>// Used to store breadth-first search state in findComponentRoot.
<del>var findComponentRootReusableArray = [];
<del>
<ide> /**
<ide> * Finds the index of the first character
<ide> * that's not common between the two given strings.
<ide> function getReactRootID(container) {
<ide> return rootElement && internalGetID(rootElement);
<ide> }
<ide>
<del>/**
<del> * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
<del> * element can return its control whose name or ID equals ATTR_NAME. All
<del> * DOM nodes support `getAttributeNode` but this can also get called on
<del> * other objects so just return '' if we're given something other than a
<del> * DOM node (such as window).
<del> *
<del> * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
<del> * @return {string} ID of the supplied `domNode`.
<del> */
<del>function getID(node) {
<del> var id = internalGetID(node);
<del> if (id) {
<del> var cached = nodeCache[id];
<del> // TODO: Fix this whole concept of "validity" -- the cache just shouldn't
<del> // have nodes that have been unmounted.
<del> invariant(
<del> !cached || cached === node || !isValid(cached, id),
<del> 'ReactMount: Two valid but unequal nodes with the same `%s`: %s',
<del> ATTR_NAME, id
<del> );
<del> nodeCache[id] = node;
<del> }
<del>
<del> return id;
<del>}
<del>
<ide> function internalGetID(node) {
<ide> // If node is something like a window, document, or text node, none of
<ide> // which support attributes or a .getAttribute method, gracefully return
<ide> // the empty string, as if the attribute were missing.
<ide> return node && node.getAttribute && node.getAttribute(ATTR_NAME) || '';
<ide> }
<ide>
<del>/**
<del> * Sets the React-specific ID of the given node.
<del> *
<del> * @param {DOMElement} node The DOM node whose ID will be set.
<del> * @param {string} id The value of the ID attribute.
<del> */
<del>function setID(node, id) {
<del> var oldID = internalGetID(node);
<del> if (oldID !== id) {
<del> delete nodeCache[oldID];
<del> }
<del> node.setAttribute(ATTR_NAME, id);
<del> nodeCache[id] = node;
<del>}
<del>
<del>/**
<del> * Finds the node with the supplied ID if present in the cache.
<del> */
<del>function getNodeIfCached(id) {
<del> var node = nodeCache[id];
<del> // TODO: Fix this whole concept of "validity" -- the cache just shouldn't have
<del> // nodes that have been unmounted.
<del> if (node && isValid(node, id)) {
<del> return node;
<del> }
<del>}
<del>
<del>/**
<del> * Finds the node with the supplied React-generated DOM ID.
<del> *
<del> * @param {string} id A React-generated DOM ID.
<del> * @return {DOMElement} DOM node with the suppled `id`.
<del> * @internal
<del> */
<del>function getNode(id) {
<del> var node = getNodeIfCached(id);
<del> if (node) {
<del> return node;
<del> } else {
<del> return nodeCache[id] = ReactMount.findReactNodeByID(id);
<del> }
<del>}
<del>
<del>/**
<del> * A node is "valid" if it is contained by a currently mounted container.
<del> *
<del> * This means that the node does not have to be contained by a document in
<del> * order to be considered valid.
<del> *
<del> * @param {?DOMElement} node The candidate DOM node.
<del> * @param {string} id The expected ID of the node.
<del> * @return {boolean} Whether the node is contained by a mounted container.
<del> */
<del>function isValid(node, id) {
<del> if (node) {
<del> invariant(
<del> internalGetID(node) === id,
<del> 'ReactMount: Unexpected modification of `%s`',
<del> ATTR_NAME
<del> );
<del>
<del> var container = ReactMount.findReactContainerForID(id);
<del> if (container && containsNode(container, node)) {
<del> return true;
<del> }
<del> }
<del>
<del> return false;
<del>}
<del>
<del>/**
<del> * Causes the cache to forget about one React-specific ID.
<del> *
<del> * @param {string} id The ID to forget.
<del> */
<del>function purgeID(id) {
<del> delete nodeCache[id];
<del>}
<del>
<del>var deepestNodeSoFar = null;
<del>function findDeepestCachedAncestorImpl(ancestorID) {
<del> var ancestor = getNodeIfCached(ancestorID);
<del> if (ancestor) {
<del> deepestNodeSoFar = ancestor;
<del> } else {
<del> // This node isn't populated in the cache, so presumably none of its
<del> // descendants are. Break out of the loop.
<del> return false;
<del> }
<del>}
<del>
<del>/**
<del> * Return the deepest cached node whose ID is a prefix of `targetID`.
<del> */
<del>function findDeepestCachedAncestor(targetID) {
<del> deepestNodeSoFar = null;
<del> ReactInstanceHandles.traverseAncestors(
<del> targetID,
<del> findDeepestCachedAncestorImpl
<del> );
<del>
<del> var foundNode = deepestNodeSoFar;
<del> deepestNodeSoFar = null;
<del> return foundNode;
<del>}
<del>
<ide> /**
<ide> * Mounts this component and inserts it into the DOM.
<ide> *
<ide> function hasNonRootReactChild(node) {
<ide> ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false;
<ide> }
<ide>
<del>/**
<del> * Returns the first (deepest) ancestor of a node which is rendered by this copy
<del> * of React.
<del> */
<del>function findFirstReactDOMImpl(node) {
<del> // This node might be from another React instance, so we make sure not to
<del> // examine the node cache here
<del> for (; node && node.parentNode !== node; node = node.parentNode) {
<del> if (node.nodeType !== 1) {
<del> // Not a DOMElement, therefore not a React component
<del> continue;
<del> }
<del> var nodeID = internalGetID(node);
<del> if (!nodeID) {
<del> continue;
<del> }
<del> var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
<del>
<del> // If containersByReactRootID contains the container we find by crawling up
<del> // the tree, we know that this instance of React rendered the node.
<del> // nb. isValid's strategy (with containsNode) does not work because render
<del> // trees may be nested and we don't want a false positive in that case.
<del> var current = node;
<del> var lastID;
<del> do {
<del> lastID = internalGetID(current);
<del> current = current.parentNode;
<del> if (current == null) {
<del> // The passed-in node has been detached from the container it was
<del> // originally rendered into.
<del> return null;
<del> }
<del> } while (lastID !== reactRootID);
<del>
<del> if (current === containersByReactRootID[reactRootID]) {
<del> return node;
<del> }
<del> }
<del> return null;
<del>}
<del>
<ide> /**
<ide> * Temporary (?) hack so that we can store all top-level pending updates on
<ide> * composites instead of having to worry about different types of components
<ide> var ReactMount = {
<ide> return true;
<ide> },
<ide>
<del> /**
<del> * Finds the container DOM element that contains React component to which the
<del> * supplied DOM `id` belongs.
<del> *
<del> * @param {string} id The ID of an element rendered by a React component.
<del> * @return {?DOMElement} DOM element that contains the `id`.
<del> */
<del> findReactContainerForID: function(id) {
<del> var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
<del> var container = containersByReactRootID[reactRootID];
<del>
<del> if (__DEV__) {
<del> var rootElement = rootElementsByReactRootID[reactRootID];
<del> if (rootElement && rootElement.parentNode !== container) {
<del> warning(
<del> // Call internalGetID here because getID calls isValid which calls
<del> // findReactContainerForID (this function).
<del> internalGetID(rootElement) === reactRootID,
<del> 'ReactMount: Root element ID differed from reactRootID.'
<del> );
<del> var containerChild = container.firstChild;
<del> if (containerChild &&
<del> reactRootID === internalGetID(containerChild)) {
<del> // If the container has a new child with the same ID as the old
<del> // root element, then rootElementsByReactRootID[reactRootID] is
<del> // just stale and needs to be updated. The case that deserves a
<del> // warning is when the container is empty.
<del> rootElementsByReactRootID[reactRootID] = containerChild;
<del> } else {
<del> warning(
<del> false,
<del> 'ReactMount: Root element has been removed from its original ' +
<del> 'container. New container: %s',
<del> rootElement.parentNode
<del> );
<del> }
<del> }
<del> }
<del>
<del> return container;
<del> },
<del>
<del> /**
<del> * Finds an element rendered by React with the supplied ID.
<del> *
<del> * @param {string} id ID of a DOM node in the React component.
<del> * @return {DOMElement} Root DOM node of the React component.
<del> */
<del> findReactNodeByID: function(id) {
<del> var reactRoot = ReactMount.findReactContainerForID(id);
<del> return ReactMount.findComponentRoot(reactRoot, id);
<del> },
<del>
<del> /**
<del> * Traverses up the ancestors of the supplied node to find a node that is a
<del> * DOM representation of a React component rendered by this copy of React.
<del> *
<del> * @param {*} node
<del> * @return {?DOMEventTarget}
<del> * @internal
<del> */
<del> getFirstReactDOM: function(node) {
<del> return findFirstReactDOMImpl(node);
<del> },
<del>
<del> /**
<del> * Finds a node with the supplied `targetID` inside of the supplied
<del> * `ancestorNode`. Exploits the ID naming scheme to perform the search
<del> * quickly.
<del> *
<del> * @param {DOMEventTarget} ancestorNode Search from this root.
<del> * @pararm {string} targetID ID of the DOM representation of the component.
<del> * @return {DOMEventTarget} DOM node with the supplied `targetID`.
<del> * @internal
<del> */
<del> findComponentRoot: function(ancestorNode, targetID) {
<del> var firstChildren = findComponentRootReusableArray;
<del> var childIndex = 0;
<del>
<del> var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode;
<del>
<del> if (__DEV__) {
<del> // This will throw on the next line; give an early warning
<del> warning(
<del> deepestAncestor != null,
<del> 'React can\'t find the root component node for data-reactid value ' +
<del> '`%s`. If you\'re seeing this message, it probably means that ' +
<del> 'you\'ve loaded two copies of React on the page. At this time, only ' +
<del> 'a single copy of React can be loaded at a time.',
<del> targetID
<del> );
<del> }
<del>
<del> firstChildren[0] = deepestAncestor.firstChild;
<del> firstChildren.length = 1;
<del>
<del> while (childIndex < firstChildren.length) {
<del> var child = firstChildren[childIndex++];
<del> var targetChild;
<del>
<del> while (child) {
<del> var childID = ReactMount.getID(child);
<del> if (childID) {
<del> // Even if we find the node we're looking for, we finish looping
<del> // through its siblings to ensure they're cached so that we don't have
<del> // to revisit this node again. Otherwise, we make n^2 calls to getID
<del> // when visiting the many children of a single node in order.
<del>
<del> if (targetID === childID) {
<del> targetChild = child;
<del> } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) {
<del> // If we find a child whose ID is an ancestor of the given ID,
<del> // then we can be sure that we only want to search the subtree
<del> // rooted at this child, so we can throw out the rest of the
<del> // search state.
<del> firstChildren.length = childIndex = 0;
<del> firstChildren.push(child.firstChild);
<del> }
<del>
<del> } else {
<del> // If this child had no ID, then there's a chance that it was
<del> // injected automatically by the browser, as when a `<table>`
<del> // element sprouts an extra `<tbody>` child as a side effect of
<del> // `.innerHTML` parsing. Optimistically continue down this
<del> // branch, but not before examining the other siblings.
<del> firstChildren.push(child.firstChild);
<del> }
<del>
<del> child = child.nextSibling;
<del> }
<del>
<del> if (targetChild) {
<del> // Emptying firstChildren/findComponentRootReusableArray is
<del> // not necessary for correctness, but it helps the GC reclaim
<del> // any nodes that were left at the end of the search.
<del> firstChildren.length = 0;
<del>
<del> return targetChild;
<del> }
<del> }
<del>
<del> firstChildren.length = 0;
<del>
<del> invariant(
<del> false,
<del> 'findComponentRoot(..., %s): Unable to find element. This probably ' +
<del> 'means the DOM was unexpectedly mutated (e.g., by the browser), ' +
<del> 'usually due to forgetting a <tbody> when using tables, nesting tags ' +
<del> 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' +
<del> 'parent. ' +
<del> 'Try inspecting the child nodes of the element with React ID `%s`.',
<del> targetID,
<del> ReactMount.getID(ancestorNode)
<del> );
<del> },
<del>
<ide> _mountImageIntoNode: function(
<ide> markup,
<ide> container,
<ide> var ReactMount = {
<ide> ReactDOMComponentTree.precacheNode(instance, container.firstChild);
<ide> }
<ide> },
<del>
<del> /**
<del> * React ID utilities.
<del> */
<del>
<del> getReactRootID: getReactRootID,
<del>
<del> getID: getID,
<del>
<del> setID: setID,
<del>
<del> getNode: getNode,
<del>
<del> isValid: isValid,
<del>
<del> purgeID: purgeID,
<ide> };
<ide>
<ide> ReactPerf.measureMethods(ReactMount, 'ReactMount', {
<ide><path>src/renderers/dom/client/__tests__/ReactMount-test.js
<ide> describe('ReactMount', function() {
<ide> );
<ide> });
<ide>
<del> it('should not crash in node cache when unmounting', function() {
<del> var Component = React.createClass({
<del> render: function() {
<del> // Add refs to some nodes so that they get traversed and cached
<del> return (
<del> <div ref="a">
<del> <div ref="b">b</div>
<del> {this.props.showC && <div>c</div>}
<del> </div>
<del> );
<del> },
<del> });
<del>
<del> var container = document.createElement('container');
<del>
<del> ReactDOM.render(<div><Component showC={false} /></div>, container);
<del>
<del> // Right now, A and B are in the cache. When we add C, it won't get added to
<del> // the cache (assuming markup-string mode).
<del> ReactDOM.render(<div><Component showC={true} /></div>, container);
<del>
<del> // Remove A, B, and C. Unmounting C shouldn't cause B to get recached.
<del> ReactDOM.render(<div></div>, container);
<del>
<del> // Add them back -- this shouldn't cause a cached node collision.
<del> ReactDOM.render(<div><Component showC={true} /></div>, container);
<del>
<del> ReactDOM.unmountComponentAtNode(container);
<del> });
<del>
<del> it('should not crash in node cache when unmounting, case 2', function() {
<del> var A = React.createClass({
<del> render: function() {
<del> return <a key={this.props.innerKey}>{this.props.innerKey}</a>;
<del> },
<del> });
<del> var Component = React.createClass({
<del> render: function() {
<del> return (
<del> <b>
<del> <i>{this.props.step === 1 && <q />}</i>
<del> {this.props.step === 1 && <A innerKey={this.props.step} />}
<del> </b>
<del> );
<del> },
<del> });
<del>
<del> var container = document.createElement('container');
<del>
<del> ReactDOM.render(<Component step={1} />, container);
<del> ReactDOM.render(<Component step={2} />, container);
<del> ReactDOM.render(<Component step={1} />, container);
<del> ReactMount.getID(container.querySelector('a'));
<del> });
<del>
<ide> it('passes the correct callback context', function() {
<ide> var container = document.createElement('div');
<ide> var calls = 0;
<ide><path>src/renderers/dom/client/__tests__/ReactRenderDocument-test.js
<ide> jest
<ide> var React;
<ide> var ReactDOM;
<ide> var ReactDOMServer;
<del>var ReactInstanceMap;
<del>var ReactMount;
<ide>
<ide> var getTestDocument;
<ide>
<ide> describe('rendering React components at document', function() {
<ide> React = require('React');
<ide> ReactDOM = require('ReactDOM');
<ide> ReactDOMServer = require('ReactDOMServer');
<del> ReactInstanceMap = require('ReactInstanceMap');
<del> ReactMount = require('ReactMount');
<ide> getTestDocument = require('getTestDocument');
<ide>
<ide> testDocument = getTestDocument();
<ide> });
<ide>
<del> it('should be able to get root component id for document node', function() {
<add> it('should be able to adopt server markup', function() {
<ide> expect(testDocument).not.toBeUndefined();
<ide>
<ide> var Root = React.createClass({
<ide> describe('rendering React components at document', function() {
<ide> <title>Hello World</title>
<ide> </head>
<ide> <body>
<del> Hello world
<add> {'Hello ' + this.props.hello}
<ide> </body>
<ide> </html>
<ide> );
<ide> },
<ide> });
<ide>
<del> var markup = ReactDOMServer.renderToString(<Root />);
<add> var markup = ReactDOMServer.renderToString(<Root hello="world" />);
<ide> testDocument = getTestDocument(markup);
<del> var component = ReactDOM.render(<Root />, testDocument);
<add> var body = testDocument.body;
<add>
<add> ReactDOM.render(<Root hello="world" />, testDocument);
<ide> expect(testDocument.body.innerHTML).toBe('Hello world');
<ide>
<del> // TODO: This is a bad test. I have no idea what this is testing.
<del> // Node IDs is an implementation detail and not part of the public API.
<del> var componentID = ReactMount.getReactRootID(testDocument);
<del> expect(componentID).toBe(ReactInstanceMap.get(component)._rootNodeID);
<add> ReactDOM.render(<Root hello="moon" />, testDocument);
<add> expect(testDocument.body.innerHTML).toBe('Hello moon');
<add>
<add> expect(body).toBe(testDocument.body);
<ide> });
<ide>
<ide> it('should not be able to unmount component from document node', function() {
<ide><path>src/renderers/dom/client/wrappers/ReactDOMInput.js
<ide> var DOMPropertyOperations = require('DOMPropertyOperations');
<ide> var LinkedValueUtils = require('LinkedValueUtils');
<ide> var ReactDOMComponentTree = require('ReactDOMComponentTree');
<del>var ReactMount = require('ReactMount');
<ide> var ReactUpdates = require('ReactUpdates');
<ide>
<ide> var assign = require('Object.assign');
<ide> function _handleChange(event) {
<ide> // This will throw if radio buttons rendered by different copies of React
<ide> // and the same name are rendered into the same form (same as #1939).
<ide> // That's probably okay; we don't support it just as we don't support
<del> // mixing React with non-React.
<del> var otherID = ReactMount.getID(otherNode);
<add> // mixing React radio buttons with non-React ones.
<add> var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode);
<ide> invariant(
<del> otherID,
<add> otherInstance,
<ide> 'ReactDOMInput: Mixing React and non-React radio inputs with the ' +
<ide> 'same `name` is not supported.'
<ide> );
<del> var otherInstance = instancesByReactID[otherID];
<del> invariant(
<del> otherInstance,
<del> 'ReactDOMInput: Unknown radio button ID %s.',
<del> otherID
<del> );
<ide> // If this is a controlled radio button group, forcing the input that
<ide> // was previously checked to update will cause it to be come re-checked
<ide> // as appropriate.
<ide><path>src/renderers/dom/shared/ReactComponentBrowserEnvironment.js
<ide>
<ide> var DOMChildrenOperations = require('DOMChildrenOperations');
<ide> var ReactDOMIDOperations = require('ReactDOMIDOperations');
<del>var ReactMount = require('ReactMount');
<ide> var ReactPerf = require('ReactPerf');
<ide>
<ide> /**
<ide> var ReactComponentBrowserEnvironment = {
<ide> * @private
<ide> */
<ide> unmountIDFromEnvironment: function(rootNodeID) {
<del> ReactMount.purgeID(rootNodeID);
<ide> },
<ide>
<ide> };
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> var ReactDOMInput = require('ReactDOMInput');
<ide> var ReactDOMOption = require('ReactDOMOption');
<ide> var ReactDOMSelect = require('ReactDOMSelect');
<ide> var ReactDOMTextarea = require('ReactDOMTextarea');
<del>var ReactMount = require('ReactMount');
<ide> var ReactMultiChild = require('ReactMultiChild');
<ide> var ReactPerf = require('ReactPerf');
<ide> var ReactUpdateQueue = require('ReactUpdateQueue');
<ide> ReactDOMComponent.Mixin = {
<ide> ReactDOMComponentTree.precacheNode(this, el);
<ide> this._flags |= Flags.hasCachedChildNodes;
<ide> DOMPropertyOperations.setAttributeForID(el, this._rootNodeID);
<del> // Populate node cache
<del> ReactMount.getID(el);
<ide> this._updateDOMProperties(null, props, transaction);
<ide> var lazyTree = DOMLazyTree(el);
<ide> this._createInitialChildren(transaction, props, context, lazyTree);
<ide><path>src/renderers/dom/shared/ReactDOMTextComponent.js
<ide> var DOMPropertyOperations = require('DOMPropertyOperations');
<ide> var ReactComponentBrowserEnvironment =
<ide> require('ReactComponentBrowserEnvironment');
<ide> var ReactDOMComponentTree = require('ReactDOMComponentTree');
<del>var ReactMount = require('ReactMount');
<ide>
<ide> var assign = require('Object.assign');
<ide> var escapeTextContentForBrowser = require('escapeTextContentForBrowser');
<ide> assign(ReactDOMTextComponent.prototype, {
<ide> if (transaction.useCreateElement) {
<ide> var ownerDocument = nativeContainerInfo._ownerDocument;
<ide> var el = ownerDocument.createElement('span');
<del> this._nativeNode = el;
<add> ReactDOMComponentTree.precacheNode(this, el);
<ide> DOMPropertyOperations.setAttributeForID(el, rootID);
<del> // Populate node cache
<del> ReactMount.getID(el);
<ide> var lazyTree = DOMLazyTree(el);
<ide> DOMLazyTree.queueText(lazyTree, this._stringText);
<ide> return lazyTree;
<ide><path>src/renderers/shared/reconciler/__tests__/ReactCompositeComponent-test.js
<ide> var MorphingComponent;
<ide> var React;
<ide> var ReactDOM;
<ide> var ReactCurrentOwner;
<del>var ReactMount;
<ide> var ReactPropTypes;
<ide> var ReactServerRendering;
<ide> var ReactTestUtils;
<ide> describe('ReactCompositeComponent', function() {
<ide> ReactCurrentOwner = require('ReactCurrentOwner');
<ide> ReactPropTypes = require('ReactPropTypes');
<ide> ReactTestUtils = require('ReactTestUtils');
<del> ReactMount = require('ReactMount');
<ide> ReactServerRendering = require('ReactServerRendering');
<ide> ReactUpdates = require('ReactUpdates');
<ide>
<ide> describe('ReactCompositeComponent', function() {
<ide> var container = document.createElement('div');
<ide> var innerUnmounted = false;
<ide>
<del> spyOn(ReactMount, 'purgeID').andCallThrough();
<del>
<ide> var Component = React.createClass({
<ide> render: function() {
<ide> return (
<ide> describe('ReactCompositeComponent', function() {
<ide> });
<ide> var Inner = React.createClass({
<ide> componentWillUnmount: function() {
<del> // It's important that ReactMount.purgeID is called after any component
<del> // lifecycle methods, because a componentWillUnmount implementation is
<del> // likely to call ReactDOM.findDOMNode(this), which will repopulate the
<del> // node cache after it's been cleared, causing a memory leak.
<del> expect(ReactMount.purgeID.calls.length).toBe(0);
<ide> innerUnmounted = true;
<ide> },
<ide> render: function() {
<ide> describe('ReactCompositeComponent', function() {
<ide> ReactDOM.render(<Component />, container);
<ide> ReactDOM.unmountComponentAtNode(container);
<ide> expect(innerUnmounted).toBe(true);
<del>
<del> // The text and both <div /> elements and their wrappers each call
<del> // unmountIDFromEnvironment which calls purgeID, for a total of 3.
<del> // TODO: Test the effect of this. E.g. does the node cache get repopulated
<del> // after a getDOMNode call?
<del> expect(ReactMount.purgeID.calls.length).toBe(3);
<ide> });
<ide>
<ide> it('should warn when shouldComponentUpdate() returns undefined', function() {
<ide><path>src/renderers/shared/reconciler/__tests__/ReactIdentity-test.js
<ide>
<ide> var React;
<ide> var ReactDOM;
<add>var ReactDOMComponentTree;
<ide> var ReactFragment;
<ide> var ReactTestUtils;
<del>var ReactMount;
<ide>
<ide> describe('ReactIdentity', function() {
<ide>
<ide> beforeEach(function() {
<ide> jest.resetModuleRegistry();
<ide> React = require('React');
<ide> ReactDOM = require('ReactDOM');
<add> ReactDOMComponentTree = require('ReactDOMComponentTree');
<ide> ReactFragment = require('ReactFragment');
<ide> ReactTestUtils = require('ReactTestUtils');
<del> ReactMount = require('ReactMount');
<ide> });
<ide>
<ide> var idExp = /^\.[^.]+(.*)$/;
<ide> function checkID(child, expectedID) {
<del> var actual = idExp.exec(ReactMount.getID(child));
<add> // TODO: Node IDs are not public API; rewrite these tests.
<add> var rootID = ReactDOMComponentTree.getInstanceFromNode(child)._rootNodeID;
<add> var actual = idExp.exec(rootID);
<ide> var expected = idExp.exec(expectedID);
<ide> expect(actual).toBeTruthy();
<ide> expect(expected).toBeTruthy();
<ide> describe('ReactIdentity', function() {
<ide> var wrapped = <TestContainer first={instance0} second={instance1} />;
<ide>
<ide> wrapped = ReactDOM.render(wrapped, document.createElement('div'));
<add> var div = ReactDOM.findDOMNode(wrapped);
<ide>
<del> var beforeID = ReactMount.getID(ReactDOM.findDOMNode(wrapped).firstChild);
<del>
<add> var beforeA = div.childNodes[0];
<add> var beforeB = div.childNodes[1];
<ide> wrapped.swap();
<add> var afterA = div.childNodes[1];
<add> var afterB = div.childNodes[0];
<ide>
<del> var afterID = ReactMount.getID(ReactDOM.findDOMNode(wrapped).firstChild);
<del>
<del> expect(beforeID).not.toEqual(afterID);
<add> expect(beforeA).toBe(afterA);
<add> expect(beforeB).toBe(afterB);
<ide>
<ide> });
<ide>
<ide><path>src/renderers/shared/reconciler/__tests__/ReactInstanceHandles-test.js
<ide>
<ide> var React = require('React');
<ide> var ReactTestUtils = require('ReactTestUtils');
<del>var ReactMount = require('ReactMount');
<ide>
<ide> /**
<ide> * Ensure that all callbacks are invoked, passing this unique argument.
<ide> describe('ReactInstanceHandles', function() {
<ide> aggregatedArgs = [];
<ide> });
<ide>
<del> describe('findComponentRoot', function() {
<del> it('should find the correct node with prefix sibling IDs', function() {
<del> var parentNode = ReactTestUtils.renderIntoDocument(
<del> <div>
<del> <div />
<del> {[<div key="x" />]}
<del> </div>
<del> );
<del> var childNodeB = parentNode.childNodes[1];
<del>
<del> expect(
<del> ReactMount.getNode(
<del> getNodeID(childNodeB)
<del> )
<del> ).toBe(childNodeB);
<del> });
<del>
<del> it('should work around unidentified nodes', function() {
<del> var parentNode = ReactTestUtils.renderIntoDocument(
<del> <div>
<del> {[<div key="x" />]}
<del> </div>
<del> );
<del> var childNodeB = parentNode.childNodes[0];
<del>
<del> // No ID on `childNodeA`.
<del> var childNodeA = document.createElement('div');
<del> parentNode.insertBefore(childNodeA, childNodeB);
<del>
<del> expect(
<del> ReactMount.getNode(
<del> getNodeID(childNodeB)
<del> )
<del> ).toBe(childNodeB);
<del> });
<del>
<del> it('should throw if a rendered element cannot be found', function() {
<del> spyOn(console, 'error');
<del> var parentNode = ReactTestUtils.renderIntoDocument(
<del> <table>
<del> <tr />
<del> </table>
<del> );
<del> var childNodeA = parentNode.childNodes[0];
<del> var childNodeB;
<del> if (childNodeA.tagName === 'TR') {
<del> childNodeB = childNodeA;
<del> // No ID on `childNodeA`, it was "rendered by the browser".
<del> childNodeA = document.createElement('tbody');
<del> childNodeA.appendChild(childNodeB);
<del> parentNode.appendChild(childNodeA);
<del> } else {
<del> childNodeB = childNodeA.childNodes[0];
<del> }
<del> expect(childNodeA.tagName).toBe('TBODY');
<del>
<del> expect(
<del> ReactMount.getNode(
<del> getNodeID(childNodeB)
<del> )
<del> ).toBe(childNodeB);
<del>
<del> var junkID = getNodeID(childNodeB) + ':junk';
<del> expect(function() {
<del> ReactMount.getNode(
<del> junkID
<del> );
<del> }).toThrow(
<del> 'findComponentRoot(..., ' + junkID + '): Unable to find element. ' +
<del> 'This probably means the DOM was unexpectedly mutated (e.g., by the ' +
<del> 'browser), usually due to forgetting a <tbody> when using tables, ' +
<del> 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements in ' +
<del> 'an <svg> parent. Try inspecting the child nodes of the element with ' +
<del> 'React ID ``.'
<del> );
<del>
<del> expect(console.error.argsForCall.length).toBe(1);
<del> expect(console.error.argsForCall[0][0]).toContain(
<del> '<tr> cannot appear as a child of <table>'
<del> );
<del> });
<del> });
<del>
<ide> describe('getReactRootIDFromNodeID', function() {
<ide> it('should support strings', function() {
<ide> var test = '.s_0_1.0..1';
<ide><path>src/renderers/shared/reconciler/__tests__/ReactMultiChildReconcile-test.js
<ide>
<ide> var React = require('React');
<ide> var ReactDOM = require('ReactDOM');
<add>var ReactDOMComponentTree = require('ReactDOMComponentTree');
<ide> var ReactInstanceMap = require('ReactInstanceMap');
<del>var ReactMount = require('ReactMount');
<ide>
<ide> var mapObject = require('mapObject');
<ide>
<ide> function verifyDomOrderingAccurate(parentInstance, statusDisplays) {
<ide> var i;
<ide> var orderedDomIDs = [];
<ide> for (i = 0; i < statusDisplayNodes.length; i++) {
<del> orderedDomIDs.push(ReactMount.getID(statusDisplayNodes[i]));
<add> var inst = ReactDOMComponentTree.getInstanceFromNode(statusDisplayNodes[i]);
<add> orderedDomIDs.push(inst._rootNodeID);
<ide> }
<ide>
<ide> var orderedLogicalIDs = [];
<ide><path>src/test/ReactDefaultPerf.js
<ide> 'use strict';
<ide>
<ide> var DOMProperty = require('DOMProperty');
<add>var ReactDOMComponentTree = require('ReactDOMComponentTree');
<ide> var ReactDefaultPerfAnalysis = require('ReactDefaultPerfAnalysis');
<ide> var ReactMount = require('ReactMount');
<ide> var ReactPerf = require('ReactPerf');
<ide> var ReactDefaultPerf = {
<ide> totalTime = performanceNow() - start;
<ide>
<ide> if (fnName === '_mountImageIntoNode') {
<del> var mountID = ReactMount.getID(args[1]);
<del> ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]);
<add> ReactDefaultPerf._recordWrite('', fnName, totalTime, args[0]);
<ide> } else if (fnName === 'dangerouslyProcessChildrenUpdates') {
<ide> // special format
<ide> args[0].forEach(function(update) {
<ide> var ReactDefaultPerf = {
<ide> if (moduleName === 'EventPluginHub') {
<ide> id = id._rootNodeID;
<ide> } else if (typeof id === 'object') {
<del> id = ReactMount.getID(args[0]);
<add> id = ReactDOMComponentTree.getInstanceFromNode(args[0])._rootNodeID;
<ide> }
<ide> ReactDefaultPerf._recordWrite(
<ide> id, | 12 |
PHP | PHP | throw exception when no primary key and deleting | 549faad51c4b9ca05cc4e49f354e7b55d0f3afb9 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public static function destroy($ids)
<ide> */
<ide> public function delete()
<ide> {
<add> if (is_null($this->primaryKey))
<add> {
<add> throw new \Exception("No primary key defined on model.");
<add> }
<add>
<ide> if ($this->exists)
<ide> {
<ide> if ($this->fireModelEvent('deleting') === false) return false; | 1 |
Javascript | Javascript | add missing param to safelycalldestroy() | 23595ff593b2e53ddfec2a08e848704d15d84b51 | <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js
<ide> function commitBeforeMutationLifeCycles(
<ide> );
<ide> }
<ide>
<del>function commitHookEffectListUnmount(tag: HookEffectTag, finishedWork: Fiber) {
<add>function commitHookEffectListUnmount(
<add> tag: HookEffectTag,
<add> finishedWork: Fiber,
<add> nearestMountedAncestor: Fiber | null,
<add>) {
<ide> const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any);
<ide> const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
<ide> if (lastEffect !== null) {
<ide> function commitHookEffectListUnmount(tag: HookEffectTag, finishedWork: Fiber) {
<ide> const destroy = effect.destroy;
<ide> effect.destroy = undefined;
<ide> if (destroy !== undefined) {
<del> safelyCallDestroy(finishedWork, destroy);
<add> safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);
<ide> }
<ide> }
<ide> effect = effect.next;
<ide> function commitWork(current: Fiber | null, finishedWork: Fiber): void {
<ide> commitHookEffectListUnmount(
<ide> HookLayout | HookHasEffect,
<ide> finishedWork,
<add> finishedWork.return,
<ide> );
<ide> } finally {
<ide> recordLayoutEffectDuration(finishedWork);
<ide> }
<ide> } else {
<del> commitHookEffectListUnmount(HookLayout | HookHasEffect, finishedWork);
<add> commitHookEffectListUnmount(
<add> HookLayout | HookHasEffect,
<add> finishedWork,
<add> finishedWork.return,
<add> );
<ide> }
<ide> return;
<ide> }
<ide> function commitWork(current: Fiber | null, finishedWork: Fiber): void {
<ide> ) {
<ide> try {
<ide> startLayoutEffectTimer();
<del> commitHookEffectListUnmount(HookLayout | HookHasEffect, finishedWork);
<add> commitHookEffectListUnmount(
<add> HookLayout | HookHasEffect,
<add> finishedWork,
<add> finishedWork.return,
<add> );
<ide> } finally {
<ide> recordLayoutEffectDuration(finishedWork);
<ide> }
<ide> } else {
<del> commitHookEffectListUnmount(HookLayout | HookHasEffect, finishedWork);
<add> commitHookEffectListUnmount(
<add> HookLayout | HookHasEffect,
<add> finishedWork,
<add> finishedWork.return,
<add> );
<ide> }
<ide> return;
<ide> } | 1 |
Mixed | Text | add ticks.samplesize option | fc76610b121d71fc5b903631d21edd04b886e3e0 | <ide><path>docs/axes/cartesian/README.md
<ide> The following options are common to all cartesian axes but do not apply to other
<ide> | ---- | ---- | ------- | -----------
<ide> | `min` | `number` | | User defined minimum value for the scale, overrides minimum value from data.
<ide> | `max` | `number` | | User defined maximum value for the scale, overrides maximum value from data.
<add>| `sampleSize` | `number` | `ticks.length` | The number of ticks to examine when deciding how many labels will fit. Setting a smaller value will be faster, but may be less accurate when there is large variability in label length.
<ide> | `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to `maxRotation` before skipping any. Turn `autoSkip` off to show all labels no matter what.
<ide> | `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled.
<ide> | `labelOffset` | `number` | `0` | Distance in pixels to offset the label from the centre point of the tick (in the x direction for the x axis, and the y direction for the y axis). *Note: this can cause labels at the edges to be cropped by the edge of the canvas*
<ide><path>docs/general/performance.md
<add># Performance
<add>
<add>Chart.js charts are rendered on `canvas` elements, which makes rendering quite fast. For large datasets or performance sensitive applications, you may wish to consider the tips below:
<add>
<add>* Set `animation: { duration: 0 }` to disable [animations](../configuration/animations.md).
<add>* For large datasets:
<add> * You may wish to sample your data before providing it to Chart.js. E.g. if you have a data point for each day, you may find it more performant to pass in a data point for each week instead
<add> * Set the [`ticks.sampleSize`](../axes/cartesian/README.md#tick-configuration) option in order to render axes more quickly
<ide><path>src/core/core.scale.js
<ide> defaults._set('scale', {
<ide> }
<ide> });
<ide>
<add>/** Returns a new array containing numItems from arr */
<add>function sample(arr, numItems) {
<add> var result = [];
<add> var increment = arr.length / numItems;
<add> var i = 0;
<add> var len = arr.length;
<add>
<add> for (; i < len; i += increment) {
<add> result.push(arr[Math.floor(i)]);
<add> }
<add> return result;
<add>}
<add>
<ide> function getPixelForGridLine(scale, index, offsetGridLines) {
<ide> var length = scale.getTicks().length;
<ide> var validIndex = Math.min(index, length - 1);
<ide> var Scale = Element.extend({
<ide> update: function(maxWidth, maxHeight, margins) {
<ide> var me = this;
<ide> var tickOpts = me.options.ticks;
<del> var i, ilen, labels, label, ticks, tick;
<add> var sampleSize = tickOpts.sampleSize;
<add> var i, ilen, labels, ticks;
<ide>
<ide> // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
<ide> me.beforeUpdate();
<ide> var Scale = Element.extend({
<ide> bottom: 0
<ide> }, margins);
<ide>
<add> me._ticks = null;
<add> me.ticks = null;
<ide> me._labelSizes = null;
<ide> me._maxLabelLines = 0;
<ide> me.longestLabelWidth = 0;
<ide> var Scale = Element.extend({
<ide> // Allow modification of ticks in callback.
<ide> ticks = me.afterBuildTicks(ticks) || ticks;
<ide>
<del> me.beforeTickToLabelConversion();
<del>
<del> // New implementations should return the formatted tick labels but for BACKWARD
<del> // COMPAT, we still support no return (`this.ticks` internally changed by calling
<del> // this method and supposed to contain only string values).
<del> labels = me.convertTicksToLabels(ticks) || me.ticks;
<del>
<del> me.afterTickToLabelConversion();
<del>
<del> me.ticks = labels; // BACKWARD COMPATIBILITY
<del>
<del> // IMPORTANT: below this point, we consider that `this.ticks` will NEVER change!
<del>
<del> // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
<del> for (i = 0, ilen = labels.length; i < ilen; ++i) {
<del> label = labels[i];
<del> tick = ticks[i];
<del> if (!tick) {
<del> ticks.push(tick = {
<del> label: label,
<add> // Ensure ticks contains ticks in new tick format
<add> if ((!ticks || !ticks.length) && me.ticks) {
<add> ticks = [];
<add> for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
<add> ticks.push({
<add> value: me.ticks[i],
<ide> major: false
<ide> });
<del> } else {
<del> tick.label = label;
<ide> }
<ide> }
<ide>
<ide> me._ticks = ticks;
<ide>
<add> // Compute tick rotation and fit using a sampled subset of labels
<add> // We generally don't need to compute the size of every single label for determining scale size
<add> labels = me._convertTicksToLabels(sampleSize ? sample(ticks, sampleSize) : ticks);
<add>
<ide> // _configure is called twice, once here, once from core.controller.updateLayout.
<ide> // Here we haven't been positioned yet, but dimensions are correct.
<ide> // Variables set in _configure are needed for calculateTickRotation, and
<ide> var Scale = Element.extend({
<ide> me.beforeCalculateTickRotation();
<ide> me.calculateTickRotation();
<ide> me.afterCalculateTickRotation();
<del> // Fit
<add>
<ide> me.beforeFit();
<ide> me.fit();
<ide> me.afterFit();
<add>
<ide> // Auto-skip
<del> me._ticksToDraw = tickOpts.display && tickOpts.autoSkip ? me._autoSkip(me._ticks) : me._ticks;
<add> me._ticksToDraw = tickOpts.display && tickOpts.autoSkip ? me._autoSkip(ticks) : ticks;
<add>
<add> if (sampleSize) {
<add> // Generate labels using all non-skipped ticks
<add> labels = me._convertTicksToLabels(me._ticksToDraw);
<add> }
<add>
<add> me.ticks = labels; // BACKWARD COMPATIBILITY
<add>
<add> // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
<ide>
<ide> me.afterUpdate();
<ide>
<ide> // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
<ide> // make maxWidth and maxHeight private
<ide> return me.minSize;
<del>
<ide> },
<ide>
<ide> /**
<ide> var Scale = Element.extend({
<ide> return rawValue;
<ide> },
<ide>
<add> _convertTicksToLabels: function(ticks) {
<add> var me = this;
<add> var labels, i, ilen;
<add>
<add> me.ticks = ticks.map(function(tick) {
<add> return tick.value;
<add> });
<add>
<add> me.beforeTickToLabelConversion();
<add>
<add> // New implementations should return the formatted tick labels but for BACKWARD
<add> // COMPAT, we still support no return (`this.ticks` internally changed by calling
<add> // this method and supposed to contain only string values).
<add> labels = me.convertTicksToLabels(ticks) || me.ticks;
<add>
<add> me.afterTickToLabelConversion();
<add>
<add> // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
<add> for (i = 0, ilen = ticks.length; i < ilen; ++i) {
<add> ticks[i].label = labels[i];
<add> }
<add>
<add> return labels;
<add> },
<add>
<ide> /**
<ide> * @private
<ide> */
<ide> var Scale = Element.extend({
<ide> for (i = 0; i < tickCount; i++) {
<ide> tick = ticks[i];
<ide>
<del> if (skipRatio > 1 && i % skipRatio > 0) {
<del> // leave tick in place but make sure it's not displayed (#4635)
<add> if (skipRatio <= 1 || i % skipRatio === 0) {
<add> tick._index = i;
<add> result.push(tick);
<add> } else {
<ide> delete tick.label;
<ide> }
<del> result.push(tick);
<ide> }
<ide> return result;
<ide> },
<ide> var Scale = Element.extend({
<ide> borderDashOffset = gridLines.borderDashOffset || 0.0;
<ide> }
<ide>
<del> lineValue = getPixelForGridLine(me, i, offsetGridLines);
<add> lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
<ide>
<ide> // Skip if the pixel is out of the range
<ide> if (lineValue === undefined) {
<ide> var Scale = Element.extend({
<ide> continue;
<ide> }
<ide>
<del> pixel = me.getPixelForTick(i) + optionTicks.labelOffset;
<add> pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
<ide> font = tick.major ? fonts.major : fonts.minor;
<ide> lineHeight = font.lineHeight;
<ide> lineCount = isArray(label) ? label.length : 1; | 3 |
Java | Java | fix switchmap to indicate boundary fusion | 90203b6f6962e7aa8259780b94fb591e4232ddba | <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableSwitchMap.java
<ide> public void onSubscribe(Subscription s) {
<ide> @SuppressWarnings("unchecked")
<ide> QueueSubscription<R> qs = (QueueSubscription<R>) s;
<ide>
<del> int m = qs.requestFusion(QueueSubscription.ANY);
<add> int m = qs.requestFusion(QueueSubscription.ANY | QueueSubscription.BOUNDARY);
<ide> if (m == QueueSubscription.SYNC) {
<ide> fusionMode = m;
<ide> queue = qs;
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableSwitchMap.java
<ide> public void onSubscribe(Disposable s) {
<ide> @SuppressWarnings("unchecked")
<ide> QueueDisposable<R> qd = (QueueDisposable<R>) s;
<ide>
<del> int m = qd.requestFusion(QueueDisposable.ANY);
<add> int m = qd.requestFusion(QueueDisposable.ANY | QueueDisposable.BOUNDARY);
<ide> if (m == QueueDisposable.SYNC) {
<ide> queue = qd;
<ide> done = true;
<ide><path>src/test/java/io/reactivex/TestHelper.java
<ide> public void request(long n) {
<ide> }
<ide> };
<ide> }
<add>
<add> static final class FlowableStripBoundary<T> extends Flowable<T> implements FlowableTransformer<T, T> {
<add>
<add> final Flowable<T> source;
<add>
<add> FlowableStripBoundary(Flowable<T> source) {
<add> this.source = source;
<add> }
<add>
<add> @Override
<add> public Flowable<T> apply(Flowable<T> upstream) {
<add> return new FlowableStripBoundary<T>(upstream);
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Subscriber<? super T> s) {
<add> source.subscribe(new StripBoundarySubscriber<T>(s));
<add> }
<add>
<add> static final class StripBoundarySubscriber<T> implements FlowableSubscriber<T>, QueueSubscription<T> {
<add>
<add> final Subscriber<? super T> actual;
<add>
<add> Subscription upstream;
<add>
<add> QueueSubscription<T> qs;
<add>
<add> StripBoundarySubscriber(Subscriber<? super T> actual) {
<add> this.actual = actual;
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @Override
<add> public void onSubscribe(Subscription subscription) {
<add> this.upstream = subscription;
<add> if (subscription instanceof QueueSubscription) {
<add> qs = (QueueSubscription<T>)subscription;
<add> }
<add> actual.onSubscribe(this);
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> actual.onNext(t);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable throwable) {
<add> actual.onError(throwable);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> actual.onComplete();
<add> }
<add>
<add> @Override
<add> public int requestFusion(int mode) {
<add> QueueSubscription<T> fs = qs;
<add> if (fs != null) {
<add> return fs.requestFusion(mode & ~BOUNDARY);
<add> }
<add> return NONE;
<add> }
<add>
<add> @Override
<add> public boolean offer(T value) {
<add> throw new UnsupportedOperationException("Should not be called");
<add> }
<add>
<add> @Override
<add> public boolean offer(T v1, T v2) {
<add> throw new UnsupportedOperationException("Should not be called");
<add> }
<add>
<add> @Override
<add> public T poll() throws Exception {
<add> return qs.poll();
<add> }
<add>
<add> @Override
<add> public void clear() {
<add> qs.clear();
<add> }
<add>
<add> @Override
<add> public boolean isEmpty() {
<add> return qs.isEmpty();
<add> }
<add>
<add> @Override
<add> public void request(long n) {
<add> upstream.request(n);
<add> }
<add>
<add> @Override
<add> public void cancel() {
<add> upstream.cancel();
<add> }
<add> }
<add> }
<add>
<add> public static <T> FlowableTransformer<T, T> flowableStripBoundary() {
<add> return new FlowableStripBoundary<T>(null);
<add> }
<add>
<add> static final class ObservableStripBoundary<T> extends Observable<T> implements ObservableTransformer<T, T> {
<add>
<add> final Observable<T> source;
<add>
<add> ObservableStripBoundary(Observable<T> source) {
<add> this.source = source;
<add> }
<add>
<add> @Override
<add> public Observable<T> apply(Observable<T> upstream) {
<add> return new ObservableStripBoundary<T>(upstream);
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Observer<? super T> s) {
<add> source.subscribe(new StripBoundaryObserver<T>(s));
<add> }
<add>
<add> static final class StripBoundaryObserver<T> implements Observer<T>, QueueDisposable<T> {
<add>
<add> final Observer<? super T> actual;
<add>
<add> Disposable upstream;
<add>
<add> QueueDisposable<T> qd;
<add>
<add> StripBoundaryObserver(Observer<? super T> actual) {
<add> this.actual = actual;
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> this.upstream = d;
<add> if (d instanceof QueueDisposable) {
<add> qd = (QueueDisposable<T>)d;
<add> }
<add> actual.onSubscribe(this);
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> actual.onNext(t);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable throwable) {
<add> actual.onError(throwable);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> actual.onComplete();
<add> }
<add>
<add> @Override
<add> public int requestFusion(int mode) {
<add> QueueDisposable<T> fs = qd;
<add> if (fs != null) {
<add> return fs.requestFusion(mode & ~BOUNDARY);
<add> }
<add> return NONE;
<add> }
<add>
<add> @Override
<add> public boolean offer(T value) {
<add> throw new UnsupportedOperationException("Should not be called");
<add> }
<add>
<add> @Override
<add> public boolean offer(T v1, T v2) {
<add> throw new UnsupportedOperationException("Should not be called");
<add> }
<add>
<add> @Override
<add> public T poll() throws Exception {
<add> return qd.poll();
<add> }
<add>
<add> @Override
<add> public void clear() {
<add> qd.clear();
<add> }
<add>
<add> @Override
<add> public boolean isEmpty() {
<add> return qd.isEmpty();
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> upstream.dispose();
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return upstream.isDisposed();
<add> }
<add> }
<add> }
<add>
<add> public static <T> ObservableTransformer<T, T> observableStripBoundary() {
<add> return new ObservableStripBoundary<T>(null);
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java
<ide> import io.reactivex.internal.util.ExceptionHelper;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.processors.PublishProcessor;
<del>import io.reactivex.schedulers.TestScheduler;
<add>import io.reactivex.schedulers.*;
<ide> import io.reactivex.subscribers.*;
<ide>
<ide> public class FlowableSwitchTest {
<ide> public void run() {
<ide> @Test
<ide> public void fusedInnerCrash() {
<ide> Flowable.just(1).hide()
<del> .switchMap(Functions.justFunction(Flowable.just(1).map(new Function<Integer, Object>() {
<del> @Override
<del> public Object apply(Integer v) throws Exception {
<del> throw new TestException();
<del> }
<del> })))
<add> .switchMap(Functions.justFunction(Flowable.just(1)
<add> .map(new Function<Integer, Object>() {
<add> @Override
<add> public Object apply(Integer v) throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .compose(TestHelper.<Object>flowableStripBoundary())
<add> )
<add> )
<ide> .test()
<ide> .assertFailure(TestException.class);
<ide> }
<ide> public void innerCancelledOnMainError() {
<ide>
<ide> ts.assertFailure(TestException.class);
<ide> }
<add>
<add> @Test
<add> public void fusedBoundary() {
<add> String thread = Thread.currentThread().getName();
<add>
<add> Flowable.range(1, 10000)
<add> .switchMap(new Function<Integer, Flowable<? extends Object>>() {
<add> @Override
<add> public Flowable<? extends Object> apply(Integer v)
<add> throws Exception {
<add> return Flowable.just(2).hide()
<add> .observeOn(Schedulers.single())
<add> .map(new Function<Integer, Object>() {
<add> @Override
<add> public Object apply(Integer w) throws Exception {
<add> return Thread.currentThread().getName();
<add> }
<add> });
<add> }
<add> })
<add> .test()
<add> .awaitDone(5, TimeUnit.SECONDS)
<add> .assertNever(thread)
<add> .assertNoErrors()
<add> .assertComplete();
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<add>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide> import io.reactivex.*;
<ide> import io.reactivex.disposables.*;
<ide> import io.reactivex.exceptions.*;
<del>import io.reactivex.functions.Consumer;
<del>import io.reactivex.functions.Function;
<add>import io.reactivex.functions.*;
<ide> import io.reactivex.internal.functions.Functions;
<ide> import io.reactivex.internal.schedulers.ImmediateThinScheduler;
<ide> import io.reactivex.internal.util.ExceptionHelper;
<ide> import io.reactivex.observers.TestObserver;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<del>import io.reactivex.schedulers.TestScheduler;
<del>import io.reactivex.subjects.PublishSubject;
<add>import io.reactivex.schedulers.*;
<add>import io.reactivex.subjects.*;
<ide>
<ide> public class ObservableSwitchTest {
<ide>
<ide> public Integer apply(Integer v) throws Exception {
<ide> throw new TestException();
<ide> }
<ide> })
<add> .compose(TestHelper.<Integer>observableStripBoundary())
<ide> ))
<ide> .test();
<ide>
<ide> public Integer apply(Integer v) throws Exception {
<ide> throw new TestException();
<ide> }
<ide> })
<add> .compose(TestHelper.<Integer>observableStripBoundary())
<ide> ))
<ide> .test();
<ide>
<ide> public Integer apply(Integer v) throws Exception {
<ide>
<ide> assertFalse(ps.hasObservers());
<ide> }
<add>
<add> @Test
<add> public void fusedBoundary() {
<add> String thread = Thread.currentThread().getName();
<add>
<add> Observable.range(1, 10000)
<add> .switchMap(new Function<Integer, ObservableSource<? extends Object>>() {
<add> @Override
<add> public ObservableSource<? extends Object> apply(Integer v)
<add> throws Exception {
<add> return Observable.just(2).hide()
<add> .observeOn(Schedulers.single())
<add> .map(new Function<Integer, Object>() {
<add> @Override
<add> public Object apply(Integer w) throws Exception {
<add> return Thread.currentThread().getName();
<add> }
<add> });
<add> }
<add> })
<add> .test()
<add> .awaitDone(5, TimeUnit.SECONDS)
<add> .assertNever(thread)
<add> .assertNoErrors()
<add> .assertComplete();
<add> }
<ide> } | 5 |
Python | Python | convert numpy types to their native python types | 24ee7f7ce51e1285ebc6cb34a9b4fb0361db9d6d | <ide><path>airflow/utils.py
<ide> from builtins import str, input, object
<ide> from past.builtins import basestring
<ide> from copy import copy
<del>from datetime import datetime, timedelta
<add>from datetime import datetime, date, timedelta
<ide> from dateutil.relativedelta import relativedelta # for doctest
<ide> from email.mime.text import MIMEText
<ide> from email.mime.multipart import MIMEMultipart
<ide> from sqlalchemy import event, exc
<ide> from sqlalchemy.pool import Pool
<ide>
<add>import numpy
<add>
<ide> from airflow import settings
<ide> from airflow.configuration import conf
<ide>
<ide> def chain(*tasks):
<ide>
<ide> class AirflowJsonEncoder(json.JSONEncoder):
<ide> def default(self, obj):
<add> # convert dates and numpy objects in a json serializable format
<ide> if isinstance(obj, datetime):
<ide> return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
<ide> elif isinstance(obj, date):
<ide> return obj.strftime('%Y-%m-%d')
<add> elif type(obj) in [numpy.int_, numpy.intc, numpy.intp, numpy.int8,
<add> numpy.int16, numpy.int32, numpy.int64, numpy.uint8, numpy.uint16, numpy.uint32, numpy.uint64]:
<add> return int(obj)
<add> elif type(obj) in [numpy.bool_]:
<add> return bool(obj)
<add> elif type(obj) in [numpy.float_, numpy.float16, numpy.float32, numpy.float64,
<add> numpy.complex_, numpy.complex64, numpy.complex128,:
<add> return float(obj)
<add>
<ide> # Let the base class default method raise the TypeError
<ide> return json.JSONEncoder.default(self, obj) | 1 |
Javascript | Javascript | support editable usestate hooks in devtools | bb2939ccc23c9895d798f889d9c32848be43225e | <ide><path>packages/react-debug-tools/src/ReactDebugHooks.js
<ide> const Dispatcher: DispatcherType = {
<ide> // Inspect
<ide>
<ide> type HooksNode = {
<add> id: number | null,
<add> isStateEditable: boolean,
<ide> name: string,
<ide> value: mixed,
<ide> subHooks: Array<HooksNode>,
<ide> function buildTree(rootStack, readHookLog): HooksTree {
<ide> let rootChildren = [];
<ide> let prevStack = null;
<ide> let levelChildren = rootChildren;
<add> let nativeHookID = 0;
<ide> let stackOfChildren = [];
<ide> for (let i = 0; i < readHookLog.length; i++) {
<ide> let hook = readHookLog[i];
<ide> function buildTree(rootStack, readHookLog): HooksTree {
<ide> for (let j = stack.length - commonSteps - 1; j >= 1; j--) {
<ide> let children = [];
<ide> levelChildren.push({
<add> id: null,
<add> isStateEditable: false,
<ide> name: parseCustomHookName(stack[j - 1].functionName),
<ide> value: undefined,
<ide> subHooks: children,
<ide> function buildTree(rootStack, readHookLog): HooksTree {
<ide> }
<ide> prevStack = stack;
<ide> }
<add> const {primitive} = hook;
<add>
<add> // For now, the "id" of stateful hooks is just the stateful hook index.
<add> // Custom hooks have no ids, nor do non-stateful native hooks (e.g. Context, DebugValue).
<add> const id =
<add> primitive === 'Context' || primitive === 'DebugValue'
<add> ? null
<add> : nativeHookID++;
<add>
<add> // For the time being, only State and Reducer hooks support runtime overrides.
<add> const isStateEditable = primitive === 'Reducer' || primitive === 'State';
<add>
<ide> levelChildren.push({
<del> name: hook.primitive,
<add> id,
<add> isStateEditable,
<add> name: primitive,
<ide> value: hook.value,
<ide> subHooks: [],
<ide> });
<ide><path>packages/react-debug-tools/src/__tests__/ReactDevToolsHooksIntegration-test.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @emails react-core
<add> * @jest-environment node
<add> */
<add>
<add>'use strict';
<add>
<add>describe('React hooks DevTools integration', () => {
<add> let React;
<add> let ReactDebugTools;
<add> let ReactTestRenderer;
<add> let act;
<add> let overrideHookState;
<add>
<add> beforeEach(() => {
<add> global.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
<add> inject: injected => {
<add> overrideHookState = injected.overrideHookState;
<add> },
<add> supportsFiber: true,
<add> onCommitFiberRoot: () => {},
<add> onCommitFiberUnmount: () => {},
<add> };
<add>
<add> jest.resetModules();
<add>
<add> React = require('react');
<add> ReactDebugTools = require('react-debug-tools');
<add> ReactTestRenderer = require('react-test-renderer');
<add>
<add> act = ReactTestRenderer.act;
<add> });
<add>
<add> it('should support editing useState hooks', () => {
<add> let setCountFn;
<add>
<add> function MyComponent() {
<add> const [count, setCount] = React.useState(0);
<add> setCountFn = setCount;
<add> return <div>count:{count}</div>;
<add> }
<add>
<add> const renderer = ReactTestRenderer.create(<MyComponent />);
<add> expect(renderer.toJSON()).toEqual({
<add> type: 'div',
<add> props: {},
<add> children: ['count:', '0'],
<add> });
<add>
<add> const fiber = renderer.root.findByType(MyComponent)._currentFiber();
<add> const tree = ReactDebugTools.inspectHooksOfFiber(fiber);
<add> const stateHook = tree[0];
<add> expect(stateHook.isStateEditable).toBe(true);
<add>
<add> if (__DEV__) {
<add> overrideHookState(fiber, stateHook.id, [], 10);
<add> expect(renderer.toJSON()).toEqual({
<add> type: 'div',
<add> props: {},
<add> children: ['count:', '10'],
<add> });
<add>
<add> act(() => setCountFn(count => count + 1));
<add> expect(renderer.toJSON()).toEqual({
<add> type: 'div',
<add> props: {},
<add> children: ['count:', '11'],
<add> });
<add> }
<add> });
<add>
<add> it('should support editable useReducer hooks', () => {
<add> const initialData = {foo: 'abc', bar: 123};
<add>
<add> function reducer(state, action) {
<add> switch (action.type) {
<add> case 'swap':
<add> return {foo: state.bar, bar: state.foo};
<add> default:
<add> throw new Error();
<add> }
<add> }
<add>
<add> let dispatchFn;
<add> function MyComponent() {
<add> const [state, dispatch] = React.useReducer(reducer, initialData);
<add> dispatchFn = dispatch;
<add> return (
<add> <div>
<add> foo:{state.foo}, bar:{state.bar}
<add> </div>
<add> );
<add> }
<add>
<add> const renderer = ReactTestRenderer.create(<MyComponent />);
<add> expect(renderer.toJSON()).toEqual({
<add> type: 'div',
<add> props: {},
<add> children: ['foo:', 'abc', ', bar:', '123'],
<add> });
<add>
<add> const fiber = renderer.root.findByType(MyComponent)._currentFiber();
<add> const tree = ReactDebugTools.inspectHooksOfFiber(fiber);
<add> const reducerHook = tree[0];
<add> expect(reducerHook.isStateEditable).toBe(true);
<add>
<add> if (__DEV__) {
<add> overrideHookState(fiber, reducerHook.id, ['foo'], 'def');
<add> expect(renderer.toJSON()).toEqual({
<add> type: 'div',
<add> props: {},
<add> children: ['foo:', 'def', ', bar:', '123'],
<add> });
<add>
<add> act(() => dispatchFn({type: 'swap'}));
<add> expect(renderer.toJSON()).toEqual({
<add> type: 'div',
<add> props: {},
<add> children: ['foo:', '123', ', bar:', 'def'],
<add> });
<add> }
<add> });
<add>
<add> // This test case is based on an open source bug report:
<add> // facebookincubator/redux-react-hook/issues/34#issuecomment-466693787
<add> it('should handle interleaved stateful hooks (e.g. useState) and non-stateful hooks (e.g. useContext)', () => {
<add> const MyContext = React.createContext(1);
<add>
<add> let setStateFn;
<add> function useCustomHook() {
<add> const context = React.useContext(MyContext);
<add> const [state, setState] = React.useState({count: context});
<add> React.useDebugValue(state.count);
<add> setStateFn = setState;
<add> return state.count;
<add> }
<add>
<add> function MyComponent() {
<add> const count = useCustomHook();
<add> return <div>count:{count}</div>;
<add> }
<add>
<add> const renderer = ReactTestRenderer.create(<MyComponent />);
<add> expect(renderer.toJSON()).toEqual({
<add> type: 'div',
<add> props: {},
<add> children: ['count:', '1'],
<add> });
<add>
<add> const fiber = renderer.root.findByType(MyComponent)._currentFiber();
<add> const tree = ReactDebugTools.inspectHooksOfFiber(fiber);
<add> const stateHook = tree[0].subHooks[1];
<add> expect(stateHook.isStateEditable).toBe(true);
<add>
<add> if (__DEV__) {
<add> overrideHookState(fiber, stateHook.id, ['count'], 10);
<add> expect(renderer.toJSON()).toEqual({
<add> type: 'div',
<add> props: {},
<add> children: ['count:', '10'],
<add> });
<add>
<add> act(() => setStateFn(state => ({count: state.count + 1})));
<add> expect(renderer.toJSON()).toEqual({
<add> type: 'div',
<add> props: {},
<add> children: ['count:', '11'],
<add> });
<add> }
<add> });
<add>});
<ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspection-test.js
<ide> describe('ReactHooksInspection', () => {
<ide> let tree = ReactDebugTools.inspectHooks(Foo, {});
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: true,
<add> id: 0,
<ide> name: 'State',
<ide> value: 'hello world',
<ide> subHooks: [],
<ide> describe('ReactHooksInspection', () => {
<ide> let tree = ReactDebugTools.inspectHooks(Foo, {});
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Custom',
<ide> value: __DEV__ ? 'custom hook label' : undefined,
<ide> subHooks: [
<ide> {
<add> isStateEditable: true,
<add> id: 0,
<ide> name: 'State',
<ide> value: 'hello world',
<ide> subHooks: [],
<ide> describe('ReactHooksInspection', () => {
<ide> let tree = ReactDebugTools.inspectHooks(Foo, {});
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Custom',
<ide> value: undefined,
<ide> subHooks: [
<ide> {
<add> isStateEditable: true,
<add> id: 0,
<ide> name: 'State',
<ide> subHooks: [],
<ide> value: 'hello',
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: 1,
<ide> name: 'Effect',
<ide> subHooks: [],
<ide> value: effect,
<ide> },
<ide> ],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Custom',
<ide> value: undefined,
<ide> subHooks: [
<ide> {
<add> isStateEditable: true,
<add> id: 2,
<ide> name: 'State',
<ide> value: 'world',
<ide> subHooks: [],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: 3,
<ide> name: 'Effect',
<ide> value: effect,
<ide> subHooks: [],
<ide> describe('ReactHooksInspection', () => {
<ide> let tree = ReactDebugTools.inspectHooks(Foo, {});
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Bar',
<ide> value: undefined,
<ide> subHooks: [
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Custom',
<ide> value: undefined,
<ide> subHooks: [
<ide> {
<add> isStateEditable: true,
<add> id: 0,
<ide> name: 'Reducer',
<ide> value: 'hello',
<ide> subHooks: [],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: 1,
<ide> name: 'Effect',
<ide> value: effect,
<ide> subHooks: [],
<ide> },
<ide> ],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: 2,
<ide> name: 'LayoutEffect',
<ide> value: effect,
<ide> subHooks: [],
<ide> },
<ide> ],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Baz',
<ide> value: undefined,
<ide> subHooks: [
<ide> {
<add> isStateEditable: false,
<add> id: 3,
<ide> name: 'LayoutEffect',
<ide> value: effect,
<ide> subHooks: [],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Custom',
<ide> subHooks: [
<ide> {
<add> isStateEditable: true,
<add> id: 4,
<ide> name: 'Reducer',
<ide> subHooks: [],
<ide> value: 'world',
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: 5,
<ide> name: 'Effect',
<ide> subHooks: [],
<ide> value: effect,
<ide> describe('ReactHooksInspection', () => {
<ide> let tree = ReactDebugTools.inspectHooks(Foo, {});
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Context',
<ide> value: 'default',
<ide> subHooks: [],
<ide> describe('ReactHooksInspection', () => {
<ide> let tree = ReactDebugTools.inspectHooks(Foo, {});
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Custom',
<ide> value: __DEV__ ? 'bar:123' : undefined,
<del> subHooks: [{name: 'State', subHooks: [], value: 0}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> subHooks: [],
<add> value: 0,
<add> },
<add> ],
<ide> },
<ide> ]);
<ide> });
<ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> let childFiber = renderer.root.findByType(Foo)._currentFiber();
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<del> {name: 'State', value: 'hello', subHooks: []},
<del> {name: 'State', value: 'world', subHooks: []},
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 'hello',
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: true,
<add> id: 1,
<add> name: 'State',
<add> value: 'world',
<add> subHooks: [],
<add> },
<ide> ]);
<ide>
<ide> let {
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide>
<ide> expect(tree).toEqual([
<del> {name: 'State', value: 'Hi', subHooks: []},
<del> {name: 'State', value: 'world', subHooks: []},
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 'Hi',
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: true,
<add> id: 1,
<add> name: 'State',
<add> value: 'world',
<add> subHooks: [],
<add> },
<ide> ]);
<ide>
<ide> act(() => setStateB('world!'));
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide>
<ide> expect(tree).toEqual([
<del> {name: 'State', value: 'Hi', subHooks: []},
<del> {name: 'State', value: 'world!', subHooks: []},
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 'Hi',
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: true,
<add> id: 1,
<add> name: 'State',
<add> value: 'world!',
<add> subHooks: [],
<add> },
<ide> ]);
<ide> });
<ide>
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide>
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<del> {name: 'State', value: 'a', subHooks: []},
<del> {name: 'Reducer', value: 'b', subHooks: []},
<del> {name: 'Ref', value: 'c', subHooks: []},
<del> {name: 'LayoutEffect', value: effect, subHooks: []},
<del> {name: 'Effect', value: effect, subHooks: []},
<del> {name: 'ImperativeHandle', value: outsideRef.current, subHooks: []},
<del> {name: 'Memo', value: 'ab', subHooks: []},
<del> {name: 'Callback', value: updateStates, subHooks: []},
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 'a',
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: true,
<add> id: 1,
<add> name: 'Reducer',
<add> value: 'b',
<add> subHooks: [],
<add> },
<add> {isStateEditable: false, id: 2, name: 'Ref', value: 'c', subHooks: []},
<add> {
<add> isStateEditable: false,
<add> id: 3,
<add> name: 'LayoutEffect',
<add> value: effect,
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: false,
<add> id: 4,
<add> name: 'Effect',
<add> value: effect,
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: false,
<add> id: 5,
<add> name: 'ImperativeHandle',
<add> value: outsideRef.current,
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: false,
<add> id: 6,
<add> name: 'Memo',
<add> value: 'ab',
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: false,
<add> id: 7,
<add> name: 'Callback',
<add> value: updateStates,
<add> subHooks: [],
<add> },
<ide> ]);
<ide>
<ide> updateStates();
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide>
<ide> expect(tree).toEqual([
<del> {name: 'State', value: 'A', subHooks: []},
<del> {name: 'Reducer', value: 'B', subHooks: []},
<del> {name: 'Ref', value: 'C', subHooks: []},
<del> {name: 'LayoutEffect', value: effect, subHooks: []},
<del> {name: 'Effect', value: effect, subHooks: []},
<del> {name: 'ImperativeHandle', value: outsideRef.current, subHooks: []},
<del> {name: 'Memo', value: 'Ab', subHooks: []},
<del> {name: 'Callback', value: updateStates, subHooks: []},
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 'A',
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: true,
<add> id: 1,
<add> name: 'Reducer',
<add> value: 'B',
<add> subHooks: [],
<add> },
<add> {isStateEditable: false, id: 2, name: 'Ref', value: 'C', subHooks: []},
<add> {
<add> isStateEditable: false,
<add> id: 3,
<add> name: 'LayoutEffect',
<add> value: effect,
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: false,
<add> id: 4,
<add> name: 'Effect',
<add> value: effect,
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: false,
<add> id: 5,
<add> name: 'ImperativeHandle',
<add> value: outsideRef.current,
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: false,
<add> id: 6,
<add> name: 'Memo',
<add> value: 'Ab',
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: false,
<add> id: 7,
<add> name: 'Callback',
<add> value: updateStates,
<add> subHooks: [],
<add> },
<ide> ]);
<ide> });
<ide>
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Context',
<ide> value: 'contextual',
<ide> subHooks: [],
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> let childFiber = renderer.root.findByType(Foo)._currentFiber();
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<del> {name: 'ImperativeHandle', value: obj, subHooks: []},
<add> {
<add> isStateEditable: false,
<add> id: 0,
<add> name: 'ImperativeHandle',
<add> value: obj,
<add> subHooks: [],
<add> },
<ide> ]);
<ide> });
<ide>
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> // TODO: Test renderer findByType is broken for memo. Have to search for the inner.
<ide> let childFiber = renderer.root.findByType(InnerFoo)._currentFiber();
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<del> expect(tree).toEqual([{name: 'State', value: 'hello', subHooks: []}]);
<add> expect(tree).toEqual([
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 'hello',
<add> subHooks: [],
<add> },
<add> ]);
<ide> });
<ide>
<ide> it('should inspect custom hooks', () => {
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Custom',
<ide> value: undefined,
<del> subHooks: [{name: 'State', value: 'hello', subHooks: []}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 'hello',
<add> subHooks: [],
<add> },
<add> ],
<ide> },
<ide> ]);
<ide> });
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'LabeledValue',
<ide> value: __DEV__ ? 'custom label a' : undefined,
<del> subHooks: [{name: 'State', value: 'a', subHooks: []}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 'a',
<add> subHooks: [],
<add> },
<add> ],
<ide> },
<ide> {
<add> isStateEditable: true,
<add> id: 1,
<ide> name: 'State',
<ide> value: 'b',
<ide> subHooks: [],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Anonymous',
<ide> value: undefined,
<del> subHooks: [{name: 'State', value: 'c', subHooks: []}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 2,
<add> name: 'State',
<add> value: 'c',
<add> subHooks: [],
<add> },
<add> ],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'LabeledValue',
<ide> value: __DEV__ ? 'custom label d' : undefined,
<del> subHooks: [{name: 'State', value: 'd', subHooks: []}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 3,
<add> name: 'State',
<add> value: 'd',
<add> subHooks: [],
<add> },
<add> ],
<ide> },
<ide> ]);
<ide> });
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Outer',
<ide> value: __DEV__ ? 'outer' : undefined,
<ide> subHooks: [
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Inner',
<ide> value: __DEV__ ? 'inner' : undefined,
<del> subHooks: [{name: 'State', value: 0, subHooks: []}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 0,
<add> subHooks: [],
<add> },
<add> ],
<ide> },
<ide> ],
<ide> },
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'SingleLabelCustom',
<ide> value: __DEV__ ? 'single one' : undefined,
<del> subHooks: [{name: 'State', value: 0, subHooks: []}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 0,
<add> subHooks: [],
<add> },
<add> ],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'MultiLabelCustom',
<ide> value: __DEV__ ? ['one', 'two', 'three'] : undefined,
<del> subHooks: [{name: 'State', value: 0, subHooks: []}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 1,
<add> name: 'State',
<add> value: 0,
<add> subHooks: [],
<add> },
<add> ],
<ide> },
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'SingleLabelCustom',
<ide> value: __DEV__ ? 'single two' : undefined,
<del> subHooks: [{name: 'State', value: 0, subHooks: []}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 2,
<add> name: 'State',
<add> value: 0,
<add> subHooks: [],
<add> },
<add> ],
<ide> },
<ide> ]);
<ide> });
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<ide> {
<add> isStateEditable: false,
<add> id: null,
<ide> name: 'Custom',
<ide> value: __DEV__ ? 'bar:123' : undefined,
<del> subHooks: [{name: 'State', subHooks: [], value: 0}],
<add> subHooks: [
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> subHooks: [],
<add> value: 0,
<add> },
<add> ],
<ide> },
<ide> ]);
<ide> });
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide>
<ide> let childFiber = renderer.root._currentFiber();
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<del> expect(tree).toEqual([{name: 'State', value: 'def', subHooks: []}]);
<add> expect(tree).toEqual([
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: 'def',
<add> subHooks: [],
<add> },
<add> ]);
<ide> });
<ide>
<ide> it('should support an injected dispatcher', () => {
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> const childFiber = renderer.root._currentFiber();
<ide> const tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide> expect(tree).toEqual([
<del> {name: 'Context', value: 1, subHooks: []},
<del> {name: 'State', value: {count: 2}, subHooks: []},
<add> {
<add> isStateEditable: false,
<add> id: null,
<add> name: 'Context',
<add> value: 1,
<add> subHooks: [],
<add> },
<add> {
<add> isStateEditable: true,
<add> id: 0,
<add> name: 'State',
<add> value: {count: 2},
<add> subHooks: [],
<add> },
<ide> ]);
<ide> });
<ide> });
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.js
<ide> export function findHostInstanceWithNoPortals(
<ide> return hostFiber.stateNode;
<ide> }
<ide>
<add>let overrideHookState = null;
<ide> let overrideProps = null;
<ide>
<ide> if (__DEV__) {
<ide> if (__DEV__) {
<ide> return copyWithSetImpl(obj, path, 0, value);
<ide> };
<ide>
<add> // Support DevTools editable values for useState and useReducer.
<add> overrideHookState = (
<add> fiber: Fiber,
<add> id: number,
<add> path: Array<string | number>,
<add> value: any,
<add> ) => {
<add> // For now, the "id" of stateful hooks is just the stateful hook index.
<add> // This may change in the future with e.g. nested hooks.
<add> let currentHook = fiber.memoizedState;
<add> while (currentHook !== null && id > 0) {
<add> currentHook = currentHook.next;
<add> id--;
<add> }
<add> if (currentHook !== null) {
<add> flushPassiveEffects();
<add>
<add> const newState = copyWithSet(currentHook.memoizedState, path, value);
<add> currentHook.memoizedState = newState;
<add> currentHook.baseState = newState;
<add>
<add> // We aren't actually adding an update to the queue,
<add> // because there is no update we can add for useReducer hooks that won't trigger an error.
<add> // (There's no appropriate action type for DevTools overrides.)
<add> // As a result though, React will see the scheduled update as a noop and bailout.
<add> // Shallow cloning props works as a workaround for now to bypass the bailout check.
<add> fiber.memoizedProps = {...fiber.memoizedProps};
<add>
<add> scheduleWork(fiber, Sync);
<add> }
<add> };
<add>
<ide> // Support DevTools props for function components, forwardRef, memo, host components, etc.
<ide> overrideProps = (fiber: Fiber, path: Array<string | number>, value: any) => {
<ide> flushPassiveEffects();
<ide> export function injectIntoDevTools(devToolsConfig: DevToolsConfig): boolean {
<ide>
<ide> return injectInternals({
<ide> ...devToolsConfig,
<add> overrideHookState,
<ide> overrideProps,
<ide> currentDispatcherRef: ReactCurrentDispatcher,
<ide> findHostInstanceByFiber(fiber: Fiber): Instance | TextInstance | null { | 5 |
Javascript | Javascript | add chrome.properties for moz central build | 03032d21c40a50ff75fd7c4cf3e046c447d44a90 | <ide><path>make.js
<ide> target.mozcentral = function() {
<ide> 'components',
<ide> '../../LICENSE'],
<ide> DEFAULT_LOCALE_FILES =
<del> [LOCALE_SRC_DIR + 'en-US/viewer.properties'],
<add> [LOCALE_SRC_DIR + 'en-US/viewer.properties',
<add> LOCALE_SRC_DIR + 'en-US/chrome.properties'],
<ide> FIREFOX_MC_EXTENSION_FILES =
<ide> ['bootstrap.js',
<ide> 'icon.png', | 1 |
PHP | PHP | ignore invalid samesite value when parsing header | b45c664e5649397750a4617bba13266269e68166 | <ide><path>src/Http/Cookie/Cookie.php
<ide> public static function createFromHeaderString(string $cookie)
<ide> $data['expires'] = new DateTimeImmutable('@' . (time() + (int)$data['max-age']));
<ide> }
<ide>
<add> if ($data['samesite'] !== null) {
<add> // Ignore invalid value when parsing headers
<add> // https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1
<add> if (!in_array($data['samesite'], CookieInterface::SAMESITE_VALUES, true)) {
<add> $data['samesite'] = null;
<add> }
<add> }
<add>
<ide> $name = (string)$data['name'];
<ide> $value = (string)$data['value'];
<ide> unset($data['name'], $data['value'], $data['max-age']);
<ide> public function withSameSite(?string $sameSite)
<ide> */
<ide> protected function validateSameSiteValue(string $sameSite)
<ide> {
<del> if (!in_array($sameSite, CookieInterface::SAMESITE_VALUES)) {
<add> if (!in_array($sameSite, CookieInterface::SAMESITE_VALUES, true)) {
<ide> throw new InvalidArgumentException(
<ide> 'Samesite value must be either of: ' . implode(',', CookieInterface::SAMESITE_VALUES)
<ide> );
<ide><path>tests/TestCase/Http/Cookie/CookieTest.php
<ide> public function testGetId()
<ide> $cookie = new Cookie('test', 'val', null, '/path', 'example.com');
<ide> $this->assertSame('test;example.com;/path', $cookie->getId());
<ide> }
<add>
<add> public function testCreateFromHeaderString()
<add> {
<add> $header = 'cakephp=cakephp-rocks; expires=Wed, 01-Dec-2027 12:00:00 GMT; path=/; domain=cakephp.org; samesite=invalid; secure; httponly';
<add> $result = Cookie::createFromHeaderString($header);
<add>
<add> // Ignore invalid value when parsing headers
<add> // https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1
<add> $this->assertNull($result->getSameSite());
<add> }
<ide> } | 2 |
Text | Text | add info on what's used for fswatch on aix | 8af25a39d32d2383be219fd3a56dc773fe9277b0 | <ide><path>doc/api/fs.md
<ide> to be notified of filesystem changes.
<ide> * On OS X, this uses `kqueue` for files and 'FSEvents' for directories.
<ide> * On SunOS systems (including Solaris and SmartOS), this uses `event ports`.
<ide> * On Windows systems, this feature depends on `ReadDirectoryChangesW`.
<add>* On Aix systems, this feature depends on `AHAFS`, which must be enabled.
<ide>
<ide> If the underlying functionality is not available for some reason, then
<ide> `fs.watch` will not be able to function. For example, watching files or | 1 |
Ruby | Ruby | check existing prs for exact file match | 1395259ad67c29c353ad0528bdc297d1bb2d39ab | <ide><path>Library/Homebrew/dev-cmd/bump-cask-pr.rb
<ide> def fetch_resource(cask, new_version, url, **specs)
<ide> end
<ide>
<ide> def check_open_pull_requests(cask, tap_full_name, args:)
<del> GitHub.check_for_duplicate_pull_requests(cask.token, tap_full_name, state: "open", args: args)
<del> end
<del>
<del> def check_closed_pull_requests(cask, tap_full_name, version:, args:)
<del> # if we haven't already found open requests, try for an exact match across closed requests
<del> pr_title = "Update #{cask.token} from #{cask.version} to #{version}"
<del> GitHub.check_for_duplicate_pull_requests(pr_title, tap_full_name, state: "closed", args: args)
<add> GitHub.check_for_duplicate_pull_requests(cask.token, tap_full_name,
<add> state: "open",
<add> file: cask.sourcefile_path.relative_path_from(cask.tap.path).to_s,
<add> args: args)
<ide> end
<ide>
<ide> def run_cask_audit(cask, old_contents, args:)
<ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<ide> def formula_version(formula, spec, contents = nil)
<ide> end
<ide>
<ide> def check_open_pull_requests(formula, tap_full_name, args:)
<del> GitHub.check_for_duplicate_pull_requests(formula.name, tap_full_name, state: "open", args: args)
<add> GitHub.check_for_duplicate_pull_requests(formula.name, tap_full_name,
<add> state: "open",
<add> file: formula.path.relative_path_from(formula.tap.path).to_s,
<add> args: args)
<ide> end
<ide>
<ide> def check_closed_pull_requests(formula, tap_full_name, args:, version: nil, url: nil, tag: nil)
<ide> def check_closed_pull_requests(formula, tap_full_name, args:, version: nil, url:
<ide> version = Version.detect(url, **specs)
<ide> end
<ide> # if we haven't already found open requests, try for an exact match across closed requests
<del> GitHub.check_for_duplicate_pull_requests("#{formula.name} #{version}", tap_full_name, state: "closed", args: args)
<add> GitHub.check_for_duplicate_pull_requests("#{formula.name} #{version}", tap_full_name,
<add> state: "closed",
<add> file: formula.path.relative_path_from(formula.tap.path).to_s,
<add> args: args)
<ide> end
<ide>
<ide> def alias_update_pair(formula, new_formula_version)
<ide><path>Library/Homebrew/utils/github.rb
<ide> def fetch_pull_requests(query, tap_full_name, state: nil)
<ide> []
<ide> end
<ide>
<del> def check_for_duplicate_pull_requests(query, tap_full_name, state:, args:)
<add> def check_for_duplicate_pull_requests(query, tap_full_name, state:, file:, args:)
<ide> pull_requests = fetch_pull_requests(query, tap_full_name, state: state)
<add> pull_requests.select! do |pr|
<add> pr_files = open_api(url_to("repos", tap_full_name, "pulls", pr["number"], "files"))
<add> pr_files.any? { |f| f["filename"] == file }
<add> end
<ide> return if pull_requests.blank?
<ide>
<ide> duplicates_message = <<~EOS | 3 |
Go | Go | accept platform spec on container create | 7a9cb29fb980c0ab3928272cdc24c7089b2fcf64 | <ide><path>api/server/router/container/container_routes.go
<ide> import (
<ide> "strconv"
<ide> "syscall"
<ide>
<add> "github.com/containerd/containerd/platforms"
<ide> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/backend"
<ide> import (
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/signal"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> "golang.org/x/net/websocket"
<ide> func (s *containerRouter) postContainersCreate(ctx context.Context, w http.Respo
<ide> }
<ide> }
<ide>
<add> var platform *specs.Platform
<add> if versions.GreaterThanOrEqualTo(version, "1.41") {
<add> if v := r.Form.Get("platform"); v != "" {
<add> p, err := platforms.Parse(v)
<add> if err != nil {
<add> return errdefs.InvalidParameter(err)
<add> }
<add> platform = &p
<add> }
<add> defaultPlatform := platforms.DefaultSpec()
<add> if platform == nil {
<add> platform = &defaultPlatform
<add> }
<add> if platform.OS == "" {
<add> platform.OS = defaultPlatform.OS
<add> }
<add> if platform.Architecture == "" {
<add> platform.Architecture = defaultPlatform.Architecture
<add> platform.Variant = defaultPlatform.Variant
<add> }
<add> }
<add>
<ide> if hostConfig != nil && hostConfig.PidsLimit != nil && *hostConfig.PidsLimit <= 0 {
<ide> // Don't set a limit if either no limit was specified, or "unlimited" was
<ide> // explicitly set.
<ide> func (s *containerRouter) postContainersCreate(ctx context.Context, w http.Respo
<ide> HostConfig: hostConfig,
<ide> NetworkingConfig: networkingConfig,
<ide> AdjustCPUShares: adjustCPUShares,
<add> Platform: platform,
<ide> })
<ide> if err != nil {
<ide> return err
<ide><path>api/types/configs.go
<ide> package types // import "github.com/docker/docker/api/types"
<ide> import (
<ide> "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/api/types/network"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> )
<ide>
<ide> // configs holds structs used for internal communication between the
<ide> type ContainerCreateConfig struct {
<ide> Config *container.Config
<ide> HostConfig *container.HostConfig
<ide> NetworkingConfig *network.NetworkingConfig
<add> Platform *specs.Platform
<ide> AdjustCPUShares bool
<ide> }
<ide>
<ide><path>client/container_create.go
<ide> import (
<ide> "encoding/json"
<ide> "net/url"
<ide>
<add> "github.com/containerd/containerd/platforms"
<ide> "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/api/types/network"
<ide> "github.com/docker/docker/api/types/versions"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> )
<ide>
<ide> type configWrapper struct {
<ide> *container.Config
<ide> HostConfig *container.HostConfig
<ide> NetworkingConfig *network.NetworkingConfig
<add> Platform *specs.Platform
<ide> }
<ide>
<ide> // ContainerCreate creates a new container based in the given configuration.
<ide> // It can be associated with a name, but it's not mandatory.
<del>func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (container.ContainerCreateCreatedBody, error) {
<add>func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *specs.Platform, containerName string) (container.ContainerCreateCreatedBody, error) {
<ide> var response container.ContainerCreateCreatedBody
<ide>
<ide> if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil {
<ide> func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config
<ide> hostConfig.AutoRemove = false
<ide> }
<ide>
<add> if err := cli.NewVersionError("1.41", "specify container image platform"); platform != nil && err != nil {
<add> return response, err
<add> }
<add>
<ide> query := url.Values{}
<add> if platform != nil {
<add> query.Set("platform", platforms.Format(*platform))
<add> }
<add>
<ide> if containerName != "" {
<ide> query.Set("name", containerName)
<ide> }
<ide><path>client/container_create_test.go
<ide> func TestContainerCreateError(t *testing.T) {
<ide> client := &Client{
<ide> client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
<ide> }
<del> _, err := client.ContainerCreate(context.Background(), nil, nil, nil, "nothing")
<add> _, err := client.ContainerCreate(context.Background(), nil, nil, nil, nil, "nothing")
<ide> if !errdefs.IsSystem(err) {
<ide> t.Fatalf("expected a Server Error while testing StatusInternalServerError, got %T", err)
<ide> }
<ide> func TestContainerCreateError(t *testing.T) {
<ide> client = &Client{
<ide> client: newMockClient(errorMock(http.StatusNotFound, "Server error")),
<ide> }
<del> _, err = client.ContainerCreate(context.Background(), nil, nil, nil, "nothing")
<add> _, err = client.ContainerCreate(context.Background(), nil, nil, nil, nil, "nothing")
<ide> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected a Server Error while testing StatusNotFound, got %T", err)
<ide> }
<ide> func TestContainerCreateImageNotFound(t *testing.T) {
<ide> client := &Client{
<ide> client: newMockClient(errorMock(http.StatusNotFound, "No such image")),
<ide> }
<del> _, err := client.ContainerCreate(context.Background(), &container.Config{Image: "unknown_image"}, nil, nil, "unknown")
<add> _, err := client.ContainerCreate(context.Background(), &container.Config{Image: "unknown_image"}, nil, nil, nil, "unknown")
<ide> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected an imageNotFound error, got %v, %T", err, err)
<ide> }
<ide> func TestContainerCreateWithName(t *testing.T) {
<ide> }),
<ide> }
<ide>
<del> r, err := client.ContainerCreate(context.Background(), nil, nil, nil, "container_name")
<add> r, err := client.ContainerCreate(context.Background(), nil, nil, nil, nil, "container_name")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestContainerCreateAutoRemove(t *testing.T) {
<ide> client: newMockClient(autoRemoveValidator(false)),
<ide> version: "1.24",
<ide> }
<del> if _, err := client.ContainerCreate(context.Background(), nil, &container.HostConfig{AutoRemove: true}, nil, ""); err != nil {
<add> if _, err := client.ContainerCreate(context.Background(), nil, &container.HostConfig{AutoRemove: true}, nil, nil, ""); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> client = &Client{
<ide> client: newMockClient(autoRemoveValidator(true)),
<ide> version: "1.25",
<ide> }
<del> if _, err := client.ContainerCreate(context.Background(), nil, &container.HostConfig{AutoRemove: true}, nil, ""); err != nil {
<add> if _, err := client.ContainerCreate(context.Background(), nil, &container.HostConfig{AutoRemove: true}, nil, nil, ""); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }
<ide><path>client/interface.go
<ide> import (
<ide> "github.com/docker/docker/api/types/registry"
<ide> "github.com/docker/docker/api/types/swarm"
<ide> volumetypes "github.com/docker/docker/api/types/volume"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> )
<ide>
<ide> // CommonAPIClient is the common methods between stable and experimental versions of APIClient.
<ide> type CommonAPIClient interface {
<ide> type ContainerAPIClient interface {
<ide> ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error)
<ide> ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error)
<del> ContainerCreate(ctx context.Context, config *containertypes.Config, hostConfig *containertypes.HostConfig, networkingConfig *networktypes.NetworkingConfig, containerName string) (containertypes.ContainerCreateCreatedBody, error)
<add> ContainerCreate(ctx context.Context, config *containertypes.Config, hostConfig *containertypes.HostConfig, networkingConfig *networktypes.NetworkingConfig, platform *specs.Platform, containerName string) (containertypes.ContainerCreateCreatedBody, error)
<ide> ContainerDiff(ctx context.Context, container string) ([]containertypes.ContainerChangeResponseItem, error)
<ide> ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error)
<ide> ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error)
<ide><path>daemon/create.go
<ide> func (daemon *Daemon) containerCreate(opts createOpts) (containertypes.Container
<ide>
<ide> os := runtime.GOOS
<ide> if opts.params.Config.Image != "" {
<del> img, err := daemon.imageService.GetImage(opts.params.Config.Image)
<add> img, err := daemon.imageService.GetImage(opts.params.Config.Image, opts.params.Platform)
<ide> if err == nil {
<ide> os = img.OS
<ide> }
<ide> func (daemon *Daemon) create(opts createOpts) (retC *container.Container, retErr
<ide>
<ide> os := runtime.GOOS
<ide> if opts.params.Config.Image != "" {
<del> img, err = daemon.imageService.GetImage(opts.params.Config.Image)
<add> img, err = daemon.imageService.GetImage(opts.params.Config.Image, opts.params.Platform)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide><path>daemon/images/cache.go
<ide> func (i *ImageService) MakeImageCache(sourceRefs []string) builder.ImageCache {
<ide> cache := cache.New(i.imageStore)
<ide>
<ide> for _, ref := range sourceRefs {
<del> img, err := i.GetImage(ref)
<add> img, err := i.GetImage(ref, nil)
<ide> if err != nil {
<ide> logrus.Warnf("Could not look up %s for cache resolution, skipping: %+v", ref, err)
<ide> continue
<ide><path>daemon/images/image.go
<ide> package images // import "github.com/docker/docker/daemon/images"
<ide> import (
<ide> "fmt"
<ide>
<add> "github.com/pkg/errors"
<add>
<ide> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/image"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> )
<ide>
<ide> // ErrImageDoesNotExist is error returned when no image can be found for a reference.
<ide> func (e ErrImageDoesNotExist) Error() string {
<ide> func (e ErrImageDoesNotExist) NotFound() {}
<ide>
<ide> // GetImage returns an image corresponding to the image referred to by refOrID.
<del>func (i *ImageService) GetImage(refOrID string) (*image.Image, error) {
<add>func (i *ImageService) GetImage(refOrID string, platform *specs.Platform) (retImg *image.Image, retErr error) {
<add> defer func() {
<add> if retErr != nil || retImg == nil || platform == nil {
<add> return
<add> }
<add>
<add> // This allows us to tell clients that we don't have the image they asked for
<add> // Where this gets hairy is the image store does not currently support multi-arch images, e.g.:
<add> // An image `foo` may have a multi-arch manifest, but the image store only fetches the image for a specific platform
<add> // The image store does not store the manifest list and image tags are assigned to architecture specific images.
<add> // So we can have a `foo` image that is amd64 but the user requested armv7. If the user looks at the list of images.
<add> // This may be confusing.
<add> // The alternative to this is to return a errdefs.Conflict error with a helpful message, but clients will not be
<add> // able to automatically tell what causes the conflict.
<add> if retImg.OS != platform.OS {
<add> retErr = errdefs.NotFound(errors.Errorf("image with reference %s was found but does not match the specified OS platform: wanted: %s, actual: %s", refOrID, platform.OS, retImg.OS))
<add> retImg = nil
<add> return
<add> }
<add> if retImg.Architecture != platform.Architecture {
<add> retErr = errdefs.NotFound(errors.Errorf("image with reference %s was found but does not match the specified platform cpu architecture: wanted: %s, actual: %s", refOrID, platform.Architecture, retImg.Architecture))
<add> retImg = nil
<add> return
<add> }
<add>
<add> // Only validate variant if retImg has a variant set.
<add> // The image variant may not be set since it's a newer field.
<add> if platform.Variant != "" && retImg.Variant != "" && retImg.Variant != platform.Variant {
<add> retErr = errdefs.NotFound(errors.Errorf("image with reference %s was found but does not match the specified platform cpu architecture variant: wanted: %s, actual: %s", refOrID, platform.Variant, retImg.Variant))
<add> retImg = nil
<add> return
<add> }
<add> }()
<ide> ref, err := reference.ParseAnyReference(refOrID)
<ide> if err != nil {
<ide> return nil, errdefs.InvalidParameter(err)
<ide><path>daemon/images/image_builder.go
<ide> func (i *ImageService) pullForBuilder(ctx context.Context, name string, authConf
<ide> if err := i.pullImageWithReference(ctx, ref, platform, nil, pullRegistryAuth, output); err != nil {
<ide> return nil, err
<ide> }
<del> return i.GetImage(name)
<add> return i.GetImage(name, platform)
<ide> }
<ide>
<ide> // GetImageAndReleasableLayer returns an image and releaseable layer for a reference or ID.
<ide> func (i *ImageService) GetImageAndReleasableLayer(ctx context.Context, refOrID s
<ide> }
<ide>
<ide> if opts.PullOption != backend.PullOptionForcePull {
<del> image, err := i.GetImage(refOrID)
<add> image, err := i.GetImage(refOrID, opts.Platform)
<ide> if err != nil && opts.PullOption == backend.PullOptionNoPull {
<ide> return nil, nil, err
<ide> }
<ide><path>daemon/images/image_delete.go
<ide> func (i *ImageService) ImageDelete(imageRef string, force, prune bool) ([]types.
<ide> start := time.Now()
<ide> records := []types.ImageDeleteResponseItem{}
<ide>
<del> img, err := i.GetImage(imageRef)
<add> img, err := i.GetImage(imageRef, nil)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide><path>daemon/images/image_events.go
<ide> func (i *ImageService) LogImageEvent(imageID, refName, action string) {
<ide>
<ide> // LogImageEventWithAttributes generates an event related to an image with specific given attributes.
<ide> func (i *ImageService) LogImageEventWithAttributes(imageID, refName, action string, attributes map[string]string) {
<del> img, err := i.GetImage(imageID)
<add> img, err := i.GetImage(imageID, nil)
<ide> if err == nil && img.Config != nil {
<ide> // image has not been removed yet.
<ide> // it could be missing if the event is `delete`.
<ide><path>daemon/images/image_history.go
<ide> import (
<ide> // name by walking the image lineage.
<ide> func (i *ImageService) ImageHistory(name string) ([]*image.HistoryResponseItem, error) {
<ide> start := time.Now()
<del> img, err := i.GetImage(name)
<add> img, err := i.GetImage(name, nil)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (i *ImageService) ImageHistory(name string) ([]*image.HistoryResponseItem,
<ide> if id == "" {
<ide> break
<ide> }
<del> histImg, err = i.GetImage(id.String())
<add> histImg, err = i.GetImage(id.String(), nil)
<ide> if err != nil {
<ide> break
<ide> }
<ide><path>daemon/images/image_inspect.go
<ide> import (
<ide> // LookupImage looks up an image by name and returns it as an ImageInspect
<ide> // structure.
<ide> func (i *ImageService) LookupImage(name string) (*types.ImageInspect, error) {
<del> img, err := i.GetImage(name)
<add> img, err := i.GetImage(name, nil)
<ide> if err != nil {
<ide> return nil, errors.Wrapf(err, "no such image: %s", name)
<ide> }
<ide><path>daemon/images/image_tag.go
<ide> import (
<ide> // TagImage creates the tag specified by newTag, pointing to the image named
<ide> // imageName (alternatively, imageName can also be an image ID).
<ide> func (i *ImageService) TagImage(imageName, repository, tag string) (string, error) {
<del> img, err := i.GetImage(imageName)
<add> img, err := i.GetImage(imageName, nil)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide><path>daemon/images/images.go
<ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr
<ide>
<ide> var beforeFilter, sinceFilter *image.Image
<ide> err = imageFilters.WalkValues("before", func(value string) error {
<del> beforeFilter, err = i.GetImage(value)
<add> beforeFilter, err = i.GetImage(value, nil)
<ide> return err
<ide> })
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> err = imageFilters.WalkValues("since", func(value string) error {
<del> sinceFilter, err = i.GetImage(value)
<add> sinceFilter, err = i.GetImage(value, nil)
<ide> return err
<ide> })
<ide> if err != nil {
<ide><path>daemon/list.go
<ide> func (daemon *Daemon) foldFilter(view container.View, config *types.ContainerLis
<ide> if psFilters.Contains("ancestor") {
<ide> ancestorFilter = true
<ide> psFilters.WalkValues("ancestor", func(ancestor string) error {
<del> img, err := daemon.imageService.GetImage(ancestor)
<add> img, err := daemon.imageService.GetImage(ancestor, nil)
<ide> if err != nil {
<ide> logrus.Warnf("Error while looking up for image %v", ancestor)
<ide> return nil
<ide> func (daemon *Daemon) refreshImage(s *container.Snapshot, ctx *listContext) (*ty
<ide> c := s.Container
<ide> image := s.Image // keep the original ref if still valid (hasn't changed)
<ide> if image != s.ImageID {
<del> img, err := daemon.imageService.GetImage(image)
<add> img, err := daemon.imageService.GetImage(image, nil)
<ide> if _, isDNE := err.(images.ErrImageDoesNotExist); err != nil && !isDNE {
<ide> return nil, err
<ide> }
<ide><path>daemon/oci_windows.go
<ide> const (
<ide>
<ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) {
<ide>
<del> img, err := daemon.imageService.GetImage(string(c.ImageID))
<add> img, err := daemon.imageService.GetImage(string(c.ImageID), nil)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestContainerAPIBadPort(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
<add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.ErrorContains(c, err, `invalid port specification: "aa80"`)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestContainerAPICreate(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
<add> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.NilError(c, err)
<ide>
<ide> out, _ := dockerCmd(c, "start", "-a", container.ID)
<ide> func (s *DockerSuite) TestContainerAPICreateEmptyConfig(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &containertypes.Config{}, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
<add> _, err = cli.ContainerCreate(context.Background(), &containertypes.Config{}, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "")
<ide>
<ide> expected := "No command specified"
<ide> assert.ErrorContains(c, err, expected)
<ide> func (s *DockerSuite) TestContainerAPICreateMultipleNetworksConfig(c *testing.T)
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networkingConfig, "")
<add> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networkingConfig, nil, "")
<ide> msg := err.Error()
<ide> // network name order in error message is not deterministic
<ide> assert.Assert(c, strings.Contains(msg, "Container cannot be connected to network endpoints"))
<ide> func UtilCreateNetworkMode(c *testing.T, networkMode containertypes.NetworkMode)
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
<add> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.NilError(c, err)
<ide>
<ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
<ide> func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
<add> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.NilError(c, err)
<ide>
<ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
<ide> func (s *DockerSuite) TestContainerAPIStart(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, name)
<add> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, name)
<ide> assert.NilError(c, err)
<ide>
<ide> err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{})
<ide> func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *t
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "echotest")
<add> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "echotest")
<ide> assert.NilError(c, err)
<ide> out, _ := dockerCmd(c, "start", "-a", "echotest")
<ide> assert.Equal(c, strings.TrimSpace(out), "hello world")
<ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *testing.T)
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "echotest")
<add> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "echotest")
<ide> assert.NilError(c, err)
<ide> out, _ := dockerCmd(c, "start", "-a", "echotest")
<ide> assert.Equal(c, strings.TrimSpace(out), "hello world")
<ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *tes
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config2, &hostConfig, &networktypes.NetworkingConfig{}, "capaddtest1")
<add> _, err = cli.ContainerCreate(context.Background(), &config2, &hostConfig, &networktypes.NetworkingConfig{}, nil, "capaddtest1")
<ide> assert.NilError(c, err)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestContainerAPICreateNoHostConfig118(c *testing.T) {
<ide> cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.18"))
<ide> assert.NilError(c, err)
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
<add> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.NilError(c, err)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *testing.T
<ide> }
<ide> name := "wrong-cpuset-cpus"
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig1, &networktypes.NetworkingConfig{}, name)
<add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig1, &networktypes.NetworkingConfig{}, nil, name)
<ide> expected := "Invalid value 1-42,, for cpuset cpus"
<ide> assert.ErrorContains(c, err, expected)
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *testing.T
<ide> },
<ide> }
<ide> name = "wrong-cpuset-mems"
<del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig2, &networktypes.NetworkingConfig{}, name)
<add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig2, &networktypes.NetworkingConfig{}, nil, name)
<ide> expected = "Invalid value 42-3,1-- for cpuset mems"
<ide> assert.ErrorContains(c, err, expected)
<ide> }
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
<add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.ErrorContains(c, err, "SHM size can not be less than 0")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *testin
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
<add> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.NilError(c, err)
<ide>
<ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
<add> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.NilError(c, err)
<ide>
<ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
<ide> func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
<add> container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.NilError(c, err)
<ide>
<ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
<ide> func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
<add> container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, "")
<ide> assert.NilError(c, err)
<ide>
<ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
<ide> func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *tes
<ide> defer cli.Close()
<ide>
<ide> name := "oomscoreadj-over"
<del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, name)
<add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, name)
<ide>
<ide> expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]"
<ide> assert.ErrorContains(c, err, expected)
<ide> func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *tes
<ide> }
<ide>
<ide> name = "oomscoreadj-low"
<del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, name)
<add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, name)
<ide>
<ide> expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]"
<ide> assert.ErrorContains(c, err, expected)
<ide> func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, name)
<add> _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, nil, name)
<ide> assert.NilError(c, err)
<ide>
<ide> err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{})
<ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *testing.T) {
<ide> for i, x := range cases {
<ide> x := x
<ide> c.Run(fmt.Sprintf("case %d", i), func(c *testing.T) {
<del> _, err = apiClient.ContainerCreate(context.Background(), &x.config, &x.hostConfig, &networktypes.NetworkingConfig{}, "")
<add> _, err = apiClient.ContainerCreate(context.Background(), &x.config, &x.hostConfig, &networktypes.NetworkingConfig{}, nil, "")
<ide> if len(x.msg) > 0 {
<ide> assert.ErrorContains(c, err, x.msg, "%v", cases[i].config)
<ide> } else {
<ide> func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "test")
<add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, "test")
<ide> assert.NilError(c, err)
<ide>
<ide> out, _ := dockerCmd(c, "start", "-a", "test")
<ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) {
<ide> &containertypes.Config{Image: testImg},
<ide> &containertypes.HostConfig{Mounts: []mounttypes.Mount{x.spec}},
<ide> &networktypes.NetworkingConfig{},
<add> nil,
<ide> "")
<ide> assert.NilError(c, err)
<ide>
<ide> func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *testing.T) {
<ide> Mounts: []mounttypes.Mount{x.cfg},
<ide> }
<ide>
<del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, cName)
<add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, nil, cName)
<ide> assert.NilError(c, err)
<ide> out, _ := dockerCmd(c, "start", "-a", cName)
<ide> for _, option := range x.expectedOptions {
<ide><path>integration-cli/docker_api_containers_windows_test.go
<ide> func (s *DockerSuite) TestContainersAPICreateMountsBindNamedPipe(c *testing.T) {
<ide> },
<ide> },
<ide> },
<del> nil, name)
<add> nil, nil, name)
<ide> assert.NilError(c, err)
<ide>
<ide> err = client.ContainerStart(ctx, name, types.ContainerStartOptions{})
<ide><path>integration-cli/docker_cli_volume_test.go
<ide> func (s *DockerSuite) TestDuplicateMountpointsForVolumesFromAndMounts(c *testing
<ide> },
<ide> },
<ide> }
<del> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, "app")
<add> _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "app")
<ide>
<ide> assert.NilError(c, err)
<ide>
<ide><path>integration/container/create_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/container"
<add> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/api/types/network"
<ide> "github.com/docker/docker/api/types/versions"
<ide> "github.com/docker/docker/client"
<ide> "github.com/docker/docker/errdefs"
<ide> ctr "github.com/docker/docker/integration/internal/container"
<ide> "github.com/docker/docker/oci"
<ide> "github.com/docker/docker/testutil/request"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> "gotest.tools/v3/assert"
<ide> is "gotest.tools/v3/assert/cmp"
<ide> "gotest.tools/v3/poll"
<ide> func TestCreateFailsWhenIdentifierDoesNotExist(t *testing.T) {
<ide> &container.Config{Image: tc.image},
<ide> &container.HostConfig{},
<ide> &network.NetworkingConfig{},
<add> nil,
<ide> "",
<ide> )
<ide> assert.Check(t, is.ErrorContains(err, tc.expectedError))
<ide> func TestCreateLinkToNonExistingContainer(t *testing.T) {
<ide> Links: []string{"no-such-container"},
<ide> },
<ide> &network.NetworkingConfig{},
<add> nil,
<ide> "",
<ide> )
<ide> assert.Check(t, is.ErrorContains(err, "could not get container for no-such-container"))
<ide> func TestCreateWithInvalidEnv(t *testing.T) {
<ide> },
<ide> &container.HostConfig{},
<ide> &network.NetworkingConfig{},
<add> nil,
<ide> "",
<ide> )
<ide> assert.Check(t, is.ErrorContains(err, tc.expectedError))
<ide> func TestCreateTmpfsMountsTarget(t *testing.T) {
<ide> Tmpfs: map[string]string{tc.target: ""},
<ide> },
<ide> &network.NetworkingConfig{},
<add> nil,
<ide> "",
<ide> )
<ide> assert.Check(t, is.ErrorContains(err, tc.expectedError))
<ide> func TestCreateWithCustomMaskedPaths(t *testing.T) {
<ide> &config,
<ide> &hc,
<ide> &network.NetworkingConfig{},
<add> nil,
<ide> name,
<ide> )
<ide> assert.NilError(t, err)
<ide> func TestCreateWithCapabilities(t *testing.T) {
<ide> &container.Config{Image: "busybox"},
<ide> &tc.hostConfig,
<ide> &network.NetworkingConfig{},
<add> nil,
<ide> "",
<ide> )
<ide> if tc.expectedError == "" {
<ide> func TestCreateWithCustomReadonlyPaths(t *testing.T) {
<ide> &config,
<ide> &hc,
<ide> &network.NetworkingConfig{},
<add> nil,
<ide> name,
<ide> )
<ide> assert.NilError(t, err)
<ide> func TestCreateWithInvalidHealthcheckParams(t *testing.T) {
<ide> cfg.Healthcheck.StartPeriod = tc.startPeriod
<ide> }
<ide>
<del> resp, err := client.ContainerCreate(ctx, &cfg, &container.HostConfig{}, nil, "")
<add> resp, err := client.ContainerCreate(ctx, &cfg, &container.HostConfig{}, nil, nil, "")
<ide> assert.Check(t, is.Equal(len(resp.Warnings), 0))
<ide>
<ide> if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") {
<ide> func TestCreateTmpfsOverrideAnonymousVolume(t *testing.T) {
<ide> assert.NilError(t, err)
<ide> }
<ide> }
<add>
<add>// Test that if the referenced image platform does not match the requested platform on container create that we get an
<add>// error.
<add>func TestCreateDifferentPlatform(t *testing.T) {
<add> defer setupTest(t)()
<add> c := testEnv.APIClient()
<add> ctx := context.Background()
<add>
<add> img, _, err := c.ImageInspectWithRaw(ctx, "busybox:latest")
<add> assert.NilError(t, err)
<add> assert.Assert(t, img.Architecture != "")
<add>
<add> t.Run("different os", func(t *testing.T) {
<add> p := specs.Platform{
<add> OS: img.Os + "DifferentOS",
<add> Architecture: img.Architecture,
<add> Variant: img.Variant,
<add> }
<add> _, err := c.ContainerCreate(ctx, &containertypes.Config{Image: "busybox:latest"}, &containertypes.HostConfig{}, nil, &p, "")
<add> assert.Assert(t, client.IsErrNotFound(err), err)
<add> })
<add> t.Run("different cpu arch", func(t *testing.T) {
<add> p := specs.Platform{
<add> OS: img.Os,
<add> Architecture: img.Architecture + "DifferentArch",
<add> Variant: img.Variant,
<add> }
<add> _, err := c.ContainerCreate(ctx, &containertypes.Config{Image: "busybox:latest"}, &containertypes.HostConfig{}, nil, &p, "")
<add> assert.Assert(t, client.IsErrNotFound(err), err)
<add> })
<add>}
<ide><path>integration/container/ipcmode_linux_test.go
<ide> func testIpcNonePrivateShareable(t *testing.T, mode string, mustBeMounted bool,
<ide> client := testEnv.APIClient()
<ide> ctx := context.Background()
<ide>
<del> resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, "")
<add> resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, nil, "")
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(len(resp.Warnings), 0))
<ide>
<ide> func testIpcContainer(t *testing.T, donorMode string, mustWork bool) {
<ide> client := testEnv.APIClient()
<ide>
<ide> // create and start the "donor" container
<del> resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, "")
<add> resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, nil, "")
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(len(resp.Warnings), 0))
<ide> name1 := resp.ID
<ide> func testIpcContainer(t *testing.T, donorMode string, mustWork bool) {
<ide>
<ide> // create and start the second container
<ide> hostCfg.IpcMode = containertypes.IpcMode("container:" + name1)
<del> resp, err = client.ContainerCreate(ctx, &cfg, &hostCfg, nil, "")
<add> resp, err = client.ContainerCreate(ctx, &cfg, &hostCfg, nil, nil, "")
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(len(resp.Warnings), 0))
<ide> name2 := resp.ID
<ide> func TestAPIIpcModeHost(t *testing.T) {
<ide> ctx := context.Background()
<ide>
<ide> client := testEnv.APIClient()
<del> resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, "")
<add> resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, nil, "")
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(len(resp.Warnings), 0))
<ide> name := resp.ID
<ide> func testDaemonIpcPrivateShareable(t *testing.T, mustBeShared bool, arg ...strin
<ide> }
<ide> ctx := context.Background()
<ide>
<del> resp, err := c.ContainerCreate(ctx, &cfg, &containertypes.HostConfig{}, nil, "")
<add> resp, err := c.ContainerCreate(ctx, &cfg, &containertypes.HostConfig{}, nil, nil, "")
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(len(resp.Warnings), 0))
<ide>
<ide><path>integration/container/mounts_linux_test.go
<ide> func TestContainerNetworkMountsNoChown(t *testing.T) {
<ide> assert.NilError(t, err)
<ide> defer cli.Close()
<ide>
<del> ctrCreate, err := cli.ContainerCreate(ctx, &config, &hostConfig, &network.NetworkingConfig{}, "")
<add> ctrCreate, err := cli.ContainerCreate(ctx, &config, &hostConfig, &network.NetworkingConfig{}, nil, "")
<ide> assert.NilError(t, err)
<ide> // container will exit immediately because of no tty, but we only need the start sequence to test the condition
<ide> err = cli.ContainerStart(ctx, ctrCreate.ID, types.ContainerStartOptions{})
<ide> func TestMountDaemonRoot(t *testing.T) {
<ide> c, err := client.ContainerCreate(ctx, &containertypes.Config{
<ide> Image: "busybox",
<ide> Cmd: []string{"true"},
<del> }, hc, nil, "")
<add> }, hc, nil, nil, "")
<ide>
<ide> if err != nil {
<ide> if test.expected != "" {
<ide><path>integration/container/restart_test.go
<ide> func TestDaemonRestartKillContainers(t *testing.T) {
<ide> defer d.Stop(t)
<ide> ctx := context.Background()
<ide>
<del> resp, err := client.ContainerCreate(ctx, c.config, c.hostConfig, nil, "")
<add> resp, err := client.ContainerCreate(ctx, c.config, c.hostConfig, nil, nil, "")
<ide> assert.NilError(t, err)
<ide> defer client.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{Force: true})
<ide>
<ide><path>integration/internal/container/container.go
<ide> import (
<ide> "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/api/types/network"
<ide> "github.com/docker/docker/client"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> "gotest.tools/v3/assert"
<ide> )
<ide>
<ide> type TestContainerConfig struct {
<ide> Config *container.Config
<ide> HostConfig *container.HostConfig
<ide> NetworkingConfig *network.NetworkingConfig
<add> Platform *specs.Platform
<ide> }
<ide>
<ide> // create creates a container with the specified options
<ide> func create(ctx context.Context, t *testing.T, client client.APIClient, ops ...f
<ide> op(config)
<ide> }
<ide>
<del> return client.ContainerCreate(ctx, config.Config, config.HostConfig, config.NetworkingConfig, config.Name)
<add> return client.ContainerCreate(ctx, config.Config, config.HostConfig, config.NetworkingConfig, config.Platform, config.Name)
<ide> }
<ide>
<ide> // Create creates a container with the specified options, asserting that there was no error
<ide><path>integration/internal/container/ops.go
<ide> import (
<ide> networktypes "github.com/docker/docker/api/types/network"
<ide> "github.com/docker/docker/api/types/strslice"
<ide> "github.com/docker/go-connections/nat"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> )
<ide>
<ide> // WithName sets the name of the container
<ide> func WithExtraHost(extraHost string) func(*TestContainerConfig) {
<ide> c.HostConfig.ExtraHosts = append(c.HostConfig.ExtraHosts, extraHost)
<ide> }
<ide> }
<add>
<add>// WithPlatform specifies the desired platform the image should have.
<add>func WithPlatform(p *specs.Platform) func(*TestContainerConfig) {
<add> return func(c *TestContainerConfig) {
<add> c.Platform = p
<add> }
<add>}
<ide><path>integration/plugin/logging/read_test.go
<ide> func TestReadPluginNoRead(t *testing.T) {
<ide> cfg,
<ide> &container.HostConfig{LogConfig: container.LogConfig{Type: "test"}},
<ide> nil,
<add> nil,
<ide> "",
<ide> )
<ide> assert.Assert(t, err)
<ide><path>testutil/fakestorage/storage.go
<ide> COPY . /static`); err != nil {
<ide> // Start the container
<ide> b, err := c.ContainerCreate(context.Background(), &containertypes.Config{
<ide> Image: image,
<del> }, &containertypes.HostConfig{}, nil, container)
<add> }, &containertypes.HostConfig{}, nil, nil, container)
<ide> assert.NilError(t, err)
<ide> err = c.ContainerStart(context.Background(), b.ID, types.ContainerStartOptions{})
<ide> assert.NilError(t, err) | 28 |
Ruby | Ruby | reuse available collection? check instead of macro | bfd0159413ac7941c80166b41856795d93158bb1 | <ide><path>activerecord/lib/active_record/associations/association.rb
<ide> def find_target?
<ide> def creation_attributes
<ide> attributes = {}
<ide>
<del> if (reflection.has_one? || reflection.macro == :has_many) && !options[:through]
<add> if (reflection.has_one? || reflection.collection?) && !options[:through]
<ide> attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key]
<ide>
<ide> if reflection.options[:as]
<ide><path>activerecord/lib/active_record/associations/has_many_through_association.rb
<ide> def build_record(attributes)
<ide>
<ide> inverse = source_reflection.inverse_of
<ide> if inverse
<del> if inverse.macro == :has_many
<add> if inverse.collection?
<ide> record.send(inverse.name) << build_through_record(record)
<ide> elsif inverse.has_one?
<ide> record.send("#{inverse.name}=", build_through_record(record))
<ide> def delete_records(records, method)
<ide> klass.decrement_counter counter, records.map(&:id)
<ide> end
<ide>
<del> if through_reflection.macro == :has_many && update_through_counter?(method)
<add> if through_reflection.collection? && update_through_counter?(method)
<ide> update_counter(-count, through_reflection)
<ide> end
<ide>
<ide> def delete_through_records(records)
<ide> records.each do |record|
<ide> through_records = through_records_for(record)
<ide>
<del> if through_reflection.macro == :has_many
<add> if through_reflection.collection?
<ide> through_records.each { |r| through_association.target.delete(r) }
<ide> else
<ide> if through_records.include?(through_association.target)
<ide><path>activerecord/lib/active_record/reflection.rb
<ide> def collection?
<ide> # * you use autosave; <tt>autosave: true</tt>
<ide> # * the association is a +has_many+ association
<ide> def validate?
<del> !options[:validate].nil? ? options[:validate] : (options[:autosave] == true || macro == :has_many)
<add> !options[:validate].nil? ? options[:validate] : (options[:autosave] == true || collection?)
<ide> end
<ide>
<ide> # Returns +true+ if +self+ is a +belongs_to+ reflection. | 3 |
Python | Python | verify np.ma.take works on scalars | 6e5aa5e6b7980021ba5de67c872fad70dd4f9c92 | <ide><path>numpy/ma/tests/test_core.py
<ide> def test_take(self):
<ide> assert_equal(x.take([[0, 1], [0, 1]]),
<ide> masked_array([[10, 20], [10, 20]], [[0, 1], [0, 1]]))
<ide>
<add> # assert_equal crashes when passed np.ma.mask
<add> self.assertIs(x[1], np.ma.masked)
<add> self.assertIs(x.take(1), np.ma.masked)
<add>
<ide> x = array([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0, ]])
<ide> assert_equal(x.take([0, 2], axis=1),
<ide> array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]])) | 1 |
Javascript | Javascript | prepare test-assert for strictequal linting | 9c6e23d10ff4cfefd9d12fbf4c8614049b9a0a0f | <ide><path>test/parallel/test-assert.js
<ide> try {
<ide> }
<ide>
<ide> try {
<del> assert.strictEqual(1, 2, 'oh no');
<add> assert.strictEqual(1, 2, 'oh no'); // eslint-disable-line no-restricted-syntax
<ide> } catch (e) {
<ide> assert.strictEqual(e.message, 'oh no');
<del> assert.strictEqual(e.generatedMessage, false,
<del> 'Message incorrectly marked as generated');
<add> // Message should not be marked as generated.
<add> assert.strictEqual(e.generatedMessage, false);
<ide> }
<ide>
<ide> { | 1 |
Ruby | Ruby | check migration symlinks | b41a88eac4a1fe75af18d115d40c8821bcd2a160 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def migrate_tap_migration
<ide>
<ide> def migrate_formula_rename
<ide> Formula.installed.map(&:oldname).compact.each do |old_name|
<del> next unless (dir = HOMEBREW_CELLAR/old_name).directory? && !dir.subdirs.empty?
<add> old_name_dir = HOMEBREW_CELLAR/old_name
<add> next if old_name_dir.symlink?
<add> next unless old_name_dir.directory? && !old_name_dir.subdirs.empty?
<ide>
<ide> new_name = tap.formula_renames[old_name]
<ide> next unless new_name | 1 |
Python | Python | fix retried tasks with expirations | 6c0abdbc0ecfcd40c3d7bc5b190166d4df1d2ac0 | <ide><path>celery/app/amqp.py
<ide> def as_task_v2(self, task_id, name, args=None, kwargs=None,
<ide> now + timedelta(seconds=expires), tz=timezone,
<ide> )
<ide> eta = eta and eta.isoformat()
<del> expires = expires and expires.isoformat()
<add> # If we retry a task `expires` will already be ISO8601-formatted.
<add> if not isinstance(expires, string_t):
<add> expires = expires and expires.isoformat()
<ide>
<ide> if argsrepr is None:
<ide> argsrepr = saferepr(args, self.argsrepr_maxsize)
<ide><path>t/integration/tasks.py
<ide> def collect_ids(self, res, i):
<ide>
<ide> """
<ide> return res, (self.request.root_id, self.request.parent_id, i)
<add>
<add>
<add>@shared_task(bind=True, expires=60.0, max_retries=1)
<add>def retry_once(self):
<add> """Task that fails and is retried. Returns the number of retries."""
<add> if self.request.retries:
<add> return self.request.retries
<add> raise self.retry(countdown=0.1)
<ide><path>t/integration/test_tasks.py
<ide> from __future__ import absolute_import, unicode_literals
<ide> from celery import group
<ide> from .conftest import flaky
<del>from .tasks import print_unicode, sleeping
<add>from .tasks import print_unicode, retry_once, sleeping
<ide>
<ide>
<ide> class test_tasks:
<ide> def test_task_accepted(self, manager, sleep=1):
<ide> sleeping.delay(sleep)
<ide> manager.assert_accepted([r1.id])
<ide>
<add> @flaky
<add> def test_task_retried(self):
<add> res = retry_once.delay()
<add> assert res.get(timeout=10) == 1 # retried once
<add>
<ide> @flaky
<ide> def test_unicode_task(self, manager):
<ide> manager.join( | 3 |
Java | Java | fix typo in rmisupporttests | d54b903d28c176c20abde6134a302092b3107daf | <ide><path>spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java
<ide> private void doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefres
<ide> assertThat(condition1).isFalse();
<ide> assertThatExceptionOfType(springExceptionClass).isThrownBy(() ->
<ide> proxy.setName(rmiExceptionClass.getName()));
<del> boolean isRemoteConnectFaiure = RemoteConnectFailureException.class.isAssignableFrom(springExceptionClass);
<del> assertThat(factory.counter).isEqualTo(isRemoteConnectFaiure ? 2 : 1);
<add> boolean isRemoteConnectFailure = RemoteConnectFailureException.class.isAssignableFrom(springExceptionClass);
<add> assertThat(factory.counter).isEqualTo(isRemoteConnectFailure ? 2 : 1);
<ide> }
<ide>
<ide> @Test | 1 |
Javascript | Javascript | use findone in controllers/story | 92f4c7a41a3896b2b91356cc959d1de54a70f565 | <ide><path>controllers/story.js
<ide> exports.returnIndividualStory = function(req, res, next) {
<ide>
<ide> if (story.length < 1) {
<ide> req.flash('errors', {
<del> msg: "404: We couldn't find a story with that name. Please double check the name."
<add> msg: "404: We couldn't find a story with that name. " +
<add> "Please double check the name."
<ide> });
<ide>
<ide> return res.redirect('/news/');
<ide> exports.upvote = function(req, res, next) {
<ide> );
<ide> story.markModified('rank');
<ide> story.save();
<del> User.find({'_id': story.author.userId}, function(err, user) {
<del> 'use strict';
<add> User.findOne({'_id': story.author.userId}, function(err, user) {
<ide> if (err) {
<ide> return next(err);
<ide> }
<del> user = user.pop();
<ide> user.progressTimestamps.push(Date.now() || 0);
<ide> user.save(function (err, user) {
<ide> req.user.save(function (err, user) {
<ide> exports.storySubmission = function(req, res, next) {
<ide> if (link.search(/^https?:\/\//g) === -1) {
<ide> link = 'http://' + link;
<ide> }
<del> Story.count({'storyLink': new RegExp('^' + storyLink + '(?: [0-9]+)?$', 'i')}, function (err, storyCount) {
<add> Story.count({ storyLink: new RegExp('^' + storyLink + '(?: [0-9]+)?$', 'i')}, function (err, storyCount) {
<ide> if (err) {
<ide> return res.status(500);
<ide> }
<ide> exports.storySubmission = function(req, res, next) {
<ide> return next(err);
<ide> }
<ide> try {
<del> // Based on the context retrieve the parent object of the comment (Story/Comment)
<add> // Based on the context retrieve the parent
<add> // object of the comment (Story/Comment)
<ide> Context.find({'_id': data.associatedPost}, function (err, associatedContext) {
<ide> if (err) {
<ide> return next(err);
<ide> exports.storySubmission = function(req, res, next) {
<ide> if (err) {
<ide> return next(err);
<ide> }
<del> // If the emails of both authors differ, only then proceed with email notification
<del> if (typeof data.author !== 'undefined' && data.author.email && typeof recipient !== 'undefined' && recipient.email && (data.author.email !== recipient.email)) {
<add> // If the emails of both authors differ,
<add> // only then proceed with email notification
<add> if (
<add> typeof data.author !== 'undefined' &&
<add> data.author.email &&
<add> typeof recipient !== 'undefined' &&
<add> recipient.email &&
<add> (data.author.email !== recipient.email)
<add> ) {
<ide> var transporter = nodemailer.createTransport({
<ide> service: 'Mandrill',
<ide> auth: {
<ide> exports.storySubmission = function(req, res, next) {
<ide> var mailOptions = {
<ide> to: recipient.email,
<ide> from: 'Team@freecodecamp.com',
<del> subject: data.author.username + ' replied to your post on Camper News',
<add> subject: data.author.username +
<add> ' replied to your post on Camper News',
<ide> text: [
<del> 'Just a quick heads-up: ' + data.author.username + ' replied to you on Camper News.',
<add> 'Just a quick heads-up: ',
<add> data.author.username,
<add> ' replied to you on Camper News.',
<ide> 'You can keep this conversation going.',
<del> 'Just head back to the discussion here: http://freecodecamp.com/news/' + data.originalStoryLink,
<add> 'Just head back to the discussion here: ',
<add> 'http://freecodecamp.com/news/',
<add> data.originalStoryLink,
<ide> '- the Free Code Camp Volunteer Team'
<ide> ].join('\n')
<ide> }; | 1 |
Ruby | Ruby | fix minor formatting error | 0e8abd2d09277ef785b1a1b0e680c4f69cd9dee7 | <ide><path>activerecord/lib/active_record/validations.rb
<ide> def validates_length_of(*attrs)
<ide> # the same time, and a Comment's title must be unique. At the database-level,
<ide> # the actions performed by these users could be interleaved in the following manner:
<ide> #
<del> # User 1 | User 2
<del> # ---------- | ----------
<add> # User 1 | User 2
<add> # ------------------------------------+--------------------------------------
<ide> # # User 1 checks whether there's |
<ide> # # already a comment with the title |
<ide> # # 'My Post'. This is not the case. | | 1 |
Javascript | Javascript | remove cache from array of vectors uniforms | 9b7de2df47f49d3c0895039b21ea32750928e587 | <ide><path>src/renderers/webgl/WebGLUniforms.js
<ide> function setValue1iv( gl, v ) {
<ide>
<ide> function setValueV2a( gl, v ) {
<ide>
<del> var cache = this.cache;
<ide> var data = flatten( v, this.size, 2 );
<ide>
<del> if ( arraysEqual( cache, data ) ) return;
<del>
<ide> gl.uniform2fv( this.addr, data );
<ide>
<del> this.updateCache( data );
<del>
<ide> }
<ide>
<ide> function setValueV3a( gl, v ) {
<ide>
<del> var cache = this.cache;
<ide> var data = flatten( v, this.size, 3 );
<ide>
<del> if ( arraysEqual( cache, data ) ) return;
<del>
<ide> gl.uniform3fv( this.addr, data );
<ide>
<del> this.updateCache( data );
<del>
<ide> }
<ide>
<ide> function setValueV4a( gl, v ) {
<ide>
<del> var cache = this.cache;
<ide> var data = flatten( v, this.size, 4 );
<ide>
<del> if ( arraysEqual( cache, data ) ) return;
<del>
<ide> gl.uniform4fv( this.addr, data );
<ide>
<del> this.updateCache( data );
<del>
<ide> }
<ide>
<ide> // Array of matrices (flat or from THREE clases) | 1 |
Ruby | Ruby | withdraw support for homebrew supplied *.pc files | fa3591681800f9da06cd2d0179a5ef9e63b10729 | <ide><path>Library/Homebrew/extend/os/mac/extend/ENV/std.rb
<ide> module Stdenv
<ide> # @private
<ide>
<del> undef homebrew_extra_pkg_config_paths, x11
<del>
<del> def homebrew_extra_pkg_config_paths
<del> ["#{HOMEBREW_LIBRARY}/Homebrew/os/mac/pkgconfig/#{MacOS.version}"]
<del> end
<add> undef x11
<ide>
<ide> def x11
<ide> # There are some config scripts here that should go in the PATH | 1 |
Ruby | Ruby | drop unnecessary map + compact in search_tap | d01c671d74ddafcbc0c8dc8eaa805d971e7169fc | <ide><path>Library/Homebrew/cmd/search.rb
<ide> def search_tap user, repo, rx
<ide> results = []
<ide> GitHub.open "https://api.github.com/repos/#{user}/homebrew-#{repo}/git/trees/HEAD?recursive=1" do |json|
<ide> user = user.downcase if user == "Homebrew" # special handling for the Homebrew organization
<del> json["tree"].map{ |hash| hash['path'] }.compact.each do |file|
<del> name = File.basename(file, '.rb')
<del> if file =~ /\.rb$/ and name =~ rx
<add> json["tree"].each do |object|
<add> next unless object["type"] == "blob"
<add>
<add> path = object["path"]
<add> name = File.basename(path, ".rb")
<add>
<add> if path.end_with?(".rb") && rx === name
<ide> results << "#{user}/#{repo}/#{name}"
<ide> end
<ide> end | 1 |
Javascript | Javascript | use session not socket timeout, tests | 46133b5beba2c780fb3b9a9d6be610d09f752182 | <ide><path>lib/internal/http2/core.js
<ide> function emit() {
<ide> // event. If the stream is not new, emit the 'headers' event to pass
<ide> // the block of headers on.
<ide> function onSessionHeaders(id, cat, flags, headers) {
<del> _unrefActive(this);
<ide> const owner = this[kOwner];
<add> _unrefActive(owner);
<ide> debug(`[${sessionName(owner[kType])}] headers were received on ` +
<ide> `stream ${id}: ${cat}`);
<ide> const streams = owner[kState].streams;
<ide> function onSessionStreamClose(id, code) {
<ide> const stream = owner[kState].streams.get(id);
<ide> if (stream === undefined)
<ide> return;
<del> _unrefActive(this);
<add> _unrefActive(owner);
<ide> // Set the rst state for the stream
<ide> abort(stream);
<ide> const state = stream[kState];
<ide> function afterFDClose(err) {
<ide>
<ide> // Called when an error event needs to be triggered
<ide> function onSessionError(error) {
<del> _unrefActive(this);
<del> process.nextTick(() => this[kOwner].emit('error', error));
<add> const owner = this[kOwner];
<add> _unrefActive(owner);
<add> process.nextTick(() => owner.emit('error', error));
<ide> }
<ide>
<ide> // Receives a chunk of data for a given stream and forwards it on
<ide> // to the Http2Stream Duplex for processing.
<ide> function onSessionRead(nread, buf, handle) {
<del> const streams = this[kOwner][kState].streams;
<add> const owner = this[kOwner];
<add> const streams = owner[kState].streams;
<ide> const id = handle.id;
<ide> const stream = streams.get(id);
<ide> // It should not be possible for the stream to not exist at this point.
<ide> function onSessionRead(nread, buf, handle) {
<ide> 'Internal HTTP/2 Failure. Stream does not exist. Please ' +
<ide> 'report this as a bug in Node.js');
<ide> const state = stream[kState];
<del> _unrefActive(this); // Reset the session timeout timer
<add> _unrefActive(owner); // Reset the session timeout timer
<ide> _unrefActive(stream); // Reset the stream timeout timer
<ide>
<ide> if (nread >= 0 && !stream.destroyed) {
<ide> function onSessionRead(nread, buf, handle) {
<ide> function onSettings(ack) {
<ide> const owner = this[kOwner];
<ide> debug(`[${sessionName(owner[kType])}] new settings received`);
<del> _unrefActive(this);
<add> _unrefActive(owner);
<ide> let event = 'remoteSettings';
<ide> if (ack) {
<ide> if (owner[kState].pendingAck > 0)
<ide> function onPriority(id, parent, weight, exclusive) {
<ide> debug(`[${sessionName(owner[kType])}] priority advisement for stream ` +
<ide> `${id}: \n parent: ${parent},\n weight: ${weight},\n` +
<ide> ` exclusive: ${exclusive}`);
<del> _unrefActive(this);
<add> _unrefActive(owner);
<ide> const streams = owner[kState].streams;
<ide> const stream = streams.get(id);
<ide> const emitter = stream === undefined ? owner : stream;
<ide> function onFrameError(id, type, code) {
<ide> const owner = this[kOwner];
<ide> debug(`[${sessionName(owner[kType])}] error sending frame type ` +
<ide> `${type} on stream ${id}, code: ${code}`);
<del> _unrefActive(this);
<add> _unrefActive(owner);
<ide> const streams = owner[kState].streams;
<ide> const stream = streams.get(id);
<ide> const emitter = stream !== undefined ? stream : owner;
<ide> class Http2Session extends EventEmitter {
<ide> state.destroying = true;
<ide>
<ide> // Unenroll the timer
<del> this.setTimeout(0);
<add> this.setTimeout(0, sessionOnTimeout);
<ide>
<ide> // Shut down any still open streams
<ide> const streams = state.streams;
<ide> function socketDestroy(error) {
<ide> const type = this[kSession][kType];
<ide> debug(`[${sessionName(type)}] socket destroy called`);
<ide> delete this[kServer];
<del> this.setTimeout(0);
<ide> // destroy the session first so that it will stop trying to
<ide> // send data while we close the socket.
<ide> this[kSession].destroy();
<ide> function socketOnError(error) {
<ide> this.destroy(error);
<ide> }
<ide>
<del>// When the socket times out on the server, attempt a graceful shutdown
<del>// of the session.
<del>function socketOnTimeout() {
<del> debug('socket timeout');
<del> process.nextTick(() => {
<del> const server = this[kServer];
<del> const session = this[kSession];
<del> // If server or session are undefined, or session.destroyed is true
<del> // then we're already in the process of shutting down, do nothing.
<del> if (server === undefined || session === undefined)
<del> return;
<del> const state = session[kState];
<del> if (state.destroyed || state.destroying)
<del> return;
<del> if (!server.emit('timeout', session, this)) {
<del> session.shutdown(
<del> {
<del> graceful: true,
<del> errorCode: NGHTTP2_NO_ERROR
<del> },
<del> this.destroy.bind(this));
<del> }
<del> });
<del>}
<del>
<ide> // Handles the on('stream') event for a session and forwards
<ide> // it on to the server object.
<ide> function sessionOnStream(stream, headers, flags, rawHeaders) {
<ide> function sessionOnSocketError(error, socket) {
<ide> this[kServer].emit('socketError', error, socket, this);
<ide> }
<ide>
<add>// When the session times out on the server, attempt a graceful shutdown
<add>function sessionOnTimeout() {
<add> debug('session timeout');
<add> process.nextTick(() => {
<add> // if destroyed or destryoing, do nothing
<add> if (this[kState].destroyed || this[kState].destroying)
<add> return;
<add> const server = this[kServer];
<add> const socket = this[kSocket];
<add> // If server or socket are undefined, then we're already in the process of
<add> // shutting down, do nothing.
<add> if (server === undefined || socket === undefined)
<add> return;
<add> if (!server.emit('timeout', this)) {
<add> this.shutdown(
<add> {
<add> graceful: true,
<add> errorCode: NGHTTP2_NO_ERROR
<add> },
<add> socket.destroy.bind(socket));
<add> }
<add> });
<add>}
<add>
<ide> function connectionListener(socket) {
<ide> debug('[server] received a connection');
<ide> const options = this[kOptions] || {};
<ide>
<del> if (this.timeout) {
<del> socket.setTimeout(this.timeout);
<del> socket.on('timeout', socketOnTimeout);
<del> }
<del>
<ide> if (socket.alpnProtocol === false || socket.alpnProtocol === 'http/1.1') {
<ide> if (options.allowHTTP1 === true) {
<ide> // Fallback to HTTP/1.1
<ide> function connectionListener(socket) {
<ide> session.on('priority', sessionOnPriority);
<ide> session.on('socketError', sessionOnSocketError);
<ide>
<add> if (this.timeout) {
<add> session.setTimeout(this.timeout);
<add> session.on('timeout', sessionOnTimeout);
<add> }
<add>
<ide> socket[kServer] = this;
<ide>
<ide> process.nextTick(emit.bind(this, 'session', session));
<ide><path>test/parallel/test-http2-session-timeout.js
<add>// Flags: --expose-http2
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>const h2 = require('http2');
<add>
<add>const serverTimeout = common.platformTimeout(200);
<add>const callTimeout = common.platformTimeout(10);
<add>
<add>const server = h2.createServer();
<add>server.timeout = serverTimeout;
<add>
<add>server.on('request', (req, res) => res.end());
<add>server.on('timeout', common.mustNotCall());
<add>
<add>server.listen(0, common.mustCall(() => {
<add> const port = server.address().port;
<add>
<add> const url = `http://localhost:${port}`;
<add> const client = h2.connect(url);
<add> makeReq(40);
<add>
<add> function makeReq(attempts) {
<add> const request = client.request({
<add> ':path': '/foobar',
<add> ':method': 'GET',
<add> ':scheme': 'http',
<add> ':authority': `localhost:${port}`,
<add> });
<add> request.end();
<add>
<add> if (attempts) {
<add> setTimeout(() => makeReq(attempts - 1), callTimeout);
<add> } else {
<add> server.close();
<add> client.destroy();
<add> }
<add> }
<add>})); | 2 |
Text | Text | fix typo in config value [ci skip] | 767427719ef9e8f0d375dbdcb88ad6c7abbda9e6 | <ide><path>actionview/CHANGELOG.md
<ide> be true. Default value is `true`. For example in `application.rb`:
<ide>
<ide> # in order to turn off missing key wrapping
<del> config.action_view.debug_missing_tranlation = false
<add> config.action_view.debug_missing_translation = false
<ide>
<ide> *Sameer Rahmani*
<ide> | 1 |
PHP | PHP | use php 5.4 closures $this where safe to | a1c5dd80aa6a13e0f8cf1f0e0e1700ff65c11f2c | <ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php
<ide> protected function compileBasicHaving($having)
<ide> */
<ide> protected function compileOrders(Builder $query, $orders)
<ide> {
<del> $me = $this;
<del>
<del> return 'order by '.implode(', ', array_map(function($order) use ($me)
<add> return 'order by '.implode(', ', array_map(function($order)
<ide> {
<ide> if (isset($order['sql'])) return $order['sql'];
<ide>
<del> return $me->wrap($order['column']).' '.$order['direction'];
<add> return $this->wrap($order['column']).' '.$order['direction'];
<ide> }
<ide> , $orders));
<ide> }
<ide><path>src/Illuminate/Events/Dispatcher.php
<ide> public function hasListeners($eventName)
<ide> */
<ide> public function queue($event, $payload = array())
<ide> {
<del> $me = $this;
<del>
<del> $this->listen($event.'_queue', function() use ($me, $event, $payload)
<add> $this->listen($event.'_queue', function() use ($event, $payload)
<ide> {
<del> $me->fire($event, $payload);
<add> $this->fire($event, $payload);
<ide> });
<ide> }
<ide>
<ide><path>src/Illuminate/Foundation/MigrationPublisher.php
<ide> public function publish($source, $destination)
<ide> */
<ide> protected function getFreshMigrations($source, $destination)
<ide> {
<del> $me = $this;
<del>
<del> return array_filter($this->getPackageMigrations($source), function($file) use ($me, $destination)
<add> return array_filter($this->getPackageMigrations($source), function($file) use ($destination)
<ide> {
<del> return ! $me->migrationExists($file, $destination);
<add> return ! $this->migrationExists($file, $destination);
<ide> });
<ide> }
<ide>
<ide> protected function getNewMigrationName($file, $add)
<ide> return Carbon::now()->addSeconds($add)->format('Y_m_d_His').substr(basename($file), 17);
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add>}
<ide><path>src/Illuminate/Remote/Connection.php
<ide> protected function getCallback($callback)
<ide> {
<ide> if ( ! is_null($callback)) return $callback;
<ide>
<del> $me = $this;
<del>
<del> return function($line) use ($me) { $me->display($line); };
<add> return function($line) { $this->display($line); };
<ide> }
<ide>
<ide> /**
<ide> public function setOutput(OutputInterface $output)
<ide> $this->output = $output;
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add>}
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function getResourceUri($resource)
<ide> */
<ide> protected function getNestedResourceUri(array $segments)
<ide> {
<del> $me = $this;
<del>
<ide> // We will spin through the segments and create a place-holder for each of the
<ide> // resource segments, as well as the resource itself. Then we should get an
<ide> // entire string for the resource URI that contains all nested resources.
<del> return implode('/', array_map(function($s) use ($me)
<add> return implode('/', array_map(function($s)
<ide> {
<del> return $s.'/{'.$me->getResourceWildcard($s).'}';
<add> return $s.'/{'.$this->getResourceWildcard($s).'}';
<ide>
<ide> }, $segments));
<ide> }
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php
<ide> protected function compileEchos($value)
<ide> */
<ide> protected function compileRegularEchos($value)
<ide> {
<del> $me = $this;
<del>
<ide> $pattern = sprintf('/(@)?%s\s*(.+?)\s*%s/s', $this->contentTags[0], $this->contentTags[1]);
<ide>
<del> $callback = function($matches) use ($me)
<add> $callback = function($matches)
<ide> {
<del> return $matches[1] ? substr($matches[0], 1) : '<?php echo '.$me->compileEchoDefaults($matches[2]).'; ?>';
<add> return $matches[1] ? substr($matches[0], 1) : '<?php echo '.$this->compileEchoDefaults($matches[2]).'; ?>';
<ide> };
<ide>
<ide> return preg_replace_callback($pattern, $callback, $value);
<ide> protected function compileRegularEchos($value)
<ide> */
<ide> protected function compileEscapedEchos($value)
<ide> {
<del> $me = $this;
<del>
<ide> $pattern = sprintf('/%s\s*(.+?)\s*%s/s', $this->escapedTags[0], $this->escapedTags[1]);
<ide>
<del> $callback = function($matches) use ($me)
<add> $callback = function($matches)
<ide> {
<del> return '<?php echo e('.$me->compileEchoDefaults($matches[1]).'); ?>';
<add> return '<?php echo e('.$this->compileEchoDefaults($matches[1]).'); ?>';
<ide> };
<ide>
<ide> return preg_replace_callback($pattern, $callback, $value); | 6 |
Javascript | Javascript | remove confusing warning from scrollresponder | 5f77f15bac82c7a13605fdbd1ee7e2823c1821bf | <ide><path>Libraries/Components/ScrollResponder.js
<ide> var ScrollResponderMixin = {
<ide> * a touch has already started.
<ide> */
<ide> scrollResponderHandleResponderReject: function() {
<del> warning(false, "ScrollView doesn't take rejection well - scrolls anyway");
<ide> },
<ide>
<ide> /** | 1 |
Python | Python | prevent clickable bad links on disabled pagination | 57388ef6579b91f7b38fe279da12f8a170590321 | <ide><path>airflow/www/utils.py
<ide> def generate_pages(current_page, num_of_pages, search=None, status=None, window=
<ide> output = [Markup('<ul class="pagination" style="margin-top:0;">')]
<ide>
<ide> is_disabled = 'disabled' if current_page <= 0 else ''
<add>
<add> first_node_link = void_link if is_disabled else f'?{get_params(page=0, search=search, status=status)}'
<ide> output.append(
<ide> first_node.format(
<del> href_link=f"?{get_params(page=0, search=search, status=status)}", # noqa
<add> href_link=first_node_link,
<ide> disabled=is_disabled,
<ide> )
<ide> )
<ide> def is_current(current, page): # noqa
<ide> )
<ide>
<ide> output.append(next_node.format(href_link=page_link, disabled=is_disabled)) # noqa
<add>
<add> last_node_link = (
<add> void_link if is_disabled else f'?{get_params(page=last_page, search=search, status=status)}'
<add> )
<ide> output.append(
<ide> last_node.format(
<del> href_link=f"?{get_params(page=last_page, search=search, status=status)}", # noqa
<add> href_link=last_node_link,
<ide> disabled=is_disabled,
<ide> )
<ide> ) | 1 |
Python | Python | add correct signature to all operators and sensors | cdec3012542b45d23a05f62d69110944ba542e2a | <ide><path>airflow/operators/email.py
<ide> class EmailOperator(BaseOperator):
<ide> ui_color = '#e6faf9'
<ide>
<ide> @apply_defaults
<del> def __init__(
<del> self,
<add> def __init__( # pylint: disable=invalid-name
<add> self, *,
<ide> to: Union[List[str], str],
<ide> subject: str,
<ide> html_content: str,
<ide><path>airflow/operators/sql.py
<ide> class SQLValueCheckOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> sql: str,
<ide> pass_value: Any,
<ide> tolerance: Any = None,
<ide> class SQLIntervalCheckOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> table: str,
<ide> metrics_thresholds: Dict[str, int],
<ide> date_filter_column: Optional[str] = "ds",
<ide> class SQLThresholdCheckOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> sql: str,
<ide> min_threshold: Any,
<ide> max_threshold: Any,
<ide> class BranchSQLOperator(BaseOperator, SkipMixin):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> sql: str,
<ide> follow_task_ids_if_true: List[str],
<ide> follow_task_ids_if_false: List[str],
<ide><path>airflow/providers/celery/sensors/celery_queue.py
<ide> class CeleryQueueSensor(BaseSensorOperator):
<ide> """
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> celery_queue: str,
<ide> target_task_id: Optional[str] = None,
<ide> **kwargs) -> None:
<ide><path>airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py
<ide> class KubernetesPodOperator(BaseOperator): # pylint: disable=too-many-instance-
<ide>
<ide> @apply_defaults
<ide> def __init__(self, # pylint: disable=too-many-arguments,too-many-locals
<add> *,
<ide> namespace: Optional[str] = None,
<ide> image: Optional[str] = None,
<ide> name: Optional[str] = None,
<ide><path>airflow/providers/cncf/kubernetes/operators/spark_kubernetes.py
<ide> class SparkKubernetesOperator(BaseOperator):
<ide> ui_color = '#f4a460'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> application_file: str,
<ide> namespace: Optional[str] = None,
<ide> kubernetes_conn_id: str = 'kubernetes_default',
<ide><path>airflow/providers/cncf/kubernetes/sensors/spark_kubernetes.py
<ide> class SparkKubernetesSensor(BaseSensorOperator):
<ide> SUCCESS_STATES = ('COMPLETED',)
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> application_name: str,
<ide> namespace: Optional[str] = None,
<ide> kubernetes_conn_id: str = 'kubernetes_default',
<ide><path>airflow/providers/databricks/operators/databricks.py
<ide> class DatabricksSubmitRunOperator(BaseOperator):
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> json=None,
<ide> spark_jar_task=None,
<ide> notebook_task=None,
<ide> class DatabricksRunNowOperator(BaseOperator):
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> job_id=None,
<ide> json=None,
<ide> notebook_params=None,
<ide><path>airflow/providers/datadog/sensors/datadog.py
<ide> class DatadogSensor(BaseSensorOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> datadog_conn_id: str = 'datadog_default',
<ide> from_seconds_ago: int = 3600,
<ide> up_to_seconds_from_now: int = 0,
<ide><path>airflow/providers/dingding/operators/dingding.py
<ide> class DingdingOperator(BaseOperator):
<ide> ui_color = '#4ea4d4' # Dingding icon color
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> dingding_conn_id='dingding_default',
<ide> message_type='text',
<ide> message=None,
<ide><path>airflow/providers/discord/operators/discord_webhook.py
<ide> class DiscordWebhookOperator(SimpleHttpOperator):
<ide> template_fields = ['username', 'message']
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> http_conn_id: Optional[str] = None,
<ide> webhook_endpoint: Optional[str] = None,
<ide> message: str = "",
<ide><path>airflow/providers/docker/operators/docker.py
<ide> class DockerOperator(BaseOperator):
<ide> # pylint: disable=too-many-arguments,too-many-locals
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> image: str,
<ide> api_version: Optional[str] = None,
<ide> command: Optional[Union[str, List[str]]] = None,
<ide><path>airflow/providers/docker/operators/docker_swarm.py
<ide> class DockerSwarmOperator(DockerOperator):
<ide> @apply_defaults
<ide> def __init__(
<ide> self,
<add> *,
<ide> image: str,
<ide> enable_logging: bool = True,
<del> *args,
<ide> **kwargs) -> None:
<del> super().__init__(image=image, *args, **kwargs) # type: ignore
<add> super().__init__(image=image, **kwargs)
<ide>
<ide> self.enable_logging = enable_logging
<ide> self.service = None
<ide><path>airflow/providers/exasol/operators/exasol.py
<ide> class ExasolOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> sql: str,
<ide> exasol_conn_id: str = 'exasol_default',
<ide> autocommit: bool = False,
<ide><path>airflow/providers/ftp/sensors/ftp.py
<ide> class FTPSensor(BaseSensorOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> path: str,
<ide> ftp_conn_id: str = 'ftp_default',
<ide> fail_on_transient_errors: bool = True,
<ide><path>airflow/providers/google/ads/transfers/ads_to_gcs.py
<ide> class GoogleAdsToGcsOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> client_ids: List[str],
<ide> query: str,
<ide> attributes: List[str],
<ide><path>airflow/providers/google/cloud/sensors/bigquery.py
<ide> class BigQueryTableExistenceSensor(BaseSensorOperator):
<ide> ui_color = '#f0eee4'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> project_id: str,
<ide> dataset_id: str,
<ide> table_id: str,
<ide><path>airflow/providers/google/cloud/sensors/bigquery_dts.py
<ide> class BigQueryDataTransferServiceTransferRunSensor(BaseSensorOperator):
<ide> @apply_defaults
<ide> def __init__(
<ide> self,
<add> *,
<ide> run_id: str,
<ide> transfer_config_id: str,
<ide> expected_statuses: Union[Set[str], str] = 'SUCCEEDED',
<ide><path>airflow/providers/google/cloud/sensors/bigtable.py
<ide> class BigtableTableReplicationCompletedSensor(BaseSensorOperator, BigtableValida
<ide> @apply_defaults
<ide> def __init__(
<ide> self,
<add> *,
<ide> instance_id: str,
<ide> table_id: str,
<ide> project_id: Optional[str] = None,
<ide><path>airflow/providers/google/cloud/sensors/cloud_storage_transfer_service.py
<ide> class CloudDataTransferServiceJobStatusSensor(BaseSensorOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> job_name: str,
<ide> expected_statuses: Union[Set[str], str],
<ide> project_id: Optional[str] = None,
<ide><path>airflow/providers/google/cloud/sensors/gcs.py
<ide> class GCSObjectExistenceSensor(BaseSensorOperator):
<ide> ui_color = '#f0eee4'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> bucket: str,
<ide> object: str, # pylint: disable=redefined-builtin
<ide> google_cloud_conn_id: str = 'google_cloud_default',
<ide><path>airflow/providers/google/cloud/sensors/pubsub.py
<ide> class PubSubPullSensor(BaseSensorOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> project_id: str,
<ide> subscription: str,
<ide> max_messages: int = 5,
<ide><path>airflow/providers/google/cloud/transfers/adls_to_gcs.py
<ide> class ADLSToGCSOperator(AzureDataLakeStorageListOperator):
<ide> ui_color = '#f0eee4'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> src_adls: str,
<ide> dest_gcs: str,
<ide> azure_data_lake_conn_id: str,
<ide><path>airflow/providers/google/cloud/transfers/bigquery_to_bigquery.py
<ide> class BigQueryToBigQueryOperator(BaseOperator):
<ide> ui_color = '#e6f0e4'
<ide>
<ide> @apply_defaults
<del> def __init__(self, # pylint: disable=too-many-arguments
<add> def __init__(self, *, # pylint: disable=too-many-arguments
<ide> source_project_dataset_tables: Union[List[str], str],
<ide> destination_project_dataset_table: str,
<ide> write_disposition: str = 'WRITE_EMPTY',
<ide><path>airflow/providers/google/cloud/transfers/bigquery_to_gcs.py
<ide> class BigQueryToGCSOperator(BaseOperator):
<ide> ui_color = '#e4e6f0'
<ide>
<ide> @apply_defaults
<del> def __init__(self, # pylint: disable=too-many-arguments
<add> def __init__(self, *, # pylint: disable=too-many-arguments
<ide> source_project_dataset_table: str,
<ide> destination_cloud_storage_uris: List[str],
<ide> compression: str = 'NONE',
<ide><path>airflow/providers/google/cloud/transfers/bigquery_to_mysql.py
<ide> class BigQueryToMySqlOperator(BaseOperator):
<ide> template_fields = ('dataset_id', 'table_id', 'mysql_table')
<ide>
<ide> @apply_defaults
<del> def __init__(self, # pylint: disable=too-many-arguments
<add> def __init__(self, *, # pylint: disable=too-many-arguments
<ide> dataset_table: str,
<ide> mysql_table: str,
<ide> selected_fields: Optional[str] = None,
<ide><path>airflow/providers/google/cloud/transfers/cassandra_to_gcs.py
<ide> class CassandraToGCSOperator(BaseOperator):
<ide> ui_color = '#a0e08c'
<ide>
<ide> @apply_defaults
<del> def __init__(self, # pylint: disable=too-many-arguments
<add> def __init__(self, *, # pylint: disable=too-many-arguments
<ide> cql: str,
<ide> bucket: str,
<ide> filename: str,
<ide><path>airflow/providers/google/cloud/transfers/facebook_ads_to_gcs.py
<ide> class FacebookAdsReportToGcsOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> bucket_name: str,
<ide> object_name: str,
<ide> fields: List[str],
<ide><path>airflow/providers/google/cloud/transfers/gcs_to_bigquery.py
<ide> class GCSToBigQueryOperator(BaseOperator):
<ide>
<ide> # pylint: disable=too-many-locals,too-many-arguments
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> bucket,
<ide> source_objects,
<ide> destination_project_dataset_table,
<ide><path>airflow/providers/google/cloud/transfers/gcs_to_gcs.py
<ide> class GCSToGCSOperator(BaseOperator):
<ide> ui_color = '#f0eee4'
<ide>
<ide> @apply_defaults
<del> def __init__(self, # pylint: disable=too-many-arguments
<add> def __init__(self, *, # pylint: disable=too-many-arguments
<ide> source_bucket,
<ide> source_object=None,
<ide> source_objects=None,
<ide><path>airflow/providers/google/cloud/transfers/gcs_to_local.py
<ide> class GCSToLocalFilesystemOperator(BaseOperator):
<ide> ui_color = '#f0eee4'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> bucket: str,
<ide> object_name: Optional[str] = None,
<ide> filename: Optional[str] = None,
<ide><path>airflow/providers/google/cloud/transfers/gcs_to_sftp.py
<ide> class GCSToSFTPOperator(BaseOperator):
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> source_bucket: str,
<ide> source_object: str,
<ide> destination_path: str,
<ide><path>airflow/providers/google/cloud/transfers/local_to_gcs.py
<ide> class LocalFilesystemToGCSOperator(BaseOperator):
<ide> template_fields = ('src', 'dst', 'bucket')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> src,
<ide> dst,
<ide> bucket,
<ide><path>airflow/providers/google/cloud/transfers/mssql_to_gcs.py
<ide> class MSSQLToGCSOperator(BaseSQLToGCSOperator):
<ide> }
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> mssql_conn_id='mssql_default',
<ide> **kwargs):
<ide> super().__init__(**kwargs)
<ide><path>airflow/providers/google/cloud/transfers/mysql_to_gcs.py
<ide> class MySQLToGCSOperator(BaseSQLToGCSOperator):
<ide> }
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> mysql_conn_id='mysql_default',
<ide> ensure_utc=False,
<ide> **kwargs):
<ide><path>airflow/providers/google/cloud/transfers/postgres_to_gcs.py
<ide> class PostgresToGCSOperator(BaseSQLToGCSOperator):
<ide> }
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> postgres_conn_id='postgres_default',
<ide> **kwargs):
<ide> super().__init__(**kwargs)
<ide><path>airflow/providers/google/cloud/transfers/presto_to_gcs.py
<ide> class PrestoToGCSOperator(BaseSQLToGCSOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> presto_conn_id: str = "presto_default",
<ide> **kwargs
<ide> ):
<ide><path>airflow/providers/google/cloud/transfers/s3_to_gcs.py
<ide> class S3ToGCSOperator(S3ListOperator):
<ide>
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> bucket,
<ide> prefix='',
<ide> delimiter='',
<ide><path>airflow/providers/google/cloud/transfers/sftp_to_gcs.py
<ide> class SFTPToGCSOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> source_path: str,
<ide> destination_bucket: str,
<ide> destination_path: Optional[str] = None,
<ide><path>airflow/providers/google/cloud/transfers/sheets_to_gcs.py
<ide> from airflow.models import BaseOperator
<ide> from airflow.providers.google.cloud.hooks.gcs import GCSHook
<ide> from airflow.providers.google.suite.hooks.sheets import GSheetsHook
<add>from airflow.utils.decorators import apply_defaults
<ide>
<ide>
<ide> class GoogleSheetsToGCSOperator(BaseOperator):
<ide> class GoogleSheetsToGCSOperator(BaseOperator):
<ide>
<ide> template_fields = ["spreadsheet_id", "destination_bucket", "destination_path", "sheet_filter"]
<ide>
<add> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> spreadsheet_id: str,
<ide> destination_bucket: str,
<ide> sheet_filter: Optional[List[str]] = None,
<ide> destination_path: Optional[str] = None,
<ide> gcp_conn_id: str = "google_cloud_default",
<ide> delegate_to: Optional[str] = None,
<del> *args,
<ide> **kwargs,
<ide> ) -> None:
<del> super().__init__(*args, **kwargs)
<add> super().__init__(**kwargs)
<ide> self.gcp_conn_id = gcp_conn_id
<ide> self.spreadsheet_id = spreadsheet_id
<ide> self.sheet_filter = sheet_filter
<ide><path>airflow/providers/google/cloud/transfers/sql_to_gcs.py
<ide> class BaseSQLToGCSOperator(BaseOperator):
<ide> ui_color = '#a0e08c'
<ide>
<ide> @apply_defaults
<del> def __init__(self, # pylint: disable=too-many-arguments
<add> def __init__(self, *, # pylint: disable=too-many-arguments
<ide> sql,
<ide> bucket,
<ide> filename,
<ide><path>airflow/providers/google/marketing_platform/sensors/campaign_manager.py
<ide> def poke(self, context: Dict) -> bool:
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> profile_id: str,
<ide> report_id: str,
<ide> file_id: str,
<ide><path>airflow/providers/google/marketing_platform/sensors/display_video.py
<ide> class GoogleDisplayVideo360ReportSensor(BaseSensorOperator):
<ide> template_fields = ("report_id",)
<ide>
<ide> def __init__(
<del> self,
<add> self, *,
<ide> report_id: str,
<ide> api_version: str = "v1",
<ide> gcp_conn_id: str = "google_cloud_default",
<ide> delegate_to: Optional[str] = None,
<del> *args,
<ide> **kwargs
<ide> ):
<del> super().__init__(*args, **kwargs)
<add> super().__init__(**kwargs)
<ide>
<ide> self.report_id = report_id
<ide> self.api_version = api_version
<ide><path>airflow/providers/google/marketing_platform/sensors/search_ads.py
<ide> class GoogleSearchAdsReportSensor(BaseSensorOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> report_id: str,
<ide> api_version: str = "v2",
<ide> gcp_conn_id: str = "google_cloud_default",
<ide><path>airflow/providers/grpc/operators/grpc.py
<ide> class GrpcOperator(BaseOperator):
<ide> template_fields = ('stub_class', 'call_func', 'data')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> stub_class: Callable,
<ide> call_func: str,
<ide> grpc_conn_id: str = "grpc_default",
<ide><path>airflow/providers/http/operators/http.py
<ide> class SimpleHttpOperator(BaseOperator):
<ide> ui_color = '#f4a460'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> endpoint: Optional[str] = None,
<ide> method: str = 'POST',
<ide> data: Any = None,
<ide><path>airflow/providers/http/sensors/http.py
<ide> def response_check(response, task_instance):
<ide> template_fields = ('endpoint', 'request_params')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> endpoint: str,
<ide> http_conn_id: str = 'http_default',
<ide> method: str = 'GET',
<ide><path>airflow/providers/imap/sensors/imap_attachment.py
<ide> class ImapAttachmentSensor(BaseSensorOperator):
<ide> template_fields = ('attachment_name', 'mail_filter')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> attachment_name,
<ide> check_regex=False,
<ide> mail_folder='INBOX',
<ide><path>airflow/providers/jdbc/operators/jdbc.py
<ide> class JdbcOperator(BaseOperator):
<ide> ui_color = '#ededed'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> sql: str,
<ide> jdbc_conn_id: str = 'jdbc_default',
<ide> autocommit: bool = False,
<ide><path>airflow/providers/jenkins/operators/jenkins_job_trigger.py
<ide> class JenkinsJobTriggerOperator(BaseOperator):
<ide> ui_color = '#f9ec86'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> jenkins_connection_id: str,
<ide> job_name: str,
<ide> parameters: ParamType = "",
<ide> sleep_time: int = 10,
<ide> max_try_before_job_appears: int = 10,
<del> *args,
<ide> **kwargs):
<ide> super().__init__(**kwargs)
<ide> self.job_name = job_name
<ide><path>airflow/providers/jira/operators/jira.py
<ide> class JiraOperator(BaseOperator):
<ide> template_fields = ("jira_method_args",)
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> jira_method: str,
<ide> jira_conn_id: str = 'jira_default',
<ide> jira_method_args: Optional[dict] = None,
<ide><path>airflow/providers/jira/sensors/jira.py
<ide> class JiraSensor(BaseSensorOperator):
<ide> """
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> method_name: str,
<ide> jira_conn_id: str = 'jira_default',
<ide> method_params: Optional[dict] = None,
<ide> class JiraTicketSensor(JiraSensor):
<ide> template_fields = ("ticket_id",)
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> jira_conn_id: str = 'jira_default',
<ide> ticket_id: Optional[str] = None,
<ide> field: Optional[str] = None,
<ide><path>airflow/providers/microsoft/azure/operators/adls_list.py
<ide> class AzureDataLakeStorageListOperator(BaseOperator):
<ide> ui_color = '#901dd2'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> path: str,
<ide> azure_data_lake_conn_id: str = 'azure_data_lake_default',
<ide> **kwargs) -> None:
<ide><path>airflow/providers/microsoft/azure/operators/adx.py
<ide> class AzureDataExplorerQueryOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> query: str,
<ide> database: str,
<ide> options: Optional[Dict] = None,
<ide><path>airflow/providers/microsoft/azure/operators/azure_batch.py
<ide> class AzureBatchOperator(BaseOperator):
<ide> ui_color = '#f0f0e4'
<ide>
<ide> @apply_defaults
<del> def __init__(self, # pylint: disable=too-many-arguments,too-many-locals
<add> def __init__(self, *, # pylint: disable=too-many-arguments,too-many-locals
<ide> batch_pool_id: str,
<ide> batch_pool_vm_size: str,
<ide> batch_job_id: str,
<ide><path>airflow/providers/microsoft/azure/operators/azure_container_instances.py
<ide> class AzureContainerInstancesOperator(BaseOperator):
<ide>
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> ci_conn_id: str,
<ide> registry_conn_id: Optional[str],
<ide> resource_group: str,
<ide><path>airflow/providers/microsoft/azure/operators/azure_cosmos.py
<ide> class AzureCosmosInsertDocumentOperator(BaseOperator):
<ide> ui_color = '#e4f0e8'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> database_name: str,
<ide> collection_name: str,
<ide> document: dict,
<ide><path>airflow/providers/microsoft/azure/operators/wasb_delete_blob.py
<ide> class WasbDeleteBlobOperator(BaseOperator):
<ide> template_fields = ('container_name', 'blob_name')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> container_name: str,
<ide> blob_name: str,
<ide> wasb_conn_id: str = 'wasb_default',
<ide><path>airflow/providers/microsoft/azure/sensors/azure_cosmos.py
<ide> class AzureCosmosDocumentSensor(BaseSensorOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> database_name: str,
<ide> collection_name: str,
<ide> document_id: str,
<ide><path>airflow/providers/microsoft/azure/sensors/wasb.py
<ide> class WasbBlobSensor(BaseSensorOperator):
<ide> template_fields = ('container_name', 'blob_name')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> container_name: str,
<ide> blob_name: str,
<ide> wasb_conn_id: str = 'wasb_default',
<ide> class WasbPrefixSensor(BaseSensorOperator):
<ide> template_fields = ('container_name', 'prefix')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> container_name: str,
<ide> prefix: str,
<ide> wasb_conn_id: str = 'wasb_default',
<ide><path>airflow/providers/microsoft/azure/transfers/file_to_wasb.py
<ide> class FileToWasbOperator(BaseOperator):
<ide> template_fields = ('file_path', 'container_name', 'blob_name')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> file_path: str,
<ide> container_name: str,
<ide> blob_name: str,
<ide><path>airflow/providers/microsoft/azure/transfers/oracle_to_azure_data_lake.py
<ide> class OracleToAzureDataLakeOperator(BaseOperator):
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> filename: str,
<ide> azure_data_lake_conn_id: str,
<ide> azure_data_lake_path: str,
<ide><path>airflow/providers/microsoft/mssql/operators/mssql.py
<ide> class MsSqlOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> sql: str,
<ide> mssql_conn_id: str = 'mssql_default',
<ide> parameters: Optional[Union[Mapping, Iterable]] = None,
<ide><path>airflow/providers/microsoft/winrm/operators/winrm.py
<ide> class WinRMOperator(BaseOperator):
<ide> template_fields = ('command',)
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> winrm_hook=None,
<ide> ssh_conn_id=None,
<ide> remote_host=None,
<ide><path>airflow/providers/mongo/sensors/mongo.py
<ide> class MongoSensor(BaseSensorOperator):
<ide> template_fields = ('collection', 'query')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> collection: str,
<ide> query: dict,
<ide> mongo_conn_id: str = "mongo_default",
<ide><path>airflow/providers/mysql/operators/mysql.py
<ide> class MySqlOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> sql: str,
<ide> mysql_conn_id: str = 'mysql_default',
<ide> parameters: Optional[Union[Mapping, Iterable]] = None,
<ide><path>airflow/providers/mysql/transfers/presto_to_mysql.py
<ide> class PrestoToMySqlOperator(BaseOperator):
<ide> ui_color = '#a0e08c'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> sql: str,
<ide> mysql_table: str,
<ide> presto_conn_id: str = 'presto_default',
<ide><path>airflow/providers/mysql/transfers/s3_to_mysql.py
<ide> class S3ToMySqlOperator(BaseOperator):
<ide> ui_color = '#f4a460'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> s3_source_key: str,
<ide> mysql_table: str,
<ide> mysql_duplicate_key_handling: str = 'IGNORE',
<ide><path>airflow/providers/mysql/transfers/vertica_to_mysql.py
<ide> class VerticaToMySqlOperator(BaseOperator):
<ide> @apply_defaults
<ide> def __init__(
<ide> self,
<add> *,
<ide> sql,
<ide> mysql_table,
<ide> vertica_conn_id='vertica_default',
<ide><path>airflow/providers/opsgenie/operators/opsgenie_alert.py
<ide> class OpsgenieAlertOperator(BaseOperator):
<ide>
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> message,
<ide> opsgenie_conn_id='opsgenie_default',
<ide> alias=None,
<ide><path>airflow/providers/oracle/operators/oracle.py
<ide> class OracleOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> sql: str,
<ide> oracle_conn_id: str = 'oracle_default',
<ide> parameters: Optional[Union[Mapping, Iterable]] = None,
<ide><path>airflow/providers/oracle/transfers/oracle_to_oracle.py
<ide> class OracleToOracleOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> oracle_destination_conn_id,
<ide> destination_table,
<ide> oracle_source_conn_id,
<ide><path>airflow/providers/papermill/operators/papermill.py
<ide> class PapermillOperator(BaseOperator):
<ide> supports_lineage = True
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> input_nb: Optional[str] = None,
<ide> output_nb: Optional[str] = None,
<ide> parameters: Optional[Dict] = None,
<ide><path>airflow/providers/postgres/operators/postgres.py
<ide> class PostgresOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> sql: str,
<ide> postgres_conn_id: str = 'postgres_default',
<ide> autocommit: bool = False,
<ide><path>airflow/providers/qubole/operators/qubole.py
<ide> class QuboleOperator(BaseOperator):
<ide> )
<ide>
<ide> @apply_defaults
<del> def __init__(self, qubole_conn_id="qubole_default", **kwargs):
<add> def __init__(self, *, qubole_conn_id="qubole_default", **kwargs):
<ide> self.kwargs = kwargs
<ide> self.kwargs['qubole_conn_id'] = qubole_conn_id
<ide> self.hook = None
<ide><path>airflow/providers/qubole/operators/qubole_check.py
<ide> class QuboleCheckOperator(CheckOperator, QuboleOperator):
<ide> ui_fgcolor = '#000'
<ide>
<ide> @apply_defaults
<del> def __init__(self, qubole_conn_id="qubole_default", **kwargs):
<add> def __init__(self, *, qubole_conn_id="qubole_default", **kwargs):
<ide> sql = get_sql_from_qbol_cmd(kwargs)
<ide> super().__init__(qubole_conn_id=qubole_conn_id, sql=sql, **kwargs)
<ide> self.on_failure_callback = QuboleCheckHook.handle_failure_retry
<ide><path>airflow/providers/qubole/sensors/qubole.py
<ide> class QuboleSensor(BaseSensorOperator):
<ide> template_ext = ('.txt',)
<ide>
<ide> @apply_defaults
<del> def __init__(self, data, qubole_conn_id="qubole_default", **kwargs):
<add> def __init__(self, *, data, qubole_conn_id="qubole_default", **kwargs):
<ide> self.data = data
<ide> self.qubole_conn_id = qubole_conn_id
<ide>
<ide><path>airflow/providers/redis/operators/redis_publish.py
<ide> class RedisPublishOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> channel: str,
<ide> message: str,
<ide> redis_conn_id: str = 'redis_default',
<ide><path>airflow/providers/redis/sensors/redis_key.py
<ide> class RedisKeySensor(BaseSensorOperator):
<ide> ui_color = '#f0eee4'
<ide>
<ide> @apply_defaults
<del> def __init__(self, key: str, redis_conn_id: str, **kwargs) -> None:
<add> def __init__(self, *, key: str, redis_conn_id: str, **kwargs) -> None:
<ide> super().__init__(**kwargs)
<ide> self.redis_conn_id = redis_conn_id
<ide> self.key = key
<ide><path>airflow/providers/redis/sensors/redis_pub_sub.py
<ide> class RedisPubSubSensor(BaseSensorOperator):
<ide> ui_color = '#f0eee4'
<ide>
<ide> @apply_defaults
<del> def __init__(self, channels: Union[List[str], str], redis_conn_id: str, **kwargs) -> None:
<add> def __init__(self, *, channels: Union[List[str], str], redis_conn_id: str, **kwargs) -> None:
<ide> super().__init__(**kwargs)
<ide> self.channels = channels
<ide> self.redis_conn_id = redis_conn_id
<ide><path>airflow/providers/salesforce/operators/tableau_refresh_workbook.py
<ide> class TableauRefreshWorkbookOperator(BaseOperator):
<ide> """
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> workbook_name: str,
<ide> site_id: Optional[str] = None,
<ide> blocking: bool = True,
<ide><path>airflow/providers/salesforce/sensors/tableau_job_status.py
<ide> class TableauJobStatusSensor(BaseSensorOperator):
<ide> template_fields = ('job_id',)
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> job_id: str,
<ide> site_id: Optional[str] = None,
<ide> tableau_conn_id: str = 'tableau_default',
<ide><path>airflow/providers/segment/operators/segment_track_event.py
<ide> class SegmentTrackEventOperator(BaseOperator):
<ide> ui_color = '#ffd700'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> user_id: str,
<ide> event: str,
<ide> properties: Optional[dict] = None,
<ide><path>airflow/providers/sftp/operators/sftp.py
<ide> class SFTPOperator(BaseOperator):
<ide> template_fields = ('local_filepath', 'remote_filepath', 'remote_host')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> ssh_hook=None,
<ide> ssh_conn_id=None,
<ide> remote_host=None,
<ide><path>airflow/providers/sftp/sensors/sftp.py
<ide> class SFTPSensor(BaseSensorOperator):
<ide> template_fields = ('path',)
<ide>
<ide> @apply_defaults
<del> def __init__(self, path, sftp_conn_id='sftp_default', **kwargs):
<add> def __init__(self, *, path, sftp_conn_id='sftp_default', **kwargs):
<ide> super().__init__(**kwargs)
<ide> self.path = path
<ide> self.hook = None
<ide><path>airflow/providers/singularity/operators/singularity.py
<ide> class SingularityOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__( # pylint: disable=too-many-arguments
<del> self,
<add> self, *,
<ide> image: str,
<ide> command: Union[str, List[str]],
<ide> start_command: Optional[Union[str, List[str]]] = None,
<ide><path>airflow/providers/slack/operators/slack.py
<ide> class SlackAPIOperator(BaseOperator):
<ide> """
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> slack_conn_id: Optional[str] = None,
<ide> token: Optional[str] = None,
<ide> method: Optional[str] = None,
<ide><path>airflow/providers/slack/operators/slack_webhook.py
<ide> class SlackWebhookOperator(SimpleHttpOperator):
<ide>
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> http_conn_id=None,
<ide> webhook_token=None,
<ide> message="",
<ide><path>airflow/providers/snowflake/operators/snowflake.py
<ide> class SnowflakeOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self, sql, snowflake_conn_id='snowflake_default', parameters=None,
<add> self, *, sql, snowflake_conn_id='snowflake_default', parameters=None,
<ide> autocommit=True, warehouse=None, database=None, role=None,
<ide> schema=None, authenticator=None, **kwargs):
<ide> super().__init__(**kwargs)
<ide><path>airflow/providers/snowflake/transfers/s3_to_snowflake.py
<ide> class S3ToSnowflakeOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(self,
<add> *,
<ide> s3_keys,
<ide> table,
<ide> stage,
<ide><path>airflow/providers/snowflake/transfers/snowflake_to_slack.py
<ide> class SnowflakeToSlackOperator(BaseOperator):
<ide> @apply_defaults
<ide> def __init__( # pylint: disable=too-many-arguments
<ide> self,
<add> *,
<ide> sql: str,
<ide> slack_message: str,
<ide> snowflake_conn_id: str = 'snowflake_default',
<ide><path>airflow/providers/sqlite/operators/sqlite.py
<ide> class SqliteOperator(BaseOperator):
<ide> @apply_defaults
<ide> def __init__(
<ide> self,
<add> *,
<ide> sql: str,
<ide> sqlite_conn_id: str = 'sqlite_default',
<ide> parameters: Optional[Union[Mapping, Iterable]] = None,
<ide><path>airflow/providers/ssh/operators/ssh.py
<ide> class SSHOperator(BaseOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(self,
<add> *,
<ide> ssh_hook=None,
<ide> ssh_conn_id=None,
<ide> remote_host=None,
<ide><path>airflow/providers/vertica/operators/vertica.py
<ide> class VerticaOperator(BaseOperator):
<ide> ui_color = '#b4e0ff'
<ide>
<ide> @apply_defaults
<del> def __init__(self, sql: Union[str, List[str]],
<add> def __init__(self, *, sql: Union[str, List[str]],
<ide> vertica_conn_id: str = 'vertica_default',
<ide> **kwargs: Any) -> None:
<ide> super().__init__(**kwargs)
<ide><path>airflow/providers/yandex/operators/yandexcloud_dataproc.py
<ide> class DataprocCreateClusterOperator(BaseOperator):
<ide> # pylint: disable=too-many-locals
<ide> @apply_defaults
<ide> def __init__(self,
<add> *,
<ide> folder_id: Optional[str] = None,
<ide> cluster_name: Optional[str] = None,
<ide> cluster_description: str = '',
<ide> class DataprocDeleteClusterOperator(BaseOperator):
<ide> template_fields = ['cluster_id']
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> connection_id: Optional[str] = None,
<ide> cluster_id: Optional[str] = None,
<ide> **kwargs):
<ide> class DataprocCreateHiveJobOperator(BaseOperator):
<ide>
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> query: Optional[str] = None,
<ide> query_file_uri: Optional[str] = None,
<ide> script_variables: Optional[Dict[str, str]] = None,
<ide> class DataprocCreateMapReduceJobOperator(BaseOperator):
<ide>
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> main_class: Optional[str] = None,
<ide> main_jar_file_uri: Optional[str] = None,
<ide> jar_file_uris: Optional[Iterable[str]] = None,
<ide> class DataprocCreateSparkJobOperator(BaseOperator):
<ide>
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> main_class: Optional[str] = None,
<ide> main_jar_file_uri: Optional[str] = None,
<ide> jar_file_uris: Optional[Iterable[str]] = None,
<ide> class DataprocCreatePysparkJobOperator(BaseOperator):
<ide>
<ide> # pylint: disable=too-many-arguments
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> main_python_file_uri: Optional[str] = None,
<ide> python_file_uris: Optional[Iterable[str]] = None,
<ide> jar_file_uris: Optional[Iterable[str]] = None,
<ide><path>airflow/sensors/base_sensor_operator.py
<ide> class BaseSensorOperator(BaseOperator, SkipMixin):
<ide> valid_modes = ['poke', 'reschedule'] # type: Iterable[str]
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> poke_interval: float = 60,
<ide> timeout: float = 60 * 60 * 24 * 7,
<ide> soft_fail: bool = False,
<ide><path>airflow/sensors/bash.py
<ide> class BashSensor(BaseSensorOperator):
<ide> template_fields = ('bash_command', 'env')
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> bash_command,
<ide> env=None,
<ide> output_encoding='utf-8',
<ide><path>airflow/sensors/date_time_sensor.py
<ide> class DateTimeSensor(BaseSensorOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self, target_time: Union[str, datetime.datetime], **kwargs
<add> self, *, target_time: Union[str, datetime.datetime], **kwargs
<ide> ) -> None:
<ide> super().__init__(**kwargs)
<ide> if isinstance(target_time, datetime.datetime):
<ide><path>airflow/sensors/external_task_sensor.py
<ide> class ExternalTaskSensor(BaseSensorOperator):
<ide> ui_color = '#19647e'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> external_dag_id,
<ide> external_task_id=None,
<ide> allowed_states=None,
<ide> class ExternalTaskMarker(DummyOperator):
<ide> ui_color = '#19647e'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> external_dag_id,
<ide> external_task_id,
<ide> execution_date: Optional[Union[str, datetime.datetime]] = "{{ execution_date.isoformat() }}",
<ide><path>airflow/sensors/filesystem.py
<ide> class FileSensor(BaseSensorOperator):
<ide> ui_color = '#91818a'
<ide>
<ide> @apply_defaults
<del> def __init__(self,
<add> def __init__(self, *,
<ide> filepath,
<ide> fs_conn_id='fs_default',
<ide> **kwargs):
<ide><path>airflow/sensors/python.py
<ide> class PythonSensor(BaseSensorOperator):
<ide>
<ide> @apply_defaults
<ide> def __init__(
<del> self,
<add> self, *,
<ide> python_callable: Callable,
<ide> op_args: Optional[List] = None,
<ide> op_kwargs: Optional[Dict] = None,
<ide><path>airflow/sensors/sql_sensor.py
<ide> class SqlSensor(BaseSensorOperator):
<ide> ui_color = '#7c7287'
<ide>
<ide> @apply_defaults
<del> def __init__(self, conn_id, sql, parameters=None, success=None, failure=None, fail_on_empty=False,
<add> def __init__(self, *, conn_id, sql, parameters=None, success=None, failure=None, fail_on_empty=False,
<ide> **kwargs):
<ide> self.conn_id = conn_id
<ide> self.sql = sql
<ide><path>airflow/sensors/time_delta_sensor.py
<ide> class TimeDeltaSensor(BaseSensorOperator):
<ide> """
<ide>
<ide> @apply_defaults
<del> def __init__(self, delta, **kwargs):
<add> def __init__(self, *, delta, **kwargs):
<ide> super().__init__(**kwargs)
<ide> self.delta = delta
<ide>
<ide><path>airflow/sensors/time_sensor.py
<ide> class TimeSensor(BaseSensorOperator):
<ide> """
<ide>
<ide> @apply_defaults
<del> def __init__(self, target_time, **kwargs):
<add> def __init__(self, *, target_time, **kwargs):
<ide> super().__init__(**kwargs)
<ide> self.target_time = target_time
<ide>
<ide><path>airflow/sensors/weekday_sensor.py
<ide> class DayOfWeekSensor(BaseSensorOperator):
<ide> """
<ide>
<ide> @apply_defaults
<del> def __init__(self, week_day,
<add> def __init__(self, *, week_day,
<ide> use_task_execution_day=False,
<ide> **kwargs):
<ide> super().__init__(**kwargs) | 104 |
Javascript | Javascript | fix a typo in container docs | e242301f8a7250bf60f72d940149f607bb72c862 | <ide><path>packages/container/lib/main.js
<ide> define("container",
<ide> @method makeToString
<ide>
<ide> @param {any} factory
<del> @param {string} fullNae
<add> @param {string} fullName
<ide> @return {function} toString function
<ide> */
<ide> makeToString: function(factory, fullName) { | 1 |
Ruby | Ruby | avoid failure if no arguments | 6b779c4f6db64e106adfc1949f7bd3b96c49097e | <ide><path>Library/Homebrew/exceptions.rb
<ide> def initialize(formula, cmd, args, env)
<ide> @cmd = cmd
<ide> @args = args
<ide> @env = env
<del> pretty_args = args.map { |arg| arg.to_s.gsub " ", "\\ " }.join(" ")
<del> super "Failed executing: #{cmd} #{pretty_args}"
<add> pretty_args = Array(args).map { |arg| arg.to_s.gsub " ", "\\ " }.join(" ")
<add> super "Failed executing: #{cmd} #{pretty_args}".strip
<ide> end
<ide>
<ide> def issues | 1 |
Python | Python | fix noqa [ci skip] | 96b91a8898799bb5cce0b264f0a7685643f46b9f | <ide><path>spacy/tests/lang/test_initialize.py
<ide> @pytest.mark.parametrize("lang", LANGUAGES)
<ide> def test_lang_initialize(lang, capfd):
<ide> """Test that languages can be initialized."""
<del> nlp = get_lang_class(lang)() # noqa: F841
<add> nlp = get_lang_class(lang)()
<ide> # Check for stray print statements (see #3342)
<del> doc = nlp("test")
<add> doc = nlp("test") # noqa: F841
<ide> captured = capfd.readouterr()
<ide> assert not captured.out | 1 |
Javascript | Javascript | make profile update after server response | ed015fb06f95ee2b7f9e68e3347d0781cf070110 | <ide><path>client/src/components/settings/Privacy.js
<ide> import { bindActionCreators } from 'redux';
<ide> import { connect } from 'react-redux';
<ide> import { createSelector } from 'reselect';
<ide> import { Button, Form } from '@freecodecamp/react-bootstrap';
<del>import { isEqual } from 'lodash';
<ide>
<ide> import { userSelector } from '../../redux';
<ide> import { submitProfileUI } from '../../redux/settings';
<ide> import SectionHeader from './SectionHeader';
<ide> const mapStateToProps = createSelector(
<ide> userSelector,
<ide> user => ({
<del> ...user.profileUI,
<ide> user
<ide> })
<ide> );
<ide> const mapDispatchToProps = dispatch =>
<ide> bindActionCreators({ submitProfileUI }, dispatch);
<ide>
<ide> const propTypes = {
<del> isLocked: PropTypes.bool,
<del> showAbout: PropTypes.bool,
<del> showCerts: PropTypes.bool,
<del> showDonation: PropTypes.bool,
<del> showHeatMap: PropTypes.bool,
<del> showLocation: PropTypes.bool,
<del> showName: PropTypes.bool,
<del> showPoints: PropTypes.bool,
<del> showPortfolio: PropTypes.bool,
<del> showTimeLine: PropTypes.bool,
<ide> submitProfileUI: PropTypes.func.isRequired,
<del> user: PropTypes.object
<add> user: PropTypes.shape({
<add> profileUI: PropTypes.shape({
<add> isLocked: PropTypes.bool,
<add> showAbout: PropTypes.bool,
<add> showCerts: PropTypes.bool,
<add> showDonation: PropTypes.bool,
<add> showHeatMap: PropTypes.bool,
<add> showLocation: PropTypes.bool,
<add> showName: PropTypes.bool,
<add> showPoints: PropTypes.bool,
<add> showPortfolio: PropTypes.bool,
<add> showTimeLine: PropTypes.bool
<add> }),
<add> username: PropTypes.String
<add> })
<ide> };
<ide>
<ide> class PrivacySettings extends Component {
<del> constructor(props) {
<del> super(props);
<del>
<del> const originalProfileUI = { ...props.user.profileUI };
<del>
<del> this.state = {
<del> privacyValues: {
<del> ...originalProfileUI
<del> },
<del> originalProfileUI: { ...originalProfileUI }
<del> };
<del> }
<del>
<del> componentDidUpdate() {
<del> const { profileUI: currentPropsProfileUI } = this.props.user;
<del> const { originalProfileUI } = this.state;
<del> if (!isEqual(originalProfileUI, currentPropsProfileUI)) {
<del> /* eslint-disable-next-line react/no-did-update-set-state */
<del> return this.setState(state => ({
<del> ...state,
<del> originalProfileUI: { ...currentPropsProfileUI },
<del> privacyValues: { ...currentPropsProfileUI }
<del> }));
<del> }
<del> return null;
<del> }
<del>
<ide> handleSubmit = e => e.preventDefault();
<ide>
<del> toggleFlag = flag => () =>
<del> this.setState(
<del> state => ({
<del> privacyValues: {
<del> ...state.privacyValues,
<del> [flag]: !state.privacyValues[flag]
<del> }
<del> }),
<del> () => this.props.submitProfileUI(this.state.privacyValues)
<del> );
<add> toggleFlag = flag => () => {
<add> const privacyValues = { ...this.props.user.profileUI };
<add> privacyValues[flag] = !privacyValues[flag];
<add> this.props.submitProfileUI(privacyValues);
<add> };
<ide>
<ide> render() {
<del> const {
<del> privacyValues: {
<del> isLocked = true,
<del> showAbout = false,
<del> showCerts = false,
<del> showDonation = false,
<del> showHeatMap = false,
<del> showLocation = false,
<del> showName = false,
<del> showPoints = false,
<del> showPortfolio = false,
<del> showTimeLine = false
<del> }
<del> } = this.state;
<ide> const { user } = this.props;
<add> const {
<add> isLocked = true,
<add> showAbout = false,
<add> showCerts = false,
<add> showDonation = false,
<add> showHeatMap = false,
<add> showLocation = false,
<add> showName = false,
<add> showPoints = false,
<add> showPortfolio = false,
<add> showTimeLine = false
<add> } = user.profileUI;
<ide>
<ide> return (
<ide> <div className='privacy-settings'>
<ide><path>client/src/redux/index.js
<ide> export const reducer = handleActions(
<ide> [settingsTypes.updateUserFlagComplete]: (state, { payload }) =>
<ide> payload ? spreadThePayloadOnUser(state, payload) : state,
<ide> [settingsTypes.verifyCertComplete]: (state, { payload }) =>
<del> payload ? spreadThePayloadOnUser(state, payload) : state
<add> payload ? spreadThePayloadOnUser(state, payload) : state,
<add> [settingsTypes.submitProfileUIComplete]: (state, { payload }) =>
<add> payload
<add> ? {
<add> ...state,
<add> user: {
<add> ...state.user,
<add> [state.appUsername]: {
<add> ...state.user[state.appUsername],
<add> profileUI: { ...payload }
<add> }
<add> }
<add> }
<add> : state
<ide> },
<ide> initialState
<ide> ); | 2 |
Javascript | Javascript | add missing round bracket | f5f802c6e68a3d4e22f5e7725057652519d15e60 | <ide><path>src/ng/rootScope.js
<ide> function $RootScopeProvider() {
<ide> * $digest()} and should return the value that will be watched. (`watchExpression` should not change
<ide> * its value when executed multiple times with the same input because it may be executed multiple
<ide> * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
<del> * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
<add> * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
<ide> * - The `listener` is called only when the value from the current `watchExpression` and the
<ide> * previous call to `watchExpression` are not equal (with the exception of the initial run,
<ide> * see below). Inequality is determined according to reference inequality, | 1 |
Javascript | Javascript | update backburner to fix ie8 failing test | 9e75b058a240af6d9681ddeda1260b027c5c1172 | <ide><path>packages/ember-metal/lib/vendor/backburner.js
<ide> define("backburner",
<ide> clearTimeout(laterTimer);
<ide> laterTimer = null;
<ide> }
<del> laterTimer = setTimeout(function() {
<add> laterTimer = window.setTimeout(function() {
<ide> executeTimers(self);
<ide> laterTimer = null;
<ide> laterTimerExpiresAt = null;
<ide> define("backburner",
<ide> if (debouncee[0] === target && debouncee[1] === method) { return; } // do nothing
<ide> }
<ide>
<del> var timer = setTimeout(function() {
<add> var timer = window.setTimeout(function() {
<ide> self.run.apply(self, args);
<ide>
<ide> // remove debouncee
<ide> define("backburner",
<ide>
<ide> function createAutorun(backburner) {
<ide> backburner.begin();
<del> autorun = setTimeout(function() {
<add> autorun = window.setTimeout(function() {
<ide> backburner.end();
<ide> autorun = null;
<ide> });
<ide> define("backburner",
<ide> });
<ide>
<ide> if (timers.length) {
<del> laterTimer = setTimeout(function() {
<add> laterTimer = window.setTimeout(function() {
<ide> executeTimers(self);
<ide> laterTimer = null;
<ide> laterTimerExpiresAt = null;
<ide> define("backburner/queue",
<ide> };
<ide>
<ide> __exports__.Queue = Queue;
<del> });
<ide>\ No newline at end of file
<add> }); | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.