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
Text
Text
fix some indentation and change some typo
d93ad2c00b9410bb6489a04fc8cb202d08556e9f
<ide><path>guide/english/cplusplus/if-else-statement/index.md <ide> else <ide> //Program to check whether number entered by user is positive or negative <ide> #include <iostream> <ide> using namespace std; <add> <ide> int main() <ide> { <ide> int no; <ide> cout << "Enter a number: " << endl; <del> <ide> cin >> no; <ide> <ide> // condition to check if number is positive or negative <ide> This step is always printed <ide> If we have to make decisions based on more than one conditions using if else. We use else if condition as follows - <ide> ```cpp <ide> #include<iostream> <add>using namespace std; <add> <ide> int main() <ide> { <ide> int score; <del> std::cout<<"Enter your score: \n"; <del> std::cin>>score; <del> if(score>=90) <del> std::cout<<"Top performance."; <del> else if(score<90 && score>=70) <del> std::cout<<"Good performance"; <del> else if(score<70 && score>=45) <del> std::cout<<"Average performance"; <del> else if(score<45 && score>=30) <del> std::cout<<"You can improve it."; <add> cout << "Enter your score: \n"; <add> cin >> score; <add> <add> if (score >= 90) <add> cout << "Top performance."; <add> else if (score < 90 && score >= 70) <add> cout << "Good performance"; <add> else if (score < 70 && score >= 45) <add> cout << "Average performance"; <add> else if (score < 45 && score >= 30) <add> cout << "You can improve it."; <ide> return 0; <ide> } <ide> ``` <ide> Good performance <ide> ### Another example of if...else if...else ladder <ide> Suppose we have the user input two numbers and we are going to display if either number is greater than the other. And if neither is greater than the other, then we print the statement "Both are equal". <ide> <del>In this scinerio we will need an if...else if...else ladder statement. The program will look like this : <add>In this scenario, we will need an if...else if...else ladder statement. The program will look like this : <ide> <ide> ``` <ide> #include<iostream> <ide> using namespace std; <add> <ide> int main() <ide> { <ide> int number1,number2; <ide> int main() <ide> cout << "Enter second number: \n"; <ide> cin >> number2; <ide> <del> if(number1 > number2) // Checks if the first number is greater than the second number <add> if (number1 > number2) // Checks if the first number is greater than the second number <ide> { <ide> cout << "Number 1 is greater."; <ide> } <del> else if(number2 > number1) // Checks if the second number is greater than the first number <add> else if (number2 > number1) // Checks if the second number is greater than the first number <ide> { <ide> cout << "Number 2 is greater."; <ide> }
1
Ruby
Ruby
add debug output to install name machinery
f458fa9e9aafe01c86054209b5f7da3f80cf9501
<ide><path>Library/Homebrew/keg_fix_install_names.rb <ide> def relocate_install_names old_prefix, new_prefix, old_cellar, new_cellar, optio <ide> end <ide> <ide> def change_dylib_id(id, file) <add> puts "Changing dylib ID in #{file} to #{id}" if ARGV.debug? <ide> install_name_tool("-id", id, file) <ide> end <ide> <ide> def change_install_name(old, new, file) <add> puts "Changing install name in #{file} from #{old} to #{new}" if ARGV.debug? <ide> install_name_tool("-change", old, new, file) <ide> end <ide>
1
Javascript
Javascript
use shell mode for windows support
30c35abb44bdc6da4c0093f4cd144e8af5313cfb
<ide><path>bin/webpack.js <ide> function runCommand(command, options) { <ide> const cp = require("child_process"); <ide> return new Promise((resolve, reject) => { <ide> const executedCommand = cp.spawn(command, options, { <del> stdio: "inherit" <add> stdio: "inherit", <add> shell: true <ide> }); <ide> <ide> executedCommand.on("error", error => { <ide> if (!webpackCliInstalled) { <ide> <ide> const commandToBeRun = `${packageManager} ${options.join(" ")}`; <ide> <del> const question = `Would you like to install webpack-cli? (That will run ${commandToBeRun}) `; <add> const question = `Would you like to install webpack-cli? (That will run ${commandToBeRun}) (yes/NO)`; <ide> <ide> console.error("The CLI moved into a separate package: webpack-cli"); <ide> const questionInterface = readLine.createInterface({
1
PHP
PHP
add ssl context options to socket
5dc186bbb9fe4bb68a47b569514008ff7b33a77f
<ide><path>src/Network/Socket.php <ide> public function connect() <ide> $scheme = $this->_config['protocol'] . '://'; <ide> } <ide> <add> $this->_setSslContext($this->_config['host']); <ide> if (!empty($this->_config['context'])) { <ide> $context = stream_context_create($this->_config['context']); <ide> } else { <ide> public function connect() <ide> return $this->connected; <ide> } <ide> <add> /** <add> * Configure the SSL context options. <add> * <add> * @param string $host The host name being connected to. <add> */ <add> protected function _setSslContext($host) { <add> foreach ($this->_config as $key => $value) { <add> if (substr($key, 0, 4) !== 'ssl_') { <add> continue; <add> } <add> $contextKey = substr($key, 4); <add> if (empty($this->_config['context']['ssl'][$contextKey])) { <add> $this->_config['context']['ssl'][$contextKey] = $value; <add> } <add> unset($this->_config[$key]); <add> } <add> if (!isset($this->_config['context']['ssl']['SNI_enabled'])) { <add> $this->_config['context']['ssl']['SNI_enabled'] = true; <add> } <add> if (version_compare(PHP_VERSION, '5.6.0', '>=')) { <add> if (empty($this->_config['context']['ssl']['peer_name'])) { <add> $this->_config['context']['ssl']['peer_name'] = $host; <add> } <add> } else { <add> if (empty($this->_config['context']['ssl']['SNI_server_name'])) { <add> $this->_config['context']['ssl']['SNI_server_name'] = $host; <add> } <add> } <add> if (empty($this->_config['context']['ssl']['cafile'])) { <add> $dir = dirname(__DIR__); <add> $this->_config['context']['ssl']['cafile'] = $dir . DIRECTORY_SEPARATOR . <add> 'config' . DIRECTORY_SEPARATOR . 'cacert.pem'; <add> } <add> if (!empty($this->_config['context']['ssl']['verify_host'])) { <add> $this->_config['context']['ssl']['CN_match'] = $host; <add> } <add> unset($this->_config['context']['ssl']['verify_host']); <add> } <add> <ide> /** <ide> * socket_stream_client() does not populate errNum, or $errStr when there are <ide> * connection errors, as in the case of SSL verification failure. <ide><path>tests/TestCase/Network/SocketTest.php <ide> public function testGetContext() <ide> $this->markTestSkipped('No network, skipping test.'); <ide> } <ide> $result = $this->Socket->context(); <del> $this->assertEquals($config['context'], $result); <add> $this->assertTrue($result['ssl']['capture_peer']); <add> } <add> <add> /** <add> * test configuring the context from the flat keys. <add> * <add> * @return void <add> */ <add> public function testConfigContext() { <add> $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.'); <add> $config = array( <add> 'host' => 'smtp.gmail.com', <add> 'port' => 465, <add> 'timeout' => 5, <add> 'ssl_verify_peer' => true, <add> 'ssl_allow_self_signed' => false, <add> 'ssl_verify_depth' => 5, <add> 'ssl_verify_host' => true, <add> ); <add> $socket = new Socket($config); <add> <add> $socket->connect(); <add> $result = $socket->context(); <add> <add> $this->assertTrue($result['ssl']['verify_peer']); <add> $this->assertFalse($result['ssl']['allow_self_signed']); <add> $this->assertEquals(5, $result['ssl']['verify_depth']); <add> $this->assertEquals('smtp.gmail.com', $result['ssl']['CN_match']); <add> $this->assertArrayNotHasKey('ssl_verify_peer', $socket->config()); <add> $this->assertArrayNotHasKey('ssl_allow_self_signed', $socket->config()); <add> $this->assertArrayNotHasKey('ssl_verify_host', $socket->config()); <add> $this->assertArrayNotHasKey('ssl_verify_depth', $socket->config()); <ide> } <ide> }
2
Python
Python
fix tok2vec for empty batches
cf5b46b63e91b9a2881c3a7d52bb9d2856c809f2
<ide><path>spacy/pipeline/tok2vec.py <ide> def predict(self, docs: Iterable[Doc]): <ide> <ide> DOCS: https://spacy.io/api/tok2vec#predict <ide> """ <add> if not any(len(doc) for doc in docs): <add> # Handle cases where there are no tokens in any docs. <add> width = self.model.get_dim("nO") <add> return [self.model.ops.alloc((0, width)) for doc in docs] <ide> tokvecs = self.model.predict(docs) <ide> batch_id = Tok2VecListener.get_batch_id(docs) <ide> for listener in self.listeners: <ide><path>spacy/tests/pipeline/test_tok2vec.py <ide> from thinc.api import Config, get_current_ops <ide> from numpy.testing import assert_array_equal <ide> <del>from ..util import get_batch, make_tempdir <add>from ..util import get_batch, make_tempdir, add_vecs_to_vocab <ide> <ide> <ide> def test_empty_doc(): <ide> def test_init_tok2vec(): <ide> ] <ide> <ide> <del>def test_tok2vec_listener(): <add>@pytest.mark.parametrize("with_vectors", (False, True)) <add>def test_tok2vec_listener(with_vectors): <ide> orig_config = Config().from_str(cfg_string) <add> orig_config["components"]["tok2vec"]["model"]["embed"][ <add> "include_static_vectors" <add> ] = with_vectors <ide> nlp = util.load_model_from_config(orig_config, auto_fill=True, validate=True) <add> <add> if with_vectors: <add> ops = get_current_ops() <add> vectors = [ <add> ("apple", ops.asarray([1, 2, 3])), <add> ("orange", ops.asarray([-1, -2, -3])), <add> ("and", ops.asarray([-1, -1, -1])), <add> ("juice", ops.asarray([5, 5, 10])), <add> ("pie", ops.asarray([7, 6.3, 8.9])), <add> ] <add> add_vecs_to_vocab(nlp.vocab, vectors) <add> <ide> assert nlp.pipe_names == ["tok2vec", "tagger"] <ide> tagger = nlp.get_pipe("tagger") <ide> tok2vec = nlp.get_pipe("tok2vec") <ide> def test_tok2vec_listener(): <ide> ops = get_current_ops() <ide> assert_array_equal(ops.to_numpy(doc.tensor), ops.to_numpy(doc_tensor)) <ide> <add> # test with empty doc <add> doc = nlp("") <add> <ide> # TODO: should this warn or error? <ide> nlp.select_pipes(disable="tok2vec") <ide> assert nlp.pipe_names == ["tagger"]
2
Text
Text
update changelog for 1.5.0-beta.3
1a13d839f301e2e0f7e6dd6f64b673e18d6423a2
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### Ember 1.5.0-beta.3 (March 1, 2014) <add> <add>* [BUGFIX] PromiseProxyMixin reset isFulfilled and isRejected. <add>* Use documentElement instead of body for ember-extension detection. <add>* Many documentation updates. <ide> <ide> ### Ember 1.5.0-beta.2 (February 23, 2014) <ide>
1
Text
Text
add v4.6.0 to changelog
6dbd66eaa82fafcbc443f4f00403deeb7c6f5230
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v4.6.0-beta.2 (June 27, 2022) <add>### v4.6.0 (July 25, 2022) <ide> <ide> - [#20125](https://github.com/emberjs/ember.js/pull/20125) [BUGFIX] Replace deprecated substr() method with substring() method. <del>- [#20120](https://github.com/emberjs/ember.js/pull/20120) [BUGFIX] Adjust uniqueId() implementation to only generate valid selectors. <del> <del>### v4.6.0-beta.1 (June 13, 2022) <del> <del>No new external changes. <ide> <ide> ### v4.5.1 (July 25, 2022) <ide>
1
Text
Text
add language-text to build list
3b309792a531fb809d29c6742de956f50b3acec5
<ide><path>docs/build-instructions/build-status.md <ide> | [Sass](https://github.com/atom/language-sass) | [![macOS Build Status](https://travis-ci.org/atom/language-sass.svg?branch=master)](https://travis-ci.org/atom/language-sass) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/g7p16vainm4iuoot/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-sass/branch/master) | <ide> | [ShellScript](https://github.com/atom/language-shellscript) | [![macOS Build Status](https://travis-ci.org/atom/language-shellscript.svg?branch=master)](https://travis-ci.org/atom/language-shellscript) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/p4um3lowgrg8y0ty/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-shellscript/branch/master) | <ide> | [SQL](https://github.com/atom/language-sql) | [![macOS Build Status](https://travis-ci.org/atom/language-sql.svg?branch=master)](https://travis-ci.org/atom/language-sql) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/ji31ouk5ehs4jdu1/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-sql/branch/master) | <add>| [Text](https://github.com/atom/language-text) | [![macOS Build Status](https://travis-ci.org/atom/language-text.svg?branch=master)](https://travis-ci.org/atom/language-text) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/psnekekg8lon67dw/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-text/branch/master) | <ide> | [TODO](https://github.com/atom/language-todo) | [![macOS Build Status](https://travis-ci.org/atom/language-todo.svg?branch=master)](https://travis-ci.org/atom/language-todo) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/gcgb9m7h146lv6qp/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-todo/branch/master) | <ide> | [TOML](https://github.com/atom/language-toml) | [![macOS Build Status](https://travis-ci.org/atom/language-toml.svg?branch=master)](https://travis-ci.org/atom/language-toml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/kohao3fjyk6xv0sc/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-toml/branch/master) | <ide> | [XML](https://github.com/atom/language-xml) | [![macOS Build Status](https://travis-ci.org/atom/language-xml.svg?branch=master)](https://travis-ci.org/atom/language-xml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/m5f6rn74a6h3q5uq/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-xml/branch/master) |
1
PHP
PHP
add exit status to workstopping event.
ea3b5e5300be3824cee30dfa9608d27d8432addf
<ide><path>src/Illuminate/Queue/Events/WorkerStopping.php <ide> <ide> class WorkerStopping <ide> { <del> // <add> /** <add> * The exit status. <add> * <add> * @var int <add> */ <add> public $status; <add> <add> /** <add> * Create a new event instance. <add> * <add> * @param int $status <add> * @return void <add> */ <add> public function __construct($status = 0) <add> { <add> $this->status = $status; <add> } <ide> } <ide><path>src/Illuminate/Queue/Worker.php <ide> public function memoryExceeded($memoryLimit) <ide> */ <ide> public function stop($status = 0) <ide> { <del> $this->events->dispatch(new Events\WorkerStopping); <add> $this->events->dispatch(new Events\WorkerStopping($status)); <ide> <ide> exit($status); <ide> } <ide> public function stop($status = 0) <ide> */ <ide> public function kill($status = 0) <ide> { <del> $this->events->dispatch(new Events\WorkerStopping); <add> $this->events->dispatch(new Events\WorkerStopping($status)); <ide> <ide> if (extension_loaded('posix')) { <ide> posix_kill(getmypid(), SIGKILL);
2
Text
Text
remove stub information from a guide article
44445fec7225cac66040db17960a92e95a4e9d08
<ide><path>guide/english/mathematics/exponents-basic-rules/index.md <ide> title: Exponents Basic Rules <ide> --- <ide> ## Exponents Basic Rules <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/exponents-basic-rules/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <del> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <del> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <ide> ### Rules of Exponents <ide> The nine laws for exponents are: <ide> - x<sup>1</sup> = x <ide> The nine laws for exponents are: <ide> <ide> ## 0<sup>0</sup> = ? <ide> <del>0<sup>0</sup> has no correct answear but is generally taken as 1. More information about it can be found [here](https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero) <add>0<sup>0</sup> has no correct answear but is generally taken as 1. More information about it can be found [here](https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero). <ide> <ide> #### More Information: <ide> - https://www.mathsisfun.com/algebra/exponent-laws.html <ide> - https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero <del><!-- Please add any articles you think might be helpful to read before writing the article --> <del> <del>
1
PHP
PHP
fix phpdocs for json resources
227c71b3011740987fab7cf317312bbfb02b562c
<ide><path>src/Illuminate/Http/Resources/Json/JsonResource.php <ide> public function resolve($request = null) <ide> * Transform the resource into an array. <ide> * <ide> * @param \Illuminate\Http\Request $request <del> * @return array <add> * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable <ide> */ <ide> public function toArray($request) <ide> { <ide><path>src/Illuminate/Http/Resources/Json/ResourceCollection.php <ide> public function count() <ide> * Transform the resource into a JSON array. <ide> * <ide> * @param \Illuminate\Http\Request $request <del> * @return array <add> * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable <ide> */ <ide> public function toArray($request) <ide> {
2
Ruby
Ruby
remove all sudo references from ci build script
a4c32897585dde2b939b269f23ea537393e6fc0b
<ide><path>ci/ci_build.rb <ide> def rake(*tasks) <ide> puts "[CruiseControl] Rails build" <ide> build_results = {} <ide> <del># Install rubygems-update, so 'gem update --system' in cruise_config.rb auto-installs it on next build. <del># This is how you can auto-update rubygems without logging in to CI system <del>rubygems_install_cmd = "sudo gem install rubygems-update -v 1.3.5 --no-ri --no-rdoc" <del>puts "Running command: #{rubygems_install_cmd}" <del>build_results[:install_rubygems_update] = system rubygems_install_cmd <del> <ide> # Install required version of bundler. <del>bundler_install_cmd = "sudo gem install bundler -v 0.9.3 --no-ri --no-rdoc" <add>bundler_install_cmd = "gem install bundler -v 0.9.3 --no-ri --no-rdoc" <ide> puts "Running command: #{bundler_install_cmd}" <ide> build_results[:install_bundler] = system bundler_install_cmd <ide>
1
Python
Python
authorize last version of tokenizer
21b3922e35529dfbf9213365d7d37756a59f8e0e
<ide><path>scripts/check_tokenizers.py <add>from collections import Counter <add>import datasets <add>import transformers <add>from transformers.convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS <add> <add>from transformers.utils import logging <add> <add>logging.set_verbosity_info() <add> <add>TOKENIZER_CLASSES = { <add> name: (getattr(transformers, name), getattr(transformers, name + "Fast")) for name in SLOW_TO_FAST_CONVERTERS <add>} <add> <add>dataset = datasets.load_dataset("xnli", split="test+validation") <add> <add>total = 0 <add>perfect = 0 <add>imperfect = 0 <add>wrong = 0 <add> <add> <add>def check_diff(spm_diff, tok_diff, slow, fast): <add> if spm_diff == list(reversed(tok_diff)): <add> # AAA -> AA+A vs A+AA case. <add> return True <add> elif len(spm_diff) == len(tok_diff) and fast.decode(spm_diff) == fast.decode(tok_diff): <add> # Second order OK <add> # Barrich -> Barr + ich vs Bar + rich <add> return True <add> spm_reencoded = slow.encode(slow.decode(spm_diff)) <add> tok_reencoded = fast.encode(fast.decode(spm_diff)) <add> if spm_reencoded != spm_diff and spm_reencoded == tok_reencoded: <add> # Type 3 error. <add> # Snehagatha -> <add> # Sne, h, aga, th, a <add> # Sne, ha, gat, ha <add> # Encoding the wrong with sp does not even recover what spm gave us <add> # It fits tokenizer however... <add> return True <add> return False <add> <add> <add>def check_LTR_mark(line, idx, fast): <add> enc = fast.encode_plus(line)[0] <add> offsets = enc.offsets <add> curr, prev = offsets[idx], offsets[idx - 1] <add> if curr is not None and line[curr[0] : curr[1]] == "\u200f": <add> return True <add> if prev is not None and line[prev[0] : prev[1]] == "\u200f": <add> return True <add> <add> <add>def check_details(line, spm_ids, tok_ids, slow, fast): <add> # Encoding can be the same with same result AAA -> A + AA vs AA + A <add> # We can check that we use at least exactly the same number of tokens. <add> for i, (spm_id, tok_id) in enumerate(zip(spm_ids, tok_ids)): <add> if spm_id != tok_id: <add> break <add> first = i <add> for i, (spm_id, tok_id) in enumerate(zip(reversed(spm_ids), reversed(tok_ids))): <add> if spm_id != tok_id: <add> break <add> last = len(spm_ids) - i <add> <add> spm_diff = spm_ids[first:last] <add> tok_diff = tok_ids[first:last] <add> <add> if check_diff(spm_diff, tok_diff, slow, fast): <add> return True <add> <add> if check_LTR_mark(line, first, fast): <add> return True <add> <add> if last - first > 5: <add> # We might have twice a single problem, attempt to subdivide the disjointed tokens into smaller problems <add> spms = Counter(spm_ids[first:last]) <add> toks = Counter(tok_ids[first:last]) <add> <add> removable_tokens = {spm_ for (spm_, si) in spms.items() if toks.get(spm_, 0) == si} <add> min_width = 3 <add> for i in range(last - first - min_width): <add> if all(spm_ids[first + i + j] in removable_tokens for j in range(min_width)): <add> possible_matches = [ <add> k <add> for k in range(last - first - min_width) <add> if tok_ids[first + k : first + k + min_width] == spm_ids[first + i : first + i + min_width] <add> ] <add> for j in possible_matches: <add> if check_diff(spm_ids[first : first + i], tok_ids[first : first + j], sp, tok) and check_details( <add> line, <add> spm_ids[first + i : last], <add> tok_ids[first + j : last], <add> slow, <add> fast, <add> ): <add> return True <add> <add> print(f"Spm: {[fast.decode([spm_ids[i]]) for i in range(first, last)]}") <add> try: <add> print(f"Tok: {[fast.decode([tok_ids[i]]) for i in range(first, last)]}") <add> except Exception: <add> pass <add> <add> ok_start = fast.decode(spm_ids[:first]) <add> ok_end = fast.decode(spm_ids[last:]) <add> wrong = fast.decode(spm_ids[first:last]) <add> print() <add> print(wrong) <add> return False <add> <add> <add>def test_string(slow, fast, text): <add> global perfect <add> global imperfect <add> global wrong <add> global total <add> <add> slow_ids = slow.encode(text) <add> fast_ids = fast.encode(text) <add> <add> skip_assert = False <add> total += 1 <add> <add> if slow_ids != fast_ids: <add> if check_details(text, slow_ids, fast_ids, slow, fast): <add> skip_assert = True <add> imperfect += 1 <add> else: <add> wrong += 1 <add> else: <add> perfect += 1 <add> <add> if total % 10000 == 0: <add> print(f"({perfect} / {imperfect} / {wrong} ----- {perfect + imperfect + wrong})") <add> <add> if skip_assert: <add> return <add> <add> assert ( <add> slow_ids == fast_ids <add> ), f"line {text} : \n\n{slow_ids}\n{fast_ids}\n\n{slow.tokenize(text)}\n{fast.tokenize(text)}" <add> <add> <add>def test_tokenizer(slow, fast): <add> global batch_total <add> for i in range(len(dataset)): <add> # premise, all languages <add> for text in dataset[i]["premise"].values(): <add> test_string(slow, fast, text) <add> <add> # hypothesis, all languages <add> for text in dataset[i]["hypothesis"]["translation"]: <add> test_string(slow, fast, text) <add> <add> <add>if __name__ == "__main__": <add> for name, (slow_class, fast_class) in TOKENIZER_CLASSES.items(): <add> checkpoint_names = list(slow_class.max_model_input_sizes.keys()) <add> for checkpoint in checkpoint_names: <add> imperfect = 0 <add> perfect = 0 <add> wrong = 0 <add> total = 0 <add> <add> print(f"========================== Checking {name}: {checkpoint} ==========================") <add> slow = slow_class.from_pretrained(checkpoint, force_download=True) <add> fast = fast_class.from_pretrained(checkpoint, force_download=True) <add> test_tokenizer(slow, fast) <add> print(f"Accuracy {perfect * 100 / total:.2f}") <ide><path>setup.py <ide> "tensorflow-cpu>=2.3", <ide> "tensorflow>=2.3", <ide> "timeout-decorator", <del> "tokenizers==0.9.4", <add> "tokenizers==0.10.1rc1", <ide> "torch>=1.0", <ide> "tqdm>=4.27", <ide> "unidic>=1.0.2", <ide><path>src/transformers/convert_slow_tokenizer.py <ide> <ide> from typing import Dict, List, Tuple <ide> <del>from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors <add>from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors <ide> from tokenizers.models import BPE, Unigram, WordPiece <ide> <ide> from .file_utils import requires_protobuf, requires_sentencepiece <ide> def tokenizer(self, proto): <ide> <ide> def normalizer(self, proto): <ide> precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap <del> return normalizers.Precompiled(precompiled_charsmap) <add> return normalizers.Sequence( <add> [normalizers.Precompiled(precompiled_charsmap), normalizers.Replace(Regex(" {2,}"), " ")] <add> ) <add> <add> def pre_tokenizer(self, replacement, add_prefix_space): <add> return pre_tokenizers.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space) <ide> <ide> def post_processor(self): <ide> return None <ide> def converted(self) -> Tokenizer: <ide> <ide> replacement = "▁" <ide> add_prefix_space = True <del> tokenizer.pre_tokenizer = pre_tokenizers.Sequence( <del> [ <del> pre_tokenizers.WhitespaceSplit(), <del> pre_tokenizers.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space), <del> ] <del> ) <add> tokenizer.pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space) <ide> tokenizer.decoder = decoders.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space) <ide> post_processor = self.post_processor() <ide> if post_processor: <ide> def vocab(self, proto): <ide> ] <ide> <ide> def normalizer(self, proto): <del> list_normalizers = [normalizers.Replace("``", '"'), normalizers.Replace("''", '"')] <add> list_normalizers = [ <add> normalizers.Replace("``", '"'), <add> normalizers.Replace("''", '"'), <add> normalizers.Replace(Regex(" {2,}"), " "), <add> ] <ide> if not self.original_tokenizer.keep_accents: <ide> list_normalizers.append(normalizers.NFKD()) <ide> list_normalizers.append(normalizers.StripAccents()) <ide> def vocab(self, proto): <ide> ] <ide> <ide> def normalizer(self, proto): <del> list_normalizers = [normalizers.Replace("``", '"'), normalizers.Replace("''", '"')] <add> list_normalizers = [ <add> normalizers.Replace("``", '"'), <add> normalizers.Replace("''", '"'), <add> normalizers.Replace(Regex(" {2,}"), " "), <add> ] <ide> if not self.original_tokenizer.keep_accents: <ide> list_normalizers.append(normalizers.NFKD()) <ide> list_normalizers.append(normalizers.StripAccents()) <ide> def vocab(self, proto): <ide> def unk_id(self, proto): <ide> return proto.trainer_spec.unk_id + self.original_tokenizer.offset <ide> <add> def pre_tokenizer(self, replacement, add_prefix_space): <add> return pre_tokenizers.Sequence( <add> [ <add> pre_tokenizers.WhitespaceSplit(), <add> pre_tokenizers.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space), <add> ] <add> ) <add> <ide> def post_processor(self): <ide> eos = self.original_tokenizer.eos_token <ide> special_tokens = [ <ide><path>src/transformers/dependency_versions_table.py <ide> "tensorflow-cpu": "tensorflow-cpu>=2.3", <ide> "tensorflow": "tensorflow>=2.3", <ide> "timeout-decorator": "timeout-decorator", <del> "tokenizers": "tokenizers==0.9.4", <add> "tokenizers": "tokenizers==0.10.1rc1", <ide> "torch": "torch>=1.0", <ide> "tqdm": "tqdm>=4.27", <ide> "unidic": "unidic>=1.0.2", <ide><path>src/transformers/models/albert/tokenization_albert.py <ide> <ide> import sentencepiece as spm <ide> <del>from ...tokenization_utils import PreTrainedTokenizer <add>from ...tokenization_utils import AddedToken, PreTrainedTokenizer <ide> from ...utils import logging <ide> <ide> <ide> def __init__( <ide> mask_token="[MASK]", <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> do_lower_case=do_lower_case, <ide> remove_space=remove_space, <ide><path>src/transformers/models/albert/tokenization_albert_fast.py <ide> from typing import List, Optional, Tuple <ide> <ide> from ...file_utils import is_sentencepiece_available <add>from ...tokenization_utils import AddedToken <ide> from ...tokenization_utils_fast import PreTrainedTokenizerFast <ide> from ...utils import logging <ide> <ide> def __init__( <ide> mask_token="[MASK]", <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> vocab_file, <ide> tokenizer_file=tokenizer_file, <ide><path>src/transformers/models/barthez/tokenization_barthez.py <ide> <ide> import sentencepiece as spm <ide> <del>from ...tokenization_utils import PreTrainedTokenizer <add>from ...tokenization_utils import AddedToken, PreTrainedTokenizer <ide> from ...utils import logging <ide> <ide> <ide> def __init__( <ide> mask_token="<mask>", <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> bos_token=bos_token, <ide> eos_token=eos_token, <ide><path>src/transformers/models/barthez/tokenization_barthez_fast.py <ide> from typing import List, Optional, Tuple <ide> <ide> from ...file_utils import is_sentencepiece_available <add>from ...tokenization_utils import AddedToken <ide> from ...tokenization_utils_fast import PreTrainedTokenizerFast <ide> from ...utils import logging <ide> <ide> def __init__( <ide> mask_token="<mask>", <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> vocab_file, <ide> tokenizer_file=tokenizer_file, <ide><path>src/transformers/models/camembert/tokenization_camembert.py <ide> <ide> import sentencepiece as spm <ide> <del>from ...tokenization_utils import PreTrainedTokenizer <add>from ...tokenization_utils import AddedToken, PreTrainedTokenizer <ide> from ...utils import logging <ide> <ide> <ide> def __init__( <ide> additional_special_tokens=["<s>NOTUSED", "</s>NOTUSED"], <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> bos_token=bos_token, <ide> eos_token=eos_token, <ide><path>src/transformers/models/camembert/tokenization_camembert_fast.py <ide> from typing import List, Optional, Tuple <ide> <ide> from ...file_utils import is_sentencepiece_available <add>from ...tokenization_utils import AddedToken <ide> from ...tokenization_utils_fast import PreTrainedTokenizerFast <ide> from ...utils import logging <ide> <ide> def __init__( <ide> additional_special_tokens=["<s>NOTUSED", "</s>NOTUSED"], <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> vocab_file, <ide> tokenizer_file=tokenizer_file, <ide><path>src/transformers/models/pegasus/tokenization_pegasus.py <ide> VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"} <ide> <ide> PRETRAINED_VOCAB_FILES_MAP = { <del> "vocab_file": {"google/pegasus-xsum": "https://cdn.huggingface.co/google/pegasus-xsum/spiece.model"} <add> "vocab_file": {"google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"} <ide> } <ide> <ide> PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { <ide><path>src/transformers/models/pegasus/tokenization_pegasus_fast.py <ide> VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} <ide> <ide> PRETRAINED_VOCAB_FILES_MAP = { <del> "vocab_file": {"google/pegasus-xsum": "https://cdn.huggingface.co/google/pegasus-xsum/spiece.model"}, <del> "tokenizer_file": {"google/pegasus-xsum": "https://cdn.huggingface.co/google/pegasus-xsum/tokenizer.json"}, <add> "vocab_file": {"google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"}, <add> "tokenizer_file": { <add> "google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/tokenizer.json" <add> }, <ide> } <ide> <ide> PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { <ide><path>src/transformers/models/reformer/tokenization_reformer.py <ide> #################################################### <ide> PRETRAINED_VOCAB_FILES_MAP = { <ide> "vocab_file": { <del> "google/reformer-crime-and-punishment": "https://cdn.huggingface.co/google/reformer-crime-and-punishment/spiece.model" <add> "google/reformer-crime-and-punishment": "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model" <ide> } <ide> } <ide> <ide><path>src/transformers/models/reformer/tokenization_reformer_fast.py <ide> #################################################### <ide> PRETRAINED_VOCAB_FILES_MAP = { <ide> "vocab_file": { <del> "google/reformer-crime-and-punishment": "https://cdn.huggingface.co/google/reformer-crime-and-punishment/spiece.model" <add> "google/reformer-crime-and-punishment": "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model" <ide> }, <ide> "tokenizer_file": { <del> "google/reformer-crime-and-punishment": "https://cdn.huggingface.co/google/reformer-crime-and-punishment/tokenizer.json" <add> "google/reformer-crime-and-punishment": "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/tokenizer.json" <ide> }, <ide> } <ide> <ide><path>src/transformers/models/xlm_roberta/tokenization_xlm_roberta.py <ide> <ide> import sentencepiece as spm <ide> <del>from ...tokenization_utils import PreTrainedTokenizer <add>from ...tokenization_utils import AddedToken, PreTrainedTokenizer <ide> from ...utils import logging <ide> <ide> <ide> def __init__( <ide> mask_token="<mask>", <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> bos_token=bos_token, <ide> eos_token=eos_token, <ide><path>src/transformers/models/xlm_roberta/tokenization_xlm_roberta_fast.py <ide> from typing import List, Optional, Tuple <ide> <ide> from ...file_utils import is_sentencepiece_available <add>from ...tokenization_utils import AddedToken <ide> from ...tokenization_utils_fast import PreTrainedTokenizerFast <ide> from ...utils import logging <ide> <ide> def __init__( <ide> mask_token="<mask>", <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> vocab_file, <ide> tokenizer_file=tokenizer_file, <ide><path>src/transformers/models/xlnet/tokenization_xlnet.py <ide> import sentencepiece as spm <ide> <ide> from ...file_utils import SPIECE_UNDERLINE <del>from ...tokenization_utils import PreTrainedTokenizer <add>from ...tokenization_utils import AddedToken, PreTrainedTokenizer <ide> from ...utils import logging <ide> <ide> <ide> def __init__( <ide> additional_special_tokens=["<eop>", "<eod>"], <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> do_lower_case=do_lower_case, <ide> remove_space=remove_space, <ide><path>src/transformers/models/xlnet/tokenization_xlnet_fast.py <ide> from typing import List, Optional, Tuple <ide> <ide> from ...file_utils import is_sentencepiece_available <add>from ...tokenization_utils import AddedToken <ide> from ...tokenization_utils_fast import PreTrainedTokenizerFast <ide> from ...utils import logging <ide> <ide> def __init__( <ide> additional_special_tokens=["<eop>", "<eod>"], <ide> **kwargs <ide> ): <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <ide> super().__init__( <ide> vocab_file=vocab_file, <ide> tokenizer_file=tokenizer_file,
18
Text
Text
provide an example to fs.stat()
c03df4c75d7ca9688865701b553e3843f80fda52
<ide><path>doc/api/fs.md <ide> error raised if the file is not available. <ide> To check if a file exists without manipulating it afterwards, [`fs.access()`] <ide> is recommended. <ide> <add>For example, given the following folder structure: <add> <add>```fundamental <add>- txtDir <add>-- file.txt <add>- app.js <add>``` <add> <add>The next program will check for the stats of the given paths: <add> <add>```js <add>const fs = require('fs'); <add> <add>const pathsToCheck = ['./txtDir', './txtDir/file.txt']; <add> <add>for (let i = 0; i < pathsToCheck.length; i++) { <add> fs.stat(pathsToCheck[i], function(err, stats) { <add> console.log(stats.isDirectory()); <add> console.log(stats); <add> }); <add>} <add>``` <add> <add>The resulting output will resemble: <add> <add>```console <add>true <add>Stats { <add> dev: 16777220, <add> mode: 16877, <add> nlink: 3, <add> uid: 501, <add> gid: 20, <add> rdev: 0, <add> blksize: 4096, <add> ino: 14214262, <add> size: 96, <add> blocks: 0, <add> atimeMs: 1561174653071.963, <add> mtimeMs: 1561174614583.3518, <add> ctimeMs: 1561174626623.5366, <add> birthtimeMs: 1561174126937.2893, <add> atime: 2019-06-22T03:37:33.072Z, <add> mtime: 2019-06-22T03:36:54.583Z, <add> ctime: 2019-06-22T03:37:06.624Z, <add> birthtime: 2019-06-22T03:28:46.937Z <add>} <add>false <add>Stats { <add> dev: 16777220, <add> mode: 33188, <add> nlink: 1, <add> uid: 501, <add> gid: 20, <add> rdev: 0, <add> blksize: 4096, <add> ino: 14214074, <add> size: 8, <add> blocks: 8, <add> atimeMs: 1561174616618.8555, <add> mtimeMs: 1561174614584, <add> ctimeMs: 1561174614583.8145, <add> birthtimeMs: 1561174007710.7478, <add> atime: 2019-06-22T03:36:56.619Z, <add> mtime: 2019-06-22T03:36:54.584Z, <add> ctime: 2019-06-22T03:36:54.584Z, <add> birthtime: 2019-06-22T03:26:47.711Z <add>} <add>``` <add> <ide> ## fs.statSync(path[, options]) <ide> <!-- YAML <ide> added: v0.1.21
1
Text
Text
change tab to spaces
c8915c07160f3286d8d7d9c1258739cee067e054
<ide><path>docs/api-guide/status-codes.md <ide> The 4xx class of status code is intended for cases in which the client seems to <ide> HTTP_428_PRECONDITION_REQUIRED <ide> HTTP_429_TOO_MANY_REQUESTS <ide> HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE <del> HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS <add> HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS <ide> <ide> ## Server Error - 5xx <ide>
1
PHP
PHP
fix a styling issue
12e82c5155687082dc5c444e0438f59d2fc901b9
<ide><path>tests/Database/DatabaseSchemaBlueprintIntegrationTest.php <ide> public function testChangingColumnWithCollationWorks() <ide> 'DROP TABLE users', <ide> 'CREATE TABLE users (age INTEGER NOT NULL COLLATE RTRIM)', <ide> 'INSERT INTO users (age) SELECT age FROM __temp__users', <del> 'DROP TABLE __temp__users' <add> 'DROP TABLE __temp__users', <ide> ]; <ide> <ide> $expected2 = [ <ide> 'CREATE TEMPORARY TABLE __temp__users AS SELECT age FROM users', <ide> 'DROP TABLE users', <ide> 'CREATE TABLE users (age INTEGER NOT NULL COLLATE NOCASE)', <ide> 'INSERT INTO users (age) SELECT age FROM __temp__users', <del> 'DROP TABLE __temp__users' <add> 'DROP TABLE __temp__users', <ide> ]; <ide> <ide> $this->assertEquals($expected, $queries);
1
Text
Text
add changelogs for readline
d9c3a27565fd6c2d9e756d61ea0d2df420d2c2ba
<ide><path>doc/api/readline.md <ide> the current position of the cursor down. <ide> ## readline.createInterface(options) <ide> <!-- YAML <ide> added: v0.1.98 <add>changes: <add> - version: v6.3.0 <add> pr-url: https://github.com/nodejs/node/pull/7125 <add> description: The `prompt` option is supported now. <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/6352 <add> description: The `historySize` option can be `0` now. <ide> --> <ide> <ide> * `options` {Object}
1
PHP
PHP
apply fixes from styleci
77227bd9f53ac0b6ad07e9007582443e8767f612
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public static function unsetConnectionResolver() <ide> public function getTable() <ide> { <ide> if (! isset($this->table)) { <del> $this->setTable(str_replace( <del> '\\', '', Str::snake(Str::plural(class_basename($this))) <del> )); <add> $this->setTable(str_replace( <add> '\\', '', Str::snake(Str::plural(class_basename($this))) <add> )); <ide> } <ide> <ide> return $this->table;
1
Javascript
Javascript
replace common.fixtures with fixtures module
beb5226c296492e214346ada70a736195dcab699
<ide><path>test/parallel/test-https-agent-sockets-leak.js <ide> const common = require('../common'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <del>const fs = require('fs'); <ide> const https = require('https'); <ide> const assert = require('assert'); <add>const fixtures = require('../common/fixtures'); <ide> <ide> const options = { <del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`), <del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`), <del> ca: fs.readFileSync(`${common.fixturesDir}/keys/ca1-cert.pem`) <add> key: fixtures.readKey('agent1-key.pem'), <add> cert: fixtures.readKey('agent1-cert.pem'), <add> ca: fixtures.readKey('ca1-cert.pem') <ide> }; <ide> <ide> const server = https.Server(options, common.mustCall((req, res) => {
1
PHP
PHP
fix const docblock indentation
f78a1310d63e17c59a647fd19c6335dacc056441
<ide><path>src/Console/ConsoleIo.php <ide> class ConsoleIo <ide> protected $_in; <ide> <ide> /** <del> * Output constant making verbose shells. <del> * <del> * @var int <del> */ <add> * Output constant making verbose shells. <add> * <add> * @var int <add> */ <ide> const VERBOSE = 2; <ide> <ide> /** <del> * Output constant for making normal shells. <del> * <del> * @var int <del> */ <add> * Output constant for making normal shells. <add> * <add> * @var int <add> */ <ide> const NORMAL = 1; <ide> <ide> /** <del> * Output constants for making quiet shells. <del> * <del> * @var int <del> */ <add> * Output constants for making quiet shells. <add> * <add> * @var int <add> */ <ide> const QUIET = 0; <ide> <ide> /** <ide><path>src/Console/ConsoleOutput.php <ide> class ConsoleOutput <ide> { <ide> <ide> /** <del> * Raw output constant - no modification of output text. <del> * <del> * @var int <del> */ <add> * Raw output constant - no modification of output text. <add> * <add> * @var int <add> */ <ide> const RAW = 0; <ide> <ide> /** <del> * Plain output - tags will be stripped. <del> * <del> * @var int <del> */ <add> * Plain output - tags will be stripped. <add> * <add> * @var int <add> */ <ide> const PLAIN = 1; <ide> <ide> /** <del> * Color output - Convert known tags in to ANSI color escape codes. <del> * <del> * @var int <del> */ <add> * Color output - Convert known tags in to ANSI color escape codes. <add> * <add> * @var int <add> */ <ide> const COLOR = 2; <ide> <ide> /** <del> * Constant for a newline. <del> * <del> * @var string <del> */ <add> * Constant for a newline. <add> * <add> * @var string <add> */ <ide> const LF = PHP_EOL; <ide> <ide> /** <ide><path>src/Console/Shell.php <ide> class Shell <ide> use ModelAwareTrait; <ide> <ide> /** <del> * Output constant making verbose shells. <del> * <del> * @var int <del> */ <add> * Output constant making verbose shells. <add> * <add> * @var int <add> */ <ide> const VERBOSE = ConsoleIo::VERBOSE; <ide> <ide> /** <del> * Output constant for making normal shells. <del> * <del> * @var int <del> */ <add> * Output constant for making normal shells. <add> * <add> * @var int <add> */ <ide> const NORMAL = ConsoleIo::NORMAL; <ide> <ide> /** <del> * Output constants for making quiet shells. <del> * <del> * @var int <del> */ <add> * Output constants for making quiet shells. <add> * <add> * @var int <add> */ <ide> const QUIET = ConsoleIo::QUIET; <ide> <ide> /** <ide><path>src/Controller/Component/AuthComponent.php <ide> class AuthComponent extends Component <ide> use EventManagerTrait; <ide> <ide> /** <del> * Constant for 'all' <del> * <del> * @var string <del> */ <add> * Constant for 'all' <add> * <add> * @var string <add> */ <ide> const ALL = 'all'; <ide> <ide> /** <ide><path>src/Database/Expression/UnaryExpression.php <ide> class UnaryExpression implements ExpressionInterface <ide> { <ide> <ide> /** <del> * Indicates that the operation is in pre-order <del> * <del> */ <add> * Indicates that the operation is in pre-order <add> * <add> */ <ide> const PREFIX = 0; <ide> <ide> /** <del> * Indicates that the operation is in post-order <del> * <del> */ <add> * Indicates that the operation is in post-order <add> * <add> */ <ide> const POSTFIX = 1; <ide> <ide> /** <ide><path>src/Database/Schema/Table.php <ide> class Table <ide> ]; <ide> <ide> /** <del> * Primary constraint type <del> * <del> * @var string <del> */ <add> * Primary constraint type <add> * <add> * @var string <add> */ <ide> const CONSTRAINT_PRIMARY = 'primary'; <ide> <ide> /** <del> * Unique constraint type <del> * <del> * @var string <del> */ <add> * Unique constraint type <add> * <add> * @var string <add> */ <ide> const CONSTRAINT_UNIQUE = 'unique'; <ide> <ide> /** <del> * Foreign constraint type <del> * <del> * @var string <del> */ <add> * Foreign constraint type <add> * <add> * @var string <add> */ <ide> const CONSTRAINT_FOREIGN = 'foreign'; <ide> <ide> /** <del> * Index - index type <del> * <del> * @var string <del> */ <add> * Index - index type <add> * <add> * @var string <add> */ <ide> const INDEX_INDEX = 'index'; <ide> <ide> /** <del> * Fulltext index type <del> * <del> * @var string <del> */ <add> * Fulltext index type <add> * <add> * @var string <add> */ <ide> const INDEX_FULLTEXT = 'fulltext'; <ide> <ide> /** <del> * Foreign key cascade action <del> * <del> * @var string <del> */ <add> * Foreign key cascade action <add> * <add> * @var string <add> */ <ide> const ACTION_CASCADE = 'cascade'; <ide> <ide> /** <del> * Foreign key set null action <del> * <del> * @var string <del> */ <add> * Foreign key set null action <add> * <add> * @var string <add> */ <ide> const ACTION_SET_NULL = 'setNull'; <ide> <ide> /** <del> * Foreign key no action <del> * <del> * @var string <del> */ <add> * Foreign key no action <add> * <add> * @var string <add> */ <ide> const ACTION_NO_ACTION = 'noAction'; <ide> <ide> /** <del> * Foreign key restrict action <del> * <del> * @var string <del> */ <add> * Foreign key restrict action <add> * <add> * @var string <add> */ <ide> const ACTION_RESTRICT = 'restrict'; <ide> <ide> /** <del> * Foreign key restrict default <del> * <del> * @var string <del> */ <add> * Foreign key restrict default <add> * <add> * @var string <add> */ <ide> const ACTION_SET_DEFAULT = 'setDefault'; <ide> <ide> /** <ide><path>src/Filesystem/Folder.php <ide> class Folder <ide> { <ide> <ide> /** <del> * Default scheme for Folder::copy <del> * Recursively merges subfolders with the same name <del> * <del> * @var string <del> */ <add> * Default scheme for Folder::copy <add> * Recursively merges subfolders with the same name <add> * <add> * @var string <add> */ <ide> const MERGE = 'merge'; <ide> <ide> /** <del> * Overwrite scheme for Folder::copy <del> * subfolders with the same name will be replaced <del> * <del> * @var string <del> */ <add> * Overwrite scheme for Folder::copy <add> * subfolders with the same name will be replaced <add> * <add> * @var string <add> */ <ide> const OVERWRITE = 'overwrite'; <ide> <ide> /** <del> * Skip scheme for Folder::copy <del> * if a subfolder with the same name exists it will be skipped <del> * <del> * @var string <del> */ <add> * Skip scheme for Folder::copy <add> * if a subfolder with the same name exists it will be skipped <add> * <add> * @var string <add> */ <ide> const SKIP = 'skip'; <ide> <ide> /** <ide><path>src/I18n/Parser/MoFileParser.php <ide> class MoFileParser <ide> { <ide> <ide> /** <del> * Magic used for validating the format of a MO file as well as <del> * detecting if the machine used to create that file was little endian. <del> * <del> * @var float <del> */ <add> * Magic used for validating the format of a MO file as well as <add> * detecting if the machine used to create that file was little endian. <add> * <add> * @var float <add> */ <ide> const MO_LITTLE_ENDIAN_MAGIC = 0x950412de; <ide> <ide> /** <del> * Magic used for validating the format of a MO file as well as <del> * detecting if the machine used to create that file was big endian. <del> * <del> * @var float <del> */ <add> * Magic used for validating the format of a MO file as well as <add> * detecting if the machine used to create that file was big endian. <add> * <add> * @var float <add> */ <ide> const MO_BIG_ENDIAN_MAGIC = 0xde120495; <ide> <ide> /** <del> * The size of the header of a MO file in bytes. <del> * <del> * @var int Number of bytes. <del> */ <add> * The size of the header of a MO file in bytes. <add> * <add> * @var int Number of bytes. <add> */ <ide> const MO_HEADER_SIZE = 28; <ide> <ide> /** <ide><path>src/Network/Email/Email.php <ide> class Email implements JsonSerializable, Serializable <ide> use StaticConfigTrait; <ide> <ide> /** <del> * Line length - no should more - RFC 2822 - 2.1.1 <del> * <del> * @var int <del> */ <add> * Line length - no should more - RFC 2822 - 2.1.1 <add> * <add> * @var int <add> */ <ide> const LINE_LENGTH_SHOULD = 78; <ide> <ide> /** <del> * Line length - no must more - RFC 2822 - 2.1.1 <del> * <del> * @var int <del> */ <add> * Line length - no must more - RFC 2822 - 2.1.1 <add> * <add> * @var int <add> */ <ide> const LINE_LENGTH_MUST = 998; <ide> <ide> /** <del> * Type of message - HTML <del> * <del> * @var string <del> */ <add> * Type of message - HTML <add> * <add> * @var string <add> */ <ide> const MESSAGE_HTML = 'html'; <ide> <ide> /** <del> * Type of message - TEXT <del> * <del> * @var string <del> */ <add> * Type of message - TEXT <add> * <add> * @var string <add> */ <ide> const MESSAGE_TEXT = 'text'; <ide> <ide> /** <del> * Holds the regex pattern for email validation <del> * <del> * @var string <del> */ <add> * Holds the regex pattern for email validation <add> * <add> * @var string <add> */ <ide> const EMAIL_PATTERN = '/^((?:[\p{L}0-9.!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-.]+)$/ui'; <ide> <ide> /** <ide><path>src/Network/Http/Message.php <ide> class Message <ide> { <ide> <ide> /** <del> * HTTP 200 code <del> * <del> * @var int <del> */ <add> * HTTP 200 code <add> * <add> * @var int <add> */ <ide> const STATUS_OK = 200; <ide> <ide> /** <del> * HTTP 201 code <del> * <del> * @var int <del> */ <add> * HTTP 201 code <add> * <add> * @var int <add> */ <ide> const STATUS_CREATED = 201; <ide> <ide> /** <del> * HTTP 202 code <del> * <del> * @var int <del> */ <add> * HTTP 202 code <add> * <add> * @var int <add> */ <ide> const STATUS_ACCEPTED = 202; <ide> <ide> /** <del> * HTTP 301 code <del> * <del> * @var int <del> */ <add> * HTTP 301 code <add> * <add> * @var int <add> */ <ide> const STATUS_MOVED_PERMANENTLY = 301; <ide> <ide> /** <del> * HTTP 302 code <del> * <del> * @var int <del> */ <add> * HTTP 302 code <add> * <add> * @var int <add> */ <ide> const STATUS_FOUND = 302; <ide> <ide> /** <del> * HTTP 303 code <del> * <del> * @var int <del> */ <add> * HTTP 303 code <add> * <add> * @var int <add> */ <ide> const STATUS_SEE_OTHER = 303; <ide> <ide> /** <del> * HTTP 307 code <del> * <del> * @var int <del> */ <add> * HTTP 307 code <add> * <add> * @var int <add> */ <ide> const STATUS_TEMPORARY_REDIRECT = 307; <ide> <ide> /** <del> * HTTP GET method <del> * <del> * @var string <del> */ <add> * HTTP GET method <add> * <add> * @var string <add> */ <ide> const METHOD_GET = 'GET'; <ide> <ide> /** <del> * HTTP POST method <del> * <del> * @var string <del> */ <add> * HTTP POST method <add> * <add> * @var string <add> */ <ide> const METHOD_POST = 'POST'; <ide> <ide> /** <del> * HTTP PUT method <del> * <del> * @var string <del> */ <add> * HTTP PUT method <add> * <add> * @var string <add> */ <ide> const METHOD_PUT = 'PUT'; <ide> <ide> /** <del> * HTTP DELETE method <del> * <del> * @var string <del> */ <add> * HTTP DELETE method <add> * <add> * @var string <add> */ <ide> const METHOD_DELETE = 'DELETE'; <ide> <ide> /** <del> * HTTP PATCH method <del> * <del> * @var string <del> */ <add> * HTTP PATCH method <add> * <add> * @var string <add> */ <ide> const METHOD_PATCH = 'PATCH'; <ide> <ide> /** <del> * HTTP HEAD method <del> * <del> * @var string <del> */ <add> * HTTP HEAD method <add> * <add> * @var string <add> */ <ide> const METHOD_HEAD = 'HEAD'; <ide> <ide> /** <ide><path>src/ORM/Association.php <ide> abstract class Association <ide> use ConventionsTrait; <ide> <ide> /** <del> * Strategy name to use joins for fetching associated records <del> * <del> * @var string <del> */ <add> * Strategy name to use joins for fetching associated records <add> * <add> * @var string <add> */ <ide> const STRATEGY_JOIN = 'join'; <ide> <ide> /** <del> * Strategy name to use a subquery for fetching associated records <del> * <del> * @var string <del> */ <add> * Strategy name to use a subquery for fetching associated records <add> * <add> * @var string <add> */ <ide> const STRATEGY_SUBQUERY = 'subquery'; <ide> <ide> /** <del> * Strategy name to use a select for fetching associated records <del> * <del> * @var string <del> */ <add> * Strategy name to use a select for fetching associated records <add> * <add> * @var string <add> */ <ide> const STRATEGY_SELECT = 'select'; <ide> <ide> /** <del> * Association type for one to one associations. <del> * <del> * @var string <del> */ <add> * Association type for one to one associations. <add> * <add> * @var string <add> */ <ide> const ONE_TO_ONE = 'oneToOne'; <ide> <ide> /** <del> * Association type for one to many associations. <del> * <del> * @var string <del> */ <add> * Association type for one to many associations. <add> * <add> * @var string <add> */ <ide> const ONE_TO_MANY = 'oneToMany'; <ide> <ide> /** <del> * Association type for many to many associations. <del> * <del> * @var string <del> */ <add> * Association type for many to many associations. <add> * <add> * @var string <add> */ <ide> const MANY_TO_MANY = 'manyToMany'; <ide> <ide> /** <del> * Association type for many to one associations. <del> * <del> * @var string <del> */ <add> * Association type for many to one associations. <add> * <add> * @var string <add> */ <ide> const MANY_TO_ONE = 'manyToOne'; <ide> <ide> /** <ide><path>src/ORM/Association/BelongsToMany.php <ide> class BelongsToMany extends Association <ide> } <ide> <ide> /** <del> * Saving strategy that will only append to the links set <del> * <del> * @var string <del> */ <add> * Saving strategy that will only append to the links set <add> * <add> * @var string <add> */ <ide> const SAVE_APPEND = 'append'; <ide> <ide> /** <del> * Saving strategy that will replace the links with the provided set <del> * <del> * @var string <del> */ <add> * Saving strategy that will replace the links with the provided set <add> * <add> * @var string <add> */ <ide> const SAVE_REPLACE = 'replace'; <ide> <ide> /** <ide><path>src/ORM/Query.php <ide> class Query extends DatabaseQuery implements JsonSerializable <ide> } <ide> <ide> /** <del> * Indicates that the operation should append to the list <del> * <del> * @var int <del> */ <add> * Indicates that the operation should append to the list <add> * <add> * @var int <add> */ <ide> const APPEND = 0; <ide> <ide> /** <del> * Indicates that the operation should prepend to the list <del> * <del> * @var int <del> */ <add> * Indicates that the operation should prepend to the list <add> * <add> * @var int <add> */ <ide> const PREPEND = 1; <ide> <ide> /** <del> * Indicates that the operation should overwrite the list <del> * <del> * @var bool <del> */ <add> * Indicates that the operation should overwrite the list <add> * <add> * @var bool <add> */ <ide> const OVERWRITE = true; <ide> <ide> /** <ide><path>src/ORM/RulesChecker.php <ide> class RulesChecker <ide> { <ide> <ide> /** <del> * Indicates that the checking rules to apply are those used for creating entities <del> * <del> * @var string <del> */ <add> * Indicates that the checking rules to apply are those used for creating entities <add> * <add> * @var string <add> */ <ide> const CREATE = 'create'; <ide> <ide> /** <del> * Indicates that the checking rules to apply are those used for updating entities <del> * <del> * @var string <del> */ <add> * Indicates that the checking rules to apply are those used for updating entities <add> * <add> * @var string <add> */ <ide> const UPDATE = 'update'; <ide> <ide> /** <del> * Indicates that the checking rules to apply are those used for deleting entities <del> * <del> * @var string <del> */ <add> * Indicates that the checking rules to apply are those used for deleting entities <add> * <add> * @var string <add> */ <ide> const DELETE = 'delete'; <ide> <ide> /** <ide><path>src/Routing/RouteBuilder.php <ide> class RouteBuilder <ide> { <ide> <ide> /** <del> * Regular expression for auto increment IDs <del> * <del> * @var string <del> */ <add> * Regular expression for auto increment IDs <add> * <add> * @var string <add> */ <ide> const ID = '[0-9]+'; <ide> <ide> /** <del> * Regular expression for UUIDs <del> * <del> * @var string <del> */ <add> * Regular expression for UUIDs <add> * <add> * @var string <add> */ <ide> const UUID = '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}'; <ide> <ide> /** <ide><path>src/Routing/Router.php <ide> class Router <ide> protected static $_fullBaseUrl; <ide> <ide> /** <del> * Regular expression for action names <del> * <del> * @var string <del> */ <add> * Regular expression for action names <add> * <add> * @var string <add> */ <ide> const ACTION = 'index|show|add|create|edit|update|remove|del|delete|view|item'; <ide> <ide> /** <del> * Regular expression for years <del> * <del> * @var string <del> */ <add> * Regular expression for years <add> * <add> * @var string <add> */ <ide> const YEAR = '[12][0-9]{3}'; <ide> <ide> /** <del> * Regular expression for months <del> * <del> * @var string <del> */ <add> * Regular expression for months <add> * <add> * @var string <add> */ <ide> const MONTH = '0[1-9]|1[012]'; <ide> <ide> /** <del> * Regular expression for days <del> * <del> * @var string <del> */ <add> * Regular expression for days <add> * <add> * @var string <add> */ <ide> const DAY = '0[1-9]|[12][0-9]|3[01]'; <ide> <ide> /** <del> * Regular expression for auto increment IDs <del> * <del> * @var string <del> */ <add> * Regular expression for auto increment IDs <add> * <add> * @var string <add> */ <ide> const ID = '[0-9]+'; <ide> <ide> /** <del> * Regular expression for UUIDs <del> * <del> * @var string <del> */ <add> * Regular expression for UUIDs <add> * <add> * @var string <add> */ <ide> const UUID = '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}'; <ide> <ide> protected static $_collection; <ide><path>src/Shell/ServerShell.php <ide> class ServerShell extends Shell <ide> { <ide> <ide> /** <del> * Default ServerHost <del> * <del> * @var string <del> */ <add> * Default ServerHost <add> * <add> * @var string <add> */ <ide> const DEFAULT_HOST = 'localhost'; <ide> <ide> /** <del> * Default ListenPort <del> * <del> * @var int <del> */ <add> * Default ListenPort <add> * <add> * @var int <add> */ <ide> const DEFAULT_PORT = 8765; <ide> <ide> /** <ide><path>src/View/Helper/FormHelper.php <ide> class FormHelper extends Helper <ide> public $fields = []; <ide> <ide> /** <del> * Constant used internally to skip the securing process, <del> * and neither add the field to the hash or to the unlocked fields. <del> * <del> * @var string <del> */ <add> * Constant used internally to skip the securing process, <add> * and neither add the field to the hash or to the unlocked fields. <add> * <add> * @var string <add> */ <ide> const SECURE_SKIP = 'skip'; <ide> <ide> /** <ide><path>src/View/View.php <ide> class View <ide> protected $_stack = []; <ide> <ide> /** <del> * Constant for view file type 'view' <del> * <del> * @var string <del> */ <add> * Constant for view file type 'view' <add> * <add> * @var string <add> */ <ide> const TYPE_VIEW = 'view'; <ide> <ide> /** <del> * Constant for view file type 'element' <del> * <del> * @var string <del> */ <add> * Constant for view file type 'element' <add> * <add> * @var string <add> */ <ide> const TYPE_ELEMENT = 'element'; <ide> <ide> /** <del> * Constant for view file type 'layout' <del> * <del> * @var string <del> */ <add> * Constant for view file type 'layout' <add> * <add> * @var string <add> */ <ide> const TYPE_LAYOUT = 'layout'; <ide> <ide> /** <ide><path>src/View/ViewBlock.php <ide> class ViewBlock <ide> { <ide> <ide> /** <del> * Append content <del> * <del> * @var string <del> */ <add> * Append content <add> * <add> * @var string <add> */ <ide> const APPEND = 'append'; <ide> <ide> /** <del> * Prepend content <del> * <del> * @var string <del> */ <add> * Prepend content <add> * <add> * @var string <add> */ <ide> const PREPEND = 'prepend'; <ide> <ide> /**
20
Javascript
Javascript
update snapshots for improved error format
59c141d8592d55173e453530fe838b88caf8e974
<ide><path>test/Validation.test.js <ide> describe("Validation", () => { <ide> expect(msg).toMatchInlineSnapshot(` <ide> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. <ide> - configuration.output.ecmaVersion should be one of these: <del> number (should be >= 5, should be <= 11) | 2009 | number (should be >= 2015, should be <= 2020) <add> number (should be >= 5 and <= 11) | 2009 | number (should be >= 2015 and <= 2020) <ide> -> The maximum EcmaScript version of the webpack generated code (doesn't include input source code from modules). <ide> Details: <del> * configuration.output.ecmaVersion should be <= 11. <del> * configuration.output.ecmaVersion should be >= 2015." <add> * configuration.output.ecmaVersion should be >= 5 and <= 11. <add> * configuration.output.ecmaVersion should be >= 2015 and <= 2020." <ide> `) <ide> ); <ide> <ide> describe("Validation", () => { <ide> expect(msg).toMatchInlineSnapshot(` <ide> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. <ide> - configuration.output.ecmaVersion should be one of these: <del> number (should be >= 5, should be <= 11) | 2009 | number (should be >= 2015, should be <= 2020) <add> number (should be >= 5 and <= 11) | 2009 | number (should be >= 2015 and <= 2020) <ide> -> The maximum EcmaScript version of the webpack generated code (doesn't include input source code from modules). <ide> Details: <del> * configuration.output.ecmaVersion should be <= 11. <del> * configuration.output.ecmaVersion should be <= 2020." <add> * configuration.output.ecmaVersion should be >= 5 and <= 11. <add> * configuration.output.ecmaVersion should be >= 2015 and <= 2020." <ide> `) <ide> ); <ide> <ide> describe("Validation", () => { <ide> expect(msg).toMatchInlineSnapshot(` <ide> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. <ide> - configuration.output.ecmaVersion should be one of these: <del> number (should be >= 5, should be <= 11) | 2009 | number (should be >= 2015, should be <= 2020) <add> number (should be >= 5 and <= 11) | 2009 | number (should be >= 2015 and <= 2020) <ide> -> The maximum EcmaScript version of the webpack generated code (doesn't include input source code from modules). <ide> Details: <del> * configuration.output.ecmaVersion should be >= 5. <del> * configuration.output.ecmaVersion should be >= 2015." <add> * configuration.output.ecmaVersion should be >= 5 and <= 11. <add> * configuration.output.ecmaVersion should be >= 2015 and <= 2020." <ide> `) <ide> ); <ide> <ide> describe("Validation", () => { <ide> expect(msg).toMatchInlineSnapshot(` <ide> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. <ide> - configuration.output.ecmaVersion should be one of these: <del> number (should be >= 5, should be <= 11) | 2009 | number (should be >= 2015, should be <= 2020) <add> number (should be >= 5 and <= 11) | 2009 | number (should be >= 2015 and <= 2020) <ide> -> The maximum EcmaScript version of the webpack generated code (doesn't include input source code from modules). <ide> Details: <del> * configuration.output.ecmaVersion should be <= 11. <del> * configuration.output.ecmaVersion should be >= 2015." <add> * configuration.output.ecmaVersion should be >= 5 and <= 11. <add> * configuration.output.ecmaVersion should be >= 2015 and <= 2020." <ide> `) <ide> ); <ide> });
1
Text
Text
fix quotes and ruby old hashes
1010f9382b81f5f3a02009126271ac0cbde4bc59
<ide><path>guides/source/association_basics.md <ide> If you want to make sure that, upon insertion, all of the records in the <ide> persisted association are distinct (so that you can be sure that when you <ide> inspect the association that you will never find duplicate records), you should <ide> add a unique index on the table itself. For example, if you have a table named <del>``person_posts`` and you want to make sure all the posts are unique, you could <add>`person_posts` and you want to make sure all the posts are unique, you could <ide> add the following in a migration: <ide> <ide> ```ruby <del>add_index :person_posts, :post, :unique => true <add>add_index :person_posts, :post, unique: true <ide> ``` <ide> <del>Note that checking for uniqueness using something like ``include?`` is subject <del>to race conditions. Do not attempt to use ``include?`` to enforce distinctness <add>Note that checking for uniqueness using something like `include?` is subject <add>to race conditions. Do not attempt to use `include?` to enforce distinctness <ide> in an association. For instance, using the post example from above, the <ide> following code would be racy because multiple users could be attempting this <ide> at the same time:
1
Javascript
Javascript
add textual output to benchmark runner
42992032da507f5460b4aeee684316b5a5af45f3
<ide><path>benchmarks/benchmark-runner.js <ide> export default async function (benchmarkPaths) { <ide> datasets: [{label: key, fill: false, data: data.points}] <ide> } <ide> }) <add> <add> const textualOutput = `${key}:\n` + data.points.map((p) => ` (${p.x}, ${p.y})`).join('\n') <add> console.log(textualOutput) <ide> } else { <ide> const title = document.createElement('h2') <ide> title.textContent = key <ide> benchmarkContainer.appendChild(title) <ide> const duration = document.createElement('p') <ide> duration.textContent = `${data.points[0].y}ms` <ide> benchmarkContainer.appendChild(duration) <add> <add> const textualOutput = `${key}: ${data.points[0].y}` <add> console.log(textualOutput) <ide> } <ide> <ide> global.atom.reset()
1
Text
Text
fix trailing whitespace
a4470c42765004825ed6c09ae434dfd7dd969d1e
<ide><path>docs/api-guide/authentication.md <ide> Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the author <ide> <ide> If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`. <ide> <del> # this can go in either server config, virtual host, directory or .htaccess <add> # this can go in either server config, virtual host, directory or .htaccess <ide> WSGIPassAuthorization On <ide> <ide> --- <ide> Unauthenticated responses that are denied permission will result in an `HTTP 401 <ide> <ide> ## TokenAuthentication <ide> <del>This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. <add>This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. <ide> <ide> To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting: <ide> <ide> INSTALLED_APPS = ( <ide> ... <ide> 'rest_framework.authtoken' <ide> ) <del> <add> <ide> Make sure to run `manage.py syncdb` after changing your settings. The `authtoken` database tables are managed by south (see [Schema migrations](#schema-migrations) below). <ide> <ide> You'll also need to create tokens for your users. <ide> You can do so by inserting a `needed_by` attribute in your user migration: <ide> needed_by = ( <ide> ('authtoken', '0001_initial'), <ide> ) <del> <add> <ide> def forwards(self): <ide> ... <ide> <ide> Note that the `namespace='oauth2'` argument is required. <ide> Finally, sync your database. <ide> <ide> python manage.py syncdb <del> python manage.py migrate <add> python manage.py migrate <ide> <ide> --- <ide> <ide> The following example will authenticate any incoming request as the user given b <ide> user = User.objects.get(username=username) <ide> except User.DoesNotExist: <ide> raise exceptions.AuthenticationFailed('No such user') <del> <add> <ide> return (user, None) <ide> <ide> ---
1
PHP
PHP
fix typos and grammar
167ae78b87cc6b270be7067d2b7efaca511bf88a
<ide><path>src/Core/Retry/CommandRetry.php <ide> /** <ide> * Allows any action to be retried in case of an exception. <ide> * <del> * This class can be parametrized with an strategy, which will be followed <add> * This class can be parametrized with a strategy, which will be followed <ide> * to determine whether or not the action should be retried. <ide> */ <ide> class CommandRetry <ide> { <ide> <ide> /** <del> * The strategy to follow should the executed action fail <add> * The strategy to follow should the executed action fail. <ide> * <ide> * @var \Cake\Core\Retry\RetryStrategyInterface <ide> */ <ide> protected $strategy; <ide> <ide> /** <del> * The number of retries to perform in case of failure <add> * The number of retries to perform in case of failure. <ide> * <ide> * @var int <ide> */ <ide><path>src/Core/Retry/RetryStrategyInterface.php <ide> use Exception; <ide> <ide> /** <del> * Used to instruct the CommandRetry object on whether or not a retry <add> * Used to instruct a CommandRetry object on whether or not a retry <ide> * for an action should be performed <ide> */ <ide> interface RetryStrategyInterface <ide><path>src/Database/Connection.php <ide> public function setDriver($driver, $config = []) <ide> } <ide> <ide> /** <del> * Get the retry wrapper object, that is used to recover from server disconnects <del> * while performing ceratain database actions, such as executing a query <add> * Get the retry wrapper object that is allows recovery from server disconnects <add> * while performing certain database actions, such as executing a query. <ide> * <ide> * @return \Cake\Core\Retry\CommandRetry The retry wrapper <ide> */ <ide><path>src/Database/Retry/ReconnectStrategy.php <ide> class ReconnectStrategy implements RetryStrategyInterface <ide> { <ide> /** <del> * The list of errors strings to match when looking for disconnection error. <del> * This is a static variable to avoid holding all the strings in the array can <del> * be inlined by the opcache. <add> * The list of error strings to match when looking for a disconnection error. <add> * <add> * This is a static variable to enable opcache to inline the values. <ide> * <ide> * @var array <ide> */
4
Python
Python
add missing tags to el/es/pt tag maps
46250f60acdcdb847780789ed3a715639c67c9fa
<ide><path>spacy/lang/el/tag_map.py <ide> from __future__ import unicode_literals <ide> <ide> from ...symbols import POS, PUNCT, SYM, ADJ, CCONJ, SCONJ, NUM, DET, ADV, ADP, X, VERB <del>from ...symbols import NOUN, PROPN, PART, INTJ, PRON <add>from ...symbols import NOUN, PROPN, PART, INTJ, PRON, AUX <ide> <ide> <ide> TAG_MAP = { <ide> "Voice": "Act", <ide> "Case": "Nom|Gen|Dat|Acc|Voc", <ide> }, <add> 'ADJ': {POS: ADJ}, <add> 'ADP': {POS: ADP}, <add> 'ADV': {POS: ADV}, <add> 'AtDf': {POS: DET}, <add> 'AUX': {POS: AUX}, <add> 'CCONJ': {POS: CCONJ}, <add> 'DET': {POS: DET}, <add> 'NOUN': {POS: NOUN}, <add> 'NUM': {POS: NUM}, <add> 'PART': {POS: PART}, <add> 'PRON': {POS: PRON}, <add> 'PROPN': {POS: PROPN}, <add> 'SCONJ': {POS: SCONJ}, <add> 'SYM': {POS: SYM}, <add> 'VERB': {POS: VERB}, <add> 'X': {POS: X}, <ide> } <ide><path>spacy/lang/es/tag_map.py <ide> "VERB__VerbForm=Ger": {"morph": "VerbForm=Ger", POS: VERB}, <ide> "VERB__VerbForm=Inf": {"morph": "VerbForm=Inf", POS: VERB}, <ide> "X___": {"morph": "_", POS: X}, <add> "___PunctType=Quot": {POS: PUNCT}, <add> "___VerbForm=Inf": {POS: VERB}, <add> "___Number=Sing|Person=2|PronType=Prs": {POS: PRON}, <ide> "_SP": {"morph": "_", POS: SPACE}, <ide> } <ide> # fmt: on <ide><path>spacy/lang/pt/tag_map.py <ide> "punc": {POS: PUNCT}, <ide> "v-pcp|M|P": {POS: VERB}, <ide> "v-pcp|M|S": {POS: VERB}, <add> "ADJ": {POS: ADJ}, <add> "AUX": {POS: AUX}, <add> "CCONJ": {POS: CCONJ}, <add> "DET": {POS: DET}, <add> "INTJ": {POS: INTJ}, <add> "NUM": {POS: NUM}, <add> "PART": {POS: PART}, <add> "PRON": {POS: PRON}, <add> "PUNCT": {POS: PUNCT}, <add> "SCONJ": {POS: SCONJ}, <add> "SYM": {POS: SYM}, <add> "VERB": {POS: VERB}, <add> "X": {POS: X}, <add> "adv": {POS: ADV}, <ide> "_SP": {POS: SPACE}, <ide> }
3
Go
Go
use ++ instead of += 1
1ba15b8acaf8625db23ccd7d0ba7d3acf7d2f69e
<ide><path>daemon/attach.go <ide> func (daemon *Daemon) Attach(container *Container, stdin io.ReadCloser, stdinClo <ide> ) <ide> <ide> if stdin != nil && container.Config.OpenStdin { <del> nJobs += 1 <add> nJobs++ <ide> if cStdin, err := container.StdinPipe(); err != nil { <ide> errors <- err <ide> } else { <ide> func (daemon *Daemon) Attach(container *Container, stdin io.ReadCloser, stdinClo <ide> } <ide> } <ide> if stdout != nil { <del> nJobs += 1 <add> nJobs++ <ide> if p, err := container.StdoutPipe(); err != nil { <ide> errors <- err <ide> } else { <ide> func (daemon *Daemon) Attach(container *Container, stdin io.ReadCloser, stdinClo <ide> }() <ide> } <ide> if stderr != nil { <del> nJobs += 1 <add> nJobs++ <ide> if p, err := container.StderrPipe(); err != nil { <ide> errors <- err <ide> } else { <ide> func (daemon *Daemon) Attach(container *Container, stdin io.ReadCloser, stdinClo <ide> <ide> // FIXME: how to clean up the stdin goroutine without the unwanted side effect <ide> // of closing the passed stdin? Add an intermediary io.Pipe? <del> for i := 0; i < nJobs; i += 1 { <add> for i := 0; i < nJobs; i++ { <ide> log.Debugf("attach: waiting for job %d/%d", i+1, nJobs) <ide> if err := <-errors; err != nil { <ide> log.Errorf("attach: job %d returned error %s, aborting all jobs", i+1, err) <ide><path>daemon/build.go <ide> func (b *buildFile) Build(context io.Reader) (string, error) { <ide> } else if b.rm { <ide> b.clearTmp(b.tmpContainers) <ide> } <del> stepN += 1 <add> stepN++ <ide> } <ide> if b.image != "" { <ide> fmt.Fprintf(b.outStream, "Successfully built %s\n", utils.TruncateID(b.image))
2
Text
Text
lowercase the "the" word
3413848b5c8bc4595d42582d8cec56e2f09b3282
<ide><path>guide/english/algorithms/b-trees/index.md <ide> Properties of B-Tree: <ide> 8) Like other balanced Binary Search Trees, time complexity to search, insert and delete is O(Logn). <ide> <ide> Search: <del>Search is similar to search in Binary Search Tree. Let the key to be searched be k. We start from root and recursively traverse down. For every visited non-leaf node, if the node has key, we simply return the node. Otherwise we recur down to the appropriate child (The child which is just before the first greater key) of the node. If we reach a leaf node and don’t find k in the leaf node, we return NULL. <add>Search is similar to search in Binary Search Tree. Let the key to be searched be k. We start from root and recursively traverse down. For every visited non-leaf node, if the node has key, we simply return the node. Otherwise we recur down to the appropriate child (the child which is just before the first greater key) of the node. If we reach a leaf node and don’t find k in the leaf node, we return NULL. <ide> <ide> Traverse: <ide> Traversal is also similar to Inorder traversal of Binary Tree. We start from the leftmost child, recursively print the leftmost child, then repeat the same process for remaining children and keys. In the end, recursively print the rightmost child.
1
Javascript
Javascript
fix angularjs versions
ef7d18b1c44eda924b336b5ad55c629423cd0a64
<ide><path>src/ng/compile.js <ide> function $CompileProvider($provide, $$sanitizeUriProvider) { <ide> * <ide> * If disabled (false), the compiler calls the constructor first before assigning bindings. <ide> * <del> * The default value is true in AngularJS.5.x but will switch to false in AngularJS.6.x. <add> * The default value is true in AngularJS 1.5.x but will switch to false in AngularJS 1.6.x. <ide> */ <ide> var preAssignBindingsEnabled = false; <ide> this.preAssignBindingsEnabled = function(enabled) {
1
Python
Python
add getexception to compat.py3k
ca1241a2ffc57b04563ecae7d709fbf46d94eb6c
<ide><path>numpy/compat/py3k.py <ide> <ide> """ <ide> <del>__all__ = ['bytes', 'asbytes', 'isfileobj'] <add>__all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception'] <ide> <ide> import sys <add> <ide> if sys.version_info[0] >= 3: <ide> import io <ide> bytes = bytes <ide> def isfileobj(f): <ide> asbytes = str <ide> def isfileobj(f): <ide> return isinstance(f, file) <add> <add>def getexception(): <add> return sys.exc_info()[1] <add>
1
Ruby
Ruby
make search and create arguments mandatory
86c241ab42744f075484740583580c12e388db8e
<ide><path>Library/Homebrew/help.rb <ide> module Help <ide> # NOTE: Keep lines less than 80 characters! Wrapping is just not cricket. <ide> HOMEBREW_HELP = <<~EOS <ide> Example usage: <del> brew search [TEXT|/REGEX/] <add> brew search TEXT|/REGEX/ <ide> brew info [FORMULA|CASK...] <ide> brew install FORMULA|CASK... <ide> brew update <ide> module Help <ide> brew install --verbose --debug FORMULA|CASK <ide> <ide> Contributing: <del> brew create [URL [--no-fetch]] <add> brew create URL [--no-fetch] <ide> brew edit [FORMULA|CASK...] <ide> <ide> Further help:
1
Javascript
Javascript
remove parser static
9878355df7af29a621403f9303691f0f4d547624
<ide><path>src/Parser.js <ide> function Parser(text, parseStrings){ <ide> this.index = 0; <ide> } <ide> <del>Parser.ZERO = function(){ <add>ZERO = function(){ <ide> return 0; <ide> }; <ide> <ide> Parser.prototype = { <ide> if (this.expect('+')) { <ide> return this.primary(); <ide> } else if (token = this.expect('-')) { <del> return this._binary(Parser.ZERO, token.fn, this.unary()); <add> return this._binary(ZERO, token.fn, this.unary()); <ide> } else if (token = this.expect('!')) { <ide> return this._unary(token.fn, this.unary()); <ide> } else {
1
Python
Python
add fab pex command
6044d55f0f6228d7a636b4b0256c4a0f4e0e93cf
<ide><path>fabfile.py <ide> def virtualenv(name, create=False, python='/usr/bin/python3.6'): <ide> if env_path.exists(): <ide> shutil.rmtree(str(env_path)) <ide> local('{python} -m venv {env_path}'.format(python=python, env_path=VENV_DIR)) <del> def wrapped_local(cmd, env_vars=[], capture=False): <add> def wrapped_local(cmd, env_vars=[], capture=False, direct=False): <ide> env_py = env_path / 'bin' / 'python' <ide> env_vars = ' '.join(env_vars) <ide> if cmd.split()[0] == 'python': <ide> cmd = cmd.replace('python', str(env_py)) <ide> return local(env_vars + ' ' + cmd, capture=capture) <add> elif direct: <add> cmd, args = cmd.split(' ', 1) <add> env_cmd = str(env_py).replace('python', cmd) <add> return local('{env_vars} {env_cmd} {args}'.format( <add> env_cmd=env_cmd, args=args, env_vars=env_vars), <add> capture=capture) <ide> else: <ide> return local('{env_vars} {env_py} -m {cmd}'.format( <ide> env_py=env_py, cmd=cmd, env_vars=env_vars), <ide> def make(): <ide> with virtualenv(VENV_DIR) as venv_local: <ide> with lcd(path.dirname(__file__)): <ide> venv_local('pip install -r requirements.txt') <add> venv_local('pip install pex') <ide> venv_local('python setup.py build_ext --inplace', env_vars=['PYTHONPATH=`pwd`']) <ide> <ide> def sdist(): <ide> def wheel(): <ide> with lcd(path.dirname(__file__)): <ide> venv_local('python setup.py bdist_wheel') <ide> <add>def pex(): <add> with virtualenv(VENV_DIR) as venv_local: <add> with lcd(path.dirname(__file__)): <add> venv_local('pex . -e spacy -o dist/spacy', direct=True) <add> <ide> <ide> def clean(): <ide> with lcd(path.dirname(__file__)):
1
PHP
PHP
unalign doc block
21c5b0d28e29b00c1b024cbeb9f98157e83e40fa
<ide><path>src/Database/Expression/QueryExpression.php <ide> public function in($field, $values, $type = null) { <ide> /** <ide> * Adds a new case expression to the expression object <ide> * <del> * @param array|ExpressionInterface $conditions The conditions to test. <del> * Must be a QueryExpression, or an array of QueryExpressions. <del> * @param string|array|ExpressionInterface $trueValues Value of each condition if that condition is true <add> * @param array|ExpressionInterface $conditions The conditions to test. Must be a QueryExpression, or an array of QueryExpressions. <add> * @param string|array|ExpressionInterface $trueValues Value of each condition if that condition is true <ide> * @param string|array|ExpressionInterface $defaultValue Default value if none of the conditiosn are true <ide> * <ide> * @return QueryExpression
1
Python
Python
finalize cluster and node api
bd01086ba73cb0d4eb0c8ec0c8024ecb232a687f
<ide><path>celery/apps/multi.py <ide> from kombu.utils.objects import cached_property <ide> <ide> from celery.five import UserList, items <del>from celery.platforms import IS_WINDOWS, Pidfile, signal_name, signals <add>from celery.platforms import IS_WINDOWS, Pidfile, signal_name <ide> from celery.utils.nodenames import ( <ide> gethostname, host_format, node_format, nodesplit, <ide> ) <ide> def celery_exe(*args): <ide> return ' '.join((CELERY_EXE,) + args) <ide> <ide> <add>def build_nodename(name, prefix, suffix): <add> hostname = suffix <add> if '@' in name: <add> nodename = host_format(name) <add> shortname, hostname = nodesplit(nodename) <add> name = shortname <add> else: <add> shortname = '%s%s' % (prefix, name) <add> nodename = host_format( <add> '{0}@{1}'.format(shortname, hostname), <add> ) <add> return name, nodename, hostname <add> <add> <add>def build_expander(nodename, shortname, hostname): <add> return partial( <add> node_format, <add> nodename=nodename, <add> N=shortname, <add> d=hostname, <add> h=nodename, <add> i='%i', <add> I='%I', <add> ) <add> <add> <add>def format_opt(opt, value): <add> if not value: <add> return opt <add> if opt.startswith('--'): <add> return '{0}={1}'.format(opt, value) <add> return '{0} {1}'.format(opt, value) <add> <add> <add>def _kwargs_to_command_line(kwargs): <add> return { <add> ('--{0}'.format(k.replace('_', '-')) <add> if len(k) > 1 else '-{0}'.format(k)): '{0}'.format(v) <add> for k, v in items(kwargs) <add> } <add> <add> <ide> class NamespacedOptionParser(object): <ide> <ide> def __init__(self, args): <ide> def __init__(self, args): <ide> self.passthrough = '' <ide> self.namespaces = defaultdict(lambda: OrderedDict()) <ide> <del> self.parse() <del> <ide> def parse(self): <ide> rargs = list(self.args) <ide> pos = 0 <ide> def add_option(self, name, value, short=False, ns=None): <ide> <ide> class Node(object): <ide> <del> def __init__(self, name, argv, expander, namespace, p): <del> self.p = p <add> def __init__(self, name, <add> cmd=None, append=None, options=None, extra_args=None): <ide> self.name = name <del> self.argv = tuple(argv) <del> self.expander = expander <del> self.namespace = namespace <add> self.cmd = cmd or '-m {0}'.format(celery_exe('worker', '--detach')) <add> self.append = append <add> self.extra_args = extra_args or '' <add> self.options = self._annotate_with_default_opts( <add> options or OrderedDict()) <add> self.expander = self._prepare_expander() <add> self.argv = self._prepare_argv() <ide> self._pid = None <ide> <add> def _annotate_with_default_opts(self, options): <add> options['-n'] = self.name <add> self._setdefaultopt(options, ['--pidfile', '-p'], '%n.pid') <add> self._setdefaultopt(options, ['--logfile', '-f'], '%n%I.log') <add> self._setdefaultopt(options, ['--executable'], sys.executable) <add> return options <add> <add> def _setdefaultopt(self, d, alt, value): <add> for opt in alt[1:]: <add> try: <add> return d[opt] <add> except KeyError: <add> pass <add> return d.setdefault(alt[0], value) <add> <add> def _prepare_expander(self): <add> shortname, hostname = self.name.split('@', 1) <add> return build_expander( <add> self.name, shortname, hostname) <add> <add> def _prepare_argv(self): <add> argv = tuple( <add> [self.expander(self.cmd)] + <add> [format_opt(opt, self.expander(value)) <add> for opt, value in items(self.options)] + <add> [self.extra_args] <add> ) <add> if self.append: <add> argv += (self.expander(self.append),) <add> return argv <add> <ide> def alive(self): <ide> return self.send(0) <ide> <ide> def prepare_argv(self, argv, path): <ide> return shlex.split(from_utf8(args), posix=not IS_WINDOWS) <ide> <ide> def getopt(self, *alt): <del> try: <del> return self._getnsopt(*alt) <del> except KeyError: <del> return self._getoptopt(*alt) <del> <del> def _getnsopt(self, *alt): <del> return self._getopt(self.p.namespaces[self.namespace], list(alt)) <del> <del> def _getoptopt(self, *alt): <del> return self._getopt(self.p.options, list(alt)) <del> <del> def _getopt(self, d, alt): <ide> for opt in alt: <ide> try: <del> return d[opt] <add> return self.options[opt] <ide> except KeyError: <ide> pass <ide> raise KeyError(alt[0]) <ide> def pid(self, value): <ide> <ide> @cached_property <ide> def executable(self): <del> return self.p.options['--executable'] <add> return self.options['--executable'] <ide> <ide> @cached_property <ide> def argv_with_executable(self): <ide> return (self.executable,) + self.argv <ide> <add> @classmethod <add> def from_kwargs(cls, name, **kwargs): <add> return cls(name, options=_kwargs_to_command_line(kwargs)) <add> <ide> <ide> def maybe_call(fun, *args, **kwargs): <ide> if fun is not None: <ide> def parse(self, p): <ide> options = dict(p.options) <ide> ranges = len(names) == 1 <ide> prefix = self.prefix <del> if ranges: <del> try: <del> names, prefix = self._get_ranges(names), self.range_prefix <del> except ValueError: <del> pass <ide> cmd = options.pop('--cmd', self.cmd) <ide> append = options.pop('--append', self.append) <ide> hostname = options.pop('--hostname', options.pop('-n', gethostname())) <ide> prefix = options.pop('--prefix', prefix) or '' <ide> suffix = options.pop('--suffix', self.suffix) or hostname <ide> suffix = '' if suffix in ('""', "''") else suffix <ide> <add> if ranges: <add> try: <add> names, prefix = self._get_ranges(names), self.range_prefix <add> except ValueError: <add> pass <ide> self._update_ns_opts(p, names) <ide> self._update_ns_ranges(p, ranges) <add> <ide> return ( <del> self._args_for_node(p, name, prefix, suffix, cmd, append, options) <add> self._node_from_options( <add> p, name, prefix, suffix, cmd, append, options) <ide> for name in names <ide> ) <ide> <add> def _node_from_options(self, p, name, prefix, <add> suffix, cmd, append, options): <add> namespace, nodename, _ = build_nodename(name, prefix, suffix) <add> namespace = nodename if nodename in p.namespaces else namespace <add> return Node(nodename, cmd, append, <add> p.optmerge(namespace, options), p.passthrough) <add> <ide> def _get_ranges(self, names): <ide> noderange = int(names[0]) <ide> return [str(n) for n in range(1, noderange + 1)] <ide> <ide> def _update_ns_opts(self, p, names): <ide> # Numbers in args always refers to the index in the list of names. <del> # (e.g. `start foo bar baz -c:1` where 1 is foo, 2 is bar, and so on). <add> # (e.g., `start foo bar baz -c:1` where 1 is foo, 2 is bar, and so on). <ide> for ns_name, ns_opts in list(items(p.namespaces)): <ide> if ns_name.isdigit(): <ide> ns_index = int(ns_name) - 1 <ide> def _parse_ns_range(self, ns, ranges=False): <ide> ret.append(space) <ide> return ret <ide> <del> def _args_for_node(self, p, name, prefix, suffix, cmd, append, options): <del> name, nodename, expand = self._get_nodename( <del> name, prefix, suffix, options) <del> <del> if nodename in p.namespaces: <del> ns = nodename <del> else: <del> ns = name <del> <del> argv = ( <del> [expand(cmd)] + <del> [self.format_opt(opt, expand(value)) <del> for opt, value in items(p.optmerge(ns, options))] + <del> [p.passthrough] <del> ) <del> if append: <del> argv.append(expand(append)) <del> return self.Node(nodename, argv, expand, name, p) <del> <del> def _get_nodename(self, name, prefix, suffix, options): <del> hostname = suffix <del> if '@' in name: <del> nodename = options['-n'] = host_format(name) <del> shortname, hostname = nodesplit(nodename) <del> name = shortname <del> else: <del> shortname = '%s%s' % (prefix, name) <del> nodename = options['-n'] = host_format( <del> '{0}@{1}'.format(shortname, hostname), <del> ) <del> expand = partial( <del> node_format, nodename=nodename, N=shortname, d=hostname, <del> h=nodename, i='%i', I='%I', <del> ) <del> return name, nodename, expand <del> <del> def format_opt(self, opt, value): <del> if not value: <del> return opt <del> if opt.startswith('--'): <del> return '{0}={1}'.format(opt, value) <del> return '{0} {1}'.format(opt, value) <del> <ide> <ide> class Cluster(UserList): <del> MultiParser = MultiParser <del> OptionParser = NamespacedOptionParser <ide> <del> def __init__(self, argv, cmd=None, env=None, <add> def __init__(self, nodes, cmd=None, env=None, <ide> on_stopping_preamble=None, <ide> on_send_signal=None, <ide> on_still_waiting_for=None, <ide> def __init__(self, argv, cmd=None, env=None, <ide> on_child_spawn=None, <ide> on_child_signalled=None, <ide> on_child_failure=None): <del> self.argv = argv <add> self.nodes = nodes <ide> self.cmd = cmd or celery_exe('worker') <ide> self.env = env <del> self.p = self.OptionParser(argv) <del> self.with_detacher_default_options(self.p) <ide> <ide> self.on_stopping_preamble = on_stopping_preamble <ide> self.on_send_signal = on_send_signal <ide> def send_all(self, sig): <ide> def kill(self): <ide> return self.send_all(signal.SIGKILL) <ide> <del> def restart(self): <add> def restart(self, sig=signal.SIGTERM): <ide> retvals = [] <ide> <ide> def restart_on_down(node): <ide> def restart_on_down(node): <ide> maybe_call(self.on_node_status, node, retval) <ide> retvals.append(retval) <ide> <del> self._stop_nodes(retry=2, on_down=restart_on_down) <add> self._stop_nodes(retry=2, on_down=restart_on_down, sig=sig) <ide> return retvals <ide> <del> def stop(self, retry=None, callback=None): <del> return self._stop_nodes(retry=retry, on_down=callback) <add> def stop(self, retry=None, callback=None, sig=signal.SIGTERM): <add> return self._stop_nodes(retry=retry, on_down=callback, sig=sig) <ide> <del> def stopwait(self, retry=2, callback=None): <del> return self._stop_nodes(retry=retry, on_down=callback) <add> def stopwait(self, retry=2, callback=None, sig=signal.SIGTERM): <add> return self._stop_nodes(retry=retry, on_down=callback, sig=sig) <ide> <del> def _stop_nodes(self, retry=None, on_down=None): <add> def _stop_nodes(self, retry=None, on_down=None, sig=signal.SIGTERM): <ide> on_down = on_down if on_down is not None else self.on_node_down <del> restargs = self.p.args[len(self.p.values):] <ide> nodes = list(self.getpids(on_down=on_down)) <ide> if nodes: <del> for node in self.shutdown_nodes( <del> nodes, <del> sig=self._find_sig_argument(restargs), <del> retry=retry): <add> for node in self.shutdown_nodes(nodes, sig=sig, retry=retry): <ide> maybe_call(on_down, node) <ide> <del> def _find_sig_argument(self, args, default=signal.SIGTERM): <del> for arg in reversed(args): <del> if len(arg) == 2 and arg[0] == '-': <del> try: <del> return int(arg[1]) <del> except ValueError: <del> pass <del> if arg[0] == '-': <del> try: <del> return signals.signum(arg[1:]) <del> except (AttributeError, TypeError): <del> pass <del> return default <del> <ide> def shutdown_nodes(self, nodes, sig=signal.SIGTERM, retry=None): <ide> P = set(nodes) <ide> maybe_call(self.on_stopping_preamble, nodes) <ide> def find(self, name): <ide> return node <ide> raise KeyError(name) <ide> <del> def with_detacher_default_options(self, p): <del> self._setdefaultopt(p.options, ['--pidfile', '-p'], '%n.pid') <del> self._setdefaultopt(p.options, ['--logfile', '-f'], '%n%I.log') <del> self._setdefaultopt(p.options, ['--executable'], sys.executable) <del> p.options.setdefault( <del> '--cmd', <del> '-m {0}'.format(celery_exe('worker', '--detach')), <del> ) <del> <del> def _setdefaultopt(self, d, alt, value): <del> for opt in alt[1:]: <del> try: <del> return d[opt] <del> except KeyError: <del> pass <del> return d.setdefault(alt[0], value) <del> <ide> def getpids(self, on_down=None): <ide> for node in self: <ide> if node.pid: <ide> def __repr__(self): <ide> name=type(self).__name__, <ide> ) <ide> <del> @cached_property <add> @property <ide> def data(self): <del> return list(self.MultiParser(cmd=self.cmd).parse(self.p)) <add> return self.nodes <ide><path>celery/bin/multi.py <ide> from __future__ import absolute_import, print_function, unicode_literals <ide> <ide> import os <add>import signal <ide> import sys <ide> <ide> from functools import wraps <ide> <ide> from kombu.utils.objects import cached_property <ide> <ide> from celery import VERSION_BANNER <del>from celery.apps.multi import Cluster <del>from celery.platforms import EX_FAILURE, EX_OK <add>from celery.apps.multi import Cluster, MultiParser, NamespacedOptionParser <add>from celery.platforms import EX_FAILURE, EX_OK, signals <ide> from celery.utils import term <ide> from celery.utils.text import pluralize <ide> <ide> def _inner(self, *args, **kwargs): <ide> return _inner <ide> <ide> <add>def using_cluster(fun): <add> <add> @wraps(fun) <add> def _inner(self, *argv, **kwargs): <add> return fun(self, self.cluster_from_argv(argv), **kwargs) <add> return _inner <add> <add> <add>def using_cluster_and_sig(fun): <add> <add> @wraps(fun) <add> def _inner(self, *argv, **kwargs): <add> p, cluster = self._cluster_from_argv(argv) <add> sig = self._find_sig_argument(p) <add> return fun(self, cluster, sig, **kwargs) <add> return _inner <add> <add> <ide> class TermLogger(object): <ide> <ide> splash_text = 'celery multi v{version}' <ide> def colored(self): <ide> <ide> <ide> class MultiTool(TermLogger): <add> MultiParser = MultiParser <add> OptionParser = NamespacedOptionParser <ide> <ide> reserved_options = [ <ide> ('--nosplash', 'nosplash'), <ide> def _handle_reserved_options(self, argv): <ide> return argv <ide> <ide> @splash <del> def start(self, *argv): <add> @using_cluster <add> def start(self, cluster): <ide> self.note('> Starting nodes...') <del> return int(any(self.Cluster(argv).start())) <add> return int(any(cluster.start())) <ide> <ide> @splash <del> def stop(self, *argv, **kwargs): <del> return self.Cluster(argv).stop(**kwargs) <add> @using_cluster_and_sig <add> def stop(self, cluster, sig, **kwargs): <add> return cluster.stop(sig=sig, **kwargs) <ide> <ide> @splash <del> def stopwait(self, *argv, **kwargs): <del> return self.Cluster(argv).stopwait(**kwargs) <add> @using_cluster_and_sig <add> def stopwait(self, cluster, sig, **kwargs): <add> return cluster.stopwait(sig=sig, **kwargs) <ide> stop_verify = stopwait # compat <ide> <ide> @splash <del> def restart(self, *argv, **kwargs): <del> return int(any(self.Cluster(argv).restart(**kwargs))) <add> @using_cluster_and_sig <add> def restart(self, cluster, sig, **kwargs): <add> return int(any(cluster.restart(sig=sig, **kwargs))) <ide> <del> def names(self, *argv): <del> self.say('\n'.join(n.name for n in self.Cluster(argv))) <add> @using_cluster <add> def names(self, cluster): <add> self.say('\n'.join(n.name for n in cluster)) <ide> <ide> def get(self, wanted, *argv): <ide> try: <del> node = self.Cluster(argv).find(wanted) <add> node = self.cluster_from_argv(argv).find(wanted) <ide> except KeyError: <ide> return EX_FAILURE <ide> else: <ide> return self.ok(' '.join(node.argv)) <ide> <del> def show(self, *argv): <add> @using_cluster <add> def show(self, cluster): <ide> return self.ok('\n'.join( <ide> ' '.join(node.argv_with_executable) <del> for node in self.Cluster(argv) <add> for node in cluster <ide> )) <ide> <ide> @splash <del> def kill(self, *argv): <del> return self.Cluster(argv).kill() <add> @using_cluster <add> def kill(self, cluster): <add> return cluster.kill() <ide> <ide> def expand(self, template, *argv): <ide> return self.ok('\n'.join( <ide> node.expander(template) <del> for node in self.Cluster(argv) <add> for node in self.cluster_from_argv(argv) <ide> )) <ide> <ide> def help(self, *argv): <ide> self.say(__doc__) <ide> <del> def Cluster(self, argv, cmd=None): <add> def _find_sig_argument(self, p, default=signal.SIGTERM): <add> args = p.args[len(p.values):] <add> for arg in reversed(args): <add> if len(arg) == 2 and arg[0] == '-': <add> try: <add> return int(arg[1]) <add> except ValueError: <add> pass <add> if arg[0] == '-': <add> try: <add> return signals.signum(arg[1:]) <add> except (AttributeError, TypeError): <add> pass <add> return default <add> <add> def _nodes_from_argv(self, argv, cmd=None): <add> cmd = cmd if cmd is not None else self.cmd <add> p = self.OptionParser(argv) <add> p.parse() <add> return p, self.MultiParser(cmd=cmd).parse(p) <add> <add> def cluster_from_argv(self, argv, cmd=None): <add> _, cluster = self._cluster_from_argv(argv, cmd=cmd) <add> return cluster <add> <add> def _cluster_from_argv(self, argv, cmd=None): <add> p, nodes = self._nodes_from_argv(argv, cmd=cmd) <add> return p, self.Cluster(list(nodes), cmd=cmd) <add> <add> def Cluster(self, nodes, cmd=None): <ide> return Cluster( <del> argv, cmd if cmd is not None else self.cmd, <add> nodes, <add> cmd=cmd, <ide> env=self.env, <ide> on_stopping_preamble=self.on_stopping_preamble, <ide> on_send_signal=self.on_send_signal, <ide><path>celery/tests/apps/test_multi.py <ide> <ide> import errno <ide> import signal <add>import sys <ide> <ide> from celery.apps.multi import ( <del> Cluster, MultiParser, NamespacedOptionParser, Node, <add> Cluster, MultiParser, NamespacedOptionParser, Node, format_opt, <ide> ) <ide> <ide> from celery.tests.case import AppCase, Mock, call, patch <ide> <ide> <ide> class test_functions(AppCase): <ide> <del> def test_findsig(self): <del> m = Cluster([]) <del> self.assertEqual(m._find_sig_argument(['a', 'b', 'c', '-1']), 1) <del> self.assertEqual(m._find_sig_argument(['--foo=1', '-9']), 9) <del> self.assertEqual(m._find_sig_argument(['-INT']), signal.SIGINT) <del> self.assertEqual(m._find_sig_argument([]), signal.SIGTERM) <del> self.assertEqual(m._find_sig_argument(['-s']), signal.SIGTERM) <del> self.assertEqual(m._find_sig_argument(['-log']), signal.SIGTERM) <del> <ide> def test_parse_ns_range(self): <ide> m = MultiParser() <ide> self.assertEqual(m._parse_ns_range('1-3', True), ['1', '2', '3']) <ide> def test_parse_ns_range(self): <ide> ) <ide> <ide> def test_format_opt(self): <del> m = MultiParser() <del> self.assertEqual(m.format_opt('--foo', None), '--foo') <del> self.assertEqual(m.format_opt('-c', 1), '-c 1') <del> self.assertEqual(m.format_opt('--log', 'foo'), '--log=foo') <add> self.assertEqual(format_opt('--foo', None), '--foo') <add> self.assertEqual(format_opt('-c', 1), '-c 1') <add> self.assertEqual(format_opt('--log', 'foo'), '--log=foo') <ide> <ide> <ide> class test_NamespacedOptionParser(AppCase): <ide> <ide> def test_parse(self): <ide> x = NamespacedOptionParser(['-c:1,3', '4']) <add> x.parse() <ide> self.assertEqual(x.namespaces.get('1,3'), {'-c': '4'}) <ide> x = NamespacedOptionParser(['-c:jerry,elaine', '5', <ide> '--loglevel:kramer=DEBUG', <ide> '--flag', <ide> '--logfile=foo', '-Q', 'bar', 'a', 'b', <ide> '--', '.disable_rate_limits=1']) <add> x.parse() <ide> self.assertEqual(x.options, {'--logfile': 'foo', <ide> '-Q': 'bar', <ide> '--flag': None}) <ide> def test_parse(self, gethostname): <ide> 'elaine', 'kramer', <ide> '--', '.disable_rate_limits=1', <ide> ]) <add> p.parse() <ide> it = multi_args(p, cmd='COMMAND', append='*AP*', <ide> prefix='*P*', suffix='*S*') <ide> nodes = list(it) <ide> def assert_line_in(name, args): <ide> self.assertEqual(nodes2[0].argv[-1], '-- .disable_rate_limits=1') <ide> <ide> p2 = NamespacedOptionParser(['10', '-c:1', '5']) <add> p2.parse() <ide> nodes3 = list(multi_args(p2, cmd='COMMAND')) <add> <add> def _args(name, *args): <add> return args + ( <add> '--pidfile={0}.pid'.format(name), <add> '--logfile={0}%I.log'.format(name), <add> '--executable={0}'.format(sys.executable), <add> '', <add> ) <add> <ide> self.assertEqual(len(nodes3), 10) <ide> self.assertEqual(nodes3[0].name, '[email protected]') <ide> self.assertTupleEqual( <ide> nodes3[0].argv, <del> ('COMMAND', '-n [email protected]', '-c 5', ''), <add> ('COMMAND', '-c 5', '-n [email protected]') + _args('celery1'), <ide> ) <ide> for i, worker in enumerate(nodes3[1:]): <ide> self.assertEqual(worker.name, 'celery%[email protected]' % (i + 2)) <ide> self.assertTupleEqual( <ide> worker.argv, <del> ('COMMAND', '-n celery%[email protected]' % (i + 2), ''), <add> (('COMMAND', '-n celery%[email protected]' % (i + 2)) + <add> _args('celery%s' % (i + 2))), <ide> ) <ide> <ide> nodes4 = list(multi_args(p2, cmd='COMMAND', suffix='""')) <ide> self.assertEqual(len(nodes4), 10) <ide> self.assertEqual(nodes4[0].name, 'celery1@') <ide> self.assertTupleEqual( <ide> nodes4[0].argv, <del> ('COMMAND', '-n celery1@', '-c 5', ''), <add> ('COMMAND', '-c 5', '-n celery1@') + _args('celery1'), <ide> ) <ide> <ide> p3 = NamespacedOptionParser(['foo@', '-c:foo', '5']) <add> p3.parse() <ide> nodes5 = list(multi_args(p3, cmd='COMMAND', suffix='""')) <ide> self.assertEqual(nodes5[0].name, 'foo@') <ide> self.assertTupleEqual( <ide> nodes5[0].argv, <del> ('COMMAND', '-n foo@', '-c 5', ''), <add> ('COMMAND', '-c 5', '-n foo@') + _args('foo'), <ide> ) <ide> <ide> p4 = NamespacedOptionParser(['foo', '-Q:1', 'test']) <add> p4.parse() <ide> nodes6 = list(multi_args(p4, cmd='COMMAND', suffix='""')) <ide> self.assertEqual(nodes6[0].name, 'foo@') <ide> self.assertTupleEqual( <ide> nodes6[0].argv, <del> ('COMMAND', '-n foo@', '-Q test', ''), <add> ('COMMAND', '-Q test', '-n foo@') + _args('foo'), <ide> ) <ide> <ide> p5 = NamespacedOptionParser(['foo@bar', '-Q:1', 'test']) <add> p5.parse() <ide> nodes7 = list(multi_args(p5, cmd='COMMAND', suffix='""')) <ide> self.assertEqual(nodes7[0].name, 'foo@bar') <ide> self.assertTupleEqual( <ide> nodes7[0].argv, <del> ('COMMAND', '-n foo@bar', '-Q test', ''), <add> ('COMMAND', '-Q test', '-n foo@bar') + _args('foo'), <ide> ) <ide> <ide> p6 = NamespacedOptionParser(['foo@bar', '-Q:0', 'test']) <add> p6.parse() <ide> with self.assertRaises(KeyError): <ide> list(multi_args(p6)) <ide> <ide> def test_optmerge(self): <ide> p = NamespacedOptionParser(['foo', 'test']) <add> p.parse() <ide> p.options = {'x': 'y'} <ide> r = p.optmerge('foo') <ide> self.assertEqual(r['x'], 'y') <ide> def setup(self): <ide> '--logfile': 'foo.log', <ide> } <ide> self.p.namespaces = {} <del> self.expander = Mock(name='expander') <del> self.node = Node( <del> '[email protected]', ['-A', 'proj'], self.expander, 'foo', self.p, <del> ) <add> self.node = Node('[email protected]', options={'-A': 'proj'}) <add> self.expander = self.node.expander = Mock(name='expander') <ide> self.node.pid = 303 <ide> <add> def test_from_kwargs(self): <add> n = Node.from_kwargs( <add> '[email protected]', <add> max_tasks_per_child=30, A='foo', Q='q1,q2', O='fair', <add> ) <add> self.assertTupleEqual(n.argv, ( <add> '-m celery worker --detach', <add> '-A foo', <add> '--executable={0}'.format(n.executable), <add> '-O fair', <add> '-n [email protected]', <add> '--logfile=foo%I.log', <add> '-Q q1,q2', <add> '--max-tasks-per-child=30', <add> '--pidfile=foo.pid', <add> '', <add> )) <add> <ide> @patch('os.kill') <ide> def test_send(self, kill): <ide> self.assertTrue(self.node.send(9)) <ide> def test_handle_process_exit__signalled(self): <ide> <ide> def test_logfile(self): <ide> self.assertEqual(self.node.logfile, self.expander.return_value) <del> self.expander.assert_called_with('foo.log') <add> self.expander.assert_called_with('%n%I.log') <ide> <ide> <ide> class test_Cluster(AppCase): <ide> def setup(self): <ide> self.gethostname.return_value = 'example.com' <ide> self.Pidfile = self.patch('celery.apps.multi.Pidfile') <ide> self.cluster = Cluster( <del> ['foo', 'bar', 'baz'], <add> [Node('[email protected]'), <add> Node('[email protected]'), <add> Node('[email protected]')], <ide> on_stopping_preamble=Mock(name='on_stopping_preamble'), <ide> on_send_signal=Mock(name='on_send_signal'), <ide> on_still_waiting_for=Mock(name='on_still_waiting_for'), <ide> def test_getpids(self): <ide> self.prepare_pidfile_for_getpids(self.Pidfile) <ide> callback = Mock() <ide> <del> p = Cluster(['foo', 'bar', 'baz']) <add> p = Cluster([ <add> Node('[email protected]'), <add> Node('[email protected]'), <add> Node('[email protected]'), <add> ]) <ide> nodes = p.getpids(on_down=callback) <ide> node_0, node_1 = nodes <ide> self.assertEqual(node_0.name, '[email protected]') <ide><path>celery/tests/bin/test_multi.py <ide> from __future__ import absolute_import, unicode_literals <ide> <add>import signal <ide> import sys <ide> <ide> from celery.bin.multi import ( <ide> def setup(self): <ide> self.fh = WhateverIO() <ide> self.env = {} <ide> self.t = MultiTool(env=self.env, fh=self.fh) <add> self.t.cluster_from_argv = Mock(name='cluster_from_argv') <add> self.t._cluster_from_argv = Mock(name='cluster_from_argv') <ide> self.t.Cluster = Mock(name='Cluster') <ide> self.t.carp = Mock(name='.carp') <ide> self.t.usage = Mock(name='.usage') <ide> def setup(self): <ide> self.t.ok = Mock(name='.ok') <ide> self.cluster = self.t.Cluster.return_value <ide> <add> def _cluster_from_argv(argv): <add> p = self.t.OptionParser(argv) <add> p.parse() <add> return p, self.cluster <add> self.t.cluster_from_argv.return_value = self.cluster <add> self.t._cluster_from_argv.side_effect = _cluster_from_argv <add> <add> def test_findsig(self): <add> self.assert_sig_argument(['a', 'b', 'c', '-1'], 1) <add> self.assert_sig_argument(['--foo=1', '-9'], 9) <add> self.assert_sig_argument(['-INT'], signal.SIGINT) <add> self.assert_sig_argument([], signal.SIGTERM) <add> self.assert_sig_argument(['-s'], signal.SIGTERM) <add> self.assert_sig_argument(['-log'], signal.SIGTERM) <add> <add> def assert_sig_argument(self, args, expected): <add> p = self.t.OptionParser(args) <add> p.parse() <add> self.assertEqual(self.t._find_sig_argument(p), expected) <add> <ide> def test_execute_from_commandline(self): <ide> self.t.call_command = Mock(name='call_command') <ide> self.t.execute_from_commandline( <ide> def test_start(self): <ide> self.cluster.start.return_value = [0, 0, 1, 0] <ide> self.assertTrue(self.t.start('10', '-A', 'proj')) <ide> self.t.splash.assert_called_with() <del> self.t.Cluster.assert_called_with(('10', '-A', 'proj')) <add> self.t.cluster_from_argv.assert_called_with(('10', '-A', 'proj')) <ide> self.cluster.start.assert_called_with() <ide> <ide> def test_start__exitcodes(self): <ide> def test_start__exitcodes(self): <ide> def test_stop(self): <ide> self.t.stop('10', '-A', 'proj', retry=3) <ide> self.t.splash.assert_called_with() <del> self.t.Cluster.assert_called_with(('10', '-A', 'proj')) <del> self.cluster.stop.assert_called_with(retry=3) <add> self.t._cluster_from_argv.assert_called_with(('10', '-A', 'proj')) <add> self.cluster.stop.assert_called_with(retry=3, sig=signal.SIGTERM) <ide> <ide> def test_stopwait(self): <ide> self.t.stopwait('10', '-A', 'proj', retry=3) <ide> self.t.splash.assert_called_with() <del> self.t.Cluster.assert_called_with(('10', '-A', 'proj')) <del> self.cluster.stopwait.assert_called_with(retry=3) <add> self.t._cluster_from_argv.assert_called_with(('10', '-A', 'proj')) <add> self.cluster.stopwait.assert_called_with(retry=3, sig=signal.SIGTERM) <ide> <ide> def test_restart(self): <ide> self.cluster.restart.return_value = [0, 0, 1, 0] <ide> self.t.restart('10', '-A', 'proj') <ide> self.t.splash.assert_called_with() <del> self.t.Cluster.assert_called_with(('10', '-A', 'proj')) <del> self.cluster.restart.assert_called_with() <add> self.t._cluster_from_argv.assert_called_with(('10', '-A', 'proj')) <add> self.cluster.restart.assert_called_with(sig=signal.SIGTERM) <ide> <ide> def test_names(self): <del> self.t.Cluster.return_value = [Mock(), Mock()] <del> self.t.Cluster.return_value[0].name = 'x' <del> self.t.Cluster.return_value[1].name = 'y' <add> self.t.cluster_from_argv.return_value = [Mock(), Mock()] <add> self.t.cluster_from_argv.return_value[0].name = 'x' <add> self.t.cluster_from_argv.return_value[1].name = 'y' <ide> self.t.names('10', '-A', 'proj') <ide> self.t.say.assert_called() <ide> <ide> def test_get(self): <ide> self.t.ok.return_value, <ide> ) <ide> self.cluster.find.assert_called_with('wanted') <del> self.t.Cluster.assert_called_with(('10', '-A', 'proj')) <add> self.t.cluster_from_argv.assert_called_with(('10', '-A', 'proj')) <ide> self.t.ok.assert_called_with(' '.join(node.argv)) <ide> <ide> def test_get__KeyError(self): <ide> self.cluster.find.side_effect = KeyError() <ide> self.assertTrue(self.t.get('wanted', '10', '-A', 'proj')) <ide> <ide> def test_show(self): <del> nodes = self.t.Cluster.return_value = [ <add> nodes = self.t.cluster_from_argv.return_value = [ <ide> Mock(name='n1'), <ide> Mock(name='n2'), <ide> ] <ide> def test_show(self): <ide> def test_kill(self): <ide> self.t.kill('10', '-A', 'proj') <ide> self.t.splash.assert_called_with() <del> self.t.Cluster.assert_called_with(('10', '-A', 'proj')) <add> self.t.cluster_from_argv.assert_called_with(('10', '-A', 'proj')) <ide> self.cluster.kill.assert_called_with() <ide> <ide> def test_expand(self): <ide> node1 = Mock(name='n1') <ide> node2 = Mock(name='n2') <ide> node1.expander.return_value = 'A' <ide> node2.expander.return_value = 'B' <del> nodes = self.t.Cluster.return_value = [node1, node2] <add> nodes = self.t.cluster_from_argv.return_value = [node1, node2] <ide> self.assertIs(self.t.expand('%p', '10'), self.t.ok.return_value) <del> self.t.Cluster.assert_called_with(('10',)) <add> self.t.cluster_from_argv.assert_called_with(('10',)) <ide> for node in nodes: <ide> node.expander.assert_called_with('%p') <ide> self.t.ok.assert_called_with('A\nB') <ide> def test_splash(self): <ide> <ide> def test_Cluster(self): <ide> m = MultiTool() <del> c = m.Cluster(['A', 'B', 'C']) <del> self.assertListEqual(c.argv, ['A', 'B', 'C']) <add> c = m.cluster_from_argv(['A', 'B', 'C']) <ide> self.assertIs(c.env, m.env) <ide> self.assertEqual(c.cmd, 'celery worker') <ide> self.assertEqual(c.on_stopping_preamble, m.on_stopping_preamble) <ide><path>celery/utils/imports.py <ide> def load_extension_classes(namespace): <ide> namespace, class_name, exc)) <ide> else: <ide> yield name, cls <del>
5
Ruby
Ruby
check destination before unlinking
17953f2b83ba764c5cd5dc679d98c82fb6cc4b77
<ide><path>Library/Homebrew/cmd/unlink.rb <ide> def unlink <ide> raise KegUnspecifiedError if ARGV.named.empty? <ide> <ide> ARGV.kegs.each do |keg| <del> return if !keg.linked? <ide> print "Unlinking #{keg}... " <ide> puts "#{keg.unlink} links removed" <ide> end <ide><path>Library/Homebrew/keg.rb <ide> def uninstall <ide> <ide> def unlink <ide> n=0 <del> return n if !linked? <ide> <ide> %w[bin etc lib include sbin share var].map{ |d| self/d }.each do |src| <ide> next unless src.exist? <ide> src.find do |src| <ide> next if src == self <ide> dst=HOMEBREW_PREFIX+src.relative_path_from(self) <del> next unless dst.symlink? <add> <add> # check whether the file to be unlinked is from the current keg first <add> if !dst.symlink? || !dst.exist? || src.expand_path != dst.realpath <add> next <add> end <add> <ide> dst.uninstall_info if dst.to_s =~ INFOFILE_RX and ENV['HOMEBREW_KEEP_INFO'] <ide> dst.unlink <ide> dst.parent.rmdir_if_possible
2
Go
Go
add utility to check if snapshotters are enabled
74b84d00b38e81a00d105d4755919c3710afd05d
<ide><path>integration-cli/docker_cli_inspect_test.go <ide> func (s *DockerCLIInspectSuite) TestInspectImage(c *testing.T) { <ide> // fails, fix the difference in the image serialization instead of <ide> // updating this hash. <ide> imageTestID := "sha256:11f64303f0f7ffdc71f001788132bca5346831939a956e3e975c93267d89a16d" <del> usesContainerdSnapshotter := false // TODO(vvoland): Check for feature flag <del> if usesContainerdSnapshotter { <add> if containerdSnapshotterEnabled() { <ide> // Under containerd ID of the image is the digest of the manifest list. <ide> imageTestID = "sha256:e43ca824363c5c56016f6ede3a9035afe0e9bd43333215e0b0bde6193969725d" <ide> } <ide><path>integration-cli/requirements_test.go <ide> import ( <ide> "testing" <ide> "time" <ide> <add> "github.com/containerd/containerd/plugin" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/swarm" <ide> "github.com/docker/docker/api/types/versions" <ide> func Devicemapper() bool { <ide> return strings.HasPrefix(testEnv.DaemonInfo.Driver, "devicemapper") <ide> } <ide> <add>// containerdSnapshotterEnabled checks if the daemon in the test-environment is <add>// configured with containerd-snapshotters enabled. <add>func containerdSnapshotterEnabled() bool { <add> for _, v := range testEnv.DaemonInfo.DriverStatus { <add> if v[0] == "driver-type" { <add> return v[1] == string(plugin.SnapshotPlugin) <add> } <add> } <add> return false <add>} <add> <ide> func IPv6() bool { <ide> cmd := exec.Command("test", "-f", "/proc/net/if_inet6") <ide> return cmd.Run() != nil
2
Text
Text
fix tutorial to have exact translation of example
2e3cf459ba225e7a0bd8489bb57bce7b6aea7d53
<ide><path>docs/docs/tutorial.md <ide> The first thing you'll notice is the XML-ish syntax in your JavaScript. We have <ide> <ide> ```javascript <ide> // tutorial1-raw.js <del>var CommentBox = React.createClass({ <add>var CommentBox = React.createClass({displayName: 'CommentBox', <ide> render: function() { <ide> return ( <del> React.DOM.div({ <del> className: 'commentBox', <del> children: 'Hello, world! I am a CommentBox.' <del> }) <add> React.DOM.div({className: "commentBox"}, <add> "Hello, world! I am a CommentBox." <add> ) <ide> ); <ide> } <ide> }); <ide> React.renderComponent( <del> CommentBox({}), <add> CommentBox(null), <ide> document.getElementById('content') <ide> ); <ide> ```
1
Python
Python
fix doc for errordetail
fff3db5517ef80ce0ecb7448feba5aeca46d85d3
<ide><path>rest_framework/exceptions.py <ide> def _get_full_details(detail): <ide> <ide> class ErrorDetail(six.text_type): <ide> """ <del> A string-like object that can additionally <add> A string-like object that can additionally have a code. <ide> """ <ide> code = None <ide>
1
Text
Text
fix a minor typo in swarm tutorial docs
93fa7e75553c3332314b3b988f7082cfde857475
<ide><path>docs/swarm/swarm-tutorial/delete-service.md <ide> removed the service. The CLI returns a message that the service is not found: <ide> <ide> ## What's next? <ide> <del>In the next step of the tutorial, you set up a new service and and apply a <add>In the next step of the tutorial, you set up a new service and apply a <ide> [rolling update](rolling-update.md).
1
Ruby
Ruby
remove obsoleted argument
8fecd4c198948dc1d86240b1a3ee4648da49ffe0
<ide><path>Library/Homebrew/cmd/help.rb <ide> brew search [foo] <ide> brew list [FORMULA...] <ide> brew update <del> brew upgrade [--all | FORMULA...] <add> brew upgrade [FORMULA...] <ide> brew pin/unpin [FORMULA...] <ide> <ide> Troubleshooting:
1
PHP
PHP
change visibility of mergerules
f7e04670b70300f724ecd70377f16173f0c506f6
<ide><path>src/Illuminate/Validation/Validator.php <ide> public function sometimes($attribute, $rules, $callback) <ide> * @param string|array $rules <ide> * @return void <ide> */ <del> protected function mergeRules($attribute, $rules) <add> public function mergeRules($attribute, $rules) <ide> { <ide> $current = array_get($this->rules, $attribute, array()); <ide> <ide> public function failed() <ide> public function messages() <ide> { <ide> if ( ! $this->messages) $this->passes(); <del> <add> <ide> return $this->messages; <ide> } <ide> <ide> public function messages() <ide> public function errors() <ide> { <ide> if ( ! $this->messages) $this->passes(); <del> <add> <ide> return $this->messages; <ide> } <ide>
1
Python
Python
fix mypy in
06dad4f9d8624d9b9a4be56fef47a657f6ce6b82
<ide><path>blockchain/chinese_remainder_theorem.py <del># Chinese Remainder Theorem: <del># GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) <add>""" <add>Chinese Remainder Theorem: <add>GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) <ide> <del># If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b <del># there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are <del># two such integers, then n1=n2(mod ab) <add>If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b <add>there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are <add>two such integers, then n1=n2(mod ab) <ide> <del># Algorithm : <add>Algorithm : <ide> <del># 1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1 <del># 2. Take n = ra*by + rb*ax <add>1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1 <add>2. Take n = ra*by + rb*ax <add>""" <add>from typing import Tuple <ide> <ide> <ide> # Extended Euclid <del>def extended_euclid(a: int, b: int) -> (int, int): <add>def extended_euclid(a: int, b: int) -> Tuple[int, int]: <ide> """ <ide> >>> extended_euclid(10, 6) <ide> (-1, 2) <ide><path>blockchain/diophantine_equation.py <del># Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the <del># diophantine equation a*x + b*y = c has a solution (where x and y are integers) <del># iff gcd(a,b) divides c. <add>from typing import Tuple <ide> <del># GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) <ide> <del> <del>def diophantine(a: int, b: int, c: int) -> (int, int): <add>def diophantine(a: int, b: int, c: int) -> Tuple[float, float]: <ide> """ <add> Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the <add> diophantine equation a*x + b*y = c has a solution (where x and y are integers) <add> iff gcd(a,b) divides c. <add> <add> GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) <add> <ide> >>> diophantine(10,6,14) <ide> (-7.0, 14.0) <ide> <ide> def diophantine(a: int, b: int, c: int) -> (int, int): <ide> return (r * x, r * y) <ide> <ide> <del># Lemma : if n|ab and gcd(a,n) = 1, then n|b. <del> <del># Finding All solutions of Diophantine Equations: <add>def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: <add> """ <add> Lemma : if n|ab and gcd(a,n) = 1, then n|b. <ide> <del># Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine <del># Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the solutions have the form <del># a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer. <add> Finding All solutions of Diophantine Equations: <ide> <del># n is the number of solution you want, n = 2 by default <add> Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of <add> Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the <add> solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, <add> where t is an arbitrary integer. <ide> <add> n is the number of solution you want, n = 2 by default <ide> <del>def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: <del> """ <ide> >>> diophantine_all_soln(10, 6, 14) <ide> -7.0 14.0 <ide> -4.0 9.0 <ide> def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: <ide> print(x, y) <ide> <ide> <del># Euclid's Lemma : d divides a and b, if and only if d divides a-b and b <del> <del># Euclid's Algorithm <del> <del> <ide> def greatest_common_divisor(a: int, b: int) -> int: <ide> """ <add> Euclid's Lemma : d divides a and b, if and only if d divides a-b and b <add> <add> Euclid's Algorithm <add> <ide> >>> greatest_common_divisor(7,5) <ide> 1 <ide> <ide> def greatest_common_divisor(a: int, b: int) -> int: <ide> return b <ide> <ide> <del># Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers <del># x and y, then d = gcd(a,b) <del> <del> <del>def extended_gcd(a: int, b: int) -> (int, int, int): <add>def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: <ide> """ <add> Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers <add> x and y, then d = gcd(a,b) <add> <ide> >>> extended_gcd(10, 6) <ide> (2, -1, 2) <ide> <ide><path>blockchain/modular_division.py <del># Modular Division : <del># An efficient algorithm for dividing b by a modulo n. <add>from typing import Tuple <ide> <del># GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) <ide> <del># Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should <del># return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)). <add>def modular_division(a: int, b: int, n: int) -> int: <add> """ <add> Modular Division : <add> An efficient algorithm for dividing b by a modulo n. <ide> <del># Theorem: <del># a has a multiplicative inverse modulo n iff gcd(a,n) = 1 <add> GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) <ide> <add> Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should <add> return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)). <ide> <del># This find x = b*a^(-1) mod n <del># Uses ExtendedEuclid to find the inverse of a <add> Theorem: <add> a has a multiplicative inverse modulo n iff gcd(a,n) = 1 <ide> <ide> <del>def modular_division(a: int, b: int, n: int) -> int: <del> """ <add> This find x = b*a^(-1) mod n <add> Uses ExtendedEuclid to find the inverse of a <add> <ide> >>> modular_division(4,8,5) <ide> 2 <ide> <ide> def modular_division(a: int, b: int, n: int) -> int: <ide> return x <ide> <ide> <del># This function find the inverses of a i.e., a^(-1) <ide> def invert_modulo(a: int, n: int) -> int: <ide> """ <add> This function find the inverses of a i.e., a^(-1) <add> <ide> >>> invert_modulo(2, 5) <ide> 3 <ide> <ide> def invert_modulo(a: int, n: int) -> int: <ide> <ide> # ------------------ Finding Modular division using invert_modulo ------------------- <ide> <del># This function used the above inversion of a to find x = (b*a^(-1))mod n <add> <ide> def modular_division2(a: int, b: int, n: int) -> int: <ide> """ <add> This function used the above inversion of a to find x = (b*a^(-1))mod n <add> <ide> >>> modular_division2(4,8,5) <ide> 2 <ide> <ide> def modular_division2(a: int, b: int, n: int) -> int: <ide> return x <ide> <ide> <del># Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x <del># and y, then d = gcd(a,b) <del> <del> <del>def extended_gcd(a: int, b: int) -> (int, int, int): <add>def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: <ide> """ <del> >>> extended_gcd(10, 6) <del> (2, -1, 2) <add> Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x <add> and y, then d = gcd(a,b) <add> >>> extended_gcd(10, 6) <add> (2, -1, 2) <ide> <del> >>> extended_gcd(7, 5) <del> (1, -2, 3) <add> >>> extended_gcd(7, 5) <add> (1, -2, 3) <ide> <ide> ** extended_gcd function is used when d = gcd(a,b) is required in output <ide> <ide> def extended_gcd(a: int, b: int) -> (int, int, int): <ide> return (d, x, y) <ide> <ide> <del># Extended Euclid <del>def extended_euclid(a: int, b: int) -> (int, int): <add>def extended_euclid(a: int, b: int) -> Tuple[int, int]: <ide> """ <add> Extended Euclid <ide> >>> extended_euclid(10, 6) <ide> (-1, 2) <ide> <ide> def extended_euclid(a: int, b: int) -> (int, int): <ide> return (y, x - k * y) <ide> <ide> <del># Euclid's Lemma : d divides a and b, if and only if d divides a-b and b <del># Euclid's Algorithm <del> <del> <ide> def greatest_common_divisor(a: int, b: int) -> int: <ide> """ <add> Euclid's Lemma : d divides a and b, if and only if d divides a-b and b <add> Euclid's Algorithm <add> <ide> >>> greatest_common_divisor(7,5) <ide> 1 <ide>
3
Ruby
Ruby
pass explicit sort to handle apfs
f1b183b287f7b3d94d5cc5093581fe8c1de8be9d
<ide><path>Library/Homebrew/cmd/list.rb <ide> def list_unbrewed <ide> dirs.delete "etc" <ide> dirs.delete "var" <ide> <del> args = dirs + %w[-type f (] <add> args = dirs.sort + %w[-type f (] <ide> args.concat UNBREWED_EXCLUDE_FILES.flat_map { |f| %W[! -name #{f}] } <ide> args.concat UNBREWED_EXCLUDE_PATHS.flat_map { |d| %W[! -path #{d}] } <ide> args.concat %w[)]
1
Python
Python
fix wrong reference in ptb_word_lm.py
99566f8149b03af593935fd0708010ab805421fc
<ide><path>tutorials/rnn/ptb/ptb_word_lm.py <ide> def make_cell(): <ide> <ide> self._initial_state = cell.zero_state(config.batch_size, data_type()) <ide> state = self._initial_state <del> # Simplified version of tensorflow_models/tutorials/rnn/rnn.py's rnn(). <add> # Simplified version of tf.nn.static_rnn(). <ide> # This builds an unrolled LSTM for tutorial purposes only. <del> # In general, use the rnn() or state_saving_rnn() from rnn.py. <add> # In general, use tf.nn.static_rnn() or tf.nn.static_state_saving_rnn(). <ide> # <ide> # The alternative version of the code below is: <ide> # <del> # inputs = tf.unstack(inputs, num=num_steps, axis=1) <del> # outputs, state = tf.contrib.rnn.static_rnn(cell, inputs, <del> # initial_state=self._initial_state) <add> # inputs = tf.unstack(inputs, num=self.num_steps, axis=1) <add> # outputs, state = tf.nn.static_rnn(cell, inputs, <add> # initial_state=self._initial_state) <ide> outputs = [] <ide> with tf.variable_scope("RNN"): <ide> for time_step in range(self.num_steps):
1
Javascript
Javascript
name anonymous functions in core.js
ce3f9ae3e8134f33917740e38ad1a0fcc0641a20
<ide><path>src/core.js <ide> var Page = (function pagePage() { <ide> return shadow(this, 'rotate', rotate); <ide> }, <ide> <del> startRenderingFromIRQueue: function startRenderingFromIRQueue( <add> startRenderingFromIRQueue: function pageStartRenderingFromIRQueue( <ide> IRQueue, fonts) { <ide> var self = this; <ide> this.IRQueue = IRQueue; <ide> var Page = (function pagePage() { <ide> }); <ide> }; <ide> <del> this.ensureFonts(fonts, function() { <add> this.ensureFonts(fonts, <add> function pageStartRenderingFromIRQueueEnsureFonts() { <ide> displayContinuation(); <ide> }); <ide> }, <ide> <del> getIRQueue: function(handler, dependency) { <add> getIRQueue: function pageGetIRQueue(handler, dependency) { <ide> if (this.IRQueue) { <ide> // content was compiled <ide> return this.IRQueue; <ide> var Page = (function pagePage() { <ide> content, resources, IRQueue, dependency); <ide> }, <ide> <del> ensureFonts: function(fonts, callback) { <add> ensureFonts: function pageEnsureFonts(fonts, callback) { <ide> // Convert the font names to the corresponding font obj. <ide> for (var i = 0; i < fonts.length; i++) { <ide> fonts[i] = this.objs.objs[fonts[i]].data; <ide> var Page = (function pagePage() { <ide> // Load all the fonts <ide> var fontObjs = FontLoader.bind( <ide> fonts, <del> function(fontObjs) { <add> function pageEnsureFontsFontObjs(fontObjs) { <ide> this.stats.fonts = Date.now(); <ide> <ide> callback.call(this); <ide> var Page = (function pagePage() { <ide> ); <ide> }, <ide> <del> display: function(gfx, callback) { <add> display: function pageDisplay(gfx, callback) { <ide> var xref = this.xref; <ide> var resources = xref.fetchIfRef(this.resources); <ide> var mediaBox = xref.fetchIfRef(this.mediaBox); <ide> var Page = (function pagePage() { <ide> } <ide> return links; <ide> }, <del> startRendering: function(ctx, callback) { <add> startRendering: function pageStartRendering(ctx, callback) { <ide> this.ctx = ctx; <ide> this.callback = callback; <ide> <ide> var PDFDocModel = (function pdfDoc() { <ide> return constructor; <ide> })(); <ide> <del>var PDFDoc = (function() { <add>var PDFDoc = (function pdfDoc() { <ide> function constructor(arg, callback) { <ide> var stream = null; <ide> var data = null; <ide> var PDFDoc = (function() { <ide> } else { <ide> // If we don't use a worker, just post/sendMessage to the main thread. <ide> var worker = { <del> postMessage: function(obj) { <add> postMessage: function pdfDocPostMessage(obj) { <ide> worker.onmessage({data: obj}); <ide> }, <del> terminate: function() {} <add> terminate: function pdfDocTerminate() {} <ide> }; <ide> } <ide> this.worker = worker; <ide> var PDFDoc = (function() { <ide> var processorHandler = this.processorHandler = <ide> new MessageHandler('main', worker); <ide> <del> processorHandler.on('page', function(data) { <add> processorHandler.on('page', function pdfDocPage(data) { <ide> var pageNum = data.pageNum; <ide> var page = this.pageCache[pageNum]; <ide> var depFonts = data.depFonts; <ide> <ide> page.startRenderingFromIRQueue(data.IRQueue, depFonts); <ide> }, this); <ide> <del> processorHandler.on('obj', function(data) { <add> processorHandler.on('obj', function pdfDocObj(data) { <ide> var id = data[0]; <ide> var type = data[1]; <ide> <ide> var PDFDoc = (function() { <ide> } <ide> }, this); <ide> <del> processorHandler.on('font_ready', function(data) { <add> processorHandler.on('font_ready', function pdfDocFontReady(data) { <ide> var id = data[0]; <ide> var font = new FontShape(data[1]); <ide> <ide> var PDFDoc = (function() { <ide> } <ide> <ide> this.workerReadyPromise = new Promise('workerReady'); <del> setTimeout(function() { <add> setTimeout(function pdfDocFontReadySetTimeout() { <ide> processorHandler.send('doc', this.data); <ide> this.workerReadyPromise.resolve(true); <ide> }.bind(this)); <ide> var PDFDoc = (function() { <ide> return this.pdf.numPages; <ide> }, <ide> <del> startRendering: function(page) { <add> startRendering: function pdfDocStartRendering(page) { <ide> // The worker might not be ready to receive the page request yet. <del> this.workerReadyPromise.then(function() { <add> this.workerReadyPromise.then(function pdfDocStartRenderingThen() { <ide> this.processorHandler.send('page_request', page.pageNumber + 1); <ide> }.bind(this)); <ide> }, <ide> <del> getPage: function(n) { <add> getPage: function pdfDocGetPage(n) { <ide> if (this.pageCache[n]) <ide> return this.pageCache[n]; <ide> <ide> var PDFDoc = (function() { <ide> return this.pageCache[n] = page; <ide> }, <ide> <del> destroy: function() { <add> destroy: function pdfDocDestroy() { <ide> if (this.worker) <ide> this.worker.terminate(); <ide>
1
Javascript
Javascript
add prototype support for boxed primitives
55147d7d9939cce1bbc2c8a70ac7ebe03e91e5cf
<ide><path>lib/internal/util/inspect.js <ide> function getPrefix(constructor, tag, fallback) { <ide> return `${constructor} `; <ide> } <ide> <del>const getBoxedValue = formatPrimitive.bind(null, stylizeNoColor); <del> <ide> // Look up the keys of the object. <ide> function getKeys(value, showHidden) { <ide> let keys; <ide> function formatRaw(ctx, value, recurseTimes, typedArray) { <ide> braces[0] = `[${tag}] {`; <ide> formatter = formatNamespaceObject; <ide> } else if (isBoxedPrimitive(value)) { <del> let type; <del> if (isNumberObject(value)) { <del> base = `[Number: ${getBoxedValue(NumberPrototype.valueOf(value))}]`; <del> type = 'number'; <del> } else if (isStringObject(value)) { <del> base = `[String: ${ <del> getBoxedValue(StringPrototype.valueOf(value), ctx) <del> }]`; <del> type = 'string'; <del> // For boxed Strings, we have to remove the 0-n indexed entries, <del> // since they just noisy up the output and are redundant <del> // Make boxed primitive Strings look like such <del> keys = keys.slice(value.length); <del> } else if (isBooleanObject(value)) { <del> base = `[Boolean: ${getBoxedValue(BooleanPrototype.valueOf(value))}]`; <del> type = 'boolean'; <del> } else if (isBigIntObject(value)) { <del> base = `[BigInt: ${getBoxedValue(BigIntPrototype.valueOf(value))}]`; <del> type = 'bigint'; <del> } else { <del> base = `[Symbol: ${getBoxedValue(SymbolPrototype.valueOf(value))}]`; <del> type = 'symbol'; <del> } <add> base = getBoxedBase(value, ctx, keys, constructor, tag); <ide> if (keys.length === 0) { <del> return ctx.stylize(base, type); <add> return base; <ide> } <ide> } else { <ide> // The input prototype got manipulated. Special handle these. We have to <ide> function getIteratorBraces(type, tag) { <ide> return [`[${tag}] {`, '}']; <ide> } <ide> <add>function getBoxedBase(value, ctx, keys, constructor, tag) { <add> let fn; <add> let type; <add> if (isNumberObject(value)) { <add> fn = NumberPrototype; <add> type = 'Number'; <add> } else if (isStringObject(value)) { <add> fn = StringPrototype; <add> type = 'String'; <add> // For boxed Strings, we have to remove the 0-n indexed entries, <add> // since they just noisy up the output and are redundant <add> // Make boxed primitive Strings look like such <add> keys.splice(0, value.length); <add> } else if (isBooleanObject(value)) { <add> fn = BooleanPrototype; <add> type = 'Boolean'; <add> } else if (isBigIntObject(value)) { <add> fn = BigIntPrototype; <add> type = 'BigInt'; <add> } else { <add> fn = SymbolPrototype; <add> type = 'Symbol'; <add> } <add> let base = `[${type}`; <add> if (type !== constructor) { <add> if (constructor === null) { <add> base += ' (null prototype)'; <add> } else { <add> base += ` (${constructor})`; <add> } <add> } <add> base += `: ${formatPrimitive(stylizeNoColor, fn.valueOf(value), ctx)}]`; <add> if (tag !== '' && tag !== constructor) { <add> base += ` [${tag}]`; <add> } <add> if (keys.length !== 0 || ctx.stylize === stylizeNoColor) <add> return base; <add> return ctx.stylize(base, type.toLowerCase()); <add>} <add> <ide> function formatError(err, constructor, tag, ctx) { <ide> // TODO(BridgeAR): Always show the error code if present. <ide> let stack = err.stack || ErrorPrototype.toString(err); <ide><path>test/parallel/test-util-inspect.js <ide> assert.strictEqual( <ide> '[Symbol: Symbol(test)]' <ide> ); <ide> assert.strictEqual(util.inspect(new Boolean(false)), '[Boolean: false]'); <del>assert.strictEqual(util.inspect(new Boolean(true)), '[Boolean: true]'); <add>assert.strictEqual( <add> util.inspect(Object.setPrototypeOf(new Boolean(true), null)), <add> '[Boolean (null prototype): true]' <add>); <ide> assert.strictEqual(util.inspect(new Number(0)), '[Number: 0]'); <del>assert.strictEqual(util.inspect(new Number(-0)), '[Number: -0]'); <add>assert.strictEqual( <add> util.inspect( <add> Object.defineProperty( <add> Object.setPrototypeOf(new Number(-0), Array.prototype), <add> Symbol.toStringTag, <add> { value: 'Foobar' } <add> ) <add> ), <add> '[Number (Array): -0] [Foobar]' <add>); <ide> assert.strictEqual(util.inspect(new Number(-1.1)), '[Number: -1.1]'); <ide> assert.strictEqual(util.inspect(new Number(13.37)), '[Number: 13.37]'); <ide>
2
Text
Text
add solution to handle click event - english
67e0f33a891d48dea4d824f1e64a2efb12a0b119
<ide><path>curriculum/challenges/english/04-data-visualization/json-apis-and-ajax/handle-click-events-with-javascript-using-the-onclick-property.english.md <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add><script> <add> document.addEventListener('DOMContentLoaded',function(){ <add> // Add your code below this line <add> document.getElementById('getMessage').onclick=function(){} <add> // Add your code above this line <add> }); <add></script> <add><style> <add> body { <add> text-align: center; <add> font-family: "Helvetica", sans-serif; <add> } <add> h1 { <add> font-size: 2em; <add> font-weight: bold; <add> } <add> .box { <add> border-radius: 5px; <add> background-color: #eee; <add> padding: 20px 5px; <add> } <add> button { <add> color: white; <add> background-color: #4791d0; <add> border-radius: 5px; <add> border: 1px solid #4791d0; <add> padding: 5px 10px 8px 10px; <add> } <add> button:hover { <add> background-color: #0F5897; <add> border: 1px solid #0F5897; <add> } <add></style> <add><h1>Cat Photo Finder</h1> <add><p class="message box"> <add> The message will go here <add></p> <add><p> <add> <button id="getMessage"> <add> Get Message <add> </button> <add></p> <ide> ``` <ide> <ide> </section>
1
Ruby
Ruby
update flash[] docs a bit
1a858f87425cb3ae5815d0356605ef74a4ae174b
<ide><path>actionpack/lib/action_controller/flash.rb <ide> module ActionController #:nodoc: <ide> # action that sets <tt>flash[:notice] = "Successfully created"</tt> before redirecting to a display action that can <ide> # then expose the flash to its template. Actually, that exposure is automatically done. Example: <ide> # <del> # class WeblogController < ActionController::Base <add> # class PostsController < ActionController::Base <ide> # def create <ide> # # save post <ide> # flash[:notice] = "Successfully created post" <del> # redirect_to :action => "display", :params => { :id => post.id } <add> # redirect_to posts_path(@post) <ide> # end <ide> # <del> # def display <add> # def show <ide> # # doesn't need to assign the flash notice to the template, that's done automatically <ide> # end <ide> # end <ide> # <del> # display.erb <del> # <% if flash[:notice] %><div class="notice"><%= flash[:notice] %></div><% end %> <add> # show.html.erb <add> # <% if flash[:notice] %> <add> # <div class="notice"><%= flash[:notice] %></div> <add> # <% end %> <ide> # <ide> # This example just places a string in the flash, but you can put any object in there. And of course, you can put as <ide> # many as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
1
Javascript
Javascript
exclude debug only tests in production builds
1b02939a7a095c883de55be9f4f09419b50c4a69
<ide><path>packages/ember-views/tests/views/view/element_test.js <add>/*globals EmberDev */ <add> <ide> import { get } from "ember-metal/property_get"; <ide> import { set } from "ember-metal/property_set"; <ide> import run from "ember-metal/run_loop"; <ide> QUnit.test("returns element if you set the value", function() { <ide> equal(get(view, 'element'), dom, 'now has set element'); <ide> }); <ide> <del>Ember.runInDebug(function() { <add>if (EmberDev && !EmberDev.runningProdBuild) { <ide> QUnit.test("should not allow the elementId to be changed after inserted", function() { <ide> view = EmberView.create({ <ide> elementId: 'one' <ide> Ember.runInDebug(function() { <ide> <ide> equal(view.get('elementId'), 'one', 'elementId is still "one"'); <ide> }); <del>}); <del> <add>}
1
PHP
PHP
implement call named scope
386e7d7ada0985dfb5408d2f4d5cdbf30846f9af
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function scopes($scopes) <ide> // Next we'll pass the scope callback to the callScope method which will take <ide> // care of grouping the "wheres" properly so the logical order doesn't get <ide> // messed up when adding scopes. Then we'll return back out the builder. <del> $builder = $builder->callScope( <del> [$this->model, 'scope'.ucfirst($scope)], <del> (array) $parameters <del> ); <add> $builder = $builder->callNamedScope($scope, (array) $parameters); <ide> } <ide> <ide> return $builder; <ide> public function applyScopes() <ide> * @param array $parameters <ide> * @return mixed <ide> */ <del> protected function callScope(callable $scope, $parameters = []) <add> protected function callScope(callable $scope, array $parameters = []) <ide> { <ide> array_unshift($parameters, $this); <ide> <ide> protected function callScope(callable $scope, $parameters = []) <ide> return $result; <ide> } <ide> <add> /** <add> * Apply the given named scope on the current builder instance. <add> * <add> * @param string $scope <add> * @param array $parameters <add> * @return mixed <add> */ <add> protected function callNamedScope($scope, array $parameters = []) <add> { <add> return $this->callScope(function () use ($scope, $parameters) { <add> return $this->model->callNamedScope($scope, $parameters); <add> }); <add> } <add> <ide> /** <ide> * Nest where conditions by slicing them at the given where count. <ide> * <ide> public function __call($method, $parameters) <ide> } <ide> <ide> if ($this->hasScope($method)) { <del> return $this->callScope([$this->model, 'scope'.ucfirst($method)], $parameters); <add> return $this->callNamedScope($method, $parameters); <ide> } <ide> <ide> if (in_array($method, $this->passthru)) { <ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function newPivot(self $parent, array $attributes, $table, $exists, $usin <ide> /** <ide> * Determine if the model has a given scope. <ide> * <del> * @param string $method <add> * @param string $scope <ide> * @return bool <ide> */ <del> public function hasScope($method) <add> public function hasScope($scope) <add> { <add> return method_exists($this, 'scope'.ucfirst($scope)); <add> } <add> <add> /** <add> * Apply the given named scope if possible. <add> * <add> * @param string $scope <add> * @param array $parameters <add> * @return mixed <add> */ <add> public function callNamedScope($scope, array $parameters = []) <ide> { <del> return method_exists($this, 'scope'.ucfirst($method)); <add> return $this->{'scope'.ucfirst($scope)}(...$parameters); <ide> } <ide> <ide> /**
2
Python
Python
standardize numpy import as "import numpy as np"
681aa536342db1332a5af9b632495ddc883ecba9
<ide><path>numpy/ma/tests/test_subclassing.py <ide> __revision__ = "$Revision: 3473 $" <ide> __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' <ide> <del>import numpy as N <add>import numpy as np <ide> import numpy.core.numeric as numeric <ide> <ide> from numpy.testing import * <ide> from numpy.ma.testutils import * <ide> from numpy.ma.core import * <ide> <del>class SubArray(N.ndarray): <del> """Defines a generic N.ndarray subclass, that stores some metadata <add>class SubArray(np.ndarray): <add> """Defines a generic np.ndarray subclass, that stores some metadata <ide> in the dictionary `info`.""" <ide> def __new__(cls,arr,info={}): <del> x = N.asanyarray(arr).view(cls) <add> x = np.asanyarray(arr).view(cls) <ide> x.info = info <ide> return x <ide> def __array_finalize__(self, obj): <ide> self.info = getattr(obj,'info',{}) <ide> return <ide> def __add__(self, other): <del> result = N.ndarray.__add__(self, other) <add> result = np.ndarray.__add__(self, other) <ide> result.info.update({'added':result.info.pop('added',0)+1}) <ide> return result <ide> <ide> def _get_series(self): <ide> <ide> msubarray = MSubArray <ide> <del>class MMatrix(MaskedArray, N.matrix,): <add>class MMatrix(MaskedArray, np.matrix,): <ide> def __new__(cls, data, mask=nomask): <del> mat = N.matrix(data) <add> mat = np.matrix(data) <ide> _data = MaskedArray.__new__(cls, data=mat, mask=mask) <ide> return _data <ide> def __array_finalize__(self,obj): <del> N.matrix.__array_finalize__(self, obj) <add> np.matrix.__array_finalize__(self, obj) <ide> MaskedArray.__array_finalize__(self,obj) <ide> return <ide> def _get_series(self): <ide> class TestSubclassing(TestCase): <ide> <ide> def test_data_subclassing(self): <ide> "Tests whether the subclass is kept." <del> x = N.arange(5) <add> x = np.arange(5) <ide> m = [0,0,1,0,0] <ide> xsub = SubArray(x) <ide> xmsub = masked_array(xsub, mask=m) <ide> def test_data_subclassing(self): <ide> <ide> def test_maskedarray_subclassing(self): <ide> "Tests subclassing MaskedArray" <del> x = N.arange(5) <add> x = np.arange(5) <ide> mx = mmatrix(x,mask=[0,1,0,0,0]) <del> assert isinstance(mx._data, N.matrix) <add> assert isinstance(mx._data, np.matrix) <ide> "Tests masked_unary_operation" <ide> assert isinstance(add(mx,mx), mmatrix) <ide> assert isinstance(add(mx,x), mmatrix) <ide> assert_equal(add(mx,x), mx+x) <del> assert isinstance(add(mx,mx)._data, N.matrix) <add> assert isinstance(add(mx,mx)._data, np.matrix) <ide> assert isinstance(add.outer(mx,mx), mmatrix) <ide> "Tests masked_binary_operation" <ide> assert isinstance(hypot(mx,mx), mmatrix) <ide> def test_attributepropagation(self): <ide> <ide> def test_subclasspreservation(self): <ide> "Checks that masked_array(...,subok=True) preserves the class." <del> x = N.arange(5) <add> x = np.arange(5) <ide> m = [0,0,1,0,0] <ide> xinfo = [(i,j) for (i,j) in zip(x,m)] <ide> xsub = MSubArray(x, mask=m, info={'xsub':xinfo}) <ide><path>numpy/testing/tests/test_utils.py <del>import numpy as N <add>import numpy as np <ide> from numpy.testing import * <ide> import unittest <ide> <ide> def _test_not_equal(self, a, b): <ide> <ide> def test_array_rank1_eq(self): <ide> """Test two equal array of rank 1 are found equal.""" <del> a = N.array([1, 2]) <del> b = N.array([1, 2]) <add> a = np.array([1, 2]) <add> b = np.array([1, 2]) <ide> <ide> self._test_equal(a, b) <ide> <ide> def test_array_rank1_noteq(self): <ide> """Test two different array of rank 1 are found not equal.""" <del> a = N.array([1, 2]) <del> b = N.array([2, 2]) <add> a = np.array([1, 2]) <add> b = np.array([2, 2]) <ide> <ide> self._test_not_equal(a, b) <ide> <ide> def test_array_rank2_eq(self): <ide> """Test two equal array of rank 2 are found equal.""" <del> a = N.array([[1, 2], [3, 4]]) <del> b = N.array([[1, 2], [3, 4]]) <add> a = np.array([[1, 2], [3, 4]]) <add> b = np.array([[1, 2], [3, 4]]) <ide> <ide> self._test_equal(a, b) <ide> <ide> def test_array_diffshape(self): <ide> """Test two arrays with different shapes are found not equal.""" <del> a = N.array([1, 2]) <del> b = N.array([[1, 2], [1, 2]]) <add> a = np.array([1, 2]) <add> b = np.array([[1, 2], [1, 2]]) <ide> <ide> self._test_not_equal(a, b) <ide> <ide> def setUp(self): <ide> def test_generic_rank1(self): <ide> """Test rank 1 array for all dtypes.""" <ide> def foo(t): <del> a = N.empty(2, t) <add> a = np.empty(2, t) <ide> a.fill(1) <ide> b = a.copy() <ide> c = a.copy() <ide> def foo(t): <ide> def test_generic_rank3(self): <ide> """Test rank 3 array for all dtypes.""" <ide> def foo(t): <del> a = N.empty((4, 2, 3), t) <add> a = np.empty((4, 2, 3), t) <ide> a.fill(1) <ide> b = a.copy() <ide> c = a.copy() <ide> def foo(t): <ide> <ide> def test_nan_array(self): <ide> """Test arrays with nan values in them.""" <del> a = N.array([1, 2, N.nan]) <del> b = N.array([1, 2, N.nan]) <add> a = np.array([1, 2, np.nan]) <add> b = np.array([1, 2, np.nan]) <ide> <ide> self._test_equal(a, b) <ide> <del> c = N.array([1, 2, 3]) <add> c = np.array([1, 2, 3]) <ide> self._test_not_equal(c, b) <ide> <ide> def test_string_arrays(self): <ide> """Test two arrays with different shapes are found not equal.""" <del> a = N.array(['floupi', 'floupa']) <del> b = N.array(['floupi', 'floupa']) <add> a = np.array(['floupi', 'floupa']) <add> b = np.array(['floupi', 'floupa']) <ide> <ide> self._test_equal(a, b) <ide> <del> c = N.array(['floupipi', 'floupa']) <add> c = np.array(['floupipi', 'floupa']) <ide> <ide> self._test_not_equal(c, b) <ide> <ide> def test_recarrays(self): <ide> """Test record arrays.""" <del> a = N.empty(2, [('floupi', N.float), ('floupa', N.float)]) <add> a = np.empty(2, [('floupi', np.float), ('floupa', np.float)]) <ide> a['floupi'] = [1, 2] <ide> a['floupa'] = [1, 2] <ide> b = a.copy() <ide> <ide> self._test_equal(a, b) <ide> <del> c = N.empty(2, [('floupipi', N.float), ('floupa', N.float)]) <add> c = np.empty(2, [('floupipi', np.float), ('floupa', np.float)]) <ide> c['floupipi'] = a['floupi'].copy() <ide> c['floupa'] = a['floupa'].copy() <ide>
2
Text
Text
fix active record changelog [ci skip]
2d7ff70b3f0ae7e25f766c7701eaebdaa3f2766a
<ide><path>activerecord/CHANGELOG.md <ide> <ide> Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped. <ide> <del> In order to fix this we are storing the advisory lock on a new connection with the connection specification name `AdisoryLockBase`. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this. <add> In order to fix this we are storing the advisory lock on a new connection with the connection specification name `AdvisoryLockBase`. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this. <ide> <ide> *Eileen M. Uchitelle*, *John Crepezzi* <ide> <ide> * Deprecate `#default_hash` and it's alias `#[]` on database configurations <ide> <ide> Applications should use `configs_for`. `#default_hash` and `#[]` will be removed in 6.2. <del>======= <add> <add> *Eileen M. Uchitelle*, *John Crepezzi* <ide> <ide> * Add scale support to `ActiveRecord::Validations::NumericalityValidator`. <ide>
1
PHP
PHP
fix a bug with string via in queued notifications
84b438c432531dc41d4d71f18d396636addebedb
<ide><path>src/Illuminate/Notifications/NotificationSender.php <ide> protected function queueNotification($notifiables, $notification) <ide> foreach ($notifiables as $notifiable) { <ide> $notificationId = Str::uuid()->toString(); <ide> <del> foreach ($original->via($notifiable) as $channel) { <add> foreach ((array) $original->via($notifiable) as $channel) { <ide> $notification = clone $original; <ide> <ide> $notification->id = $notificationId; <ide><path>tests/Notifications/NotificationSenderTest.php <add><?php <add> <add>namespace Illuminate\Tests\Notifications; <add> <add>use Illuminate\Bus\Queueable; <add>use Mockery as m; <add>use PHPUnit\Framework\TestCase; <add>use Illuminate\Notifications\Notifiable; <add>use Illuminate\Notifications\Notification; <add>use Illuminate\Contracts\Queue\ShouldQueue; <add>use Illuminate\Notifications\ChannelManager; <add>use Illuminate\Notifications\NotificationSender; <add>use Illuminate\Contracts\Bus\Dispatcher as BusDispatcher; <add>use Illuminate\Contracts\Events\Dispatcher as EventDispatcher; <add> <add>class NotificationSenderTest extends TestCase <add>{ <add> protected function tearDown(): void <add> { <add> parent::tearDown(); <add> <add> m::close(); <add> } <add> <add> public function test_it_can_send_queued_notifications_with_a_string_via() <add> { <add> $notifiable = m::mock(Notifiable::class); <add> $manager = m::mock(ChannelManager::class); <add> $bus = m::mock(BusDispatcher::class); <add> $bus->shouldReceive('dispatch'); <add> $events = m::mock(EventDispatcher::class); <add> <add> $sender = new NotificationSender($manager, $bus, $events); <add> <add> $sender->send($notifiable, new DummyQueuedNotificationWithStringVia()); <add> } <add>} <add> <add>class DummyQueuedNotificationWithStringVia extends Notification implements ShouldQueue <add>{ <add> use Queueable; <add> <add> /** <add> * Get the notification channels. <add> * <add> * @param mixed $notifiable <add> * @return array|string <add> * @return array|string <add> */ <add> public function via($notifiable) <add> { <add> return 'mail'; <add> } <add>}
2
Java
Java
check original beanclass in #isfactorybean calls
f3f73f0e32dc54c463831668d4700f022bc8461f
<ide><path>org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java <ide> /* <del> * Copyright 2002-2011 the original author or authors. <add> * Copyright 2002-2012 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Clas <ide> * @param mbd the corresponding bean definition <ide> */ <ide> protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) { <del> Class<?> beanClass = predictBeanType(beanName, mbd, FactoryBean.class); <del> return (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)); <add> Class<?> predictedType = predictBeanType(beanName, mbd, FactoryBean.class); <add> return (predictedType != null && FactoryBean.class.isAssignableFrom(predictedType)) || <add> (mbd.hasBeanClass() && FactoryBean.class.isAssignableFrom(mbd.getBeanClass())); <ide> } <ide> <ide> /** <ide><path>org.springframework.beans/src/test/java/org/springframework/beans/factory/support/Spr8954Tests.java <add>/* <add> * Copyright 2002-2012 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> * 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> <add>package org.springframework.beans.factory.support; <add> <add>import static org.hamcrest.CoreMatchers.*; <add>import static org.junit.Assert.*; <add> <add>import java.util.Map; <add> <add>import org.junit.Test; <add>import org.springframework.beans.factory.FactoryBean; <add>import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; <add>import org.springframework.beans.factory.support.DefaultListableBeanFactory; <add>import org.springframework.beans.factory.support.RootBeanDefinition; <add> <add>/** <add> * Unit tests for SPR-8954, in which a custom {@link InstantiationAwareBeanPostProcessor} <add> * forces the predicted type of a FactoryBean, effectively preventing retrieval of the <add> * bean from calls to #getBeansOfType(FactoryBean.class). The implementation of <add> * {@link AbstractBeanFactory#isFactoryBean(String, RootBeanDefinition)} now ensures <add> * that not only the predicted bean type is considered, but also the original bean <add> * definition's beanClass. <add> * <add> * @author Chris Beams <add> * @author Oliver Gierke <add> */ <add>public class Spr8954Tests { <add> <add> @Test <add> public void repro() { <add> DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); <add> bf.registerBeanDefinition("foo", new RootBeanDefinition(FooFactoryBean.class)); <add> bf.addBeanPostProcessor(new PredictingBPP()); <add> <add> assertThat(bf.getBean("foo"), instanceOf(Foo.class)); <add> assertThat(bf.getBean("&foo"), instanceOf(FooFactoryBean.class)); <add> <add> @SuppressWarnings("rawtypes") <add> Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class); <add> assertThat(1, equalTo(fbBeans.size())); <add> assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); <add> <add> Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class); <add> assertThat(1, equalTo(aiBeans.size())); <add> assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); <add> } <add> <add> static class FooFactoryBean implements FactoryBean<Foo>, AnInterface { <add> <add> public Foo getObject() throws Exception { <add> return new Foo(); <add> } <add> <add> public Class<?> getObjectType() { <add> return Foo.class; <add> } <add> <add> public boolean isSingleton() { <add> return true; <add> } <add> } <add> <add> interface AnInterface { <add> } <add> <add> static class Foo { <add> } <add> <add> interface PredictedType { <add> <add> } <add> <add> static class PredictingBPP extends InstantiationAwareBeanPostProcessorAdapter { <add> <add> @Override <add> public Class<?> predictBeanType(Class<?> beanClass, String beanName) { <add> return FactoryBean.class.isAssignableFrom(beanClass) ? <add> PredictedType.class : <add> super.predictBeanType(beanClass, beanName); <add> } <add> } <add>}
2
PHP
PHP
keys method
1e2dbe02b40aaf94c2dd776f2530213ab2084ccc
<ide><path>src/Illuminate/Http/Concerns/InteractsWithInput.php <ide> public function all($keys = null) <ide> return $results; <ide> } <ide> <add> /** <add> * Get the keys for all input and files for the request. <add> * <add> * @return array <add> */ <add> public function keys() <add> { <add> return array_merge(array_keys($this->input()), $this->files->keys()); <add> } <add> <ide> /** <ide> * Retrieve an input item from the request. <ide> * <ide><path>tests/Http/HttpRequestTest.php <ide> public function testAllMethod() <ide> $this->assertEquals(['developer' => ['name' => 'Taylor', 'age' => null]], $request->all()); <ide> } <ide> <add> public function testKeysMethod() <add> { <add> $request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => null]); <add> $this->assertEquals(['name', 'age'], $request->keys()); <add> <add> $files = [ <add> 'foo' => [ <add> 'size' => 500, <add> 'name' => 'foo.jpg', <add> 'tmp_name' => __FILE__, <add> 'type' => 'blah', <add> 'error' => null, <add> ], <add> ]; <add> $request = Request::create('/', 'GET', [], [], $files); <add> $this->assertEquals(['foo'], $request->keys()); <add> <add> $request = Request::create('/', 'GET', ['name' => 'Taylor'], [], $files); <add> $this->assertEquals(['name', 'foo'], $request->keys()); <add> } <add> <ide> public function testOnlyMethod() <ide> { <ide> $request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => null]);
2
Python
Python
fix various typos in error messages
94373fefce87226db29f8270eca75408aa085996
<ide><path>keras/engine/input_layer.py <ide> def __init__(self, <ide> batch_size = batch_input_shape[0] <ide> input_shape = batch_input_shape[1:] <ide> if kwargs: <del> raise ValueError('Unrecognized keyword arguments:', kwargs.keys()) <add> raise ValueError(f'Unrecognized keyword arguments: {list(kwargs.keys())}') <ide> <ide> if sparse and ragged: <ide> raise ValueError( <ide> def __init__(self, <ide> else: <ide> dtype = backend.dtype(input_tensor) <ide> elif input_tensor is not None and input_tensor.dtype != dtype: <del> raise ValueError('`input_tensor.dtype` differs from `dtype`: %s vs. %s' % <del> (input_tensor.dtype, dtype)) <add> raise ValueError( <add> '`input_tensor.dtype` differs from `dtype`. Received: ' <add> f'input_tensor.dtype={input_tensor.dtype} ' <add> f'but expected dtype={dtype}') <ide> super(InputLayer, self).__init__(dtype=dtype, name=name) <ide> self.built = True <ide> self.sparse = True if sparse else False <ide> def __init__(self, <ide> if not tf_utils.is_symbolic_tensor(input_tensor): <ide> raise ValueError('You should not pass an EagerTensor to `Input`. ' <ide> 'For example, instead of creating an ' <del> 'InputLayer, you should instantiate your model and ' <del> 'directly call it on your input.') <add> '`InputLayer`, you should instantiate your model ' <add> 'and directly call it on your input.') <ide> self.is_placeholder = False <ide> try: <ide> self._batch_input_shape = tuple(input_tensor.shape.as_list()) <ide> def Input( # pylint: disable=invalid-name <ide> """ <ide> if sparse and ragged: <ide> raise ValueError( <del> 'Cannot set both sparse and ragged to True in a Keras input.') <add> 'Cannot set both `sparse` and `ragged` to `True` in a Keras `Input`.') <ide> <ide> input_layer_config = {'name': name, 'dtype': dtype, 'sparse': sparse, <ide> 'ragged': ragged, 'input_tensor': tensor, <ide> def Input( # pylint: disable=invalid-name <ide> 'to Input, not both at the same time.') <ide> if (batch_input_shape is None and shape is None and tensor is None <ide> and type_spec is None): <del> raise ValueError('Please provide to Input a `shape`' <del> ' or a `tensor` or a `type_spec` argument. Note that ' <add> raise ValueError('Please provide to Input a `shape` ' <add> 'or a `tensor` or a `type_spec` argument. Note that ' <ide> '`shape` does not include the batch ' <ide> 'dimension.') <ide> if kwargs: <del> raise ValueError('Unrecognized keyword arguments:', kwargs.keys()) <add> raise ValueError(f'Unrecognized keyword arguments: {list(kwargs.keys())}') <ide> <ide> if batch_input_shape: <ide> shape = batch_input_shape[1:] <ide><path>keras/engine/input_spec.py <ide> def __init__(self, <ide> axes = axes or {} <ide> self.axes = {int(k): axes[k] for k in axes} <ide> except (ValueError, TypeError): <del> raise TypeError('The keys in axes must be integers.') <add> raise TypeError('Argument `axes` must be a dict with integer keys. ' <add> f'Received: axes={axes}') <ide> <ide> if self.axes and (self.ndim is not None or self.max_ndim is not None): <ide> max_dim = (self.ndim if self.ndim else self.max_ndim) - 1 <ide><path>keras/engine/input_spec_test.py <ide> def test_axes_initialization(self): <ide> input_spec.InputSpec(shape=[1, None, 2, 3], axes={3: 5, '2': 2}) <ide> with self.assertRaisesRegex(ValueError, 'Axis 4 is greater than'): <ide> input_spec.InputSpec(shape=[1, None, 2, 3], axes={4: 5}) <del> with self.assertRaisesRegex(TypeError, 'keys in axes must be integers'): <add> with self.assertRaisesRegex(TypeError, 'Argument `axes` must be a dict'): <ide> input_spec.InputSpec(shape=[1, None, 2, 3], axes={'string': 5}) <ide> <ide> <ide><path>keras/engine/sequential.py <ide> def call(self, inputs, training=None, mask=None): # pylint: disable=redefined-o <ide> # invalid use case of Sequential, but we tolerate it for backwards <ide> # compatibility. <ide> self._use_legacy_deferred_behavior = True <del> self._build_input_shape = tf.nest.map_structure(_get_shape_tuple, inputs) <add> self._build_input_shape = tf.nest.map_structure( <add> _get_shape_tuple, inputs) <ide> if tf.__internal__.tf2.enabled(): <ide> logging.warning('Layers in a Sequential model should only have a ' <del> 'single input tensor, but we receive a %s input: %s' <del> '\nConsider rewriting this model with the Functional ' <del> 'API.' % (type(inputs), inputs)) <add> f'single input tensor. Received: inputs={inputs}. ' <add> 'Consider rewriting this model with the Functional ' <add> 'API.') <ide> else: <ide> self._build_graph_network_for_inferred_shape(inputs.shape, inputs.dtype) <ide> <ide><path>keras/engine/training.py <ide> def build(self, input_shape): <ide> return <ide> <ide> if input_shape is None: <del> raise ValueError('Input shape must be defined when calling `build` on a ' <del> 'model subclass network.') <add> raise ValueError('Input shape must be defined when calling `build()` on ' <add> 'a `Model` subclass.') <ide> valid_types = (tuple, list, tf.TensorShape, dict) <ide> if not isinstance(input_shape, valid_types): <ide> raise ValueError('Specified input shape is not one of the valid types. ' <ide> def evaluate(self, <ide> _disallow_inside_tf_function('evaluate') <ide> use_cached_eval_dataset = kwargs.pop('_use_cached_eval_dataset', False) <ide> if kwargs: <del> raise TypeError(f'Invalid keyword arguments: {(kwargs,)}') <add> raise TypeError(f'Invalid keyword arguments: {list(kwargs.keys())}') <ide> <ide> if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access <ide> self._cluster_coordinator = tf.distribute.experimental.coordinator.ClusterCoordinator(
5
Java
Java
initialize js executor and context at loadapp time
530ee3eeac40d43c6517cc47dfa8745222cf5956
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> public class ReactInstanceManager { <ide> private @Nullable DefaultHardwareBackBtnHandler mDefaultBackButtonImpl; <ide> private String mSourceUrl; <ide> private @Nullable Activity mCurrentActivity; <add> private volatile boolean mHasStartedCreatingInitialContext = false; <ide> <ide> private final ReactInstanceDevCommandsHandler mDevInterface = <ide> new ReactInstanceDevCommandsHandler() { <ide> public void setJSBundleFile(String jsBundleFile) { <ide> /** <ide> * Trigger react context initialization asynchronously in a background async task. This enables <ide> * applications to pre-load the application JS, and execute global code before <del> * {@link ReactRootView} is available and measured. <add> * {@link ReactRootView} is available and measured. This should only be called the first time the <add> * application is set up, which is enforced to keep developers from accidentally creating their <add> * application multiple times without realizing it. <ide> * <ide> * Called from UI thread. <ide> */ <ide> public void createReactContextInBackground() { <add> Assertions.assertCondition( <add> !mHasStartedCreatingInitialContext, <add> "createReactContextInBackground should only be called when creating the react " + <add> "application for the first time. When reloading JS, e.g. from a new file, explicitly" + <add> "use recreateReactContextInBackground"); <add> <add> mHasStartedCreatingInitialContext = true; <add> recreateReactContextInBackgroundInner(); <add> } <add> <add> /** <add> * Recreate the react application and context. This should be called if configuration has <add> * changed or the developer has requested the app to be reloaded. It should only be called after <add> * an initial call to createReactContextInBackground. <add> * <add> * Called from UI thread. <add> */ <add> public void recreateReactContextInBackground() { <add> Assertions.assertCondition( <add> mHasStartedCreatingInitialContext, <add> "recreateReactContextInBackground should only be called after the initial " + <add> "createReactContextInBackground call."); <add> recreateReactContextInBackgroundInner(); <add> } <add> <add> private void recreateReactContextInBackgroundInner() { <add> UiThreadUtil.assertOnUiThread(); <add> <ide> if (mUseDeveloperSupport && mJSMainModuleName != null) { <ide> if (mDevSupportManager.hasUpToDateJSBundleInCache()) { <ide> // If there is a up-to-date bundle downloaded from server, always use that <ide> private void recreateReactContextInBackgroundFromBundleFile() { <ide> JSBundleLoader.createFileLoader(mApplicationContext, mJSBundleFile)); <ide> } <ide> <add> /** <add> * @return whether createReactContextInBackground has been called. Will return false after <add> * onDestroy until a new initial context has been created. <add> */ <add> public boolean hasStartedCreatingInitialContext() { <add> return mHasStartedCreatingInitialContext; <add> } <add> <ide> /** <ide> * This method will give JS the opportunity to consume the back button event. If JS does not <ide> * consume the event, mDefaultBackButtonImpl will be invoked at the end of the round trip to JS. <ide> public void onDestroy() { <ide> <ide> if (mCurrentReactContext != null) { <ide> mCurrentReactContext.onDestroy(); <add> mCurrentReactContext = null; <add> mHasStartedCreatingInitialContext = false; <ide> } <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java <ide> public void startReactApplication( <ide> ReactInstanceManager reactInstanceManager, <ide> String moduleName, <ide> @Nullable Bundle launchOptions) { <add> UiThreadUtil.assertOnUiThread(); <add> <ide> // TODO(6788889): Use POJO instead of bundle here, apparently we can't just use WritableMap <ide> // here as it may be deallocated in native after passing via JNI bridge, but we want to reuse <ide> // it in the case of re-creating the catalyst instance <ide> public void startReactApplication( <ide> mJSModuleName = moduleName; <ide> mLaunchOptions = launchOptions; <ide> <add> if (!mReactInstanceManager.hasStartedCreatingInitialContext()) { <add> mReactInstanceManager.createReactContextInBackground(); <add> } <add> <ide> // We need to wait for the initial onMeasure, if this view has not yet been measured, we set <ide> // mAttachScheduled flag, which will make this view startReactApplication itself to instance <ide> // manager once onMeasure is called.
2
PHP
PHP
add wherenotnull to joinclause
2719387da1caec95d9d537cbcfd9278597df25a0
<ide><path>src/Illuminate/Database/Query/JoinClause.php <ide> public function whereNull($column, $boolean = 'and') <ide> return $this->on($column, 'is', new Expression('null'), $boolean, false); <ide> } <ide> <add> /** <add> * Add an "on where is not null" clause to the join <add> * <add> * @param string $column <add> * @param string $boolean <add> * @return \Illuminate\Database\Query\JoinClause <add> */ <add> public function whereNotNull($column, $boolean = 'and') <add> { <add> return $this->on($column, 'is', new Expression('not null'), $boolean, false); <add> } <add> <ide> } <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testComplexJoin() <ide> $this->assertEquals(array('foo', 'bar'), $builder->getBindings()); <ide> } <ide> <add> <ide> public function testJoinWhereNull() <ide> { <ide> $builder = $this->getBuilder(); <ide> public function testJoinWhereNull() <ide> $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" and "contacts"."deleted_at" is null', $builder->toSql()); <ide> } <ide> <add> <add> public function testJoinWhereNotNull() <add> { <add> $builder = $this->getBuilder(); <add> $builder->select('*')->from('users')->join('contacts', function($j) <add> { <add> $j->on('users.id', '=', 'contacts.id')->whereNotNull('contacts.deleted_at'); <add> }); <add> $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" and "contacts"."deleted_at" is not null', $builder->toSql()); <add> } <add> <add> <ide> public function testRawExpressionsInSelect() <ide> { <ide> $builder = $this->getBuilder();
2
Python
Python
add comment clarifying spatial squeeze.
9c17823e147ff2893427b47cb57d171da9350d20
<ide><path>slim/nets/resnet_v1.py <ide> def resnet_v1(inputs, <ide> max-pooling, if False excludes it. <ide> spatial_squeeze: if True, logits is of shape [B, C], if false logits is <ide> of shape [B, 1, 1, C], where B is batch_size and C is number of classes. <add> To use this parameter, the input images must be smaller than 300x300 <add> pixels, in which case the output logit layer does not contain spatial <add> information and can be removed. <ide> reuse: whether or not the network and its variables should be reused. To be <ide> able to reuse 'scope' must be given. <ide> scope: Optional variable_scope. <ide> def resnet_v1(inputs, <ide> if num_classes is not None: <ide> net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, <ide> normalizer_fn=None, scope='logits') <del> if spatial_squeeze: <del> logits = tf.squeeze(net, [1, 2], name='SpatialSqueeze') <del> else: <del> logits = net <add> if spatial_squeeze: <add> net = tf.squeeze(net, [1, 2], name='SpatialSqueeze') <ide> # Convert end_points_collection into a dictionary of end_points. <ide> end_points = slim.utils.convert_collection_to_dict( <ide> end_points_collection) <ide> if num_classes is not None: <del> end_points['predictions'] = slim.softmax(logits, scope='predictions') <del> return logits, end_points <add> end_points['predictions'] = slim.softmax(net, scope='predictions') <add> return net, end_points <ide> resnet_v1.default_image_size = 224 <ide> <ide> <ide><path>slim/nets/resnet_v2.py <ide> def resnet_v2(inputs, <ide> results of an activation-less convolution. <ide> spatial_squeeze: if True, logits is of shape [B, C], if false logits is <ide> of shape [B, 1, 1, C], where B is batch_size and C is number of classes. <add> To use this parameter, the input images must be smaller than 300x300 <add> pixels, in which case the output logit layer does not contain spatial <add> information and can be removed. <ide> reuse: whether or not the network and its variables should be reused. To be <ide> able to reuse 'scope' must be given. <ide> scope: Optional variable_scope. <ide> def resnet_v2(inputs, <ide> if num_classes is not None: <ide> net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, <ide> normalizer_fn=None, scope='logits') <del> if spatial_squeeze: <del> logits = tf.squeeze(net, [1, 2], name='SpatialSqueeze') <del> else: <del> logits = net <add> if spatial_squeeze: <add> net = tf.squeeze(net, [1, 2], name='SpatialSqueeze') <ide> # Convert end_points_collection into a dictionary of end_points. <ide> end_points = slim.utils.convert_collection_to_dict( <ide> end_points_collection) <ide> if num_classes is not None: <del> end_points['predictions'] = slim.softmax(logits, scope='predictions') <del> return logits, end_points <add> end_points['predictions'] = slim.softmax(net, scope='predictions') <add> return net, end_points <ide> resnet_v2.default_image_size = 224 <ide> <ide>
2
Ruby
Ruby
use argumenterror exception
c34ed98eaf64f0dafcbbba2980de09e1eaa97029
<ide><path>Library/Homebrew/dependency_collector.rb <ide> def parse_symbol_spec(spec, tags) <ide> when :ld64 then LD64Dependency.new if MacOS.version < :leopard <ide> when :ant then ant_dep(spec, tags) <ide> else <del> raise "Unsupported special dependency #{spec.inspect}" <add> raise ArgumentError, "Unsupported special dependency #{spec.inspect}" <ide> end <ide> end <ide>
1
Text
Text
add more details to tests
7a8a3a30d7e42984b0c8eb2667d993496b8ec980
<ide><path>docs/Formula-Cookbook.md <ide> function. The environment variable `HOME` is set to [`testpath`](https://rubydoc <ide> <ide> We want tests that don't require any user input and test the basic functionality of the application. For example `foo build-foo input.foo` is a good test and (despite their widespread use) `foo --version` and `foo --help` are bad tests. However, a bad test is better than no test at all. <ide> <del>See [`cmake`](https://github.com/Homebrew/homebrew-core/blob/master/Formula/cmake.rb) for an example of a formula with a good test. The formula writes a basic `CMakeLists.txt` file into the test directory then calls CMake to generate Makefiles. This test checks that CMake doesn't e.g. segfault during basic operation. Another good example is [`tinyxml2`](https://github.com/Homebrew/homebrew-core/blob/master/Formula/tinyxml2.rb), which writes a small C++ source file into the test directory, compiles and links it against the tinyxml2 library and finally checks that the resulting program runs successfully. <add>See [`cmake`](https://github.com/Homebrew/homebrew-core/blob/master/Formula/cmake.rb) for an example of a formula with a good test. The formula writes a basic `CMakeLists.txt` file into the test directory then calls CMake to generate Makefiles. This test checks that CMake doesn't e.g. segfault during basic operation. <add> <add>You can check that the output is as expected with `assert_equal` or `assert_match` on the output of shell_output such as in this example from the [envv formula](https://github.com/Homebrew/homebrew-core/blob/master/Formula/envv.rb): <add> <add>```ruby <add>assert_equal "mylist=A:C; export mylist", shell_output("#{bin}/envv del mylist B").strip <add>``` <add> <add>You can also check that an output file was created: <add> <add>```ruby <add>assert_predicate testpath/"output.txt", :exist? <add>``` <add> <add>Some advice for specific cases: <add>* If the formula is a library, compile and run some simple code that links against it. It could be taken from upstream's documentation / source examples. <add>A good example is [`tinyxml2`](https://github.com/Homebrew/homebrew-core/blob/master/Formula/tinyxml2.rb), which writes a small C++ source file into the test directory, compiles and links it against the tinyxml2 library and finally checks that the resulting program runs successfully. <add>* If the formula is for a GUI program, try to find some function that runs as command-line only, like a format conversion, reading or displaying a config file, etc. <add>* If the software cannot function without credentials or requires a virtual machine, docker instance, etc. to run, a test could be to try to connect with invalid credentials (or without credentials) and confirm that it fails as expected. <ide> <ide> ### Manuals <ide>
1
Ruby
Ruby
use curl options where appropriate
f88966a8a53198106f01475b7c09ef08ef00e0e9
<ide><path>Library/Homebrew/api.rb <ide> def fetch(endpoint, json: true) <ide> return cache[endpoint] if cache.present? && cache.key?(endpoint) <ide> <ide> api_url = "#{API_DOMAIN}/#{endpoint}" <del> output = Utils::Curl.curl_output("--fail", "--max-time", "5", api_url) <add> output = Utils::Curl.curl_output("--fail", api_url, max_time: 5) <ide> raise ArgumentError, "No file found at #{Tty.underline}#{api_url}#{Tty.reset}" unless output.success? <ide> <ide> cache[endpoint] = if json <ide><path>Library/Homebrew/download_strategy.rb <ide> def curl_output(*args, **options) <ide> end <ide> <ide> def curl(*args, **options) <del> args << "--connect-timeout" << "15" unless mirrors.empty? <add> options[:connect_timeout] = 15 unless mirrors.empty? <ide> super(*_curl_args, *args, **_curl_opts, **command_output_options, **options) <ide> end <ide> end <ide><path>Library/Homebrew/livecheck/strategy.rb <ide> module Strategy <ide> DEFAULT_CURL_ARGS = [ <ide> # Follow redirections to handle mirrors, relocations, etc. <ide> "--location", <del> "--connect-timeout", CURL_CONNECT_TIMEOUT, <del> "--max-time", CURL_MAX_TIME <ide> ].freeze <ide> <ide> # `curl` arguments used in `Strategy#page_headers` method. <ide> module Strategy <ide> <ide> # Baseline `curl` options used in {Strategy} methods. <ide> DEFAULT_CURL_OPTIONS = { <del> print_stdout: false, <del> print_stderr: false, <del> debug: false, <del> verbose: false, <del> timeout: CURL_PROCESS_TIMEOUT, <del> retries: 0, <add> print_stdout: false, <add> print_stderr: false, <add> debug: false, <add> verbose: false, <add> timeout: CURL_PROCESS_TIMEOUT, <add> connect_timeout: CURL_CONNECT_TIMEOUT, <add> max_time: CURL_MAX_TIME, <add> retries: 0, <ide> }.freeze <ide> <ide> # HTTP response head(s) and body are typically separated by a double <ide><path>Library/Homebrew/utils/curl.rb <ide> def curl_check_http_content(url, url_type, specs: {}, user_agents: [:default], <ide> if url != secure_url <ide> user_agents.each do |user_agent| <ide> secure_details = begin <del> curl_http_content_headers_and_checksum(secure_url, specs: specs, hash_needed: true, <del> user_agent: user_agent, use_homebrew_curl: use_homebrew_curl) <add> curl_http_content_headers_and_checksum( <add> secure_url, <add> specs: specs, <add> hash_needed: true, <add> use_homebrew_curl: use_homebrew_curl, <add> user_agent: user_agent, <add> ) <ide> rescue Timeout::Error <ide> next <ide> end <ide> def curl_check_http_content(url, url_type, specs: {}, user_agents: [:default], <ide> details = nil <ide> user_agents.each do |user_agent| <ide> details = <del> curl_http_content_headers_and_checksum(url, specs: specs, hash_needed: hash_needed, <del> user_agent: user_agent, use_homebrew_curl: use_homebrew_curl) <add> curl_http_content_headers_and_checksum( <add> url, <add> specs: specs, <add> hash_needed: hash_needed, <add> use_homebrew_curl: use_homebrew_curl, <add> user_agent: user_agent, <add> ) <ide> break if http_status_ok?(details[:status]) <ide> end <ide> <ide> def curl_check_http_content(url, url_type, specs: {}, user_agents: [:default], <ide> "The #{url_type} #{url} may be able to use HTTPS rather than HTTP. Please verify it in a browser." <ide> end <ide> <del> def curl_http_content_headers_and_checksum(url, specs: {}, hash_needed: false, <del> user_agent: :default, use_homebrew_curl: false) <add> def curl_http_content_headers_and_checksum( <add> url, specs: {}, hash_needed: false, <add> use_homebrew_curl: false, user_agent: :default <add> ) <ide> file = Tempfile.new.tap(&:close) <ide> <ide> specs = specs.flat_map { |option, argument| ["--#{option.to_s.tr("_", "-")}", argument] } <del> max_time = hash_needed ? "600" : "25" <add> max_time = hash_needed ? 600 : 25 <ide> output, _, status = curl_output( <del> *specs, "--dump-header", "-", "--output", file.path, "--location", <del> "--connect-timeout", "15", "--max-time", max_time, "--retry-max-time", max_time, url, <del> user_agent: user_agent, use_homebrew_curl: use_homebrew_curl <add> *specs, "--dump-header", "-", "--output", file.path, "--location", url, <add> use_homebrew_curl: use_homebrew_curl, <add> connect_timeout: 15, <add> max_time: max_time, <add> retry_max_time: max_time, <add> user_agent: user_agent <ide> ) <ide> <ide> status_code = :unknown
4
PHP
PHP
add handle method from lumen into crawler trait
ed4ccf6b3932d3a0cadce79379d71104bc4c4c2b
<ide><path>src/Illuminate/Foundation/Testing/CrawlerTrait.php <ide> public function delete($uri, array $data = [], array $headers = []) <ide> return $this; <ide> } <ide> <add> /** <add> * Send the given request through the application. <add> * <add> * @param \Illuminate\Http\Request $request <add> * @return $this <add> */ <add> public function handle(Request $request) <add> { <add> $this->currentUri = $request->fullUrl(); <add> <add> $this->response = $this->app->prepareResponse($this->app->handle($request)); <add> <add> return $this; <add> } <add> <ide> /** <ide> * Make a request to the application and create a Crawler instance. <ide> *
1
Python
Python
fix circular import in transformers.pipelines
d0c9fe277a012d4ba8b3133ae1b39ff92c9a6dc7
<ide><path>transformers/pipelines.py <ide> import numpy as np <ide> import six <ide> <del>from transformers import ( <del> ALL_PRETRAINED_CONFIG_ARCHIVE_MAP, <del> AutoConfig, <del> AutoTokenizer, <del> BasicTokenizer, <del> ModelCard, <del> PretrainedConfig, <del> PreTrainedTokenizer, <del> SquadExample, <del> is_tf_available, <del> is_torch_available, <del> squad_convert_examples_to_features, <del>) <add>from .configuration_auto import ALL_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoConfig <add>from .configuration_utils import PretrainedConfig <add>from .data import SquadExample, squad_convert_examples_to_features <add>from .file_utils import is_tf_available, is_torch_available <add>from .modelcard import ModelCard <add>from .tokenization_auto import AutoTokenizer <add>from .tokenization_bert import BasicTokenizer <add>from .tokenization_utils import PreTrainedTokenizer <ide> <ide> <ide> if is_tf_available(): <ide> import tensorflow as tf <del> from transformers import ( <add> from .modeling_tf_auto import ( <ide> TFAutoModel, <ide> TFAutoModelForSequenceClassification, <ide> TFAutoModelForQuestionAnswering, <ide> <ide> if is_torch_available(): <ide> import torch <del> from transformers import ( <add> from .modeling_auto import ( <ide> AutoModel, <ide> AutoModelForSequenceClassification, <ide> AutoModelForQuestionAnswering,
1
Ruby
Ruby
create fewer relation objects
d5a8bdb2e21bc9b22241b9e2b604e88b76398339
<ide><path>activerecord/lib/active_record/relation/calculations.rb <ide> def execute_grouped_calculation(operation, column_name, distinct) #:nodoc: <ide> group_fields = group_attrs <ide> end <ide> <del> group_aliases = group_fields.map { |field| column_alias_for(field) } <add> group_aliases = group_fields.map { |field| <add> column_alias_for(field) <add> } <ide> group_columns = group_aliases.zip(group_fields).map { |aliaz,field| <ide> [aliaz, column_for(field)] <ide> } <ide> def execute_grouped_calculation(operation, column_name, distinct) #:nodoc: <ide> if operation == 'count' && column_name == :all <ide> aggregate_alias = 'count_all' <ide> else <del> aggregate_alias = column_alias_for(operation, column_name) <add> aggregate_alias = column_alias_for([operation, column_name].join(' ')) <ide> end <ide> <ide> select_values = [ <ide> def execute_grouped_calculation(operation, column_name, distinct) #:nodoc: <ide> end <ide> } <ide> <del> relation = except(:group).group(group) <add> relation = except(:group) <add> relation.group_values = group <ide> relation.select_values = select_values <ide> <ide> calculated_data = @klass.connection.select_all(relation, nil, bind_values)
1
Mixed
Ruby
define `reading_request?` in resolver
439119c8c504a7643a7e8e1f116e9100553109c7
<ide><path>activerecord/CHANGELOG.md <add>* Allow overriding `reading_request?` in `DatabaseSelector::Resolver` <add> <add> The default implementation checks if a request is a `get?` or `head?`, <add> but you can now change it to anything you like. If the method returns true, <add> `Resolver#read` gets called meaning the request could be served by the <add> replica database. <add> <add> *Alex Ghiculescu* <add> <ide> * Remove `ActiveRecord.legacy_connection_handling`. <ide> <ide> *Eileen M. Uchitelle* <ide><path>activerecord/lib/active_record/middleware/database_selector.rb <ide> def select_database(request, &blk) <ide> context = context_klass.call(request) <ide> resolver = resolver_klass.call(context, options) <ide> <del> response = if reading_request?(request) <add> response = if resolver.reading_request?(request) <ide> resolver.read(&blk) <ide> else <ide> resolver.write(&blk) <ide> def select_database(request, &blk) <ide> resolver.update_context(response) <ide> response <ide> end <del> <del> def reading_request?(request) <del> request.get? || request.head? <del> end <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/middleware/database_selector/resolver.rb <ide> def update_context(response) <ide> context.save(response) <ide> end <ide> <add> def reading_request?(request) <add> request.get? || request.head? <add> end <add> <ide> private <ide> def read_from_primary(&blk) <ide> ActiveRecord::Base.connected_to(role: ActiveRecord.writing_role, prevent_writes: true) do <ide><path>activerecord/test/cases/database_selector_test.rb <ide> def test_the_middleware_chooses_reading_role_with_GET_request <ide> <ide> assert_equal [200, {}, ["body"]], middleware.call("REQUEST_METHOD" => "GET") <ide> end <add> <add> class ReadonlyResolver < ActiveRecord::Middleware::DatabaseSelector::Resolver <add> def reading_request?(request) <add> true <add> end <add> end <add> <add> def test_the_middleware_chooses_reading_role_with_POST_request_if_resolver_tells_it_to <add> middleware = ActiveRecord::Middleware::DatabaseSelector.new(lambda { |env| <add> assert ActiveRecord::Base.connected_to?(role: :reading) <add> [200, {}, ["body"]] <add> }, ReadonlyResolver) <add> <add> cache = ActiveSupport::Cache::MemoryStore.new <add> middleware = ActionDispatch::Session::CacheStore.new(middleware, cache: cache, key: "_session_id") <add> assert_equal [200, {}, ["body"]], middleware.call("REQUEST_METHOD" => "POST") <add> end <ide> end <ide> end
4
Text
Text
fix a word to an actually used one
2bbcf1b03be25eff2d37d656e44157620e01ff52
<ide><path>docs/tutorials/essentials/part-5-async-logic.md <ide> Uncommenting that line will force the fake API to wait 2 seconds before respondi <ide> <ide> ## Loading Users <ide> <del>We're now fetching and displaying our list of posts. But, if we look at the posts, there's a problem: they all now say "Unknown User" as the authors: <add>We're now fetching and displaying our list of posts. But, if we look at the posts, there's a problem: they all now say "Unknown author" as the authors: <ide> <ide> ![Unknown post authors](/img/tutorials/essentials/posts-unknownAuthor.png) <ide>
1
PHP
PHP
return timestamps as strings
ca2f2286d31f26fbb5b23fcdd49c4e40df615b10
<ide><path>src/Http/Cookie/Cookie.php <ide> protected function getFormattedExpires() <ide> /** <ide> * Get the timestamp from the expiration time <ide> * <del> * @return int <add> * Timestamps are strings as large timestamps can overflow MAX_INT <add> * in 32bit systems. <add> * <add> * @return string|null The expiry time as a string timestamp. <ide> */ <ide> public function getExpiresTimestamp() <ide> { <ide> if (!$this->expiresAt) { <del> return 0; <add> return null; <ide> } <ide> <del> return (int)$this->expiresAt->format('U'); <add> return $this->expiresAt->format('U'); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/Cookie/CookieTest.php <ide> public function testWithExpiryChangesTimezone() <ide> <ide> $this->assertContains('expires=Wed, 15-Jun-2022', $new->toHeaderValue()); <ide> $this->assertContains('GMT', $new->toHeaderValue()); <add> $this->assertSame($date->format('U'), $new->getExpiresTimestamp()); <ide> } <ide> <ide> /**
2
Ruby
Ruby
remove unused av fixtures from ap tests
7d493a6020fd6302bbaa8b6658d7254125ab3f0e
<ide><path>actionpack/test/controller/render_test.rb <ide> def conditional_hello_with_record <ide> end <ide> end <ide> <del> def conditional_hello_with_public_header <del> if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) <del> render :action => 'hello_world' <del> end <del> end <del> <del> def conditional_hello_with_public_header_with_record <del> record = Struct.new(:updated_at, :cache_key).new(Time.now.utc.beginning_of_day, "foo/123") <del> <del> if stale?(record, :public => true) <del> render :action => 'hello_world' <del> end <del> end <del> <del> def conditional_hello_with_public_header_and_expires_at <del> expires_in 1.minute <del> if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) <del> render :action => 'hello_world' <del> end <del> end <del> <ide> def conditional_hello_with_expires_in <ide> expires_in 60.1.seconds <ide> render :action => 'hello_world' <ide> def handle_last_modified_and_etags <ide> fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ]) <ide> end <ide> <del> def heading <del> head :ok <del> end <del> <del> # :ported: <del> def double_render <del> render :text => "hello" <del> render :text => "world" <del> end <del> <del> def double_redirect <del> redirect_to :action => "double_render" <del> redirect_to :action => "double_render" <del> end <del> <del> def render_and_redirect <del> render :text => "hello" <del> redirect_to :action => "double_render" <del> end <del> <del> def render_to_string_and_render <del> @stuff = render_to_string :text => "here is some cached stuff" <del> render :text => "Hi web users! #{@stuff}" <del> end <del> <del> def render_to_string_with_inline_and_render <del> render_to_string :inline => "<%= 'dlrow olleh'.reverse %>" <del> render :template => "test/hello_world" <del> end <del> <del> def rendering_with_conflicting_local_vars <del> @name = "David" <del> render :action => "potential_conflicts" <del> end <del> <del> def hello_world_from_rxml_using_action <del> render :action => "hello_world_from_rxml", :handlers => [:builder] <del> end <del> <del> # :deprecated: <del> def hello_world_from_rxml_using_template <del> render :template => "test/hello_world_from_rxml", :handlers => [:builder] <del> end <del> <ide> def head_created <ide> head :created <ide> end
1
Javascript
Javascript
avoid extra boolean conversion
bc550ed597a70e6c1f15f22b3a9d6f574cbcf547
<ide><path>packages/ember-routing/lib/system/router.js <ide> const EmberRouter = EmberObject.extend(Evented, { <ide> }, <ide> <ide> _buildDSL() { <del> let moduleBasedResolver = this._hasModuleBasedResolver(); <del> let options = { <del> enableLoadingSubstates: !!moduleBasedResolver <del> }; <add> let enableLoadingSubstates = this._hasModuleBasedResolver(); <add> let options = { enableLoadingSubstates }; <ide> <ide> let owner = getOwner(this); <ide> let router = this; <ide> const EmberRouter = EmberObject.extend(Evented, { <ide> <ide> _hasModuleBasedResolver() { <ide> let owner = getOwner(this); <del> <ide> if (!owner) { return false; } <ide> <del> let resolver = owner.application && owner.application.__registry__ && owner.application.__registry__.resolver; <del> <del> if (!resolver) { return false; } <del> <del> return !!resolver.moduleBasedResolver; <add> let resolver = get(owner, 'application.__registry__.resolver.moduleBasedResolver'); <add> return !!resolver; <ide> }, <ide> <ide> /**
1
Javascript
Javascript
replace fixturesdir with common.fixtures
d2c0978831a863c854177c80a53e1039d04aa787
<ide><path>test/parallel/test-https-client-reject.js <ide> const common = require('../common'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <add>const fixtures = require('../common/fixtures'); <add> <ide> const assert = require('assert'); <ide> const https = require('https'); <del>const fs = require('fs'); <del>const path = require('path'); <ide> <ide> const options = { <del> key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), <del> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) <add> key: fixtures.readSync('test_key.pem'), <add> cert: fixtures.readSync('test_cert.pem') <ide> }; <ide> <ide> const server = https.createServer(options, common.mustCall(function(req, res) { <ide> function rejectUnauthorized() { <ide> function authorized() { <ide> const options = { <ide> port: server.address().port, <del> ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))] <add> ca: [fixtures.readSync('test_cert.pem')] <ide> }; <ide> options.agent = new https.Agent(options); <ide> const req = https.request(options, function(res) {
1
Javascript
Javascript
prevent null access (#523)
ad0f0a4d79e313fcadecccff021cb6c3b38b0d2f
<ide><path>server/build/plugins/watch-pages-plugin.js <ide> import { resolve, relative, join, extname } from 'path' <ide> export default class WatchPagesPlugin { <ide> constructor (dir) { <ide> this.dir = resolve(dir, 'pages') <del> this.prevFileDependencies = null <add> this.prevFileDependencies = [] <ide> } <ide> <ide> apply (compiler) {
1
Javascript
Javascript
provide jquery for now
bf3487086648b7d811806cfbd01c6b2836901251
<ide><path>index.js <ide> function add(paths, name, path) { <ide> add(paths, 'prod', 'vendor/ember/ember.prod.js'); <ide> add(paths, 'debug', 'vendor/ember/ember.debug.js'); <ide> add(paths, 'shims', 'vendor/ember/shims.js'); <add>add(paths, 'jquery', 'vendor/ember/jquery/jquery.js'); <ide> <ide> add(absolutePaths, 'templateCompiler', __dirname + '/dist/ember-template-compiler.js'); <ide> <ide> module.exports = { <ide> destDir: 'ember', <ide> files: [ <ide> 'ember-runtime.js', <del> 'ember-runtime.map', <ide> 'ember-template-compiler.js', <del> 'ember-template-compiler.map', <ide> 'ember-testing.js', <del> 'ember.debug.cjs.js', <del> 'ember.debug.cjs.map', <ide> 'ember.debug.js', <ide> 'ember.min.js', <del> 'ember.prod.js' <add> 'ember.prod.js', <add> 'jquery/jquery.js' <ide> ] <ide> }); <ide>
1
Javascript
Javascript
use es6 map in reactcomponenttreehook if available
db452bd20bb2f4f7f0a5621c07c6eec6dc618179
<ide><path>src/isomorphic/hooks/ReactComponentTreeHook.js <ide> var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> var invariant = require('invariant'); <ide> var warning = require('warning'); <ide> <del>var itemByKey = {}; <del>var unmountedIDs = {}; <del>var rootIDs = {}; <add>function isNative(fn) { <add> // Based on isNative() from Lodash <add> var funcToString = Function.prototype.toString; <add> var hasOwnProperty = Object.prototype.hasOwnProperty; <add> var reIsNative = RegExp('^' + funcToString <add> // Take an example native function source for comparison <add> .call(hasOwnProperty) <add> // Strip regex characters so we can use it for regex <add> .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') <add> // Remove hasOwnProperty from the template to make it generic <add> .replace( <add> /hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, <add> '$1.*?' <add> ) + '$' <add> ); <add> try { <add> var source = funcToString.call(fn); <add> return reIsNative.test(source); <add> } catch (err) { <add> return false; <add> } <add>} <add> <add>var itemMap; <add>var itemByKey; <add> <add>var canUseMap = ( <add> typeof Array.from === 'function' && <add> typeof Map === 'function' && <add> isNative(Map) <add>); <add> <add>if (canUseMap) { <add> itemMap = new Map(); <add>} else { <add> itemByKey = {}; <add>} <add> <add>var unmountedIDs = []; <add>var rootIDs = []; <ide> <ide> // Use non-numeric keys to prevent V8 performance issues: <ide> // https://github.com/facebook/react/pull/7232 <ide> function getIDFromKey(key) { <ide> } <ide> <ide> function get(id) { <add> if (canUseMap) { <add> return itemMap.get(id); <add> } <ide> var key = getKeyFromID(id); <ide> return itemByKey[key]; <ide> } <ide> <ide> function remove(id) { <add> if (canUseMap) { <add> itemMap.delete(id); <add> return; <add> } <ide> var key = getKeyFromID(id); <ide> delete itemByKey[key]; <ide> } <ide> <ide> function create(id, element, parentID) { <del> var key = getKeyFromID(id); <del> itemByKey[key] = { <add> var item = { <ide> element, <ide> parentID, <ide> text: null, <ide> childIDs: [], <ide> isMounted: false, <ide> updateCount: 0, <ide> }; <add> if (canUseMap) { <add> itemMap.set(id, item); <add> return; <add> } <add> var key = getKeyFromID(id); <add> itemByKey[key] = item; <ide> } <ide> <ide> function purgeDeep(id) { <ide> var ReactComponentTreeHook = { <ide> <ide> onBeforeMountComponent(id, element, parentID) { <ide> create(id, element, parentID); <del> <del> if (parentID === 0) { <del> rootIDs[id] = true; <del> } <ide> }, <ide> <ide> onBeforeUpdateComponent(id, element) { <ide> var ReactComponentTreeHook = { <ide> onMountComponent(id) { <ide> var item = get(id); <ide> item.isMounted = true; <add> if (item.parentID === 0) { <add> rootIDs.push(id); <add> } <ide> }, <ide> <ide> onUpdateComponent(id) { <ide> var ReactComponentTreeHook = { <ide> // got a chance to mount, but it still gets an unmounting event during <ide> // the error boundary cleanup. <ide> item.isMounted = false; <add> if (item.parentID === 0) { <add> var indexInRootIDs = rootIDs.indexOf(id); <add> if (indexInRootIDs !== -1) { <add> rootIDs.splice(indexInRootIDs, 1); <add> } <add> } <ide> } <del> unmountedIDs[id] = true; <del> delete rootIDs[id]; <add> unmountedIDs.push(id); <ide> }, <ide> <ide> purgeUnmountedComponents() { <ide> var ReactComponentTreeHook = { <ide> return; <ide> } <ide> <del> for (var id in unmountedIDs) { <add> for (var i = 0; i < unmountedIDs.length; i++) { <add> var id = unmountedIDs[i]; <ide> purgeDeep(id); <ide> } <del> unmountedIDs = {}; <add> unmountedIDs.length = 0; <ide> }, <ide> <ide> isMounted(id) { <ide> var ReactComponentTreeHook = { <ide> }, <ide> <ide> getRootIDs() { <del> return Object.keys(rootIDs); <add> return rootIDs; <ide> }, <ide> <ide> getRegisteredIDs() { <add> if (canUseMap) { <add> return Array.from(itemMap.keys()); <add> } <ide> return Object.keys(itemByKey).map(getIDFromKey); <ide> }, <ide> }; <ide><path>src/renderers/shared/hooks/__tests__/ReactComponentTreeHook-test.js <ide> describe('ReactComponentTreeHook', () => { <ide> } <ide> } <ide> <del> function expectWrapperTreeToEqual(expectedTree) { <add> function expectWrapperTreeToEqual(expectedTree, andStayMounted) { <ide> ReactComponentTreeTestUtils.expectTree(rootInstance._debugID, { <ide> displayName: 'Wrapper', <ide> children: expectedTree ? [expectedTree] : [], <ide> }); <add> var rootDisplayNames = ReactComponentTreeTestUtils.getRootDisplayNames(); <add> var registeredDisplayNames = ReactComponentTreeTestUtils.getRegisteredDisplayNames(); <ide> if (!expectedTree) { <del> expect(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual([]); <del> expect(ReactComponentTreeTestUtils.getRegisteredDisplayNames()).toEqual([]); <add> expect(rootDisplayNames).toEqual([]); <add> expect(registeredDisplayNames).toEqual([]); <add> } else if (andStayMounted) { <add> expect(rootDisplayNames).toContain('Wrapper'); <add> expect(registeredDisplayNames).toContain('Wrapper'); <ide> } <ide> } <ide> <ide> describe('ReactComponentTreeHook', () => { <ide> <ide> // Mount a new tree or update the existing tree. <ide> ReactDOM.render(<Wrapper />, node); <del> expectWrapperTreeToEqual(expectedTree); <add> expectWrapperTreeToEqual(expectedTree, true); <ide> <ide> // Purging should have no effect <ide> // on the tree we expect to see. <ide> ReactComponentTreeHook.purgeUnmountedComponents(); <del> expectWrapperTreeToEqual(expectedTree); <add> expectWrapperTreeToEqual(expectedTree, true); <ide> }); <ide> <ide> // Unmounting the root node should purge <ide> describe('ReactComponentTreeHook', () => { <ide> ReactDOM.render(<Foo />, el); <ide> }); <ide> }); <add> <add> describe('in environment without Map and Array.from', () => { <add> var realMap; <add> var realArrayFrom; <add> <add> beforeEach(() => { <add> realMap = global.Map; <add> realArrayFrom = Array.from; <add> <add> global.Map = undefined; <add> Array.from = undefined; <add> <add> jest.resetModuleRegistry(); <add> <add> React = require('React'); <add> ReactDOM = require('ReactDOM'); <add> ReactDOMServer = require('ReactDOMServer'); <add> ReactInstanceMap = require('ReactInstanceMap'); <add> ReactComponentTreeHook = require('ReactComponentTreeHook'); <add> ReactComponentTreeTestUtils = require('ReactComponentTreeTestUtils'); <add> }); <add> <add> afterEach(() => { <add> global.Map = realMap; <add> Array.from = realArrayFrom; <add> }); <add> <add> it('works', () => { <add> class Qux extends React.Component { <add> render() { <add> return null; <add> } <add> } <add> <add> function Foo() { <add> return { <add> render() { <add> return <Qux />; <add> }, <add> }; <add> } <add> function Bar({children}) { <add> return <h1>{children}</h1>; <add> } <add> class Baz extends React.Component { <add> render() { <add> return ( <add> <div> <add> <Foo /> <add> <Bar> <add> <span>Hi,</span> <add> Mom <add> </Bar> <add> <a href="#">Click me.</a> <add> </div> <add> ); <add> } <add> } <add> <add> var element = <Baz />; <add> var tree = { <add> displayName: 'Baz', <add> element, <add> children: [{ <add> displayName: 'div', <add> children: [{ <add> displayName: 'Foo', <add> element: <Foo />, <add> children: [{ <add> displayName: 'Qux', <add> element: <Qux />, <add> children: [], <add> }], <add> }, { <add> displayName: 'Bar', <add> children: [{ <add> displayName: 'h1', <add> children: [{ <add> displayName: 'span', <add> children: [{ <add> displayName: '#text', <add> element: 'Hi,', <add> text: 'Hi,', <add> }], <add> }, { <add> displayName: '#text', <add> text: 'Mom', <add> element: 'Mom', <add> }], <add> }], <add> }, { <add> displayName: 'a', <add> children: [{ <add> displayName: '#text', <add> text: 'Click me.', <add> element: 'Click me.', <add> }], <add> }], <add> }], <add> }; <add> assertTreeMatches([element, tree]); <add> }); <add> }); <ide> }); <ide><path>src/renderers/shared/hooks/__tests__/ReactComponentTreeHook-test.native.js <ide> describe('ReactComponentTreeHook', () => { <ide> } <ide> } <ide> <del> function expectWrapperTreeToEqual(expectedTree) { <add> function expectWrapperTreeToEqual(expectedTree, andStayMounted) { <ide> ReactComponentTreeTestUtils.expectTree(rootInstance._debugID, { <ide> displayName: 'Wrapper', <ide> children: expectedTree ? [expectedTree] : [], <ide> }); <add> var rootDisplayNames = ReactComponentTreeTestUtils.getRootDisplayNames(); <add> var registeredDisplayNames = ReactComponentTreeTestUtils.getRegisteredDisplayNames(); <ide> if (!expectedTree) { <del> expect(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual([]); <del> expect(ReactComponentTreeTestUtils.getRegisteredDisplayNames()).toEqual([]); <add> expect(rootDisplayNames).toEqual([]); <add> expect(registeredDisplayNames).toEqual([]); <add> } else if (andStayMounted) { <add> expect(rootDisplayNames).toContain('Wrapper'); <add> expect(registeredDisplayNames).toContain('Wrapper'); <ide> } <ide> } <ide> <ide> describe('ReactComponentTreeHook', () => { <ide> <ide> // Mount a new tree or update the existing tree. <ide> ReactNative.render(<Wrapper />, 1); <del> expectWrapperTreeToEqual(expectedTree); <add> expectWrapperTreeToEqual(expectedTree, true); <ide> <ide> // Purging should have no effect <ide> // on the tree we expect to see. <ide> ReactComponentTreeHook.purgeUnmountedComponents(); <del> expectWrapperTreeToEqual(expectedTree); <add> expectWrapperTreeToEqual(expectedTree, true); <ide> }); <ide> <ide> // Unmounting the root node should purge
3
Javascript
Javascript
fix regression from a5dba82
39aafcf801de9c683fb0049b4c0186345ffed55e
<ide><path>src/node.js <ide> startup.processKillAndExit = function() { <ide> process.exitCode = 0; <ide> process.exit = function(code) { <del> if (NativeModule.require('util').isNumber(code)) <add> if (code || code === 0) <ide> process.exitCode = code; <ide> <ide> if (!process._exiting) { <ide><path>test/simple/test-process-exit-recursive.js <ide> process.on('exit', function(code) { <ide> assert.equal(code, 1); <ide> <ide> // now override the exit code of 1 with 0 so that the test passes <del> process.exit(); <add> process.exit(0); <ide> }); <ide> <ide> process.exit(1);
2
Javascript
Javascript
fix referenceerror in resolve() error path
009ba02e18a9ac8539c357be902573b1a014a13a
<ide><path>lib/dns.js <ide> exports.resolve = function(domain, type_, callback_) { <ide> if (typeof resolver === 'function') { <ide> return resolver(domain, callback); <ide> } else { <del> throw new Error('Unknown type "' + type + '"'); <add> throw new Error('Unknown type "' + type_ + '"'); <ide> } <ide> }; <ide> <ide><path>test/simple/test-c-ares.js <ide> dns.lookup('::1', function(error, result, addressType) { <ide> assert.equal(6, addressType); <ide> }); <ide> <add>// Try calling resolve with an unsupported type. <add>assert.throws(function() { <add> dns.resolve('www.google.com', 'HI'); <add>}, /Unknown type/); <add> <ide> // Windows doesn't usually have an entry for localhost 127.0.0.1 in <ide> // C:\Windows\System32\drivers\etc\hosts <ide> // so we disable this test on Windows.
2
Text
Text
fix bugs in _construct() example
f441c8bb1780b7659f06c477d000c04e3acfb599
<ide><path>doc/api/stream.md <ide> class WriteStream extends Writable { <ide> constructor(filename) { <ide> super(); <ide> this.filename = filename; <del> this.fd = fd; <ide> } <ide> _construct(callback) { <del> fs.open(this.filename, (fd, err) => { <add> fs.open(this.filename, (err, fd) => { <ide> if (err) { <ide> callback(err); <ide> } else {
1
Go
Go
add wait time into xtables lock warning
3df00a6c647117b894961f63cd61c52b2c55f4e0
<ide><path>libnetwork/iptables/iptables.go <ide> const opWarnTime = 2 * time.Second <ide> <ide> func filterOutput(start time.Time, output []byte, args ...string) []byte { <ide> // Flag operations that have taken a long time to complete <del> if time.Since(start) > opWarnTime { <del> logrus.Warnf("xtables contention detected while running [%s]: %q", strings.Join(args, " "), string(output)) <add> opTime := time.Since(start) <add> if opTime > opWarnTime { <add> logrus.Warnf("xtables contention detected while running [%s]: Waited for %.2f seconds and received %q", strings.Join(args, " "), float64(opTime)/float64(time.Second), string(output)) <ide> } <ide> // ignore iptables' message about xtables lock: <ide> // it is a warning, not an error.
1
Ruby
Ruby
check types in formula#==
50c7c6bbd6eac0dfb1d3c48e7d0ee49e667b315c
<ide><path>Library/Homebrew/formula.rb <ide> def unpin <ide> @pin.unpin <ide> end <ide> <del> def == b <del> name == b.name <del> end <del> def eql? b <del> self == b and self.class.equal? b.class <add> def == other <add> instance_of?(other.class) && name == other.name <ide> end <add> alias_method :eql?, :== <add> <ide> def hash <ide> name.hash <ide> end <ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_inequality <ide> assert !y.eql?(x) <ide> end <ide> <add> def test_comparison_with_non_formula_objects_does_not_raise <add> assert_not_equal TestBall.new, Object.new <add> end <add> <ide> def test_class_naming <ide> assert_equal 'ShellFm', Formula.class_s('shell.fm') <ide> assert_equal 'Fooxx', Formula.class_s('foo++')
2
Javascript
Javascript
fix lint errors in examples/async/
e9e4c568077016e0884c9656baf16432fd25d90c
<ide><path>examples/async/actions/index.js <del>import fetch from 'isomorphic-fetch'; <add>import fetch from 'isomorphic-fetch' <ide> <del>export const REQUEST_POSTS = 'REQUEST_POSTS'; <del>export const RECEIVE_POSTS = 'RECEIVE_POSTS'; <del>export const SELECT_REDDIT = 'SELECT_REDDIT'; <del>export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT'; <add>export const REQUEST_POSTS = 'REQUEST_POSTS' <add>export const RECEIVE_POSTS = 'RECEIVE_POSTS' <add>export const SELECT_REDDIT = 'SELECT_REDDIT' <add>export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT' <ide> <ide> export function selectReddit(reddit) { <ide> return { <ide> type: SELECT_REDDIT, <ide> reddit <del> }; <add> } <ide> } <ide> <ide> export function invalidateReddit(reddit) { <ide> return { <ide> type: INVALIDATE_REDDIT, <ide> reddit <del> }; <add> } <ide> } <ide> <ide> function requestPosts(reddit) { <ide> return { <ide> type: REQUEST_POSTS, <ide> reddit <del> }; <add> } <ide> } <ide> <ide> function receivePosts(reddit, json) { <ide> function receivePosts(reddit, json) { <ide> reddit: reddit, <ide> posts: json.data.children.map(child => child.data), <ide> receivedAt: Date.now() <del> }; <add> } <ide> } <ide> <ide> function fetchPosts(reddit) { <ide> return dispatch => { <del> dispatch(requestPosts(reddit)); <add> dispatch(requestPosts(reddit)) <ide> return fetch(`http://www.reddit.com/r/${reddit}.json`) <ide> .then(response => response.json()) <del> .then(json => dispatch(receivePosts(reddit, json))); <del> }; <add> .then(json => dispatch(receivePosts(reddit, json))) <add> } <ide> } <ide> <ide> function shouldFetchPosts(state, reddit) { <del> const posts = state.postsByReddit[reddit]; <add> const posts = state.postsByReddit[reddit] <ide> if (!posts) { <del> return true; <add> return true <ide> } <ide> if (posts.isFetching) { <del> return false; <add> return false <ide> } <del> return posts.didInvalidate; <add> return posts.didInvalidate <ide> } <ide> <ide> export function fetchPostsIfNeeded(reddit) { <ide> return (dispatch, getState) => { <ide> if (shouldFetchPosts(getState(), reddit)) { <del> return dispatch(fetchPosts(reddit)); <add> return dispatch(fetchPosts(reddit)) <ide> } <del> }; <add> } <ide> } <ide><path>examples/async/components/Picker.js <del>import React, { Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react' <ide> <ide> export default class Picker extends Component { <ide> render() { <del> const { value, onChange, options } = this.props; <add> const { value, onChange, options } = this.props <ide> <ide> return ( <ide> <span> <ide> export default class Picker extends Component { <ide> } <ide> </select> <ide> </span> <del> ); <add> ) <ide> } <ide> } <ide> <ide> Picker.propTypes = { <ide> ).isRequired, <ide> value: PropTypes.string.isRequired, <ide> onChange: PropTypes.func.isRequired <del>}; <add>} <ide><path>examples/async/components/Posts.js <del>import React, { PropTypes, Component } from 'react'; <add>import React, { PropTypes, Component } from 'react' <ide> <ide> export default class Posts extends Component { <ide> render() { <ide> export default class Posts extends Component { <ide> <li key={i}>{post.title}</li> <ide> )} <ide> </ul> <del> ); <add> ) <ide> } <ide> } <ide> <ide> Posts.propTypes = { <ide> posts: PropTypes.array.isRequired <del>}; <add>} <ide><path>examples/async/containers/App.js <del>import React, { Component, PropTypes } from 'react'; <del>import { connect } from 'react-redux'; <del>import { selectReddit, fetchPostsIfNeeded, invalidateReddit } from '../actions'; <del>import Picker from '../components/Picker'; <del>import Posts from '../components/Posts'; <add>import React, { Component, PropTypes } from 'react' <add>import { connect } from 'react-redux' <add>import { selectReddit, fetchPostsIfNeeded, invalidateReddit } from '../actions' <add>import Picker from '../components/Picker' <add>import Posts from '../components/Posts' <ide> <ide> class App extends Component { <ide> constructor(props) { <del> super(props); <del> this.handleChange = this.handleChange.bind(this); <del> this.handleRefreshClick = this.handleRefreshClick.bind(this); <add> super(props) <add> this.handleChange = this.handleChange.bind(this) <add> this.handleRefreshClick = this.handleRefreshClick.bind(this) <ide> } <ide> <ide> componentDidMount() { <del> const { dispatch, selectedReddit } = this.props; <del> dispatch(fetchPostsIfNeeded(selectedReddit)); <add> const { dispatch, selectedReddit } = this.props <add> dispatch(fetchPostsIfNeeded(selectedReddit)) <ide> } <ide> <ide> componentWillReceiveProps(nextProps) { <ide> if (nextProps.selectedReddit !== this.props.selectedReddit) { <del> const { dispatch, selectedReddit } = nextProps; <del> dispatch(fetchPostsIfNeeded(selectedReddit)); <add> const { dispatch, selectedReddit } = nextProps <add> dispatch(fetchPostsIfNeeded(selectedReddit)) <ide> } <ide> } <ide> <ide> handleChange(nextReddit) { <del> this.props.dispatch(selectReddit(nextReddit)); <add> this.props.dispatch(selectReddit(nextReddit)) <ide> } <ide> <ide> handleRefreshClick(e) { <del> e.preventDefault(); <add> e.preventDefault() <ide> <del> const { dispatch, selectedReddit } = this.props; <del> dispatch(invalidateReddit(selectedReddit)); <del> dispatch(fetchPostsIfNeeded(selectedReddit)); <add> const { dispatch, selectedReddit } = this.props <add> dispatch(invalidateReddit(selectedReddit)) <add> dispatch(fetchPostsIfNeeded(selectedReddit)) <ide> } <ide> <ide> render() { <del> const { selectedReddit, posts, isFetching, lastUpdated } = this.props; <add> const { selectedReddit, posts, isFetching, lastUpdated } = this.props <ide> return ( <ide> <div> <ide> <Picker value={selectedReddit} <ide> onChange={this.handleChange} <del> options={['reactjs', 'frontend']} /> <add> options={[ 'reactjs', 'frontend' ]} /> <ide> <p> <ide> {lastUpdated && <ide> <span> <ide> class App extends Component { <ide> </div> <ide> } <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> <ide> App.propTypes = { <ide> isFetching: PropTypes.bool.isRequired, <ide> lastUpdated: PropTypes.number, <ide> dispatch: PropTypes.func.isRequired <del>}; <add>} <ide> <ide> function mapStateToProps(state) { <del> const { selectedReddit, postsByReddit } = state; <add> const { selectedReddit, postsByReddit } = state <ide> const { <ide> isFetching, <ide> lastUpdated, <ide> items: posts <ide> } = postsByReddit[selectedReddit] || { <ide> isFetching: true, <ide> items: [] <del> }; <add> } <ide> <ide> return { <ide> selectedReddit, <ide> posts, <ide> isFetching, <ide> lastUpdated <del> }; <add> } <ide> } <ide> <del>export default connect(mapStateToProps)(App); <add>export default connect(mapStateToProps)(App) <ide><path>examples/async/index.js <del>import 'babel-core/polyfill'; <del>import React from 'react'; <del>import { render } from 'react-dom'; <del>import { Provider } from 'react-redux'; <del>import App from './containers/App'; <del>import configureStore from './store/configureStore'; <add>import 'babel-core/polyfill' <add>import React from 'react' <add>import { render } from 'react-dom' <add>import { Provider } from 'react-redux' <add>import App from './containers/App' <add>import configureStore from './store/configureStore' <ide> <del>const store = configureStore(); <add>const store = configureStore() <ide> <ide> render( <ide> <Provider store={store}> <ide> <App /> <ide> </Provider>, <ide> document.getElementById('root') <del>); <add>) <ide><path>examples/async/reducers/index.js <del>import { combineReducers } from 'redux'; <add>import { combineReducers } from 'redux' <ide> import { <ide> SELECT_REDDIT, INVALIDATE_REDDIT, <ide> REQUEST_POSTS, RECEIVE_POSTS <del>} from '../actions'; <add>} from '../actions' <ide> <ide> function selectedReddit(state = 'reactjs', action) { <ide> switch (action.type) { <del> case SELECT_REDDIT: <del> return action.reddit; <del> default: <del> return state; <add> case SELECT_REDDIT: <add> return action.reddit <add> default: <add> return state <ide> } <ide> } <ide> <ide> function posts(state = { <ide> items: [] <ide> }, action) { <ide> switch (action.type) { <del> case INVALIDATE_REDDIT: <del> return Object.assign({}, state, { <del> didInvalidate: true <del> }); <del> case REQUEST_POSTS: <del> return Object.assign({}, state, { <del> isFetching: true, <del> didInvalidate: false <del> }); <del> case RECEIVE_POSTS: <del> return Object.assign({}, state, { <del> isFetching: false, <del> didInvalidate: false, <del> items: action.posts, <del> lastUpdated: action.receivedAt <del> }); <del> default: <del> return state; <add> case INVALIDATE_REDDIT: <add> return Object.assign({}, state, { <add> didInvalidate: true <add> }) <add> case REQUEST_POSTS: <add> return Object.assign({}, state, { <add> isFetching: true, <add> didInvalidate: false <add> }) <add> case RECEIVE_POSTS: <add> return Object.assign({}, state, { <add> isFetching: false, <add> didInvalidate: false, <add> items: action.posts, <add> lastUpdated: action.receivedAt <add> }) <add> default: <add> return state <ide> } <ide> } <ide> <ide> function postsByReddit(state = { }, action) { <ide> switch (action.type) { <del> case INVALIDATE_REDDIT: <del> case RECEIVE_POSTS: <del> case REQUEST_POSTS: <del> return Object.assign({}, state, { <del> [action.reddit]: posts(state[action.reddit], action) <del> }); <del> default: <del> return state; <add> case INVALIDATE_REDDIT: <add> case RECEIVE_POSTS: <add> case REQUEST_POSTS: <add> return Object.assign({}, state, { <add> [action.reddit]: posts(state[action.reddit], action) <add> }) <add> default: <add> return state <ide> } <ide> } <ide> <ide> const rootReducer = combineReducers({ <ide> postsByReddit, <ide> selectedReddit <del>}); <add>}) <ide> <del>export default rootReducer; <add>export default rootReducer <ide><path>examples/async/server.js <del>var webpack = require('webpack'); <del>var webpackDevMiddleware = require('webpack-dev-middleware'); <del>var webpackHotMiddleware = require('webpack-hot-middleware'); <del>var config = require('./webpack.config'); <add>var webpack = require('webpack') <add>var webpackDevMiddleware = require('webpack-dev-middleware') <add>var webpackHotMiddleware = require('webpack-hot-middleware') <add>var config = require('./webpack.config') <ide> <del>var app = new require('express')(); <del>var port = 3000; <add>var app = new require('express')() <add>var port = 3000 <ide> <del>var compiler = webpack(config); <del>app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); <del>app.use(webpackHotMiddleware(compiler)); <add>var compiler = webpack(config) <add>app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })) <add>app.use(webpackHotMiddleware(compiler)) <ide> <ide> app.get("/", function(req, res) { <del> res.sendFile(__dirname + '/index.html'); <del>}); <add> res.sendFile(__dirname + '/index.html') <add>}) <ide> <ide> app.listen(port, function(error) { <ide> if (error) { <del> console.error(error); <add> console.error(error) <ide> } else { <del> console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port); <add> console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port) <ide> } <del>}); <add>}) <ide><path>examples/async/store/configureStore.js <del>import { createStore, applyMiddleware } from 'redux'; <del>import thunkMiddleware from 'redux-thunk'; <del>import createLogger from 'redux-logger'; <del>import rootReducer from '../reducers'; <add>import { createStore, applyMiddleware } from 'redux' <add>import thunkMiddleware from 'redux-thunk' <add>import createLogger from 'redux-logger' <add>import rootReducer from '../reducers' <ide> <ide> const createStoreWithMiddleware = applyMiddleware( <ide> thunkMiddleware, <ide> createLogger() <del>)(createStore); <add>)(createStore) <ide> <ide> export default function configureStore(initialState) { <del> const store = createStoreWithMiddleware(rootReducer, initialState); <add> const store = createStoreWithMiddleware(rootReducer, initialState) <ide> <ide> if (module.hot) { <ide> // Enable Webpack hot module replacement for reducers <ide> module.hot.accept('../reducers', () => { <del> const nextRootReducer = require('../reducers'); <del> store.replaceReducer(nextRootReducer); <del> }); <add> const nextRootReducer = require('../reducers') <add> store.replaceReducer(nextRootReducer) <add> }) <ide> } <ide> <del> return store; <add> return store <ide> } <ide><path>examples/async/webpack.config.js <del>var path = require('path'); <del>var webpack = require('webpack'); <add>var path = require('path') <add>var webpack = require('webpack') <ide> <ide> module.exports = { <ide> devtool: 'cheap-module-eval-source-map', <ide> module.exports = { <ide> include: __dirname <ide> }] <ide> } <del>}; <add>} <ide> <ide> <ide> // When inside Redux repo, prefer src to compiled version. <ide> // You can safely delete these lines in your project. <del>var reduxSrc = path.join(__dirname, '..', '..', 'src'); <del>var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules'); <del>var fs = require('fs'); <add>var reduxSrc = path.join(__dirname, '..', '..', 'src') <add>var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules') <add>var fs = require('fs') <ide> if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) { <ide> // Resolve Redux to source <del> module.exports.resolve = { alias: { 'redux': reduxSrc } }; <add> module.exports.resolve = { alias: { 'redux': reduxSrc } } <ide> // Compile Redux from source <ide> module.exports.module.loaders.push({ <ide> test: /\.js$/, <ide> loaders: ['babel'], <ide> include: reduxSrc <del> }); <add> }) <ide> }
9
Java
Java
refine multipart parsing limits
00ead7a756a993e824f50d696d17509280eaaf97
<ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartException.java <del>/* <del> * Copyright 2002-2019 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * https://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.http.codec.multipart; <del> <del>/** <del> * @author Brian Clozel <del> */ <del>@SuppressWarnings("serial") <del>public class MultipartException extends RuntimeException { <del> <del> public MultipartException(String message) { <del> super(message); <del> } <del> <del> public MultipartException(String message, Throwable cause) { <del> super(message, cause); <del> } <del>} <ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import reactor.core.publisher.SignalType; <ide> <ide> import org.springframework.core.ResolvableType; <add>import org.springframework.core.codec.DecodingException; <ide> import org.springframework.core.codec.Hints; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferFactory; <add>import org.springframework.core.io.buffer.DataBufferLimitException; <ide> import org.springframework.core.io.buffer.DataBufferUtils; <ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory; <ide> import org.springframework.core.log.LogFormatUtils; <ide> */ <ide> public class SynchronossPartHttpMessageReader extends LoggingCodecSupport implements HttpMessageReader<Part> { <ide> <del> private final DataBufferFactory bufferFactory; <add> // Static DataBufferFactory to copy from FileInputStream or wrap bytes[]. <add> private static final DataBufferFactory bufferFactory = new DefaultDataBufferFactory(); <ide> <del> private final PartBodyStreamStorageFactory streamStorageFactory = new DefaultPartBodyStreamStorageFactory(); <ide> <del> private long maxPartCount = -1; <add> private int maxInMemorySize = 256 * 1024; <ide> <del> private long maxFilePartSize = -1; <add> private long maxDiskUsagePerPart = -1; <ide> <del> private long maxPartSize = -1; <add> private long maxParts = -1; <ide> <del> public SynchronossPartHttpMessageReader() { <del> this.bufferFactory = new DefaultDataBufferFactory(); <del> } <del> <del> SynchronossPartHttpMessageReader(DataBufferFactory bufferFactory) { <del> this.bufferFactory = bufferFactory; <del> } <ide> <ide> /** <del> * Get the maximum number of parts allowed in a single multipart request. <add> * Configure the maximum amount of memory that is allowed to use per part. <add> * When the limit is exceeded: <add> * <ul> <add> * <li>file parts are written to a temporary file. <add> * <li>non-file parts are rejected with {@link DataBufferLimitException}. <add> * </ul> <add> * <p>By default this is set to 256K. <add> * @param byteCount the in-memory limit in bytes; if set to -1 this limit is <add> * not enforced, and all parts may be written to disk and are limited only <add> * by the {@link #setMaxDiskUsagePerPart(long) maxDiskUsagePerPart} property. <ide> * @since 5.1.11 <ide> */ <del> public long getMaxPartCount() { <del> return maxPartCount; <add> public void setMaxInMemorySize(int byteCount) { <add> this.maxInMemorySize = byteCount; <ide> } <ide> <ide> /** <del> * Configure the maximum number of parts allowed in a single multipart request. <add> * Get the {@link #setMaxInMemorySize configured} maximum in-memory size. <ide> * @since 5.1.11 <ide> */ <del> public void setMaxPartCount(long maxPartCount) { <del> this.maxPartCount = maxPartCount; <add> public int getMaxInMemorySize() { <add> return this.maxInMemorySize; <ide> } <ide> <ide> /** <del> * Get the maximum size of a file part. <add> * Configure the maximum amount of disk space allowed for file parts. <add> * <p>By default this is set to -1. <add> * @param maxDiskUsagePerPart the disk limit in bytes, or -1 for unlimited <ide> * @since 5.1.11 <ide> */ <del> public long getMaxFilePartSize() { <del> return this.maxFilePartSize; <add> public void setMaxDiskUsagePerPart(long maxDiskUsagePerPart) { <add> this.maxDiskUsagePerPart = maxDiskUsagePerPart; <ide> } <ide> <ide> /** <del> * Configure the the maximum size of a file part. <add> * Get the {@link #setMaxDiskUsagePerPart configured} maximum disk usage. <ide> * @since 5.1.11 <ide> */ <del> public void setMaxFilePartSize(long maxFilePartSize) { <del> this.maxFilePartSize = maxFilePartSize; <add> public long getMaxDiskUsagePerPart() { <add> return this.maxDiskUsagePerPart; <ide> } <ide> <ide> /** <del> * Get the maximum size of a part. <add> * Specify the maximum number of parts allowed in a given multipart request. <ide> * @since 5.1.11 <ide> */ <del> public long getMaxPartSize() { <del> return this.maxPartSize; <add> public void setMaxParts(long maxParts) { <add> this.maxParts = maxParts; <ide> } <ide> <ide> /** <del> * Configure the maximum size of a part. <del> * For limits on file parts, use the dedicated {@link #setMaxFilePartSize(long)}. <add> * Return the {@link #setMaxParts configured} limit on the number of parts. <ide> * @since 5.1.11 <ide> */ <del> public void setMaxPartSize(long maxPartSize) { <del> this.maxPartSize = maxPartSize; <add> public long getMaxParts() { <add> return this.maxParts; <ide> } <ide> <add> <ide> @Override <ide> public List<MediaType> getReadableMediaTypes() { <ide> return Collections.singletonList(MediaType.MULTIPART_FORM_DATA); <ide> public boolean canRead(ResolvableType elementType, @Nullable MediaType mediaType <ide> <ide> @Override <ide> public Flux<Part> read(ResolvableType elementType, ReactiveHttpInputMessage message, Map<String, Object> hints) { <del> return Flux.create(new SynchronossPartGenerator(message, this.bufferFactory, this.streamStorageFactory, <del> new MultipartSizeLimiter(getMaxPartCount(), getMaxFilePartSize(), getMaxPartSize()))) <add> return Flux.create(new SynchronossPartGenerator(message)) <ide> .doOnNext(part -> { <ide> if (!Hints.isLoggingSuppressed(hints)) { <ide> LogFormatUtils.traceDebug(logger, traceOn -> Hints.getLogPrefix(hints) + "Parsed " + <ide> public Flux<Part> read(ResolvableType elementType, ReactiveHttpInputMessage mess <ide> <ide> <ide> @Override <del> public Mono<Part> readMono(ResolvableType elementType, ReactiveHttpInputMessage message, Map<String, Object> hints) { <del> return Mono.error(new UnsupportedOperationException("Cannot read multipart request body into single Part")); <del> } <del> <del> <del> private static class MultipartSizeLimiter { <del> <del> private final long maxPartCount; <del> <del> private final long maxFilePartSize; <del> <del> private final long maxPartSize; <del> <del> private boolean currentIsFilePart; <del> <del> private long currentPartCount; <del> <del> private long currentPartSize; <del> <del> <del> public MultipartSizeLimiter(long maxPartCount, long maxFilePartSize, long maxPartSize) { <del> this.maxPartCount = maxPartCount; <del> this.maxFilePartSize = maxFilePartSize; <del> this.maxPartSize = maxPartSize; <del> } <del> <del> public void startPart(boolean isFilePart) { <del> this.currentPartCount++; <del> this.currentIsFilePart = isFilePart; <del> if (this.maxPartCount != -1 && this.currentPartCount > this.maxPartCount) { <del> throw new IllegalStateException("Exceeded limit on maximum number of multipart parts"); <del> } <del> } <del> <del> public void endPart() { <del> this.currentPartSize = 0L; <del> this.currentIsFilePart = false; <del> } <del> <del> public void checkCurrentPartSize(long addedBytes) { <del> this.currentPartSize += addedBytes; <del> if (this.currentIsFilePart && this.maxFilePartSize != -1 && this.currentPartSize > this.maxFilePartSize) { <del> throw new IllegalStateException("Exceeded limit on max size of multipart file : " + this.maxFilePartSize); <del> } <del> else if (!this.currentIsFilePart && this.maxPartSize != -1 && this.currentPartSize > this.maxPartSize) { <del> throw new IllegalStateException("Exceeded limit on max size of multipart part : " + this.maxPartSize); <del> } <del> } <add> public Mono<Part> readMono( <add> ResolvableType elementType, ReactiveHttpInputMessage message, Map<String, Object> hints) { <ide> <add> return Mono.error(new UnsupportedOperationException( <add> "Cannot read multipart request body into single Part")); <ide> } <ide> <add> <ide> /** <del> * Consume {@code DataBuffer} as a {@code BaseSubscriber} of the request body <del> * and feed it as input to the Synchronoss parser. Also listen for parser <del> * output events and adapt them to {@code Flux<Sink<Part>>} to emit parts <del> * for subscribers. <add> * Subscribe to the input stream and feed the Synchronoss parser. Then listen <add> * for parser output, creating parts, and pushing them into the FluxSink. <ide> */ <del> private static class SynchronossPartGenerator extends BaseSubscriber<DataBuffer> <del> implements Consumer<FluxSink<Part>> { <add> private class SynchronossPartGenerator extends BaseSubscriber<DataBuffer> implements Consumer<FluxSink<Part>> { <ide> <ide> private final ReactiveHttpInputMessage inputMessage; <ide> <del> private final DataBufferFactory bufferFactory; <del> <del> private final PartBodyStreamStorageFactory streamStorageFactory; <del> <del> private final MultipartSizeLimiter limiter; <add> private final LimitedPartBodyStreamStorageFactory storageFactory = new LimitedPartBodyStreamStorageFactory(); <ide> <ide> private NioMultipartParserListener listener; <ide> <ide> private NioMultipartParser parser; <ide> <ide> <del> public SynchronossPartGenerator(ReactiveHttpInputMessage inputMessage, DataBufferFactory bufferFactory, <del> PartBodyStreamStorageFactory streamStorageFactory, MultipartSizeLimiter limiter) { <add> public SynchronossPartGenerator(ReactiveHttpInputMessage inputMessage) { <ide> this.inputMessage = inputMessage; <del> this.bufferFactory = bufferFactory; <del> this.streamStorageFactory = new PartBodyStreamStorageFactoryDecorator(streamStorageFactory, limiter); <del> this.limiter = limiter; <ide> } <ide> <add> <ide> @Override <del> public void accept(FluxSink<Part> emitter) { <add> public void accept(FluxSink<Part> sink) { <ide> HttpHeaders headers = this.inputMessage.getHeaders(); <ide> MediaType mediaType = headers.getContentType(); <ide> Assert.state(mediaType != null, "No content type set"); <ide> public void accept(FluxSink<Part> emitter) { <ide> Charset charset = Optional.ofNullable(mediaType.getCharset()).orElse(StandardCharsets.UTF_8); <ide> MultipartContext context = new MultipartContext(mediaType.toString(), length, charset.name()); <ide> <del> this.listener = new FluxSinkAdapterListener(emitter, this.bufferFactory, context, this.limiter); <add> this.listener = new FluxSinkAdapterListener(sink, context, this.storageFactory); <add> <ide> this.parser = Multipart <ide> .multipart(context) <del> .usePartBodyStreamStorageFactory(this.streamStorageFactory) <del> // long to int downcast vs. keeping the default 16Kb value <del> //.withHeadersSizeLimit(this.limiter.maxPartSize) <add> .usePartBodyStreamStorageFactory(this.storageFactory) <ide> .forNIO(this.listener); <add> <ide> this.inputMessage.getBody().subscribe(this); <ide> } <ide> <ide> @Override <ide> protected void hookOnNext(DataBuffer buffer) { <del> int readableByteCount = buffer.readableByteCount(); <del> this.limiter.checkCurrentPartSize(readableByteCount); <del> byte[] resultBytes = new byte[readableByteCount]; <add> int size = buffer.readableByteCount(); <add> this.storageFactory.increaseByteCount(size); <add> byte[] resultBytes = new byte[size]; <ide> buffer.read(resultBytes); <ide> try { <del> parser.write(resultBytes); <add> this.parser.write(resultBytes); <ide> } <ide> catch (IOException ex) { <del> this.cancel(); <del> listener.onError("Exception thrown while providing input to the parser", ex); <add> cancel(); <add> int index = this.storageFactory.getCurrentPartIndex(); <add> this.listener.onError("Parser error for part [" + index + "]", ex); <ide> } <ide> finally { <ide> DataBufferUtils.release(buffer); <ide> } <ide> } <ide> <ide> @Override <del> protected void hookOnError(Throwable throwable) { <del> this.cancel(); <del> listener.onError("Could not parse multipart request", throwable); <del> } <del> <del> @Override <del> protected void hookOnCancel() { <del> this.cancel(); <add> protected void hookOnError(Throwable ex) { <add> try { <add> this.parser.close(); <add> } <add> catch (IOException ex2) { <add> // ignore <add> } <add> finally { <add> int index = this.storageFactory.getCurrentPartIndex(); <add> this.listener.onError("Failure while parsing part[" + index + "]", ex); <add> } <ide> } <ide> <ide> @Override <ide> protected void hookFinally(SignalType type) { <ide> try { <del> parser.close(); <add> this.parser.close(); <ide> } <ide> catch (IOException ex) { <del> listener.onError("Exception thrown while closing the parser", ex); <add> this.listener.onError("Error while closing parser", ex); <ide> } <ide> } <ide> <ide> private int getContentLength(HttpHeaders headers) { <ide> } <ide> } <ide> <del> private static class PartBodyStreamStorageFactoryDecorator implements PartBodyStreamStorageFactory { <ide> <del> private final PartBodyStreamStorageFactory streamStorageFactory; <add> private class LimitedPartBodyStreamStorageFactory implements PartBodyStreamStorageFactory { <add> <add> private final PartBodyStreamStorageFactory storageFactory = maxInMemorySize > 0 ? <add> new DefaultPartBodyStreamStorageFactory(maxInMemorySize) : <add> new DefaultPartBodyStreamStorageFactory(); <add> <add> private int index = 1; <add> <add> private boolean isFilePart; <ide> <del> private final MultipartSizeLimiter limiter; <add> private long partSize; <ide> <del> public PartBodyStreamStorageFactoryDecorator(PartBodyStreamStorageFactory streamStorageFactory, <del> MultipartSizeLimiter limiter) { <del> this.streamStorageFactory = streamStorageFactory; <del> this.limiter = limiter; <add> <add> public int getCurrentPartIndex() { <add> return this.index; <ide> } <ide> <ide> @Override <del> public StreamStorage newStreamStorageForPartBody(Map<String, List<String>> partHeaders, int partIndex) { <del> HttpHeaders httpHeaders = new HttpHeaders(); <del> httpHeaders.putAll(partHeaders); <del> String filename = MultipartUtils.getFileName(httpHeaders); <del> this.limiter.startPart(filename != null); <del> return streamStorageFactory.newStreamStorageForPartBody(partHeaders, partIndex); <add> public StreamStorage newStreamStorageForPartBody(Map<String, List<String>> headers, int index) { <add> this.index = index; <add> this.isFilePart = (MultipartUtils.getFileName(headers) != null); <add> this.partSize = 0; <add> if (maxParts > 0 && index > maxParts) { <add> throw new DecodingException("Too many parts (" + index + " allowed)"); <add> } <add> return this.storageFactory.newStreamStorageForPartBody(headers, index); <add> } <add> <add> public void increaseByteCount(long byteCount) { <add> this.partSize += byteCount; <add> if (maxInMemorySize > 0 && !this.isFilePart && this.partSize >= maxInMemorySize) { <add> throw new DataBufferLimitException("Part[" + this.index + "] " + <add> "exceeded the in-memory limit of " + maxInMemorySize + " bytes"); <add> } <add> if (maxDiskUsagePerPart > 0 && this.isFilePart && this.partSize > maxDiskUsagePerPart) { <add> throw new DecodingException("Part[" + this.index + "] " + <add> "exceeded the disk usage limit of " + maxDiskUsagePerPart + " bytes"); <add> } <add> } <add> <add> public void partFinished() { <add> this.index++; <add> this.isFilePart = false; <add> this.partSize = 0; <ide> } <ide> } <ide> <ide> private static class FluxSinkAdapterListener implements NioMultipartParserListen <ide> <ide> private final FluxSink<Part> sink; <ide> <del> private final DataBufferFactory bufferFactory; <del> <ide> private final MultipartContext context; <ide> <del> private final MultipartSizeLimiter limiter; <add> private final LimitedPartBodyStreamStorageFactory storageFactory; <ide> <ide> private final AtomicInteger terminated = new AtomicInteger(0); <ide> <del> FluxSinkAdapterListener(FluxSink<Part> sink, DataBufferFactory factory, <del> MultipartContext context, MultipartSizeLimiter limiter) { <add> <add> FluxSinkAdapterListener( <add> FluxSink<Part> sink, MultipartContext context, LimitedPartBodyStreamStorageFactory factory) { <add> <ide> this.sink = sink; <del> this.bufferFactory = factory; <ide> this.context = context; <del> this.limiter = limiter; <add> this.storageFactory = factory; <ide> } <ide> <add> <ide> @Override <ide> public void onPartFinished(StreamStorage storage, Map<String, List<String>> headers) { <ide> HttpHeaders httpHeaders = new HttpHeaders(); <ide> httpHeaders.putAll(headers); <add> this.storageFactory.partFinished(); <ide> this.sink.next(createPart(storage, httpHeaders)); <del> this.limiter.endPart(); <ide> } <ide> <ide> private Part createPart(StreamStorage storage, HttpHeaders httpHeaders) { <ide> String filename = MultipartUtils.getFileName(httpHeaders); <ide> if (filename != null) { <del> return new SynchronossFilePart(httpHeaders, filename, storage, this.bufferFactory); <add> return new SynchronossFilePart(httpHeaders, filename, storage); <ide> } <ide> else if (MultipartUtils.isFormField(httpHeaders, this.context)) { <ide> String value = MultipartUtils.readFormParameterValue(storage, httpHeaders); <del> return new SynchronossFormFieldPart(httpHeaders, this.bufferFactory, value); <add> return new SynchronossFormFieldPart(httpHeaders, value); <ide> } <ide> else { <del> return new SynchronossPart(httpHeaders, storage, this.bufferFactory); <add> return new SynchronossPart(httpHeaders, storage); <ide> } <ide> } <ide> <ide> @Override <ide> public void onError(String message, Throwable cause) { <ide> if (this.terminated.getAndIncrement() == 0) { <del> this.sink.error(new MultipartException(message, cause)); <add> this.sink.error(new DecodingException(message, cause)); <ide> } <ide> } <ide> <ide> private abstract static class AbstractSynchronossPart implements Part { <ide> <ide> private final HttpHeaders headers; <ide> <del> private final DataBufferFactory bufferFactory; <del> <del> AbstractSynchronossPart(HttpHeaders headers, DataBufferFactory bufferFactory) { <add> AbstractSynchronossPart(HttpHeaders headers) { <ide> Assert.notNull(headers, "HttpHeaders is required"); <del> Assert.notNull(bufferFactory, "DataBufferFactory is required"); <ide> this.name = MultipartUtils.getFieldName(headers); <ide> this.headers = headers; <del> this.bufferFactory = bufferFactory; <ide> } <ide> <ide> @Override <ide> public HttpHeaders headers() { <ide> return this.headers; <ide> } <ide> <del> DataBufferFactory getBufferFactory() { <del> return this.bufferFactory; <del> } <del> <ide> @Override <ide> public String toString() { <ide> return "Part '" + this.name + "', headers=" + this.headers; <ide> private static class SynchronossPart extends AbstractSynchronossPart { <ide> <ide> private final StreamStorage storage; <ide> <del> SynchronossPart(HttpHeaders headers, StreamStorage storage, DataBufferFactory factory) { <del> super(headers, factory); <add> SynchronossPart(HttpHeaders headers, StreamStorage storage) { <add> super(headers); <ide> Assert.notNull(storage, "StreamStorage is required"); <ide> this.storage = storage; <ide> } <ide> <ide> @Override <ide> public Flux<DataBuffer> content() { <del> return DataBufferUtils.readInputStream(getStorage()::getInputStream, getBufferFactory(), 4096); <add> return DataBufferUtils.readInputStream(getStorage()::getInputStream, bufferFactory, 4096); <ide> } <ide> <ide> protected StreamStorage getStorage() { <ide> private static class SynchronossFilePart extends SynchronossPart implements File <ide> <ide> private final String filename; <ide> <del> SynchronossFilePart(HttpHeaders headers, String filename, StreamStorage storage, DataBufferFactory factory) { <del> super(headers, storage, factory); <add> SynchronossFilePart(HttpHeaders headers, String filename, StreamStorage storage) { <add> super(headers, storage); <ide> this.filename = filename; <ide> } <ide> <ide> private static class SynchronossFormFieldPart extends AbstractSynchronossPart im <ide> <ide> private final String content; <ide> <del> SynchronossFormFieldPart(HttpHeaders headers, DataBufferFactory bufferFactory, String content) { <del> super(headers, bufferFactory); <add> SynchronossFormFieldPart(HttpHeaders headers, String content) { <add> super(headers); <ide> this.content = content; <ide> } <ide> <ide> public String value() { <ide> @Override <ide> public Flux<DataBuffer> content() { <ide> byte[] bytes = this.content.getBytes(getCharset()); <del> DataBuffer buffer = getBufferFactory().allocateBuffer(bytes.length); <del> buffer.write(bytes); <del> return Flux.just(buffer); <add> return Flux.just(bufferFactory.wrap(bytes)); <ide> } <ide> <ide> private Charset getCharset() { <ide><path>spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java <ide> import reactor.test.StepVerifier; <ide> <ide> import org.springframework.core.ResolvableType; <add>import org.springframework.core.codec.DecodingException; <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.buffer.AbstractLeakCheckingTests; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> public class SynchronossPartHttpMessageReaderTests extends AbstractLeakCheckingTests { <ide> <ide> private final MultipartHttpMessageReader reader = <del> new MultipartHttpMessageReader(new SynchronossPartHttpMessageReader(this.bufferFactory)); <add> new MultipartHttpMessageReader(new SynchronossPartHttpMessageReader()); <ide> <ide> private static final ResolvableType PARTS_ELEMENT_TYPE = <ide> forClassWithGenerics(MultiValueMap.class, String.class, Part.class); <ide> void readPartsWithoutDemand() { <ide> <ide> @Test <ide> void readTooManyParts() { <del> testMultipartExceptions( <del> reader -> reader.setMaxPartCount(1), <del> err -> { <del> assertThat(err).isInstanceOf(MultipartException.class) <del> .hasMessage("Could not parse multipart request"); <del> assertThat(err.getCause()).hasMessage("Exceeded limit on maximum number of multipart parts"); <add> testMultipartExceptions(reader -> reader.setMaxParts(1), ex -> { <add> assertThat(ex) <add> .isInstanceOf(DecodingException.class) <add> .hasMessageStartingWith("Failure while parsing part[2]"); <add> assertThat(ex.getCause()) <add> .hasMessage("Too many parts (2 allowed)"); <ide> } <ide> ); <ide> } <del> <add> <ide> @Test <ide> void readFilePartTooBig() { <del> testMultipartExceptions( <del> reader -> reader.setMaxFilePartSize(5), <del> err -> { <del> assertThat(err).isInstanceOf(MultipartException.class) <del> .hasMessage("Could not parse multipart request"); <del> assertThat(err.getCause()).hasMessage("Exceeded limit on max size of multipart file : 5"); <add> testMultipartExceptions(reader -> reader.setMaxDiskUsagePerPart(5), ex -> { <add> assertThat(ex) <add> .isInstanceOf(DecodingException.class) <add> .hasMessageStartingWith("Failure while parsing part[1]"); <add> assertThat(ex.getCause()) <add> .hasMessage("Part[1] exceeded the disk usage limit of 5 bytes"); <ide> } <ide> ); <ide> } <ide> <ide> @Test <del> void readPartTooBig() { <del> testMultipartExceptions( <del> reader -> reader.setMaxPartSize(6), <del> err -> { <del> assertThat(err).isInstanceOf(MultipartException.class) <del> .hasMessage("Could not parse multipart request"); <del> assertThat(err.getCause()).hasMessage("Exceeded limit on max size of multipart part : 6"); <add> void readPartHeadersTooBig() { <add> testMultipartExceptions(reader -> reader.setMaxInMemorySize(1), ex -> { <add> assertThat(ex) <add> .isInstanceOf(DecodingException.class) <add> .hasMessageStartingWith("Failure while parsing part[1]"); <add> assertThat(ex.getCause()) <add> .hasMessage("Part[1] exceeded the in-memory limit of 1 bytes"); <ide> } <ide> ); <ide> } <ide> <del> private void testMultipartExceptions(Consumer<SynchronossPartHttpMessageReader> configurer, <del> Consumer<Throwable> assertions) { <del> SynchronossPartHttpMessageReader synchronossReader = new SynchronossPartHttpMessageReader(this.bufferFactory); <del> configurer.accept(synchronossReader); <del> MultipartHttpMessageReader reader = new MultipartHttpMessageReader(synchronossReader); <del> ServerHttpRequest request = generateMultipartRequest(); <del> StepVerifier.create(reader.readMono(PARTS_ELEMENT_TYPE, request, emptyMap())) <add> private void testMultipartExceptions( <add> Consumer<SynchronossPartHttpMessageReader> configurer, Consumer<Throwable> assertions) { <add> <add> SynchronossPartHttpMessageReader reader = new SynchronossPartHttpMessageReader(); <add> configurer.accept(reader); <add> MultipartHttpMessageReader multipartReader = new MultipartHttpMessageReader(reader); <add> StepVerifier.create(multipartReader.readMono(PARTS_ELEMENT_TYPE, generateMultipartRequest(), emptyMap())) <ide> .consumeErrorWith(assertions) <ide> .verify(); <ide> } <ide> private ServerHttpRequest generateMultipartRequest() { <ide> new MultipartHttpMessageWriter() <ide> .write(Mono.just(partsBuilder.build()), null, MediaType.MULTIPART_FORM_DATA, outputMessage, null) <ide> .block(Duration.ofSeconds(5)); <del> Flux<DataBuffer> requestBody = outputMessage.getBody().map(buffer -> this.bufferFactory.wrap(buffer.asByteBuffer())); <add> Flux<DataBuffer> requestBody = outputMessage.getBody() <add> .map(buffer -> this.bufferFactory.wrap(buffer.asByteBuffer())); <ide> return MockServerHttpRequest.post("/") <ide> .contentType(outputMessage.getHeaders().getContentType()) <ide> .body(requestBody);
3
Mixed
Javascript
expose urltohttpoptions utility
7efada695f9cb7515a78565213f25d8077c206ff
<ide><path>doc/api/url.md <ide> new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c <ide> pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) <ide> ``` <ide> <add>### `url.urlToHttpOptions(url)` <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `url` {URL} The [WHATWG URL][] object to convert to an options object. <add>* Returns: {Object} Options object <add> * `protocol` {string} Protocol to use. <add> * `hostname` {string} A domain name or IP address of the server to issue the <add> request to. <add> * `hash` {string} The fragment portion of the URL. <add> * `search` {string} The serialized query portion of the URL. <add> * `pathname` {string} The path portion of the URL. <add> * `path` {string} Request path. Should include query string if any. <add> E.G. `'/index.html?page=12'`. An exception is thrown when the request path <add> contains illegal characters. Currently, only spaces are rejected but that <add> may change in the future. <add> * `href` {string} The serialized URL. <add> * `port` {number} Port of remote server. <add> * `auth` {string} Basic authentication i.e. `'user:password'` to compute an <add> Authorization header. <add> <add>This utility function converts a URL object into an ordinary options object as <add>expected by the [`http.request()`][] and [`https.request()`][] APIs. <add> <add>```js <add>const { urlToHttpOptions } = require('url'); <add>const myURL = new URL('https://a:b@測試?abc#foo'); <add> <add>console.log(urlToHttpOptions(myUrl)); <add>/** <add>{ <add> protocol: 'https:', <add> hostname: 'xn--g6w251d', <add> hash: '#foo', <add> search: '?abc', <add> pathname: '/', <add> path: '/?abc', <add> href: 'https://a:b@xn--g6w251d/?abc#foo', <add> auth: 'a:b' <add>} <add>*/ <add>``` <add> <ide> ## Legacy URL API <ide> <!-- YAML <ide> deprecated: v11.0.0 <ide> console.log(myURL.origin); <ide> [`TypeError`]: errors.md#errors_class_typeerror <ide> [`URLSearchParams`]: #url_class_urlsearchparams <ide> [`array.toString()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString <add>[`http.request()`]: http.md#http_http_request_options_callback <add>[`https.request()`]: https.md#https_https_request_options_callback <ide> [`new URL()`]: #url_new_url_input_base <ide> [`querystring`]: querystring.md <ide> [`require('url').format()`]: #url_url_format_url_options <ide><path>lib/_http_client.js <ide> const { OutgoingMessage } = require('_http_outgoing'); <ide> const Agent = require('_http_agent'); <ide> const { Buffer } = require('buffer'); <ide> const { defaultTriggerAsyncIdScope } = require('internal/async_hooks'); <del>const { URL, urlToOptions, searchParamsSymbol } = require('internal/url'); <add>const { URL, urlToHttpOptions, searchParamsSymbol } = require('internal/url'); <ide> const { kOutHeaders, kNeedDrain } = require('internal/http'); <ide> const { connResetException, codes } = require('internal/errors'); <ide> const { <ide> function ClientRequest(input, options, cb) { <ide> if (typeof input === 'string') { <ide> const urlStr = input; <ide> try { <del> input = urlToOptions(new URL(urlStr)); <add> input = urlToHttpOptions(new URL(urlStr)); <ide> } catch (err) { <ide> input = url.parse(urlStr); <ide> if (!input.hostname) { <ide> function ClientRequest(input, options, cb) { <ide> } else if (input && input[searchParamsSymbol] && <ide> input[searchParamsSymbol][searchParamsSymbol]) { <ide> // url.URL instance <del> input = urlToOptions(input); <add> input = urlToHttpOptions(input); <ide> } else { <ide> cb = options; <ide> options = input; <ide><path>lib/https.js <ide> const { ClientRequest } = require('_http_client'); <ide> let debug = require('internal/util/debuglog').debuglog('https', (fn) => { <ide> debug = fn; <ide> }); <del>const { URL, urlToOptions, searchParamsSymbol } = require('internal/url'); <add>const { URL, urlToHttpOptions, searchParamsSymbol } = require('internal/url'); <ide> const { IncomingMessage, ServerResponse } = require('http'); <ide> const { kIncomingMessage } = require('_http_common'); <ide> <ide> function request(...args) { <ide> if (typeof args[0] === 'string') { <ide> const urlStr = ArrayPrototypeShift(args); <ide> try { <del> options = urlToOptions(new URL(urlStr)); <add> options = urlToHttpOptions(new URL(urlStr)); <ide> } catch (err) { <ide> options = url.parse(urlStr); <ide> if (!options.hostname) { <ide> function request(...args) { <ide> } else if (args[0] && args[0][searchParamsSymbol] && <ide> args[0][searchParamsSymbol][searchParamsSymbol]) { <ide> // url.URL instance <del> options = urlToOptions(ArrayPrototypeShift(args)); <add> options = urlToHttpOptions(ArrayPrototypeShift(args)); <ide> } <ide> <ide> if (args[0] && typeof args[0] !== 'function') { <ide><path>lib/internal/url.js <ide> function domainToUnicode(domain) { <ide> // Utility function that converts a URL object into an ordinary <ide> // options object as expected by the http.request and https.request <ide> // APIs. <del>function urlToOptions(url) { <add>function urlToHttpOptions(url) { <ide> const options = { <ide> protocol: url.protocol, <ide> hostname: typeof url.hostname === 'string' && <ide> module.exports = { <ide> URLSearchParams, <ide> domainToASCII, <ide> domainToUnicode, <del> urlToOptions, <add> urlToHttpOptions, <ide> formatSymbol: kFormat, <ide> searchParamsSymbol: searchParams, <ide> encodeStr <ide><path>lib/url.js <ide> const { <ide> URLSearchParams, <ide> domainToASCII, <ide> domainToUnicode, <add> fileURLToPath, <ide> formatSymbol, <ide> pathToFileURL, <del> fileURLToPath <add> urlToHttpOptions, <ide> } = require('internal/url'); <ide> <ide> // Original url.parse() API <ide> module.exports = { <ide> <ide> // Utilities <ide> pathToFileURL, <del> fileURLToPath <add> fileURLToPath, <add> urlToHttpOptions, <ide> }; <ide><path>test/parallel/test-url-urltooptions.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add>const { urlToHttpOptions } = require('url'); <add> <add>// Test urlToHttpOptions <add>const urlObj = new URL('http://user:[email protected]:21/aaa/zzz?l=24#test'); <add>const opts = urlToHttpOptions(urlObj); <add>assert.strictEqual(opts instanceof URL, false); <add>assert.strictEqual(opts.protocol, 'http:'); <add>assert.strictEqual(opts.auth, 'user:pass'); <add>assert.strictEqual(opts.hostname, 'foo.bar.com'); <add>assert.strictEqual(opts.port, 21); <add>assert.strictEqual(opts.path, '/aaa/zzz?l=24'); <add>assert.strictEqual(opts.pathname, '/aaa/zzz'); <add>assert.strictEqual(opts.search, '?l=24'); <add>assert.strictEqual(opts.hash, '#test'); <add> <add>const { hostname } = urlToHttpOptions(new URL('http://[::1]:21')); <add>assert.strictEqual(hostname, '::1'); <add> <add>// If a WHATWG URL object is copied, it is possible that the resulting copy <add>// contains the Symbols that Node uses for brand checking, but not the data <add>// properties, which are getters. Verify that urlToHttpOptions() can handle <add>// such a case. <add>const copiedUrlObj = { ...urlObj }; <add>const copiedOpts = urlToHttpOptions(copiedUrlObj); <add>assert.strictEqual(copiedOpts instanceof URL, false); <add>assert.strictEqual(copiedOpts.protocol, undefined); <add>assert.strictEqual(copiedOpts.auth, undefined); <add>assert.strictEqual(copiedOpts.hostname, undefined); <add>assert.strictEqual(copiedOpts.port, NaN); <add>assert.strictEqual(copiedOpts.path, ''); <add>assert.strictEqual(copiedOpts.pathname, undefined); <add>assert.strictEqual(copiedOpts.search, undefined); <add>assert.strictEqual(copiedOpts.hash, undefined); <add>assert.strictEqual(copiedOpts.href, undefined); <ide><path>test/parallel/test-whatwg-url-custom-properties.js <ide> require('../common'); <ide> const URL = require('url').URL; <ide> const assert = require('assert'); <del>const urlToOptions = require('internal/url').urlToOptions; <ide> <ide> const url = new URL('http://user:[email protected]:21/aaa/zzz?l=24#test'); <ide> const oldParams = url.searchParams; // For test of [SameObject] <ide> assert.strictEqual(url.toString(), <ide> assert.strictEqual((delete url.searchParams), true); <ide> assert.strictEqual(url.searchParams, oldParams); <ide> <del>// Test urlToOptions <del>{ <del> const urlObj = new URL('http://user:[email protected]:21/aaa/zzz?l=24#test'); <del> const opts = urlToOptions(urlObj); <del> assert.strictEqual(opts instanceof URL, false); <del> assert.strictEqual(opts.protocol, 'http:'); <del> assert.strictEqual(opts.auth, 'user:pass'); <del> assert.strictEqual(opts.hostname, 'foo.bar.com'); <del> assert.strictEqual(opts.port, 21); <del> assert.strictEqual(opts.path, '/aaa/zzz?l=24'); <del> assert.strictEqual(opts.pathname, '/aaa/zzz'); <del> assert.strictEqual(opts.search, '?l=24'); <del> assert.strictEqual(opts.hash, '#test'); <del> <del> const { hostname } = urlToOptions(new URL('http://[::1]:21')); <del> assert.strictEqual(hostname, '::1'); <del> <del> // If a WHATWG URL object is copied, it is possible that the resulting copy <del> // contains the Symbols that Node uses for brand checking, but not the data <del> // properties, which are getters. Verify that urlToOptions() can handle such <del> // a case. <del> const copiedUrlObj = { ...urlObj }; <del> const copiedOpts = urlToOptions(copiedUrlObj); <del> assert.strictEqual(copiedOpts instanceof URL, false); <del> assert.strictEqual(copiedOpts.protocol, undefined); <del> assert.strictEqual(copiedOpts.auth, undefined); <del> assert.strictEqual(copiedOpts.hostname, undefined); <del> assert.strictEqual(copiedOpts.port, NaN); <del> assert.strictEqual(copiedOpts.path, ''); <del> assert.strictEqual(copiedOpts.pathname, undefined); <del> assert.strictEqual(copiedOpts.search, undefined); <del> assert.strictEqual(copiedOpts.hash, undefined); <del> assert.strictEqual(copiedOpts.href, undefined); <del>} <del> <ide> // Test special origins <ide> [ <ide> { expected: 'https://whatwg.org',
7
Python
Python
fix small typos in docs + constructor
fa338ebe86f9c8a8fb50b9741f9a90fcf1dfe782
<ide><path>airflow/operators/mysql_to_hive.py <ide> class MySqlToHiveTransfer(BaseOperator): <ide> a ``CREATE TABLE`` and ``DROP TABLE`` statements are generated. <ide> Hive data types are inferred from the cursors's metadata. <ide> <del> Note that the table genearted in Hive uses ``STORED AS textfile`` <add> Note that the table generated in Hive uses ``STORED AS textfile`` <ide> which isn't the most efficient serialization format. If a <del> large amount of data is loaded and/or if the tables gets <add> large amount of data is loaded and/or if the table gets <ide> queried considerably, you may want to use this operator only to <ide> stage the data into a temporary table before loading it into its <ide> final destination using a ``HiveOperator``. <ide> <add> :param sql: SQL query to execute against the MySQL database <add> :type sql: str <ide> :param hive_table: target Hive table, use dot notation to target a <ide> specific database <ide> :type hive_table: str <ide> def __init__( <ide> recreate=False, <ide> partition=None, <ide> delimiter=chr(1), <del> mysql_conn_id='hive_cli_default', <add> mysql_conn_id='mysql_default', <ide> hive_cli_conn_id='hive_cli_default', <ide> *args, **kwargs): <ide> super(MySqlToHiveTransfer, self).__init__(*args, **kwargs)
1
PHP
PHP
change emailregex to emailpattern
f6a011215c2d6f51da1b75d886001ffccbbdff33
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> class CakeEmail { <ide> * <ide> * @var string <ide> */ <del> protected $_emailRegex = null; <add> protected $_emailPattern = null; <ide> <ide> /** <ide> * Constructor <ide> public function headerCharset($charset = null) { <ide> } <ide> <ide> /** <del> * EmailRegex setter/getter <add> * EmailPattern setter/getter <ide> * <del> * @param string $regexp <add> * @param string $regex for email address validation <ide> * @return string|CakeEmail <ide> */ <del> public function emailRegex($regex = null) { <add> public function emailPattern($regex = null) { <ide> if ($regex === null) { <del> return $this->_emailRegex; <add> return $this->_emailPattern; <ide> } <del> $this->_emailRegex = $regex; <add> $this->_emailPattern = $regex; <ide> return $this; <ide> } <ide> <ide> public function emailRegex($regex = null) { <ide> */ <ide> protected function _setEmail($varName, $email, $name) { <ide> if (!is_array($email)) { <del> if (!Validation::email($email, false, $this->_emailRegex)) { <add> if (!Validation::email($email, false, $this->_emailPattern)) { <ide> throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $email)); <ide> } <ide> if ($name === null) { <ide> protected function _setEmail($varName, $email, $name) { <ide> if (is_int($key)) { <ide> $key = $value; <ide> } <del> if (!Validation::email($key, false, $this->_emailRegex)) { <add> if (!Validation::email($key, false, $this->_emailPattern)) { <ide> throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $key)); <ide> } <ide> $list[$key] = $value; <ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage) { <ide> */ <ide> protected function _addEmail($varName, $email, $name) { <ide> if (!is_array($email)) { <del> if (!Validation::email($email, false, $this->_emailRegex)) { <add> if (!Validation::email($email, false, $this->_emailPattern)) { <ide> throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $email)); <ide> } <ide> if ($name === null) { <ide> protected function _addEmail($varName, $email, $name) { <ide> if (is_int($key)) { <ide> $key = $value; <ide> } <del> if (!Validation::email($key, false, $this->_emailRegex)) { <add> if (!Validation::email($key, false, $this->_emailPattern)) { <ide> throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $key)); <ide> } <ide> $list[$key] = $value; <ide> protected function _applyConfig($config) { <ide> $simpleMethods = array( <ide> 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', 'cc', 'bcc', <ide> 'messageId', 'domain', 'subject', 'viewRender', 'viewVars', 'attachments', <del> 'transport', 'emailFormat', 'theme', 'helpers', 'emailRegex' <add> 'transport', 'emailFormat', 'theme', 'helpers', 'emailPattern' <ide> ); <ide> foreach ($simpleMethods as $method) { <ide> if (isset($config[$method])) { <ide> public function reset() { <ide> $this->headerCharset = null; <ide> $this->_attachments = array(); <ide> $this->_config = array(); <del> $this->_emailRegex = null; <add> $this->_emailPattern = null; <ide> return $this; <ide> } <ide> <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testInvalidEmailAdd($value) { <ide> } <ide> <ide> /** <del> * test emailRegex method <add> * test emailPattern method <ide> * <ide> * @return void <ide> */ <del> public function testEmailRegex() { <add> public function testEmailPattern() { <ide> $regex = '/.+@.+\..+/i'; <del> $this->assertNull($this->CakeEmail->emailRegex()); <del> $this->assertSame($regex, $this->CakeEmail->emailRegex($regex)->emailRegex()); <add> $this->assertNull($this->CakeEmail->emailPattern()); <add> $this->assertSame($regex, $this->CakeEmail->emailPattern($regex)->emailPattern()); <ide> } <ide> <ide> /** <ide> * Tests that it is possible to set email regex configuration to a CakeEmail object <ide> * <ide> * @return void <ide> */ <del> public function testConfigEmailRegex() { <add> public function testConfigEmailPattern() { <ide> $regex = '/.+@.+\..+/i'; <del> $email = new CakeEmail(array('emailRegex' => $regex)); <del> $this->assertSame($regex, $email->emailRegex()); <add> $email = new CakeEmail(array('emailPattern' => $regex)); <add> $this->assertSame($regex, $email->emailPattern()); <ide> } <ide> <ide> /** <ide> public function testConfigEmailRegex() { <ide> public function testCustomEmailValidation() { <ide> $regex = '/^[\.a-z0-9!#$%&\'*+\/=?^_`{|}~-]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]{2,6}$/i'; <ide> <del> $this->CakeEmail->emailRegex($regex)->to('[email protected]'); <add> $this->CakeEmail->emailPattern($regex)->to('[email protected]'); <ide> $this->assertSame(array( <ide> '[email protected]' => '[email protected]', <ide> ), $this->CakeEmail->to()); <ide> public function testCustomEmailValidation() { <ide> '[email protected]', <ide> '[email protected]' <ide> ); <del> $this->CakeEmail->emailRegex($regex)->to($emails); <add> $this->CakeEmail->emailPattern($regex)->to($emails); <ide> $this->assertSame(array( <ide> '[email protected]' => '[email protected]', <ide> '[email protected]' => '[email protected]', <ide> public function testMessage() { <ide> public function testReset() { <ide> $this->CakeEmail->to('[email protected]'); <ide> $this->CakeEmail->theme('TestTheme'); <del> $this->CakeEmail->emailRegex('/.+@.+\..+/i'); <add> $this->CakeEmail->emailPattern('/.+@.+\..+/i'); <ide> $this->assertSame($this->CakeEmail->to(), array('[email protected]' => '[email protected]')); <ide> <ide> $this->CakeEmail->reset(); <ide> $this->assertSame($this->CakeEmail->to(), array()); <ide> $this->assertSame(null, $this->CakeEmail->theme()); <del> $this->assertSame(null, $this->CakeEmail->emailRegex()); <add> $this->assertSame(null, $this->CakeEmail->emailPattern()); <ide> } <ide> <ide> /**
2
PHP
PHP
fix bugs and formatting
12e47bb3dad10294268fa3167112b198fd0a2036
<ide><path>src/Illuminate/Queue/SqsQueue.php <ide> public function getQueue($queue) <ide> } <ide> <ide> /** <del> * Suffixes a queue <add> * Add the given suffix to the given queue name. <ide> * <del> * @param string $queue <del> * @param string $suffix <add> * @param string $queue <add> * @param string $suffix <ide> * @return string <ide> */ <del> private function suffixQueue($queue, $suffix = '') <add> protected function suffixQueue($queue, $suffix = '') <ide> { <del> $fifo = Str::endsWith($queue, '.fifo') ? '.fifo' : ''; <del> $queue = rtrim($queue, '.fifo'); <del> return rtrim($this->prefix, '/') . '/' . Str::finish($queue, $suffix) . $fifo; <add> if (Str::endsWith($queue, '.fifo')) { <add> $queue = Str::beforeLast($queue, '.fifo'); <add> <add> return rtrim($this->prefix, '/').'/'.Str::finish($queue, $suffix).'.fifo'; <add> } <add> <add> return rtrim($this->prefix, '/').'/'.Str::finish($queue, $this->suffix); <ide> } <ide> <ide> /**
1
Javascript
Javascript
handle writestream errors in sys.pump
f08985c193a7b55e4c82a1681290fb10a9e8471e
<ide><path>lib/sys.js <ide> exports.exec = function () { <ide> <ide> <ide> exports.pump = function (readStream, writeStream, callback) { <add> var callbackCalled = false; <add> <add> function call (a, b, c) { <add> if (callback && !callbackCalled) { <add> callback(a, b, c); <add> callbackCalled = true; <add> } <add> } <add> <ide> if (!readStream.pause) readStream.pause = function () {readStream.emit("pause")}; <ide> if (!readStream.resume) readStream.resume = function () {readStream.emit("resume")}; <ide> <ide> exports.pump = function (readStream, writeStream, callback) { <ide> }); <ide> <ide> readStream.addListener("close", function () { <del> if (callback) callback(); <add> call(); <ide> }); <ide> <del> readStream.addListener("error", function(err) { <add> readStream.addListener("error", function (err) { <ide> writeStream.end(); <del> if (callback) callback(err); <add> call(err); <add> }); <add> <add> writeStream.addListener("error", function (err) { <add> readStream.destroy(); <add> call(err); <ide> }); <ide> }; <ide>
1
Javascript
Javascript
replace global.alert use to fix eslint warnings
55994f5900d1ddb92bc9c37d085d6ac15b1692f8
<ide><path>RNTester/js/AccessibilityIOSExample.js <ide> <ide> const React = require('react'); <ide> const ReactNative = require('react-native'); <del>const {AccessibilityInfo, Text, View, TouchableOpacity} = ReactNative; <add>const {AccessibilityInfo, Text, View, TouchableOpacity, Alert} = ReactNative; <ide> <ide> class AccessibilityIOSExample extends React.Component<{}> { <ide> render() { <ide> return ( <ide> <View> <ide> <View <del> onAccessibilityTap={() => alert('onAccessibilityTap success')} <add> onAccessibilityTap={() => <add> Alert.alert('Alert', 'onAccessibilityTap success') <add> } <ide> accessible={true}> <ide> <Text>Accessibility normal tap example</Text> <ide> </View> <del> <View onMagicTap={() => alert('onMagicTap success')} accessible={true}> <add> <View <add> onMagicTap={() => Alert.alert('Alert', 'onMagicTap success')} <add> accessible={true}> <ide> <Text>Accessibility magic tap example</Text> <ide> </View> <ide> <View accessibilityLabel="Some announcement" accessible={true}> <ide><path>RNTester/js/ActionSheetIOSExample.js <ide> <ide> const React = require('react'); <ide> const ReactNative = require('react-native'); <del>const {ActionSheetIOS, StyleSheet, takeSnapshot, Text, View} = ReactNative; <add>const { <add> ActionSheetIOS, <add> StyleSheet, <add> takeSnapshot, <add> Text, <add> View, <add> Alert, <add>} = ReactNative; <ide> <ide> const BUTTONS = ['Option 0', 'Option 1', 'Option 2', 'Delete', 'Cancel']; <ide> const DESTRUCTIVE_INDEX = 3; <ide> class ShareActionSheetExample extends React.Component< <ide> subject: 'a subject to go in the email heading', <ide> excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'], <ide> }, <del> error => alert(error), <add> error => Alert.alert('Error', error), <ide> (completed, method) => { <ide> let text; <ide> if (completed) { <ide> class ShareScreenshotExample extends React.Component<{}, $FlowFixMeState> { <ide> url: uri, <ide> excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'], <ide> }, <del> error => alert(error), <add> error => Alert.alert('Error', error), <ide> (completed, method) => { <ide> let text; <ide> if (completed) { <ide> class ShareScreenshotExample extends React.Component<{}, $FlowFixMeState> { <ide> }, <ide> ); <ide> }) <del> .catch(error => alert(error)); <add> .catch(error => Alert.alert('Error', error)); <ide> }; <ide> } <ide> <ide><path>RNTester/js/GeolocationExample.js <ide> <ide> const React = require('react'); <ide> const ReactNative = require('react-native'); <del>const {StyleSheet, Text, View} = ReactNative; <add>const {StyleSheet, Text, View, Alert} = ReactNative; <ide> <ide> exports.framework = 'React'; <ide> exports.title = 'Geolocation'; <ide> class GeolocationExample extends React.Component<{}, $FlowFixMeState> { <ide> const initialPosition = JSON.stringify(position); <ide> this.setState({initialPosition}); <ide> }, <del> error => alert(JSON.stringify(error)), <add> error => Alert.alert('Error', JSON.stringify(error)), <ide> {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}, <ide> ); <ide> this.watchID = navigator.geolocation.watchPosition(position => { <ide><path>RNTester/js/MultiColumnExample.js <ide> <ide> const React = require('react'); <ide> const ReactNative = require('react-native'); <del>const {FlatList, StyleSheet, Text, View} = ReactNative; <add>const {FlatList, StyleSheet, Text, View, Alert} = ReactNative; <ide> <ide> const RNTesterPage = require('./RNTesterPage'); <ide> <ide> class MultiColumnExample extends React.PureComponent< <ide> data={filteredData} <ide> key={this.state.numColumns + (this.state.fixedHeight ? 'f' : 'v')} <ide> numColumns={this.state.numColumns || 1} <del> onRefresh={() => alert('onRefresh: nothing to refresh :P')} <add> onRefresh={() => <add> Alert.alert('Alert', 'onRefresh: nothing to refresh :P') <add> } <ide> refreshing={false} <ide> renderItem={this._renderItemComponent} <ide> disableVirtualization={!this.state.virtualized} <ide><path>RNTester/js/TextInputExample.ios.js <ide> const Button = require('Button'); <ide> const InputAccessoryView = require('InputAccessoryView'); <ide> const React = require('react'); <ide> const ReactNative = require('react-native'); <del>const {Text, TextInput, View, StyleSheet, Slider, Switch} = ReactNative; <add>const {Text, TextInput, View, StyleSheet, Slider, Switch, Alert} = ReactNative; <ide> <ide> class WithLabel extends React.Component<$FlowFixMeProps> { <ide> render() { <ide> exports.examples = [ <ide> returnKeyType="next" <ide> blurOnSubmit={true} <ide> multiline={true} <del> onSubmitEditing={event => alert(event.nativeEvent.text)} <add> onSubmitEditing={event => <add> Alert.alert('Alert', event.nativeEvent.text) <add> } <ide> /> <ide> </View> <ide> ); <ide><path>RNTester/js/TransparentHitTestExample.js <ide> <ide> const React = require('react'); <ide> const ReactNative = require('react-native'); <del>const {Text, View, TouchableOpacity} = ReactNative; <add>const {Text, View, TouchableOpacity, Alert} = ReactNative; <ide> <ide> class TransparentHitTestExample extends React.Component<{}> { <ide> render() { <ide> return ( <ide> <View style={{flex: 1}}> <del> <TouchableOpacity onPress={() => alert('Hi!')}> <add> <TouchableOpacity onPress={() => Alert.alert('Alert', 'Hi!')}> <ide> <Text>HELLO!</Text> <ide> </TouchableOpacity> <ide>
6
Java
Java
add additional test for spr-16210
3f3141cddaf878d635318750b49f54147012a137
<ide><path>spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java <ide> * <ide> * @author Phillip Webb <ide> * @author Juergen Hoeller <add> * @author Sebastien Deleuze <ide> */ <ide> @SuppressWarnings("rawtypes") <ide> @RunWith(MockitoJUnitRunner.class) <ide> public void forMethodParameterMustNotBeNull() throws Exception { <ide> ResolvableType.forMethodParameter(null); <ide> } <ide> <add> @Test // SPR-16210 <add> public void forMethodParameterWithSameSignatureAndGenerics() throws Exception { <add> Method method = Methods.class.getMethod("list1"); <add> MethodParameter methodParameter = MethodParameter.forExecutable(method, -1); <add> ResolvableType type = ResolvableType.forMethodParameter(methodParameter); <add> assertThat(((MethodParameter)type.getSource()).getMethod(), equalTo(method)); <add> <add> method = Methods.class.getMethod("list2"); <add> methodParameter = MethodParameter.forExecutable(method, -1); <add> type = ResolvableType.forMethodParameter(methodParameter); <add> assertThat(((MethodParameter)type.getSource()).getMethod(), equalTo(method)); <add> } <add> <ide> @Test <ide> public void forMethodReturn() throws Exception { <ide> Method method = Methods.class.getMethod("charSequenceReturn"); <ide> static class TypedFields extends Fields<String> { <ide> T typedReturn(); <ide> <ide> Set<?> wildcardSet(); <add> <add> List<String> list1(); <add> <add> List<String> list2(); <ide> } <ide> <ide>
1
Ruby
Ruby
fix nested attribute for memory record
cfb5f1b6083d4b0dabaaab70c383d223193811fd
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> def merge_target_lists(persisted, memory) <ide> return memory if persisted.empty? <ide> <ide> persisted.map! do |record| <del> mem_record = memory.delete(record) <add> mem_record_index = memory.index(record) <add> if mem_record_index <add> mem_record = memory.at(mem_record_index) <add> memory.delete_at(mem_record_index) <add> end <ide> <ide> if mem_record <ide> (record.attribute_names - mem_record.changes.keys).each do |name|
1
Javascript
Javascript
remove obsolete todo comments
b180995ebecaf75375838e8982bc86d773cf6360
<ide><path>src/geo/path.js <ide> import "projection"; <ide> import "resample"; <ide> import "stream"; <ide> <del>// TODO better encapsulation for d3_geo_pathArea; move to area.js <del>// TODO better encapsulation for d3_geo_pathCentroid; move to centroid.js <del> <ide> d3.geo.path = function() { <ide> var pointRadius = 4.5, <ide> projection,
1
Ruby
Ruby
add support for with and union
d532b7ee430c5d0c412ab9f1a5e0dd3ebc47f86b
<ide><path>lib/arel/nodes.rb <ide> # unary <ide> require 'arel/nodes/unary' <ide> require 'arel/nodes/unqualified_column' <add>require 'arel/nodes/with' <ide> <ide> # binary <ide> require 'arel/nodes/binary' <ide><path>lib/arel/nodes/binary.rb <ide> def initialize_copy other <ide> NotEqual <ide> NotIn <ide> Or <add> Union <add> UnionAll <ide> }.each do |name| <ide> const_set name, Class.new(Binary) <ide> end <ide><path>lib/arel/nodes/select_statement.rb <ide> module Arel <ide> module Nodes <ide> class SelectStatement < Arel::Nodes::Node <ide> attr_reader :cores <del> attr_accessor :limit, :orders, :lock, :offset <add> attr_accessor :limit, :orders, :lock, :offset, :with, :with_recursive <ide> <ide> def initialize cores = [SelectCore.new] <ide> #puts caller <del> @cores = cores <del> @orders = [] <del> @limit = nil <del> @lock = nil <del> @offset = nil <add> @cores = cores <add> @orders = [] <add> @limit = nil <add> @lock = nil <add> @offset = nil <add> @with = nil <add> @with_recursive = nil <ide> end <ide> <ide> def initialize_copy other <ide><path>lib/arel/nodes/with.rb <add>module Arel <add> module Nodes <add> class With < Arel::Nodes::Unary <add> attr_reader :children <add> alias value children <add> alias expr children <add> <add> def initialize *children <add> @children = children <add> end <add> <add> end <add> <add> class WithRecursive < With; end <add> end <add>end <add> <ide><path>lib/arel/select_manager.rb <ide> def where_sql <ide> Nodes::SqlLiteral.new viz.accept @ctx <ide> end <ide> <add> def union operation, other = nil <add> if operation.is_a? Symbol <add> if operation === :all <add> node_class = Nodes::UnionAll <add> else <add> raise "Only supported UNION operation is :all" <add> end <add> else <add> other = operation <add> node_class = Nodes::Union <add> end <add> <add> node_class.new self.ast, other.ast <add> end <add> <add> def with *subqueries <add> if subqueries.first.is_a? Symbol <add> if subqueries.shift == :recursive <add> node_class = Nodes::WithRecursive <add> else <add> raise "Only supported WITH modifier is :recursive" <add> end <add> else <add> node_class = Nodes::With <add> end <add> @ast.with = node_class.new(*subqueries) <add> end <add> <add> <ide> def take limit <ide> @ast.limit = Nodes::Limit.new(limit) <ide> @ctx.top = Nodes::Top.new(limit) <ide><path>lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_Values o <ide> <ide> def visit_Arel_Nodes_SelectStatement o <ide> [ <add> (visit(o.with) if o.with), <add> (visit(o.with_recursive) if o.with_recursive), <ide> o.cores.map { |x| visit_Arel_Nodes_SelectCore x }.join, <ide> ("ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty?), <ide> (visit(o.limit) if o.limit), <ide> def visit_Arel_Nodes_SelectCore o <ide> ].compact.join ' ' <ide> end <ide> <add> def visit_Arel_Nodes_With o <add> "WITH #{visit o.children}" <add> end <add> <add> def visit_Arel_Nodes_WithRecursive o <add> "WITH RECURSIVE #{visit o.children}" <add> end <add> <add> def visit_Arel_Nodes_Union o <add> "( #{visit o.left} UNION #{visit o.right} )" <add> end <add> <add> def visit_Arel_Nodes_UnionAll o <add> "( #{visit o.left} UNION ALL #{visit o.right} )" <add> end <add> <ide> def visit_Arel_Nodes_Having o <ide> "HAVING #{visit o.expr}" <ide> end <ide><path>test/test_select_manager.rb <ide> def test_join_sources <ide> end <ide> end <ide> <add> describe 'union' do <add> before do <add> table = Table.new :users <add> @m1 = Arel::SelectManager.new Table.engine, table <add> @m1.project Arel.star <add> @m1.where(table[:age].lt(18)) <add> <add> @m2 = Arel::SelectManager.new Table.engine, table <add> @m2.project Arel.star <add> @m2.where(table[:age].gt(99)) <add> <add> <add> end <add> <add> it 'should union two managers' do <add> # FIXME should this union "managers" or "statements" ? <add> # FIXME this probably shouldn't return a node <add> node = @m1.union @m2 <add> <add> # maybe FIXME: decide when wrapper parens are needed <add> node.to_sql.must_be_like %{ <add> ( SELECT * FROM "users" WHERE "users"."age" < 18 UNION SELECT * FROM "users" WHERE "users"."age" > 99 ) <add> } <add> end <add> <add> it 'should union all' do <add> node = @m1.union :all, @m2 <add> <add> node.to_sql.must_be_like %{ <add> ( SELECT * FROM "users" WHERE "users"."age" < 18 UNION ALL SELECT * FROM "users" WHERE "users"."age" > 99 ) <add> } <add> end <add> <add> end <add> <add> describe 'with' do <add> <add> it "should support WITH RECURSIVE" do <add> comments = Table.new(:comments) <add> comments_id = comments[:id] <add> comments_parent_id = comments[:parent_id] <add> <add> replies = Table.new(:replies) <add> replies_id = replies[:id] <add> <add> recursive_term = Arel::SelectManager.new Table.engine <add> recursive_term.from(comments).project(comments_id, comments_parent_id).where(comments_id.eq 42) <add> <add> non_recursive_term = Arel::SelectManager.new Table.engine <add> non_recursive_term.from(comments).project(comments_id, comments_parent_id).join(replies).on(comments_parent_id.eq replies_id) <add> <add> union = recursive_term.union(non_recursive_term) <add> <add> as_statement = Arel::Nodes::As.new replies, union <add> <add> manager = Arel::SelectManager.new Table.engine <add> manager.from replies <add> manager.with :recursive, as_statement <add> manager.project Arel.star <add> <add> sql = manager.to_sql <add> sql.must_be_like %{ <add> WITH RECURSIVE "replies" AS ( <add> SELECT "comments"."id", "comments"."parent_id" FROM "comments" WHERE "comments"."id" = 42 <add> UNION <add> SELECT "comments"."id", "comments"."parent_id" FROM "comments" INNER JOIN "replies" ON "comments"."parent_id" = "replies"."id" <add> ) <add> SELECT * FROM "replies" <add> } <add> end <add> <add> end <add> <ide> describe 'ast' do <ide> it 'should return the ast' do <ide> table = Table.new :users <ide><path>test/visitors/test_postgres.rb <ide> module Visitors <ide> assert_match(/LIMIT 'omg'/, sql) <ide> assert_equal 1, sql.scan(/LIMIT/).length, 'should have one limit' <ide> end <add> <ide> end <ide> end <ide> end
8
Text
Text
add change to actionview notable changes [ci skip]
657cbd64f1d1e9f07f30ea32e15dd8635b1c7b5d
<ide><path>guides/source/4_2_release_notes.md <ide> Please refer to the [Changelog][action-view] for detailed changes. <ide> the hidden fields. <ide> ([Pull Request](https://github.com/rails/rails/pull/14738)) <ide> <add>* Placeholder I18n follows the same convention as `label` I18n. <add> ([Pull Request](https://github.com/rails/rails/pull/16438)) <add> <ide> <ide> Action Mailer <ide> -------------
1
Go
Go
fix issue with plugin scanner going to deep
b27f70d45a0fbb744c17dda02f597ffa6a47d4d9
<ide><path>pkg/plugins/discovery.go <ide> package plugins <ide> <ide> import ( <ide> "encoding/json" <del> "errors" <ide> "fmt" <ide> "io/ioutil" <ide> "net/url" <ide> "os" <ide> "path/filepath" <ide> "strings" <ide> "sync" <add> <add> "github.com/pkg/errors" <ide> ) <ide> <ide> var ( <ide> func newLocalRegistry() localRegistry { <ide> // Scan scans all the plugin paths and returns all the names it found <ide> func Scan() ([]string, error) { <ide> var names []string <del> if err := filepath.Walk(socketsPath, func(path string, fi os.FileInfo, err error) error { <del> if err != nil { <del> return nil <add> dirEntries, err := ioutil.ReadDir(socketsPath) <add> if err != nil && !os.IsNotExist(err) { <add> return nil, errors.Wrap(err, "error reading dir entries") <add> } <add> <add> for _, fi := range dirEntries { <add> if fi.IsDir() { <add> fi, err = os.Stat(filepath.Join(socketsPath, fi.Name(), fi.Name()+".sock")) <add> if err != nil { <add> continue <add> } <ide> } <ide> <ide> if fi.Mode()&os.ModeSocket != 0 { <del> name := strings.TrimSuffix(fi.Name(), filepath.Ext(fi.Name())) <del> names = append(names, name) <add> names = append(names, strings.TrimSuffix(filepath.Base(fi.Name()), filepath.Ext(fi.Name()))) <ide> } <del> return nil <del> }); err != nil { <del> return nil, err <ide> } <ide> <del> for _, path := range specsPaths { <del> if err := filepath.Walk(path, func(p string, fi os.FileInfo, err error) error { <del> if err != nil || fi.IsDir() { <del> return nil <add> for _, p := range specsPaths { <add> dirEntries, err := ioutil.ReadDir(p) <add> if err != nil && !os.IsNotExist(err) { <add> return nil, errors.Wrap(err, "error reading dir entries") <add> } <add> <add> for _, fi := range dirEntries { <add> if fi.IsDir() { <add> infos, err := ioutil.ReadDir(filepath.Join(p, fi.Name())) <add> if err != nil { <add> continue <add> } <add> <add> for _, info := range infos { <add> if strings.TrimSuffix(info.Name(), filepath.Ext(info.Name())) == fi.Name() { <add> fi = info <add> break <add> } <add> } <add> } <add> <add> ext := filepath.Ext(fi.Name()) <add> switch ext { <add> case ".spec", ".json": <add> plugin := strings.TrimSuffix(fi.Name(), ext) <add> names = append(names, plugin) <add> default: <ide> } <del> name := strings.TrimSuffix(fi.Name(), filepath.Ext(fi.Name())) <del> names = append(names, name) <del> return nil <del> }); err != nil { <del> return nil, err <ide> } <ide> } <ide> return names, nil <ide> func (l *localRegistry) Plugin(name string) (*Plugin, error) { <ide> return readPluginInfo(name, p) <ide> } <ide> } <del> return nil, ErrNotFound <add> return nil, errors.Wrapf(ErrNotFound, "could not find plugin %s in v1 plugin registry", name) <ide> } <ide> <ide> func readPluginInfo(name, path string) (*Plugin, error) { <ide><path>pkg/plugins/discovery_unix_test.go <ide> func TestScan(t *testing.T) { <ide> if err != nil { <ide> t.Fatal(err) <ide> } <add> if len(pluginNamesNotEmpty) != 1 { <add> t.Fatalf("expected 1 plugin entry: %v", pluginNamesNotEmpty) <add> } <ide> if p.Name() != pluginNamesNotEmpty[0] { <ide> t.Fatalf("Unable to scan plugin with name %s", p.name) <ide> } <ide> } <add> <add>func TestScanNotPlugins(t *testing.T) { <add> tmpdir, unregister := Setup(t) <add> defer unregister() <add> <add> // not that `Setup()` above sets the sockets path and spec path dirs, which <add> // `Scan()` uses to find plugins to the returned `tmpdir` <add> <add> notPlugin := filepath.Join(tmpdir, "not-a-plugin") <add> if err := os.MkdirAll(notPlugin, 0700); err != nil { <add> t.Fatal(err) <add> } <add> <add> // this is named differently than the dir it's in, so the scanner should ignore it <add> l, err := net.Listen("unix", filepath.Join(notPlugin, "foo.sock")) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer l.Close() <add> <add> // same let's test a spec path <add> f, err := os.Create(filepath.Join(notPlugin, "foo.spec")) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer f.Close() <add> <add> names, err := Scan() <add> if err != nil { <add> t.Fatal(err) <add> } <add> if len(names) != 0 { <add> t.Fatalf("expected no plugins, got %v", names) <add> } <add> <add> // Just as a sanity check, let's make an entry that the scanner should read <add> f, err = os.Create(filepath.Join(notPlugin, "not-a-plugin.spec")) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer f.Close() <add> <add> names, err = Scan() <add> if err != nil { <add> t.Fatal(err) <add> } <add> if len(names) != 1 { <add> t.Fatalf("expected 1 entry in result: %v", names) <add> } <add> if names[0] != "not-a-plugin" { <add> t.Fatalf("expected plugin named `not-a-plugin`, got: %s", names[0]) <add> } <add>} <ide><path>pkg/plugins/plugin_test.go <ide> package plugins <ide> import ( <ide> "bytes" <ide> "encoding/json" <del> "errors" <ide> "io" <ide> "io/ioutil" <ide> "net/http" <ide> import ( <ide> <ide> "github.com/docker/docker/pkg/plugins/transport" <ide> "github.com/docker/go-connections/tlsconfig" <add> "github.com/pkg/errors" <ide> "github.com/stretchr/testify/assert" <ide> ) <ide> <ide> func TestGet(t *testing.T) { <ide> <ide> // check negative case where plugin fruit doesn't implement banana <ide> _, err = Get("fruit", "banana") <del> assert.Equal(t, err, ErrNotImplements) <add> assert.Equal(t, errors.Cause(err), ErrNotImplements) <ide> <ide> // check negative case where plugin vegetable doesn't exist <ide> _, err = Get("vegetable", "potato") <del> assert.Equal(t, err, ErrNotFound) <add> assert.Equal(t, errors.Cause(err), ErrNotFound) <ide> <ide> } <ide>
3
Text
Text
add a note to the changelog
244446fcc52127274d5ad38986bf585c89ba82a5
<ide><path>activerecord/CHANGELOG.md <add>* `has_and_belongs_to_many` is now transparently implemented in terms of <add> `has_many :through`. Behavior should remain the same, if not, it is a bug. <add> <ide> * `create_savepoint`, `rollback_to_savepoint` and `release_savepoint` accept <ide> a savepoint name. <ide>
1
Javascript
Javascript
remove duplicate test
481d940e79f9d01e49218bf76575849158214e28
<ide><path>test/unit/ajax.js <ide> test("serialize()", function() { <ide> }); <ide> <ide> test("jQuery.param()", function() { <del> expect(25); <add> expect(24); <ide> <ide> equals( !jQuery.ajaxSettings.traditional, true, "traditional flag, falsy by default" ); <ide> <ide> test("jQuery.param()", function() { <ide> // #7945 <ide> equals( jQuery.param({"jquery": "1.4.2"}), "jquery=1.4.2", "Check that object with a jQuery property get serialized correctly" ); <ide> <del> equals( jQuery.param(jQuery("#form :input")), "action=Test&text2=Test&radio1=on&radio2=on&check=on&=on&hidden=&foo%5Bbar%5D=&name=name&search=search&button=&=foobar&select1=&select2=3&select3=1&select4=1&select5=3", "Make sure jQuery objects are properly serialized"); <del> <ide> jQuery.ajaxSetup({ traditional: true }); <ide> <ide> var params = {foo:"bar", baz:42, quux:"All your base are belong to us"};
1
Text
Text
remove babelrc from preact example doc
9393440402f089d8371e6a8d7c66b9a42167a3cf
<ide><path>examples/using-preact/README.md <ide> This example uses [Preact](https://github.com/developit/preact) instead of React <ide> <ide> Here's how we did it: <ide> <del>* Create `.babelrc` file with es2015 and react presets. This allow us to get rid of the hard coded React dependency for core Next.js modules. <ide> * Use `next.config.js` to customize our webpack config to support [preact-compat](https://github.com/developit/preact-compat)
1
Python
Python
remove unused variable `_range`
f8aebff8b068fd383ce5c54311f049a06ccad563
<ide><path>celery/platforms.py <ide> import signal as _signal <ide> import sys <ide> import warnings <del>from collections import namedtuple <ide> from contextlib import contextmanager <ide> <ide> from billiard.compat import close_open_fds, get_fdmax <ide> PIDLOCKED = """ERROR: Pidfile ({0}) already exists. <ide> Seems we're already running? (pid: {1})""" <ide> <del>_range = namedtuple('_range', ('start', 'stop')) <del> <ide> ROOT_DISALLOWED = """\ <ide> Running a worker with superuser privileges when the <ide> worker accepts messages serialized with pickle is a very bad idea!
1
Go
Go
fix config cleanup on canceling restartmanager
7bf07737b90f087271b5a9a3a1c8d262c154554f
<ide><path>libcontainerd/container_linux.go <ide> type container struct { <ide> } <ide> <ide> func (ctr *container) clean() error { <add> if os.Getenv("LIBCONTAINERD_NOCLEAN") == "1" { <add> return nil <add> } <ide> if _, err := os.Lstat(ctr.dir); err != nil { <ide> if os.IsNotExist(err) { <ide> return nil <ide> func (ctr *container) handleEvent(e *containerd.Event) error { <ide> ctr.client.deleteContainer(e.Id) <ide> go func() { <ide> err := <-wait <add> ctr.client.lock(ctr.containerID) <add> defer ctr.client.unlock(ctr.containerID) <ide> ctr.restarting = false <ide> if err != nil { <ide> st.State = StateExit <add> ctr.clean() <ide> ctr.client.q.append(e.Id, func() { <ide> if err := ctr.client.backend.StateChanged(e.Id, st); err != nil { <ide> logrus.Error(err) <ide> func (ctr *container) handleEvent(e *containerd.Event) error { <ide> // We need to do so here in case the Message Handler decides to restart it. <ide> switch st.State { <ide> case StateExit: <del> if os.Getenv("LIBCONTAINERD_NOCLEAN") != "1" { <del> ctr.clean() <del> } <add> ctr.clean() <ide> ctr.client.deleteContainer(e.Id) <ide> case StateExitProcess: <ide> ctr.cleanProcess(st.ProcessID)
1
PHP
PHP
check iv length
886d261df0854426b4662b7ed5db6a1c575a4279
<ide><path>src/Illuminate/Encryption/Encrypter.php <ide> protected function getJsonPayload($payload) <ide> */ <ide> protected function validPayload($payload) <ide> { <del> return is_array($payload) && isset( <del> $payload['iv'], $payload['value'], $payload['mac'] <del> ); <add> return is_array($payload) && isset($payload['iv'], $payload['value'], $payload['mac']) && <add> strlen(base64_decode($payload['iv'], true)) === openssl_cipher_iv_length($this->cipher); <ide> } <ide> <ide> /** <ide><path>tests/Encryption/EncrypterTest.php <ide> public function testExceptionThrownWithDifferentKey() <ide> $b = new Encrypter(str_repeat('b', 16)); <ide> $b->decrypt($a->encrypt('baz')); <ide> } <add> <add> /** <add> * @expectedException \Illuminate\Contracts\Encryption\DecryptException <add> * @expectedExceptionMessage The payload is invalid. <add> */ <add> public function testExceptionThrownWhenIvIsTooLong() <add> { <add> $e = new Encrypter(str_repeat('a', 16)); <add> $payload = $e->encrypt('foo'); <add> $data = json_decode(base64_decode($payload), true); <add> $data['iv'] .= $data['value'][0]; <add> $data['value'] = substr($data['value'], 1); <add> $modified_payload = base64_encode(json_encode($data)); <add> $e->decrypt($modified_payload); <add> } <ide> }
2