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
fix a bug in 3mfloader
f344d8fe97ead056131f31d96a1b20019c1e32cd
<ide><path>examples/js/loaders/3MFLoader.js <ide> THREE.ThreeMFLoader.prototype = { <ide> } ); <ide> var mat4 = new THREE.Matrix4(); <ide> buildItem[ 'transform' ] = mat4.set( <del> t[ 0 ], t[ 1 ], t[ 2 ], 0.0, <del> t[ 3 ], t[ 4 ], t[ 5 ], 0.0, <del> t[ 6 ], t[ 7 ], t[ 8 ], 0.0, <del> t[ 9 ], t[ 10 ], t[ 11 ], 1.0 <add> t[ 0 ], t[ 3 ], t[ 6 ], t[ 9 ], <add> t[ 1 ], t[ 4 ], t[ 7 ], t[ 10 ], <add> t[ 2 ], t[ 5 ], t[ 8 ], t[ 11 ], <add> 0.0, 0.0, 0.0, 1.0 <ide> ); <ide> <ide> }
1
Text
Text
remove an extra space in a hint
53d6ea90fd66b8ff0db7c0608e596245d78e8658
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md <ide> assert( <ide> ); <ide> ``` <ide> <del>A `setter` should be defined. <add>A `setter` should be defined. <ide> <ide> ```js <ide> assert(
1
Text
Text
add asr colabs
0bc2e54f00f2464494d01ad43bcbaf21eaf80742
<ide><path>examples/pytorch/README.md <ide> Coming soon! <ide> | [**`text-generation`**](https://github.com/huggingface/transformers/tree/master/examples/pytorch/text-generation) | - | n/a | - | - | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb) <ide> | [**`token-classification`**](https://github.com/huggingface/transformers/tree/master/examples/pytorch/token-classification) | CoNLL NER | ✅ |✅ | ✅ | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/token_classification.ipynb) <ide> | [**`translation`**](https://github.com/huggingface/transformers/tree/master/examples/pytorch/translation) | WMT | ✅ | ✅ |✅ | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/translation.ipynb) <add>| [**`speech-recognition`**](https://github.com/huggingface/transformers/tree/master/examples/pytorch/speech-recognition) | TIMIT | ✅ | - |✅ | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/speech_recognition.ipynb) <add>| [**`multi-lingual speech-recognition`**](https://github.com/huggingface/transformers/tree/master/examples/pytorch/speech-recognition) | Common Voice | ✅ | - |✅ | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/multi_lingual_speech_recognition.ipynb) <ide> <ide> <ide> ## Running quick tests <ide><path>notebooks/README.md <ide> You can open any page of the documentation as a notebook in colab (there is a bu <ide> | [How to fine-tune a model on multiple choice](https://github.com/huggingface/notebooks/blob/master/examples/multiple_choice.ipynb) | Show how to preprocess the data and fine-tune a pretrained model on SWAG. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/multiple_choice.ipynb)| <ide> | [How to fine-tune a model on translation](https://github.com/huggingface/notebooks/blob/master/examples/translation.ipynb) | Show how to preprocess the data and fine-tune a pretrained model on WMT. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/translation.ipynb)| <ide> | [How to fine-tune a model on summarization](https://github.com/huggingface/notebooks/blob/master/examples/summarization.ipynb) | Show how to preprocess the data and fine-tune a pretrained model on XSUM. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/summarization.ipynb)| <add>| [How to fine-tune a speech recognition model in English](https://github.com/huggingface/notebooks/blob/master/examples/speech_recognition.ipynb)| Show how to preprocess the data and fine-tune a pretrained Speech model on TIMIT | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/speech_recognition.ipynb)| <add>| [How to fine-tune a speech recognition in any language](https://github.com/huggingface/notebooks/blob/master/examples/multi_lingual_speech_recognition.ipynb)| Show how to preprocess the data and fine-tune a multi-lingually pretrained speech model on Common Voice | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/multi_lingual_speech_recognition.ipynb)| <ide> | [How to train a language model from scratch](https://github.com/huggingface/blog/blob/master/notebooks/01_how_to_train.ipynb)| Highlight all the steps to effectively train Transformer model on custom data | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/01_how_to_train.ipynb)| <ide> | [How to generate text](https://github.com/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb)| How to use different decoding methods for language generation with transformers | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb)| <ide> | [How to export model to ONNX](https://github.com/huggingface/notebooks/blob/master/examples/onnx-export.ipynb) | Highlight how to export and run inference workloads through ONNX |
2
Text
Text
use active voice and use more descriptive terms
7fe1f0f4ea2c9e82b4b19ecb07a3c9f4dca96821
<ide><path>guides/source/active_record_querying.md <ide> class Post < ActiveRecord::Base <ide> end <ide> ``` <ide> <del>This may then be called using this: <add>Call the scope as if it were a class method: <ide> <ide> ```ruby <ide> Post.created_before(Time.zone.now)
1
Python
Python
use trunc as fix implementation
96bcaf6272b1045bd766025163837d3083503f1f
<ide><path>numpy/lib/ufunclike.py <ide> def fix(x, y=None): <ide> """ Round x to nearest integer towards zero. <ide> """ <del> x = asanyarray(x) <del> if y is None: <del> y = nx.floor(x) <del> else: <del> nx.floor(x, y) <del> if x.ndim == 0: <del> if (x<0): <del> y += 1 <del> else: <del> y[x<0] = y[x<0]+1 <del> return y <add> # fix is now implemented in C, using the C99 trunc function. <add> return umath.trunc(x, y) <ide> <ide> def isposinf(x, y=None): <ide> """
1
Python
Python
add folders plugin to the unitaries tests
5ab1059c3504366cd018995205d98ffa5b0341b7
<ide><path>unitest-restful.py <ide> def test_003_plugins(self): <ide> if p in ('uptime', 'now'): <ide> self.assertIsInstance(req.json(), text_type) <ide> elif p in ('fs', 'monitor', 'percpu', 'sensors', 'alert', 'processlist', <del> 'diskio', 'hddtemp', 'batpercent', 'network'): <add> 'diskio', 'hddtemp', 'batpercent', 'network', 'folders'): <ide> self.assertIsInstance(req.json(), list) <ide> elif p in ('psutilversion', 'help'): <ide> pass <ide><path>unitest-xmlrpc.py <ide> def test_006_net(self): <ide> <ide> def test_007_disk(self): <ide> """DISK.""" <del> method = "getFs() and getDiskIO()" <add> method = "getFs(), getFolders() and getDiskIO()" <ide> print('INFO: [TEST_007] Method: %s' % method) <ide> <ide> req = json.loads(client.getFs()) <ide> self.assertIsInstance(req, list) <ide> <add> req = json.loads(client.getFolders()) <add> self.assertIsInstance(req, list) <add> <ide> req = json.loads(client.getDiskIO()) <ide> self.assertIsInstance(req, list) <ide>
2
Python
Python
fix imports again based on sponge error
25efe03e7a59ce66e7da9c6823364d16ea2ca8de
<ide><path>official/resnet/keras/keras_common.py <ide> <ide> import time <ide> <add>import numpy as np <add> <ide> # pylint: disable=g-bad-import-order <ide> from absl import flags <del>import numpy as np <ide> import tensorflow as tf <ide> from tensorflow.python.keras.optimizer_v2 import (gradient_descent as <ide> gradient_descent_v2)
1
Python
Python
improve testcliconfig in local environment
c970053254969348919ebcdc9549c8b24be7d894
<ide><path>tests/cli/commands/test_config_command.py <ide> def setUpClass(cls): <ide> @mock.patch("airflow.cli.commands.config_command.io.StringIO") <ide> @mock.patch("airflow.cli.commands.config_command.conf") <ide> def test_cli_show_config_should_write_data(self, mock_conf, mock_stringio): <del> config_command.show_config(self.parser.parse_args(['config'])) <add> config_command.show_config(self.parser.parse_args(['config', '--color', 'off'])) <ide> mock_conf.write.assert_called_once_with(mock_stringio.return_value.__enter__.return_value) <ide> <ide> @conf_vars({ <ide> ('core', 'testkey'): 'test_value' <ide> }) <ide> def test_cli_show_config_should_display_key(self): <ide> with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: <del> config_command.show_config(self.parser.parse_args(['config'])) <add> config_command.show_config(self.parser.parse_args(['config', '--color', 'off'])) <ide> self.assertIn('[core]', temp_stdout.getvalue()) <ide> self.assertIn('testkey = test_value', temp_stdout.getvalue())
1
Javascript
Javascript
update openssl3 error messages for beta-1
d58f0e005efb9bcf9c308f0fde590c7e278f7ca6
<ide><path>test/parallel/test-crypto-dh-stateless.js <ide> assert.throws(() => { <ide> crypto.generateKeyPairSync('ec', { namedCurve: not256k1 })); <ide> }, common.hasOpenSSL3 ? { <ide> name: 'Error', <del> code: 'ERR_OSSL_MISMATCHING_SHARED_PARAMETERS' <add> code: 'ERR_OSSL_MISMATCHING_DOMAIN_PARAMETERS' <ide> } : { <ide> name: 'Error', <ide> code: 'ERR_OSSL_EVP_DIFFERENT_PARAMETERS' <ide><path>test/parallel/test-crypto-key-objects.js <ide> const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem', <ide> assert.throws(() => { <ide> createPrivateKey({ key: '' }); <ide> }, common.hasOpenSSL3 ? { <del> message: 'Failed to read private key', <add> message: 'error:1E08010C:DECODER routines::unsupported', <ide> } : { <ide> message: 'error:0909006C:PEM routines:get_name:no start line', <ide> code: 'ERR_OSSL_PEM_NO_START_LINE', <ide> const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem', <ide> // Reading an encrypted key without a passphrase should fail. <ide> assert.throws(() => createPrivateKey(privateDsa), common.hasOpenSSL3 ? { <ide> name: 'Error', <del> message: 'error:07880109:common libcrypto routines::interrupted or ' + <del> 'cancelled', <add> message: 'error:1E08010C:DECODER routines::unsupported', <ide> } : { <ide> name: 'TypeError', <ide> code: 'ERR_MISSING_PASSPHRASE', <ide> const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem', <ide> passphrase: Buffer.alloc(1024, 'a') <ide> }), { <ide> message: common.hasOpenSSL3 ? <del> 'error:07880109:common libcrypto routines::interrupted or cancelled' : <add> 'error:1E08010C:DECODER routines::unsupported' : <ide> /bad decrypt/ <ide> }); <ide> <ide><path>test/parallel/test-crypto-keygen.js <ide> const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher); <ide> // Since the private key is encrypted, signing shouldn't work anymore. <ide> assert.throws(() => testSignVerify(publicKey, privateKey), <ide> common.hasOpenSSL3 ? { <del> message: 'error:07880109:common libcrypto ' + <del> 'routines::interrupted or cancelled' <add> message: 'error:1E08010C:DECODER routines::unsupported' <ide> } : { <ide> name: 'TypeError', <ide> code: 'ERR_MISSING_PASSPHRASE', <ide> const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher); <ide> // Since the private key is encrypted, signing shouldn't work anymore. <ide> assert.throws(() => testSignVerify(publicKey, privateKey), <ide> common.hasOpenSSL3 ? { <del> message: 'error:07880109:common libcrypto ' + <del> 'routines::interrupted or cancelled' <add> message: 'error:1E08010C:DECODER routines::unsupported' <ide> } : { <ide> name: 'TypeError', <ide> code: 'ERR_MISSING_PASSPHRASE',
3
Text
Text
add documentation for active support on load hooks
8ca42638bc3115e5161b084a668e253dee94fd24
<ide><path>guides/source/engines.md <ide> After reading this guide, you will know: <ide> * How to build features for the engine. <ide> * How to hook the engine into an application. <ide> * How to override engine functionality in the application. <add>* Avoid loading Rails frameworks with Load and Configuration Hooks <ide> <ide> -------------------------------------------------------------------------------- <ide> <ide> module MyEngine <ide> end <ide> end <ide> ``` <add> <add>Active Support On Load Hooks <add>---------------------------- <add> <add>Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal utilities. <add> <add>Rails code can often be referenced on load of an application. Rails is responsible for the load order of these frameworks, so when you load frameworks, such as `ActiveRecord::Base`, prematurely you are violating an implicit contract your application has with Rails. Moreover, by loading code such as `ActiveRecord::Base` on boot of your application you are loading entire frameworks which may slow down your boot time and could cause conflicts with load order and boot of your application. <add> <add>On Load hooks are the API that allow you to hook into this initialization process without violating the load contract with Rails. This will also mitigate boot performance degradation and avoid conflicts. <add> <add>## What are `on_load` hooks? <add> <add>Since Ruby is a dynamic language, some code will cause different Rails frameworks to load. Take this snippet for instance: <add> <add>```ruby <add>ActiveRecord::Base.include(MyActiveRecordHelper) <add>``` <add> <add>This snippet means that when this file is loaded, it will encounter `ActiveRecord::Base`. This encounter causes Ruby to look for the definition of that constant and will require it. This causes the entire Active Record framework to be loaded on boot. <add> <add>`ActiveSupport.on_load` is a mechanism that can be used to defer the loading of code until it is actually needed. The snippet above can be changed to: <add> <add>```ruby <add>ActiveSupport.on_load(:active_record) { include MyActiveRecordHelper } <add>``` <add> <add>This new snippet will only include `MyActiveRecordHelper` when `ActiveRecord::Base` is loaded. <add> <add>## How does it work? <add> <add>In the Rails framework these hooks are called when a specific library is loaded. For example, when `ActionController::Base` is loaded, the `:action_controller_base` hook is called. This means that all `ActiveSupport.on_load` calls with `:action_controller_base` hooks will be called in the context of `ActionController::Base` (that means `self` will be an `ActionController::Base`). <add> <add>## Modifying code to use `on_load` hooks <add> <add>Modifying code is generally straightforward. If you have a line of code that refers to a Rails framework such as `ActiveRecord::Base` you can wrap that code in an `on_load` hook. <add> <add>### Example 1 <add> <add>```ruby <add>ActiveRecord::Base.include(MyActiveRecordHelper) <add>``` <add> <add>becomes <add> <add>```ruby <add>ActiveSupport.on_load(:active_record) { include MyActiveRecordHelper } # self refers to ActiveRecord::Base here, so we can simply #include <add>``` <add> <add>### Example 2 <add> <add>```ruby <add>ActionController::Base.prepend(MyActionControllerHelper) <add>``` <add> <add>becomes <add> <add>```ruby <add>ActiveSupport.on_load(:action_controller_base) { prepend MyActionControllerHelper } # self refers to ActionController::Base here, so we can simply #prepend <add>``` <add> <add>### Example 3 <add> <add>```ruby <add>ActiveRecord::Base.include_root_in_json = true <add>``` <add> <add>becomes <add> <add>```ruby <add>ActiveSupport.on_load(:active_record) { self.include_root_in_json = true } # self refers to ActiveRecord::Base here <add>``` <add> <add>## Available Hooks <add> <add>These are the hooks you can use in your own code. <add> <add>To hook into the initialization process of one of the following classes use the available hook. <add> <add>| Class | Available Hooks | <add>| --------------------------------- | ------------------------------------ | <add>| `ActionCable` | `action_cable` | <add>| `ActionController::API` | `action_controller_api` | <add>| `ActionController::API` | `action_controller` | <add>| `ActionController::Base` | `action_controller_base` | <add>| `ActionController::Base` | `action_controller` | <add>| `ActionController::TestCase` | `action_controller_test_case` | <add>| `ActionDispatch::IntegrationTest` | `action_dispatch_integration_test` | <add>| `ActionMailer::Base` | `action_mailer` | <add>| `ActionMailer::TestCase` | `action_mailer_test_case` | <add>| `ActionView::Base` | `action_view` | <add>| `ActionView::TestCase` | `action_view_test_case` | <add>| `ActiveJob::Base` | `active_job` | <add>| `ActiveJob::TestCase` | `active_job_test_case` | <add>| `ActiveRecord::Base` | `active_record` | <add>| `ActiveSupport::TestCase` | `active_support_test_case` | <add>| `i18n` | `i18n` | <add> <add>## Configuration hooks <add> <add>These are the available configuration hooks. They do not hook into any particular framework, instead they run in context of the entire application. <add> <add>| Hook | Use Case | <add>| ---------------------- | ------------------------------------------------------------------------------------- | <add>| `before_configuration` | First configurable block to run. Called before any initializers are run. | <add>| `before_initialize` | Second configurable block to run. Called before frameworks initialize. | <add>| `before_eager_load` | Third configurable block to run. Does not run if `config.cache_classes` set to false. | <add>| `after_initialize` | Last configurable block to run. Called after frameworks initialize. | <add> <add>### Example <add> <add>`config.before_configuration { puts 'I am called before any initializers' }`
1
Text
Text
create model card
55b932a8180e1823285f6a29f853f600463a5006
<ide><path>model_cards/mrm8488/electra-small-finetuned-squadv2/README.md <add>--- <add>language: english <add>--- <add> <add># Electra small ⚡ + SQuAD v2 ❓ <add> <add>[Electra-small-discriminator](https://huggingface.co/google/electra-small-discriminator) fine-tuned on [SQUAD v2.0 dataset](https://rajpurkar.github.io/SQuAD-explorer/explore/v2.0/dev/) for **Q&A** downstream task. <add> <add>## Details of the downstream task (Q&A) - Model 🧠 <add> <add>**ELECTRA** is a new method for self-supervised language representation learning. It can be used to pre-train transformer networks using relatively little compute. ELECTRA models are trained to distinguish "real" input tokens vs "fake" input tokens generated by another neural network, similar to the discriminator of a [GAN](https://arxiv.org/pdf/1406.2661.pdf). At small scale, ELECTRA achieves strong results even when trained on a single GPU. At large scale, ELECTRA achieves state-of-the-art results on the [SQuAD 2.0](https://rajpurkar.github.io/SQuAD-explorer/) dataset. <add> <add> <add>## Details of the downstream task (Q&A) - Dataset 📚 <add> <add>**SQuAD2.0** combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions written adversarially by crowdworkers to look similar to answerable ones. To do well on SQuAD2.0, systems must not only answer questions when possible, but also determine when no answer is supported by the paragraph and abstain from answering. <add> <add>## Model training 🏋️‍ <add> <add>The model was trained on a Tesla P100 GPU and 25GB of RAM with the following command: <add> <add>```bash <add>python transformers/examples/question-answering/run_squad.py \ <add> --model_type electra \ <add> --model_name_or_path 'google/electra-small-discriminator' \ <add> --do_eval \ <add> --do_train \ <add> --do_lower_case \ <add> --train_file '/content/dataset/train-v2.0.json' \ <add> --predict_file '/content/dataset/dev-v2.0.json' \ <add> --per_gpu_train_batch_size 16 \ <add> --learning_rate 3e-5 \ <add> --num_train_epochs 10 \ <add> --max_seq_length 384 \ <add> --doc_stride 128 \ <add> --output_dir '/content/output' \ <add> --overwrite_output_dir \ <add> --save_steps 1000 \ <add> --version_2_with_negative <add>``` <add> <add>## Test set Results 🧾 <add> <add>| Metric | # Value | <add>| ------ | --------- | <add>| **EM** | **69.71** | <add>| **F1** | **73.44** | <add>| **Size**| **50 MB** | <add> <add> <add>```json <add>{ <add>'exact': 69.71279373368147, <add>'f1': 73.4439546123672, <add>'total': 11873, <add>'HasAns_exact': 69.92240215924427, <add>'HasAns_f1': 77.39542393937836, <add>'HasAns_total': 5928, <add>'NoAns_exact': 69.50378469301934, <add>'NoAns_f1': 69.50378469301934, <add>'NoAns_total': 5945, <add>'best_exact': 69.71279373368147, <add>'best_exact_thresh': 0.0, <add>'best_f1': 73.44395461236732, <add>'best_f1_thresh': 0.0 <add>} <add>``` <add> <add>### Model in action 🚀 <add> <add>Fast usage with **pipelines**: <add> <add>```python <add>from transformers import pipeline <add>QnA_pipeline = pipeline('question-answering', model='mrm8488/electra-base-finetuned-squadv2') <add>QnA_pipeline({ <add> 'context': 'A new strain of flu that has the potential to become a pandemic has been identified in China by scientists.', <add> 'question': 'What has been discovered by scientists from China ?' <add>}) <add># Output: <add>{'answer': 'A new strain of flu', 'end': 19, 'score': 0.8650811568752914, 'start': 0} <add>``` <add> <add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) | [LinkedIn](https://www.linkedin.com/in/manuel-romero-cs/) <add> <add>> Made with <span style="color: #e25555;">&hearts;</span> in Spain
1
Ruby
Ruby
use installed cask file for `brew cask zap`
3fb7c3a2f3825984ed3bc1da0595864404338bf6
<ide><path>Library/Homebrew/cask/cmd/uninstall.rb <ide> def self.uninstall_casks(*casks, binaries: nil, force: false, verbose: false) <ide> casks.each do |cask| <ide> odebug "Uninstalling Cask #{cask}" <ide> <del> raise CaskNotInstalledError, cask unless cask.installed? || force <del> <del> if cask.installed? && !cask.installed_caskfile.nil? <del> # use the same cask file that was used for installation, if possible <del> cask = CaskLoader.load(cask.installed_caskfile) if cask.installed_caskfile.exist? <add> if cask.installed? <add> if installed_caskfile = cask.installed_caskfile <add> # Use the same cask file that was used for installation, if possible. <add> cask = CaskLoader.load(installed_caskfile) if installed_caskfile.exist? <add> end <add> else <add> raise CaskNotInstalledError, cask unless force <ide> end <ide> <ide> Installer.new(cask, **options).uninstall <ide><path>Library/Homebrew/cask/cmd/zap.rb <ide> def run <ide> casks.each do |cask| <ide> odebug "Zapping Cask #{cask}" <ide> <del> raise CaskNotInstalledError, cask unless cask.installed? || args.force? <add> if cask.installed? <add> if installed_caskfile = cask.installed_caskfile <add> # Use the same cask file that was used for installation, if possible. <add> cask = CaskLoader.load(installed_caskfile) if installed_caskfile.exist? <add> end <add> else <add> raise CaskNotInstalledError, cask unless args.force? <add> end <ide> <ide> Installer.new(cask, verbose: args.verbose?, force: args.force?).zap <ide> end
2
Python
Python
update russian tokenizer exceptions
7e684ad691992e759e71026a11c1ddd77c401f39
<ide><path>spacy/lang/ru/tokenizer_exceptions.py <ide> {ORTH: "2к23", NORM: "2023"}, <ide> {ORTH: "2к24", NORM: "2024"}, <ide> {ORTH: "2к25", NORM: "2025"}, <add> {ORTH: "2к26", NORM: "2026"}, <add> {ORTH: "2к27", NORM: "2027"}, <add> {ORTH: "2к28", NORM: "2028"}, <add> {ORTH: "2к29", NORM: "2029"}, <add> {ORTH: "2к30", NORM: "2030"}, <ide> ]: <ide> _exc[abbr[ORTH]] = [abbr] <ide> <ide> {ORTH: "з-ка", NORM: "заимка"}, <ide> {ORTH: "п-к", NORM: "починок"}, <ide> {ORTH: "киш.", NORM: "кишлак"}, <del> {ORTH: "п. ст. ", NORM: "поселок станция"}, <del> {ORTH: "п. ж/д ст. ", NORM: "поселок при железнодорожной станции"}, <add> {ORTH: "п. ст.", NORM: "поселок станция"}, <add> {ORTH: "п. ж/д ст.", NORM: "поселок при железнодорожной станции"}, <ide> {ORTH: "ж/д бл-ст", NORM: "железнодорожный блокпост"}, <ide> {ORTH: "ж/д б-ка", NORM: "железнодорожная будка"}, <ide> {ORTH: "ж/д в-ка", NORM: "железнодорожная ветка"}, <ide> {ORTH: "ж/д п.п.", NORM: "железнодорожный путевой пост"}, <ide> {ORTH: "ж/д о.п.", NORM: "железнодорожный остановочный пункт"}, <ide> {ORTH: "ж/д рзд.", NORM: "железнодорожный разъезд"}, <del> {ORTH: "ж/д ст. ", NORM: "железнодорожная станция"}, <add> {ORTH: "ж/д ст.", NORM: "железнодорожная станция"}, <ide> {ORTH: "м-ко", NORM: "местечко"}, <ide> {ORTH: "д.", NORM: "деревня"}, <ide> {ORTH: "с.", NORM: "село"}, <ide> {ORTH: "сл.", NORM: "слобода"}, <del> {ORTH: "ст. ", NORM: "станция"}, <add> {ORTH: "ст.", NORM: "станция"}, <ide> {ORTH: "ст-ца", NORM: "станица"}, <ide> {ORTH: "у.", NORM: "улус"}, <ide> {ORTH: "х.", NORM: "хутор"}, <ide> {ORTH: "прим.", NORM: "примечание"}, <ide> {ORTH: "прим.ред.", NORM: "примечание редакции"}, <ide> {ORTH: "см. также", NORM: "смотри также"}, <del> {ORTH: "кв.м.", NORM: "квадрантный метр"}, <del> {ORTH: "м2", NORM: "квадрантный метр"}, <add> {ORTH: "см.", NORM: "смотри"}, <add> {ORTH: "кв.м.", NORM: "квадратный метр"}, <add> {ORTH: "м2", NORM: "квадратный метр"}, <ide> {ORTH: "б/у", NORM: "бывший в употреблении"}, <ide> {ORTH: "сокр.", NORM: "сокращение"}, <ide> {ORTH: "чел.", NORM: "человек"},
1
Text
Text
fix formatting issue
4d6debcfd331d767a509a24cd7545a4367193977
<ide><path>client/src/pages/guide/english/python/web-frameworks-and-what-they-do-for-you/bottle/index.md <ide> The following details how to write and run a simple greeting web app where we ca <ide> <ide> If we enter our name and press submit now we will get a `HTTP 404` error though as we have not yet defined the function to respond to this request. <ide> <del> <ide> ```python <ide> run(host='localhost', port=8080) <ide> ```
1
PHP
PHP
use "toarray()" when available
b6eb79e51f4d098fea020536003c38c5c109b423
<ide><path>src/Utility/Hash.php <ide> public static function extract($data, $path) <ide> list($token, $conditions) = self::_splitConditions($token); <ide> <ide> foreach ($context[$_key] as $item) { <add> if (is_object($item) && method_exists($item, 'toArray')) { <add> $item = $item->toArray(); <add> } <ide> foreach ((array)$item as $k => $v) { <ide> if (static::_matchToken($k, $token)) { <ide> $next[] = $v; <ide><path>tests/TestCase/Utility/HashTest.php <ide> namespace Cake\Test\TestCase\Utility; <ide> <ide> use ArrayObject; <add>use Cake\ORM\Entity; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Hash; <ide> <ide> public static function articleData() <ide> public static function articleDataObject() <ide> { <ide> return new ArrayObject([ <del> new ArrayObject([ <add> new Entity([ <ide> 'Article' => new ArrayObject([ <ide> 'id' => '1', <ide> 'user_id' => '1',
2
Python
Python
remove logical object ufuncs with bool output
4a74cee8530e51fe60f77fa0131eda5e2c8a986d
<ide><path>numpy/core/code_generators/generate_umath.py <ide> def english_upper(s): <ide> 'PyUFunc_SimpleBinaryComparisonTypeResolver', <ide> TD(nodatetime_or_obj, out='?', simd=[('avx2', ints)]), <ide> TD(O, f='npy_ObjectLogicalAnd'), <del> TD(O, f='npy_ObjectLogicalAnd', out='?'), <ide> ), <ide> 'logical_not': <ide> Ufunc(1, 1, None, <ide> docstrings.get('numpy.core.umath.logical_not'), <ide> None, <ide> TD(nodatetime_or_obj, out='?', simd=[('avx2', ints)]), <ide> TD(O, f='npy_ObjectLogicalNot'), <del> TD(O, f='npy_ObjectLogicalNot', out='?'), <ide> ), <ide> 'logical_or': <ide> Ufunc(2, 1, False_, <ide> docstrings.get('numpy.core.umath.logical_or'), <ide> 'PyUFunc_SimpleBinaryComparisonTypeResolver', <ide> TD(nodatetime_or_obj, out='?', simd=[('avx2', ints)]), <ide> TD(O, f='npy_ObjectLogicalOr'), <del> TD(O, f='npy_ObjectLogicalOr', out='?'), <ide> ), <ide> 'logical_xor': <ide> Ufunc(2, 1, False_, <ide> docstrings.get('numpy.core.umath.logical_xor'), <ide> 'PyUFunc_SimpleBinaryComparisonTypeResolver', <ide> TD(nodatetime_or_obj, out='?'), <add> # TODO: using obj.logical_xor() seems pretty much useless: <ide> TD(P, f='logical_xor'), <ide> ), <ide> 'maximum': <ide><path>numpy/core/tests/test_ufunc.py <ide> def test_NotImplemented_not_returned(self): <ide> assert_raises(TypeError, f, a, b) <ide> assert_raises(TypeError, f, c, a) <ide> <add> @pytest.mark.parametrize("ufunc", <add> [np.logical_and, np.logical_or]) # logical_xor object loop is bad <add> @pytest.mark.parametrize("signature", <add> [(None, None, object), (object, None, None), <add> (None, object, None)]) <add> def test_logical_ufuncs_object_signatures(self, ufunc, signature): <add> a = np.array([True, None, False], dtype=object) <add> res = ufunc(a, a, signature=signature) <add> assert res.dtype == object <add> <add> @pytest.mark.parametrize("ufunc", <add> [np.logical_and, np.logical_or, np.logical_xor]) <add> @pytest.mark.parametrize("signature", <add> [(bool, None, object), (object, None, bool), <add> (None, object, bool)]) <add> def test_logical_ufuncs_mixed_object_signatures(self, ufunc, signature): <add> # Most mixed signatures fail (except those with bool out, e.g. `OO->?`) <add> a = np.array([True, None, False]) <add> with pytest.raises(TypeError): <add> ufunc(a, a, signature=signature) <add> <ide> def test_reduce_noncontig_output(self): <ide> # Check that reduction deals with non-contiguous output arrays <ide> # appropriately.
2
Javascript
Javascript
refactor the attr method
c8ba433f1892f61e51991439e484e78322137eb6
<ide><path>src/jqLite.js <ide> forEach({ <ide> }, <ide> <ide> attr: function(element, name, value) { <add> var ret; <ide> var nodeType = element.nodeType; <ide> if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) { <ide> return; <ide> } <add> <ide> var lowercasedName = lowercase(name); <del> if (BOOLEAN_ATTR[lowercasedName]) { <del> if (isDefined(value)) { <del> if (value !== false && value !== null) { <del> element.setAttribute(name, name); <del> } else { <del> element.removeAttribute(name); <del> } <del> } else { <del> return element.getAttribute(name) != null ? lowercasedName : undefined; <del> } <del> } else if (isDefined(value)) { <del> if (value === null) { <add> var isBooleanAttr = BOOLEAN_ATTR[lowercasedName]; <add> <add> if (isDefined(value)) { <add> // setter <add> <add> if (value === null || (value === false && isBooleanAttr)) { <ide> element.removeAttribute(name); <ide> } else { <del> element.setAttribute(name, value); <add> element.setAttribute(name, isBooleanAttr ? lowercasedName : value); <ide> } <ide> } else if (element.getAttribute) { <del> var ret = element.getAttribute(name); <del> // normalize non-existing attributes to undefined (as jQuery) <add> // getter <add> <add> ret = element.getAttribute(name); <add> <add> if (isBooleanAttr && ret !== null) { <add> ret = lowercasedName; <add> } <add> // Normalize non-existing attributes to undefined (as jQuery). <ide> return ret === null ? undefined : ret; <ide> } <ide> },
1
Ruby
Ruby
add more docs and tests to templates
64c7f7e39244129e9330afed82da8a7ffeb948b3
<ide><path>actionpack/lib/action_view/template.rb <ide> def initialize(source, identifier, handler, details) <ide> @compiled = false <ide> end <ide> <add> # Render a template. If the template was not compiled yet, it is done <add> # exactly before rendering. <add> # <add> # This method is instrumented as "!render_template.action_view". Notice that <add> # we use a bang in this instrumentation because you don't want to <add> # consume this in production. This is only slow if it's being listened to. <ide> def render(view, locals, &block) <del> # Notice that we use a bang in this instrumentation because you don't want to <del> # consume this in production. This is only slow if it's being listened to. <ide> ActiveSupport::Notifications.instrument("!render_template.action_view", :virtual_path => @virtual_path) do <ide> compile!(view) <ide> view.send(method_name, locals, &block) <ide> end <ide> rescue Exception => e <del> if e.is_a?(Template::Error) <del> e.sub_template_of(self) <del> raise e <del> else <del> raise Template::Error.new(refresh(view) || self, view.respond_to?(:assigns) ? view.assigns : {}, e) <del> end <add> handle_render_error(view, e) <ide> end <ide> <ide> def mime_type <ide> @mime_type ||= Mime::Type.lookup_by_extension(@formats.first.to_s) if @formats.first <ide> end <ide> <del> # TODO Remove me <del> def variable_name <del> @variable_name ||= @virtual_path[%r'_?(\w+)(\.\w+)*$', 1].to_sym <del> end <del> <del> # TODO Remove me <del> def counter_name <del> @counter_name ||= "#{variable_name}_counter".to_sym <add> # Receives a view object and return a template similar to self by using @virtual_path. <add> # <add> # This method is useful if you have a template object but it does not contain its source <add> # anymore since it was already compiled. In such cases, all you need to do is to call <add> # refresh passing in the view object. <add> # <add> # Notice this method raises an error if the template to be refreshed does not have a <add> # virtual path set (true just for inline templates). <add> def refresh(view) <add> raise "A template need to have a virtual path in order to be refreshed" unless @virtual_path <add> pieces = @virtual_path.split("/") <add> name = pieces.pop <add> partial = name.sub!(/^_/, "") <add> view.lookup_context.disable_cache do <add> view.find_template(name, pieces.join, partial || false, @locals) <add> end <ide> end <ide> <ide> def inspect <ide> def inspect <ide> end <ide> end <ide> <del> def compile!(view) <del> return if @compiled <add> protected <ide> <del> if view.is_a?(ActionView::CompiledTemplates) <del> mod = ActionView::CompiledTemplates <del> else <del> mod = view.singleton_class <del> end <add> # Compile a template. This method ensures a template is compiled <add> # just once and removes the source after it is compiled. <add> def compile!(view) #:nodoc: <add> return if @compiled <ide> <del> compile(view, mod) <add> if view.is_a?(ActionView::CompiledTemplates) <add> mod = ActionView::CompiledTemplates <add> else <add> mod = view.singleton_class <add> end <ide> <del> # Just discard the source if we have a virtual path. This <del> # means we can get the template back. <del> @source = nil if @virtual_path <del> @compiled = true <del> end <add> compile(view, mod) <ide> <del> protected <add> # Just discard the source if we have a virtual path. This <add> # means we can get the template back. <add> @source = nil if @virtual_path <add> @compiled = true <add> end <ide> <ide> # Among other things, this method is responsible for properly setting <ide> # the encoding of the source. Until this point, we assume that the <ide> def compile!(view) <ide> # encode the source into Encoding.default_internal. In general, <ide> # this means that templates will be UTF-8 inside of Rails, <ide> # regardless of the original source encoding. <del> def compile(view, mod) <add> def compile(view, mod) #:nodoc: <ide> method_name = self.method_name <del> locals_code = @locals.map { |key| "#{key} = local_assigns[:#{key}];" }.join <ide> <ide> if source.encoding_aware? <ide> # Look for # encoding: *. If we find one, we'll encode the <ide> def #{method_name}(local_assigns) <ide> end <ide> end <ide> <del> def refresh(view) <del> return unless @virtual_path <del> pieces = @virtual_path.split("/") <del> name = pieces.pop <del> partial = name.sub!(/^_/, "") <del> view.lookup_context.disable_cache do <del> view.find_template(name, pieces.join, partial || false, @locals) <add> def handle_render_error(view, e) #:nodoc: <add> if e.is_a?(Template::Error) <add> e.sub_template_of(self) <add> raise e <add> else <add> assigns = view.respond_to?(:assigns) ? view.assigns : {} <add> template = @virtual_path ? refresh(view) : self <add> raise Template::Error.new(template, assigns, e) <ide> end <ide> end <ide> <del> def method_name <add> def locals_code #:nodoc: <add> @locals.map { |key| "#{key} = local_assigns[:#{key}];" }.join <add> end <add> <add> def method_name #:nodoc: <ide> @method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".gsub('-', "_") <ide> end <ide> <del> def identifier_method_name <add> def identifier_method_name #:nodoc: <ide> inspect.gsub(/[^a-z_]/, '_') <ide> end <ide> end <ide><path>actionpack/test/template/template_test.rb <ide> def test_basic_template <ide> assert_equal "Hello", render <ide> end <ide> <add> def test_template_loses_its_source_after_rendering <add> @template = new_template <add> render <add> assert_nil @template.source <add> end <add> <add> def test_template_does_not_lose_its_source_after_rendering_if_it_does_not_have_a_virtual_path <add> @template = new_template("Hello", :virtual_path => nil) <add> render <add> assert_equal "Hello", @template.source <add> end <add> <ide> def test_locals <ide> @template = new_template("<%= my_local %>") <ide> @template.locals = [:my_local]
2
Go
Go
add stream flag to logs command
62263967b91ca841c43b980aec0ebc74ab2d838d
<ide><path>commands.go <ide> func (cli *DockerCli) CmdDiff(args ...string) error { <ide> <ide> func (cli *DockerCli) CmdLogs(args ...string) error { <ide> cmd := cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container") <add> stream := cmd.Bool("stream", false, "Stream output") <ide> if err := cmd.Parse(args); err != nil { <ide> return nil <ide> } <ide> func (cli *DockerCli) CmdLogs(args ...string) error { <ide> return err <ide> } <ide> <del> if err := cli.hijack("POST", "/containers/"+name+"/attach?logs=1&stdout=1&stderr=1", container.Config.Tty, nil, cli.out, cli.err, nil); err != nil { <add> v := url.Values{} <add> v.Set("logs", "1") <add> v.Set("stdout", "1") <add> v.Set("stderr", "1") <add> if *stream { <add> v.Set("stream", "1") <add> } <add> <add> if err := cli.hijack("POST", "/containers/"+name+"/attach?"+v.Encode(), container.Config.Tty, nil, cli.out, cli.err, nil); err != nil { <ide> return err <ide> } <ide> return nil
1
Ruby
Ruby
reduce some lasigns
ef4ffed660015772f67826e8aaa319febe84f271
<ide><path>activerecord/lib/active_record/associations/association_proxy.rb <ide> def association_scope <ide> scope = target_klass.unscoped <ide> scope = scope.create_with(creation_attributes) <ide> scope = scope.apply_finder_options(@reflection.options.slice(:conditions, :readonly, :include)) <del> scope = scope.where(construct_owner_conditions) <ide> scope = scope.select(select_value) if select_value = self.select_value <del> scope <add> scope.where(construct_owner_conditions) <ide> end <ide> <ide> def select_value
1
Python
Python
provide perclass iou
8de71c4b8b164a093e9f0972a9a45ffb887c5b44
<ide><path>official/vision/keras_cv/__init__.py <ide> # pylint: disable=wildcard-import <ide> from official.vision.keras_cv import layers <ide> from official.vision.keras_cv import losses <add>from official.vision.keras_cv import metrics <ide> from official.vision.keras_cv import ops <ide><path>official/vision/keras_cv/metrics/__init__.py <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Keras-CV metrics package definition.""" <add>from official.vision.keras_cv.metrics.iou import PerClassIoU <ide><path>official/vision/keras_cv/metrics/iou.py <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""IOU Metrics used for semantic segmentation models.""" <add> <add>import numpy as np <add>import tensorflow as tf <add> <add> <add>class PerClassIoU(tf.keras.metrics.Metric): <add> """Computes the per-class Intersection-Over-Union metric. <add> <add> Mean Intersection-Over-Union is a common evaluation metric for semantic image <add> segmentation, which first computes the IOU for each semantic class. <add> IOU is defined as follows: <add> IOU = true_positive / (true_positive + false_positive + false_negative). <add> The predictions are accumulated in a confusion matrix, weighted by <add> `sample_weight` and the metric is then calculated from it. <add> <add> If `sample_weight` is `None`, weights default to 1. <add> Use `sample_weight` of 0 to mask values. <add> <add> Example: <add> <add> >>> # cm = [[1, 1], <add> >>> # [1, 1]] <add> >>> # sum_row = [2, 2], sum_col = [2, 2], true_positives = [1, 1] <add> >>> # iou = true_positives / (sum_row + sum_col - true_positives)) <add> >>> # result = [(1 / (2 + 2 - 1), 1 / (2 + 2 - 1)] = 0.33 <add> >>> m = tf.keras.metrics.MeanIoU(num_classes=2) <add> >>> m.update_state([0, 0, 1, 1], [0, 1, 0, 1]) <add> >>> m.result().numpy() <add> [0.33333334, 0.33333334] <add> <add> """ <add> <add> def __init__(self, num_classes, name=None, dtype=None): <add> """Initializes `PerClassIoU`. <add> <add> Arguments: <add> num_classes: The possible number of labels the prediction task can have. <add> This value must be provided, since a confusion matrix of dimension = <add> [num_classes, num_classes] will be allocated. <add> name: (Optional) string name of the metric instance. <add> dtype: (Optional) data type of the metric result. <add> <add> """ <add> <add> super(PerClassIoU, self).__init__(name=name, dtype=dtype) <add> self.num_classes = num_classes <add> <add> # Variable to accumulate the predictions in the confusion matrix. <add> self.total_cm = self.add_weight( <add> 'total_confusion_matrix', <add> shape=(num_classes, num_classes), <add> initializer=tf.compat.v1.zeros_initializer) <add> <add> def update_state(self, y_true, y_pred, sample_weight=None): <add> """Accumulates the confusion matrix statistics. <add> <add> Args: <add> y_true: The ground truth values. <add> y_pred: The predicted values. <add> sample_weight: Optional weighting of each example. Defaults to 1. Can be a <add> `Tensor` whose rank is either 0, or the same rank as `y_true`, and must <add> be broadcastable to `y_true`. <add> <add> Returns: <add> IOU per class. <add> """ <add> <add> y_true = tf.cast(y_true, self._dtype) <add> y_pred = tf.cast(y_pred, self._dtype) <add> <add> # Flatten the input if its rank > 1. <add> if y_pred.shape.ndims > 1: <add> y_pred = tf.reshape(y_pred, [-1]) <add> <add> if y_true.shape.ndims > 1: <add> y_true = tf.reshape(y_true, [-1]) <add> <add> if sample_weight is not None: <add> sample_weight = tf.cast(sample_weight, self._dtype) <add> if sample_weight.shape.ndims > 1: <add> sample_weight = tf.reshape(sample_weight, [-1]) <add> <add> # Accumulate the prediction to current confusion matrix. <add> current_cm = tf.math.confusion_matrix( <add> y_true, <add> y_pred, <add> self.num_classes, <add> weights=sample_weight, <add> dtype=self._dtype) <add> return self.total_cm.assign_add(current_cm) <add> <add> def result(self): <add> """Compute the mean intersection-over-union via the confusion matrix.""" <add> sum_over_row = tf.cast( <add> tf.reduce_sum(self.total_cm, axis=0), dtype=self._dtype) <add> sum_over_col = tf.cast( <add> tf.reduce_sum(self.total_cm, axis=1), dtype=self._dtype) <add> true_positives = tf.cast( <add> tf.linalg.tensor_diag_part(self.total_cm), dtype=self._dtype) <add> <add> # sum_over_row + sum_over_col = <add> # 2 * true_positives + false_positives + false_negatives. <add> denominator = sum_over_row + sum_over_col - true_positives <add> <add> return tf.math.divide_no_nan(true_positives, denominator) <add> <add> def reset_states(self): <add> tf.keras.backend.set_value( <add> self.total_cm, np.zeros((self.num_classes, self.num_classes))) <add> <add> def get_config(self): <add> config = {'num_classes': self.num_classes} <add> base_config = super(PerClassIoU, self).get_config() <add> return dict(list(base_config.items()) + list(config.items())) <ide><path>official/vision/keras_cv/metrics/iou_test.py <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Tests for Keras metrics functions.""" <add> <add>import tensorflow as tf <add> <add>from official.vision.keras_cv.metrics import iou <add> <add> <add>class MeanIoUTest(tf.test.TestCase): <add> <add> def test_config(self): <add> m_obj = iou.PerClassIoU(num_classes=2, name='per_class_iou') <add> self.assertEqual(m_obj.name, 'per_class_iou') <add> self.assertEqual(m_obj.num_classes, 2) <add> <add> m_obj2 = iou.PerClassIoU.from_config(m_obj.get_config()) <add> self.assertEqual(m_obj2.name, 'per_class_iou') <add> self.assertEqual(m_obj2.num_classes, 2) <add> <add> def test_unweighted(self): <add> y_pred = [0, 1, 0, 1] <add> y_true = [0, 0, 1, 1] <add> <add> m_obj = iou.PerClassIoU(num_classes=2) <add> <add> result = m_obj(y_true, y_pred) <add> <add> # cm = [[1, 1], <add> # [1, 1]] <add> # sum_row = [2, 2], sum_col = [2, 2], true_positives = [1, 1] <add> # iou = true_positives / (sum_row + sum_col - true_positives)) <add> expected_result = [1 / (2 + 2 - 1), 1 / (2 + 2 - 1)] <add> self.assertAllClose(expected_result, result, atol=1e-3) <add> <add> def test_weighted(self): <add> y_pred = tf.constant([0, 1, 0, 1], dtype=tf.float32) <add> y_true = tf.constant([0, 0, 1, 1]) <add> sample_weight = tf.constant([0.2, 0.3, 0.4, 0.1]) <add> <add> m_obj = iou.PerClassIoU(num_classes=2) <add> <add> result = m_obj(y_true, y_pred, sample_weight=sample_weight) <add> <add> # cm = [[0.2, 0.3], <add> # [0.4, 0.1]] <add> # sum_row = [0.6, 0.4], sum_col = [0.5, 0.5], true_positives = [0.2, 0.1] <add> # iou = true_positives / (sum_row + sum_col - true_positives)) <add> expected_result = [0.2 / (0.6 + 0.5 - 0.2), 0.1 / (0.4 + 0.5 - 0.1)] <add> self.assertAllClose(expected_result, result, atol=1e-3) <add> <add> def test_multi_dim_input(self): <add> y_pred = tf.constant([[0, 1], [0, 1]], dtype=tf.float32) <add> y_true = tf.constant([[0, 0], [1, 1]]) <add> sample_weight = tf.constant([[0.2, 0.3], [0.4, 0.1]]) <add> <add> m_obj = iou.PerClassIoU(num_classes=2) <add> <add> result = m_obj(y_true, y_pred, sample_weight=sample_weight) <add> <add> # cm = [[0.2, 0.3], <add> # [0.4, 0.1]] <add> # sum_row = [0.6, 0.4], sum_col = [0.5, 0.5], true_positives = [0.2, 0.1] <add> # iou = true_positives / (sum_row + sum_col - true_positives)) <add> expected_result = [0.2 / (0.6 + 0.5 - 0.2), 0.1 / (0.4 + 0.5 - 0.1)] <add> self.assertAllClose(expected_result, result, atol=1e-3) <add> <add> def test_zero_valid_entries(self): <add> m_obj = iou.PerClassIoU(num_classes=2) <add> self.assertAllClose(m_obj.result(), [0, 0], atol=1e-3) <add> <add> def test_zero_and_non_zero_entries(self): <add> y_pred = tf.constant([1], dtype=tf.float32) <add> y_true = tf.constant([1]) <add> <add> m_obj = iou.PerClassIoU(num_classes=2) <add> result = m_obj(y_true, y_pred) <add> <add> # cm = [[0, 0], <add> # [0, 1]] <add> # sum_row = [0, 1], sum_col = [0, 1], true_positives = [0, 1] <add> # iou = true_positives / (sum_row + sum_col - true_positives)) <add> expected_result = [0, 1 / (1 + 1 - 1)] <add> self.assertAllClose(expected_result, result, atol=1e-3) <add> <add>if __name__ == '__main__': <add> tf.test.main()
4
Text
Text
tweak the contributing wording in readme
1c0b5dca5aa3ece735a78ea9bef601eaa1857d58
<ide><path>README.md <ide> npm i --save react <ide> <ide> ## Contributing <ide> <del>The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, check out our [contribution guide](https://facebook.github.io/react/contributing/how-to-contribute.html). <add>The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. Development of React happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take a part in improving React. <ide> <ide> ### [Code of Conduct](https://code.facebook.com/codeofconduct) <ide> <ide> Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) so that you can understand what actions will and will not be tolerated. <ide> <add>### Contributing Guide <add> <add>Read our [contributing guide](https://facebook.github.io/react/contributing/how-to-contribute.html) to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to React. <add> <ide> ### Good First Bug <ide> <ide> To help you get your feet wet and get you familiar with our contribution process, we have a list of [good first bugs](https://github.com/facebook/react/labels/good%20first%20bug) that contain bugs which are fairly easy to fix. This is a great place to get started.
1
Java
Java
add resolvers for uri, cookies, and request params
2794553d2e12a7c74f7654fc093bcfc93de1723d
<ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/CookieValueArgumentResolver.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.service.invoker; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.convert.ConversionService; <add>import org.springframework.web.bind.annotation.CookieValue; <add> <add> <add>/** <add> * {@link HttpServiceArgumentResolver} for {@link CookieValue @CookieValue} <add> * annotated arguments. <add> * <add> * <p>The argument may be: <add> * <ul> <add> * <li>{@code Map<String, ?>} or <add> * {@link org.springframework.util.MultiValueMap MultiValueMap&lt;String, ?&gt;} with <add> * multiple cookies and value(s). <add> * <li>{@code Collection} or an array of cookie values. <add> * <li>An individual cookie value. <add> * </ul> <add> * <add> * <p>Individual cookie values may be Strings or Objects to be converted to <add> * String values through the configured {@link ConversionService}. <add> * <add> * <p>If the value is required but {@code null}, {@link IllegalArgumentException} <add> * is raised. The value is not required if: <add> * <ul> <add> * <li>{@link CookieValue#required()} is set to {@code false} <add> * <li>{@link CookieValue#defaultValue()} provides a fallback value <add> * <li>The argument is declared as {@link java.util.Optional} <add> * </ul> <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>public class CookieValueArgumentResolver extends AbstractNamedValueArgumentResolver { <add> <add> <add> public CookieValueArgumentResolver(ConversionService conversionService) { <add> super(conversionService); <add> } <add> <add> <add> @Override <add> protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { <add> CookieValue annot = parameter.getParameterAnnotation(CookieValue.class); <add> return (annot == null ? null : <add> new NamedValueInfo(annot.name(), annot.required(), annot.defaultValue(), "cookie value", true)); <add> } <add> <add> @Override <add> protected void addRequestValue(String name, String value, HttpRequestValues.Builder requestValues) { <add> requestValues.addCookie(name, value); <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpRequestValues.java <ide> <ide> <ide> import java.net.URI; <add>import java.nio.charset.Charset; <add>import java.nio.charset.StandardCharsets; <ide> import java.util.Collections; <add>import java.util.HashMap; <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.function.Function; <ide> <ide> import org.reactivestreams.Publisher; <ide> <ide> import org.springframework.core.ParameterizedTypeReference; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.MediaType; <add>import org.springframework.http.codec.FormHttpMessageWriter; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <add>import org.springframework.web.util.UriComponentsBuilder; <add>import org.springframework.web.util.UriUtils; <ide> <ide> <ide> /** <ide> public final class HttpRequestValues { <ide> private final ParameterizedTypeReference<?> bodyElementType; <ide> <ide> <del> private HttpRequestValues(HttpMethod httpMethod, @Nullable URI uri, <del> @Nullable String uriTemplate, @Nullable Map<String, String> uriVariables, <del> @Nullable HttpHeaders headers, @Nullable MultiValueMap<String, String> cookies, <add> private HttpRequestValues(HttpMethod httpMethod, <add> @Nullable URI uri, @Nullable String uriTemplate, Map<String, String> uriVariables, <add> HttpHeaders headers, MultiValueMap<String, String> cookies, <ide> @Nullable Object bodyValue, <del> @Nullable Publisher<?> body, <del> @Nullable ParameterizedTypeReference<?> bodyElementType) { <add> @Nullable Publisher<?> body, @Nullable ParameterizedTypeReference<?> bodyElementType) { <ide> <del> Assert.isTrue(uri == null || uriTemplate == null, "Expected either URI or URI template, not both"); <add> Assert.isTrue(uri != null || uriTemplate != null, "Neither URI nor URI template"); <ide> <ide> this.httpMethod = httpMethod; <ide> this.uri = uri; <del> this.uriTemplate = (uri != null || uriTemplate != null ? uriTemplate : ""); <del> this.uriVariables = (uriVariables != null ? uriVariables : Collections.emptyMap()); <del> this.headers = (headers != null ? headers : HttpHeaders.EMPTY); <del> this.cookies = (cookies != null ? cookies : EMPTY_COOKIES_MAP); <add> this.uriTemplate = uriTemplate; <add> this.uriVariables = uriVariables; <add> this.headers = headers; <add> this.cookies = cookies; <ide> this.bodyValue = bodyValue; <ide> this.body = body; <ide> this.bodyElementType = bodyElementType; <ide> public static Builder builder(HttpMethod httpMethod) { <ide> */ <ide> public final static class Builder { <ide> <add> private static final Function<MultiValueMap<String, String>, byte[]> FORM_DATA_SERIALIZER = new FormDataSerializer(); <add> <ide> private HttpMethod httpMethod; <ide> <ide> @Nullable <ide> public final static class Builder { <ide> private String uriTemplate; <ide> <ide> @Nullable <del> private Map<String, String> uriVariables; <add> private Map<String, String> uriVars; <ide> <ide> @Nullable <ide> private HttpHeaders headers; <ide> <ide> @Nullable <ide> private MultiValueMap<String, String> cookies; <ide> <add> @Nullable <add> private MultiValueMap<String, String> requestParams; <add> <ide> @Nullable <ide> private Object bodyValue; <ide> <ide> public Builder setHttpMethod(HttpMethod httpMethod) { <ide> public Builder setUri(URI uri) { <ide> this.uri = uri; <ide> this.uriTemplate = null; <add> this.uriVars = null; <ide> return this; <ide> } <ide> <ide> public Builder setUriTemplate(String uriTemplate) { <ide> * {@link #setUri(URI) full URI}. <ide> */ <ide> public Builder setUriVariable(String name, String value) { <del> this.uriVariables = (this.uriVariables != null ? this.uriVariables : new LinkedHashMap<>()); <del> this.uriVariables.put(name, value); <add> this.uriVars = (this.uriVars != null ? this.uriVars : new LinkedHashMap<>()); <add> this.uriVars.put(name, value); <ide> this.uri = null; <ide> return this; <ide> } <ide> public Builder addCookie(String name, String... values) { <ide> return this; <ide> } <ide> <add> /** <add> * Add the given request parameter name and values. <add> * <p>When {@code "content-type"} is set to <add> * {@code "application/x-www-form-urlencoded"}, request parameters are <add> * encoded in the request body. Otherwise, they are added as URL query <add> * parameters. <add> */ <add> public Builder addRequestParameter(String name, String... values) { <add> this.requestParams = (this.requestParams != null ? this.requestParams : new LinkedMultiValueMap<>()); <add> for (String value : values) { <add> this.requestParams.add(name, value); <add> } <add> return this; <add> } <add> <ide> /** <ide> * Set the request body as a concrete value to be serialized. <ide> * <p>This is mutually exclusive with, and resets any previously set <ide> public <T, P extends Publisher<T>> void setBody(Publisher<P> body, Parameterized <ide> * Builder the {@link HttpRequestValues} instance. <ide> */ <ide> public HttpRequestValues build() { <add> <add> URI uri = this.uri; <add> String uriTemplate = (this.uriTemplate != null || uri != null ? this.uriTemplate : ""); <add> Map<String, String> uriVars = (this.uriVars != null ? new HashMap<>(this.uriVars) : Collections.emptyMap()); <add> <add> Object bodyValue = this.bodyValue; <add> <add> if (!CollectionUtils.isEmpty(this.requestParams)) { <add> <add> boolean isFormData = (this.headers != null && <add> MediaType.APPLICATION_FORM_URLENCODED.equals(this.headers.getContentType())); <add> <add> if (isFormData) { <add> Assert.isTrue(bodyValue == null && this.body == null, "Expected body or request params, not both"); <add> bodyValue = FORM_DATA_SERIALIZER.apply(this.requestParams); <add> } <add> else if (uri != null) { <add> uri = UriComponentsBuilder.fromUri(uri) <add> .queryParams(UriUtils.encodeQueryParams(this.requestParams)) <add> .build(true) <add> .toUri(); <add> } <add> else { <add> uriVars = (uriVars.isEmpty() ? new HashMap<>() : uriVars); <add> uriTemplate = appendQueryParams(uriTemplate, uriVars, this.requestParams); <add> } <add> } <add> <add> HttpHeaders headers = HttpHeaders.EMPTY; <add> if (this.headers != null) { <add> headers = new HttpHeaders(); <add> headers.putAll(this.headers); <add> } <add> <add> MultiValueMap<String, String> cookies = (this.cookies != null ? <add> new LinkedMultiValueMap<>(this.cookies) : EMPTY_COOKIES_MAP); <add> <ide> return new HttpRequestValues( <del> this.httpMethod, this.uri, this.uriTemplate, this.uriVariables, <del> this.headers, this.cookies, <del> this.bodyValue, this.body, this.bodyElementType); <add> this.httpMethod, uri, uriTemplate, uriVars, headers, cookies, bodyValue, <add> this.body, this.bodyElementType); <add> } <add> <add> private String appendQueryParams( <add> String uriTemplate, Map<String, String> uriVars, MultiValueMap<String, String> requestParams) { <add> <add> UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uriTemplate); <add> int i = 0; <add> for (Map.Entry<String, List<String>> entry : requestParams.entrySet()) { <add> String nameVar = "queryParam" + i; <add> uriVars.put(nameVar, entry.getKey()); <add> for (int j = 0; j < entry.getValue().size(); j++) { <add> String valueVar = nameVar + "[" + j + "]"; <add> uriVars.put(valueVar, entry.getValue().get(j)); <add> uriComponentsBuilder.queryParam("{" + nameVar + "}", "{" + valueVar + "}"); <add> } <add> i++; <add> } <add> return uriComponentsBuilder.build().toUriString(); <add> } <add> <add> } <add> <add> <add> private static class FormDataSerializer <add> extends FormHttpMessageWriter implements Function<MultiValueMap<String, String>, byte[]> { <add> <add> @Override <add> public byte[] apply(MultiValueMap<String, String> requestParams) { <add> Charset charset = StandardCharsets.UTF_8; <add> return serializeForm(requestParams, charset).getBytes(charset); <ide> } <ide> <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpServiceProxyFactory.java <ide> private List<HttpServiceArgumentResolver> initArgumentResolvers(ConversionServic <ide> List<HttpServiceArgumentResolver> resolvers = new ArrayList<>(this.customResolvers); <ide> resolvers.add(new RequestHeaderArgumentResolver(conversionService)); <ide> resolvers.add(new PathVariableArgumentResolver(conversionService)); <add> resolvers.add(new CookieValueArgumentResolver(conversionService)); <add> resolvers.add(new RequestParamArgumentResolver(conversionService)); <add> resolvers.add(new HttpUrlArgumentResolver()); <ide> resolvers.add(new HttpMethodArgumentResolver()); <ide> return resolvers; <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpUrlArgumentResolver.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.service.invoker; <add> <add>import java.net.URI; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.http.HttpMethod; <add>import org.springframework.lang.Nullable; <add> <add> <add>/** <add> * {@link HttpServiceArgumentResolver} that resolves the target <add> * request's URL from an {@link HttpMethod} argument. <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>public class HttpUrlArgumentResolver implements HttpServiceArgumentResolver { <add> <add> @Override <add> public boolean resolve( <add> @Nullable Object argument, MethodParameter parameter, HttpRequestValues.Builder requestValues) { <add> <add> if (argument instanceof URI uri) { <add> requestValues.setUri(uri); <add> return true; <add> } <add> <add> return false; <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/RequestHeaderArgumentResolver.java <ide> * <ide> * <p>The argument may be: <ide> * <ul> <del> * <li>{@code Map} or {@link org.springframework.util.MultiValueMap} with <del> * multiple headers and value(s). <add> * <li>{@code Map<String, ?>} or <add> * {@link org.springframework.util.MultiValueMap MultiValueMap&lt;String, ?&gt;} <add> * with multiple headers and value(s). <ide> * <li>{@code Collection} or an array of header values. <ide> * <li>An individual header value. <ide> * </ul> <ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/RequestParamArgumentResolver.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.service.invoker; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.convert.ConversionService; <add>import org.springframework.web.bind.annotation.RequestParam; <add> <add> <add>/** <add> * {@link HttpServiceArgumentResolver} for {@link RequestParam @RequestParam} <add> * annotated arguments. <add> * <add> * <p>When {@code "content-type"} is set to <add> * {@code "application/x-www-form-urlencoded"}, request parameters are encoded <add> * in the request body. Otherwise, they are added as URL query parameters. <add> * <add> * <p>The argument may be: <add> * <ul> <add> * <li>{@code Map<String, ?>} or <add> * {@link org.springframework.util.MultiValueMap MultiValueMap&lt;String, ?&gt;} with <add> * multiple request parameter and value(s). <add> * <li>{@code Collection} or an array of request parameters. <add> * <li>An individual request parameter. <add> * </ul> <add> * <add> * <p>Individual request parameters may be Strings or Objects to be converted to <add> * String values through the configured {@link ConversionService}. <add> * <add> * <p>If the value is required but {@code null}, {@link IllegalArgumentException} <add> * is raised. The value is not required if: <add> * <ul> <add> * <li>{@link RequestParam#required()} is set to {@code false} <add> * <li>{@link RequestParam#defaultValue()} provides a fallback value <add> * <li>The argument is declared as {@link java.util.Optional} <add> * </ul> <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>public class RequestParamArgumentResolver extends AbstractNamedValueArgumentResolver { <add> <add> <add> public RequestParamArgumentResolver(ConversionService conversionService) { <add> super(conversionService); <add> } <add> <add> <add> @Override <add> protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { <add> RequestParam annot = parameter.getParameterAnnotation(RequestParam.class); <add> return (annot == null ? null : <add> new NamedValueInfo(annot.name(), annot.required(), annot.defaultValue(), "request parameter", true)); <add> } <add> <add> @Override <add> protected void addRequestValue(String name, String value, HttpRequestValues.Builder requestValues) { <add> requestValues.addRequestParameter(name, value); <add> } <add> <add>} <ide><path>spring-web/src/test/java/org/springframework/web/service/invoker/CookieValueArgumentResolverTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.service.invoker; <add> <add>import java.util.List; <add>import java.util.Map; <add>import java.util.Optional; <add> <add>import org.apache.groovy.util.Maps; <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.lang.Nullable; <add>import org.springframework.util.ObjectUtils; <add>import org.springframework.web.bind.annotation.CookieValue; <add>import org.springframework.web.service.annotation.GetExchange; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add> <add> <add>/** <add> * Unit tests for {@link RequestHeaderArgumentResolver}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>class CookieValueArgumentResolverTests { <add> <add> private final TestHttpClientAdapter clientAdapter = new TestHttpClientAdapter(); <add> <add> private final Service service = this.clientAdapter.createService(Service.class); <add> <add> <add> @Test <add> void stringCookie() { <add> this.service.executeString("test"); <add> assertCookie("cookie", "test"); <add> } <add> <add> @Test <add> void objectCookie() { <add> this.service.execute(Boolean.TRUE); <add> assertCookie("cookie", "true"); <add> } <add> <add> @Test <add> void listCookie() { <add> this.service.executeList(List.of("test1", Boolean.TRUE, "test3")); <add> assertCookie("multiValueCookie", "test1", "true", "test3"); <add> } <add> <add> @Test <add> void arrayCookie() { <add> this.service.executeArray("test1", Boolean.FALSE, "test3"); <add> assertCookie("multiValueCookie", "test1", "false", "test3"); <add> } <add> <add> @Test <add> void namedCookie() { <add> this.service.executeNamed("test"); <add> assertCookie("cookieRenamed", "test"); <add> } <add> <add> @SuppressWarnings("ConstantConditions") <add> @Test <add> void nullCookieRequired() { <add> assertThatIllegalArgumentException().isThrownBy(() -> this.service.executeString(null)); <add> } <add> <add> @Test <add> void nullCookieNotRequired() { <add> this.service.executeNotRequired(null); <add> assertCookie("cookie"); <add> } <add> <add> @Test <add> void nullCookieWithDefaultValue() { <add> this.service.executeWithDefaultValue(null); <add> assertCookie("cookie", "default"); <add> } <add> <add> @Test <add> void optionalStringCookie() { <add> this.service.executeOptional(Optional.of("test")); <add> assertCookie("cookie", "test"); <add> } <add> <add> @Test <add> void optionalObjectCookie() { <add> this.service.executeOptional(Optional.of(Boolean.TRUE)); <add> assertCookie("cookie", "true"); <add> } <add> <add> @Test <add> void optionalEmpty() { <add> this.service.executeOptional(Optional.empty()); <add> assertCookie("cookie"); <add> } <add> <add> @Test <add> void optionalEmpthyWithDefaultValue() { <add> this.service.executeOptionalWithDefaultValue(Optional.empty()); <add> assertCookie("cookie", "default"); <add> } <add> <add> @Test <add> void mapOfCookies() { <add> this.service.executeMap(Maps.of("cookie1", "true", "cookie2", "false")); <add> assertCookie("cookie1", "true"); <add> assertCookie("cookie2", "false"); <add> } <add> <add> @Test <add> void mapOfCookiesIsNull() { <add> assertThatIllegalArgumentException().isThrownBy(() -> this.service.executeMap(null)); <add> } <add> <add> @Test <add> void mapOfCookiesHasOptionalValue() { <add> this.service.executeMapWithOptionalValue(Map.of("cookie", Optional.of("test"))); <add> assertCookie("cookie", "test"); <add> } <add> <add> private void assertCookie(String key, String... values) { <add> List<String> actualValues = this.clientAdapter.getRequestValues().getCookies().get(key); <add> if (ObjectUtils.isEmpty(values)) { <add> assertThat(actualValues).isNull(); <add> } <add> else { <add> assertThat(actualValues).containsOnly(values); <add> } <add> } <add> <add> <add> @SuppressWarnings("OptionalUsedAsFieldOrParameterType") <add> private interface Service { <add> <add> @GetExchange <add> void executeString(@CookieValue String cookie); <add> <add> @GetExchange <add> void execute(@CookieValue Object cookie); <add> <add> @GetExchange <add> void executeList(@CookieValue List<Object> multiValueCookie); <add> <add> @GetExchange <add> void executeArray(@CookieValue Object... multiValueCookie); <add> <add> @GetExchange <add> void executeNamed(@CookieValue(name = "cookieRenamed") String cookie); <add> <add> @GetExchange <add> void executeNotRequired(@Nullable @CookieValue(required = false) String cookie); <add> <add> @GetExchange <add> void executeWithDefaultValue(@Nullable @CookieValue(defaultValue = "default") String cookie); <add> <add> @GetExchange <add> void executeOptional(@CookieValue Optional<Object> cookie); <add> <add> @GetExchange <add> void executeOptionalWithDefaultValue(@CookieValue(defaultValue = "default") Optional<Object> cookie); <add> <add> @GetExchange <add> void executeMap(@Nullable @CookieValue Map<String, String> cookie); <add> <add> @GetExchange <add> void executeMapWithOptionalValue(@CookieValue Map<String, Optional<String>> cookies); <add> <add> } <add> <add>} <ide><path>spring-web/src/test/java/org/springframework/web/service/invoker/HttpUrlArgumentResolverTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.service.invoker; <add> <add>import java.net.URI; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.web.service.annotation.GetExchange; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add> <add> <add>/** <add> * Unit tests for {@link HttpUrlArgumentResolver}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class HttpUrlArgumentResolverTests { <add> <add> private final TestHttpClientAdapter clientAdapter = new TestHttpClientAdapter(); <add> <add> private final Service service = this.clientAdapter.createService(Service.class); <add> <add> <add> @Test <add> void url() { <add> URI dynamicUrl = URI.create("dynamic-path"); <add> this.service.execute(dynamicUrl); <add> <add> assertThat(getRequestValues().getUri()).isEqualTo(dynamicUrl); <add> assertThat(getRequestValues().getUriTemplate()).isNull(); <add> } <add> <add> private HttpRequestValues getRequestValues() { <add> return this.clientAdapter.getRequestValues(); <add> } <add> <add> <add> private interface Service { <add> <add> @GetExchange("/path") <add> void execute(URI uri); <add> <add> } <add> <add>} <ide><path>spring-web/src/test/java/org/springframework/web/service/invoker/RequestParamArgumentResolverTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.service.invoker; <add> <add>import java.net.URI; <add>import java.util.Arrays; <add>import java.util.List; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.web.bind.annotation.RequestParam; <add>import org.springframework.web.service.annotation.GetExchange; <add>import org.springframework.web.service.annotation.PostExchange; <add>import org.springframework.web.util.UriComponentsBuilder; <add> <add>import static java.nio.charset.StandardCharsets.UTF_8; <add>import static org.assertj.core.api.Assertions.assertThat; <add> <add> <add>/** <add> * Unit tests for {@link RequestParamArgumentResolver}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class RequestParamArgumentResolverTests { <add> <add> private final TestHttpClientAdapter clientAdapter = new TestHttpClientAdapter(); <add> <add> private final Service service = this.clientAdapter.createService(Service.class); <add> <add> <add> @Test <add> void formData() { <add> this.service.postForm("value 1", "value 2"); <add> <add> Object body = this.clientAdapter.getRequestValues().getBodyValue(); <add> assertThat(body).isNotNull().isInstanceOf(byte[].class); <add> assertThat(new String((byte[]) body, UTF_8)).isEqualTo("param1=value+1&param2=value+2"); <add> } <add> <add> @Test <add> void uriTemplate() { <add> this.service.search("1st value", Arrays.asList("2nd value A", "2nd value B")); <add> <add> HttpRequestValues requestValues = this.clientAdapter.getRequestValues(); <add> <add> assertThat(requestValues.getUriTemplate()) <add> .isEqualTo("/path?" + <add> "{queryParam0}={queryParam0[0]}&" + <add> "{queryParam1}={queryParam1[0]}&" + <add> "{queryParam1}={queryParam1[1]}"); <add> <add> assertThat(requestValues.getUriVariables()) <add> .containsOnlyKeys("queryParam0", "queryParam1", "queryParam0[0]", "queryParam1[0]", "queryParam1[1]") <add> .containsEntry("queryParam0", "param1") <add> .containsEntry("queryParam1", "param2") <add> .containsEntry("queryParam0[0]", "1st value") <add> .containsEntry("queryParam1[0]", "2nd value A") <add> .containsEntry("queryParam1[1]", "2nd value B"); <add> <add> URI uri = UriComponentsBuilder.fromUriString(requestValues.getUriTemplate()) <add> .encode().build(requestValues.getUriVariables()); <add> <add> assertThat(uri.toString()) <add> .isEqualTo("/path?param1=1st%20value&param2=2nd%20value%20A&param2=2nd%20value%20B"); <add> } <add> <add> @Test <add> void uri() { <add> URI baseUrl = URI.create("http://localhost:8080/path"); <add> this.service.searchWithDynamicUri(baseUrl, "1st value", Arrays.asList("2nd value A", "2nd value B")); <add> <add> assertThat(this.clientAdapter.getRequestValues().getUri().toString()) <add> .isEqualTo(baseUrl + "?param1=1st%20value&param2=2nd%20value%20A&param2=2nd%20value%20B"); <add> } <add> <add> <add> private interface Service { <add> <add> @PostExchange(contentType = "application/x-www-form-urlencoded") <add> void postForm(@RequestParam String param1, @RequestParam String param2); <add> <add> @GetExchange("/path") <add> void search(@RequestParam String param1, @RequestParam List<String> param2); <add> <add> @GetExchange <add> void searchWithDynamicUri(URI uri, @RequestParam String param1, @RequestParam List<String> param2); <add> } <add> <add>}
9
Python
Python
remove unused variable 'd'
002510f19cee0fa9ee9bcb8332a957b6692ae560
<ide><path>glances/attribute.py <ide> def history_json(self, nb=0): <ide> def history_mean(self, nb=5): <ide> """Return the mean on the <nb> values in the history. <ide> """ <del> d, v = zip(*self._history) <add> _, v = zip(*self._history) <ide> return sum(v[-nb:]) / float(v[-1] - v[-nb])
1
Text
Text
remove the restriction on multi-user prs
4c282b979b717a28dd7699ad5b124d82b6a99a29
<ide><path>CONTRIBUTING.md <ide> committing your changes. Most editors have plug-ins that do this automatically. <ide> Pull requests descriptions should be as clear as possible and include a <ide> reference to all the issues that they address. <ide> <del>Pull requests must not contain commits from other users or branches. <del> <ide> Commit messages must start with a capitalized and short summary (max. 50 <ide> chars) written in the imperative, followed by an optional, more detailed <ide> explanatory text which is separated from the summary by an empty line. <ide> sure to post a comment after pushing. The new commits will show up in the pull <ide> request automatically, but the reviewers will not be notified unless you <ide> comment. <ide> <add>Pull requests must be cleanly rebased ontop of master without multiple branches <add>mixed into the PR. <add> <add>**Git tip**: If your PR no longer merges cleanly, use `rebase master` in your <add>feature branch to update your pull request rather than `merge master`. <add> <ide> Before the pull request is merged, make sure that you squash your commits into <ide> logical units of work using `git rebase -i` and `git push -f`. After every <ide> commit the test suite should be passing. Include documentation changes in the
1
Javascript
Javascript
add missing module declaration
9955aaf6be4ca742801ae69893ef1b7e5c4302ab
<ide><path>flow-github/metro.js <ide> declare module 'metro/src/Server' { <ide> declare module 'metro/src/ModuleGraph/worker/collectDependencies' { <ide> declare module.exports: any; <ide> } <add> <add>declare module 'metro/src/JSTransformer/worker' { <add> declare module.exports: any; <add>}
1
Javascript
Javascript
use hrtime in throughput benchmark
e2bcff9aa75e51b9ba071330fe712180abed03e0
<ide><path>benchmark/throughput-child.js <ide> var net = require('net'); <ide> var received = 0; <del>var start = new Date(); <add>var start = process.hrtime(); <ide> var socket = net.connect(8000); <ide> <ide> socket.on('data', function(d) { <ide> var interval = setInterval(function() { <ide> process.exit(0); <ide> } else { <ide> // Otherwise print some stats. <del> var now = new Date(); <add> var elapsed = process.hrtime(start); <add> var sec = elapsed[0] + elapsed[1]/1E9; <ide> var gigabytes = received / (1024 * 1024 * 1024); <ide> var gigabits = gigabytes * 8.0; <del> var millisec = now - start; <del> var sec = millisec / 1000; <ide> console.log((gigabits / sec) + " gbit/sec") <ide> } <ide> }, 1000);
1
Text
Text
update changelog for v15
85372964e50ffe76701377278ba1ac1c6582db4a
<ide><path>CHANGELOG.md <add>## 15.0.0 (April 7, 2016) <add> <add>### Major changes <add> <add>- **Initial render now uses `document.createElement` instead of generating HTML.** Previously we would generate a large string of HTML and then set `node.innerHTML`. At the time, this was decided to be faster than using `document.createElement` for the majority of cases and browsers that we supported. Browsers have continued to improve and so overwhelmingly this is no longer true. By using `createElement` we can make other parts of React faster. (<small>)[@spicyj](https://github.com/spicyj) in [#5205](https://github.com/facebook/react/pull/5205)) <add>- **`data-reactid` is no longer on every node.** As a result of using `document.createElement`, we can prime the node cache as we create DOM nodes, allowing us to skip a potential lookup (which used the `data-reactid` attribute). Root nodes will have a `data-reactroot` attribute and server generated markup will still contain `data-reactid`. (<small>)[@spicyj](https://github.com/spicyj) in [#5205](https://github.com/facebook/react/pull/5205)) <add>- **No more extra `<span>`s.** ReactDOM will now render plain text nodes interspersed with comment nodes that are used for demarcation. This gives us the same ability to update individual pieces of text, without creating extra nested nodes. If you were targeting these `<span>`s in your CSS, you will need to adjust accordingly. You can always render them explicitly in your components. ([@mwiencek](https://github.com/mwiencek) in [#5753](https://github.com/facebook/react/pull/5753)) <add>- **Rendering `null` now uses comment nodes.** Previously `null` would render to `<noscript>` elements. We now use comment nodes. This may cause issues if making use of `:nth-child` CSS selectors. While we consider this rendering behavior an implementation detail of React, it's worth noting the potential problem. ()[@spicyj](https://github.com/spicyj) in [#5451](https://github.com/facebook/react/pull/5451)) <add>- **Functional components can now return `null`.** We added support for [defining stateless components as functions](/react/blog/2015/09/10/react-v0.14-rc1.html#stateless-function-components) in React 0.14. However, React 0.14 still allowed you to define a class component without extending `React.Component` or using `React.createClass()`, so [we couldn’t reliably tell if your component is a function or a class](https://github.com/facebook/react/issues/5355), and did not allow returning `null` from it. This issue is solved in React 15, and you can now return `null` from any component, whether it is a class or a function. ([@jimfb](https://github.com/jimfb) in [#5884](https://github.com/facebook/react/pull/5884)) <add>- **Improved SVG support.** All SVG tags are now fully supported. (Uncommon SVG tags are not present on the `React.DOM` element helper, but JSX and `React.createElement` work on all tag names.) All SVG attributes that are implemented by the browsers should be supported too. If you find any attributes that we have missed, please [let us know in this issue](https://github.com/facebook/react/issues/1657). ([@zpao](https://github.com/zpao) in [#6243](https://github.com/facebook/react/pull/6243)) <add> <add>### Breaking changes <add> <add>- **No more extra `<span>`s.** <add>- **`React.cloneElement()` now resolves `defaultProps`.** We fixed a bug in `React.cloneElement()` that some components may rely on. If some of the `props` received by `cloneElement()` are `undefined`, it used to return an element with `undefined` values for those props. We’re changing it to be consistent with `createElement()`. Now any `undefined` props passed to `cloneElement()` are resolved to the corresponding component’s `defaultProps`. ([@truongduy134](https://github.com/truongduy134) in [#5997](https://github.com/facebook/react/pull/5997)) <add>- **`ReactPerf.getLastMeasurements()` is opaque.** This change won’t affect applications but may break some third-party tools. We are [revamping `ReactPerf` implementation](https://github.com/facebook/react/pull/6046) and plan to release it during the 15.x cycle. The internal performance measurement format is subject to change so, for the time being, we consider the return value of `ReactPerf.getLastMeasurements()` an opaque data structure that should not be relied upon. ([@gaearon](https://github.com/gaearon) in [#6286](https://github.com/facebook/react/pull/6286)) <add> <add>#### Removed deprecations <add> <add>These deprecations were introduced nine months ago in v0.14 with a warning and are removed: <add> <add>- Deprecated APIs are removed from the `React` top-level export: `findDOMNode`, `render`, `renderToString`, `renderToStaticMarkup`, and `unmountComponentAtNode`. As a reminder, they are now available on `ReactDOM` and `ReactDOMServer`. ([@jimfb](https://github.com/jimfb) in [#5832](https://github.com/facebook/react/pull/5832)) <add>- Deprecated addons are removed: `batchedUpdates` and `cloneWithProps`. ([@jimfb](https://github.com/jimfb) in [#5859](https://github.com/facebook/react/pull/5859), [@zpao](https://github.com/zpao) in [#6016](https://github.com/facebook/react/pull/6016)) <add>- Deprecated component instance methods are removed: `setProps`, `replaceProps`, and `getDOMNode`. ([@jimfb](https://github.com/jimfb) in [#5570](https://github.com/facebook/react/pull/5570)) <add>- Deprecated CommonJS `react/addons` entry point is removed. As a reminder, you should use separate `react-addons-*` packages instead. This only applies if you use the CommonJS builds. ([@gaearon](https://github.com/gaearon) in [#6285](https://github.com/facebook/react/pull/6285)) <add>- Passing `children` to void elements like `<input>` was deprecated, and now throws an error. ([@jonhester](https://github.com/jonhester) in [#3372](https://github.com/facebook/react/pull/3372)) <add>- React-specific properties on DOM `refs` (e.g. `this.refs.div.props`) were deprecated, and are removed now. ([@jimfb](https://github.com/jimfb) in [#5495](https://github.com/facebook/react/pull/5495)) <add> <add>### New deprecations, introduced with a warning <add> <add>Each of these changes will continue to work as before with a new warning until the release of React 16 so you can upgrade your code gradually. <add> <add>- `LinkedStateMixin` and `valueLink` are now deprecated due to very low popularity. If you need this, you can use a wrapper component that implements the same behavior: [react-linked-input](https://www.npmjs.com/package/react-linked-input). ([@jimfb](https://github.com/jimfb) in [#6127](https://github.com/facebook/react/pull/6127)) <add>- Future versions of React will treat `<input value={null}>` as a request to clear the input. However, React 0.14 has been ignoring `value={null}`. React 15 warns you on a `null` input value and offers you to clarify your intention. To fix the warning, you may explicitly pass an empty string to clear a controlled input, or pass `undefined` to make the input uncontrolled. ([@antoaravinth](https://github.com/antoaravinth) in [#5048](https://github.com/facebook/react/pull/5048)) <add>- `ReactPerf.printDOM()` was renamed to `ReactPerf.printOperations()`, and `ReactPerf.getMeasurementsSummaryMap()` was renamed to `ReactPerf.getWasted()`. ([@gaearon](https://github.com/gaearon) in [#6287](https://github.com/facebook/react/pull/6287)) <add> <add>### New helpful warnings <add> <add>- If you use a minified copy of the _development_ build, React DOM kindly encourages you to use the faster production build instead. ([@spicyj](https://github.com/spicyj) in [#5083](https://github.com/facebook/react/pull/5083)) <add>- React DOM: When specifying a unit-less CSS value as a string, a future version will not add `px` automatically. This version now warns in this case (ex: writing `style={{'{{'}}width: '300'}}`. Unitless *number* values like `width: 300` are unchanged. ([@pluma](https://github.com/pluma) in [#5140](https://github.com/facebook/react/pull/5140)) <add>- Synthetic Events will now warn when setting and accessing properties (which will not get cleared appropriately), as well as warn on access after an event has been returned to the pool. ([@kentcdodds](https://github.com/kentcdodds) in [#5940](https://github.com/facebook/react/pull/5940) and [@koba04](https://github.com/koba04) in [#5947](https://github.com/facebook/react/pull/5947)) <add>- Elements will now warn when attempting to read `ref` and `key` from the props. ([@prometheansacrifice](https://github.com/prometheansacrifice) in [#5744](https://github.com/facebook/react/pull/5744)) <add>- React will now warn if you pass a different `props` object to `super()` in the constructor. ([@prometheansacrifice](https://github.com/prometheansacrifice) in [#5346](https://github.com/facebook/react/pull/5346)) <add>- React will now warn if you call `setState()` inside `getChildContext()`. ([@raineroviir](https://github.com/raineroviir) in [#6121](https://github.com/facebook/react/pull/6121)) <add>- React DOM now attempts to warn for mistyped event handlers on DOM elements, such as `onclick` which should be `onClick`. ([@ali](https://github.com/ali) in [#5361](https://github.com/facebook/react/pull/5361)) <add>- React DOM now warns about `NaN` values in `style`. ([@jontewks](https://github.com/jontewks) in [#5811](https://github.com/facebook/react/pull/5811)) <add>- React DOM now warns if you specify both `value` and `defaultValue` for an input. ([@mgmcdermott](https://github.com/mgmcdermott) in [#5823](https://github.com/facebook/react/pull/5823)) <add>- React DOM now warns if an input switches between being controlled and uncontrolled. ([@TheBlasfem](https://github.com/TheBlasfem) in [#5864](https://github.com/facebook/react/pull/5864)) <add>- React DOM now warns if you specify `onFocusIn` or `onFocusOut` handlers as they are unnecessary in React. ([@jontewks](https://github.com/jontewks) in [#6296](https://github.com/facebook/react/pull/6296)) <add>- React now prints a descriptive error message when you pass an invalid callback as the last argument to `ReactDOM.render()`, `this.setState()`, or `this.forceUpdate()`. ([@conorhastings](https://github.com/conorhastings) in [#5193](https://github.com/facebook/react/pull/5193) and [@gaearon](https://github.com/gaearon) in [#6310](https://github.com/facebook/react/pull/6310)) <add>- Add-Ons: `TestUtils.Simulate()` now prints a helpful message if you attempt to use it with shallow rendering. ([@conorhastings](https://github.com/conorhastings) in [#5358](https://github.com/facebook/react/pull/5358)) <add>- PropTypes: `arrayOf()` and `objectOf()` provide better error messages for invalid arguments. ([@chicoxyzzy](https://github.com/chicoxyzzy) in [#5390](https://github.com/facebook/react/pull/5390)) <add> <add>### Notable bug fixes <add> <add>- Fixed multiple small memory leaks. ([@spicyj](https://github.com/spicyj) in [#4983](https://github.com/facebook/react/pull/4983) and [@victor-homyakov](https://github.com/victor-homyakov) in [#6309](https://github.com/facebook/react/pull/6309)) <add>- Input events are handled more reliably in IE 10 and IE 11; spurious events no longer fire when using a placeholder. ([@jquense](https://github.com/jquense) in [#4051](https://github.com/facebook/react/pull/4051)) <add>- The `componentWillReceiveProps()` lifecycle method is now consistently called when `context` changes. ([@milesj](https://github.com/milesj) in [#5787](https://github.com/facebook/react/pull/5787)) <add>- `React.cloneElement()` doesn’t append slash to an existing `key` when used inside `React.Children.map()`. ([@ianobermiller](https://github.com/ianobermiller) in [#5892](https://github.com/facebook/react/pull/5892)) <add>- React DOM now supports the `cite` and `profile` HTML attributes. ([@AprilArcus](https://github.com/AprilArcus) in [#6094](https://github.com/facebook/react/pull/6094) and [@saiichihashimoto](https://github.com/saiichihashimoto) in [#6032](https://github.com/facebook/react/pull/6032)) <add>- React DOM now supports `cssFloat`, `gridRow` and `gridColumn` CSS properties. ([@stevenvachon](https://github.com/stevenvachon) in [#6133](https://github.com/facebook/react/pull/6133) and [@mnordick](https://github.com/mnordick) in [#4779](https://github.com/facebook/react/pull/4779)) <add>- React DOM now correctly handles `borderImageOutset`, `borderImageWidth`, `borderImageSlice`, `floodOpacity`, `strokeDasharray`, and `strokeMiterlimit` as unitless CSS properties. ([@rofrischmann](https://github.com/rofrischmann) in [#6210](https://github.com/facebook/react/pull/6210) and [#6270](https://github.com/facebook/react/pull/6270)) <add>- React DOM now supports the `onAnimationStart`, `onAnimationEnd`, `onAnimationIteration`, `onTransitionEnd`, and `onInvalid` events. Support for `onLoad` has been added to `object` elements. ([@tomduncalf](https://github.com/tomduncalf) in [#5187](https://github.com/facebook/react/pull/5187), [@milesj](https://github.com/milesj) in [#6005](https://github.com/facebook/react/pull/6005), and [@ara4n](https://github.com/ara4n) in [#5781](https://github.com/facebook/react/pull/5781)) <add>- React DOM now defaults to using DOM attributes instead of properties, which fixes a few edge case bugs. Additionally the nullification of values (ex: `href={null}`) now results in the forceful removal, no longer trying to set to the default value used by browsers in the absence of a value. ([@syranide](https://github.com/syranide) in [#1510](https://github.com/facebook/react/pull/1510)) <add>- React DOM does not mistakingly coerce `children` to strings for Web Components. ([@jimfb](https://github.com/jimfb) in [#5093](https://github.com/facebook/react/pull/5093)) <add>- React DOM now correctly normalizes SVG `<use>` events. ([@edmellum](https://github.com/edmellum) in [#5720](https://github.com/facebook/react/pull/5720)) <add>- React DOM does not throw if a `<select>` is unmounted while its `onChange` handler is executing. ([@sambev](https://github.com/sambev) in [#6028](https://github.com/facebook/react/pull/6028)) <add>- React DOM does not throw in Windows 8 apps. ([@Andrew8xx8](https://github.com/Andrew8xx8) in [#6063](https://github.com/facebook/react/pull/6063)) <add>- React DOM does not throw when asynchronously unmounting a child with a `ref`. ([@yiminghe](https://github.com/yiminghe) in [#6095](https://github.com/facebook/react/pull/6095)) <add>- React DOM no longer forces synchronous layout because of scroll position tracking. ([@syranide](https://github.com/syranide) in [#2271](https://github.com/facebook/react/pull/2271)) <add>- `Object.is` is used in a number of places to compare values, which leads to fewer false positives, especially involving `NaN`. In particular, this affects the `shallowCompare` add-on. ([@chicoxyzzy](https://github.com/chicoxyzzy) in [#6132](https://github.com/facebook/react/pull/6132)) <add>- Add-Ons: ReactPerf no longer instruments adding or removing an event listener because they don’t really touch the DOM due to event delegation. ([@antoaravinth](https://github.com/antoaravinth) in [#5209](https://github.com/facebook/react/pull/5209)) <add> <add>### Other improvements <add> <add>- React now uses `loose-envify` instead of `envify` so it installs less transitive dependencies. ([@qerub](https://github.com/qerub) in [#6303](https://github.com/facebook/react/pull/6303)) <add>- Shallow renderer now exposes `getMountedInstance()`. ([@glenjamin](https://github.com/glenjamin) in [#4918](https://github.com/facebook/react/pull/4918)) <add>- Shallow renderer now returns the rendered output from `render()`. ([@simonewebdesign](https://github.com/simonewebdesign) in [#5411](https://github.com/facebook/react/pull/5411)) <add>- React no longer depends on ES5 *shams* for `Object.create` and `Object.freeze` in older environments. It still, however, requires ES5 *shims* in those environments. ([@dgreensp](https://github.com/dgreensp) in [#4959](https://github.com/facebook/react/pull/4959)) <add>- React DOM now allows `data-` attributes with names that start with numbers. ([@nLight](https://github.com/nLight) in [#5216](https://github.com/facebook/react/pull/5216)) <add>- React DOM adds a new `suppressContentEditableWarning` prop for components like [Draft.js](https://facebook.github.io/draft-js/) that intentionally manage `contentEditable` children with React. ([@mxstbr](https://github.com/mxstbr) in [#6112](https://github.com/facebook/react/pull/6112)) <add>- React improves the performance for `createClass()` on complex specs. ([@spicyj](https://github.com/spicyj) in [#5550](https://github.com/facebook/react/pull/5550)) <add> <add> <ide> ## 0.14.8 (March 29, 2016) <ide> <ide> ### React
1
Text
Text
add text in portuguese
d1408853315f4d290ad804d038d7fab17987db0c
<ide><path>guide/portuguese/mathematics/percent-of-a-whole-number/index.md <ide> localeTitle: Porcentagem de um número inteiro <ide> --- <ide> ## Porcentagem de um número inteiro <ide> <del>Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/percent-of-a-whole-number/index.md) . <add>Para calcular a porcentagem de um número inteiro, basta multiplicá-lo pela porcentagem na forma decimal. <ide> <del>[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) . <add>Exemplo: <ide> <del>#### Mais Informações: <ide>\ No newline at end of file <add>15% de 40 = 40 * 0,15 = 6 <add> <add>#### Mais Informações:
1
Ruby
Ruby
add a task to commit the changes
482790db6ce85b79a74b4f0f837fc848613daa4a
<ide><path>tasks/release.rb <ide> end <ide> end <ide> <add> task :commit do <add> File.open('dist/commit_message.txt', 'w') do |f| <add> f.puts "# Preparing for #{version} release\n" <add> f.puts <add> f.puts "# UNCOMMENT THE LINE ABOVE TO APPROVE THIS COMMIT" <add> end <add> <add> sh "git add . && git commit --verbose --template=dist/commit_message.txt" <add> rm_f "dist/commit_message.txt" <add> end <add> <ide> task :tag do <ide> sh "git tag #{tag}" <ide> end <add> <add> task :full => %w(ensure_clean_state all:build commit) <ide> end <ide> <ide> namespace :all do
1
Python
Python
remove unused import from tensorflow
30e8b0373a57fa29e605a1896f90e7b3c4e279d2
<ide><path>keras/backend.py <ide> def truncated_normal( <ide> <ide> def dropout(self, inputs, rate, noise_shape=None): <ide> self._maybe_init() <del> if self._rng_type == self.RNG_STATEFUL: <del> return tf.nn.experimental.general_dropout( <del> inputs, <del> rate=rate, <del> noise_shape=noise_shape, <del> uniform_sampler=self._generator.uniform, <del> ) <del> elif self._rng_type == self.RNG_STATELESS: <add> if self._rng_type in [self.RNG_STATEFUL, self.RNG_STATELESS]: <ide> return tf.nn.experimental.stateless_dropout( <ide> inputs, <ide> rate=rate, <ide> noise_shape=noise_shape, <ide> seed=self.make_seed_for_stateless_op(), <ide> ) <del> else: <del> return tf.nn.dropout( <del> inputs, <del> rate=rate, <del> noise_shape=noise_shape, <del> seed=self.make_legacy_seed(), <del> ) <add> return tf.nn.dropout( <add> inputs, <add> rate=rate, <add> noise_shape=noise_shape, <add> seed=self.make_legacy_seed(), <add> ) <ide> <ide> <ide> @keras_export("keras.backend.random_uniform_variable") <ide><path>keras/layers/__init__.py <ide> from keras.layers.reshaping.zero_padding2d import ZeroPadding2D <ide> from keras.layers.reshaping.zero_padding3d import ZeroPadding3D <ide> <del># isort: off <del>from tensorflow.python import tf2 <del> <ide> if tf.__internal__.tf2.enabled(): <ide> from keras.layers.normalization.batch_normalization import ( <ide> BatchNormalization,
2
Go
Go
remove job from tag
99f6309b97041bf82cc845340734dc8e47977c8a
<ide><path>api/server/server.go <ide> func postImagesTag(eng *engine.Engine, version version.Version, w http.ResponseW <ide> return fmt.Errorf("Missing parameter") <ide> } <ide> <del> job := eng.Job("tag", vars["name"], r.Form.Get("repo"), r.Form.Get("tag")) <del> job.Setenv("force", r.Form.Get("force")) <del> if err := job.Run(); err != nil { <add> d := getDaemon(eng) <add> repo := r.Form.Get("repo") <add> tag := r.Form.Get("tag") <add> force := toBool(r.Form.Get("force")) <add> if err := d.Repositories().Tag(repo, tag, vars["name"], force); err != nil { <ide> return err <ide> } <ide> w.WriteHeader(http.StatusCreated) <ide><path>builder/job.go <ide> func (b *BuilderJob) CmdBuild(job *engine.Job) error { <ide> } <ide> <ide> if repoName != "" { <del> b.Daemon.Repositories().Set(repoName, tag, id, true) <add> b.Daemon.Repositories().Tag(repoName, tag, id, true) <ide> } <ide> return nil <ide> } <ide><path>daemon/commit.go <ide> func (daemon *Daemon) Commit(container *Container, repository, tag, comment, aut <ide> <ide> // Register the image if needed <ide> if repository != "" { <del> if err := daemon.repositories.Set(repository, tag, img.ID, true); err != nil { <add> if err := daemon.repositories.Tag(repository, tag, img.ID, true); err != nil { <ide> return img, err <ide> } <ide> } <ide><path>graph/import.go <ide> func (s *TagStore) CmdImport(job *engine.Job) error { <ide> } <ide> // Optionally register the image at REPO/TAG <ide> if repo != "" { <del> if err := s.Set(repo, tag, img.ID, true); err != nil { <add> if err := s.Tag(repo, tag, img.ID, true); err != nil { <ide> return err <ide> } <ide> } <ide><path>graph/manifest_test.go <ide> func TestManifestTarsumCache(t *testing.T) { <ide> if err := store.graph.Register(img, archive); err != nil { <ide> t.Fatal(err) <ide> } <del> if err := store.Set(testManifestImageName, testManifestTag, testManifestImageID, false); err != nil { <add> if err := store.Tag(testManifestImageName, testManifestTag, testManifestImageID, false); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide><path>graph/pull.go <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> if askedTag != "" && tag != askedTag { <ide> continue <ide> } <del> if err := s.Set(repoInfo.LocalName, tag, id, true); err != nil { <add> if err := s.Tag(repoInfo.LocalName, tag, id, true); err != nil { <ide> return err <ide> } <ide> } <ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri <ide> } <ide> } else { <ide> // only set the repository/tag -> image ID mapping when pulling by tag (i.e. not by digest) <del> if err = s.Set(repoInfo.LocalName, tag, downloads[0].img.ID, true); err != nil { <add> if err = s.Tag(repoInfo.LocalName, tag, downloads[0].img.ID, true); err != nil { <ide> return false, err <ide> } <ide> } <ide><path>graph/service.go <ide> import ( <ide> func (s *TagStore) Install(eng *engine.Engine) error { <ide> for name, handler := range map[string]engine.Handler{ <ide> "image_set": s.CmdSet, <del> "tag": s.CmdTag, <ide> "image_get": s.CmdGet, <ide> "image_inspect": s.CmdLookup, <ide> "image_tarlayer": s.CmdTarLayer, <ide><path>graph/tag.go <del>package graph <del> <del>import ( <del> "fmt" <del> <del> "github.com/docker/docker/engine" <del>) <del> <del>func (s *TagStore) CmdTag(job *engine.Job) error { <del> if len(job.Args) != 2 && len(job.Args) != 3 { <del> return fmt.Errorf("Usage: %s IMAGE REPOSITORY [TAG]\n", job.Name) <del> } <del> var tag string <del> if len(job.Args) == 3 { <del> tag = job.Args[2] <del> } <del> return s.Set(job.Args[1], tag, job.Args[0], job.GetenvBool("force")) <del>} <ide><path>graph/tags.go <ide> func (store *TagStore) Delete(repoName, ref string) (bool, error) { <ide> return deleted, store.save() <ide> } <ide> <del>func (store *TagStore) Set(repoName, tag, imageName string, force bool) error { <add>func (store *TagStore) Tag(repoName, tag, imageName string, force bool) error { <ide> return store.SetLoad(repoName, tag, imageName, force, nil) <ide> } <ide> <ide><path>graph/tags_unit_test.go <ide> func mkTestTagStore(root string, t *testing.T) *TagStore { <ide> if err := graph.Register(img, officialArchive); err != nil { <ide> t.Fatal(err) <ide> } <del> if err := store.Set(testOfficialImageName, "", testOfficialImageID, false); err != nil { <add> if err := store.Tag(testOfficialImageName, "", testOfficialImageID, false); err != nil { <ide> t.Fatal(err) <ide> } <ide> privateArchive, err := fakeTar() <ide> func mkTestTagStore(root string, t *testing.T) *TagStore { <ide> if err := graph.Register(img, privateArchive); err != nil { <ide> t.Fatal(err) <ide> } <del> if err := store.Set(testPrivateImageName, "", testPrivateImageID, false); err != nil { <add> if err := store.Tag(testPrivateImageName, "", testPrivateImageID, false); err != nil { <ide> t.Fatal(err) <ide> } <ide> if err := store.SetDigest(testPrivateImageName, testPrivateImageDigest, testPrivateImageID); err != nil { <ide><path>integration/api_test.go <ide> func TestDeleteImages(t *testing.T) { <ide> <ide> initialImages := getImages(eng, t, true, "") <ide> <del> if err := eng.Job("tag", unitTestImageName, "test", "test").Run(); err != nil { <add> d := getDaemon(eng) <add> if err := d.Repositories().Tag("test", "test", unitTestImageName, true); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide><path>integration/server_test.go <del>package docker <del> <del>import "testing" <del> <del>func TestCreateNumberHostname(t *testing.T) { <del> eng := NewTestEngine(t) <del> defer mkDaemonFromEngine(eng, t).Nuke() <del> <del> config, _, _, err := parseRun([]string{"-h", "web.0", unitTestImageID, "echo test"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> createTestContainer(eng, config, t) <del>} <del> <del>func TestRunWithTooLowMemoryLimit(t *testing.T) { <del> eng := NewTestEngine(t) <del> defer mkDaemonFromEngine(eng, t).Nuke() <del> <del> // Try to create a container with a memory limit of 1 byte less than the minimum allowed limit. <del> job := eng.Job("create") <del> job.Setenv("Image", unitTestImageID) <del> job.Setenv("Memory", "524287") <del> job.Setenv("CpuShares", "1000") <del> job.SetenvList("Cmd", []string{"/bin/cat"}) <del> if err := job.Run(); err == nil { <del> t.Errorf("Memory limit is smaller than the allowed limit. Container creation should've failed!") <del> } <del>} <del> <del>func TestImagesFilter(t *testing.T) { <del> eng := NewTestEngine(t) <del> defer nuke(mkDaemonFromEngine(eng, t)) <del> <del> if err := eng.Job("tag", unitTestImageName, "utest", "tag1").Run(); err != nil { <del> t.Fatal(err) <del> } <del> <del> if err := eng.Job("tag", unitTestImageName, "utest/docker", "tag2").Run(); err != nil { <del> t.Fatal(err) <del> } <del> <del> if err := eng.Job("tag", unitTestImageName, "utest:5000/docker", "tag3").Run(); err != nil { <del> t.Fatal(err) <del> } <del> <del> images := getImages(eng, t, false, "utest*/*") <del> <del> if len(images[0].RepoTags) != 2 { <del> t.Fatal("incorrect number of matches returned") <del> } <del> <del> images = getImages(eng, t, false, "utest") <del> <del> if len(images[0].RepoTags) != 1 { <del> t.Fatal("incorrect number of matches returned") <del> } <del> <del> images = getImages(eng, t, false, "utest*") <del> <del> if len(images[0].RepoTags) != 1 { <del> t.Fatal("incorrect number of matches returned") <del> } <del> <del> images = getImages(eng, t, false, "*5000*/*") <del> <del> if len(images[0].RepoTags) != 1 { <del> t.Fatal("incorrect number of matches returned") <del> } <del>}
12
Python
Python
upgrade fab to 3.1.1
5154b84f52aac6bd469ba3e726daebe9d9538a32
<ide><path>airflow/www/utils.py <ide> # under the License. <ide> import json <ide> import time <del>from typing import Any, List, Optional <ide> from urllib.parse import urlencode <ide> <ide> import markdown <ide> import sqlalchemy as sqla <ide> from flask import Markup, Response, request, url_for <ide> from flask_appbuilder.forms import FieldConverter <del>from flask_appbuilder.models.filters import Filters <ide> from flask_appbuilder.models.sqla import filters as fab_sqlafilters <ide> from flask_appbuilder.models.sqla.interface import SQLAInterface <ide> from pygments import highlight, lexers <ide> def is_utcdatetime(self, col_name): <ide> isinstance(obj.impl, UtcDateTime) <ide> return False <ide> <del> # This is a local fix until https://github.com/dpgaspar/Flask-AppBuilder/pull/1493 is merged and released. <del> def get( <del> self, <del> id, <del> filters: Optional[Filters] = None, <del> select_columns: Optional[List[str]] = None, <del> ) -> Any: <del> """ <del> Returns the result for a model get, applies filters and supports dotted <del> notation for joins and granular selecting query columns. <del> <del> :param id: The model id (pk). <del> :param filters: A Filter class that contains all filters to apply. <del> :param select_columns: A List of columns to be specifically selected. <del> on the query. Supports dotted notation. <del> :return: Model instance if found, or none <del> """ <del> pk = self.get_pk_name() <del> if filters: <del> _filters = filters.copy() <del> else: <del> _filters = Filters(self.filter_converter_class, self) <del> <del> if self.is_pk_composite(): <del> for _pk, _id in zip(pk, id): <del> _filters.add_filter(_pk, self.FilterEqual, _id) <del> else: <del> _filters.add_filter(pk, self.FilterEqual, id) <del> query = self.session.query(self.obj) <del> item = self.apply_all( <del> query, _filters, select_columns=select_columns <del> ).one_or_none() <del> if item: <del> if hasattr(item, self.obj.__name__): <del> return getattr(item, self.obj.__name__) <del> return item <del> <ide> filter_converter_class = UtcAwareFilterConverter <ide> <ide> <ide><path>setup.py <ide> def is_package_excluded(package: str, exclusion_list: List[str]): <ide> 'cryptography>=0.9.3', <ide> 'dill>=0.2.2, <0.4', <ide> 'flask>=1.1.0, <2.0', <del> 'flask-appbuilder~=3.1.0', <add> 'flask-appbuilder~=3.1.1', <ide> 'flask-caching>=1.3.3, <2.0.0', <ide> 'flask-login>=0.3, <0.5', <ide> 'flask-swagger==0.2.13',
2
Javascript
Javascript
remove tls.createsecurepair code deprecation
d8a3c4ab2aba94f1faac36e51220b270f9b88227
<ide><path>lib/tls.js <ide> exports.TLSSocket = require('_tls_wrap').TLSSocket; <ide> exports.Server = require('_tls_wrap').Server; <ide> exports.createServer = require('_tls_wrap').createServer; <ide> exports.connect = require('_tls_wrap').connect; <del> <del>// Legacy API <del>exports.__defineGetter__('createSecurePair', util.deprecate(function() { <del> return require('_tls_legacy').createSecurePair; <del>}, 'createSecurePair() is deprecated, use TLSSocket instead')); <add>exports.createSecurePair = require('_tls_legacy').createSecurePair;
1
Javascript
Javascript
save 8 chars
a83e15fdf6c3a21b84ae660e0c36590f4d8d610b
<ide><path>lib/MainTemplate.js <ide> MainTemplate.prototype = Object.create(Template.prototype); <ide> MainTemplate.prototype.requireFn = "require"; <ide> MainTemplate.prototype.render = function(hash, chunk, moduleTemplate, dependencyTemplates) { <ide> var buf = []; <add> buf.push("// shortcut for better minimizing"); <add> buf.push("var exports = \"exports\";"); <ide> buf.push(this.asString(this.renderAdditions(hash, chunk, moduleTemplate, dependencyTemplates))); <ide> buf.push(this.asString(this.renderLocalVars(hash, chunk))); <ide> buf.push(""); <ide> MainTemplate.prototype.renderRequireContent = function(hash, chunk) { <ide> return [ <ide> "// Check if module is in cache", <ide> "if(installedModules[moduleId])", <del> this.indent("return installedModules[moduleId].exports;"), <add> this.indent("return installedModules[moduleId][exports];"), <ide> "", <ide> "// Create a new module (and put it into the cache)", <ide> "var module = installedModules[moduleId] = {", <ide> this.indent(this.renderModule(hash, chunk, "moduleId")), <ide> "};", <ide> "", <ide> "// Execute the module function", <del> "modules[moduleId].call(module.exports, module, module.exports, " + this.renderRequireFunctionForModule(hash, chunk, "moduleId") + ");", <add> "modules[moduleId].call(module[exports], module, module[exports], " + this.renderRequireFunctionForModule(hash, chunk, "moduleId") + ");", <ide> "", <ide> "// Flag the module as loaded", <ide> "module.loaded = true;", <ide> "", <ide> "// Return the exports of the module", <del> "return module.exports;" <add> "return module[exports];" <ide> ]; <ide> }; <ide>
1
Javascript
Javascript
add missing semicolon in hdrcubetextureloader
6f5d75c3c5899a209c82dbeecde57bd0ece4fd86
<ide><path>examples/js/loaders/HDRCubeTextureLoader.js <ide> THREE.HDRCubeTextureLoader = function (manager) { <ide> this.hdrLoader = new THREE.RGBELoader(); <ide> <ide> if( THREE.Encodings === undefined ) throw new Error( "HDRCubeMapLoader requires THREE.Encodings" ); <del>} <add>}; <ide> <ide> THREE.HDRCubeTextureLoader.prototype.load = function(type, urls, onLoad, onProgress, onError) { <ide> var texture = new THREE.CubeTexture();
1
Javascript
Javascript
return child from execfile
d700a6f74ad7b32b1f9106634ac6b13b4ae4244a
<ide><path>lib/child_process.js <ide> exports.execFile = function (file, args /*, options, callback */) { <ide> if (callback) callback(e, stdout, stderr); <ide> } <ide> }); <add> <add> return child; <ide> }; <ide> <ide>
1
Javascript
Javascript
improve message for assert.strictequal()
e07e7081027d512ebeb9890a246c4192949abe7d
<ide><path>test/addons-napi/test_exception/test.js <ide> let caughtError; <ide> <ide> // Test that the native side successfully captures the exception <ide> let returnedError = test_exception.returnException(throwTheError); <del>assert.strictEqual(theError, returnedError, <del> 'Returned error is strictly equal to the thrown error'); <add>assert.strictEqual(theError, returnedError); <ide> <ide> // Test that the native side passes the exception through <ide> assert.throws(
1
Text
Text
add gitter badge
2189a5999f8a4561c91ed5497cdb2c1bd182a9d9
<ide><path>README.md <ide> # Airflow <ide> <add>[![Join the chat at https://gitter.im/airbnb/airflow](https://badges.gitter.im/airbnb/airflow.svg)](https://gitter.im/airbnb/airflow?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) <add> <ide> [![Build Status](https://travis-ci.org/airbnb/airflow.svg)](https://travis-ci.org/airbnb/airflow) <ide> [![Coverage Status](https://coveralls.io/repos/airbnb/airflow/badge.svg?service=github)](https://coveralls.io/github/airbnb/airflow) <ide> [![pypi downloads](https://img.shields.io/pypi/dm/airflow.svg)](https://pypi.python.org/pypi/airflow/)
1
Go
Go
allow multiple params in inspect
a799cdad3e25136ff313d692b9972cb725754055
<ide><path>commands.go <ide> func (cli *DockerCli) CmdStart(args ...string) error { <ide> } <ide> <ide> func (cli *DockerCli) CmdInspect(args ...string) error { <del> cmd := Subcmd("inspect", "CONTAINER|IMAGE", "Return low-level information on a container/image") <add> cmd := Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container/image") <ide> if err := cmd.Parse(args); err != nil { <ide> return nil <ide> } <del> if cmd.NArg() != 1 { <add> if cmd.NArg() < 1 { <ide> cmd.Usage() <ide> return nil <ide> } <del> obj, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil) <del> if err != nil { <del> obj, _, err = cli.call("GET", "/images/"+cmd.Arg(0)+"/json", nil) <add> <add> for _, name := range args { <add> obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil) <ide> if err != nil { <del> return err <add> obj, _, err = cli.call("GET", "/images/"+name+"/json", nil) <add> if err != nil { <add> fmt.Printf("%s", err) <add> continue <add> } <ide> } <del> } <ide> <del> indented := new(bytes.Buffer) <del> if err = json.Indent(indented, obj, "", " "); err != nil { <del> return err <del> } <del> if _, err := io.Copy(os.Stdout, indented); err != nil { <del> return err <add> indented := new(bytes.Buffer) <add> if err = json.Indent(indented, obj, "", " "); err != nil { <add> fmt.Printf("%s", err) <add> continue <add> } <add> if _, err := io.Copy(os.Stdout, indented); err != nil { <add> fmt.Printf("%s", err) <add> } <ide> } <ide> return nil <ide> }
1
Javascript
Javascript
improve readable push performance
359ea2a0bd772beb25267478d4f8e3ed59021e19
<ide><path>benchmark/streams/readable-boundaryread.js <ide> const common = require('../common'); <ide> const Readable = require('stream').Readable; <ide> <ide> const bench = common.createBenchmark(main, { <del> n: [200e1] <add> n: [200e1], <add> type: ['string', 'buffer'] <ide> }); <ide> <ide> function main(conf) { <ide> const n = +conf.n; <del> const b = new Buffer(32); <ide> const s = new Readable(); <del> function noop() {} <del> s._read = noop; <add> var data = 'a'.repeat(32); <add> if (conf.type === 'buffer') <add> data = Buffer.from(data); <add> s._read = function() {}; <ide> <ide> bench.start(); <ide> for (var k = 0; k < n; ++k) { <ide> for (var i = 0; i < 1e4; ++i) <del> s.push(b); <add> s.push(data); <ide> while (s.read(32)); <ide> } <ide> bench.end(n); <ide><path>lib/_stream_readable.js <ide> Readable.prototype._destroy = function(err, cb) { <ide> // write() some more. <ide> Readable.prototype.push = function(chunk, encoding) { <ide> var state = this._readableState; <del> <del> if (!state.objectMode && typeof chunk === 'string') { <del> encoding = encoding || state.defaultEncoding; <del> if (encoding !== state.encoding) { <del> chunk = Buffer.from(chunk, encoding); <del> encoding = ''; <add> var skipChunkCheck; <add> <add> if (!state.objectMode) { <add> if (typeof chunk === 'string') { <add> encoding = encoding || state.defaultEncoding; <add> if (encoding !== state.encoding) { <add> chunk = Buffer.from(chunk, encoding); <add> encoding = ''; <add> } <add> skipChunkCheck = true; <ide> } <add> } else { <add> skipChunkCheck = true; <ide> } <ide> <del> return readableAddChunk(this, state, chunk, encoding, false); <add> return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); <ide> }; <ide> <ide> // Unshift should *always* be something directly out of read() <ide> Readable.prototype.unshift = function(chunk) { <del> var state = this._readableState; <del> return readableAddChunk(this, state, chunk, '', true); <del>}; <del> <del>Readable.prototype.isPaused = function() { <del> return this._readableState.flowing === false; <add> return readableAddChunk(this, chunk, null, true, false); <ide> }; <ide> <del>function readableAddChunk(stream, state, chunk, encoding, addToFront) { <del> var er = chunkInvalid(state, chunk); <del> if (er) { <del> stream.emit('error', er); <del> } else if (chunk === null) { <add>function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { <add> var state = stream._readableState; <add> if (chunk === null) { <ide> state.reading = false; <ide> onEofChunk(stream, state); <del> } else if (state.objectMode || chunk && chunk.length > 0) { <del> if (state.ended && !addToFront) { <del> const e = new Error('stream.push() after EOF'); <del> stream.emit('error', e); <del> } else if (state.endEmitted && addToFront) { <del> const e = new Error('stream.unshift() after end event'); <del> stream.emit('error', e); <del> } else { <del> var skipAdd; <del> if (state.decoder && !addToFront && !encoding) { <del> chunk = state.decoder.write(chunk); <del> skipAdd = (!state.objectMode && chunk.length === 0); <del> } <del> <del> if (!addToFront) <add> } else { <add> var er; <add> if (!skipChunkCheck) <add> er = chunkInvalid(state, chunk); <add> if (er) { <add> stream.emit('error', er); <add> } else if (state.objectMode || chunk && chunk.length > 0) { <add> if (addToFront) { <add> if (state.endEmitted) <add> stream.emit('error', new Error('stream.unshift() after end event')); <add> else <add> addChunk(stream, state, chunk, true); <add> } else if (state.ended) { <add> stream.emit('error', new Error('stream.push() after EOF')); <add> } else { <ide> state.reading = false; <del> <del> // Don't add to the buffer if we've decoded to an empty string chunk and <del> // we're not in object mode <del> if (!skipAdd) { <del> // if we want the data now, just emit it. <del> if (state.flowing && state.length === 0 && !state.sync) { <del> stream.emit('data', chunk); <del> stream.read(0); <del> } else { <del> // update the buffer info. <del> state.length += state.objectMode ? 1 : chunk.length; <del> if (addToFront) <del> state.buffer.unshift(chunk); <add> if (state.decoder && !encoding) { <add> chunk = state.decoder.write(chunk); <add> if (state.objectMode || chunk.length !== 0) <add> addChunk(stream, state, chunk, false); <ide> else <del> state.buffer.push(chunk); <del> <del> if (state.needReadable) <del> emitReadable(stream); <add> maybeReadMore(stream, state); <add> } else { <add> addChunk(stream, state, chunk, false); <ide> } <ide> } <del> <del> maybeReadMore(stream, state); <add> } else if (!addToFront) { <add> state.reading = false; <ide> } <del> } else if (!addToFront) { <del> state.reading = false; <ide> } <ide> <ide> return needMoreData(state); <ide> } <ide> <add>function addChunk(stream, state, chunk, addToFront) { <add> if (state.flowing && state.length === 0 && !state.sync) { <add> stream.emit('data', chunk); <add> stream.read(0); <add> } else { <add> // update the buffer info. <add> state.length += state.objectMode ? 1 : chunk.length; <add> if (addToFront) <add> state.buffer.unshift(chunk); <add> else <add> state.buffer.push(chunk); <add> <add> if (state.needReadable) <add> emitReadable(stream); <add> } <add> maybeReadMore(stream, state); <add>} <add> <add>function chunkInvalid(state, chunk) { <add> var er; <add> if (!(chunk instanceof Buffer) && <add> typeof chunk !== 'string' && <add> chunk !== undefined && <add> !state.objectMode) { <add> er = new TypeError('Invalid non-string/buffer chunk'); <add> } <add> return er; <add>} <add> <ide> <ide> // if it's past the high water mark, we can push in some more. <ide> // Also, if we have no data yet, we can stand some <ide> function needMoreData(state) { <ide> state.length === 0); <ide> } <ide> <add>Readable.prototype.isPaused = function() { <add> return this._readableState.flowing === false; <add>}; <add> <ide> // backwards compatibility. <ide> Readable.prototype.setEncoding = function(enc) { <ide> if (!StringDecoder) <ide> Readable.prototype.read = function(n) { <ide> return ret; <ide> }; <ide> <del>function chunkInvalid(state, chunk) { <del> var er = null; <del> if (!(chunk instanceof Buffer) && <del> typeof chunk !== 'string' && <del> chunk !== null && <del> chunk !== undefined && <del> !state.objectMode) { <del> er = new TypeError('Invalid non-string/buffer chunk'); <del> } <del> return er; <del>} <del> <del> <ide> function onEofChunk(stream, state) { <ide> if (state.ended) return; <ide> if (state.decoder) {
2
Javascript
Javascript
add format and parse token y, so it actually works
0d9cefb39c963bd85d55ae069deb9e904d9bbc87
<ide><path>src/lib/units/year.js <ide> import toInt from '../utils/to-int'; <ide> <ide> // FORMATTING <ide> <add>addFormatToken('Y', 0, 0, function () { <add> var y = this.year(); <add> if (y < 0) { <add> return y; <add> } else if (y <= 9999) { <add> return y; <add> } else { <add> // force plus for longer years. <add> return '+' + y; <add> } <add>}); <add> <ide> addFormatToken(0, ['YY', 2], 0, function () { <ide> return this.year() % 100; <ide> }); <ide> addParseToken('YYYY', function (input, array) { <ide> addParseToken('YY', function (input, array) { <ide> array[YEAR] = hooks.parseTwoDigitYear(input); <ide> }); <add>addParseToken('Y', function (input, array) { <add> array[YEAR] = parseInt(input, 10); <add>}); <ide> <ide> // HELPERS <ide> <ide><path>src/test/moment/create.js <ide> test('hmm', function (assert) { <ide> assert.equal(moment('112345', 'Hmmss', true).format('HH:mm:ss'), '11:23:45', '112345 with Hmmss'); <ide> assert.equal(moment('172345', 'Hmmss', true).format('HH:mm:ss'), '17:23:45', '112345 with Hmmss'); <ide> }); <add> <add>test('Y token', function (assert) { <add> assert.equal(moment('1-1-2010', 'M-D-Y', true).year(), 2010, 'parsing Y'); <add>}); <ide><path>src/test/moment/format.js <ide> test('Hmm and Hmmss', function (assert) { <ide> assert.equal(moment('08:34:56', 'HH:mm:ss').format('Hmmss'), '83456'); <ide> assert.equal(moment('18:34:56', 'HH:mm:ss').format('Hmmss'), '183456'); <ide> }); <add> <add>test('Y token', function (assert) { <add> assert.equal(moment('2010-01-01', 'YYYY-MM-DD', true).format('Y'), '2010', 'format 2010 with Y'); <add> assert.equal(moment('-123-01-01', 'Y-MM-DD', true).format('Y'), '-123', 'format -123 with Y'); <add> assert.equal(moment('12345-01-01', 'Y-MM-DD', true).format('Y'), '+12345', 'format 12345 with Y'); <add>});
3
Python
Python
clarify behaviour of test_backfill_depends_on_past
a804666347b50b026a8d3a1a14c0b2e27a369201
<ide><path>tests/jobs/test_backfill_job.py <ide> def test_backfill_pooled_tasks(self): <ide> ti.refresh_from_db() <ide> assert ti.state == State.SUCCESS <ide> <del> @pytest.mark.quarantined <del> def test_backfill_depends_on_past(self): <del> """ <del> Test that backfill respects ignore_depends_on_past <del> """ <add> @pytest.mark.parametrize("ignore_depends_on_past", [True, False]) <add> def test_backfill_depends_on_past_works_independently_on_ignore_depends_on_past( <add> self, ignore_depends_on_past <add> ): <ide> dag = self.dagbag.get_dag('test_depends_on_past') <ide> dag.clear() <ide> run_date = DEFAULT_DATE + datetime.timedelta(days=5) <ide> <del> # backfill should deadlock <del> with pytest.raises(AirflowException, match='BackfillJob is deadlocked'): <del> BackfillJob(dag=dag, start_date=run_date, end_date=run_date).run() <del> <ide> BackfillJob( <ide> dag=dag, <ide> start_date=run_date, <ide> end_date=run_date, <ide> executor=MockExecutor(), <del> ignore_first_depends_on_past=True, <add> ignore_first_depends_on_past=ignore_depends_on_past, <ide> ).run() <ide> <ide> # ti should have succeeded
1
Text
Text
fix typo in globals.md
cb7e854c776d366fed74ec3edf082aea0e723a6f
<ide><path>doc/api/globals.md <ide> changes: <ide> description: Added the new optional reason argument. <ide> --> <ide> <del>* `reason` {any} An optional reason, retrievable on the `AbortSignal`s <add>* `reason` {any} An optional reason, retrievable on the `AbortSignal`'s <ide> `reason` property. <ide> <ide> Triggers the abort signal, causing the `abortController.signal` to emit
1
Javascript
Javascript
add slider and switch
a3b9840885b13a187195f2f2b3da9b5475993bc6
<ide><path>Libraries/Components/Slider/Slider.js <ide> 'use strict'; <ide> <ide> const Platform = require('../../Utilities/Platform'); <del>const SliderNativeComponent = require('./SliderNativeComponent'); <add>import SliderNativeComponent from './SliderNativeComponent'; <ide> const React = require('react'); <ide> const ReactNative = require('../../Renderer/shims/ReactNative'); <ide> const StyleSheet = require('../../StyleSheet/StyleSheet'); <ide><path>Libraries/Components/Slider/SliderNativeComponent.js <ide> type NativeProps = $ReadOnly<{| <ide> onSlidingComplete?: ?(event: DirectEvent<Event>) => void, <ide> |}>; <ide> <del>module.exports = codegenNativeComponent<NativeProps>('Slider', { <add>export default codegenNativeComponent<NativeProps>('Slider', { <ide> interfaceOnly: true, <ide> isDeprecatedPaperComponentNameRCT: true, <ide> }); <ide><path>Libraries/Components/Switch/Switch.js <ide> <ide> 'use strict'; <ide> <del>const SwitchNativeComponent = require('./SwitchNativeComponent'); <add>import SwitchNativeComponent from './SwitchNativeComponent'; <ide> const AndroidSwitchNativeComponent = require('./AndroidSwitchNativeComponent'); <ide> const Platform = require('../../Utilities/Platform'); <ide> const React = require('react'); <ide><path>Libraries/Components/Switch/SwitchNativeComponent.js <ide> type NativeProps = $ReadOnly<{| <ide> onChange?: ?(event: BubblingEvent<SwitchChangeEvent>) => mixed, <ide> |}>; <ide> <del>module.exports = codegenNativeComponent<NativeProps>('Switch', { <add>export default codegenNativeComponent<NativeProps>('Switch', { <ide> isDeprecatedPaperComponentNameRCT: true, <ide> }); <ide><path>Libraries/Utilities/verifyComponentAttributeEquivalence.js <ide> export function getConfigWithoutViewProps( <ide> viewConfig: ReactNativeBaseComponentViewConfig<>, <ide> propName: string, <ide> ) { <add> if (!viewConfig[propName]) { <add> return {}; <add> } <add> <ide> return Object.keys(viewConfig[propName]) <ide> .filter(prop => !ReactNativeViewViewConfig[propName][prop]) <ide> .reduce((obj, prop) => {
5
Javascript
Javascript
fix test-timers.reliability on os x
8bcb174d03f045b99a3c46a81af750704d273762
<ide><path>test/timers/test-timers-reliability.js <ide> var intervalFired = false; <ide> */ <ide> <ide> var monoTimer = new Timer(); <del>monoTimer.ontimeout = function() { <add>monoTimer[Timer.kOnTimeout] = function() { <ide> /* <ide> * Make sure that setTimeout's and setInterval's callbacks have <ide> * already fired, otherwise it means that they are vulnerable to
1
Text
Text
remove link to join slack
be23d14d5f110b5e7b398c4786684c2976bc3e9b
<ide><path>README.md <ide> <ide> [![Build status](https://dev.azure.com/github/Atom/_apis/build/status/Atom%20Production%20Branches?branchName=master)](https://dev.azure.com/github/Atom/_build/latest?definitionId=32&branchName=master) <ide> [![Dependency Status](https://david-dm.org/atom/atom.svg)](https://david-dm.org/atom/atom) <del>[![Join the Atom Community on Slack](https://atom-slack.herokuapp.com/badge.svg)](https://atom-slack.herokuapp.com) <ide> <ide> Atom is a hackable text editor for the 21st century, built on [Electron](https://github.com/electron/electron), and based on everything we love about our favorite editors. We designed it to be deeply customizable, but still approachable using the default configuration. <ide>
1
Text
Text
remove use of "very" [ci skip]
c709edaceba1866749ade264583ce9d0e85126ea
<ide><path>guides/source/testing.md <ide> You'll find fixtures under your `test/fixtures` directory. When you run `rails g <ide> <ide> #### YAML <ide> <del>YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the **.yml** file extension (as in `users.yml`). <add>YAML-formatted fixtures are a human-friendly way to describe your sample data. These types of fixtures have the **.yml** file extension (as in `users.yml`). <ide> <ide> Here's a sample YAML fixture file: <ide>
1
PHP
PHP
ignore a given model during a unique check
9cda938d168d8aceaab1ca0409eafce484458f0b
<ide><path>src/Illuminate/Validation/Rules/Unique.php <ide> <ide> namespace Illuminate\Validation\Rules; <ide> <add>use Illuminate\Database\Eloquent\Model; <add> <ide> class Unique <ide> { <ide> use DatabaseRule; <ide> class Unique <ide> * <ide> * @var string <ide> */ <del> protected $idColumn = 'id'; <add> protected $idColumn; <ide> <ide> /** <ide> * Ignore the given ID during the unique check. <ide> class Unique <ide> * @param string $idColumn <ide> * @return $this <ide> */ <del> public function ignore($id, $idColumn = 'id') <add> public function ignore($id, $idColumn = null) <ide> { <add> if ($id instanceof Model) { <add> return $this->ignoreModel($id, $idColumn); <add> } <add> <ide> $this->ignore = $id; <del> $this->idColumn = $idColumn; <add> $this->idColumn = $idColumn?? 'id'; <add> <add> return $this; <add> } <add> <add> /** <add> * Ignore the given model during the unique check. <add> * <add> * @param Model $model <add> * @param string|null $idColumn <add> * @return $this <add> */ <add> public function ignoreModel($model, $idColumn = null) <add> { <add> $this->idColumn = $idColumn?? $model->getKeyName(); <add> $this->ignore = $model->{$this->idColumn}; <ide> <ide> return $this; <ide> } <ide> public function __toString() <ide> $this->table, <ide> $this->column, <ide> $this->ignore ? '"'.$this->ignore.'"' : 'NULL', <del> $this->idColumn, <add> $this->idColumn?? 'NULL', <ide> $this->formatWheres() <ide> ), ','); <ide> } <ide><path>tests/Validation/ValidationUniqueRuleTest.php <ide> <ide> namespace Illuminate\Tests\Validation; <ide> <add>use Illuminate\Database\Eloquent\Model; <ide> use PHPUnit\Framework\TestCase; <ide> <ide> class ValidationUniqueRuleTest extends TestCase <ide> public function testItCorrectlyFormatsAStringVersionOfTheRule() <ide> { <ide> $rule = new \Illuminate\Validation\Rules\Unique('table'); <ide> $rule->where('foo', 'bar'); <del> $this->assertEquals('unique:table,NULL,NULL,id,foo,bar', (string) $rule); <add> $this->assertEquals('unique:table,NULL,NULL,NULL,foo,bar', (string) $rule); <ide> <ide> $rule = new \Illuminate\Validation\Rules\Unique('table', 'column'); <ide> $rule->ignore('Taylor, Otwell', 'id_column'); <ide> public function testItCorrectlyFormatsAStringVersionOfTheRule() <ide> $rule->ignore(null, 'id_column'); <ide> $rule->where('foo', 'bar'); <ide> $this->assertEquals('unique:table,column,NULL,id_column,foo,bar', (string) $rule); <add> <add> <add> $model = new EloquentModelStub(['id_column' => 1]); <add> <add> $rule = new \Illuminate\Validation\Rules\Unique('table', 'column'); <add> $rule->ignore($model); <add> $rule->where('foo', 'bar'); <add> $this->assertEquals('unique:table,column,"1",id_column,foo,bar', (string) $rule); <add> <add> $rule = new \Illuminate\Validation\Rules\Unique('table', 'column'); <add> $rule->ignore($model, 'id_column'); <add> $rule->where('foo', 'bar'); <add> $this->assertEquals('unique:table,column,"1",id_column,foo,bar', (string) $rule); <ide> } <ide> } <add> <add>class EloquentModelStub extends Model <add>{ <add> protected $primaryKey = 'id_column'; <add> protected $guarded = []; <add>}
2
Text
Text
clarify information about abi version
1b2d3f7ae7f0391908b70b0333a5adef3c8cb79d
<ide><path>doc/api/process.md <ide> added: v0.2.0 <ide> * {Object} <ide> <ide> The `process.versions` property returns an object listing the version strings of <del>Node.js and its dependencies. In addition, `process.versions.modules` indicates <del>the current ABI version, which is increased whenever a C++ API changes. Node.js <del>will refuse to load native modules built for an older `modules` value. <add>Node.js and its dependencies. `process.versions.modules` indicates the current <add>ABI version, which is increased whenever a C++ API changes. Node.js will refuse <add>to load modules that were compiled against a different module ABI version. <ide> <ide> ```js <ide> console.log(process.versions);
1
Ruby
Ruby
avoid method redefined warning
6ea967729fef4e3155fb7a50813b503a0bfdc07f
<ide><path>activemodel/test/cases/validations/callbacks_test.rb <ide> class Dog <ide> include ActiveModel::Validations <ide> include ActiveModel::Validations::Callbacks <ide> <del> attr_accessor :name, :history <add> attr_accessor :name <add> attr_writer :history <ide> <ide> def history <ide> @history ||= []
1
Python
Python
remove log line causing warning from disutils
7078f01420626e8261389ce558cb27d750d6650e
<ide><path>numpy/distutils/misc_util.py <ide> def gpaths(paths, local_path='', include_non_existing=True): <ide> <ide> _temporary_directory = None <ide> def clean_up_temporary_directory(): <del> from numpy.distutils import log <ide> global _temporary_directory <ide> if not _temporary_directory: <ide> return <del> log.debug('removing %s', _temporary_directory) <ide> try: <ide> shutil.rmtree(_temporary_directory) <ide> except OSError:
1
Java
Java
fix wrong javadoc tag
939f172b5fd39fdc83e353fa0b4626a8a61e3ee4
<ide><path>src/main/java/io/reactivex/MaybeObserver.java <ide> * first the Maybe calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows <ide> * cancelling the sequence at any time, then the <ide> * {@code Maybe} calls only one of the MaybeObserver's {@link #onSuccess}, {@link #onError} or <del> * {@lingk onComplete} methods to provide notifications. <add> * {@link #onComplete} methods to provide notifications. <ide> * <ide> * @see <a href="http://reactivex.io/documentation/observable.html">ReactiveX documentation: Observable</a> <ide> * @param <T>
1
Javascript
Javascript
document the container
58fd8c71ea677cd4e1e97de5d50b105e9ec0d92d
<ide><path>packages/container/lib/main.js <ide> define("container", <ide> [], <ide> function() { <ide> <add> /** <add> A safe and simple inheriting object. <add> <add> @class InheritingDict <add> */ <ide> function InheritingDict(parent) { <ide> this.parent = parent; <ide> this.dict = {}; <ide> } <ide> <ide> InheritingDict.prototype = { <add> <add> /** <add> @property parent <add> @type InheritingDict <add> @default null <add> */ <add> <add> parent: null, <add> <add> /** <add> Object used to store the current nodes data. <add> <add> @property dict <add> @type Object <add> @default Object <add> */ <add> dict: null, <add> <add> /** <add> Retrieve the value given a key, if the value is present at the current <add> level use it, otherwise walk up the parent hierarchy and try again. If <add> no matching key is found, return undefined. <add> <add> @method get <add> @return {any} <add> */ <ide> get: function(key) { <ide> var dict = this.dict; <ide> <ide> define("container", <ide> } <ide> }, <ide> <add> /** <add> Set the given value for the given key, at the current level. <add> <add> @method set <add> @param {String} key <add> @param {Any} value <add> */ <ide> set: function(key, value) { <ide> this.dict[key] = value; <ide> }, <ide> <add> /** <add> Check for the existence of given a key, if the key is present at the current <add> level return true, otherwise walk up the parent hierarchy and try again. If <add> no matching key is found, return false. <add> <add> @method has <add> @param {String} key <add> @returns {Boolean} <add> */ <ide> has: function(key) { <ide> var dict = this.dict; <ide> <ide> define("container", <ide> return false; <ide> }, <ide> <add> /** <add> Iterate and invoke a callback for each local key-value pair. <add> <add> @method eachLocal <add> @param {Function} callback <add> @param {Object} binding <add> */ <ide> eachLocal: function(callback, binding) { <ide> var dict = this.dict; <ide> <ide> define("container", <ide> } <ide> }; <ide> <add> /** <add> A lightweight container that helps to assemble and decouple components. <add> <add> @class Container <add> */ <ide> function Container(parent) { <ide> this.parent = parent; <ide> this.children = []; <ide> define("container", <ide> } <ide> <ide> Container.prototype = { <add> <add> /** <add> @property parent <add> @type Container <add> @default null <add> */ <add> parent: null, <add> <add> /** <add> @property children <add> @type Array <add> @default [] <add> */ <add> children: null, <add> <add> /** <add> @property resolver <add> @type function <add> */ <add> resolver: null, <add> <add> /** <add> @property registry <add> @type InheritingDict <add> */ <add> registry: null, <add> <add> /** <add> @property cache <add> @type InheritingDict <add> */ <add> cache: null, <add> <add> /** <add> @property typeInjections <add> @type InheritingDict <add> */ <add> typeInjections: null, <add> <add> /** <add> @property injections <add> @type Object <add> @default {} <add> */ <add> injections: null, <add> <add> /** <add> @private <add> <add> @property _options <add> @type InheritingDict <add> @default null <add> */ <add> _options: null, <add> <add> /** <add> @private <add> <add> @property _typeOptions <add> @type InheritingDict <add> */ <add> _typeOptions: null, <add> <add> /** <add> Returns a new child of the current container. These children are configured <add> to correctly inherit from the current container. <add> <add> @method child <add> @returns {Container} <add> */ <ide> child: function() { <ide> var container = new Container(this); <ide> this.children.push(container); <ide> return container; <ide> }, <ide> <add> /** <add> Sets a key-value pair on the current container. If a parent container, <add> has the same key, once set on a child, the parent and child will diverge <add> as expected. <add> <add> @method set <add> @param {Object} obkect <add> @param {String} key <add> @param {any} value <add> */ <ide> set: function(object, key, value) { <ide> object[key] = value; <ide> }, <ide> <add> /** <add> Registers a factory for later injection. <add> <add> Example: <add> <add> ```javascript <add> var container = new Container(); <add> <add> container.register('model:user', Person, {singleton: false }); <add> container.register('fruit:favorite', Orange); <add> container.register('communication:main', Email, {singleton: false}); <add> ``` <add> <add> @method register <add> @param {String} type <add> @param {String} name <add> @param {Function} factory <add> @param {Object} options <add> */ <ide> register: function(type, name, factory, options) { <ide> var fullName; <ide> <ide> define("container", <ide> this._options.set(normalizedName, options || {}); <ide> }, <ide> <add> /** <add> Given a fullName return the corresponding factory. <add> <add> By default `resolve` will retreive the factory from <add> it's containers registry. <add> <add> ```javascript <add> var container = new Container(); <add> container.register('api:twitter', Twitter); <add> <add> container.resolve('api:twitter') // => Twitter <add> ``` <add> <add> Optionally the container can be provided with a custom resolver. <add> If provided, `resolve` will first provide the custom resolver <add> the oppertunity to resolve the fullName, otherwise it will fallback <add> to the registry. <add> <add> ```javascript <add> var container = new Container(); <add> container.resolver = function(fullName) { <add> // lookup via the module system of choice <add> }; <add> <add> // the twitter factory is added to the module system <add> container.resolve('api:twitter') // => Twitter <add> ``` <add> <add> @method resolve <add> @param {String} fullName <add> @returns {Function} fullName's factory <add> */ <ide> resolve: function(fullName) { <ide> return this.resolver(fullName) || this.registry.get(fullName); <ide> }, <ide> <add> /** <add> A hook to enable custom fullName normalization behaviour <add> <add> @method normalize <add> @param {String} fullName <add> @return {string} normalized fullName <add> */ <ide> normalize: function(fullName) { <ide> return fullName; <ide> }, <ide> <add> /** <add> Given a fullName return a corresponding instance. <add> <add> The default behaviour is for lookup to return a singleton instance. <add> The singleton is scoped to the container, allowing multiple containers <add> to all have there own locally scoped singletons. <add> <add> ```javascript <add> var container = new Container(); <add> container.register('api:twitter', Twitter); <add> <add> var twitter = container.lookup('api:twitter'); <add> <add> twitter instanceof Twitter; // => true <add> <add> // by default the container will return singletons <add> twitter2 = container.lookup('api:twitter'); <add> twitter instanceof Twitter; // => true <add> <add> twitter === twitter2; //=> true <add> ``` <add> <add> If singletons are not wanted an optional flag can be provided at lookup. <add> <add> ```javascript <add> var container = new Container(); <add> container.register('api:twitter', Twitter); <add> <add> var twitter = container.lookup('api:twitter', { singleton: false }); <add> var twitter2 = container.lookup('api:twitter', { singleton: false }); <add> <add> twitter === twitter2; //=> false <add> ``` <add> <add> @method lookup <add> @param {String} fullName <add> @param {Object} options <add> @return {any} <add> */ <ide> lookup: function(fullName, options) { <ide> fullName = this.normalize(fullName); <ide> <ide> define("container", <ide> return value; <ide> }, <ide> <add> /** <add> Given a fullName return the corresponding factory. <add> <add> @method lookupFactory <add> @param {String} fullName <add> @return {any} <add> */ <ide> lookupFactory: function(fullName) { <ide> return factoryFor(this, fullName); <ide> }, <ide> <add> /** <add> Given a fullName check if the container is aware of its factory <add> or singleton instance. <add> <add> @method has <add> @param {String} fullName <add> @return {Boolean} <add> */ <ide> has: function(fullName) { <ide> if (this.cache.has(fullName)) { <ide> return true; <ide> define("container", <ide> return !!factoryFor(this, fullName); <ide> }, <ide> <add> /** <add> Allow registerying options for all factories of a type. <add> <add> ```javascript <add> var container = new Container(); <add> <add> // if all of type `connection` must not be singletons <add> container.optionsForType('connection', { singleton: false }); <add> <add> container.register('connection:twitter', TwitterConnection); <add> container.register('connection:facebook', FacebookConnection); <add> <add> var twitter = container.lookup('connection:twitter'); <add> var twitter2 = container.lookup('connection:twitter'); <add> <add> twitter === twitter2; // => false <add> <add> var facebook = container.lookup('connection:facebook'); <add> var facebook2 = container.lookup('connection:facebook'); <add> <add> facebook === facebook2; // => false <add> ``` <add> <add> @method optionsForType <add> @param {String} type <add> @param {Object} options <add> */ <ide> optionsForType: function(type, options) { <ide> if (this.parent) { illegalChildOperation('optionsForType'); } <ide> <ide> this._typeOptions.set(type, options); <ide> }, <ide> <add> /** <add> @method options <add> @param {String} type <add> @param {Object} options <add> */ <ide> options: function(type, options) { <ide> this.optionsForType(type, options); <ide> }, <ide> <add> /* <add> @private <add> <add> Used only via `injection`. <add> <add> Provides a specialized form of injection, specifically enabling <add> all objects of one type to be injected with a reference to another <add> object. <add> <add> For example, provided each object of type `controller` needed a `router`. <add> one would do the following: <add> <add> ```javascript <add> var container = new Container(); <add> <add> container.register('router:main', Router); <add> container.register('controller:user', UserController); <add> container.register('controller:post', PostController); <add> <add> container.typeInjection('controller', 'router', 'router:main'); <add> <add> var user = container.lookup('controller:user'); <add> var post = container.lookup('controller:post'); <add> <add> user.router instanceof Router; //=> true <add> post.router instanceof Router; //=> true <add> <add> // both controllers share the same router <add> user.router === post.router; //=> true <add> ``` <add> <add> @method typeInjection <add> @param {String} type <add> @param {String} property <add> @param {String} fullName <add> */ <ide> typeInjection: function(type, property, fullName) { <ide> if (this.parent) { illegalChildOperation('typeInjection'); } <ide> <ide> var injections = this.typeInjections.get(type); <add> <ide> if (!injections) { <ide> injections = []; <ide> this.typeInjections.set(type, injections); <ide> } <del> injections.push({ property: property, fullName: fullName }); <add> <add> injections.push({ <add> property: property, <add> fullName: fullName <add> }); <ide> }, <ide> <add> /* <add> Defines injection rules. <add> <add> These rules are used to inject dependencies onto objects when they <add> are instantiated. <add> <add> Two forms of injections are possible: <add> <add> * Injecting one fullName on another fullName <add> * Injecting one fullName on a type <add> <add> Example: <add> <add> ```javascript <add> var container = new Container(); <add> <add> container.register('source:main', Source); <add> container.register('model:user', User); <add> container.register('model:post', PostController); <add> <add> // injecting one fullName on another fullName <add> // eg. each user model gets a post model <add> container.injection('model:user', 'post', 'model:post'); <add> <add> // injecting one fullName on another type <add> container.injection('model', 'source', 'source:main'); <add> <add> var user = container.lookup('model:user'); <add> var post = container.lookup('model:post'); <add> <add> user.source instanceof Source; //=> true <add> post.source instanceof Source; //=> true <add> <add> user.post instanceof Post; //=> true <add> <add> // and both models share the same source <add> user.source === post.source; //=> true <add> ``` <add> <add> @method injection <add> @param {String} factoryName <add> @param {String} property <add> @param {String} injectionName <add> */ <ide> injection: function(factoryName, property, injectionName) { <ide> if (this.parent) { illegalChildOperation('injection'); } <ide> <ide> define("container", <ide> injections.push({ property: property, fullName: injectionName }); <ide> }, <ide> <add> /** <add> A depth first traversal, destroying the container, its descendant containers and all <add> their managed objects. <add> <add> @method destroy <add> */ <ide> destroy: function() { <ide> this.isDestroyed = true; <ide> <ide> define("container", <ide> this.isDestroyed = true; <ide> }, <ide> <add> /** <add> @method reset <add> */ <ide> reset: function() { <ide> for (var i=0, l=this.children.length; i<l; i++) { <ide> resetCache(this.children[i]); <ide> define("container", <ide> for (var i=0, l=injections.length; i<l; i++) { <ide> injection = injections[i]; <ide> lookup = container.lookup(injection.fullName); <del> hash[injection.property] = lookup; <add> <add> if (lookup) { <add> hash[injection.property] = lookup; <add> } else { <add> throw new Error('Attempting to inject an unknown injection: `' + injection.fullName + '`'); <add> } <ide> } <ide> <ide> return hash; <ide><path>packages/container/tests/container_test.js <ide> test("A failed lookup returns undefined", function() { <ide> equal(container.lookup("doesnot:exist"), undefined); <ide> }); <ide> <add>test("Injecting a failed lookup raises an error", function(){ <add> var container = new Container(); <add> var Foo = { create: function(){ }}; <add> <add> container.register('model:foo', Foo); <add> <add> container.injection('model:foo', 'store', 'store:main'); <add> <add> throws(function(){ <add> container.lookup('model:foo'); <add> }); <add>}); <add> <ide> test("Destroying the container destroys any cached singletons", function() { <ide> var container = new Container(); <ide> var PostController = factory();
2
Python
Python
allow integer device for batchencoding
222dbdb2039678564444b51fdd35975fce468fe1
<ide><path>src/transformers/tokenization_utils_base.py <ide> def to(self, device: Union[str, "torch.device"]) -> "BatchEncoding": <ide> # This check catches things like APEX blindly calling "to" on all inputs to a module <ide> # Otherwise it passes the casts down and casts the LongTensor containing the token idxs <ide> # into a HalfTensor <del> if isinstance(device, str) or isinstance(device, torch.device): <add> if isinstance(device, str) or isinstance(device, torch.device) or isinstance(device, int): <ide> self.data = {k: v.to(device=device) for k, v in self.data.items()} <ide> else: <ide> logger.warning(
1
PHP
PHP
add missing iterator unset calls
70f24dfa72b6d4c58952c8140b7668eeea82b426
<ide><path>src/Cache/Engine/FileEngine.php <ide> function (SplFileInfo $current) use ($group, $prefix) { <ide> @unlink($path); <ide> } <ide> <add> // unsetting iterators helps releasing possible locks in certain environments, <add> // which could otherwise make `rmdir()` fail <ide> unset($directoryIterator, $contents, $filtered); <ide> <ide> return true; <ide><path>src/Filesystem/Folder.php <ide> public function delete(?string $path = null): bool <ide> } else { <ide> $this->_errors[] = sprintf('%s NOT removed', $filePath); <ide> <del> // inner iterators need to be unset too in order for locks on parents to be released <ide> unset($directory, $iterator, $item); <ide> <ide> return false; <ide> } <ide> } <add> <add> // inner iterators need to be unset too in order for locks on parents to be released <add> unset($item); <ide> } <ide> <ide> // unsetting iterators helps releasing possible locks in certain environments,
2
Text
Text
update userland and core.md
cf432dce0aa99c5436dfd4aaf98e1e3b44b90315
<ide><path>docs/Basics/Userland and Core.md <add>Userland and Core <add>-------------------------- <ide> <add>TODO <add> <add>-------------------------- <add>Next: [Why Redux](Why Redux.md)
1
Javascript
Javascript
add quick temporary patch for authorization error
ec508636b0f81ac8a964ea60d77062dcc0200c82
<ide><path>server/boot/a-extendUser.js <ide> module.exports = function(app) { <ide> 'emails', <ide> 'a-extend-user-welcome.ejs' <ide> ), <del> redirect: '/' <add> redirect: '/email-signin' <ide> }; <ide> <ide> debug('sending welcome email'); <ide> return user.verify(mailOptions, function(err) { <ide> if (err) { return next(err); } <del> return req.logIn(user, function(err) { <del> if (err) { return next(err); } <del> <del> req.flash('success', { <del> msg: [ "Welcome to Free Code Camp! We've created your account." ] <del> }); <del> return res.redirect(redirect); <add> req.flash('success', { <add> msg: [ 'Congratulations ! We\'ve created your account. ', <add> 'Please check your email. We sent you a link that you can ', <add> 'click to verify your email address and then login.' <add> ].join('') <ide> }); <add> return res.redirect(redirect); <ide> }); <ide> }); <ide> };
1
PHP
PHP
add assert method for unauthorized response. (#1)
b0939f50e1178b6e2381b6379ac9942f210282db
<ide><path>src/Illuminate/Foundation/Testing/TestResponse.php <ide> public function assertForbidden() <ide> <ide> return $this; <ide> } <add> <add> /** <add> * Assert that the response has an unauthorized status code. <add> * <add> * @return $this <add> */ <add> public function assertUnauthorized() <add> { <add> $actual = $this->getStatusCode(); <add> <add> PHPUnit::assertTrue( <add> 401 === $actual, <add> 'Response status code ['.$actual.'] is not an unauthorized status code.' <add> ); <add> <add> return $this; <add> } <ide> <ide> /** <ide> * Assert that the response has the given status code.
1
Javascript
Javascript
remove knownfortype usage for dashless helpers
23888dac5efdb7fb043d9a1ee6560495d74ecef4
<ide><path>packages/ember-htmlbars/lib/hooks/has-helper.js <ide> export default function hasHelperHook(env, scope, helperName) { <ide> } <ide> <ide> var container = env.container; <del> if (validateLazyHelperName(helperName, container, env.hooks.keywords, env.knownHelpers)) { <add> if (validateLazyHelperName(helperName, container, env.hooks.keywords)) { <ide> var containerName = 'helper:' + helperName; <ide> if (container.registry.has(containerName)) { <ide> return true; <ide><path>packages/ember-htmlbars/lib/system/discover-known-helpers.js <del>import dictionary from 'ember-metal/dictionary'; <del> <del>export default function discoverKnownHelpers(container) { <del> let registry = container && container.registry; <del> let helpers = dictionary(null); <del> <del> if (!registry) { <del> return helpers; <del> } <del> <del> let known = registry.knownForType('helper'); <del> let knownContainerKeys = Object.keys(known); <del> <del> for (let index = 0, length = knownContainerKeys.length; index < length; index++) { <del> let fullName = knownContainerKeys[index]; <del> let name = fullName.slice(7); // remove `helper:` from fullName <del> <del> helpers[name] = true; <del> } <del> <del> return helpers; <del>} <ide><path>packages/ember-htmlbars/lib/system/lookup-helper.js <ide> export var CONTAINS_DASH_CACHE = new Cache(1000, function(key) { <ide> return key.indexOf('-') !== -1; <ide> }); <ide> <del>export function validateLazyHelperName(helperName, container, keywords, knownHelpers) { <del> if (!container || (helperName in keywords)) { <del> return false; <del> } <del> <del> if (knownHelpers[helperName] || CONTAINS_DASH_CACHE.get(helperName)) { <del> return true; <del> } <add>export function validateLazyHelperName(helperName, container, keywords) { <add> return container && !(helperName in keywords); <ide> } <ide> <ide> /** <ide> export function findHelper(name, view, env) { <ide> <ide> if (!helper) { <ide> var container = env.container; <del> if (validateLazyHelperName(name, container, env.hooks.keywords, env.knownHelpers)) { <add> if (validateLazyHelperName(name, container, env.hooks.keywords)) { <ide> var helperName = 'helper:' + name; <ide> if (container.registry.has(helperName)) { <ide> helper = container.lookupFactory(helperName); <ide><path>packages/ember-htmlbars/lib/system/render-env.js <ide> import defaultEnv from 'ember-htmlbars/env'; <del>import discoverKnownHelpers from 'ember-htmlbars/system/discover-known-helpers'; <ide> <ide> export default function RenderEnv(options) { <ide> this.lifecycleHooks = options.lifecycleHooks || []; <ide> export default function RenderEnv(options) { <ide> this.container = options.container; <ide> this.renderer = options.renderer; <ide> this.dom = options.dom; <del> this.knownHelpers = options.knownHelpers || discoverKnownHelpers(options.container); <ide> <ide> this.hooks = defaultEnv.hooks; <ide> this.helpers = defaultEnv.helpers; <ide> RenderEnv.prototype.childWithView = function(view) { <ide> lifecycleHooks: this.lifecycleHooks, <ide> renderedViews: this.renderedViews, <ide> renderedNodes: this.renderedNodes, <del> hasParentOutlet: this.hasParentOutlet, <del> knownHelpers: this.knownHelpers <add> hasParentOutlet: this.hasParentOutlet <ide> }); <ide> }; <ide> <ide> RenderEnv.prototype.childWithOutletState = function(outletState, hasParentOutlet <ide> lifecycleHooks: this.lifecycleHooks, <ide> renderedViews: this.renderedViews, <ide> renderedNodes: this.renderedNodes, <del> hasParentOutlet: hasParentOutlet, <del> knownHelpers: this.knownHelpers <add> hasParentOutlet: hasParentOutlet <ide> }); <ide> }; <ide><path>packages/ember-htmlbars/tests/system/discover-known-helpers-test.js <del>import Registry from 'container/registry'; <del>import Helper from 'ember-htmlbars/helper'; <del>import { runDestroy } from 'ember-runtime/tests/utils'; <del>import discoverKnownHelpers from 'ember-htmlbars/system/discover-known-helpers'; <del> <del>var resolver, registry, container; <del> <del>QUnit.module('ember-htmlbars: discover-known-helpers', { <del> setup() { <del> resolver = function() { }; <del> <del> registry = new Registry({ resolver }); <del> container = registry.container(); <del> }, <del> <del> teardown() { <del> runDestroy(container); <del> registry = container = null; <del> } <del>}); <del> <del>QUnit.test('returns an empty hash when no helpers are known', function() { <del> let result = discoverKnownHelpers(container); <del> <del> deepEqual(result, {}, 'no helpers were known'); <del>}); <del> <del>QUnit.test('includes helpers in the registry', function() { <del> registry.register('helper:t', Helper); <del> let result = discoverKnownHelpers(container); <del> let helpers = Object.keys(result); <del> <del> deepEqual(helpers, ['t'], 'helpers from the registry were known'); <del>}); <del> <del>QUnit.test('includes resolved helpers', function() { <del> resolver.knownForType = function() { <del> return { <del> 'helper:f': true <del> }; <del> }; <del> <del> registry.register('helper:t', Helper); <del> let result = discoverKnownHelpers(container); <del> let helpers = Object.keys(result); <del> <del> deepEqual(helpers, ['t', 'f'], 'helpers from the registry were known'); <del>});
5
Java
Java
improve javadoc for repeatablecontainers
965dd66f8cfc162de94d517c4e5515d6002ac874
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/RepeatableContainers.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2022 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * <p>To completely disable repeatable support use {@link #none()}. <ide> * <ide> * @author Phillip Webb <add> * @author Sam Brannen <ide> * @since 5.2 <ide> */ <ide> public abstract class RepeatableContainers { <ide> public static RepeatableContainers standardRepeatables() { <ide> } <ide> <ide> /** <del> * Create a {@link RepeatableContainers} instance that uses a defined <del> * container and repeatable type. <del> * @param repeatable the contained repeatable annotation <del> * @param container the container annotation or {@code null}. If specified, <add> * Create a {@link RepeatableContainers} instance that uses predefined <add> * repeatable and container types. <add> * @param repeatable the contained repeatable annotation type <add> * @param container the container annotation type or {@code null}. If specified, <ide> * this annotation must declare a {@code value} attribute returning an array <ide> * of repeatable annotations. If not specified, the container will be <ide> * deduced by inspecting the {@code @Repeatable} annotation on <ide> * {@code repeatable}. <ide> * @return a {@link RepeatableContainers} instance <add> * @throws IllegalArgumentException if the supplied container type is <add> * {@code null} and the annotation type is not a repeatable annotation <add> * @throws AnnotationConfigurationException if the supplied container type <add> * is not a properly configured container for a repeatable annotation <ide> */ <ide> public static RepeatableContainers of( <ide> Class<? extends Annotation> repeatable, @Nullable Class<? extends Annotation> container) {
1
Python
Python
use aligned memory for dot() out= arrays
7886906af7cccdde892db7be8f8ae53fd5266d95
<ide><path>numpy/core/tests/test_multiarray.py <ide> import operator <ide> import io <ide> import itertools <add>import functools <ide> import ctypes <ide> import os <ide> import gc <ide> EMPTY = None <ide> <ide> <add>def _aligned_zeros(shape, dtype=float, order="C", align=None): <add> """Allocate a new ndarray with aligned memory.""" <add> dtype = np.dtype(dtype) <add> if dtype == np.dtype(object): <add> # Can't do this, fall back to standard allocation (which <add> # should always be sufficiently aligned) <add> if align is not None: <add> raise ValueError("object array alignment not supported") <add> return np.zeros(shape, dtype=dtype, order=order) <add> if align is None: <add> align = dtype.alignment <add> if not hasattr(shape, '__len__'): <add> shape = (shape,) <add> size = functools.reduce(operator.mul, shape) * dtype.itemsize <add> buf = np.empty(size + align + 1, np.uint8) <add> offset = buf.__array_interface__['data'][0] % align <add> if offset != 0: <add> offset = align - offset <add> # Note: slices producing 0-size arrays do not necessarily change <add> # data pointer --- so we use and allocate size+1 <add> buf = buf[offset:offset+size+1][:-1] <add> data = np.ndarray(shape, dtype, buf, order=order) <add> data.fill(0) <add> return data <add> <add> <ide> class TestFlags(TestCase): <ide> def setUp(self): <ide> self.a = np.arange(10) <ide> def test_dot_out_mem_overlap(self): <ide> if code not in 'USVM'] <ide> for dtype in dtypes: <ide> a = np.random.rand(3, 3).astype(dtype) <del> b = np.random.rand(3, 3).astype(dtype) <add> <add> # Valid dot() output arrays must be aligned <add> b = _aligned_zeros((3, 3), dtype=dtype) <add> b[...] = np.random.rand(3, 3) <add> <ide> y = np.dot(a, b) <ide> x = np.dot(a, b, out=b) <ide> assert_equal(x, y, err_msg=repr(dtype))
1
Ruby
Ruby
remove duplication by extracting methods
6175f73f6384be6581c8ba8a117e2d3d5dcde541
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/transaction.rb <ide> def restore! <ide> def rollback_records <ide> return unless records <ide> <del> ite = records.uniq(&:__id__) <add> ite = unique_records <add> <ide> instances_to_run_callbacks_on = prepare_instances_to_run_callbacks_on(ite) <ide> <del> while record = ite.shift <del> should_run_callbacks = record.__id__ == instances_to_run_callbacks_on[record].__id__ <add> run_action_on_records(ite, instances_to_run_callbacks_on) do |record, should_run_callbacks| <ide> record.rolledback!(force_restore_state: full_rollback?, should_run_callbacks: should_run_callbacks) <ide> end <ide> ensure <ide> def rollback_records <ide> def before_commit_records <ide> return unless records <ide> <del> ite = records.uniq(&:__id__) <del> <ide> if @run_commit_callbacks <del> instances_to_run_callbacks_on = records.each_with_object({}) do |record, candidates| <add> ite = unique_records <add> <add> instances_to_run_callbacks_on = ite.each_with_object({}) do |record, candidates| <ide> candidates[record] = record <ide> end <ide> <del> while record = ite.shift <del> should_run_callbacks = record.__id__ == instances_to_run_callbacks_on[record].__id__ <add> run_action_on_records(ite, instances_to_run_callbacks_on) do |record, should_run_callbacks| <ide> record.before_committed! if should_run_callbacks <ide> end <ide> end <ide> def before_commit_records <ide> def commit_records <ide> return unless records <ide> <del> ite = records.uniq(&:__id__) <add> ite = unique_records <ide> <ide> if @run_commit_callbacks <ide> instances_to_run_callbacks_on = prepare_instances_to_run_callbacks_on(ite) <ide> <del> while record = ite.shift <del> should_run_callbacks = record.__id__ == instances_to_run_callbacks_on[record].__id__ <add> run_action_on_records(ite, instances_to_run_callbacks_on) do |record, should_run_callbacks| <ide> record.committed!(should_run_callbacks: should_run_callbacks) <ide> end <ide> else <ide> def closed?; false; end <ide> def open?; !closed?; end <ide> <ide> private <add> def unique_records <add> records.uniq(&:__id__) <add> end <add> <add> def run_action_on_records(records, instances_to_run_callbacks_on) <add> while record = records.shift <add> should_run_callbacks = record.__id__ == instances_to_run_callbacks_on[record].__id__ <add> <add> yield record, should_run_callbacks <add> end <add> end <add> <ide> def prepare_instances_to_run_callbacks_on(records) <ide> records.each_with_object({}) do |record, candidates| <ide> next unless record.trigger_transactional_callbacks?
1
Javascript
Javascript
add textcontenttype to onboarding flow
c59da6eae88690c5cd0071d88f933b0e88e9c97b
<ide><path>Libraries/Components/TextInput/TextInput.js <ide> export type ReturnKeyType = <ide> <ide> export type AutoCapitalize = 'none' | 'sentences' | 'words' | 'characters'; <ide> <add>export type TextContentType = <add> | 'none' <add> | 'URL' <add> | 'addressCity' <add> | 'addressCityAndState' <add> | 'addressState' <add> | 'countryName' <add> | 'creditCardNumber' <add> | 'emailAddress' <add> | 'familyName' <add> | 'fullStreetAddress' <add> | 'givenName' <add> | 'jobTitle' <add> | 'location' <add> | 'middleName' <add> | 'name' <add> | 'namePrefix' <add> | 'nameSuffix' <add> | 'nickname' <add> | 'organizationName' <add> | 'postalCode' <add> | 'streetAddressLine1' <add> | 'streetAddressLine2' <add> | 'sublocality' <add> | 'telephoneNumber' <add> | 'username' <add> | 'password' <add> | 'newPassword' <add> | 'oneTimeCode'; <add> <ide> type IOSProps = $ReadOnly<{| <ide> spellCheck?: ?boolean, <ide> keyboardAppearance?: ?('default' | 'light' | 'dark'), <ide> type IOSProps = $ReadOnly<{| <ide> | ?DataDetectorTypesType <ide> | $ReadOnlyArray<DataDetectorTypesType>, <ide> inputAccessoryViewID?: ?string, <del> textContentType?: ?( <del> | 'none' <del> | 'URL' <del> | 'addressCity' <del> | 'addressCityAndState' <del> | 'addressState' <del> | 'countryName' <del> | 'creditCardNumber' <del> | 'emailAddress' <del> | 'familyName' <del> | 'fullStreetAddress' <del> | 'givenName' <del> | 'jobTitle' <del> | 'location' <del> | 'middleName' <del> | 'name' <del> | 'namePrefix' <del> | 'nameSuffix' <del> | 'nickname' <del> | 'organizationName' <del> | 'postalCode' <del> | 'streetAddressLine1' <del> | 'streetAddressLine2' <del> | 'sublocality' <del> | 'telephoneNumber' <del> | 'username' <del> | 'password' <del> | 'newPassword' <del> | 'oneTimeCode' <del> ), <add> textContentType?: ?TextContentType, <ide> scrollEnabled?: ?boolean, <ide> |}>; <ide>
1
Python
Python
skip mapping against mapped ti if it returns none
6383a2772bac463bb1335cea2ad4554a3f94c6f7
<ide><path>airflow/models/taskinstance.py <ide> def _record_task_map_for_downstreams(self, task: "Operator", value: Any, *, sess <ide> validators = {m.validate_upstream_return_value for m in task.iter_mapped_dependants()} <ide> if not validators: # No mapped dependants, no need to validate. <ide> return <del> if value is None: <del> raise XComForMappingNotPushed() <ide> # TODO: We don't push TaskMap for mapped task instances because it's not <ide> # currently possible for a downstream to depend on one individual mapped <ide> # task instance. This will change when we implement task group mapping, <ide> # and we'll need to further analyze the mapped task case. <ide> if task.is_mapped: <ide> return <add> if value is None: <add> raise XComForMappingNotPushed() <ide> for validator in validators: <ide> validator(value) <ide> assert isinstance(value, collections.abc.Collection) # The validators type-guard this. <ide><path>tests/models/test_taskinstance.py <ide> def add_one(x): <ide> assert [x.value for x in query.order_by(None).order_by(XCom.map_index)] == [3, 4, 5] <ide> <ide> <del>def test_ti_mapped_depends_on_mapped_xcom_arg_XXX(dag_maker, session): <del> with dag_maker(session=session) as dag: <add>def test_mapped_upstream_return_none_should_skip(dag_maker, session): <add> results = set() <ide> <del> @dag.task <del> def add_one(x): <del> x + 1 <add> with dag_maker(dag_id="test_mapped_upstream_return_none_should_skip", session=session) as dag: <ide> <del> two_three_four = add_one.expand(x=[1, 2, 3]) <del> add_one.expand(x=two_three_four) <add> @dag.task() <add> def transform(value): <add> if value == "b": # Now downstream doesn't map against this! <add> return None <add> return value <ide> <del> dagrun = dag_maker.create_dagrun() <del> for map_index in range(3): <del> ti = dagrun.get_task_instance("add_one", map_index=map_index) <del> ti.refresh_from_task(dag.get_task("add_one")) <del> with pytest.raises(XComForMappingNotPushed): <del> ti.run() <add> @dag.task() <add> def pull(value): <add> results.add(value) <add> <add> original = ["a", "b", "c"] <add> transformed = transform.expand(value=original) # ["a", None, "c"] <add> pull.expand(value=transformed) # ["a", "c"] <add> <add> dr = dag_maker.create_dagrun() <add> <add> decision = dr.task_instance_scheduling_decisions(session=session) <add> tis = {(ti.task_id, ti.map_index): ti for ti in decision.schedulable_tis} <add> assert sorted(tis) == [("transform", 0), ("transform", 1), ("transform", 2)] <add> for ti in tis.values(): <add> ti.run() <add> <add> decision = dr.task_instance_scheduling_decisions(session=session) <add> tis = {(ti.task_id, ti.map_index): ti for ti in decision.schedulable_tis} <add> assert sorted(tis) == [("pull", 0), ("pull", 1)] <add> for ti in tis.values(): <add> ti.run() <add> <add> assert results == {"a", "c"} <ide> <ide> <ide> def test_expand_non_templated_field(dag_maker, session):
2
Go
Go
fix plugin restart on docker restart
ab12ed4a5642edb4d96b54b6152f12260093f3ea
<ide><path>plugin/backend.go <ide> func (pm *Manager) Enable(name string) error { <ide> if err != nil { <ide> return err <ide> } <del> if err := pm.enable(p); err != nil { <add> if err := pm.enable(p, false); err != nil { <ide> return err <ide> } <ide> pm.pluginEventLogger(p.PluginObj.ID, name, "enable") <ide><path>plugin/manager.go <ide> func (pm *Manager) init() error { <ide> <ide> if requiresManualRestore { <ide> // if liveRestore is not enabled, the plugin will be stopped now so we should enable it <del> if err := pm.enable(p); err != nil { <add> if err := pm.enable(p, true); err != nil { <ide> logrus.Errorf("failed to enable plugin '%s': %s", p.Name(), err) <ide> } <ide> } <ide><path>plugin/manager_linux.go <ide> import ( <ide> "github.com/opencontainers/specs/specs-go" <ide> ) <ide> <del>func (pm *Manager) enable(p *plugin) error { <del> if p.PluginObj.Active { <add>func (pm *Manager) enable(p *plugin, force bool) error { <add> if p.PluginObj.Active && !force { <ide> return fmt.Errorf("plugin %s is already enabled", p.Name()) <ide> } <ide> spec, err := pm.initSpec(p) <ide><path>plugin/manager_windows.go <ide> import ( <ide> "github.com/opencontainers/specs/specs-go" <ide> ) <ide> <del>func (pm *Manager) enable(p *plugin) error { <add>func (pm *Manager) enable(p *plugin, force bool) error { <ide> return fmt.Errorf("Not implemented") <ide> } <ide>
4
Javascript
Javascript
add warning if return pointer is inconsistent
15df051c94533c70b065d51c41cf9b6b2f1dc6a6
<ide><path>packages/react-dom/src/__tests__/ReactWrongReturnPointer-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> */ <add> <add>let React; <add>let ReactNoop; <add> <add>beforeEach(() => { <add> React = require('react'); <add> ReactNoop = require('react-noop-renderer'); <add>}); <add> <add>// Don't feel too guilty if you have to delete this test. <add>// @gate new <add>// @gate __DEV__ <add>test('warns in DEV if return pointer is inconsistent', async () => { <add> const {useRef, useLayoutEffect} = React; <add> <add> let ref = null; <add> function App({text}) { <add> ref = useRef(null); <add> return ( <add> <> <add> <Sibling text={text} /> <add> <div ref={ref}>{text}</div> <add> </> <add> ); <add> } <add> <add> function Sibling({text}) { <add> useLayoutEffect(() => { <add> if (text === 'B') { <add> // Mutate the return pointer of the div to point to the wrong alternate. <add> // This simulates the most common type of return pointer inconsistency. <add> const current = ref.current.fiber; <add> const workInProgress = current.alternate; <add> workInProgress.return = current.return; <add> } <add> }, [text]); <add> return null; <add> } <add> <add> const root = ReactNoop.createRoot(); <add> await ReactNoop.act(async () => { <add> root.render(<App text="A" />); <add> }); <add> <add> spyOnDev(console, 'error'); <add> await ReactNoop.act(async () => { <add> root.render(<App text="B" />); <add> }); <add> expect(console.error.calls.count()).toBe(1); <add> expect(console.error.calls.argsFor(0)[0]).toMatch( <add> 'Internal React error: Return pointer is inconsistent with parent.', <add> ); <add>}); <ide><path>packages/react-noop-renderer/src/createReactNoop.js <ide> function createReactNoop(reconciler: Function, useMutation: boolean) { <ide> props: Props, <ide> rootContainerInstance: Container, <ide> hostContext: HostContext, <add> internalInstanceHandle: Object, <ide> ): Instance { <ide> if (type === 'errorInCompletePhase') { <ide> throw new Error('Error in host config.'); <ide> function createReactNoop(reconciler: Function, useMutation: boolean) { <ide> value: inst.context, <ide> enumerable: false, <ide> }); <add> Object.defineProperty(inst, 'fiber', { <add> value: internalInstanceHandle, <add> enumerable: false, <add> }); <ide> return inst; <ide> }, <ide> <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js <ide> function iterativelyCommitBeforeMutationEffects_begin() { <ide> (fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && <ide> child !== null <ide> ) { <add> warnIfWrongReturnPointer(fiber, child); <ide> nextEffect = child; <ide> } else { <ide> iterativelyCommitBeforeMutationEffects_complete(); <ide> function iterativelyCommitBeforeMutationEffects_complete() { <ide> <ide> const sibling = fiber.sibling; <ide> if (sibling !== null) { <add> warnIfWrongReturnPointer(fiber.return, sibling); <ide> nextEffect = sibling; <ide> return; <ide> } <ide> function iterativelyCommitMutationEffects_begin( <ide> <ide> const child = fiber.child; <ide> if ((fiber.subtreeFlags & MutationMask) !== NoFlags && child !== null) { <add> warnIfWrongReturnPointer(fiber, child); <ide> nextEffect = child; <ide> } else { <ide> iterativelyCommitMutationEffects_complete(root, renderPriorityLevel); <ide> function iterativelyCommitMutationEffects_complete( <ide> <ide> const sibling = fiber.sibling; <ide> if (sibling !== null) { <add> warnIfWrongReturnPointer(fiber.return, sibling); <ide> nextEffect = sibling; <ide> return; <ide> } <ide> function iterativelyCommitLayoutEffects_begin( <ide> } <ide> const sibling = finishedWork.sibling; <ide> if (sibling !== null) { <add> warnIfWrongReturnPointer(finishedWork.return, sibling); <ide> nextEffect = sibling; <ide> } else { <ide> nextEffect = finishedWork.return; <ide> iterativelyCommitLayoutEffects_complete(subtreeRoot, finishedRoot); <ide> } <ide> } else { <add> warnIfWrongReturnPointer(finishedWork, firstChild); <ide> nextEffect = firstChild; <ide> } <ide> } else { <ide> function iterativelyCommitLayoutEffects_complete( <ide> <ide> const sibling = fiber.sibling; <ide> if (sibling !== null) { <add> warnIfWrongReturnPointer(fiber.return, sibling); <ide> nextEffect = sibling; <ide> return; <ide> } <ide> function iterativelyCommitPassiveMountEffects_begin( <ide> } <ide> const sibling = fiber.sibling; <ide> if (sibling !== null) { <add> warnIfWrongReturnPointer(fiber.return, sibling); <ide> nextEffect = sibling; <ide> } else { <ide> nextEffect = fiber.return; <ide> iterativelyCommitPassiveMountEffects_complete(subtreeRoot, root); <ide> } <ide> } else { <add> warnIfWrongReturnPointer(fiber, firstChild); <ide> nextEffect = firstChild; <ide> } <ide> } else { <ide> function iterativelyCommitPassiveMountEffects_complete( <ide> <ide> const sibling = fiber.sibling; <ide> if (sibling !== null) { <add> warnIfWrongReturnPointer(fiber.return, sibling); <ide> nextEffect = sibling; <ide> return; <ide> } <ide> function iterativelyCommitPassiveUnmountEffects_begin() { <ide> } <ide> <ide> if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { <add> warnIfWrongReturnPointer(fiber, child); <ide> nextEffect = child; <ide> } else { <ide> iterativelyCommitPassiveUnmountEffects_complete(); <ide> function iterativelyCommitPassiveUnmountEffects_complete() { <ide> <ide> const sibling = fiber.sibling; <ide> if (sibling !== null) { <add> warnIfWrongReturnPointer(fiber.return, sibling); <ide> nextEffect = sibling; <ide> return; <ide> } <ide> function iterativelyCommitPassiveUnmountEffectsInsideOfDeletedTree_begin( <ide> const fiber = nextEffect; <ide> const child = fiber.child; <ide> if ((fiber.subtreeFlags & PassiveStatic) !== NoFlags && child !== null) { <add> warnIfWrongReturnPointer(fiber, child); <ide> nextEffect = child; <ide> } else { <ide> iterativelyCommitPassiveUnmountEffectsInsideOfDeletedTree_complete( <ide> function iterativelyCommitPassiveUnmountEffectsInsideOfDeletedTree_complete( <ide> <ide> const sibling = fiber.sibling; <ide> if (sibling !== null) { <add> warnIfWrongReturnPointer(fiber.return, sibling); <ide> nextEffect = sibling; <ide> return; <ide> } <ide> function invokeEffectsInDev( <ide> } <ide> } <ide> } <add> <add>let didWarnWrongReturnPointer = false; <add>function warnIfWrongReturnPointer(returnFiber, child) { <add> if (__DEV__) { <add> if (!didWarnWrongReturnPointer && child.return !== returnFiber) { <add> didWarnWrongReturnPointer = true; <add> console.error( <add> 'Internal React error: Return pointer is inconsistent ' + <add> 'with parent.', <add> ); <add> } <add> } <add>}
3
Text
Text
clarify introductory module material
65a53c6f1b14b6d1339cbc45894f3de540a3a21b
<ide><path>doc/api/modules.md <ide> <ide> Node.js has a simple module loading system. In Node.js, files and modules <ide> are in one-to-one correspondence (each file is treated as a separate module). <del>As an example, `foo.js` loads the module `circle.js` in the same directory. <ide> <del>The contents of `foo.js`: <add>As an example, consider a file named `foo.js`: <ide> <ide> ```js <ide> const circle = require('./circle.js'); <ide> console.log(`The area of a circle of radius 4 is ${circle.area(4)}`); <ide> ``` <ide> <del>The contents of `circle.js`: <add>On the first line, `foo.js` loads the module `circle.js` that is in the same <add>directory as `foo.js`. <add> <add>Here are the contents of `circle.js`: <ide> <ide> ```js <ide> const PI = Math.PI; <ide> <ide> exports.area = (r) => PI * r * r; <ide> <ide> exports.circumference = (r) => 2 * PI * r; <del> <ide> ``` <ide> <ide> The module `circle.js` has exported the functions `area()` and
1
Text
Text
remove mdx tags from `readme.md`
c23d54fd261b34ff947a18170a303a305179e7bd
<ide><path>website/README.md <ide> rendered version is available at https://spacy.io/styleguide._ <ide> <ide> </Comment> <ide> <del>## Setup and installation {#setup} <add>## Setup and installation <ide> <ide> Before running the setup, make sure your versions of <ide> [Node](https://nodejs.org/en/) and [npm](https://www.npmjs.com/) are up to date. <ide> extensions for your code editor. The <ide> [`.prettierrc`](https://github.com/explosion/spaCy/tree/master/website/.prettierrc) <ide> file in the root defines the settings used in this codebase. <ide> <del>## Building & developing the site with Docker {#docker} <add>## Building & developing the site with Docker <ide> <ide> Sometimes it's hard to get a local environment working due to rapid updates to <ide> node dependencies, so it may be easier to use docker for building the docs. <ide> segfault errors from `qemu` if you use the default image. To fix this use the <ide> `arm64` tagged image in the `docker run` command <ide> (ghcr.io/explosion/spacy-io:arm64). <ide> <del>### Building the Docker image {#docker-build} <add>### Building the Docker image <ide> <ide> If you'd like to build the image locally, you can do so like this: <ide> <ide> docker build -t spacy-io . <ide> This will take some time, so if you want to use the prebuilt image you'll save a <ide> bit of time. <ide> <del>## Project structure {#structure} <add>## Project structure <ide> <ide> ```yaml <del>### Directory structure <ide> ├── docs # the actual markdown content <ide> ├── meta # JSON-formatted site metadata <ide> | ├── languages.json # supported languages and statistical models
1
Javascript
Javascript
avoid multiple textureloaders in for-loops
8ab4529129cfb80afdc35f18db505fc404ecca87
<ide><path>examples/js/MD2Character.js <ide> THREE.MD2Character = function () { <ide> <ide> function loadTextures( baseUrl, textureUrls ) { <ide> <del> var mapping = THREE.UVMapping; <add> var textureLoader = new THREE.TextureLoader(); <ide> var textures = []; <ide> <ide> for ( var i = 0; i < textureUrls.length; i ++ ) { <ide> <del> textures[ i ] = new THREE.TextureLoader().load( baseUrl + textureUrls[ i ], checkLoadingComplete ); <del> textures[ i ].mapping = mapping; <add> textures[ i ] = textureLoader.load( baseUrl + textureUrls[ i ], checkLoadingComplete ); <add> textures[ i ].mapping = THREE.UVMapping; <ide> textures[ i ].name = textureUrls[ i ]; <ide> <ide> } <ide><path>examples/js/MD2CharacterComplex.js <ide> THREE.MD2CharacterComplex = function () { <ide> <ide> function loadTextures( baseUrl, textureUrls ) { <ide> <del> var mapping = THREE.UVMapping; <add> var textureLoader = new THREE.TextureLoader(); <ide> var textures = []; <ide> <ide> for ( var i = 0; i < textureUrls.length; i ++ ) { <del> <del> textures[ i ] = new THREE.TextureLoader().load( baseUrl + textureUrls[ i ], checkLoadingComplete ); <del> textures[ i ].mapping = mapping; <add> <add> textures[ i ] = textureLoader.load( baseUrl + textureUrls[ i ], checkLoadingComplete ); <add> textures[ i ].mapping = THREE.UVMapping; <ide> textures[ i ].name = textureUrls[ i ]; <ide> <ide> } <ide><path>examples/js/UCSCharacter.js <ide> THREE.UCSCharacter = function() { <ide> <ide> function loadTextures( baseUrl, textureUrls ) { <ide> <del> var mapping = THREE.UVMapping; <add> var textureLoader = new THREE.TextureLoader(); <ide> var textures = []; <ide> <ide> for ( var i = 0; i < textureUrls.length; i ++ ) { <ide> <del> textures[ i ] = new THREE.TextureLoader().load( baseUrl + textureUrls[ i ], scope.checkLoadingComplete ); <del> textures[ i ].mapping = mapping; <add> textures[ i ] = textureLoader.load( baseUrl + textureUrls[ i ], scope.checkLoadingComplete ); <add> textures[ i ].mapping = THREE.UVMapping; <ide> textures[ i ].name = textureUrls[ i ]; <ide> <ide> }
3
Go
Go
add test for event limitation
46747963b603a5573a0b26dcef407a96757926e7
<ide><path>integration-cli/docker_cli_events_test.go <ide> package main <ide> import ( <ide> "fmt" <ide> "os/exec" <add> "strconv" <ide> "strings" <ide> "testing" <ide> "time" <ide> func TestCLIGetEventsPause(t *testing.T) { <ide> <ide> logDone("events - pause/unpause is logged") <ide> } <add> <add>func TestCLILimitEvents(t *testing.T) { <add> for i := 0; i < 30; i++ { <add> cmd(t, "run", "busybox", "echo", strconv.Itoa(i)) <add> } <add> eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", time.Now().Unix())) <add> out, _, _ := runCommandWithOutput(eventsCmd) <add> events := strings.Split(out, "\n") <add> n_events := len(events) - 1 <add> if n_events > 64 { <add> t.Fatalf("events should be limited to 64, but received %d", n_events) <add> } <add> logDone("events - limited to 64 entries") <add>}
1
Go
Go
add support for freebsd in portallocator
047f7c0793a335e0c69d503e55a5ca48d0af2de1
<ide><path>libnetwork/portallocator/portallocator_freebsd.go <add>package portallocator <add> <add>import ( <add> "bytes" <add> "fmt" <add> "os/exec" <add>) <add> <add>func getDynamicPortRange() (start int, end int, err error) { <add> portRangeKernelSysctl := []string{"net.inet.ip.portrange.hifirst", "net.ip.portrange.hilast"} <add> portRangeFallback := fmt.Sprintf("using fallback port range %d-%d", DefaultPortRangeStart, DefaultPortRangeEnd) <add> portRangeLowCmd := exec.Command("/sbin/sysctl", portRangeKernelSysctl[0]) <add> var portRangeLowOut bytes.Buffer <add> portRangeLowCmd.Stdout = &portRangeLowOut <add> cmdErr := portRangeLowCmd.Run() <add> if cmdErr != nil { <add> return 0, 0, fmt.Errorf("port allocator - sysctl net.inet.ip.portrange.hifirst failed - %s: %v", portRangeFallback, err) <add> } <add> n, err := fmt.Sscanf(portRangeLowOut.String(), "%d", &start) <add> if n != 1 || err != nil { <add> if err == nil { <add> err = fmt.Errorf("unexpected count of parsed numbers (%d)", n) <add> } <add> return 0, 0, fmt.Errorf("port allocator - failed to parse system ephemeral port range start from %s - %s: %v", portRangeLowOut.String(), portRangeFallback, err) <add> } <add> <add> portRangeHighCmd := exec.Command("/sbin/sysctl", portRangeKernelSysctl[1]) <add> var portRangeHighOut bytes.Buffer <add> portRangeHighCmd.Stdout = &portRangeHighOut <add> cmdErr = portRangeHighCmd.Run() <add> if cmdErr != nil { <add> return 0, 0, fmt.Errorf("port allocator - sysctl net.inet.ip.portrange.hilast failed - %s: %v", portRangeFallback, err) <add> } <add> n, err = fmt.Sscanf(portRangeHighOut.String(), "%d", &end) <add> if n != 1 || err != nil { <add> if err == nil { <add> err = fmt.Errorf("unexpected count of parsed numbers (%d)", n) <add> } <add> return 0, 0, fmt.Errorf("port allocator - failed to parse system ephemeral port range end from %s - %s: %v", portRangeHighOut.String(), portRangeFallback, err) <add> } <add> return start, end, nil <add>}
1
PHP
PHP
fix datetime fields not being secured
64e63371b450fc02b53b807c8613a9a252c8c0f5
<ide><path>src/View/Helper/FormHelper.php <ide> public function create($model = null, $options = []) { <ide> if (!empty($append)) { <ide> $append = $templater->format('hiddenblock', ['content' => $append]); <ide> } <del> <ide> $this->_lastAction = $action; <ide> if (strpos($action, '://')) { <ide> $query = parse_url($action, PHP_URL_QUERY); <ide> public function dateTime($fieldName, array $options = array()) { <ide> 'timeFormat' => 24, <ide> 'second' => false, <ide> ]; <add> $secure = true; <add> if (isset($options['secure'])) { <add> $secure = $options['secure']; <add> } <add> $options['secure'] = static::SECURE_SKIP; <add> <ide> $options = $this->_initInputField($fieldName, $options); <ide> $options = $this->_datetimeOptions($options); <ide> <add> foreach ($this->_datetimeParts as $type) { <add> if ($options[$type] !== false) { <add> $this->_secure($secure, $fieldName . '.' . $type); <add> } <add> } <add> <ide> return $this->widget('datetime', $options); <ide> } <ide> <ide> public function date($fieldName, array $options = []) { <ide> ]; <ide> $options['hour'] = $options['minute'] = false; <ide> $options['meridian'] = $options['second'] = false; <add> <add> $secure = true; <add> if (isset($options['secure'])) { <add> $secure = $options['secure']; <add> } <add> $options['secure'] = static::SECURE_SKIP; <add> <ide> $options = $this->_initInputField($fieldName, $options); <ide> $options = $this->_datetimeOptions($options); <ide> <add> foreach ($this->_datetimeParts as $type) { <add> if ($options[$type] !== false) { <add> $this->_secure($secure, $fieldName . '.' . $type); <add> } <add> } <add> <ide> return $this->widget('datetime', $options); <ide> } <ide> <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testDateTime() { <ide> $this->assertTags($result, $expected); <ide> } <ide> <add>/** <add> * Test that datetime fields are added to protected fields list. <add> * <add> * @return void <add> */ <add> public function testDateTimeSecured() { <add> $this->Form->request->params['_Token'] = ['unlockedFields' => []]; <add> $this->Form->dateTime('Contact.date'); <add> $expected = [ <add> 'Contact.date.year', <add> 'Contact.date.month', <add> 'Contact.date.day', <add> 'Contact.date.hour', <add> 'Contact.date.minute', <add> 'Contact.date.meridian', <add> ]; <add> $this->assertEquals($expected, $this->Form->fields); <add> <add> $this->Form->fields = []; <add> $this->Form->date('Contact.published'); <add> $expected = [ <add> 'Contact.published.year', <add> 'Contact.published.month', <add> 'Contact.published.day', <add> ]; <add> $this->assertEquals($expected, $this->Form->fields); <add> } <add> <ide> /** <ide> * Test empty defaulting to true for datetime. <ide> *
2
Text
Text
fix broken links in readme
21349d63f9ba40c4928b62f01a69b4668a7968c5
<ide><path>README.md <ide> React Native apps may target iOS 10.0 and Android 4.1 (API 16) or newer. You may <ide> <ide> ## 🎉 Building your first React Native app <ide> <del>Follow the [Getting Started guide](https://reactnative.dev/docs/getting-started.html). The recommended way to install React Native depends on your project. Here you can find short guides for the most common scenarios: <add>Follow the [Getting Started guide](https://reactnative.dev/docs/getting-started). The recommended way to install React Native depends on your project. Here you can find short guides for the most common scenarios: <ide> <ide> - [Trying out React Native][hello-world] <ide> - [Creating a New Application][new-app] <ide> - [Adding React Native to an Existing Application][existing] <ide> <ide> [hello-world]: https://snack.expo.io/@hramos/hello,-world! <del>[new-app]: https://reactnative.dev/docs/getting-started.html <del>[existing]: https://reactnative.dev/docs/integration-with-existing-apps.html <add>[new-app]: https://reactnative.dev/docs/getting-started <add>[existing]: https://reactnative.dev/docs/integration-with-existing-apps <ide> <ide> ## 📖 Documentation <ide> <ide> The React Native documentation discusses components, APIs, and topics that are s <ide> <ide> The source for the React Native documentation and website is hosted on a separate repo, [**@facebook/react-native-website**][repo-website]. <ide> <del>[docs]: https://reactnative.dev/docs/getting-started.html <add>[docs]: https://reactnative.dev/docs/getting-started <ide> [r-docs]: https://reactjs.org/docs/getting-started.html <ide> [repo-website]: https://github.com/facebook/react-native-website <ide>
1
Javascript
Javascript
fix regex escaping in route matcher
2bc39bb0b4f81b77597bb52f8572d231cf4f83e2
<ide><path>src/service/route.js <ide> angularServiceInject('$route', function($location, $routeParams) { <ide> ///////////////////////////////////////////////////// <ide> <ide> function switchRouteMatcher(on, when) { <del> var regex = '^' + when.replace(/[\.\\\(\)\^\$]/g, "\$1") + '$', <add> // TODO(i): this code is convoluted and inefficient, we should construct the route matching <add> // regex only once and then reuse it <add> var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$', <ide> params = [], <ide> dst = {}; <ide> forEach(when.split(/\W/), function(param) { <ide> if (param) { <ide> var paramRegExp = new RegExp(":" + param + "([\\W])"); <ide> if (regex.match(paramRegExp)) { <del> regex = regex.replace(paramRegExp, "([^\/]*)$1"); <add> regex = regex.replace(paramRegExp, "([^\\/]*)$1"); <ide> params.push(param); <ide> } <ide> } <ide><path>test/service/routeSpec.js <ide> describe('$route', function() { <ide> }); <ide> <ide> <add> it('should match a route that contains special chars in the path', function() { <add> $route.when('/$test.23/foo(bar)/:baz', {template: 'test.html'}); <add> <add> $location.path('/test'); <add> scope.$digest(); <add> expect($route.current).toBeUndefined(); <add> <add> $location.path('/$testX23/foo(bar)/222'); <add> scope.$digest(); <add> expect($route.current).toBeUndefined(); <add> <add> $location.path('/$test.23/foo(bar)/222'); <add> scope.$digest(); <add> expect($route.current).toBeDefined(); <add> <add> $location.path('/$test.23/foo\\(bar)/222'); <add> scope.$digest(); <add> expect($route.current).toBeUndefined(); <add> }); <add> <add> <ide> it('should change route even when only search param changes', function() { <ide> var callback = jasmine.createSpy('onRouteChange'); <ide>
2
Text
Text
replace weak links with config names
87b7ca3e0a0ac1db33a17c538f2d63a6884f7b5c
<ide><path>guides/source/active_storage_overview.md <ide> location. <ide> <%= image_tag user.avatar.variant(resize_to_limit: [100, 100]) %> <ide> ``` <ide> <del>If a variant is requested, Active Storage will automatically apply <add>If a variant is requested, Active Storage will automatically apply <ide> transformations depending on the image's format: <ide> <del>1. Content types that are [`variable`] and not considered [`web images`], will be converted to PNG. <del>2. If `quality` is not specified, the variant processor's default quality for the format will be used. <add>1. Content types that are variable (as dictated by `config.active_storage.variable_content_types`) <add> and not considered web images (as dictated by `config.active_storage.web_image_content_types`), <add> will be converted to PNG. <add> <add>2. If `quality` is not specified, the variant processor's default quality for the format will be used. <ide> <ide> The default processor for Active Storage is MiniMagick, but you can also use <ide> [Vips][]. To switch to Vips, add the following to `config/application.rb`: <ide> specific: <ide> ``` <ide> <ide> [`variant`]: https://api.rubyonrails.org/classes/ActiveStorage/Blob/Representable.html#method-i-variant <del>[`web images`]: https://github.com/rails/rails/blob/main/activestorage/lib/active_storage/engine.rb#L47 <del>[`variable`]: https://github.com/rails/rails/blob/main/activestorage/lib/active_storage/engine.rb#L34 <ide> [Vips]: https://www.rubydoc.info/gems/ruby-vips/Vips/Image <ide> <ide> ### Previewing Files
1
Text
Text
fix typo in autoloading docs
4f91215ce9bc473827d62d522076abecf17eba2c
<ide><path>guides/source/autoloading_and_reloading_constants.md <ide> ApiGateway.endpoint = "https://example.com" # DO NOT DO THIS <ide> <ide> a reloaded `ApiGateway` would have a `nil` endpoint, because the code above does not run again. <ide> <del>You can still set things up during boot, but you need to wrap them in a `to_prepare` block, which is runs on boot, and after each reload: <add>You can still set things up during boot, but you need to wrap them in a `to_prepare` block, which runs on boot, and after each reload: <ide> <ide> ```ruby <ide> # config/initializers/api_gateway_setup.rb
1
Java
Java
update scrollview ctor's to take a reactcontext
2cf2fdbc04bc5309f6942ed464ad61cd06a26ce8
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java <ide> <ide> import java.lang.reflect.Field; <ide> <del>import android.content.Context; <ide> import android.graphics.Canvas; <ide> import android.graphics.Color; <ide> import android.graphics.Rect; <ide> import android.widget.OverScroller; <ide> import android.widget.ScrollView; <ide> <add>import com.facebook.react.bridge.ReactContext; <ide> import com.facebook.react.common.ReactConstants; <ide> import com.facebook.react.uimanager.MeasureSpecAssertions; <ide> import com.facebook.react.uimanager.events.NativeGestureUtil; <ide> public class ReactScrollView extends ScrollView implements ReactClippingViewGrou <ide> private @Nullable Drawable mEndBackground; <ide> private int mEndFillColor = Color.TRANSPARENT; <ide> <del> public ReactScrollView(Context context) { <add> public ReactScrollView(ReactContext context) { <ide> this(context, null); <ide> } <ide> <del> public ReactScrollView(Context context, @Nullable FpsListener fpsListener) { <add> public ReactScrollView(ReactContext context, @Nullable FpsListener fpsListener) { <ide> super(context); <ide> mFpsListener = fpsListener; <ide>
1
PHP
PHP
add space between lines
d6545c568dffad637e3465dea0e6745025531a45
<ide><path>src/Illuminate/Cache/Section.php <ide> public function sectionItemKey($key) <ide> protected function reset() <ide> { <ide> $this->store->forever($this->sectionKey(), $id = uniqid()); <add> <ide> return $id; <ide> } <ide>
1
Javascript
Javascript
add some tests for ngrequired
2230fb4c1098b8c034cd43bdaa49f8f5747759c8
<ide><path>test/ng/directive/inputSpec.js <ide> describe('input', function() { <ide> }); <ide> }); <ide> <add> describe('ngRequired', function() { <add> <add> describe('when the ngRequired expression initially evaluates to true', function() { <add> <add> it('should be valid even if value is 0', function() { <add> compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="true" />'); <add> <add> changeInputValueTo('0'); <add> expect(inputElm).toBeValid(); <add> expect(scope.value).toBe(0); <add> expect(scope.form.numberInput.$error.required).toBeFalsy(); <add> }); <add> <add> it('should be valid even if value 0 is set from model', function() { <add> compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="true" />'); <add> <add> scope.$apply('value = 0'); <add> <add> expect(inputElm).toBeValid(); <add> expect(inputElm.val()).toBe('0'); <add> expect(scope.form.numberInput.$error.required).toBeFalsy(); <add> }); <add> <add> it('should register required on non boolean elements', function() { <add> compileInput('<div ng-model="value" name="numberInput" ng-required="true">'); <add> <add> scope.$apply("value = ''"); <add> <add> expect(inputElm).toBeInvalid(); <add> expect(scope.form.numberInput.$error.required).toBeTruthy(); <add> }); <add> <add> it('should change from invalid to valid when the value is empty and the ngRequired expression changes to false', function() { <add> compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="ngRequiredExpr" />'); <add> <add> scope.$apply('ngRequiredExpr = true'); <add> <add> expect(inputElm).toBeInvalid(); <add> expect(scope.value).toBeUndefined(); <add> expect(scope.form.numberInput.$error.required).toBeTruthy(); <add> <add> scope.$apply('ngRequiredExpr = false'); <add> <add> expect(inputElm).toBeValid(); <add> expect(scope.value).toBeUndefined(); <add> expect(scope.form.numberInput.$error.required).toBeFalsy(); <add> }); <add> }); <add> <add> describe('when the ngRequired expression initially evaluates to false', function() { <add> <add> it('should be valid even if value is empty', function() { <add> compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="false" />'); <add> <add> expect(inputElm).toBeValid(); <add> expect(scope.value).toBeUndefined(); <add> expect(scope.form.numberInput.$error.required).toBeFalsy(); <add> expect(scope.form.numberInput.$error.number).toBeFalsy(); <add> }); <add> <add> it('should be valid if value is non-empty', function() { <add> compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="false" />'); <add> <add> changeInputValueTo('42'); <add> expect(inputElm).toBeValid(); <add> expect(scope.value).toBe(42); <add> expect(scope.form.numberInput.$error.required).toBeFalsy(); <add> }); <add> <add> it('should not register required on non boolean elements', function() { <add> compileInput('<div ng-model="value" name="numberInput" ng-required="false">'); <add> <add> scope.$apply("value = ''"); <add> <add> expect(inputElm).toBeValid(); <add> expect(scope.form.numberInput.$error.required).toBeFalsy(); <add> }); <add> <add> it('should change from valid to invalid when the value is empty and the ngRequired expression changes to true', function() { <add> compileInput('<input type="number" ng-model="value" name="numberInput" ng-required="ngRequiredExpr" />'); <add> <add> scope.$apply('ngRequiredExpr = false'); <add> <add> expect(inputElm).toBeValid(); <add> expect(scope.value).toBeUndefined(); <add> expect(scope.form.numberInput.$error.required).toBeFalsy(); <add> <add> scope.$apply('ngRequiredExpr = true'); <add> <add> expect(inputElm).toBeInvalid(); <add> expect(scope.value).toBeUndefined(); <add> expect(scope.form.numberInput.$error.required).toBeTruthy(); <add> }); <add> }); <add> }); <add> <ide> describe('minlength', function() { <ide> <ide> it('should invalidate values that are shorter than the given minlength', function() {
1
Go
Go
add option processing to network.delete()
04bfc6149797487ab4da05a5df1c278e6e4a6496
<ide><path>libnetwork/network.go <ide> type Network interface { <ide> CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error) <ide> <ide> // Delete the network. <del> Delete() error <add> Delete(options ...NetworkDeleteOption) error <ide> <ide> // Endpoints returns the list of Endpoint(s) in this network. <ide> Endpoints() []Endpoint <ide> func (n *network) processOptions(options ...NetworkOption) { <ide> } <ide> } <ide> <add>type networkDeleteParams struct { <add> rmLBEndpoint bool <add>} <add> <add>// NetworkDeleteOption is a type for optional parameters to pass to the <add>// network.Delete() function. <add>type NetworkDeleteOption func(p *networkDeleteParams) <add> <add>// NetworkDeleteOptionRemoveLB informs a network.Delete() operation that should <add>// remove the load balancer endpoint for this network. Note that the Delete() <add>// method will automatically remove a load balancing endpoint for most networks <add>// when the network is otherwise empty. However, this does not occur for some <add>// networks. In particular, networks marked as ingress (which are supposed to <add>// be more permanent than other overlay networks) won't automatically remove <add>// the LB endpoint on Delete(). This method allows for explicit removal of <add>// such networks provided there are no other endpoints present in the network. <add>// If the network still has non-LB endpoints present, Delete() will not <add>// remove the LB endpoint and will return an error. <add>func NetworkDeleteOptionRemoveLB(p *networkDeleteParams) { <add> p.rmLBEndpoint = true <add>} <add> <ide> func (n *network) resolveDriver(name string, load bool) (driverapi.Driver, *driverapi.Capability, error) { <ide> c := n.getController() <ide> <ide> func (n *network) driver(load bool) (driverapi.Driver, error) { <ide> return d, nil <ide> } <ide> <del>func (n *network) Delete() error { <del> return n.delete(false) <add>func (n *network) Delete(options ...NetworkDeleteOption) error { <add> var params networkDeleteParams <add> for _, opt := range options { <add> opt(&params) <add> } <add> return n.delete(false, params.rmLBEndpoint) <ide> } <ide> <del>func (n *network) delete(force bool) error { <add>// This function gets called in 3 ways: <add>// * Delete() -- (false, false) <add>// remove if endpoint count == 0 or endpoint count == 1 and <add>// there is a load balancer IP <add>// * Delete(libnetwork.NetworkDeleteOptionRemoveLB) -- (false, true) <add>// remove load balancer and network if endpoint count == 1 <add>// * controller.networkCleanup() -- (true, true) <add>// remove the network no matter what <add>func (n *network) delete(force bool, rmLBEndpoint bool) error { <ide> n.Lock() <ide> c := n.ctrlr <ide> name := n.name <ide> func (n *network) delete(force bool) error { <ide> return &UnknownNetworkError{name: name, id: id} <ide> } <ide> <add> // Only remove ingress on force removal or explicit LB endpoint removal <add> if n.ingress && !force && !rmLBEndpoint { <add> return &ActiveEndpointsError{name: n.name, id: n.id} <add> } <add> <add> // Check that the network is empty <add> var emptyCount uint64 = 0 <add> if len(n.loadBalancerIP) != 0 { <add> emptyCount = 1 <add> } <add> if !force && n.getEpCnt().EndpointCnt() > emptyCount { <add> if n.configOnly { <add> return types.ForbiddenErrorf("configuration network %q is in use", n.Name()) <add> } <add> return &ActiveEndpointsError{name: n.name, id: n.id} <add> } <add> <ide> if len(n.loadBalancerIP) != 0 { <del> endpoints := n.Endpoints() <del> if force || (len(endpoints) == 1 && !n.ingress) { <del> n.deleteLoadBalancerSandbox() <add> // If we got to this point, then the following must hold: <add> // * force is true OR endpoint count == 1 <add> if err := n.deleteLoadBalancerSandbox(); err != nil { <add> if !force { <add> return err <add> } <add> // continue deletion when force is true even on error <add> logrus.Warnf("Error deleting load balancer sandbox: %v", err) <ide> } <ide> //Reload the network from the store to update the epcnt. <ide> n, err = c.getNetworkFromStore(id) <ide> func (n *network) delete(force bool) error { <ide> } <ide> } <ide> <del> if !force && n.getEpCnt().EndpointCnt() != 0 { <del> if n.configOnly { <del> return types.ForbiddenErrorf("configuration network %q is in use", n.Name()) <del> } <del> return &ActiveEndpointsError{name: n.name, id: n.id} <del> } <add> // Up to this point, errors that we returned were recoverable. <add> // From here on, any errors leave us in an inconsistent state. <add> // This is unfortunate, but there isn't a safe way to <add> // reconstitute a load-balancer endpoint after removing it. <ide> <ide> // Mark the network for deletion <ide> n.inDelete = true <ide> func (n *network) createLoadBalancerSandbox() error { <ide> return sb.EnableService() <ide> } <ide> <del>func (n *network) deleteLoadBalancerSandbox() { <add>func (n *network) deleteLoadBalancerSandbox() error { <ide> n.Lock() <ide> c := n.ctrlr <ide> name := n.name <ide> func (n *network) deleteLoadBalancerSandbox() { <ide> } <ide> <ide> if err := c.SandboxDestroy(sandboxName); err != nil { <del> logrus.Warnf("Failed to delete %s sandbox: %v", sandboxName, err) <add> return fmt.Errorf("Failed to delete %s sandbox: %v", sandboxName, err) <ide> } <add> return nil <ide> } <ide><path>libnetwork/store.go <ide> func (c *controller) networkCleanup() { <ide> for _, n := range networks { <ide> if n.inDelete { <ide> logrus.Infof("Removing stale network %s (%s)", n.Name(), n.ID()) <del> if err := n.delete(true); err != nil { <add> if err := n.delete(true, true); err != nil { <ide> logrus.Debugf("Error while removing stale network: %v", err) <ide> } <ide> }
2
PHP
PHP
fix stupid mistake
c076291682f31e14a17c93028cd719149badb83c
<ide><path>src/Network/Http/FormData/Part.php <ide> public function disposition($disposition = null) <ide> public function contentId($id = null) <ide> { <ide> if ($id === null) { <del> return $this->_contentId = $id; <add> return $this->_contentId; <ide> } <ide> $this->_contentId = $id; <ide> }
1
Ruby
Ruby
add test for slashes in versions
a8522c6db6cb5b78f132fa782d9830cbdc32d4d0
<ide><path>Library/Homebrew/test/cask/audit_spec.rb <ide> def tmp_cask(name, text) <ide> expect(audit.cask.url.cookies).to eq "foo" => "bar" <ide> end <ide> end <add> <add> context "when the version contains a slash" do <add> let(:cask_token) { "foo" } <add> let(:cask) do <add> tmp_cask cask_token.to_s, <<~RUBY <add> cask '#{cask_token}' do <add> version '0.1,../../directory/traversal' <add> sha256 '8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a' <add> url 'https://brew.sh/foo.zip' <add> name 'Audit' <add> desc 'Audit Description' <add> homepage 'https://brew.sh' <add> app 'Audit.app' <add> end <add> RUBY <add> end <add> <add> it { is_expected.to fail_with(%r{version should not contain '/'}) } <add> end <ide> end <ide> end
1
Javascript
Javascript
remove console warnings from scrollview methods
b119a00c45db3d1c59f8fad93c10f2194eafcf12
<ide><path>Libraries/Components/ScrollView/ScrollView.js <ide> class ScrollView extends React.Component<Props, State> { <ide> * to the underlying scroll responder's methods. <ide> */ <ide> getScrollResponder: () => ScrollResponderType = () => { <del> if (__DEV__) { <del> console.warn( <del> '`getScrollResponder()` is deprecated. This will be removed in a future release. ' + <del> 'Use <ScrollView ref={myRef} /> instead.', <del> ); <del> } <ide> // $FlowFixMe - overriding type to include ScrollResponder.Mixin <ide> return ((this: any): ScrollResponderType); <ide> }; <ide> <ide> getScrollableNode: () => ?number = () => { <del> if (__DEV__) { <del> console.warn( <del> '`getScrollableNode()` is deprecated. This will be removed in a future release. ' + <del> 'Use <ScrollView ref={myRef} /> instead.', <del> ); <del> } <ide> return ReactNative.findNodeHandle(this._scrollViewRef); <ide> }; <ide> <ide> class ScrollView extends React.Component<Props, State> { <ide> } <ide> <ide> getNativeScrollRef: () => ?React.ElementRef<HostComponent<mixed>> = () => { <del> if (__DEV__) { <del> console.warn( <del> '`getNativeScrollRef()` is deprecated. This will be removed in a future release. ' + <del> 'Use <ScrollView ref={myRef} /> instead.', <del> ); <del> } <ide> return this._scrollViewRef; <ide> }; <ide>
1
Ruby
Ruby
use drop and avoid a range object
7db93131ed01aa3b64774b81f6c6b78a6012a75a
<ide><path>activerecord/lib/active_record/associations/through_association.rb <ide> module ThroughAssociation #:nodoc: <ide> # 2. To get the type conditions for any STI models in the chain <ide> def target_scope <ide> scope = super <del> chain[1..-1].each do |reflection| <add> chain.drop(1).each do |reflection| <ide> scope.merge!( <ide> reflection.klass.all. <ide> except(:select, :create_with, :includes, :preload, :joins, :eager_load)
1
Text
Text
add @jasnell and @sam-github to release team
b0962c38e3b7626288421df818d302cde7dc0047
<ide><path>README.md <ide> Releases of Node.js and io.js will be signed with one of the following GPG keys: <ide> <ide> * **Chris Dickinson** &lt;christopher.s.dickinson@gmail.com&gt;: `9554F04D7259F04124DE6B476D5A82AC7E37093B` <ide> * **Colin Ihrig** &lt;cjihrig@gmail.com&gt; `94AE36675C464D64BAFA68DD7434390BDBE9B9C5` <add>* **Sam Roberts** &lt;octetcloud@keybase.io&gt; `0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93` <ide> * **Jeremiah Senkpiel** &lt;fishrock@keybase.io&gt; `FD3A5288F042B6850C66B31F09FE44734EB7990E` <add>* **James M Snell** &lt;jasnell@keybase.io&gt; `71DCFD284A79C3B38668286BC97EC7A07EDE3FC1` <ide> * **Rod Vagg** &lt;rod@vagg.org&gt; `DD8F2338BAE7501E3DD5AC78C273792F7D83545D` <ide> <ide> The full set of trusted release keys can be imported by running: <ide> <ide> ``` <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 9554F04D7259F04124DE6B476D5A82AC7E37093B <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 94AE36675C464D64BAFA68DD7434390BDBE9B9C5 <add>gpg --keyserver pool.sks-keyservers.net --recv-keys 0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93 <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys FD3A5288F042B6850C66B31F09FE44734EB7990E <add>gpg --keyserver pool.sks-keyservers.net --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D <ide> ``` <ide>
1
Python
Python
fix typo _add_worker -> add_worker
999f68fcafad7ad040ac999109f9211d7ced6b63
<ide><path>celery/pool.py <ide> def add_worker(self): <ide> <ide> def grow(self, size=1): <ide> """Add ``size`` new workers to the pool.""" <del> map(self._add_worker, range(size)) <add> map(self.add_worker, range(size)) <ide> <ide> def is_dead(self, process): <ide> # First try to see if the process is actually running,
1
PHP
PHP
fix flush bug
ab61c759a4b1e4513af31b899263d7efdb23a08f
<ide><path>src/Illuminate/View/Factory.php <ide> public function yieldContent($section, $default = '') <ide> */ <ide> public function flushSections() <ide> { <add> $this->renderCount = 0; <add> <ide> $this->sections = []; <ide> <ide> $this->sectionStack = [];
1
Python
Python
assign values to memory before using
948354a12e35712008a2a52fd5efc581d36595dc
<ide><path>numpy/core/tests/test_regression.py <ide> def check_unicode_string_comparison(self,level=rlevel): <ide> def check_tostring_FORTRANORDER_discontiguous(self,level=rlevel): <ide> """Fix in r2836""" <ide> # Create discontiguous Fortran-ordered array <del> x = N.empty((3,3),order='F')[:,:2] <add> x = N.array(N.random.rand(3,3),order='F')[:,:2] <ide> assert_array_almost_equal(x.ravel(),N.fromstring(x.tostring())) <ide> <ide> def check_flat_assignment(self,level=rlevel):
1
Javascript
Javascript
fix style errors
8eebe7435d1f2edbd252686d34617773cbf3954c
<ide><path>packages/ember-htmlbars/lib/helpers/bind-attr-class.js <ide> @submodule ember-htmlbars <ide> */ <ide> <add>import { get } from 'ember-metal/property_get'; <ide> import { isArray } from "ember-metal/utils"; <ide> <ide> export default function bindAttrClassHelper(params) { <ide><path>packages/ember-htmlbars/lib/helpers/loc.js <del>import Ember from 'ember-metal/core'; <ide> import { loc } from 'ember-runtime/system/string'; <ide> <ide> /** <ide> import { loc } from 'ember-runtime/system/string'; <ide> */ <ide> export default function locHelper(params) { <ide> return loc.apply(null, params); <del>} <ide>\ No newline at end of file <add>} <ide><path>packages/ember-htmlbars/lib/hooks/get-root.js <ide> function getKey(scope, key) { <ide> } <ide> <ide> function getGlobal(name) { <del> Ember.deprecate("Global lookup of " + name + " from a Handlebars template is deprecated") <add> Ember.deprecate("Global lookup of " + name + " from a Handlebars template is deprecated"); <ide> <ide> // This stream should be memoized, but this path is deprecated and <ide> // will be removed soon so it's not worth the trouble. <ide><path>packages/ember-metal/tests/streams/key-stream-test.js <ide> QUnit.test("is notified when setSource is called with a new stream whose value i <ide> equal(count, 0, "Subscribers called correct number of times"); <ide> equal(nameStream.value(), "mmun", "Stream value is correct"); <ide> <del> object = { name: "wycats" } <add> object = { name: "wycats" }; <ide> nameStream.setSource(new Stream(function() { <ide> return object; <ide> })); <ide><path>packages/ember-template-compiler/lib/plugins/transform-bind-attr-to-attributes.js <ide> TransformBindAttrToAttributes.prototype.parseClass = function parseClass(value) <ide> b.string('') <ide> ]); <ide> } <add> break; <ide> case 3: <ide> // Before: {{bind-attr class="some.path:foo:bar ..."}} <ide> // After: class="{{if some.path "foo" "bar"}} ..." <ide> function isBindAttrModifier(modifier) { <ide> return true; <ide> } else { <ide> return false; <del> }; <add> } <ide> } <ide> <ide> function assertAttrNameIsUnused(element, name) { <ide><path>packages/ember-template-compiler/lib/plugins/transform-each-in-to-block-params.js <ide> TransformEachInToBlockParams.prototype.transform = function TransformEachInToBlo <ide> throw new Error('You cannot use keyword (`{{each foo in bar}}`) and block params (`{{each bar as |foo|}}`) at the same time.'); <ide> } <ide> <del> node.program.blockParams = [ keyword ]; <add> node.program.blockParams = [keyword]; <ide> } else { <ide> node.sexpr.hash.pairs.push(b.pair( <ide> 'keyword', <ide> function validate(node) { <ide> node.sexpr.params.length === 3 && <ide> node.sexpr.params[1].type === 'PathExpression' && <ide> node.sexpr.params[1].original === 'in'; <del>}; <add>} <ide> <ide> export default TransformEachInToBlockParams; <ide><path>packages/ember-views/lib/system/build-component-template.js <ide> function normalizeClass(component, classAttr) { <ide> var prop = 'view.' + microsyntax[0]; <ide> var activeClass, inactiveClass; <ide> <del> if (microsyntax.length === 1) { <add> if (microsyntax.length === 1) { <ide> activeClass = prop; <ide> } else if (microsyntax.length === 2) { <ide> activeClass = microsyntax[1]; <ide> function normalizeClass(component, classAttr) { <ide> var prop = 'view.' + microsyntax[0]; <ide> var activeClass, inactiveClass; <ide> <del> if (microsyntax.length === 1) { <add> if (microsyntax.length === 1) { <ide> activeClass = prop; <ide> } else if (microsyntax.length === 2) { <ide> activeClass = microsyntax[1]; <ide> function normalizeClass(component, classAttr) { <ide> var prop = 'view.' + microsyntax[0]; <ide> var activeClass, inactiveClass; <ide> <del> if (microsyntax.length === 1) { <add> if (microsyntax.length === 1) { <ide> activeClass = prop; <ide> } else if (microsyntax.length === 2) { <ide> activeClass = microsyntax[1];
7
Javascript
Javascript
update location documentation
e945b9ebde480f642017e4ecea6c545014f68741
<ide><path>packages/ember-application/lib/system/location.js <ide> var get = Ember.get, set = Ember.set; <ide> getURL: returns the current URL <ide> setURL(path): sets the current URL <ide> onUpdateURL(callback): triggers the callback when the URL changes <add> formatURL(url): formats `url` to be placed into `href` attribute <ide> <ide> Calling setURL will not trigger onUpdateURL callbacks. <ide>
1
Ruby
Ruby
fix bad pathname indentation
b549ca837fce9fc6aa231c1424f2c6a2bf6875d3
<ide><path>Library/Homebrew/extend/pathname.rb <ide> def version <ide> /_((\d+\.)+\d+[abc]?)[.]orig$/.match stem <ide> return $1 if $1 <ide> <del> # brew bottle style e.g. qt-4.7.3-bottle.tar.gz <add> # brew bottle style e.g. qt-4.7.3-bottle.tar.gz <ide> /-((\d+\.)*\d+)-bottle$/.match stem <del> return $1 if $1 <add> return $1 if $1 <ide> <ide> # eg. otp_src_R13B (this is erlang's style) <ide> # eg. astyle_1.23_macosx.tar.gz
1
Ruby
Ruby
remove checks for validate constraints support
6c7d85edae5a09300bd9f429e233985a9385dc91
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb <ide> def create_schema_dumper(options) # :nodoc: <ide> # <ide> # validate_constraint :accounts, :constraint_name <ide> def validate_constraint(table_name, constraint_name) <del> return unless supports_validate_constraints? <del> <ide> at = create_alter_table table_name <ide> at.validate_constraint constraint_name <ide> <ide> def validate_constraint(table_name, constraint_name) <ide> # <ide> # The +options+ hash accepts the same keys as SchemaStatements#add_foreign_key. <ide> def validate_foreign_key(from_table, to_table = nil, **options) <del> return unless supports_validate_constraints? <del> <ide> fk_name_to_validate = foreign_key_for!(from_table, to_table: to_table, **options).name <ide> <ide> validate_constraint from_table, fk_name_to_validate <ide> def validate_foreign_key(from_table, to_table = nil, **options) <ide> # <ide> # The +options+ hash accepts the same keys as add_check_constraint[rdoc-ref:ConnectionAdapters::SchemaStatements#add_check_constraint]. <ide> def validate_check_constraint(table_name, **options) <del> return unless supports_validate_constraints? <del> <ide> chk_name_to_validate = check_constraint_for!(table_name, **options).name <ide> <ide> validate_constraint table_name, chk_name_to_validate
1
Mixed
Ruby
generate consistent names for foreign keys
b8e1f202676b4788c56241b124c401beff9f4014
<ide><path>activerecord/CHANGELOG.md <add>* Foreign keys added by migrations were given random, generated names. This <add> meant a different `structure.sql` would be generated every time a developer <add> ran migrations on their machine. <add> <add> The generated part of foreign key names is now a hash of the table name and <add> column name, which is consistent every time you run the migration. <add> <add> *Chris Sinjakli* <add> <ide> * Validation errors would be raised for parent records when an association <ide> was saved when the parent had `validate: false`. It should not be the <ide> responsibility of the model to validate an associated object unless the <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> require 'active_record/migration/join_table' <add>require 'active_support/core_ext/string/access' <add>require 'digest' <ide> <ide> module ActiveRecord <ide> module ConnectionAdapters # :nodoc: <ide> def create_alter_table(name) <ide> end <ide> <ide> def foreign_key_name(table_name, options) # :nodoc: <add> identifier = "#{table_name}_#{options.fetch(:column)}_fk" <add> hashed_identifier = Digest::SHA256.hexdigest(identifier).first(10) <ide> options.fetch(:name) do <del> "fk_rails_#{SecureRandom.hex(5)}" <add> "fk_rails_#{hashed_identifier}" <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/migration/foreign_key_test.rb <ide> def test_add_foreign_key_inferes_column <ide> assert_equal "rockets", fk.to_table <ide> assert_equal "rocket_id", fk.column <ide> assert_equal "id", fk.primary_key <del> assert_match(/^fk_rails_.{10}$/, fk.name) <add> assert_equal("fk_rails_78146ddd2e", fk.name) <ide> end <ide> <ide> def test_add_foreign_key_with_column <ide> def test_add_foreign_key_with_column <ide> assert_equal "rockets", fk.to_table <ide> assert_equal "rocket_id", fk.column <ide> assert_equal "id", fk.primary_key <del> assert_match(/^fk_rails_.{10}$/, fk.name) <add> assert_equal("fk_rails_78146ddd2e", fk.name) <ide> end <ide> <ide> def test_add_foreign_key_with_non_standard_primary_key
3
Javascript
Javascript
add pimmr to showcase
d131fa0962ed7c241fb1b2e509225b89cca6f6b9
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://itunes.apple.com/us/app/okanagan-news-reader-for-viewing/id1049147148?mt=8', <ide> author: 'Levi Cabral', <ide> }, <add> { <add> name: 'Pimmr', <add> icon: 'http://a2.mzstatic.com/eu/r30/Purple69/v4/99/da/0e/99da0ee6-bc87-e1a6-1d95-7027c78f50e1/icon175x175.jpeg', <add> link: 'https://itunes.apple.com/nl/app/pimmr/id1023343303?mt=8&ign-mpt=uo%3D4', <add> author: 'Pimmr' <add> }, <ide> { <ide> name: 'Posyt - Tinder for ideas', <ide> icon: 'http://a3.mzstatic.com/us/r30/Purple6/v4/a5/b3/86/a5b38618-a5e9-6089-7425-7fa51ecd5d30/icon175x175.jpeg',
1
Python
Python
prepare new release
54386efa549f850dff13f79fc3af67799a4e5d4f
<ide><path>keras/__init__.py <ide> from .models import Model <ide> from .models import Sequential <ide> <del>__version__ = '2.2.1' <add>__version__ = '2.2.2' <ide><path>setup.py <ide> ''' <ide> <ide> setup(name='Keras', <del> version='2.2.1', <add> version='2.2.2', <ide> description='Deep Learning for humans', <ide> long_description=long_description, <ide> author='Francois Chollet', <ide> author_email='francois.chollet@gmail.com', <ide> url='https://github.com/keras-team/keras', <del> download_url='https://github.com/keras-team/keras/tarball/2.2.1', <add> download_url='https://github.com/keras-team/keras/tarball/2.2.2', <ide> license='MIT', <ide> install_requires=['numpy>=1.9.1', <ide> 'scipy>=0.14',
2
Python
Python
add support for character features to tok2vec
e1a83d15ed53a0bc9779182bdf1732cd6f722918
<ide><path>spacy/_ml.py <ide> from thinc.api import with_square_sequences <ide> from thinc.linear.linear import LinearModel <ide> from thinc.neural.ops import NumpyOps, CupyOps <del>from thinc.neural.util import get_array_module <add>from thinc.neural.util import get_array_module, copy_array <ide> from thinc.neural.optimizers import Adam <ide> <ide> from thinc import describe <ide> def Tok2Vec(width, embed_size, **kwargs): <ide> pretrained_vectors = kwargs.get("pretrained_vectors", None) <ide> cnn_maxout_pieces = kwargs.get("cnn_maxout_pieces", 3) <ide> subword_features = kwargs.get("subword_features", True) <add> char_embed = kwargs.get("char_embed", False) <add> if char_embed: <add> subword_features = False <ide> conv_depth = kwargs.get("conv_depth", 4) <ide> bilstm_depth = kwargs.get("bilstm_depth", 0) <ide> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE, ORTH] <ide> def Tok2Vec(width, embed_size, **kwargs): <ide> if pretrained_vectors is not None: <ide> glove = StaticVectors(pretrained_vectors, width, column=cols.index(ID)) <ide> <del> if subword_features: <add> if subword_features: <ide> embed = uniqued( <ide> (glove | norm | prefix | suffix | shape) <ide> >> LN(Maxout(width, width * 5, pieces=3)), <ide> def Tok2Vec(width, embed_size, **kwargs): <ide> embed = uniqued( <ide> (norm | prefix | suffix | shape) <ide> >> LN(Maxout(width, width * 4, pieces=3)), <del> column=cols.index(ORTH), <add> column=cols.index(ORTH) <ide> ) <add> elif char_embed: <add> embed = concatenate_lists( <add> CharacterEmbed(nM=64, nC=8), <add> FeatureExtracter(cols) >> with_flatten(norm) <add> ) <add> reduce_dimensions = LN(Maxout(width, 64*8+width, pieces=cnn_maxout_pieces)) <ide> else: <ide> embed = norm <ide> <ide> convolution = Residual( <ide> ExtractWindow(nW=1) <ide> >> LN(Maxout(width, width * 3, pieces=cnn_maxout_pieces)) <ide> ) <del> tok2vec = FeatureExtracter(cols) >> with_flatten( <del> embed >> convolution ** conv_depth, pad=conv_depth <del> ) <add> if char_embed: <add> tok2vec = ( <add> embed <add> >> with_flatten( <add> reduce_dimensions <add> >> convolution ** conv_depth, pad=conv_depth <add> ) <add> ) <add> else: <add> tok2vec = ( <add> FeatureExtracter(cols) <add> >> with_flatten( <add> embed <add> >> convolution ** conv_depth, pad=conv_depth <add> ) <add> ) <add> <ide> if bilstm_depth >= 1: <ide> tok2vec = tok2vec >> PyTorchBiLSTM(width, width, bilstm_depth) <ide> # Work around thinc API limitations :(. TODO: Revise in Thinc 7 <ide> def build_morphologizer_model(class_nums, **cfg): <ide> else: <ide> token_vector_width = util.env_opt("token_vector_width", 128) <ide> pretrained_vectors = cfg.get("pretrained_vectors") <del> subword_features = cfg.get("subword_features", True) <add> char_embed = cfg.get("char_embed", True) <ide> with Model.define_operators({">>": chain, "+": add}): <ide> if "tok2vec" in cfg: <ide> tok2vec = cfg["tok2vec"] <ide> else: <ide> tok2vec = Tok2Vec( <ide> token_vector_width, <ide> embed_size, <del> subword_features=subword_features, <add> char_embed=char_embed, <ide> pretrained_vectors=pretrained_vectors, <ide> ) <ide> softmax = with_flatten(MultiSoftmax(class_nums, token_vector_width)) <ide> def concatenate_lists(*layers, **kwargs): # pragma: no cover <ide> concat = concatenate(*layers) <ide> <ide> def concatenate_lists_fwd(Xs, drop=0.0): <del> drop *= drop_factor <add> if drop is not None: <add> drop *= drop_factor <ide> lengths = ops.asarray([len(X) for X in Xs], dtype="i") <ide> flat_y, bp_flat_y = concat.begin_update(Xs, drop=drop) <ide> ys = ops.unflatten(flat_y, lengths) <ide> def _replace_word(word, random_words, mask="[MASK]"): <ide> return random_words.next() <ide> else: <ide> return word <add> <add> <add>def _uniform_init(lo, hi): <add> def wrapped(W, ops): <add> copy_array(W, ops.xp.random.uniform(lo, hi, W.shape)) <add> return wrapped <add> <add> <add>@describe.attributes( <add> nM=Dimension("Vector dimensions"), <add> nC=Dimension("Number of characters per word"), <add> vectors=Synapses("Embed matrix", <add> lambda obj: (obj.nC, obj.nV, obj.nM), <add> _uniform_init(-0.1, 0.1)), <add> d_vectors=Gradient("vectors") <add>) <add>class CharacterEmbed(Model): <add> def __init__(self, nM=None, nC=None, **kwargs): <add> Model.__init__(self, **kwargs) <add> self.nM = nM <add> self.nC = nC <add> <add> @property <add> def nO(self): <add> return self.nM * self.nC <add> <add> @property <add> def nV(self): <add> return 256 <add> <add> def begin_update(self, docs, drop=0.): <add> if not docs: <add> return [] <add> ids = [] <add> output = [] <add> weights = self.vectors <add> # This assists in indexing; it's like looping over this dimension. <add> # Still consider this weird witch craft...But thanks to Mark Neumann <add> # for the tip. <add> nCv = self.ops.xp.arange(self.nC) <add> for doc in docs: <add> doc_ids = doc.to_utf8_array(nr_char=self.nC) <add> doc_vectors = self.ops.allocate((len(doc), self.nC, self.nM)) <add> # Let's say I have a 2d array of indices, and a 3d table of data. What numpy <add> # incantation do I chant to get <add> # output[i, j, k] == data[j, ids[i, j], k]? <add> doc_vectors[:, nCv] = weights[nCv, doc_ids[:, nCv]] <add> output.append(doc_vectors.reshape((len(doc), self.nO))) <add> ids.append(doc_ids) <add> <add> def backprop_character_embed(d_vectors, sgd=None): <add> gradient = self.d_vectors <add> for doc_ids, d_doc_vectors in zip(ids, d_vectors): <add> d_doc_vectors = d_doc_vectors.reshape((len(doc_ids), self.nC, self.nM)) <add> gradient[nCv, doc_ids[:, nCv]] += d_doc_vectors[:, nCv] <add> if sgd is not None: <add> sgd(self._mem.weights, self._mem.gradient, key=self.id) <add> return None <add> return output, backprop_character_embed <add> <add>
1
Javascript
Javascript
return null when attribute does not exist
aaeed53e9f1e299975cb6f697c8038ec3a83fa4d
<ide><path>src/attributes/attr.js <ide> jQuery.extend({ <ide> return ret; <ide> <ide> } else { <del> ret = jQuery.find.attr( elem, name ); <del> <del> // Non-existent attributes return null, we normalize to undefined <del> return ret == null ? <del> undefined : <del> ret; <add> return jQuery.find.attr( elem, name ); <ide> } <ide> }, <ide> <ide><path>test/unit/attributes.js <ide> test( "attr(String)", function() { <ide> equal( jQuery("#text1").attr("value", "").attr("value"), "", "Check setting the value attribute to empty string" ); <ide> equal( jQuery("<div value='t'></div>").attr("value"), "t", "Check setting custom attr named 'value' on a div" ); <ide> equal( jQuery("#form").attr("blah", "blah").attr("blah"), "blah", "Set non-existent attribute on a form" ); <del> equal( jQuery("#foo").attr("height"), undefined, "Non existent height attribute should return undefined" ); <add> equal( jQuery("#foo").attr("height"), null, "Non existent height attribute should return null" ); <ide> <ide> // [7472] & [3113] (form contains an input with name="action" or name="id") <ide> extras = jQuery("<input id='id' name='id' /><input id='name' name='name' /><input id='target' name='target' />").appendTo("#testForm"); <ide> equal( jQuery("#form").attr("action","newformaction").attr("action"), "newformaction", "Check that action attribute was changed" ); <del> equal( jQuery("#testForm").attr("target"), undefined, "Retrieving target does not equal the input with name=target" ); <add> equal( jQuery("#testForm").attr("target"), null, "Retrieving target does not equal the input with name=target" ); <ide> equal( jQuery("#testForm").attr("target", "newTarget").attr("target"), "newTarget", "Set target successfully on a form" ); <del> equal( jQuery("#testForm").removeAttr("id").attr("id"), undefined, "Retrieving id does not equal the input with name=id after id is removed [#7472]" ); <add> equal( jQuery("#testForm").removeAttr("id").attr("id"), null, "Retrieving id does not equal the input with name=id after id is removed [#7472]" ); <ide> // Bug #3685 (form contains input with name="name") <del> equal( jQuery("#testForm").attr("name"), undefined, "Retrieving name does not retrieve input with name=name" ); <add> equal( jQuery("#testForm").attr("name"), null, "Retrieving name does not retrieve input with name=name" ); <ide> extras.remove(); <ide> <ide> equal( jQuery("#text1").attr("maxlength"), "30", "Check for maxlength attribute" ); <ide> test( "attr(String)", function() { <ide> body = document.body; <ide> $body = jQuery( body ); <ide> <del> strictEqual( $body.attr("foo"), undefined, "Make sure that a non existent attribute returns undefined" ); <add> strictEqual( $body.attr("foo"), null, "Make sure that a non existent attribute returns null" ); <ide> <ide> body.setAttribute( "foo", "baz" ); <ide> equal( $body.attr("foo"), "baz", "Make sure the dom attribute is retrieved when no expando is found" ); <ide> test( "attr(String)", function() { <ide> <ide> // Check value on button element (#1954) <ide> $button = jQuery("<button>text</button>").insertAfter("#button"); <del> strictEqual( $button.attr("value"), undefined, "Absence of value attribute on a button" ); <add> strictEqual( $button.attr("value"), null, "Absence of value attribute on a button" ); <ide> equal( $button.attr( "value", "foobar" ).attr("value"), "foobar", "Value attribute on a button does not return innerHTML" ); <ide> equal( $button.attr("value", "baz").html(), "text", "Setting the value attribute does not change innerHTML" ); <ide> <ide> // Attributes with a colon on a table element (#1591) <del> equal( jQuery("#table").attr("test:attrib"), undefined, "Retrieving a non-existent attribute on a table with a colon does not throw an error." ); <add> equal( jQuery("#table").attr("test:attrib"), null, "Retrieving a non-existent attribute on a table with a colon does not throw an error." ); <ide> equal( jQuery("#table").attr( "test:attrib", "foobar" ).attr("test:attrib"), "foobar", "Setting an attribute on a table with a colon does not throw an error." ); <ide> <ide> $form = jQuery("<form class='something'></form>").appendTo("#qunit-fixture"); <ide> test( "attr(String)", function() { <ide> $a = jQuery("<a href='#' onclick='something()'>Click</a>").appendTo("#qunit-fixture"); <ide> equal( $a.attr("onclick"), "something()", "Retrieve ^on attribute without anonymous function wrapper." ); <ide> <del> ok( jQuery("<div/>").attr("doesntexist") === undefined, "Make sure undefined is returned when no attribute is found." ); <del> ok( jQuery("<div/>").attr("title") === undefined, "Make sure undefined is returned when no attribute is found." ); <add> ok( jQuery("<div/>").attr("doesntexist") === null, "Make sure null is returned when no attribute is found." ); <add> ok( jQuery("<div/>").attr("title") === null, "Make sure null is returned when no attribute is found." ); <ide> equal( jQuery("<div/>").attr( "title", "something" ).attr("title"), "something", "Set the title attribute." ); <ide> ok( jQuery().attr("doesntexist") === undefined, "Make sure undefined is returned when no element is there." ); <del> equal( jQuery("<div/>").attr("value"), undefined, "An unset value on a div returns undefined." ); <del> strictEqual( jQuery("<select><option value='property'></option></select>").attr("value"), undefined, "An unset value on a select returns undefined." ); <add> equal( jQuery("<div/>").attr("value"), null, "An unset value on a div returns null." ); <add> strictEqual( jQuery("<select><option value='property'></option></select>").attr("value"), null, "An unset value on a select returns null." ); <ide> <ide> $form = jQuery("#form").attr( "enctype", "multipart/form-data" ); <ide> equal( $form.prop("enctype"), "multipart/form-data", "Set the enctype of a form (encoding in IE6/7 #6743)" ); <ide> test( "attr(String, Object)", function() { <ide> jQuery("#name").attr( "name", "something" ); <ide> equal( jQuery("#name").attr("name"), "something", "Set name attribute" ); <ide> jQuery("#name").attr( "name", null ); <del> equal( jQuery("#name").attr("name"), undefined, "Remove name attribute" ); <add> equal( jQuery("#name").attr("name"), null, "Remove name attribute" ); <ide> <ide> $input = jQuery( "<input>", { <ide> name: "something", <ide> test( "attr(String, Object)", function() { <ide> $input.prop( "checked", true ).prop( "checked", false ).attr( "checked", true ); <ide> equal( $input.attr("checked"), "checked", "Set checked (verified by .attr)" ); <ide> $input.prop( "checked", false ).prop( "checked", true ).attr( "checked", false ); <del> equal( $input.attr("checked"), undefined, "Remove checked (verified by .attr)" ); <add> equal( $input.attr("checked"), null, "Remove checked (verified by .attr)" ); <ide> <ide> $input = jQuery("#text1").prop( "readOnly", true ).prop( "readOnly", false ).attr( "readonly", true ); <ide> equal( $input.attr("readonly"), "readonly", "Set readonly (verified by .attr)" ); <ide> $input.prop( "readOnly", false ).prop( "readOnly", true ).attr( "readonly", false ); <del> equal( $input.attr("readonly"), undefined, "Remove readonly (verified by .attr)" ); <add> equal( $input.attr("readonly"), null, "Remove readonly (verified by .attr)" ); <ide> <ide> $input = jQuery("#check2").attr( "checked", true ).attr( "checked", false ).prop( "checked", true ); <ide> equal( $input[0].checked, true, "Set checked property (verified by native property)" ); <ide> equal( $input.prop("checked"), true, "Set checked property (verified by .prop)" ); <del> equal( $input.attr("checked"), undefined, "Setting checked property doesn't affect checked attribute" ); <add> equal( $input.attr("checked"), null, "Setting checked property doesn't affect checked attribute" ); <ide> $input.attr( "checked", false ).attr( "checked", true ).prop( "checked", false ); <ide> equal( $input[0].checked, false, "Clear checked property (verified by native property)" ); <ide> equal( $input.prop("checked"), false, "Clear checked property (verified by .prop)" ); <ide> test( "attr(String, Object)", function() { <ide> "required": true <ide> }); <ide> equal( $text.attr("autofocus"), "autofocus", "Reading autofocus attribute yields 'autofocus'" ); <del> equal( $text.attr( "autofocus", false ).attr("autofocus"), undefined, "Setting autofocus to false removes it" ); <add> equal( $text.attr( "autofocus", false ).attr("autofocus"), null, "Setting autofocus to false removes it" ); <ide> equal( $text.attr("required"), "required", "Reading required attribute yields 'required'" ); <del> equal( $text.attr( "required", false ).attr("required"), undefined, "Setting required attribute to false removes it" ); <add> equal( $text.attr( "required", false ).attr("required"), null, "Setting required attribute to false removes it" ); <ide> <ide> $details = jQuery("<details open></details>").appendTo("#qunit-fixture"); <ide> equal( $details.attr("open"), "open", "open attribute presence indicates true" ); <del> equal( $details.attr( "open", false ).attr("open"), undefined, "Setting open attribute to false removes it" ); <add> equal( $details.attr( "open", false ).attr("open"), null, "Setting open attribute to false removes it" ); <ide> <ide> $text.attr( "data-something", true ); <ide> equal( $text.attr("data-something"), "true", "Set data attributes"); <ide> test( "attr(String, Object)", function() { <ide> jQuery.each( [ commentNode, textNode, attributeNode ], function( i, elem ) { <ide> var $elem = jQuery( elem ); <ide> $elem.attr( "nonexisting", "foo" ); <del> strictEqual( $elem.attr("nonexisting"), undefined, "attr(name, value) works correctly on comment and text nodes (bug #7500)." ); <add> strictEqual( $elem.attr("nonexisting"), null, "attr(name, value) works correctly on comment and text nodes (bug #7500)." ); <ide> }); <ide> <ide> jQuery.each( [ window, document, obj, "#firstp" ], function( i, elem ) { <ide> var oldVal = elem.nonexisting, <ide> $elem = jQuery( elem ); <del> strictEqual( $elem.attr("nonexisting"), undefined, "attr works correctly for non existing attributes (bug #7500)." ); <add> strictEqual( $elem.attr("nonexisting"), null, "attr works correctly for non existing attributes (bug #7500)." ); <ide> equal( $elem.attr( "nonexisting", "foo" ).attr("nonexisting"), "foo", "attr falls back to prop on unsupported arguments" ); <ide> elem.nonexisting = oldVal; <ide> }); <ide> test( "attr(String, Object)", function() { <ide> table.attr("cellspacing", "2"); <ide> equal( table[ 0 ]["cellSpacing"], "2", "Check cellspacing is correctly set" ); <ide> <del> equal( jQuery("#area1").attr("value"), undefined, "Value attribute is distinct from value property." ); <add> equal( jQuery("#area1").attr("value"), null, "Value attribute is distinct from value property." ); <ide> <ide> // for #1070 <ide> jQuery("#name").attr( "someAttr", "0" ); <ide> test( "attr(String, Object)", function() { <ide> jQuery("#name").attr( "maxlength", "5" ).removeAttr("nonexisting"); <ide> equal( typeof jQuery("#name").attr( "maxlength", undefined ), "object", ".attr('attribute', undefined) is chainable (#5571)" ); <ide> equal( jQuery("#name").attr( "maxlength", undefined ).attr("maxlength"), "5", ".attr('attribute', undefined) does not change value (#5571)" ); <del> equal( jQuery("#name").attr( "nonexisting", undefined ).attr("nonexisting"), undefined, ".attr('attribute', undefined) does not create attribute (#5571)" ); <add> equal( jQuery("#name").attr( "nonexisting", undefined ).attr("nonexisting"), null, ".attr('attribute', undefined) does not create attribute (#5571)" ); <ide> }); <ide> <ide> test( "attr - extending the boolean attrHandle", function() { <ide> test( "attr(String, Object) - Loaded via XML fragment", function() { <ide> $frag.attr( "test", "some value" ); <ide> equal( $frag.attr("test"), "some value", "set attribute" ); <ide> $frag.attr( "test", null ); <del> equal( $frag.attr("test"), undefined, "remove attribute" ); <add> equal( $frag.attr("test"), null, "remove attribute" ); <ide> }); <ide> <ide> test( "attr('tabindex')", function() { <ide> expect( 8 ); <ide> <ide> // elements not natively tabbable <ide> equal( jQuery("#listWithTabIndex").attr("tabindex"), "5", "not natively tabbable, with tabindex set to 0" ); <del> equal( jQuery("#divWithNoTabIndex").attr("tabindex"), undefined, "not natively tabbable, no tabindex set" ); <add> equal( jQuery("#divWithNoTabIndex").attr("tabindex"), null, "not natively tabbable, no tabindex set" ); <ide> <ide> // anchor with href <del> equal( jQuery("#linkWithNoTabIndex").attr("tabindex"), undefined, "anchor with href, no tabindex set" ); <add> equal( jQuery("#linkWithNoTabIndex").attr("tabindex"), null, "anchor with href, no tabindex set" ); <ide> equal( jQuery("#linkWithTabIndex").attr("tabindex"), "2", "anchor with href, tabindex set to 2" ); <ide> equal( jQuery("#linkWithNegativeTabIndex").attr("tabindex"), "-1", "anchor with href, tabindex set to -1" ); <ide> <ide> // anchor without href <del> equal( jQuery("#linkWithNoHrefWithNoTabIndex").attr("tabindex"), undefined, "anchor without href, no tabindex set" ); <add> equal( jQuery("#linkWithNoHrefWithNoTabIndex").attr("tabindex"), null, "anchor without href, no tabindex set" ); <ide> equal( jQuery("#linkWithNoHrefWithTabIndex").attr("tabindex"), "1", "anchor without href, tabindex set to 2" ); <ide> equal( jQuery("#linkWithNoHrefWithNegativeTabIndex").attr("tabindex"), "-1", "anchor without href, no tabindex set" ); <ide> }); <ide> test( "attr('tabindex', value)", function() { <ide> expect( 9 ); <ide> <ide> var element = jQuery("#divWithNoTabIndex"); <del> equal( element.attr("tabindex"), undefined, "start with no tabindex" ); <add> equal( element.attr("tabindex"), null, "start with no tabindex" ); <ide> <ide> // set a positive string <ide> element.attr( "tabindex", "1" ); <ide> test( "removeAttr(String)", function() { <ide> expect( 12 ); <ide> var $first; <ide> <del> equal( jQuery("#mark").removeAttr("class").attr("class"), undefined, "remove class" ); <del> equal( jQuery("#form").removeAttr("id").attr("id"), undefined, "Remove id" ); <del> equal( jQuery("#foo").attr( "style", "position:absolute;" ).removeAttr("style").attr("style"), undefined, "Check removing style attribute" ); <del> equal( jQuery("#form").attr( "style", "position:absolute;" ).removeAttr("style").attr("style"), undefined, "Check removing style attribute on a form" ); <add> equal( jQuery("#mark").removeAttr("class").attr("class"), null, "remove class" ); <add> equal( jQuery("#form").removeAttr("id").attr("id"), null, "Remove id" ); <add> equal( jQuery("#foo").attr( "style", "position:absolute;" ).removeAttr("style").attr("style"), null, "Check removing style attribute" ); <add> equal( jQuery("#form").attr( "style", "position:absolute;" ).removeAttr("style").attr("style"), null, "Check removing style attribute on a form" ); <ide> equal( jQuery("<div style='position: absolute'></div>").appendTo("#foo").removeAttr("style").prop("style").cssText, "", "Check removing style attribute (#9699 Webkit)" ); <ide> equal( jQuery("#fx-test-group").attr( "height", "3px" ).removeAttr("height").get( 0 ).style.height, "1px", "Removing height attribute has no effect on height set with style attribute" ); <ide> <ide> test( "removeAttr(String)", function() { <ide> <ide> try { <ide> $first = jQuery("#first").attr( "contenteditable", "true" ).removeAttr("contenteditable"); <del> equal( $first.attr("contenteditable"), undefined, "Remove the contenteditable attribute" ); <add> equal( $first.attr("contenteditable"), null, "Remove the contenteditable attribute" ); <ide> } catch( e ) { <ide> ok( false, "Removing contenteditable threw an error (#10429)" ); <ide> } <ide> <ide> $first = jQuery("<div Case='mixed'></div>"); <ide> equal( $first.attr("Case"), "mixed", "case of attribute doesn't matter" ); <ide> $first.removeAttr("Case"); <del> equal( $first.attr( "Case" ), undefined, "mixed-case attribute was removed" ); <add> equal( $first.attr( "Case" ), null, "mixed-case attribute was removed" ); <ide> }); <ide> <ide> test( "removeAttr(String) in XML", function() { <ide> test( "removeAttr(String) in XML", function() { <ide> iwt.removeAttr("Normal"); <ide> equal( iwt.attr("normal"), "ab", "Should still be there" ); <ide> iwt.removeAttr("normal"); <del> equal( iwt.attr("normal"), undefined, "Removed" ); <add> equal( iwt.attr("normal"), null, "Removed" ); <ide> <ide> equal( iwt.attr("mixedCase"), "yes", "Check initial value" ); <del> equal( iwt.attr("mixedcase"), undefined, "toLowerCase not work good" ); <add> equal( iwt.attr("mixedcase"), null, "toLowerCase not work good" ); <ide> iwt.removeAttr("mixedcase"); <ide> equal( iwt.attr("mixedCase"), "yes", "Should still be there" ); <ide> iwt.removeAttr("mixedCase"); <del> equal( iwt.attr("mixedCase"), undefined, "Removed" ); <add> equal( iwt.attr("mixedCase"), null, "Removed" ); <ide> }); <ide> <ide> test( "removeAttr(Multi String, variable space width)", function() { <ide> test( "removeAttr(Multi String, variable space width)", function() { <ide> div.removeAttr( "id alt title rel " ); <ide> <ide> jQuery.each( tests, function( key ) { <del> equal( div.attr( key ), undefined, "Attribute `" + key + "` was removed" ); <add> equal( div.attr( key ), null, "Attribute `" + key + "` was removed" ); <ide> }); <ide> }); <ide> <ide> var testRemoveClass = function(valueObj) { <ide> <ide> <ide> jQuery( div ).removeClass( valueObj("foo") ); <del> strictEqual( jQuery( div ).attr("class"), undefined, "removeClass doesn't create a class attribute" ); <add> strictEqual( jQuery( div ).attr("class"), null, "removeClass doesn't create a class attribute" ); <ide> <ide> div.className = " test foo "; <ide>
2
Python
Python
fix lr decay in tf trainer
7cb52f53ef65317d5227f5b0ddaa09cbd0b9c0c3
<ide><path>src/transformers/trainer_tf.py <ide> import logging <ide> import math <ide> import os <add>import random <ide> from typing import Callable, Dict, Optional, Tuple <ide> <ide> import numpy as np <ide> logger = logging.getLogger(__name__) <ide> <ide> <add>def set_seed(seed: int): <add> random.seed(seed) <add> np.random.seed(seed) <add> tf.random.set_seed(seed) <add> <add> <ide> class TFTrainer: <ide> model: TFPreTrainedModel <ide> args: TFTrainingArguments <ide> def __init__( <ide> self.tb_writer = tb_writer <ide> else: <ide> self.tb_writer = tf.summary.create_file_writer(self.args.logging_dir) <add> <ide> if is_wandb_available(): <ide> self._setup_wandb() <ide> else: <ide> def __init__( <ide> "run `pip install wandb; wandb login` see https://docs.wandb.com/huggingface." <ide> ) <ide> <add> set_seed(self.args.seed) <add> <ide> def get_train_tfdataset(self) -> tf.data.Dataset: <ide> if self.train_dataset is None: <ide> raise ValueError("Trainer: training requires a train_dataset.") <ide> def get_test_tfdataset(self, test_dataset: tf.data.Dataset) -> tf.data.Dataset: <ide> return self.args.strategy.experimental_distribute_dataset(ds) <ide> <ide> def get_optimizers( <del> self, <add> self, num_training_steps: int, <ide> ) -> Tuple[tf.keras.optimizers.Optimizer, tf.keras.optimizers.schedules.LearningRateSchedule]: <ide> """ <ide> Setup the optimizer and the learning rate scheduler. <ide> def get_optimizers( <ide> <ide> optimizer, scheduler = create_optimizer( <ide> self.args.learning_rate, <del> self.train_steps, <add> num_training_steps, <ide> self.args.warmup_steps, <ide> adam_epsilon=self.args.adam_epsilon, <ide> weight_decay_rate=self.args.weight_decay, <ide> def _prediction_loop( <ide> return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics) <ide> <ide> def _log(self, logs: Dict[str, float]) -> None: <add> logs["epoch"] = self.epoch_logging <add> <ide> if self.tb_writer: <ide> with self.tb_writer.as_default(): <ide> for k, v in logs.items(): <ide> tf.summary.scalar(k, v, step=self.global_step) <ide> self.tb_writer.flush() <add> <ide> if is_wandb_available(): <ide> wandb.log(logs, step=self.global_step) <add> <ide> output = {**logs, **{"step": self.global_step}} <add> <ide> logger.info(output) <ide> <ide> def evaluate( <ide> def evaluate( <ide> <ide> logs = {**output.metrics} <ide> logs["epoch"] = self.epoch_logging <add> <ide> self._log(logs) <ide> <ide> return output.metrics <ide> def train(self) -> None: <ide> <ide> self.gradient_accumulator.reset() <ide> <add> if self.args.max_steps > 0: <add> t_total = self.args.max_steps <add> steps_per_epoch = self.args.max_steps <add> else: <add> if self.args.dataloader_drop_last: <add> approx = math.floor <add> else: <add> approx = math.ceil <add> <add> steps_per_epoch = approx( <add> self.num_train_examples / (self.args.train_batch_size * self.args.gradient_accumulation_steps) <add> ) <add> t_total = steps_per_epoch * self.args.num_train_epochs <add> <ide> with self.args.strategy.scope(): <del> optimizer, lr_scheduler = self.get_optimizers() <add> optimizer, lr_scheduler = self.get_optimizers(num_training_steps=t_total) <ide> iterations = optimizer.iterations <add> self.global_step = iterations.numpy() <ide> folder = os.path.join(self.args.output_dir, PREFIX_CHECKPOINT_DIR) <ide> ckpt = tf.train.Checkpoint(optimizer=optimizer, model=self.model) <ide> self.model.ckpt_manager = tf.train.CheckpointManager(ckpt, folder, max_to_keep=self.args.save_total_limit) <ide> <ide> if self.model.ckpt_manager.latest_checkpoint: <add> epochs_trained = self.global_step // (self.num_train_examples // self.args.gradient_accumulation_steps) <add> steps_trained_in_current_epoch = self.global_step % ( <add> self.num_train_examples // self.args.gradient_accumulation_steps <add> ) <add> <add> logger.info(" Continuing training from checkpoint, will skip to saved global_step") <add> logger.info(" Continuing training from epoch %d", epochs_trained) <add> logger.info(" Continuing training from global step %d", self.global_step) <add> logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch) <ide> logger.info( <ide> "Checkpoint file %s found and restoring from checkpoint", self.model.ckpt_manager.latest_checkpoint <ide> ) <ide> <ide> ckpt.restore(self.model.ckpt_manager.latest_checkpoint).expect_partial() <del> <del> if iterations.numpy() > 0: <del> logger.info("Start the training from the last checkpoint") <del> start_epoch = (iterations.numpy() // self.train_steps) + 1 <del> else: <del> start_epoch = 1 <add> else: <add> epochs_trained = 1 <ide> <ide> tf.summary.experimental.set_step(iterations) <ide> <ide> def train(self) -> None: <ide> logger.info("***** Running training *****") <ide> logger.info(" Num examples = %d", self.num_train_examples) <ide> logger.info(" Num Epochs = %d", epochs) <del> logger.info(" Total optimization steps = %d", self.train_steps) <add> logger.info(" Instantaneous batch size per device = %d", self.args.per_device_train_batch_size) <add> logger.info( <add> " Total train batch size (w. parallel, distributed & accumulation) = %d", self.args.train_batch_size <add> ) <add> logger.info(" Gradient Accumulation steps = %d", self.args.gradient_accumulation_steps) <add> logger.info(" Total optimization steps = %d", t_total) <ide> <del> for epoch_iter in range(start_epoch, int(epochs + 1)): <add> for epoch_iter in range(epochs_trained, int(epochs + 1)): <ide> for step, training_loss in enumerate(self._training_steps(train_ds, optimizer)): <ide> self.global_step = iterations.numpy() <del> self.epoch_logging = epoch_iter - 1 + (step + 1) / self.train_steps <add> self.epoch_logging = epoch_iter - 1 + (step + 1) / steps_per_epoch <ide> <ide> if self.args.debug: <ide> logs = {} <ide> logs["loss"] = training_loss.numpy() <ide> logs["epoch"] = self.epoch_logging <add> <ide> self._log(logs) <ide> <ide> if self.global_step == 1 and self.args.debug: <ide> def train(self) -> None: <ide> if self.args.evaluate_during_training and self.global_step % self.args.eval_steps == 0: <ide> self.evaluate() <ide> <del> if self.global_step % self.args.logging_steps == 0: <add> if ( <add> self.global_step % self.args.logging_steps == 0 <add> or self.global_step == 1 <add> and self.args.logging_first_step <add> ): <ide> logs = {} <ide> logs["loss"] = training_loss.numpy() <ide> logs["learning_rate"] = lr_scheduler(self.global_step).numpy() <ide> logs["epoch"] = self.epoch_logging <add> <ide> self._log(logs) <ide> <ide> if self.global_step % self.args.save_steps == 0: <ide> ckpt_save_path = self.model.ckpt_manager.save() <ide> logger.info("Saving checkpoint for step {} at {}".format(self.global_step, ckpt_save_path)) <ide> <del> if self.global_step % self.train_steps == 0: <add> if self.args.max_steps > 0 and self.global_step % self.args.max_steps == 0: <ide> break <ide> <ide> def _training_steps(self, ds, optimizer):
1
PHP
PHP
fix incorrect help
c5f0bcf23ded2cc61a4fa654b23d3c0d05cf97f0
<ide><path>src/Command/CacheClearCommand.php <ide> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar <ide> ->addArgument('engine', [ <ide> 'help' => 'The cache engine to clear.' . <ide> 'For example, `cake cache clear _cake_model_` will clear the model cache' . <del> 'Use `cake cache list_engines` to list available engines', <add> 'Use `cake cache list` to list available engines', <ide> 'required' => true, <ide> ]); <ide>
1