content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
apply fixes from styleci
e9c65cdd243d802784b193595227bfa29147f367
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php <ide> use Illuminate\Auth\Console\ClearResetsCommand; <ide> use Illuminate\Cache\Console\CacheTableCommand; <ide> use Illuminate\Foundation\Console\ServeCommand; <del>use Illuminate\Queue\Console\FailedTableCommand; <ide> use Illuminate\Foundation\Console\PresetCommand; <add>use Illuminate\Queue\Console\FailedTableCommand; <ide> use Illuminate\Foundation\Console\AppNameCommand; <ide> use Illuminate\Foundation\Console\JobMakeCommand; <ide> use Illuminate\Database\Console\Seeds\SeedCommand;
1
PHP
PHP
remove cheeck for "requestaction()" requests
f5996c3e84886024175f87fe193150c93450ab5b
<ide><path>src/Http/Middleware/CsrfProtectionMiddleware.php <ide> public function __invoke(ServerRequestInterface $request, ResponseInterface $res <ide> $request = $request->withAttribute('params', $params); <ide> } <ide> <del> $requested = $request->getParam('requested'); <del> if ($requested === 1) { <del> return $next($request, $response); <del> } <del> <ide> $method = $request->getMethod(); <ide> if ($method === 'GET' && $cookieData === null) { <ide> list($request, $response) = $this->_setToken($request, $response); <ide><path>tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php <ide> public function testInvalidTokenMissingCookie($method) <ide> $middleware($request, $response, $this->_getNextClosure()); <ide> } <ide> <del> /** <del> * Test that CSRF checks are not applied to request action requests. <del> * <del> * @return void <del> */ <del> public function testCsrfValidationSkipsRequestAction() <del> { <del> $request = new ServerRequest([ <del> 'environment' => ['REQUEST_METHOD' => 'POST'], <del> 'params' => ['requested' => 1], <del> 'post' => ['_csrfToken' => 'nope'], <del> 'cookies' => ['csrfToken' => 'testing123'] <del> ]); <del> $response = new Response(); <del> <del> $closure = function ($request, $response) { <del> $this->assertEquals('testing123', $request->params['_csrfToken']); <del> }; <del> <del> $middleware = new CsrfProtectionMiddleware(); <del> $middleware($request, $response, $closure); <del> } <ide> /** <ide> * Test that the configuration options work. <ide> *
2
Text
Text
update animation docs for createelement
0dd942b1214d1b3cdd3524f9331031024c4ef602
<ide><path>docs/docs/09.1-animation.md <ide> This is called when the `willLeave` `callback` is called (at the same time as `c <ide> By default `ReactTransitionGroup` renders as a `span`. You can change this behavior by providing a `component` prop. For example, here's how you would render a `<ul>`: <ide> <ide> ```javascript{1} <del><ReactTransitionGroup component={React.DOM.ul}> <add><ReactTransitionGroup component="ul"> <ide> ... <ide> </ReactTransitionGroup> <ide> ``` <ide> <del>Every DOM component is under `React.DOM`. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself! <add>Every DOM component that React can render is available for use. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself! <add> <add>> Note: <add>> <add>> Prior to v0.12, when using DOM components, the `component` prop needed to be a reference to `React.DOM.*`. Since the component is simply passed to `React.createElement`, it must now be a string. Composite components must pass the factory. <ide> <ide> Any additional, user-defined, properties will be become properties of the rendered component. For example, here's how you would you render a `<ul>` with css class: <ide> <ide> ```javascript{1} <del><ReactTransitionGroup component={React.DOM.ul} className="animated-list"> <add><ReactTransitionGroup component="ul" className="animated-list"> <ide> ... <ide> </ReactTransitionGroup> <ide> ```
1
Go
Go
add util to fetch container status
5d1cb9d0051c5263e23f06ccb431481f8e5b3d57
<ide><path>integration-cli/docker_utils.go <ide> func getIDByName(name string) (string, error) { <ide> return inspectField(name, "Id") <ide> } <ide> <add>// getContainerState returns the exit code of the container <add>// and true if it's running <add>// the exit code should be ignored if it's running <add>func getContainerState(t *testing.T, id string) (int, bool, error) { <add> var ( <add> exitStatus int <add> running bool <add> ) <add> out, exitCode, err := dockerCmd(t, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id) <add> if err != nil || exitCode != 0 { <add> return 0, false, fmt.Errorf("'%s' doesn't exist: %s", id, err) <add> } <add> <add> out = strings.Trim(out, "\n") <add> splitOutput := strings.Split(out, " ") <add> if len(splitOutput) != 2 { <add> return 0, false, fmt.Errorf("failed to get container state: output is broken") <add> } <add> if splitOutput[0] == "true" { <add> running = true <add> } <add> if n, err := strconv.Atoi(splitOutput[1]); err == nil { <add> exitStatus = n <add> } else { <add> return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer") <add> } <add> <add> return exitStatus, running, nil <add>} <add> <ide> func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) { <ide> args := []string{"build", "-t", name} <ide> if !useCache {
1
Python
Python
add language codes
08b59d10e507d2235de70430da5ae6e19afd90cc
<ide><path>src/transformers/tokenization_bart.py <ide> # limitations under the License. <ide> <ide> import logging <add>from typing import List, Optional <ide> <ide> from .tokenization_roberta import RobertaTokenizer <add>from .tokenization_utils import BatchEncoding <ide> from .tokenization_xlm_roberta import XLMRobertaTokenizer <ide> <ide> <ide> class BartTokenizer(RobertaTokenizer): <ide> <ide> <ide> class MBartTokenizer(XLMRobertaTokenizer): <add> """ <add> This inherits from XLMRobertaTokenizer. ``prepare_translation_batch`` should be used to encode inputs. <add> Other tokenizer methods like encode do not work properly. <add> The tokenization method is <tokens> <eos> <language code>. There is no BOS token. <add> <add> Examples:: <add> from transformers import MBartTokenizer <add> tokenizer = MBartTokenizer.from_pretrained('mbart-large-en-ro') <add> example_english_phrase = " UN Chief Says There Is No Military Solution in Syria" <add> expected_translation_romanian = "Şeful ONU declară că nu există o soluţie militară în Siria" <add> batch: dict = tokenizer.prepare_translation_batch( <add> example_english_phrase, src_lang="en_XX", tgt_lang="ro_RO", tgt_texts=expected_translation_romanian <add> ) <add> """ <add> <ide> vocab_files_names = {"vocab_file": "sentencepiece.bpe.model"} <ide> max_model_input_sizes = {m: 1024 for m in _all_mbart_models} <ide> pretrained_vocab_files_map = {"vocab_file": {m: SPM_URL for m in _all_mbart_models}} <add> lang_code_to_id = { # NOTE(SS): resize embeddings will break this <add> "ar_AR": 250001, <add> "cs_CZ": 250002, <add> "de_DE": 250003, <add> "en_XX": 250004, <add> "es_XX": 250005, <add> "et_EE": 250006, <add> "fi_FI": 250007, <add> "fr_XX": 250008, <add> "gu_IN": 250009, <add> "hi_IN": 250010, <add> "it_IT": 250011, <add> "ja_XX": 250012, <add> "kk_KZ": 250013, <add> "ko_KR": 250014, <add> "lt_LT": 250015, <add> "lv_LV": 250016, <add> "my_MM": 250017, <add> "ne_NP": 250018, <add> "nl_XX": 250019, <add> "ro_RO": 250020, <add> "ru_RU": 250021, <add> "si_LK": 250022, <add> "tr_TR": 250023, <add> "vi_VN": 250024, <add> "zh_CN": 250025, <add> } <add> cur_lang_code = lang_code_to_id["en_XX"] <add> <add> def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> List[int]: <add> """Build model inputs from a sequence by appending eos_token_id.""" <add> special_tokens = [self.eos_token_id, self.cur_lang_code] <add> if token_ids_1 is None: <add> return token_ids_0 + special_tokens <add> # We don't expect to process pairs, but leave the pair logic for API consistency <add> return token_ids_0 + token_ids_1 + special_tokens <add> <add> def prepare_translation_batch( <add> self, <add> src_texts: List[str], <add> src_lang: str = "en_XX", <add> tgt_texts: Optional[List[str]] = None, <add> tgt_lang: str = "ro_RO", <add> max_length: Optional[int] = None, <add> pad_to_max_length: bool = True, <add> return_tensors: str = "pt", <add> ) -> BatchEncoding: <add> """ <add> Arguments: <add> src_texts: list of src language texts <add> src_lang: default en_XX (english) <add> tgt_texts: list of tgt language texts <add> tgt_lang: default ro_RO (romanian) <add> max_length: (None) defer to config (1024 for mbart-large-en-ro) <add> pad_to_max_length: (bool) <add> <add> Returns: <add> dict with keys input_ids, attention_mask, decoder_input_ids, each value is a torch.Tensor. <add> """ <add> if max_length is None: <add> max_length = self.max_len <add> self.cur_lang_code = self.lang_code_to_id[src_lang] <add> model_inputs: BatchEncoding = self.batch_encode_plus( <add> src_texts, <add> add_special_tokens=True, <add> return_tensors=return_tensors, <add> max_length=max_length, <add> pad_to_max_length=pad_to_max_length, <add> ) <add> if tgt_texts is None: <add> return model_inputs <add> self.cur_lang_code = self.lang_code_to_id[tgt_lang] <add> decoder_inputs: BatchEncoding = self.batch_encode_plus( <add> tgt_texts, <add> add_special_tokens=True, <add> return_tensors=return_tensors, <add> max_length=max_length, <add> pad_to_max_length=pad_to_max_length, <add> ) <add> for k, v in decoder_inputs.items(): <add> model_inputs[f"decoder_{k}"] = v <add> self.cur_lang_code = self.lang_code_to_id[src_lang] <add> return model_inputs <ide><path>tests/test_modeling_bart.py <ide> import timeout_decorator # noqa <ide> <ide> from transformers import is_torch_available <add>from transformers.file_utils import cached_property <ide> <ide> from .test_configuration_common import ConfigTester <ide> from .test_modeling_common import ModelTesterMixin, ids_tensor <ide> BartConfig, <ide> BartTokenizer, <ide> MBartTokenizer, <add> BatchEncoding, <ide> ) <ide> from transformers.modeling_bart import ( <ide> BART_PRETRAINED_MODEL_ARCHIVE_LIST, <ide> def test_tiny_model(self): <ide> tiny(**inputs_dict) <ide> <ide> <add>EN_CODE = 250004 <add> <add> <ide> @require_torch <del>class BartTranslationTests(unittest.TestCase): <del> _model = None <add>class MBartIntegrationTests(unittest.TestCase): <add> src_text = [ <add> " UN Chief Says There Is No Military Solution in Syria", <add> " I ate lunch twice yesterday", <add> ] <add> tgt_text = ["Şeful ONU declară că nu există o soluţie militară în Siria", "to be padded"] <add> expected_src_tokens = [8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2, EN_CODE] <ide> <ide> @classmethod <ide> def setUpClass(cls): <ide> checkpoint_name = "facebook/mbart-large-en-ro" <ide> cls.tokenizer = MBartTokenizer.from_pretrained(checkpoint_name) <ide> cls.pad_token_id = 1 <add> return cls <add> <add> @cached_property <add> def model(self): <add> """Only load the model if needed.""" <add> <add> model = BartForConditionalGeneration.from_pretrained("facebook/mbart-large-en-ro").to(torch_device) <add> if "cuda" in torch_device: <add> model = model.half() <add> return model <add> <add> @slow <add> def test_enro_forward(self): <add> model = self.model <ide> net_input = { <ide> "input_ids": _long_tensor( <ide> [ <ide> def setUpClass(cls): <ide> ), <ide> "generation_mode": False, <ide> } <del> net_input["attention_mask"] = net_input["input_ids"].ne(cls.pad_token_id) <del> cls.net_input = net_input <del> <del> return cls <del> <del> @property <del> def model(self): <del> """Only load the model if needed.""" <del> if self._model is None: <del> model = BartForConditionalGeneration.from_pretrained("facebook/mbart-large-en-ro") <del> self._model = model.to(torch_device) <del> return self._model <del> <del> @slow <del> def test_enro_forward(self): <del> model = self.model <add> net_input["attention_mask"] = net_input["input_ids"].ne(self.pad_token_id) <ide> with torch.no_grad(): <del> logits, *other_stuff = model(**self.net_input) <add> logits, *other_stuff = model(**net_input) <ide> <ide> expected_slice = torch.tensor([9.0078, 10.1113, 14.4787], device=torch_device) <ide> result_slice = logits[0][0][:3] <ide> self.assertTrue(torch.allclose(expected_slice, result_slice, atol=TOLERANCE)) <ide> <ide> @slow <ide> def test_enro_generate(self): <del> model = self.model <del> # example_english_phrase = " UN Chief Says There Is No Military Solution in Syria" <del> # inputs: dict = tokenizer.batch_encode_plus([example_english_phrase], return_tensors="pt",) <del> expected_translation_romanian = "Şeful ONU declară că nu există o soluţie militară în Siria" <del> <del> inputs = { <del> "input_ids": torch.LongTensor( <del> [[8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2]] # 250004 <del> ) <del> } <del> translated_tokens = model.generate(input_ids=inputs["input_ids"].to(torch_device), num_beams=5,) <add> inputs: dict = self.tokenizer.prepare_translation_batch([self.src_text[0]]).to(torch_device) <add> translated_tokens = self.model.generate(input_ids=inputs["input_ids"].to(torch_device)) <ide> decoded = self.tokenizer.batch_decode(translated_tokens, skip_special_tokens=True) <del> self.assertEqual(expected_translation_romanian, decoded[0]) <add> self.assertEqual(self.tgt_text[0], decoded[0]) <ide> <ide> def test_mbart_enro_config(self): <ide> mbart_models = ["facebook/mbart-large-en-ro"] <ide> def test_mbart_enro_config(self): <ide> e.args += (name, k) <ide> raise <ide> <del> def test_enro_tokenizer(self): <del> raw = "UN Chief Says There Is No Military Solution in Syria" <del> ids = self.tokenizer.batch_encode_plus([raw])["input_ids"][0] <del> expected_result = [0, 8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2] <del> # TODO(SS): should be [8274, ..., 2, 250020] <del> self.assertListEqual(expected_result, ids) <del> <ide> def test_mbart_fast_forward(self): <ide> config = BartConfig( <ide> vocab_size=99, <ide> def test_mbart_fast_forward(self): <ide> self.assertEqual(logits.shape, expected_shape) <ide> <ide> <add>@require_torch <add>class MBartTokenizerTests(MBartIntegrationTests): <add> def test_enro_tokenizer_prepare_translation_batch(self): <add> batch = self.tokenizer.prepare_translation_batch( <add> self.src_text, tgt_texts=self.tgt_text, max_length=len(self.expected_src_tokens), <add> ) <add> self.assertIsInstance(batch, BatchEncoding) <add> <add> self.assertEqual((2, 14), batch.input_ids.shape) <add> self.assertEqual((2, 14), batch.attention_mask.shape) <add> result = batch.input_ids.tolist()[0] <add> self.assertListEqual(self.expected_src_tokens, result) <add> self.assertEqual(2, batch.decoder_input_ids[0, -2]) # EOS <add> <add> def test_enro_tokenizer_batch_encode_plus(self): <add> ids = self.tokenizer.batch_encode_plus(self.src_text).input_ids[0] <add> self.assertListEqual(self.expected_src_tokens, ids) <add> <add> def test_enro_tokenizer_truncation(self): <add> src_text = ["this is gunna be a long sentence " * 20] <add> assert isinstance(src_text[0], str) <add> desired_max_length = 10 <add> ids = self.tokenizer.prepare_translation_batch( <add> src_text, return_tensors=None, max_length=desired_max_length <add> ).input_ids[0] <add> self.assertEqual(ids[-2], 2) <add> self.assertEqual(ids[-1], EN_CODE) <add> self.assertEqual(len(ids), desired_max_length) <add> <add> <ide> @require_torch <ide> class BartHeadTests(unittest.TestCase): <ide> vocab_size = 99
2
PHP
PHP
add test for find('list') with assocaited table
8e1bf95bfa490567b351f6dd211bb1656455c2b3
<ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testFindListWithVirtualField() <ide> $this->assertEmpty($query->clause('select')); <ide> } <ide> <add> /** <add> * Test find('list') with value field from associated table <add> * <add> * @return void <add> */ <add> public function testFindListWithAssociatedTable() <add> { <add> $articles = new Table([ <add> 'table' => 'articles', <add> 'connection' => $this->connection, <add> ]); <add> <add> $articles->belongsTo('Authors'); <add> $query = $articles->find('list', ['valueField' => 'author.name']) <add> ->contain(['Authors']) <add> ->order('Articles.id'); <add> $this->assertEmpty($query->clause('select')); <add> <add> $expected = [ <add> 1 => 'mariano', <add> 2 => 'larry', <add> 3 => 'mariano', <add> ]; <add> $this->assertSame($expected, $query->toArray()); <add> } <add> <ide> /** <ide> * Test the default entityClass. <ide> *
1
Python
Python
move the rest of the ops to gpu
0d1b00b1e9ff3fbe39735839423e8f15d471e70d
<ide><path>swivel/swivel.py <ide> def __init__(self, config): <ide> sys.stdout.flush() <ide> <ide> # ===== CREATE VARIABLES ====== <del> <del> with tf.device('/cpu:0'): <del> # embeddings <del> self.row_embedding = embeddings_with_init( <del> embedding_dim=config.embedding_size, <del> vocab_size=self.n_rows, <del> name='row_embedding') <del> self.col_embedding = embeddings_with_init( <del> embedding_dim=config.embedding_size, <del> vocab_size=self.n_cols, <del> name='col_embedding') <del> tf.summary.histogram('row_emb', self.row_embedding) <del> tf.summary.histogram('col_emb', self.col_embedding) <del> <del> matrix_log_sum = math.log(np.sum(row_sums) + 1) <del> row_bias_init = [math.log(x + 1) for x in row_sums] <del> col_bias_init = [math.log(x + 1) for x in col_sums] <del> self.row_bias = tf.Variable(row_bias_init, <del> trainable=config.trainable_bias) <del> self.col_bias = tf.Variable(col_bias_init, <del> trainable=config.trainable_bias) <del> tf.summary.histogram('row_bias', self.row_bias) <del> tf.summary.histogram('col_bias', self.col_bias) <add> # embeddings <add> self.row_embedding = embeddings_with_init( <add> embedding_dim=config.embedding_size, <add> vocab_size=self.n_rows, <add> name='row_embedding') <add> self.col_embedding = embeddings_with_init( <add> embedding_dim=config.embedding_size, <add> vocab_size=self.n_cols, <add> name='col_embedding') <add> tf.summary.histogram('row_emb', self.row_embedding) <add> tf.summary.histogram('col_emb', self.col_embedding) <add> <add> matrix_log_sum = math.log(np.sum(row_sums) + 1) <add> row_bias_init = [math.log(x + 1) for x in row_sums] <add> col_bias_init = [math.log(x + 1) for x in col_sums] <add> self.row_bias = tf.Variable( <add> row_bias_init, trainable=config.trainable_bias) <add> self.col_bias = tf.Variable( <add> col_bias_init, trainable=config.trainable_bias) <add> tf.summary.histogram('row_bias', self.row_bias) <add> tf.summary.histogram('col_bias', self.col_bias) <ide> <ide> # ===== CREATE GRAPH ===== <ide> <ide> # Get input <del> with tf.device('/cpu:0'): <del> global_row, global_col, count = count_matrix_input( <del> count_matrix_files, config.submatrix_rows, config.submatrix_cols) <del> <del> # Fetch embeddings. <del> selected_row_embedding = tf.nn.embedding_lookup(self.row_embedding, <del> global_row) <del> selected_col_embedding = tf.nn.embedding_lookup(self.col_embedding, <del> global_col) <del> <del> # Fetch biases. <del> selected_row_bias = tf.nn.embedding_lookup([self.row_bias], global_row) <del> selected_col_bias = tf.nn.embedding_lookup([self.col_bias], global_col) <add> global_row, global_col, count = count_matrix_input( <add> count_matrix_files, config.submatrix_rows, config.submatrix_cols) <add> <add> # Fetch embeddings. <add> selected_row_embedding = tf.nn.embedding_lookup( <add> self.row_embedding, global_row) <add> selected_col_embedding = tf.nn.embedding_lookup( <add> self.col_embedding, global_col) <add> <add> # Fetch biases. <add> selected_row_bias = tf.nn.embedding_lookup([self.row_bias], global_row) <add> selected_col_bias = tf.nn.embedding_lookup([self.col_bias], global_col) <ide> <ide> # Multiply the row and column embeddings to generate predictions. <ide> predictions = tf.matmul(
1
Go
Go
use gotest.tools compare utilities
c207947508d88b9bbb0f2ae044389c9a39788724
<ide><path>integration-cli/docker_cli_plugins_test.go <ide> import ( <ide> "github.com/docker/docker/integration-cli/daemon" <ide> "github.com/docker/docker/testutil/fixtures/plugin" <ide> "gotest.tools/v3/assert" <add> is "gotest.tools/v3/assert/cmp" <ide> "gotest.tools/v3/skip" <ide> ) <ide> <ide> func (ps *DockerPluginSuite) TestPluginBasicOps(c *testing.T) { <ide> <ide> out, _, err := dockerCmdWithError("plugin", "ls") <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, plugin)) <del> assert.Assert(c, strings.Contains(out, "true")) <add> assert.Check(c, is.Contains(out, plugin)) <add> assert.Check(c, is.Contains(out, "true")) <ide> id, _, err := dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", plugin) <ide> id = strings.TrimSpace(id) <ide> assert.NilError(c, err) <ide> <ide> out, _, err = dockerCmdWithError("plugin", "remove", plugin) <ide> assert.ErrorContains(c, err, "") <del> assert.Assert(c, strings.Contains(out, "is enabled")) <add> assert.Check(c, is.Contains(out, "is enabled")) <ide> _, _, err = dockerCmdWithError("plugin", "disable", plugin) <ide> assert.NilError(c, err) <ide> <ide> out, _, err = dockerCmdWithError("plugin", "remove", plugin) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, plugin)) <add> assert.Check(c, is.Contains(out, plugin)) <ide> _, err = os.Stat(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "plugins", id)) <ide> if !os.IsNotExist(err) { <ide> c.Fatal(err) <ide> func (ps *DockerPluginSuite) TestPluginForceRemove(c *testing.T) { <ide> assert.NilError(c, err) <ide> <ide> out, _, _ := dockerCmdWithError("plugin", "remove", pNameWithTag) <del> assert.Assert(c, strings.Contains(out, "is enabled")) <add> assert.Check(c, is.Contains(out, "is enabled")) <ide> out, _, err = dockerCmdWithError("plugin", "remove", "--force", pNameWithTag) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, pNameWithTag)) <add> assert.Check(c, is.Contains(out, pNameWithTag)) <ide> } <ide> <ide> func (s *DockerCLIPluginsSuite) TestPluginActive(c *testing.T) { <ide> func (s *DockerCLIPluginsSuite) TestPluginActive(c *testing.T) { <ide> assert.NilError(c, err) <ide> <ide> out, _, _ := dockerCmdWithError("plugin", "disable", pNameWithTag) <del> assert.Assert(c, strings.Contains(out, "in use")) <add> assert.Check(c, is.Contains(out, "in use")) <ide> _, _, err = dockerCmdWithError("volume", "rm", "testvol1") <ide> assert.NilError(c, err) <ide> <ide> func (s *DockerCLIPluginsSuite) TestPluginActive(c *testing.T) { <ide> <ide> out, _, err = dockerCmdWithError("plugin", "remove", pNameWithTag) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, pNameWithTag)) <add> assert.Check(c, is.Contains(out, pNameWithTag)) <ide> } <ide> <ide> func (s *DockerCLIPluginsSuite) TestPluginActiveNetwork(c *testing.T) { <ide> func (s *DockerCLIPluginsSuite) TestPluginActiveNetwork(c *testing.T) { <ide> nID := strings.TrimSpace(out) <ide> <ide> out, _, _ = dockerCmdWithError("plugin", "remove", npNameWithTag) <del> assert.Assert(c, strings.Contains(out, "is in use")) <add> assert.Check(c, is.Contains(out, "is in use")) <ide> _, _, err = dockerCmdWithError("network", "rm", nID) <ide> assert.NilError(c, err) <ide> <ide> out, _, _ = dockerCmdWithError("plugin", "remove", npNameWithTag) <del> assert.Assert(c, strings.Contains(out, "is enabled")) <add> assert.Check(c, is.Contains(out, "is enabled")) <ide> _, _, err = dockerCmdWithError("plugin", "disable", npNameWithTag) <ide> assert.NilError(c, err) <ide> <ide> out, _, err = dockerCmdWithError("plugin", "remove", npNameWithTag) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, npNameWithTag)) <add> assert.Check(c, is.Contains(out, npNameWithTag)) <ide> } <ide> <ide> func (ps *DockerPluginSuite) TestPluginInstallDisable(c *testing.T) { <ide> pName := ps.getPluginRepoWithTag() <ide> <ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pName) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), pName)) <add> assert.Check(c, is.Contains(out, pName)) <ide> out, _, err = dockerCmdWithError("plugin", "ls") <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, "false")) <add> assert.Check(c, is.Contains(out, "false")) <ide> out, _, err = dockerCmdWithError("plugin", "enable", pName) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), pName)) <add> assert.Check(c, is.Contains(out, pName)) <ide> out, _, err = dockerCmdWithError("plugin", "disable", pName) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), pName)) <add> assert.Check(c, is.Contains(out, pName)) <ide> out, _, err = dockerCmdWithError("plugin", "remove", pName) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), pName)) <add> assert.Check(c, is.Contains(out, pName)) <ide> } <ide> <ide> func (s *DockerCLIPluginsSuite) TestPluginInstallDisableVolumeLs(c *testing.T) { <ide> testRequires(c, DaemonIsLinux, IsAmd64, Network) <ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pName) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), pName)) <add> assert.Check(c, is.Contains(out, pName)) <ide> dockerCmd(c, "volume", "ls") <ide> } <ide> <ide> func (ps *DockerPluginSuite) TestPluginSet(c *testing.T) { <ide> assert.Assert(c, err == nil, "failed to create test plugin") <ide> <ide> env, _ := dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", name) <del> assert.Equal(c, strings.TrimSpace(env), "[DEBUG=0]") <add> assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=0]")) <ide> <ide> dockerCmd(c, "plugin", "set", name, "DEBUG=1") <ide> <ide> env, _ = dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", name) <del> assert.Equal(c, strings.TrimSpace(env), "[DEBUG=1]") <add> assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=1]")) <ide> <ide> env, _ = dockerCmd(c, "plugin", "inspect", "-f", "{{with $mount := index .Settings.Mounts 0}}{{$mount.Source}}{{end}}", name) <del> assert.Assert(c, strings.Contains(strings.TrimSpace(env), mntSrc)) <add> assert.Check(c, is.Contains(env, mntSrc)) <ide> dockerCmd(c, "plugin", "set", name, "pmount1.source=bar") <ide> <ide> env, _ = dockerCmd(c, "plugin", "inspect", "-f", "{{with $mount := index .Settings.Mounts 0}}{{$mount.Source}}{{end}}", name) <del> assert.Assert(c, strings.Contains(strings.TrimSpace(env), "bar")) <add> assert.Check(c, is.Contains(env, "bar")) <ide> out, _, err := dockerCmdWithError("plugin", "set", name, "pmount2.source=bar2") <ide> assert.ErrorContains(c, err, "") <del> assert.Assert(c, strings.Contains(out, "Plugin config has no mount source")) <add> assert.Check(c, is.Contains(out, "Plugin config has no mount source")) <ide> out, _, err = dockerCmdWithError("plugin", "set", name, "pdev2.path=/dev/bar2") <ide> assert.ErrorContains(c, err, "") <del> assert.Assert(c, strings.Contains(out, "Plugin config has no device path")) <add> assert.Check(c, is.Contains(out, "Plugin config has no device path")) <ide> } <ide> <ide> func (ps *DockerPluginSuite) TestPluginInstallArgs(c *testing.T) { <ide> func (ps *DockerPluginSuite) TestPluginInstallArgs(c *testing.T) { <ide> }) <ide> <ide> out, _ := dockerCmd(c, "plugin", "install", "--grant-all-permissions", "--disable", pName, "DEBUG=1") <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), pName)) <add> assert.Check(c, is.Contains(out, pName)) <ide> env, _ := dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", pName) <del> assert.Equal(c, strings.TrimSpace(env), "[DEBUG=1]") <add> assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=1]")) <ide> } <ide> <ide> func (ps *DockerPluginSuite) TestPluginInstallImage(c *testing.T) { <ide> func (ps *DockerPluginSuite) TestPluginInstallImage(c *testing.T) { <ide> <ide> out, _, err := dockerCmdWithError("plugin", "install", repoName) <ide> assert.ErrorContains(c, err, "") <del> assert.Assert(c, strings.Contains(out, `Encountered remote "application/vnd.docker.container.image.v1+json"(image) when fetching`)) <add> assert.Check(c, is.Contains(out, `Encountered remote "application/vnd.docker.container.image.v1+json"(image) when fetching`)) <ide> } <ide> <ide> func (ps *DockerPluginSuite) TestPluginEnableDisableNegative(c *testing.T) { <ide> pName := ps.getPluginRepoWithTag() <ide> <ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pName) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), pName)) <add> assert.Check(c, is.Contains(out, pName)) <ide> out, _, err = dockerCmdWithError("plugin", "enable", pName) <ide> assert.ErrorContains(c, err, "") <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), "already enabled")) <add> assert.Check(c, is.Contains(out, "already enabled")) <ide> _, _, err = dockerCmdWithError("plugin", "disable", pName) <ide> assert.NilError(c, err) <ide> <ide> out, _, err = dockerCmdWithError("plugin", "disable", pName) <ide> assert.ErrorContains(c, err, "") <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), "already disabled")) <add> assert.Check(c, is.Contains(out, "already disabled")) <ide> _, _, err = dockerCmdWithError("plugin", "remove", pName) <ide> assert.NilError(c, err) <ide> } <ide> func (ps *DockerPluginSuite) TestPluginCreate(c *testing.T) { <ide> <ide> out, _, err := dockerCmdWithError("plugin", "create", name, temp) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, name)) <add> assert.Check(c, is.Contains(out, name)) <ide> out, _, err = dockerCmdWithError("plugin", "ls") <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, name)) <add> assert.Check(c, is.Contains(out, name)) <ide> out, _, err = dockerCmdWithError("plugin", "create", name, temp) <ide> assert.ErrorContains(c, err, "") <del> assert.Assert(c, strings.Contains(out, "already exist")) <add> assert.Check(c, is.Contains(out, "already exist")) <ide> out, _, err = dockerCmdWithError("plugin", "ls") <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, name)) <add> assert.Check(c, is.Contains(out, name)) <ide> // The output will consists of one HEADER line and one line of foo/bar-driver <ide> assert.Equal(c, len(strings.Split(strings.TrimSpace(out), "\n")), 2) <ide> } <ide> func (ps *DockerPluginSuite) TestPluginInspect(c *testing.T) { <ide> <ide> out, _, err := dockerCmdWithError("plugin", "ls") <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, pNameWithTag)) <del> assert.Assert(c, strings.Contains(out, "true")) <add> assert.Check(c, is.Contains(out, pNameWithTag)) <add> assert.Check(c, is.Contains(out, "true")) <ide> // Find the ID first <ide> out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", pNameWithTag) <ide> assert.NilError(c, err) <ide> func (ps *DockerPluginSuite) TestPluginInspect(c *testing.T) { <ide> // Long form <ide> out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", id) <ide> assert.NilError(c, err) <del> assert.Equal(c, strings.TrimSpace(out), id) <add> assert.Check(c, is.Equal(strings.TrimSpace(out), id)) <ide> <ide> // Short form <ide> out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", id[:5]) <ide> assert.NilError(c, err) <del> assert.Equal(c, strings.TrimSpace(out), id) <add> assert.Check(c, is.Equal(strings.TrimSpace(out), id)) <ide> <ide> // Name with tag form <ide> out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", pNameWithTag) <ide> assert.NilError(c, err) <del> assert.Equal(c, strings.TrimSpace(out), id) <add> assert.Check(c, is.Equal(strings.TrimSpace(out), id)) <ide> <ide> // Name without tag form <ide> out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", ps.getPluginRepo()) <ide> assert.NilError(c, err) <del> assert.Equal(c, strings.TrimSpace(out), id) <add> assert.Check(c, is.Equal(strings.TrimSpace(out), id)) <ide> <ide> _, _, err = dockerCmdWithError("plugin", "disable", pNameWithTag) <ide> assert.NilError(c, err) <ide> <ide> out, _, err = dockerCmdWithError("plugin", "remove", pNameWithTag) <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, pNameWithTag)) <add> assert.Check(c, is.Contains(out, pNameWithTag)) <ide> // After remove nothing should be found <ide> _, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", id[:5]) <ide> assert.ErrorContains(c, err, "") <ide> func (s *DockerCLIPluginsSuite) TestPluginInspectOnWindows(c *testing.T) { <ide> <ide> out, _, err := dockerCmdWithError("plugin", "inspect", "foobar") <ide> assert.ErrorContains(c, err, "") <del> assert.Assert(c, strings.Contains(out, "plugins are not supported on this platform")) <add> assert.Check(c, is.Contains(out, "plugins are not supported on this platform")) <ide> assert.ErrorContains(c, err, "plugins are not supported on this platform") <ide> } <ide> <ide> func (ps *DockerPluginSuite) TestPluginIDPrefix(c *testing.T) { <ide> // List current state <ide> out, _, err := dockerCmdWithError("plugin", "ls") <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, name)) <del> assert.Assert(c, strings.Contains(out, "false")) <add> assert.Check(c, is.Contains(out, name)) <add> assert.Check(c, is.Contains(out, "false")) <ide> env, _ := dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", id[:5]) <del> assert.Equal(c, strings.TrimSpace(env), "[DEBUG=0]") <add> assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=0]")) <ide> <ide> dockerCmd(c, "plugin", "set", id[:5], "DEBUG=1") <ide> <ide> env, _ = dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", id[:5]) <del> assert.Equal(c, strings.TrimSpace(env), "[DEBUG=1]") <add> assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=1]")) <ide> <ide> // Enable <ide> _, _, err = dockerCmdWithError("plugin", "enable", id[:5]) <ide> assert.NilError(c, err) <ide> out, _, err = dockerCmdWithError("plugin", "ls") <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, name)) <del> assert.Assert(c, strings.Contains(out, "true")) <add> assert.Check(c, is.Contains(out, name)) <add> assert.Check(c, is.Contains(out, "true")) <ide> // Disable <ide> _, _, err = dockerCmdWithError("plugin", "disable", id[:5]) <ide> assert.NilError(c, err) <ide> out, _, err = dockerCmdWithError("plugin", "ls") <ide> assert.NilError(c, err) <del> assert.Assert(c, strings.Contains(out, name)) <del> assert.Assert(c, strings.Contains(out, "false")) <add> assert.Check(c, is.Contains(out, name)) <add> assert.Check(c, is.Contains(out, "false")) <ide> // Remove <ide> _, _, err = dockerCmdWithError("plugin", "remove", id[:5]) <ide> assert.NilError(c, err) <ide> description: test plugin <ide> enabled: false`, id, name) <ide> <ide> out, _ = dockerCmd(c, "--config", config, "plugin", "ls", "--no-trunc") <del> assert.Assert(c, strings.Contains(strings.TrimSpace(out), expectedOutput)) <add> assert.Check(c, is.Contains(out, expectedOutput)) <ide> } <ide> <ide> func (s *DockerCLIPluginsSuite) TestPluginUpgrade(c *testing.T) { <ide> func (s *DockerCLIPluginsSuite) TestPluginUpgrade(c *testing.T) { <ide> <ide> out, _, err := dockerCmdWithError("plugin", "upgrade", "--grant-all-permissions", plugin, pluginV2) <ide> assert.ErrorContains(c, err, "", out) <del> assert.Assert(c, strings.Contains(out, "disabled before upgrading")) <add> assert.Check(c, is.Contains(out, "disabled before upgrading")) <ide> out, _ = dockerCmd(c, "plugin", "inspect", "--format={{.ID}}", plugin) <ide> id := strings.TrimSpace(out) <ide> <ide> func (s *DockerCLIPluginsSuite) TestPluginMetricsCollector(c *testing.T) { <ide> b, err := io.ReadAll(resp.Body) <ide> assert.NilError(c, err) <ide> // check that a known metric is there... don't expect this metric to change over time.. probably safe <del> assert.Assert(c, strings.Contains(string(b), "container_actions")) <add> assert.Check(c, is.Contains(string(b), "container_actions")) <ide> }
1
Javascript
Javascript
avoid materializing arraybuffer for creation
6a0f4636d9f8e94ebe905f0807edd0f5d9fbdd51
<ide><path>lib/buffer.js <ide> let poolSize, poolOffset, allocPool; <ide> const zeroFill = bindingZeroFill || [0]; <ide> <ide> function createUnsafeBuffer(size) { <del> return new FastBuffer(createUnsafeArrayBuffer(size)); <del>} <del> <del>function createUnsafeArrayBuffer(size) { <ide> zeroFill[0] = 0; <ide> try { <del> return new ArrayBuffer(size); <add> return new FastBuffer(size); <ide> } finally { <ide> zeroFill[0] = 1; <ide> } <ide> } <ide> <ide> function createPool() { <ide> poolSize = Buffer.poolSize; <del> allocPool = createUnsafeArrayBuffer(poolSize); <add> allocPool = createUnsafeBuffer(poolSize).buffer; <ide> poolOffset = 0; <ide> } <ide> createPool();
1
Javascript
Javascript
add more valid results to test-trace-atomics-wait
e06037abc4e319d30604000f430e94e6ae5393c1
<ide><path>test/parallel/test-trace-atomics-wait.js <ide> const expectedTimelines = [ <ide> [Thread 0] Atomics.wait(<address> + 4, 0, inf) started <ide> [Thread 1] Atomics.wait(<address> + 4, -1, inf) started <ide> [Thread 0] Atomics.wait(<address> + 4, 0, inf) was woken up by another thread <add>[Thread 1] Atomics.wait(<address> + 4, -1, inf) was woken up by another thread`, <add> `${begin} <add>[Thread 1] Atomics.wait(<address> + 4, 0, inf) started <add>[Thread 0] Atomics.wait(<address> + 4, -1, inf) started <add>[Thread 0] Atomics.wait(<address> + 4, 0, inf) was woken up by another thread <ide> [Thread 1] Atomics.wait(<address> + 4, -1, inf) was woken up by another thread`, <ide> `${begin} <ide> [Thread 0] Atomics.wait(<address> + 4, 0, inf) started <ide> values mismatched`, <ide> [Thread 1] Atomics.wait(<address> + 4, -1, inf) started <ide> [Thread 0] Atomics.wait(<address> + 4, 0, inf) was woken up by another thread <ide> [Thread 1] Atomics.wait(<address> + 4, -1, inf) did not wait because the \ <add>values mismatched`, <add> `${begin} <add>[Thread 1] Atomics.wait(<address> + 4, 0, inf) started <add>[Thread 0] Atomics.wait(<address> + 4, -1, inf) started <add>[Thread 0] Atomics.wait(<address> + 4, 0, inf) was woken up by another thread <add>[Thread 1] Atomics.wait(<address> + 4, -1, inf) did not wait because the \ <ide> values mismatched`, <ide> `${begin} <ide> [Thread 0] Atomics.wait(<address> + 4, 0, inf) started <ide> [Thread 0] Atomics.wait(<address> + 4, 0, inf) did not wait because the \ <ide> values mismatched <ide> [Thread 1] Atomics.wait(<address> + 4, -1, inf) started <ide> [Thread 1] Atomics.wait(<address> + 4, -1, inf) did not wait because the \ <del>values mismatched` <add>values mismatched`, <ide> ]; <ide> <ide> assert(expectedTimelines.includes(actualTimeline));
1
Text
Text
fix typo cppu
5fa89262d87561dd1485b2ab585d4ec2606b3a23
<ide><path>guide/arabic/computer-hardware/cpu/index.md <ide> localeTitle: وحدة المعالجة المركزية <ide> <ide> Gigahertz ليس العامل الوحيد الذي يحدد السرعة الفعلية للمعالج ، حيث أن المعالجات المختلفة بنفس السرعة gigahertz (المعروفة أيضًا بسرعة الساعة) قد تؤدي مهام في العالم الحقيقي بسرعات مختلفة بسبب استخدام مجموعات مختلفة من التعليمات لتنفيذ هذه المهام . تسمى مجموعات التعليمات هذه هندسة CPU. <ide> <del>تستخدم معظم وحدات المعالجة المركزية الحديثة بنية 64 بت ، مما يعني أنها تستخدم عناوين ذاكرة 64 بت طويلة. استخدام وحدات المعالجة المركزية القديمة أبنية 32 بت و 16 بت و 8 بت. أكبر عدد يمكن تخزين 64 بت وحدة المعالجة المركزية هو 18،446،744،073،709،552،000. تحتاج وحدة CPPU إلى عناوين ذاكرة للحصول على قيم محددة من ذاكرة الوصول العشوائي. إذا اتصلنا بطول عناوين الذاكرة n ، فإن 2 ^ n هي كمية خلايا الذاكرة التي يمكن لوحدة المعالجة المركزية (CPU) معالجتها. <add>تستخدم معظم وحدات المعالجة المركزية الحديثة بنية 64 بت ، مما يعني أنها تستخدم عناوين ذاكرة 64 بت طويلة. استخدام وحدات المعالجة المركزية القديمة أبنية 32 بت و 16 بت و 8 بت. أكبر عدد يمكن تخزين 64 بت وحدة المعالجة المركزية هو 18،446،744،073،709،552،000. تحتاج وحدة CPU إلى عناوين ذاكرة للحصول على قيم محددة من ذاكرة الوصول العشوائي. إذا اتصلنا بطول عناوين الذاكرة n ، فإن 2 ^ n هي كمية خلايا الذاكرة التي يمكن لوحدة المعالجة المركزية (CPU) معالجتها. <ide> <ide> تسمى دورة التعليمة الخاصة بوحدة المعالجة المركزية (CPU) دورة تنفيذ - تنفيذ - تنفيذ - حيث يقوم الكمبيوتر باسترداد تعليمة من ذاكرته ، ويحدد التعليمة التي جلبها وما يفعله ، ثم يقوم بتنفيذ instrucitons المذكورة. <ide> <ide> Gigahertz ليس العامل الوحيد الذي يحدد السرعة الف <ide> <ide> #### معلومات اكثر: <ide> <del>[ويكيبيديا](https://en.wikipedia.org/wiki/Central_processing_unit) <ide>\ No newline at end of file <add>[ويكيبيديا](https://en.wikipedia.org/wiki/Central_processing_unit)
1
Javascript
Javascript
show message for legacy donors
81bb677defc6b5fac433597469148b323e7ade4d
<ide><path>client/src/pages/donation/settings.js <ide> export class DonationSettingsPage extends Component { <ide> } <ide> <ide> renderServicebotEmbed() { <add> const { donationEmails } = this.props; <add> if (!donationEmails || donationEmails.length === 0) { <add> return null; <add> } <ide> const { currentSettingsEmail, hash } = this.state; <ide> return ( <ide> <div className='servicebot-embed-panel'> <ide> {!hash || !currentSettingsEmail ? ( <ide> <Panel> <ide> <Spacer /> <ide> <p className='text-center'> <del> Select the email associated to your donations above. <add> Select the email associated with your donations above. <ide> </p> <ide> </Panel> <ide> ) : ( <ide> export class DonationSettingsPage extends Component { <ide> <ide> renderDonationEmailsList() { <ide> const { donationEmails } = this.props; <add> if (!donationEmails || donationEmails.length === 0) { <add> return ( <add> <p> <add> Some of the data associated with your donation is unavailable. Please <add> contact team@freeCodeCamp.org to get your donation updated manually. <add> </p> <add> ); <add> } <ide> return uniq(donationEmails).map(email => ( <ide> <Button <ide> bsStyle='primary'
1
Javascript
Javascript
add .autoupdate to lod
9c0b8a57be4464b30f420357af2cd9308fda0442
<ide><path>src/objects/LOD.js <ide> function LOD() { <ide> } <ide> } ); <ide> <add> this.autoUpdate = true; <add> <ide> } <ide> <ide> LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { <ide><path>src/renderers/WebGLRenderer.js <ide> function WebGLRenderer( parameters ) { <ide> <ide> groupOrder = object.renderOrder; <ide> <add> } else if ( object.isLOD ) { <add> <add> if ( object.autoUpdate ) object.update( camera ); <add> <ide> } else if ( object.isLight ) { <ide> <ide> currentRenderState.pushLight( object );
2
Ruby
Ruby
allow setting of any libpq connection parameters
8ee6406acc67aa721127d69486bf8e244ea6d576
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> module ConnectionHandling <ide> # Establishes a connection to the database that's used by all Active Record objects <ide> def postgresql_connection(config) # :nodoc: <ide> config = config.symbolize_keys <del> host = config[:host] <del> port = config[:port] || 5432 <del> username = config[:username].to_s if config[:username] <del> password = config[:password].to_s if config[:password] <ide> <del> if config.key?(:database) <del> database = config[:database] <del> else <del> raise ArgumentError, "No database specified. Missing argument: database." <del> end <add> # Forward any unused config params to PGconn.connect. <add> conn_params = config.except(:statement_limit, :encoding, :min_messages, <add> :schema_search_path, :schema_order, <add> :adapter, :pool, :wait_timeout) <add> <add> # Map ActiveRecords param names to PGs. <add> conn_params[:user] = conn_params.delete(:username) if conn_params[:username] <add> conn_params[:dbname] = conn_params.delete(:database) if conn_params[:database] <ide> <ide> # The postgres drivers don't allow the creation of an unconnected PGconn object, <ide> # so just pass a nil connection object for the time being. <del> ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, [host, port, nil, nil, database, username, password], config) <add> ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, conn_params, config) <ide> end <ide> end <ide> <ide> def self.extract_value_from_default(default) <ide> end <ide> end <ide> <del> # The PostgreSQL adapter works both with the native C (http://ruby.scripting.ca/postgres/) and the pure <del> # Ruby (available both as gem and from http://rubyforge.org/frs/?group_id=234&release_id=1944) drivers. <add> # The PostgreSQL adapter works with the native C (https://bitbucket.org/ged/ruby-pg) driver. <ide> # <ide> # Options: <ide> # <del> # * <tt>:host</tt> - Defaults to "localhost". <add> # * <tt>:host</tt> - Defaults to a Unix-domain socket in /tmp. On machines without Unix-domain sockets, <add> # the default is to connect to localhost. <ide> # * <tt>:port</tt> - Defaults to 5432. <del> # * <tt>:username</tt> - Defaults to nothing. <del> # * <tt>:password</tt> - Defaults to nothing. <del> # * <tt>:database</tt> - The name of the database. No default, must be provided. <add> # * <tt>:username</tt> - Defaults to be the same as the operating system name of the user running the application. <add> # * <tt>:password</tt> - Password to be used if the server demands password authentication. <add> # * <tt>:database</tt> - Defaults to be the same as the user name. <ide> # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given <ide> # as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option. <ide> # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO <ide> # <encoding></tt> call on the connection. <ide> # * <tt>:min_messages</tt> - An optional client min messages that is used in a <ide> # <tt>SET client_min_messages TO <min_messages></tt> call on the connection. <add> # <add> # Any further options are used as connection parameters to libpq. See <add> # http://www.postgresql.org/docs/9.1/static/libpq-connect.html for the <add> # list of parameters. <add> # <add> # In addition, default connection parameters of libpq can be set per environment variables. <add> # See http://www.postgresql.org/docs/9.1/static/libpq-envars.html . <ide> class PostgreSQLAdapter < AbstractAdapter <ide> class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition <ide> def xml(*args) <ide> def prepare_statement(sql) <ide> # Connects to a PostgreSQL server and sets up the adapter depending on the <ide> # connected server's characteristics. <ide> def connect <del> @connection = PGconn.connect(*@connection_parameters) <add> @connection = PGconn.connect(@connection_parameters) <ide> <ide> # Money type has a fixed precision of 10 in PostgreSQL 8.2 and below, and as of <ide> # PostgreSQL 8.3 it has a fixed precision of 19. PostgreSQLColumn.extract_precision
1
Python
Python
add spacy.info module
e3e25c0a33de8c68f9fe744e92546c18c163b5d3
<ide><path>spacy/info.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <add>import plac <add>import platform <add>import sys <add>from pathlib import Path <add>from . import about <add>from . import util <add> <add> <add>@plac.annotations( <add> model=("Model to download", "positional", None, str), <add> markdown=("Generate Markdown for GitHub issues", "flag", "md", str) <add>) <add>def main(model=None, markdown=False): <add> info(model, markdown) <add> <add> <add>def info(model=None, markdown=False): <add> """Print info about spaCy installation and models for debugging.""" <add> <add> if model: <add> data = util.parse_package_meta(util.get_data_path(), model, require=True) <add> model_path = Path(__file__).parent / util.get_data_path() / model <add> if model_path.resolve() != model_path: <add> data['link'] = str(model_path) <add> data['source'] = str(model_path.resolve()) <add> else: <add> data['source'] = str(model_path) <add> print_info(data, "model " + model, markdown) <add> <add> else: <add> data = get_spacy_data() <add> print_info(data, "spaCy", markdown) <add> <add> <add>def print_info(data, title, markdown): <add> title = "Info about {title}".format(title=title) <add> <add> if markdown: <add> util.print_markdown(data, title=title) <add> <add> else: <add> util.print_table(data, title=title) <add> <add> <add>def get_spacy_data(): <add> return { <add> 'spaCy version': about.__version__, <add> 'Location': str(Path(__file__).parent), <add> 'Platform': platform.platform(), <add> 'Python version': platform.python_version(), <add> 'Installed models': ', '.join(list_models()) <add> } <add> <add> <add>def list_models(): <add> data_path = util.get_data_path() <add> return [f.parts[-1] for f in data_path.iterdir() if f.is_dir()] <add> <add> <add>if __name__ == '__main__': <add> plac.call(main)
1
Javascript
Javascript
fix timeout handling
e05652e535082807b16afe5fbeb53a7a5b47b335
<ide><path>test/configCases/plugins/profiling-plugin/test.config.js <add>module.exports = { <add> timeout: 60000 <add>}; <ide><path>test/helpers/createLazyTestEnv.js <ide> module.exports = (globalTimeout = 2000, nameSuffix = "") => { <ide> describe( <ide> nameSuffix ? `exported tests ${nameSuffix}` : "exported tests", <ide> () => { <del> jest.setTimeout(globalTimeout); <ide> // this must have a child to be handled correctly <ide> it("should run the exported tests", () => { <ide> runTests++; <ide> module.exports = (globalTimeout = 2000, nameSuffix = "") => { <ide> numberOfTests++; <ide> if (runTests >= numberOfTests) throw new Error("it called too late"); <ide> args[1] = createDisposableFn(args[1], true); <add> args[2] = args[2] || globalTimeout; <ide> inSuite(() => { <ide> it(...args); <ide> });
2
Python
Python
add an option to create a static public ip address
cc99a1a937b314dc2663c69d33e5def004bf9375
<ide><path>libcloud/compute/drivers/azure_arm.py <ide> def ex_list_public_ips(self, resource_group): <ide> params={"api-version": "2015-06-15"}) <ide> return [self._to_ip_address(net) for net in r.object["value"]] <ide> <del> def ex_create_public_ip(self, name, resource_group, location=None): <add> def ex_create_public_ip(self, name, resource_group, location=None, <add> publicIPAllocationMethod=None): <ide> """ <ide> Create a public IP resources. <ide> <ide> def ex_create_public_ip(self, name, resource_group, location=None): <ide> (if None, use default location specified as 'region' in __init__) <ide> :type location: :class:`.NodeLocation` <ide> <add> :param publicIPAllocationMethod: Call ex_create_public_ip with <add> publicIPAllocationMethod="Static" to create a static public <add> IP address <add> :type publicIPAllocationMethod: ``str`` <add> <ide> :return: The newly created public ip object <ide> :rtype: :class:`.AzureIPAddress` <ide> """ <ide> def ex_create_public_ip(self, name, resource_group, location=None): <ide> "publicIPAllocationMethod": "Dynamic" <ide> } <ide> } <add> <add> if publicIPAllocationMethod == "Static": <add> data['properties']['publicIPAllocationMethod'] = "Static" <add> <ide> r = self.connection.request(target, <ide> params={"api-version": "2015-06-15"}, <ide> data=data,
1
Python
Python
add test for get_version (cli)
9121e109bdcd8b2a50bf53cac73b470232d126df
<ide><path>tests/test_cli.py <ide> <ide> from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \ <ide> find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \ <del> find_default_import_path <add> find_default_import_path, get_version <ide> <ide> <ide> def test_cli_name(test_apps): <ide> def test_find_default_import_path(test_apps, monkeypatch, tmpdir): <ide> assert find_default_import_path() == expect_rv <ide> <ide> <add>def test_get_version(test_apps, capsys): <add> """Test of get_version.""" <add> from flask import __version__ as flask_ver <add> from sys import version as py_ver <add> class MockCtx(object): <add> resilient_parsing = False <add> color = None <add> def exit(self): return <add> ctx = MockCtx() <add> get_version(ctx, None, "test") <add> out, err = capsys.readouterr() <add> assert flask_ver in out <add> assert py_ver in out <add> <add> <ide> def test_scriptinfo(test_apps): <ide> """Test of ScriptInfo.""" <ide> obj = ScriptInfo(app_import_path="cliapp.app:testapp")
1
Javascript
Javascript
adjust nomenclature (pt)
9cc102d195c234bc644616aac456b5f7859b2947
<ide><path>src/locale/pt.js <ide> import moment from '../moment'; <ide> <ide> export default moment.defineLocale('pt', { <del> months : 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split('_'), <del> monthsShort : 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'), <del> weekdays : 'domingo_segunda-feira_terça-feira_quarta-feira_quinta-feira_sexta-feira_sábado'.split('_'), <del> weekdaysShort : 'dom_seg_ter_qua_qui_sex_sáb'.split('_'), <del> weekdaysMin : 'dom_2ª_3ª_4ª_5ª_6ª_sáb'.split('_'), <add> months : 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'), <add> monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), <add> weekdays : 'Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado'.split('_'), <add> weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), <add> weekdaysMin : 'Dom_2ª_3ª_4ª_5ª_6ª_Sáb'.split('_'), <ide> longDateFormat : { <ide> LT : 'HH:mm', <ide> LTS : 'LT:ss',
1
Ruby
Ruby
add shared method for upgrading casks
b1ca2f7e3c4499d347a831d988e91ea93d01d65e
<ide><path>Library/Homebrew/cask/cmd/upgrade.rb <ide> # frozen_string_literal: true <ide> <add>require "env_config" <ide> require "cask/config" <ide> <ide> module Cask <ide> def initialize(*) <ide> end <ide> <ide> def run <del> outdated_casks = casks(alternative: lambda { <add> self.class.upgrade_casks( <add> *casks, <add> force: force?, <add> greedy: greedy?, <add> dry_run: dry_run?, <add> binaries: binaries?, <add> quarantine: quarantine?, <add> require_sha: require_sha?, <add> skip_cask_deps: skip_cask_deps?, <add> verbose: verbose?, <add> ) <add> end <add> <add> def self.upgrade_casks( <add> *casks, <add> force: false, greedy: false, dry_run: false, binaries: true, skip_cask_deps: false, verbose: false, <add> quarantine: nil, require_sha: nil <add> ) <add> # TODO: Handle this in `CLI::Parser`. <add> quarantine = Homebrew::EnvConfig.cask_opts_quarantine? if quarantine.nil? <add> require_sha = Homebrew::EnvConfig.cask_opts_require_sha? if require_sha.nil? <add> <add> outdated_casks = if casks.empty? <ide> Caskroom.casks.select do |cask| <del> cask.outdated?(greedy?) <add> cask.outdated?(greedy) <ide> end <del> }).select do |cask| <del> raise CaskNotInstalledError, cask unless cask.installed? || force? <add> else <add> casks.select do |cask| <add> raise CaskNotInstalledError, cask unless cask.installed? || force <ide> <del> cask.outdated?(true) <add> cask.outdated?(true) <add> end <ide> end <ide> <ide> if outdated_casks.empty? <ide> oh1 "No Casks to upgrade" <ide> return <ide> end <ide> <del> ohai "Casks with `auto_updates` or `version :latest` will not be upgraded" if args.empty? && !greedy? <del> verb = dry_run? ? "Would upgrade" : "Upgrading" <add> ohai "Casks with `auto_updates` or `version :latest` will not be upgraded" if casks.empty? && !greedy <add> <add> verb = dry_run ? "Would upgrade" : "Upgrading" <ide> oh1 "#{verb} #{outdated_casks.count} #{"outdated package".pluralize(outdated_casks.count)}:" <add> <ide> caught_exceptions = [] <ide> <ide> upgradable_casks = outdated_casks.map { |c| [CaskLoader.load(c.installed_caskfile), c] } <ide> <ide> puts upgradable_casks <ide> .map { |(old_cask, new_cask)| "#{new_cask.full_name} #{old_cask.version} -> #{new_cask.version}" } <ide> .join(", ") <del> return if dry_run? <add> return if dry_run <ide> <ide> upgradable_casks.each do |(old_cask, new_cask)| <del> upgrade_cask(old_cask, new_cask) <add> upgrade_cask( <add> old_cask, new_cask, <add> binaries: binaries, force: force, skip_cask_deps: skip_cask_deps, verbose: verbose, <add> quarantine: quarantine, require_sha: require_sha <add> ) <ide> rescue => e <ide> caught_exceptions << e.exception("#{new_cask.full_name}: #{e}") <ide> next <ide> def run <ide> raise caught_exceptions.first if caught_exceptions.count == 1 <ide> end <ide> <del> def upgrade_cask(old_cask, new_cask) <add> def self.upgrade_cask( <add> old_cask, new_cask, <add> binaries:, force:, quarantine:, require_sha:, skip_cask_deps:, verbose: <add> ) <ide> odebug "Started upgrade process for Cask #{old_cask}" <ide> old_config = old_cask.config <ide> <ide> old_cask_installer = <del> Installer.new(old_cask, binaries: binaries?, <del> verbose: verbose?, <del> force: force?, <add> Installer.new(old_cask, binaries: binaries, <add> verbose: verbose, <add> force: force, <ide> upgrade: true) <ide> <ide> new_cask.config = Config.global.merge(old_config) <ide> <ide> new_cask_installer = <del> Installer.new(new_cask, binaries: binaries?, <del> verbose: verbose?, <del> force: force?, <del> skip_cask_deps: skip_cask_deps?, <del> require_sha: require_sha?, <add> Installer.new(new_cask, binaries: binaries, <add> verbose: verbose, <add> force: force, <add> skip_cask_deps: skip_cask_deps, <add> require_sha: require_sha, <ide> upgrade: true, <del> quarantine: quarantine?) <add> quarantine: quarantine) <ide> <ide> started_upgrade = false <ide> new_artifacts_installed = false <ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade_outdated_formulae(formulae, args:) <ide> end <ide> <ide> def upgrade_outdated_casks(casks, args:) <del> cask_upgrade = Cask::Cmd::Upgrade.new(casks) <del> cask_upgrade.force = args.force? <del> cask_upgrade.dry_run = args.dry_run? <del> cask_upgrade.greedy = args.greedy? <del> cask_upgrade.run <add> Cask::Cmd::Upgrade.upgrade_casks( <add> *casks, <add> force: args.force?, <add> greedy: args.greedy?, <add> dry_run: args.dry_run?, <add> binaries: args.binaries?, <add> quarantine: args.quarantine?, <add> require_sha: args.require_sha?, <add> skip_cask_deps: args.skip_cask_deps?, <add> verbose: args.verbose?, <add> ) <ide> end <ide> end <ide><path>Library/Homebrew/env_config.rb <ide> module EnvConfig <ide> "Linux: `$XDG_CACHE_HOME/Homebrew` or `$HOME/.cache/Homebrew`.", <ide> default: HOMEBREW_DEFAULT_CACHE, <ide> }, <add> HOMEBREW_CASK_OPTS: { <add> description: "Options which should be used for all `cask` commands.", <add> }, <ide> HOMEBREW_CLEANUP_MAX_AGE_DAYS: { <ide> description: "Cleanup all cached files older than this many days.", <ide> default: 120, <ide> def env_method_name(env, hash) <ide> end <ide> elsif hash[:default].present? <ide> # Needs a custom implementation. <del> next if env == "HOMEBREW_MAKE_JOBS" <add> next if ["HOMEBREW_MAKE_JOBS", "HOMEBREW_CASK_OPTS"].include?(env) <ide> <ide> define_method(method_name) do <ide> ENV[env].presence || hash.fetch(:default).to_s <ide> def make_jobs <ide> .call <ide> .to_s <ide> end <add> <add> def cask_opts <add> Shellwords.shellsplit(ENV.fetch("HOMEBREW_CASK_OPTS", "")) <add> end <add> <add> def cask_opts_quarantine? <add> cask_opts.reverse_each do |opt| <add> return true if opt == "--quarantine" <add> return false if opt == "--no-quarantine" <add> end <add> <add> true <add> end <add> <add> def cask_opts_require_sha? <add> cask_opts.include?("--require-sha") <add> end <ide> end <ide> end
3
Javascript
Javascript
fix error handling with async iteration
9c48926dba20a507968d4152fafa9d51d69cf970
<ide><path>lib/internal/streams/async_iterator.js <ide> function onError(iter, err) { <ide> iter[kLastReject] = null; <ide> reject(err); <ide> } <del> iter.error = err; <add> iter[kError] = err; <ide> } <ide> <ide> function wrapForNext(lastPromise, iter) { <ide><path>test/parallel/test-stream-readable-async-iterators.js <ide> async function tests() { <ide> readable.destroy(new Error('kaboom')); <ide> })(); <ide> <add> await (async function() { <add> console.log('call next() after error'); <add> const readable = new Readable({ <add> read() {} <add> }); <add> const iterator = readable[Symbol.asyncIterator](); <add> <add> const err = new Error('kaboom'); <add> readable.destroy(new Error('kaboom')); <add> await assert.rejects(iterator.next.bind(iterator), err); <add> })(); <add> <ide> await (async function() { <ide> console.log('read object mode'); <ide> const max = 42;
2
Javascript
Javascript
fix quaternion.slerp for special case t=0 and t=1
1965a19f3d62f01d54767f94b64612d265991833
<ide><path>src/math/Quaternion.js <ide> THREE.Quaternion.prototype = { <ide> <ide> slerp: function ( qb, t ) { <ide> <add> if (t === 0) { <add> <add> return this; <add> <add> } <add> <add> else if (t === 1) { <add> <add> return this.copy( qb ); <add> <add> } <add> <ide> var x = this._x, y = this._y, z = this._z, w = this._w; <ide> <ide> // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ <ide><path>test/unit/math/Quaternion.js <ide> test( "equals", function() { <ide> ok( a.equals( b ), "Passed!" ); <ide> ok( b.equals( a ), "Passed!" ); <ide> }); <add> <add>test( "slerp", function() { <add> var a = new THREE.Quaternion( 0.675341, 0.408783, 0.328567, 0.518512 ); <add> var b = new THREE.Quaternion( 0.660279, 0.436474, 0.35119, 0.500187 ); <add> <add> ok( a.slerp(b, 0).equals(a), "Passed!" ); <add> ok( a.slerp(b, 1).equals(b), "Passed!" ); <add>});
2
Ruby
Ruby
fix checkout on initial clone
017a5014715d21b8fc8b8aa2d0f42fec1d47f933
<ide><path>Library/Homebrew/download_strategy.rb <ide> def fetch <ide> end <ide> end <ide> <del> def stage <del> ohai "Checking out #{@ref_type} #{@ref}" if @ref_type && @ref <del> end <del> <ide> def cached_location <ide> @clone <ide> end <ide> def fetch_repo(target, url, revision = nil, ignore_externals = false) <ide> args = ["svn", svncommand] <ide> args << url unless target.directory? <ide> args << target <del> args << "-r" << revision if revision <add> if revision <add> ohai "Checking out #{ref}" <add> args << "-r" << revision <add> end <ide> args << "--ignore-externals" if ignore_externals <ide> quiet_safe_system(*args) <ide> end <ide> def clone_repo <ide> safe_system "git", *clone_args <ide> cached_location.cd do <ide> safe_system "git", "config", "homebrew.cacheversion", cache_version <add> checkout <ide> update_submodules if submodules? <ide> end <ide> end <ide> <ide> def checkout <add> ohai "Checking out #{@ref_type} #{@ref}" if @ref_type && @ref <ide> quiet_safe_system "git", "checkout", "-f", @ref, "--" <ide> end <ide> <ide> def stage <ide> dst = Dir.getwd <ide> cached_location.cd do <ide> if @ref_type && @ref <add> ohai "Checking out #{@ref_type} #{@ref}" if @ref_type && @ref <ide> safe_system hgpath, "archive", "--subrepos", "-y", "-r", @ref, "-t", "files", dst <ide> else <ide> safe_system hgpath, "archive", "--subrepos", "-y", "-t", "files", dst
1
Text
Text
fix inaccuracy in https.request docs
ca57912e0529937f736e284e2fb03c9f9bd0d8b0
<ide><path>doc/api/https.md <ide> The options argument has the following options <ide> - `false`: opts out of connection pooling with an Agent, defaults request to <ide> `Connection: close`. <ide> <del>The following options from [`tls.connect()`][] can also be specified. However, a <del>[`globalAgent`][] silently ignores these. <add>The following options from [`tls.connect()`][] can also be specified: <ide> <ide> - `pfx`: Certificate, Private key and CA certificates to use for SSL. Default `null`. <ide> - `key`: Private key to use for SSL. Default `null`.
1
Python
Python
handle more node states in rackspace better
b2f11d9eec4ec9b904d9f964dc38b76f38b4fe67
<ide><path>libcloud/drivers/rackspace.py <ide> class RackspaceNodeDriver(NodeDriver): <ide> features = {"create_node": ["generates_password"]} <ide> <ide> NODE_STATE_MAP = { 'BUILD': NodeState.PENDING, <add> 'REBUILD': NodeState.PENDING, <ide> 'ACTIVE': NodeState.RUNNING, <ide> 'SUSPENDED': NodeState.TERMINATED, <ide> 'QUEUE_RESIZE': NodeState.PENDING, <ide> 'PREP_RESIZE': NodeState.PENDING, <add> 'VERIFY_RESIZE': NodeState.RUNNING, <add> 'PASSWORD': NodeState.PENDING, <ide> 'RESCUE': NodeState.PENDING, <ide> 'REBUILD': NodeState.PENDING, <ide> 'REBOOT': NodeState.REBOOTING, <del> 'HARD_REBOOT': NodeState.REBOOTING} <add> 'HARD_REBOOT': NodeState.REBOOTING, <add> 'SHARE_IP': NodeState.PENDING, <add> 'SHARE_IP_NO_CONFIG': NodeState.PENDING, <add> 'DELETE_IP': NodeState.PENDING, <add> 'UNKNOWN': NodeState.UNKNOWN} <ide> <ide> def list_nodes(self): <ide> return self.to_nodes(self.connection.request('/servers/detail').object) <ide> def get_meta_dict(el): <ide> <ide> n = Node(id=el.get('id'), <ide> name=el.get('name'), <del> state=self.NODE_STATE_MAP.get(el.get('status')), <add> state=self.NODE_STATE_MAP.get(el.get('status'), NodeState.UNKNOWN), <ide> public_ip=public_ip, <ide> private_ip=private_ip, <ide> driver=self.connection.driver,
1
Ruby
Ruby
add methods to architecturelistextension
43f77f6ad085b8dbe0a64da1914326b98d33aed1
<ide><path>Library/Homebrew/utils.rb <ide> module ArchitectureListExtension <ide> def universal? <ide> self.include? :i386 and self.include? :x86_64 <ide> end <add> <add> def remove_ppc! <add> self.delete :ppc7400 <add> self.delete :ppc64 <add> end <add> <add> def as_arch_flags <add> self.collect{ |a| "-arch #{a}" }.join(' ') <add> end <ide> end <ide> <ide> # Returns array of architectures that the given command or library is built for.
1
Javascript
Javascript
move remaining things to named exports
549e41883046def7033a6939ecc9817a22847a61
<ide><path>packages/eslint-plugin-react-hooks/index.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./src/index'); <add>export * from './src/index'; <ide><path>packages/react-art/Circle.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const Circle = require('./npm/Circle'); <del> <del>module.exports = Circle; <add>export {default} from './npm/Circle'; <ide><path>packages/react-art/Rectangle.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const Rectangle = require('./npm/Rectangle'); <del> <del>module.exports = Rectangle; <add>export {default} from './npm/Rectangle'; <ide><path>packages/react-art/Wedge.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const Wedge = require('./npm/Wedge'); <del> <del>module.exports = Wedge; <add>export {default} from './npm/Wedge'; <ide><path>packages/react-art/index.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const ReactART = require('./src/ReactART'); <del> <del>module.exports = ReactART; <add>export * from './src/ReactART'; <ide><path>packages/react-art/src/__tests__/ReactART-test.js <ide> <ide> 'use strict'; <ide> <del>const React = require('react'); <add>import * as React from 'react'; <add> <add>import * as ReactART from 'react-art'; <add>import ARTSVGMode from 'art/modes/svg'; <add>import ARTCurrentMode from 'art/modes/current'; <add>// Since these are default exports, we need to import them using ESM. <add>// Since they must be on top, we need to import this before ReactDOM. <add>import Circle from 'react-art/Circle'; <add>import Rectangle from 'react-art/Rectangle'; <add>import Wedge from 'react-art/Wedge'; <add> <add>// Isolate DOM renderer. <add>jest.resetModules(); <ide> const ReactDOM = require('react-dom'); <ide> const ReactTestUtils = require('react-dom/test-utils'); <ide> <ide> // Isolate test renderer. <ide> jest.resetModules(); <ide> const ReactTestRenderer = require('react-test-renderer'); <ide> <del>// Isolate ART renderer. <del>jest.resetModules(); <del>const ReactART = require('react-art'); <del>const ARTSVGMode = require('art/modes/svg'); <del>const ARTCurrentMode = require('art/modes/current'); <del>const Circle = require('react-art/Circle'); <del>const Rectangle = require('react-art/Rectangle'); <del>const Wedge = require('react-art/Wedge'); <del> <ide> // Isolate the noop renderer <ide> jest.resetModules(); <ide> const ReactNoop = require('react-noop-renderer'); <ide><path>packages/react-debug-tools/index.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <del>const ReactDebugTools = require('./src/ReactDebugTools'); <del> <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactDebugTools.default || ReactDebugTools; <add>export * from './src/ReactDebugTools'; <ide><path>packages/react-flight-dom-webpack/index.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const ReactFlightDOMClient = require('./src/ReactFlightDOMClient'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest <del>module.exports = ReactFlightDOMClient.default || ReactFlightDOMClient; <add>export * from './src/ReactFlightDOMClient'; <ide><path>packages/react-flight-dom-webpack/server.browser.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const ReactFlightDOMServerBrowser = require('./src/ReactFlightDOMServerBrowser'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest <del>module.exports = <del> ReactFlightDOMServerBrowser.default || ReactFlightDOMServerBrowser; <add>export * from './src/ReactFlightDOMServerBrowser'; <ide><path>packages/react-flight-dom-webpack/server.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./server.node'); <add>export * from './server.node'; <ide><path>packages/react-flight-dom-webpack/server.node.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const ReactFlightDOMServerNode = require('./src/ReactFlightDOMServerNode'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest <del>module.exports = ReactFlightDOMServerNode.default || ReactFlightDOMServerNode; <add>export * from './src/ReactFlightDOMServerNode'; <ide><path>packages/react-flight-dom-webpack/src/ReactFlightDOMClient.js <ide> function readFromXHR<T>(request: XMLHttpRequest): ReactModelRoot<T> { <ide> return getModelRoot(response); <ide> } <ide> <del>export default { <del> readFromXHR, <del> readFromFetch, <del> readFromReadableStream, <del>}; <add>export {readFromXHR, readFromFetch, readFromReadableStream}; <ide><path>packages/react-flight-dom-webpack/src/ReactFlightDOMServerBrowser.js <ide> function renderToReadableStream(model: ReactModel): ReadableStream { <ide> }); <ide> } <ide> <del>export default { <del> renderToReadableStream, <del>}; <add>export {renderToReadableStream}; <ide><path>packages/react-flight-dom-webpack/src/ReactFlightDOMServerNode.js <ide> function pipeToNodeWritable(model: ReactModel, destination: Writable): void { <ide> startWork(request); <ide> } <ide> <del>export default { <del> pipeToNodeWritable, <del>}; <add>export {pipeToNodeWritable}; <ide><path>packages/react-flight/index.js <ide> // `react-server/inline-typed` (which *is*) for the current renderer. <ide> // On CI, we run Flow checks for each renderer separately. <ide> <del>'use strict'; <del> <del>const ReactFlightClient = require('./src/ReactFlightClient'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactFlightClient.default || ReactFlightClient; <add>export * from './src/ReactFlightClient'; <ide><path>packages/react-interactions/events/context-menu.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./src/dom/ContextMenu'); <add>export * from './src/dom/ContextMenu'; <ide><path>packages/react-interactions/events/focus.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./src/dom/Focus'); <add>export * from './src/dom/Focus'; <ide><path>packages/react-interactions/events/hover.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./src/dom/Hover'); <add>export * from './src/dom/Hover'; <ide><path>packages/react-interactions/events/input.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./src/dom/Input'); <add>export * from './src/dom/Input'; <ide><path>packages/react-interactions/events/keyboard.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./src/dom/Keyboard'); <add>export * from './src/dom/Keyboard'; <ide><path>packages/react-interactions/events/press-legacy.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./src/dom/PressLegacy'); <add>export * from './src/dom/PressLegacy'; <ide><path>packages/react-interactions/events/press.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./src/dom/Press'); <add>export * from './src/dom/Press'; <ide><path>packages/react-interactions/events/tap.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>module.exports = require('./src/dom/Tap'); <add>export * from './src/dom/Tap'; <ide><path>packages/react-noop-renderer/flight-client.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const ReactNoopFlightClient = require('./src/ReactNoopFlightClient'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactNoopFlightClient.default || ReactNoopFlightClient; <add>export * from './src/ReactNoopFlightClient'; <ide><path>packages/react-noop-renderer/flight-server.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const ReactNoopFlightServer = require('./src/ReactNoopFlightServer'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactNoopFlightServer.default || ReactNoopFlightServer; <add>export * from './src/ReactNoopFlightServer'; <ide><path>packages/react-noop-renderer/index.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const ReactNoop = require('./src/ReactNoop'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactNoop.default || ReactNoop; <add>export * from './src/ReactNoop'; <ide><path>packages/react-noop-renderer/persistent.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const ReactNoopPersistent = require('./src/ReactNoopPersistent'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactNoopPersistent.default || ReactNoopPersistent; <add>export * from './src/ReactNoopPersistent'; <ide><path>packages/react-noop-renderer/server.js <ide> * @flow <ide> */ <ide> <del>'use strict'; <del> <del>const ReactNoopServer = require('./src/ReactNoopServer'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactNoopServer.default || ReactNoopServer; <add>export * from './src/ReactNoopServer'; <ide><path>packages/react-noop-renderer/src/ReactNoop.js <ide> import ReactFiberReconciler from 'react-reconciler'; <ide> import createReactNoop from './createReactNoop'; <ide> <del>const ReactNoop = createReactNoop( <add>export const { <add> _Scheduler, <add> getChildren, <add> getPendingChildren, <add> getOrCreateRootContainer, <add> createRoot, <add> createBlockingRoot, <add> getChildrenAsJSX, <add> getPendingChildrenAsJSX, <add> createPortal, <add> render, <add> renderLegacySyncRoot, <add> renderToRootWithID, <add> unmountRootWithID, <add> findInstance, <add> flushNextYield, <add> flushWithHostCounters, <add> expire, <add> flushExpired, <add> batchedUpdates, <add> deferredUpdates, <add> unbatchedUpdates, <add> discreteUpdates, <add> flushDiscreteUpdates, <add> flushSync, <add> flushPassiveEffects, <add> act, <add> dumpTree, <add> getRoot, <add>} = createReactNoop( <ide> ReactFiberReconciler, // reconciler <ide> true, // useMutation <ide> ); <del> <del>export default ReactNoop; <ide><path>packages/react-noop-renderer/src/ReactNoopFlightClient.js <ide> function read<T>(source: Source): ReactModelRoot<T> { <ide> return getModelRoot(response); <ide> } <ide> <del>export default { <del> read, <del>}; <add>export {read}; <ide><path>packages/react-noop-renderer/src/ReactNoopFlightServer.js <ide> function render(model: ReactModel): Destination { <ide> return destination; <ide> } <ide> <del>export default { <del> render, <del>}; <add>export {render}; <ide><path>packages/react-noop-renderer/src/ReactNoopPersistent.js <ide> import ReactFiberPersistentReconciler from 'react-reconciler/persistent'; <ide> import createReactNoop from './createReactNoop'; <ide> <del>const ReactNoopPersistent = createReactNoop( <add>export const { <add> _Scheduler, <add> getChildren, <add> getPendingChildren, <add> getOrCreateRootContainer, <add> createRoot, <add> createBlockingRoot, <add> getChildrenAsJSX, <add> getPendingChildrenAsJSX, <add> createPortal, <add> render, <add> renderLegacySyncRoot, <add> renderToRootWithID, <add> unmountRootWithID, <add> findInstance, <add> flushNextYield, <add> flushWithHostCounters, <add> expire, <add> flushExpired, <add> batchedUpdates, <add> deferredUpdates, <add> unbatchedUpdates, <add> discreteUpdates, <add> flushDiscreteUpdates, <add> flushSync, <add> flushPassiveEffects, <add> act, <add> dumpTree, <add> getRoot, <add>} = createReactNoop( <ide> ReactFiberPersistentReconciler, // reconciler <ide> false, // useMutation <ide> ); <del> <del>export default ReactNoopPersistent; <ide><path>packages/react-noop-renderer/src/ReactNoopServer.js <ide> function render(children: React$Element<any>): Destination { <ide> return destination; <ide> } <ide> <del>export default { <del> render, <del>}; <add>export {render}; <ide><path>packages/react-reconciler/index.js <ide> // `react-reconciler/inline-typed` (which *is*) for the current renderer. <ide> // On CI, we run Flow checks for each renderer separately. <ide> <del>'use strict'; <del> <del>const ReactFiberReconciler = require('./src/ReactFiberReconciler'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactFiberReconciler.default || ReactFiberReconciler; <add>export * from './src/ReactFiberReconciler'; <ide><path>packages/react-reconciler/persistent.js <ide> <ide> // This is the same export as in index.js, <ide> // with persistent reconciler flags turned on. <del>const ReactFiberReconciler = require('./src/ReactFiberReconciler'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactFiberReconciler.default || ReactFiberReconciler; <add>export * from './src/ReactFiberReconciler'; <ide><path>packages/react-refresh/babel.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <del>const ReactFreshBabelPlugin = require('./src/ReactFreshBabelPlugin'); <del> <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactFreshBabelPlugin.default || ReactFreshBabelPlugin; <add>export {default} from './src/ReactFreshBabelPlugin'; <ide><path>packages/react-refresh/runtime.js <ide> * LICENSE file in the root directory of this source tree. <ide> */ <ide> <del>'use strict'; <del> <del>const ReactFreshRuntime = require('./src/ReactFreshRuntime'); <del> <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactFreshRuntime.default || ReactFreshRuntime; <add>export * from './src/ReactFreshRuntime'; <ide><path>packages/react-server/flight.js <ide> // `react-server/flight.inline-typed` (which *is*) for the current renderer. <ide> // On CI, we run Flow checks for each renderer separately. <ide> <del>'use strict'; <del> <del>const ReactFlightServer = require('./src/ReactFlightServer'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactFlightServer.default || ReactFlightServer; <add>export * from './src/ReactFlightServer'; <ide><path>packages/react-server/index.js <ide> // `react-server/inline-typed` (which *is*) for the current renderer. <ide> // On CI, we run Flow checks for each renderer separately. <ide> <del>'use strict'; <del> <del>const ReactFizzStreamer = require('./src/ReactFizzStreamer'); <del> <del>// TODO: decide on the top-level export form. <del>// This is hacky but makes it work with both Rollup and Jest. <del>module.exports = ReactFizzStreamer.default || ReactFizzStreamer; <add>export * from './src/ReactFizzStreamer'; <ide><path>scripts/rollup/wrappers.js <ide> ${license} <ide> <ide> if (process.env.NODE_ENV !== "production") { <ide> module.exports = function $$$reconciler($$$hostConfig) { <add> var exports = {}; <ide> ${source} <del> var $$$renderer = module.exports; <del> module.exports = $$$reconciler; <del> return $$$renderer; <add> return exports; <ide> }; <ide> }`; <ide> }, <ide> ${source} <ide> ${license} <ide> */ <ide> module.exports = function $$$reconciler($$$hostConfig) { <add> var exports = {}; <ide> ${source} <del> var $$$renderer = module.exports; <del> module.exports = $$$reconciler; <del> return $$$renderer; <add> return exports; <ide> };`; <ide> }, <ide> };
40
Java
Java
remove an unnecessary intermediate variable
826db885093360e8dd27f3ef566c392af1e01aa9
<ide><path>spring-web/src/main/java/org/springframework/web/filter/AbstractRequestLoggingFilter.java <ide> protected String createMessage(HttpServletRequest request, String prefix, String <ide> protected String getMessagePayload(HttpServletRequest request) { <ide> ContentCachingRequestWrapper wrapper = <ide> WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); <del> String payload = null; <ide> if (wrapper != null) { <ide> byte[] buf = wrapper.getContentAsByteArray(); <ide> if (buf.length > 0) { <ide> int length = Math.min(buf.length, getMaxPayloadLength()); <ide> try { <del> payload = new String(buf, 0, length, wrapper.getCharacterEncoding()); <add> return new String(buf, 0, length, wrapper.getCharacterEncoding()); <ide> } <ide> catch (UnsupportedEncodingException ex) { <del> payload = "[unknown]"; <add> return "[unknown]"; <ide> } <ide> } <ide> } <del> return payload; <add> return null; <ide> } <ide> <ide>
1
PHP
PHP
apply fixes from styleci
50e60dc6a0239a38d533efc00efe8e16de8605c9
<ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testGetOriginalCastsAttributes() <ide> 'foo' => 'bar2', <ide> ]; <ide> $model->collectionAttribute = collect([ <del> 'foo' => 'bar2' <add> 'foo' => 'bar2', <ide> ]); <ide> <ide> $this->assertIsInt($model->getOriginal('intAttribute'));
1
PHP
PHP
update enumerable interface
0c710c5769ed8bb8e5c487c9885afec9be96f76e
<ide><path>src/Illuminate/Collections/Enumerable.php <ide> public function splitIn($numberOfGroups); <ide> /** <ide> * Sort through each item with a callback. <ide> * <del> * @param (callable(TValue, TValue): bool)|null|int $callback <add> * @param (callable(TValue, TValue): int)|null|int $callback <ide> * @return static <ide> */ <ide> public function sort($callback = null);
1
Ruby
Ruby
avoid postgres 9.x syntax
51c2ef0b819d4732fff59cf1a86336dac38f2280
<ide><path>activerecord/test/cases/adapters/postgresql/schema_test.rb <ide> def teardown <ide> end <ide> <ide> def test_schema_change_with_prepared_stmt <add> altered = false <ide> @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]] <ide> @connection.exec_query "alter table developers add column zomg int", 'sql', [] <add> altered = true <ide> @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]] <ide> ensure <del> @connection.exec_query "alter table developers drop column if exists zomg", 'sql', [] <add> # We are not using DROP COLUMN IF EXISTS because that syntax is only <add> # supported by pg 9.X <add> @connection.exec_query("alter table developers drop column zomg", 'sql', []) if altered <ide> end <ide> <ide> def test_table_exists?
1
Javascript
Javascript
add spec for dialogmanagerandroid
32340d377bb1f9492a640ef543ffdb0440b17c16
<ide><path>Libraries/Alert/Alert.js <ide> <ide> 'use strict'; <ide> <del>const NativeModules = require('../BatchedBridge/NativeModules'); <add>import NativeModules from '../BatchedBridge/NativeModules'; <add>import Platform from '../Utilities/Platform'; <add>import DialogManagerAndroid, { <add> type DialogOptions, <add>} from '../NativeModules/specs/NativeDialogManagerAndroid'; <add> <ide> const RCTAlertManager = NativeModules.AlertManager; <del>const Platform = require('../Utilities/Platform'); <ide> <ide> export type Buttons = Array<{ <ide> text?: string, <ide> class Alert { <ide> if (Platform.OS === 'ios') { <ide> Alert.prompt(title, message, buttons, 'default'); <ide> } else if (Platform.OS === 'android') { <del> let config = { <add> if (!DialogManagerAndroid) { <add> return; <add> } <add> const constants = DialogManagerAndroid.getConstants(); <add> <add> const config: DialogOptions = { <ide> title: title || '', <ide> message: message || '', <ide> cancelable: false, <ide> }; <ide> <del> if (options) { <del> config = {...config, cancelable: options.cancelable}; <add> if (options && options.cancelable) { <add> config.cancelable = options.cancelable; <ide> } <ide> // At most three buttons (neutral, negative, positive). Ignore rest. <ide> // The text 'OK' should be probably localized. iOS Alert does that in native. <ide> class Alert { <ide> const buttonPositive = validButtons.pop(); <ide> const buttonNegative = validButtons.pop(); <ide> const buttonNeutral = validButtons.pop(); <add> <ide> if (buttonNeutral) { <del> config = {...config, buttonNeutral: buttonNeutral.text || ''}; <add> config.buttonNeutral = buttonNeutral.text || ''; <ide> } <ide> if (buttonNegative) { <del> config = {...config, buttonNegative: buttonNegative.text || ''}; <add> config.buttonNegative = buttonNegative.text || ''; <ide> } <ide> if (buttonPositive) { <del> config = {...config, buttonPositive: buttonPositive.text || ''}; <add> config.buttonPositive = buttonPositive.text || ''; <ide> } <del> NativeModules.DialogManagerAndroid.showAlert( <del> config, <del> errorMessage => console.warn(errorMessage), <del> (action, buttonKey) => { <del> if (action === NativeModules.DialogManagerAndroid.buttonClicked) { <del> if ( <del> buttonKey === NativeModules.DialogManagerAndroid.buttonNeutral <del> ) { <del> buttonNeutral.onPress && buttonNeutral.onPress(); <del> } else if ( <del> buttonKey === NativeModules.DialogManagerAndroid.buttonNegative <del> ) { <del> buttonNegative.onPress && buttonNegative.onPress(); <del> } else if ( <del> buttonKey === NativeModules.DialogManagerAndroid.buttonPositive <del> ) { <del> buttonPositive.onPress && buttonPositive.onPress(); <del> } <del> } else if (action === NativeModules.DialogManagerAndroid.dismissed) { <del> options && options.onDismiss && options.onDismiss(); <add> <add> const onAction = (action, buttonKey) => { <add> if (action === constants.buttonClicked) { <add> if (buttonKey === constants.buttonNeutral) { <add> buttonNeutral.onPress && buttonNeutral.onPress(); <add> } else if (buttonKey === constants.buttonNegative) { <add> buttonNegative.onPress && buttonNegative.onPress(); <add> } else if (buttonKey === constants.buttonPositive) { <add> buttonPositive.onPress && buttonPositive.onPress(); <ide> } <del> }, <del> ); <add> } else if (action === constants.dismissed) { <add> options && options.onDismiss && options.onDismiss(); <add> } <add> }; <add> const onError = errorMessage => console.warn(errorMessage); <add> DialogManagerAndroid.showAlert(config, onError, onAction); <ide> } <ide> } <ide> <ide><path>Libraries/Alert/RCTAlertManager.android.js <ide> <ide> 'use strict'; <ide> <del>const NativeModules = require('../BatchedBridge/NativeModules'); <add>import NativeDialogManagerAndroid from '../NativeModules/specs/NativeDialogManagerAndroid'; <ide> <ide> function emptyCallback() {} <ide> <ide> module.exports = { <ide> alertWithArgs: function(args, callback) { <ide> // TODO(5998984): Polyfill it correctly with DialogManagerAndroid <del> NativeModules.DialogManagerAndroid.showAlert( <add> if (!NativeDialogManagerAndroid) { <add> return; <add> } <add> <add> NativeDialogManagerAndroid.showAlert( <ide> args, <ide> emptyCallback, <ide> callback || emptyCallback, <ide><path>Libraries/NativeModules/specs/NativeDialogManagerAndroid.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow strict-local <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <add>/* 'buttonClicked' | 'dismissed' */ <add>type DialogAction = string; <add>/* <add> buttonPositive = -1, <add> buttonNegative = -2, <add> buttonNeutral = -3 <add>*/ <add>type DialogButtonKey = number; <add>export type DialogOptions = {| <add> title?: string, <add> message?: string, <add> buttonPositive?: string, <add> buttonNegative?: string, <add> buttonNeutral?: string, <add> items?: Array<string>, <add> cancelable?: boolean, <add>|}; <add> <add>export interface Spec extends TurboModule { <add> +getConstants: () => {| <add> +buttonClicked: DialogAction, <add> +dismissed: DialogAction, <add> +buttonPositive: DialogButtonKey, <add> +buttonNegative: DialogButtonKey, <add> +buttonNeutral: DialogButtonKey, <add> |}; <add> +showAlert: ( <add> config: DialogOptions, <add> onError: (string) => void, <add> onAction: (action: DialogAction, buttonKey?: DialogButtonKey) => void, <add> ) => void; <add>} <add> <add>export default TurboModuleRegistry.get<Spec>('DialogManagerAndroid'); <ide><path>Libraries/PermissionsAndroid/PermissionsAndroid.js <ide> <ide> 'use strict'; <ide> <add>import NativeDialogManagerAndroid from '../NativeModules/specs/NativeDialogManagerAndroid'; <ide> const NativeModules = require('../BatchedBridge/NativeModules'); <ide> <ide> export type Rationale = { <ide> class PermissionsAndroid { <ide> permission, <ide> ); <ide> <del> if (shouldShowRationale) { <add> if (shouldShowRationale && !!NativeDialogManagerAndroid) { <ide> return new Promise((resolve, reject) => { <del> NativeModules.DialogManagerAndroid.showAlert( <del> rationale, <add> const options = { <add> ...rationale, <add> }; <add> NativeDialogManagerAndroid.showAlert( <add> options, <ide> () => reject(new Error('Error showing rationale')), <ide> () => <ide> resolve(
4
PHP
PHP
fix warnings in http/client tests
792f1b97e17b4fc14dab0906693170419d98613e
<ide><path>src/Http/Client.php <ide> use Cake\Core\App; <ide> use Cake\Core\Exception\Exception; <ide> use Cake\Core\InstanceConfigTrait; <del>use Cake\Http\Client\CookieCollection; <ide> use Cake\Http\Client\Request; <add>use Cake\Http\Cookie\CookieCollection; <ide> use Cake\Http\Cookie\CookieInterface; <ide> use Cake\Utility\Hash; <ide> use InvalidArgumentException; <ide><path>src/Http/Client/Adapter/Stream.php <ide> protected function _buildContent(Request $request, $options) <ide> */ <ide> protected function _buildOptions(Request $request, $options) <ide> { <del> $this->_contextOptions['method'] = $request->method(); <del> $this->_contextOptions['protocol_version'] = $request->version(); <add> $this->_contextOptions['method'] = $request->getMethod(); <add> $this->_contextOptions['protocol_version'] = $request->getProtocolVersion(); <ide> $this->_contextOptions['ignore_errors'] = true; <ide> <ide> if (isset($options['timeout'])) { <ide><path>src/Http/Client/Request.php <ide> protected function addHeaders(array $headers) <ide> public function cookie($name, $value = null) <ide> { <ide> deprecationWarning( <del> 'Request::header() is deprecated. ' . <del> 'No longer used. CookieCollections now add `Cookie` header to the ' . <add> 'Request::cookie() is deprecated. ' . <add> 'The Client internals now add the required `Cookie` header to the ' . <ide> 'request before sending. Use Cake\Http\Cookie\CookieCollection::addToRequest() ' . <ide> 'to make adding cookies to a request easier.' <ide> ); <ide> public function body($body = null) <ide> if (is_array($body)) { <ide> $formData = new FormData(); <ide> $formData->addMany($body); <del> $this->header('Content-Type', $formData->contentType()); <add> $this->addHeaders(['Content-Type' => $formData->contentType()]); <ide> $body = (string)$formData; <ide> } <ide> $stream = new Stream('php://memory', 'rw'); <ide><path>tests/TestCase/Http/Client/Adapter/StreamTest.php <ide> public function tearDown() <ide> public function testSend() <ide> { <ide> $stream = new Stream(); <del> $request = new Request(); <del> $request->url('http://localhost') <del> ->header('User-Agent', 'CakePHP TestSuite') <del> ->cookie('testing', 'value'); <add> $request = new Request('http://localhost', 'GET', [ <add> 'User-Agent' => 'CakePHP TestSuite', <add> 'Cookie' => 'testing=value' <add> ]); <ide> <ide> try { <ide> $responses = $stream->send($request, []); <ide> public function testSend() <ide> public function testSendByUsingCakephpProtocol() <ide> { <ide> $stream = new Stream(); <del> $request = new Request(); <del> $request->url('http://dummy/'); <add> $request = new Request('http://dummy/'); <ide> <ide> $responses = $stream->send($request, []); <ide> $this->assertInstanceOf('Cake\Http\Client\Response', $responses[0]); <ide> public function testSendByUsingCakephpProtocol() <ide> */ <ide> public function testBuildingContextHeader() <ide> { <del> $request = new Request(); <del> $request->url('http://localhost') <del> ->header([ <add> $request = new Request( <add> 'http://localhost', <add> 'GET', <add> [ <ide> 'User-Agent' => 'CakePHP TestSuite', <ide> 'Content-Type' => 'application/json', <ide> 'Cookie' => 'a=b; c=do%20it' <del> ]); <add> ] <add> ); <ide> <ide> $options = [ <ide> 'redirect' => 20, <ide> ]; <ide> $this->stream->send($request, $options); <ide> $result = $this->stream->contextOptions(); <ide> $expected = [ <del> 'Connection: close', <ide> 'User-Agent: CakePHP TestSuite', <ide> 'Content-Type: application/json', <ide> 'Cookie: a=b; c=do%20it', <add> 'Connection: close', <ide> ]; <ide> $this->assertEquals(implode("\r\n", $expected), $result['header']); <ide> $this->assertSame(0, $result['max_redirects']); <ide> public function testBuildingContextHeader() <ide> public function testSendContextContentString() <ide> { <ide> $content = json_encode(['a' => 'b']); <del> $request = new Request(); <del> $request->url('http://localhost') <del> ->header([ <del> 'Content-Type' => 'application/json' <del> ]) <del> ->body($content); <add> $request = new Request( <add> 'http://localhost', <add> 'GET', <add> ['Content-Type' => 'application/json'], <add> $content <add> ); <ide> <ide> $options = [ <ide> 'redirect' => 20 <ide> ]; <ide> $this->stream->send($request, $options); <ide> $result = $this->stream->contextOptions(); <ide> $expected = [ <add> 'Content-Type: application/json', <ide> 'Connection: close', <ide> 'User-Agent: CakePHP', <del> 'Content-Type: application/json', <ide> ]; <ide> $this->assertEquals(implode("\r\n", $expected), $result['header']); <ide> $this->assertEquals($content, $result['content']); <ide> public function testSendContextContentString() <ide> */ <ide> public function testSendContextContentArray() <ide> { <del> $request = new Request(); <del> $request->url('http://localhost') <del> ->header([ <add> $request = new Request( <add> 'http://localhost', <add> 'GET', <add> [ <ide> 'Content-Type' => 'application/json' <del> ]) <del> ->body(['a' => 'my value']); <add> ], <add> ['a' => 'my value'] <add> ); <ide> <ide> $this->stream->send($request, []); <ide> $result = $this->stream->contextOptions(); <ide> $expected = [ <add> 'Content-Type: application/x-www-form-urlencoded', <ide> 'Connection: close', <ide> 'User-Agent: CakePHP', <del> 'Content-Type: application/x-www-form-urlencoded', <ide> ]; <ide> $this->assertStringStartsWith(implode("\r\n", $expected), $result['header']); <ide> $this->assertContains('a=my+value', $result['content']); <ide> public function testSendContextContentArray() <ide> */ <ide> public function testSendContextContentArrayFiles() <ide> { <del> $request = new Request(); <del> $request->url('http://localhost') <del> ->header([ <del> 'Content-Type' => 'application/json' <del> ]) <del> ->body(['upload' => fopen(CORE_PATH . 'VERSION.txt', 'r')]); <add> $request = new Request( <add> 'http://localhost', <add> 'GET', <add> ['Content-Type' => 'application/json'], <add> ['upload' => fopen(CORE_PATH . 'VERSION.txt', 'r')] <add> ); <ide> <ide> $this->stream->send($request, []); <ide> $result = $this->stream->contextOptions(); <del> $expected = [ <del> 'Connection: close', <del> 'User-Agent: CakePHP', <del> 'Content-Type: multipart/form-data', <del> ]; <del> $this->assertStringStartsWith(implode("\r\n", $expected), $result['header']); <add> $this->assertContains("Content-Type: multipart/form-data", $result['header']); <add> $this->assertContains("Connection: close\r\n", $result['header']); <add> $this->assertContains("User-Agent: CakePHP", $result['header']); <ide> $this->assertContains('name="upload"', $result['content']); <ide> $this->assertContains('filename="VERSION.txt"', $result['content']); <ide> } <ide> public function testSendContextContentArrayFiles() <ide> */ <ide> public function testSendContextSsl() <ide> { <del> $request = new Request(); <del> $request->url('https://localhost.com/test.html'); <add> $request = new Request('https://localhost.com/test.html'); <ide> $options = [ <ide> 'ssl_verify_host' => true, <ide> 'ssl_verify_peer' => true, <ide> public function testSendContextSsl() <ide> */ <ide> public function testSendContextSslNoVerifyPeerName() <ide> { <del> $request = new Request(); <del> $request->url('https://localhost.com/test.html'); <add> $request = new Request('https://localhost.com/test.html'); <ide> $options = [ <ide> 'ssl_verify_host' => true, <ide> 'ssl_verify_peer' => true, <ide> public function testCreateResponseWithRedirects() <ide> <ide> $responses = $this->stream->createResponses($headers, $content); <ide> $this->assertCount(3, $responses); <del> $this->assertEquals('close', $responses[0]->header('Connection')); <del> $this->assertEquals('', $responses[0]->body()); <del> $this->assertEquals('', $responses[1]->body()); <del> $this->assertEquals($content, $responses[2]->body()); <del> <del> $this->assertEquals(302, $responses[0]->statusCode()); <del> $this->assertEquals(302, $responses[1]->statusCode()); <del> $this->assertEquals(200, $responses[2]->statusCode()); <del> <del> $this->assertEquals('value', $responses[0]->cookie('first')); <del> $this->assertEquals(null, $responses[0]->cookie('second')); <del> $this->assertEquals(null, $responses[0]->cookie('third')); <del> <del> $this->assertEquals(null, $responses[1]->cookie('first')); <del> $this->assertEquals('val', $responses[1]->cookie('second')); <del> $this->assertEquals(null, $responses[1]->cookie('third')); <del> <del> $this->assertEquals(null, $responses[2]->cookie('first')); <del> $this->assertEquals(null, $responses[2]->cookie('second')); <del> $this->assertEquals('works', $responses[2]->cookie('third')); <add> $this->assertEquals('close', $responses[0]->getHeaderLine('Connection')); <add> $this->assertEquals('', (string)$responses[0]->getBody()); <add> $this->assertEquals('', (string)$responses[1]->getBody()); <add> $this->assertEquals($content, (string)$responses[2]->getBody()); <add> <add> $this->assertEquals(302, $responses[0]->getStatusCode()); <add> $this->assertEquals(302, $responses[1]->getStatusCode()); <add> $this->assertEquals(200, $responses[2]->getStatusCode()); <add> <add> $this->assertEquals('value', $responses[0]->getCookie('first')); <add> $this->assertEquals(null, $responses[0]->getCookie('second')); <add> $this->assertEquals(null, $responses[0]->getCookie('third')); <add> <add> $this->assertEquals(null, $responses[1]->getCookie('first')); <add> $this->assertEquals('val', $responses[1]->getCookie('second')); <add> $this->assertEquals(null, $responses[1]->getCookie('third')); <add> <add> $this->assertEquals(null, $responses[2]->getCookie('first')); <add> $this->assertEquals(null, $responses[2]->getCookie('second')); <add> $this->assertEquals('works', $responses[2]->getCookie('third')); <ide> } <ide> <ide> /** <ide> public function testCreateResponseWithRedirects() <ide> */ <ide> public function testKeepDeadline() <ide> { <del> $request = new Request(); <del> $request->url('http://dummy/?sleep'); <add> $request = new Request('http://dummy/?sleep'); <ide> $options = [ <ide> 'timeout' => 5, <ide> ]; <ide> public function testMissDeadline() <ide> { <ide> $this->expectException(\Cake\Network\Exception\HttpException::class); <ide> $this->expectExceptionMessage('Connection timed out http://dummy/?sleep'); <del> $request = new Request(); <del> $request->url('http://dummy/?sleep'); <add> $request = new Request('http://dummy/?sleep'); <ide> $options = [ <ide> 'timeout' => 2, <ide> ]; <ide><path>tests/TestCase/Http/Client/CookieCollectionTest.php <ide> <ide> /** <ide> * HTTP cookies test. <add> * <add> * @group deprecated <ide> */ <ide> class CookieCollectionTest extends TestCase <ide> { <ide> class CookieCollectionTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> $this->cookies = new CookieCollection(); <add> $this->deprecated(function () { <add> $this->cookies = new CookieCollection(); <add> }); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/ClientTest.php <ide> public function testGetWithAuthenticationAndProxy() <ide> /** <ide> * Test authentication adapter that mutates request. <ide> * <add> * @group deprecated <ide> * @return void <ide> */ <ide> public function testAuthenticationWithMutation() <ide> { <del> static::setAppNamespace(); <del> $response = new Response(); <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <del> ->setMethods(['send']) <del> ->getMock(); <del> $headers = [ <del> 'Authorization' => 'Bearer abc123', <del> 'Proxy-Authorization' => 'Bearer abc123', <del> ]; <del> $mock->expects($this->once()) <del> ->method('send') <del> ->with($this->callback(function ($request) use ($headers) { <del> $this->assertEquals(Request::METHOD_GET, $request->getMethod()); <del> $this->assertEquals('http://cakephp.org/', '' . $request->getUri()); <del> $this->assertEquals($headers['Authorization'], $request->getHeaderLine('Authorization')); <del> $this->assertEquals($headers['Proxy-Authorization'], $request->getHeaderLine('Proxy-Authorization')); <add> $this->deprecated(function () { <add> static::setAppNamespace(); <add> $response = new Response(); <add> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> ->setMethods(['send']) <add> ->getMock(); <add> $headers = [ <add> 'Authorization' => 'Bearer abc123', <add> 'Proxy-Authorization' => 'Bearer abc123', <add> ]; <add> $mock->expects($this->once()) <add> ->method('send') <add> ->with($this->callback(function ($request) use ($headers) { <add> $this->assertEquals(Request::METHOD_GET, $request->getMethod()); <add> $this->assertEquals('http://cakephp.org/', '' . $request->getUri()); <add> $this->assertEquals($headers['Authorization'], $request->getHeaderLine('Authorization')); <add> $this->assertEquals($headers['Proxy-Authorization'], $request->getHeaderLine('Proxy-Authorization')); <ide> <del> return true; <del> })) <del> ->will($this->returnValue([$response])); <del> <del> $http = new Client([ <del> 'host' => 'cakephp.org', <del> 'adapter' => $mock <del> ]); <del> $result = $http->get('/', [], [ <del> 'auth' => ['type' => 'TestApp\Http\CompatAuth'], <del> 'proxy' => ['type' => 'TestApp\Http\CompatAuth'], <del> ]); <del> $this->assertSame($result, $response); <add> return true; <add> })) <add> ->will($this->returnValue([$response])); <add> <add> $http = new Client([ <add> 'host' => 'cakephp.org', <add> 'adapter' => $mock <add> ]); <add> $result = $http->get('/', [], [ <add> 'auth' => ['type' => 'TestApp\Http\CompatAuth'], <add> 'proxy' => ['type' => 'TestApp\Http\CompatAuth'], <add> ]); <add> $this->assertSame($result, $response); <add> }); <ide> } <ide> <ide> /** <ide> public function testRedirects() <ide> <ide> $this->assertInstanceOf(Response::class, $result); <ide> $this->assertTrue($result->isOk()); <del> $cookies = $client->cookies()->get($url); <add> $cookies = $client->cookies(); <ide> <del> $this->assertArrayHasKey('redirect1', $cookies); <del> $this->assertArrayHasKey('redirect2', $cookies); <add> $this->assertTrue($cookies->has('redirect1')); <add> $this->assertTrue($cookies->has('redirect2')); <ide> } <ide> }
6
Python
Python
fix bart shift
18ecd36f657b07b032fecd199fa37d8ae0a6b9ff
<ide><path>src/transformers/models/bart/modeling_bart.py <ide> def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int): <ide> # replace possible -100 values in labels by `pad_token_id` <ide> prev_output_tokens.masked_fill_(prev_output_tokens == -100, pad_token_id) <ide> <del> index_of_eos = (input_ids.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1) <del> prev_output_tokens[:, 0] = input_ids.gather(1, index_of_eos).squeeze() <del> prev_output_tokens[:, 1:] = input_ids[:, :-1] <add> index_of_eos = (prev_output_tokens.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1) <add> decoder_start_tokens = prev_output_tokens.gather(1, index_of_eos).squeeze() <add> prev_output_tokens[:, 1:] = prev_output_tokens[:, :-1].clone() <add> prev_output_tokens[:, 0] = decoder_start_tokens <ide> <ide> return prev_output_tokens <ide>
1
Text
Text
use alphabetic order
a6dfe5f0249a4825a79407fb15ae42eac0647d4f
<ide><path>guides/source/configuring.md <ide> These configuration methods are to be called on a `Rails::Railtie` object, such <ide> <ide> * `config.action_view.cache_template_loading` controls whether or not templates should be reloaded on each request. Defaults to whatever is set for `config.cache_classes`. <ide> <add>* `config.beginning_of_week` sets the default beginning of week for the application. Accepts a valid week day symbol (e.g. `:monday`). <add> <ide> * `config.cache_store` configures which cache store to use for Rails caching. Options include one of the symbols `:memory_store`, `:file_store`, `:mem_cache_store`, `:null_store`, or an object that implements the cache API. Defaults to `:file_store` if the directory `tmp/cache` exists, and to `:memory_store` otherwise. <ide> <ide> * `config.colorize_logging` specifies whether or not to use ANSI color codes when logging information. Defaults to true. <ide> numbers. New applications filter out passwords by adding the following `config.f <ide> <ide> * `config.time_zone` sets the default time zone for the application and enables time zone awareness for Active Record. <ide> <del>* `config.beginning_of_week` sets the default beginning of week for the application. Accepts a valid week day symbol (e.g. `:monday`). <del> <ide> ### Configuring Assets <ide> <ide> * `config.assets.enabled` a flag that controls whether the asset
1
Java
Java
add support for `overflow` on android (take 2)
b81c8b51fc6fe3c2dece72e3fe500e175613c5d4
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java <ide> public class ViewProps { <ide> public static final String ALIGN_ITEMS = "alignItems"; <ide> public static final String ALIGN_SELF = "alignSelf"; <ide> public static final String ALIGN_CONTENT = "alignContent"; <del> public static final String OVERFLOW = "overflow"; <ide> public static final String DISPLAY = "display"; <ide> public static final String BOTTOM = "bottom"; <ide> public static final String COLLAPSABLE = "collapsable"; <ide> public class ViewProps { <ide> public static final String MIN_HEIGHT = "minHeight"; <ide> public static final String MAX_HEIGHT = "maxHeight"; <ide> <del> public static final String HIDDEN = "hidden"; <del> public static final String VISIBLE = "visible"; <del> <ide> public static final String ASPECT_RATIO = "aspectRatio"; <ide> <ide> // Props that sometimes may prevent us from collapsing views <ide> public class ViewProps { <ide> public static final String TEXT_DECORATION_LINE = "textDecorationLine"; <ide> public static final String TEXT_BREAK_STRATEGY = "textBreakStrategy"; <ide> public static final String OPACITY = "opacity"; <add> public static final String OVERFLOW = "overflow"; <add> <add> public static final String HIDDEN = "hidden"; <add> public static final String VISIBLE = "visible"; <ide> <ide> public static final String ALLOW_FONT_SCALING = "allowFontScaling"; <ide> public static final String INCLUDE_FONT_PADDING = "includeFontPadding"; <ide> public class ViewProps { <ide> FLEX_SHRINK, <ide> FLEX_WRAP, <ide> JUSTIFY_CONTENT, <del> OVERFLOW, <ide> ALIGN_CONTENT, <ide> DISPLAY, <ide> <ide> public static boolean isLayoutOnly(ReadableMap map, String prop) { <ide> return map.isNull(BORDER_RIGHT_WIDTH) || map.getDouble(BORDER_RIGHT_WIDTH) == 0d; <ide> case BORDER_BOTTOM_WIDTH: <ide> return map.isNull(BORDER_BOTTOM_WIDTH) || map.getDouble(BORDER_BOTTOM_WIDTH) == 0d; <add> case OVERFLOW: <add> return map.isNull(OVERFLOW) || VISIBLE.equals(map.getString(OVERFLOW)); <ide> default: <ide> return false; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java <ide> public void onLayoutChange( <ide> <ide> public ReactViewGroup(Context context) { <ide> super(context); <add> setClipChildren(false); <ide> mDrawingOrderHelper = new ViewGroupDrawingOrderHelper(this); <ide> } <ide> <ide> private void dispatchOverflowDraw(Canvas canvas) { <ide> } <ide> break; <ide> case ViewProps.HIDDEN: <del> if (mReactBackgroundDrawable != null) { <del> float left = 0f; <del> float top = 0f; <del> float right = getWidth(); <del> float bottom = getHeight(); <add> float left = 0f; <add> float top = 0f; <add> float right = getWidth(); <add> float bottom = getHeight(); <add> <add> boolean hasClipPath = false; <ide> <add> if (mReactBackgroundDrawable != null) { <ide> final RectF borderWidth = mReactBackgroundDrawable.getDirectionAwareBorderInsets(); <ide> <ide> if (borderWidth.top > 0 <ide> private void dispatchOverflowDraw(Canvas canvas) { <ide> }, <ide> Path.Direction.CW); <ide> canvas.clipPath(mPath); <del> } else { <del> canvas.clipRect(new RectF(left, top, right, bottom)); <add> hasClipPath = true; <ide> } <ide> } <add> <add> if (!hasClipPath) { <add> canvas.clipRect(new RectF(left, top, right, bottom)); <add> } <ide> break; <ide> default: <ide> break;
2
Go
Go
move "image_export" to graph/export.go
6e28d11d1fde757cf5b9418a2e752717d854f3f3
<ide><path>graph/export.go <add>package graph <add> <add>import ( <add> "encoding/json" <add> "io" <add> "io/ioutil" <add> "os" <add> "path" <add> <add> "github.com/docker/docker/archive" <add> "github.com/docker/docker/engine" <add> "github.com/docker/docker/pkg/parsers" <add> "github.com/docker/docker/utils" <add>) <add> <add>// CmdImageExport exports all images with the given tag. All versions <add>// containing the same tag are exported. The resulting output is an <add>// uncompressed tar ball. <add>// name is the set of tags to export. <add>// out is the writer where the images are written to. <add>func (s *TagStore) CmdImageExport(job *engine.Job) engine.Status { <add> if len(job.Args) != 1 { <add> return job.Errorf("Usage: %s IMAGE\n", job.Name) <add> } <add> name := job.Args[0] <add> // get image json <add> tempdir, err := ioutil.TempDir("", "docker-export-") <add> if err != nil { <add> return job.Error(err) <add> } <add> defer os.RemoveAll(tempdir) <add> <add> utils.Debugf("Serializing %s", name) <add> <add> rootRepoMap := map[string]Repository{} <add> rootRepo, err := s.Get(name) <add> if err != nil { <add> return job.Error(err) <add> } <add> if rootRepo != nil { <add> // this is a base repo name, like 'busybox' <add> <add> for _, id := range rootRepo { <add> if err := s.exportImage(job.Eng, id, tempdir); err != nil { <add> return job.Error(err) <add> } <add> } <add> rootRepoMap[name] = rootRepo <add> } else { <add> img, err := s.LookupImage(name) <add> if err != nil { <add> return job.Error(err) <add> } <add> if img != nil { <add> // This is a named image like 'busybox:latest' <add> repoName, repoTag := parsers.ParseRepositoryTag(name) <add> if err := s.exportImage(job.Eng, img.ID, tempdir); err != nil { <add> return job.Error(err) <add> } <add> // check this length, because a lookup of a truncated has will not have a tag <add> // and will not need to be added to this map <add> if len(repoTag) > 0 { <add> rootRepoMap[repoName] = Repository{repoTag: img.ID} <add> } <add> } else { <add> // this must be an ID that didn't get looked up just right? <add> if err := s.exportImage(job.Eng, name, tempdir); err != nil { <add> return job.Error(err) <add> } <add> } <add> } <add> // write repositories, if there is something to write <add> if len(rootRepoMap) > 0 { <add> rootRepoJson, _ := json.Marshal(rootRepoMap) <add> <add> if err := ioutil.WriteFile(path.Join(tempdir, "repositories"), rootRepoJson, os.FileMode(0644)); err != nil { <add> return job.Error(err) <add> } <add> } else { <add> utils.Debugf("There were no repositories to write") <add> } <add> <add> fs, err := archive.Tar(tempdir, archive.Uncompressed) <add> if err != nil { <add> return job.Error(err) <add> } <add> defer fs.Close() <add> <add> if _, err := io.Copy(job.Stdout, fs); err != nil { <add> return job.Error(err) <add> } <add> utils.Debugf("End Serializing %s", name) <add> return engine.StatusOK <add>} <add> <add>// FIXME: this should be a top-level function, not a class method <add>func (s *TagStore) exportImage(eng *engine.Engine, name, tempdir string) error { <add> for n := name; n != ""; { <add> // temporary directory <add> tmpImageDir := path.Join(tempdir, n) <add> if err := os.Mkdir(tmpImageDir, os.FileMode(0755)); err != nil { <add> if os.IsExist(err) { <add> return nil <add> } <add> return err <add> } <add> <add> var version = "1.0" <add> var versionBuf = []byte(version) <add> <add> if err := ioutil.WriteFile(path.Join(tmpImageDir, "VERSION"), versionBuf, os.FileMode(0644)); err != nil { <add> return err <add> } <add> <add> // serialize json <add> json, err := os.Create(path.Join(tmpImageDir, "json")) <add> if err != nil { <add> return err <add> } <add> job := eng.Job("image_inspect", n) <add> job.SetenvBool("raw", true) <add> job.Stdout.Add(json) <add> if err := job.Run(); err != nil { <add> return err <add> } <add> <add> // serialize filesystem <add> fsTar, err := os.Create(path.Join(tmpImageDir, "layer.tar")) <add> if err != nil { <add> return err <add> } <add> job = eng.Job("image_tarlayer", n) <add> job.Stdout.Add(fsTar) <add> if err := job.Run(); err != nil { <add> return err <add> } <add> <add> // find parent <add> job = eng.Job("image_get", n) <add> info, _ := job.Stdout.AddEnv() <add> if err := job.Run(); err != nil { <add> return err <add> } <add> n = info.Get("Parent") <add> } <add> return nil <add>} <ide><path>graph/service.go <ide> func (s *TagStore) Install(eng *engine.Engine) error { <ide> eng.Register("image_get", s.CmdGet) <ide> eng.Register("image_inspect", s.CmdLookup) <ide> eng.Register("image_tarlayer", s.CmdTarLayer) <add> eng.Register("image_export", s.CmdImageExport) <ide> return nil <ide> } <ide> <ide><path>server/image.go <ide> import ( <ide> "github.com/docker/docker/utils" <ide> ) <ide> <del>// ImageExport exports all images with the given tag. All versions <del>// containing the same tag are exported. The resulting output is an <del>// uncompressed tar ball. <del>// name is the set of tags to export. <del>// out is the writer where the images are written to. <del>func (srv *Server) ImageExport(job *engine.Job) engine.Status { <del> if len(job.Args) != 1 { <del> return job.Errorf("Usage: %s IMAGE\n", job.Name) <del> } <del> name := job.Args[0] <del> // get image json <del> tempdir, err := ioutil.TempDir("", "docker-export-") <del> if err != nil { <del> return job.Error(err) <del> } <del> defer os.RemoveAll(tempdir) <del> <del> utils.Debugf("Serializing %s", name) <del> <del> rootRepoMap := map[string]graph.Repository{} <del> rootRepo, err := srv.daemon.Repositories().Get(name) <del> if err != nil { <del> return job.Error(err) <del> } <del> if rootRepo != nil { <del> // this is a base repo name, like 'busybox' <del> <del> for _, id := range rootRepo { <del> if err := srv.exportImage(job.Eng, id, tempdir); err != nil { <del> return job.Error(err) <del> } <del> } <del> rootRepoMap[name] = rootRepo <del> } else { <del> img, err := srv.daemon.Repositories().LookupImage(name) <del> if err != nil { <del> return job.Error(err) <del> } <del> if img != nil { <del> // This is a named image like 'busybox:latest' <del> repoName, repoTag := parsers.ParseRepositoryTag(name) <del> if err := srv.exportImage(job.Eng, img.ID, tempdir); err != nil { <del> return job.Error(err) <del> } <del> // check this length, because a lookup of a truncated has will not have a tag <del> // and will not need to be added to this map <del> if len(repoTag) > 0 { <del> rootRepoMap[repoName] = graph.Repository{repoTag: img.ID} <del> } <del> } else { <del> // this must be an ID that didn't get looked up just right? <del> if err := srv.exportImage(job.Eng, name, tempdir); err != nil { <del> return job.Error(err) <del> } <del> } <del> } <del> // write repositories, if there is something to write <del> if len(rootRepoMap) > 0 { <del> rootRepoJson, _ := json.Marshal(rootRepoMap) <del> <del> if err := ioutil.WriteFile(path.Join(tempdir, "repositories"), rootRepoJson, os.FileMode(0644)); err != nil { <del> return job.Error(err) <del> } <del> } else { <del> utils.Debugf("There were no repositories to write") <del> } <del> <del> fs, err := archive.Tar(tempdir, archive.Uncompressed) <del> if err != nil { <del> return job.Error(err) <del> } <del> defer fs.Close() <del> <del> if _, err := io.Copy(job.Stdout, fs); err != nil { <del> return job.Error(err) <del> } <del> utils.Debugf("End Serializing %s", name) <del> return engine.StatusOK <del>} <del> <del>func (srv *Server) exportImage(eng *engine.Engine, name, tempdir string) error { <del> for n := name; n != ""; { <del> // temporary directory <del> tmpImageDir := path.Join(tempdir, n) <del> if err := os.Mkdir(tmpImageDir, os.FileMode(0755)); err != nil { <del> if os.IsExist(err) { <del> return nil <del> } <del> return err <del> } <del> <del> var version = "1.0" <del> var versionBuf = []byte(version) <del> <del> if err := ioutil.WriteFile(path.Join(tmpImageDir, "VERSION"), versionBuf, os.FileMode(0644)); err != nil { <del> return err <del> } <del> <del> // serialize json <del> json, err := os.Create(path.Join(tmpImageDir, "json")) <del> if err != nil { <del> return err <del> } <del> job := eng.Job("image_inspect", n) <del> job.SetenvBool("raw", true) <del> job.Stdout.Add(json) <del> if err := job.Run(); err != nil { <del> return err <del> } <del> <del> // serialize filesystem <del> fsTar, err := os.Create(path.Join(tmpImageDir, "layer.tar")) <del> if err != nil { <del> return err <del> } <del> job = eng.Job("image_tarlayer", n) <del> job.Stdout.Add(fsTar) <del> if err := job.Run(); err != nil { <del> return err <del> } <del> <del> // find parent <del> job = eng.Job("image_get", n) <del> info, _ := job.Stdout.AddEnv() <del> if err := job.Run(); err != nil { <del> return err <del> } <del> n = info.Get("Parent") <del> } <del> return nil <del>} <del> <ide> func (srv *Server) Build(job *engine.Job) engine.Status { <ide> if len(job.Args) != 0 { <ide> return job.Errorf("Usage: %s\n", job.Name) <ide><path>server/init.go <ide> func InitServer(job *engine.Job) engine.Status { <ide> for name, handler := range map[string]engine.Handler{ <ide> "tag": srv.ImageTag, // FIXME merge with "image_tag" <ide> "info": srv.DockerInfo, <del> "image_export": srv.ImageExport, <ide> "images": srv.Images, <ide> "history": srv.ImageHistory, <ide> "viz": srv.ImagesViz,
4
Javascript
Javascript
add count to interleavedbuffer
1753badadedeea82ef33200a565e6c62f833a373
<ide><path>src/core/InterleavedBuffer.js <ide> THREE.InterleavedBuffer.prototype = { <ide> <ide> }, <ide> <add> get count () { <add> <add> return this.array.length / this.stride; <add> <add> }, <add> <ide> copyAt: function ( index1, attribute, index2 ) { <ide> <ide> index1 *= this.stride; <ide><path>src/core/InterleavedBufferAttribute.js <ide> THREE.InterleavedBufferAttribute.prototype = { <ide> <ide> get length() { <ide> <del> console.warn( 'THREE.InterleavedBufferAttribute: .length has been renamed to .count.' ); <del> return this.count; <add> console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); <add> return this.array.length; <ide> <ide> }, <ide> <ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> if ( geometry.maxInstancedCount === undefined ) { <ide> <del> geometry.maxInstancedCount = data.meshPerAttribute * ( data.array.length / data.stride ); <add> geometry.maxInstancedCount = data.meshPerAttribute * data.count; <ide> <ide> } <ide> <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> if ( geometry.maxInstancedCount === undefined ) { <ide> <del> geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * ( geometryAttribute.array.length / geometryAttribute.itemSize ); <add> geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; <ide> <ide> } <ide> <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> if ( position instanceof THREE.InterleavedBufferAttribute ) { <ide> <del> extension.drawArraysInstancedANGLE( mode, 0, position.data.array.length / position.data.stride, geometry.maxInstancedCount ); // Draw the instanced meshes <add> extension.drawArraysInstancedANGLE( mode, 0, position.data.count, geometry.maxInstancedCount ); // Draw the instanced meshes <ide> <ide> } else { <ide> <del> extension.drawArraysInstancedANGLE( mode, 0, position.array.length / position.itemSize, geometry.maxInstancedCount ); // Draw the instanced meshes <add> extension.drawArraysInstancedANGLE( mode, 0, position.count, geometry.maxInstancedCount ); // Draw the instanced meshes <ide> <ide> } <ide> <ide> } else { <ide> <ide> if ( position instanceof THREE.InterleavedBufferAttribute ) { <ide> <del> _gl.drawArrays( mode, 0, position.data.array.length / position.data.stride ); <add> _gl.drawArrays( mode, 0, position.data.count ); <ide> <ide> } else { <ide> <del> _gl.drawArrays( mode, 0, position.array.length / position.itemSize ); <add> _gl.drawArrays( mode, 0, position.count ); <ide> <ide> } <ide> <ide> } <ide> <ide> _this.info.render.calls++; <del> _this.info.render.vertices += position.array.length / position.itemSize; <del> _this.info.render.faces += position.array.length / ( 3 * position.itemSize ); <add> _this.info.render.vertices += position.count; <add> _this.info.render.faces += position.count / 3; <ide> <ide> } else { <ide>
3
Ruby
Ruby
fix a bunch of minor spelling mistakes
ccf9577aee86ce1f766c5e8854e0c285dc38f8ac
<ide><path>actionmailer/lib/action_mailer/base.rb <ide> module ActionMailer #:nodoc: <ide> # <ide> # If you want to explicitly render only certain templates, pass a block: <ide> # <del> # mail(:to => user.emai) do |format| <add> # mail(:to => user.email) do |format| <ide> # format.text <ide> # format.html <ide> # end <ide> # <ide> # The block syntax is useful if also need to specify information specific to a part: <ide> # <del> # mail(:to => user.emai) do |format| <add> # mail(:to => user.email) do |format| <ide> # format.text(:content_transfer_encoding => "base64") <ide> # format.html <ide> # end <ide> # <ide> # Or even to render a special view: <ide> # <del> # mail(:to => user.emai) do |format| <add> # mail(:to => user.email) do |format| <ide> # format.text <ide> # format.html { render "some_other_template" } <ide> # end <ide> module ActionMailer #:nodoc: <ide> # end <ide> # <ide> # Which will (if it had both a <tt>welcome.text.plain.erb</tt> and <tt>welcome.text.html.erb</tt> <del> # tempalte in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts, <add> # template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts, <ide> # the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside, <ide> # and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book <ide> # with the filename +free_book.pdf+. <ide><path>actionmailer/lib/action_mailer/deprecated_api.rb <ide> module ActionMailer <ide> # This is the API which is deprecated and is going to be removed on Rails 3.1 release. <ide> # Part of the old API will be deprecated after 3.1, for a smoother deprecation process. <del> # Chech those in OldApi instead. <add> # Check those in OldApi instead. <ide> module DeprecatedApi #:nodoc: <ide> extend ActiveSupport::Concern <ide> <ide><path>actionpack/lib/abstract_controller/base.rb <ide> def inherited(klass) <ide> super <ide> end <ide> <del> # A list of all descendents of AbstractController::Base. This is <add> # A list of all descendants of AbstractController::Base. This is <ide> # useful for initializers which need to add behavior to all controllers. <ide> def descendants <ide> @descendants ||= [] <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb <ide> module RequestForgeryProtection <ide> config_accessor :request_forgery_protection_token <ide> self.request_forgery_protection_token ||= :authenticity_token <ide> <del> # Controls whether request forgergy protection is turned on or not. Turned off by default only in test mode. <add> # Controls whether request forgery protection is turned on or not. Turned off by default only in test mode. <ide> config_accessor :allow_forgery_protection <ide> self.allow_forgery_protection = true if allow_forgery_protection.nil? <ide> <ide><path>actionpack/lib/action_controller/test_case.rb <ide> def initialize(session = {}) <ide> # Superclass for ActionController functional tests. Functional tests allow you to <ide> # test a single controller action per test method. This should not be confused with <ide> # integration tests (see ActionController::IntegrationTest), which are more like <del> # "stories" that can involve multiple controllers and mutliple actions (i.e. multiple <add> # "stories" that can involve multiple controllers and multiple actions (i.e. multiple <ide> # different HTTP requests). <ide> # <ide> # == Basic example <ide> def build_request_uri(action, parameters) <ide> end <ide> <ide> # When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline <del> # (bystepping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular <add> # (skipping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular <ide> # rescue_action process takes place. This means you can test your rescue_action code by setting remote_addr to something else <ide> # than 0.0.0.0. <ide> # <ide><path>actionpack/lib/action_dispatch/http/mime_type.rb <ide> class AcceptItem #:nodoc: <ide> def initialize(order, name, q=nil) <ide> @order = order <ide> @name = name.strip <del> q ||= 0.0 if @name == Mime::ALL # default wilcard match to end of list <add> q ||= 0.0 if @name == Mime::ALL # default wildcard match to end of list <ide> @q = ((q || 1.0).to_f * 100).to_i <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/http/parameters.rb <ide> def path_parameters <ide> end <ide> <ide> private <del> # Convert nested Hashs to HashWithIndifferentAccess <add> # Convert nested Hash to HashWithIndifferentAccess <ide> def normalize_parameters(value) <ide> case value <ide> when Hash <ide><path>actionpack/lib/action_dispatch/http/upload.rb <ide> def original_filename <ide> end <ide> <ide> module Upload <del> # Convert nested Hashs to HashWithIndifferentAccess and replace <del> # file upload hashs with UploadedFile objects <add> # Convert nested Hash to HashWithIndifferentAccess and replace <add> # file upload hash with UploadedFile objects <ide> def normalize_parameters(value) <ide> if Hash === value && value.has_key?(:tempfile) <ide> upload = value[:tempfile] <ide><path>actionpack/lib/action_dispatch/middleware/stack.rb <ide> def use(*args, &block) <ide> end <ide> <ide> def active <del> ActiveSupport::Deprecation.warn "All middlewares in the chaing are active since the laziness " << <add> ActiveSupport::Deprecation.warn "All middlewares in the chain are active since the laziness " << <ide> "was removed from the middleware stack", caller <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/testing/assertions/selector.rb <ide> def count_description(min, max, count) #:nodoc: <ide> # position. Possible values are <tt>:top</tt>, <tt>:bottom</tt>, <tt>:before</tt> <ide> # and <tt>:after</tt>. <ide> # <del> # Use the argument <tt>:redirect</tt> follwed by a path to check that an statement <add> # Use the argument <tt>:redirect</tt> followed by a path to check that an statement <ide> # which redirects to the specified path is generated. <ide> # <ide> # Using the <tt>:remove</tt> statement, you will be able to pass a block, but it will <ide><path>actionpack/lib/action_dispatch/testing/test_response.rb <ide> def redirect_url_match?(pattern) <ide> # Returns the template of the file which was used to <ide> # render this response (or nil) <ide> def rendered <del> ActiveSupport::Deprecation.warn("response.rendered has been deprecated. Use tempate.rendered instead", caller) <add> ActiveSupport::Deprecation.warn("response.rendered has been deprecated. Use template.rendered instead", caller) <ide> @template.instance_variable_get(:@_rendered) <ide> end <ide> <ide> def has_session_object?(name=nil) <ide> <ide> # A shortcut to the template.assigns <ide> def template_objects <del> ActiveSupport::Deprecation.warn("response.template_objects has been deprecated. Use tempate.assigns instead", caller) <add> ActiveSupport::Deprecation.warn("response.template_objects has been deprecated. Use template.assigns instead", caller) <ide> @template.assigns || {} <ide> end <ide> <ide><path>actionpack/lib/action_view/helpers/form_helper.rb <ide> module Helpers <ide> # # error handling <ide> # end <ide> # <del> # That's how you tipically work with resources. <add> # That's how you typically work with resources. <ide> module FormHelper <ide> extend ActiveSupport::Concern <ide> <ide> module FormHelper <ide> # <tt>labelling_form</tt>. <ide> # <ide> # The custom FormBuilder class is automatically merged with the options <del> # of a nested fields_for call, unless it's explicitely set. <add> # of a nested fields_for call, unless it's explicitly set. <ide> # <ide> # In many cases you will want to wrap the above in another helper, so you <ide> # could do something like the following: <ide> def text_area(object_name, method, options = {}) <ide> # <ide> # To prevent this the helper generates an auxiliary hidden field before <ide> # the very check box. The hidden field has the same name and its <del> # attributes mimick an unchecked check box. <add> # attributes mimic an unchecked check box. <ide> # <ide> # This way, the client either sends only the hidden field (representing <ide> # the check box is unchecked), or both fields. Since the HTML specification <ide><path>actionpack/lib/action_view/helpers/form_options_helper.rb <ide> def option_groups_from_collection_for_select(collection, group_method, group_lab <ide> # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags, <ide> # which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options <ide> # as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>. <del> # * +prompt+ - set to true or a prompt string. When the select element doesn’t have a value yet, this <del> # prepends an option with a generic prompt — "Please select" — or the given prompt string. <add> # * +prompt+ - set to true or a prompt string. When the select element doesn't have a value yet, this <add> # prepends an option with a generic prompt - "Please select" - or the given prompt string. <ide> # <ide> # Sample usage (Array): <ide> # grouped_options = [ <ide><path>actionpack/lib/action_view/helpers/form_tag_helper.rb <ide> def html_options_for_form(url_for_options, options, *parameters_for_url) <ide> <ide> def extra_tags_for_form(html_options) <ide> case method = html_options.delete("method").to_s <del> when /^get$/i # must be case-insentive, but can't use downcase as might be nil <add> when /^get$/i # must be case-insensitive, but can't use downcase as might be nil <ide> html_options["method"] = "get" <ide> '' <ide> when /^post$/i, "", nil <ide><path>actionpack/lib/action_view/helpers/number_helper.rb <ide> def number_with_precision(number, *args) <ide> # number_to_human_size(483989, :precision => 2) # => 470 KB <ide> # number_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,2 MB <ide> # <del> # Unsignificant zeros after the fractional separator are stripped out by default (set <add> # Non-significant zeros after the fractional separator are stripped out by default (set <ide> # <tt>:strip_insignificant_zeros</tt> to +false+ to change that): <ide> # number_to_human_size(1234567890123, :precision => 5) # => "1.1229 TB" <ide> # number_to_human_size(524288000, :precision=>5) # => "500 MB" <ide><path>actionpack/lib/action_view/helpers/text_helper.rb <ide> def safe_concat(string) <ide> # truncate("Once upon a time in a world far far away", :length => 17) <ide> # # => "Once upon a ti..." <ide> # <del> # truncate("Once upon a time in a world far far away", :lenght => 17, :separator => ' ') <add> # truncate("Once upon a time in a world far far away", :length => 17, :separator => ' ') <ide> # # => "Once upon a..." <ide> # <ide> # truncate("And they found that many people were sleeping better.", :length => 25, :omission => '... (continued)') <ide><path>actionpack/lib/action_view/helpers/translation_helper.rb <ide> module TranslationHelper <ide> # to translate many keys within the same partials and gives you a simple framework for scoping them consistently. If you don't <ide> # prepend the key with a period, nothing is converted. <ide> # <del> # Third, it’ll mark the translation as safe HTML if the key has the suffix "_html" or the last element of the key is the word <del> # "html". For example, calling translate("footer_html") or translate("footer.html") will return a safe HTML string that won’t <add> # Third, it'll mark the translation as safe HTML if the key has the suffix "_html" or the last element of the key is the word <add> # "html". For example, calling translate("footer_html") or translate("footer.html") will return a safe HTML string that won't <ide> # be escaped by other HTML helper methods. This naming convention helps to identify translations that include HTML tags so that <ide> # you know what kind of output to expect when you call translate in a template. <ide> <ide><path>actionpack/lib/action_view/render/layouts.rb <ide> def _layout_for(name = nil, &block) #:nodoc: <ide> end <ide> <ide> # This is the method which actually finds the layout using details in the lookup <del> # context object. If no layout is found, it checkes if at least a layout with <add> # context object. If no layout is found, it checks if at least a layout with <ide> # the given name exists across all details before raising the error. <ide> def find_layout(layout) <ide> begin <ide><path>activemodel/lib/active_model/attribute_methods.rb <ide> class MissingAttributeError < NoMethodError <ide> # end <ide> # end <ide> # <del> # Please notice that whenever you include ActiveModel::AtributeMethods in your class, <add> # Please notice that whenever you include ActiveModel::AttributeMethods in your class, <ide> # it requires you to implement a <tt>attributes</tt> methods which returns a hash with <ide> # each attribute name in your model as hash key and the attribute value as hash value. <ide> # Hash keys must be a string. <ide><path>activemodel/lib/active_model/errors.rb <ide> def full_messages <ide> # default message (e.g. <tt>activemodel.errors.messages.MESSAGE</tt>). The translated model name, <ide> # translated attribute name and the value are available for interpolation. <ide> # <del> # When using inheritence in your models, it will check all the inherited models too, but only if the model itself <add> # When using inheritance in your models, it will check all the inherited models too, but only if the model itself <ide> # hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt> <ide> # error +message+ for the <tt>title</tt> +attribute+, it looks for these translations: <ide> # <ide><path>activemodel/lib/active_model/translation.rb <ide> module ActiveModel <ide> # extend ActiveModel::Translation <ide> # end <ide> # <del> # TranslatedPerson.human_attribute_name('my_attribue') <add> # TranslatedPerson.human_attribute_name('my_attribute') <ide> # #=> "My attribute" <ide> # <ide> # This also provides the required class methods for hooking into the <ide><path>activemodel/lib/active_model/validations.rb <ide> def validates_each(*attr_names, &block) <ide> end <ide> <ide> # Adds a validation method or block to the class. This is useful when <del> # overriding the +validate+ instance method becomes too unwieldly and <add> # overriding the +validate+ instance method becomes too unwieldy and <ide> # you're looking for more descriptive declaration of your validations. <ide> # <ide> # This can be done with a symbol pointing to a method: <ide> def invalid?(context = nil) <ide> !valid?(context) <ide> end <ide> <del> # Hook method defining how an attribute value should be retieved. By default this is assumed <add> # Hook method defining how an attribute value should be retrieved. By default this is assumed <ide> # to be an instance named after the attribute. Override this method in subclasses should you <ide> # need to retrieve the value for a given attribute differently e.g. <ide> # class MyClass <ide><path>activemodel/lib/active_model/validations/validates.rb <ide> module ClassMethods <ide> # validates :username, :presence => true <ide> # validates :username, :uniqueness => true <ide> # <del> # The power of the +validates+ method comes when using cusom validators <add> # The power of the +validates+ method comes when using custom validators <ide> # and default validators in one call for a given attribute e.g. <ide> # <ide> # class EmailValidator < ActiveModel::EachValidator <ide><path>activemodel/lib/active_model/validator.rb <ide> def self.kind <ide> @kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous? <ide> end <ide> <del> # Accepts options that will be made availible through the +options+ reader. <add> # Accepts options that will be made available through the +options+ reader. <ide> def initialize(options) <ide> @options = options <ide> end <ide> def validate(record) <ide> end <ide> end <ide> <del> # Override this method in subclasses with the validation logic, adding <add> # Override this method in subclasses with the validation logic, adding <ide> # errors to the records +errors+ array where necessary. <ide> def validate_each(record, attribute, value) <ide> raise NotImplementedError <ide><path>activerecord/lib/active_record/associations.rb <ide> def initialize(reflection) <ide> end <ide> end <ide> <del> # This error is raised when trying to destroy a parent instance in a N:1, 1:1 assosications <del> # (has_many, has_one) when there is at least 1 child assosociated instance. <add> # This error is raised when trying to destroy a parent instance in a N:1, 1:1 associations <add> # (has_many, has_one) when there is at least 1 child associated instance. <ide> # ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project <ide> class DeleteRestrictionError < ActiveRecordError #:nodoc: <ide> def initialize(reflection) <ide> module ClassMethods <ide> # [:inverse_of] <ide> # Specifies the name of the <tt>belongs_to</tt> association on the associated object that is the inverse of this <tt>has_many</tt> <ide> # association. Does not work in combination with <tt>:through</tt> or <tt>:as</tt> options. <del> # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional assocations for more detail. <add> # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. <ide> # <ide> # Option examples: <ide> # has_many :comments, :order => "posted_on" <ide> def has_many(association_id, options = {}, &extension) <ide> # [:inverse_of] <ide> # Specifies the name of the <tt>belongs_to</tt> association on the associated object that is the inverse of this <tt>has_one</tt> <ide> # association. Does not work in combination with <tt>:through</tt> or <tt>:as</tt> options. <del> # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional assocations for more detail. <add> # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. <ide> # <ide> # Option examples: <ide> # has_one :credit_card, :dependent => :destroy # destroys the associated credit card <ide> def has_one(association_id, options = {}) <ide> # [:inverse_of] <ide> # Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated object that is the inverse of this <tt>belongs_to</tt> <ide> # association. Does not work in combination with the <tt>:polymorphic</tt> options. <del> # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional assocations for more detail. <add> # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. <ide> # <ide> # Option examples: <ide> # belongs_to :firm, :foreign_key => "client_of" <ide><path>activerecord/lib/active_record/associations/through_association_scope.rb <ide> def construct_owner_attributes(reflection) <ide> <ide> # Construct attributes for :through pointing to owner and associate. <ide> def construct_join_attributes(associate) <del> # TODO: revist this to allow it for deletion, supposing dependent option is supported <add> # TODO: revisit this to allow it for deletion, supposing dependent option is supported <ide> raise ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(@owner, @reflection) if [:has_one, :has_many].include?(@reflection.source_reflection.macro) <ide> <ide> join_attributes = construct_owner_attributes(@reflection.through_reflection).merge(@reflection.source_reflection.primary_key_name => associate.id) <ide><path>activerecord/lib/active_record/autosave_association.rb <ide> def save_belongs_to_association(reflection) <ide> if association.updated? <ide> association_id = association.send(reflection.options[:primary_key] || :id) <ide> self[reflection.primary_key_name] = association_id <del> # TODO: Removing this code doesn't seem to matter… <add> # TODO: Removing this code doesn't seem to matter... <ide> if reflection.options[:polymorphic] <ide> self[reflection.options[:foreign_type]] = association.class.base_class.name.to_s <ide> end <ide><path>activerecord/lib/active_record/base.rb <ide> def initialize_copy(other) <ide> # For example in the test suite the topic model's after_initialize method sets the author_email_address to <ide> # test@test.com. I would have thought this would mean that all cloned models would have an author email address <ide> # of test@test.com. However the test_clone test method seems to test that this is not the case. As a result the <del> # after_initialize callback has to be run *before* the copying of the atrributes rather than afterwards in order <add> # after_initialize callback has to be run *before* the copying of the attributes rather than afterwards in order <ide> # for all tests to pass. This makes no sense to me. <ide> callback(:after_initialize) if respond_to_without_attributes?(:after_initialize) <ide> cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast) <ide><path>activerecord/lib/active_record/nested_attributes.rb <ide> def _destroy <ide> # Assigns the given attributes to the association. <ide> # <ide> # If update_only is false and the given attributes include an <tt>:id</tt> <del> # that matches the existing record’s id, then the existing record will be <add> # that matches the existing record's id, then the existing record will be <ide> # modified. If update_only is true, a new record is only created when no <ide> # object exists. Otherwise a new record will be built. <ide> # <ide><path>activerecord/lib/active_record/reflection.rb <ide> def build_association(*options) <ide> klass.new(*options) <ide> end <ide> <del> # Creates a new instance of the associated class, and immediates saves it <add> # Creates a new instance of the associated class, and immediately saves it <ide> # with ActiveRecord::Base#save. +options+ will be passed to the class's <ide> # creation method. Returns the newly created object. <ide> def create_association(*options) <ide> klass.create(*options) <ide> end <ide> <del> # Creates a new instance of the associated class, and immediates saves it <add> # Creates a new instance of the associated class, and immediately saves it <ide> # with ActiveRecord::Base#save!. +options+ will be passed to the class's <ide> # creation method. If the created record doesn't pass validations, then an <ide> # exception will be raised. <ide> def collection? <ide> # Returns whether or not the association should be validated as part of <ide> # the parent's validation. <ide> # <del> # Unless you explicitely disable validation with <add> # Unless you explicitly disable validation with <ide> # <tt>:validate => false</tt>, it will take place when: <ide> # <del> # * you explicitely enable validation; <tt>:validate => true</tt> <add> # * you explicitly enable validation; <tt>:validate => true</tt> <ide> # * you use autosave; <tt>:autosave => true</tt> <ide> # * the association is a +has_many+ association <ide> def validate? <ide><path>activerecord/lib/active_record/relation.rb <ide> def to_a <ide> preload += @includes_values unless eager_loading? <ide> preload.each {|associations| @klass.send(:preload_associations, @records, associations) } <ide> <del> # @readonly_value is true only if set explicity. @implicit_readonly is true if there are JOINS and no explicit SELECT. <add> # @readonly_value is true only if set explicitly. @implicit_readonly is true if there are JOINS and no explicit SELECT. <ide> readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value <ide> @records.each { |record| record.readonly! } if readonly <ide> <ide><path>activerecord/lib/active_record/schema_dumper.rb <ide> def default_string(value) <ide> def indexes(table, stream) <ide> if (indexes = @connection.indexes(table)).any? <ide> add_index_statements = indexes.map do |index| <del> statment_parts = [ ('add_index ' + index.table.inspect) ] <del> statment_parts << index.columns.inspect <del> statment_parts << (':name => ' + index.name.inspect) <del> statment_parts << ':unique => true' if index.unique <add> statement_parts = [ ('add_index ' + index.table.inspect) ] <add> statement_parts << index.columns.inspect <add> statement_parts << (':name => ' + index.name.inspect) <add> statement_parts << ':unique => true' if index.unique <ide> <ide> index_lengths = index.lengths.compact if index.lengths.is_a?(Array) <del> statment_parts << (':length => ' + Hash[*index.columns.zip(index.lengths).flatten].inspect) if index_lengths.present? <add> statement_parts << (':length => ' + Hash[*index.columns.zip(index.lengths).flatten].inspect) if index_lengths.present? <ide> <del> ' ' + statment_parts.join(', ') <add> ' ' + statement_parts.join(', ') <ide> end <ide> <ide> stream.puts add_index_statements.sort.join("\n") <ide><path>activeresource/lib/active_resource/base.rb <ide> def create(attributes = {}) <ide> # With any other scope, find returns nil when no data is returned. <ide> # <ide> # Person.find(1) <del> # # => raises ResourcenotFound <add> # # => raises ResourceNotFound <ide> # <ide> # Person.find(:all) <ide> # Person.find(:first) <ide> def schema <ide> end <ide> <ide> # This is a list of known attributes for this resource. Either <del> # gathered fromthe provided <tt>schema</tt>, or from the attributes <add> # gathered from the provided <tt>schema</tt>, or from the attributes <ide> # set on this instance after it has been fetched from the remote system. <ide> def known_attributes <ide> self.class.known_attributes + self.attributes.keys.map(&:to_s) <ide><path>activesupport/lib/active_support/cache.rb <ide> module Cache <ide> EMPTY_OPTIONS = {}.freeze <ide> <ide> # These options mean something to all cache implementations. Individual cache <del> # implementations may support additional optons. <add> # implementations may support additional options. <ide> UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl] <ide> <ide> module Strategy <ide><path>activesupport/lib/active_support/cache/memory_store.rb <ide> module Cache <ide> # appropriate cache for you. <ide> # <ide> # This cache has a bounded size specified by the :size options to the <del> # initializer (default is 32Mb). When the cache exceeds the alotted size, <add> # initializer (default is 32Mb). When the cache exceeds the allotted size, <ide> # a cleanup will occur which tries to prune the cache down to three quarters <ide> # of the maximum size by removing the least recently used entries. <ide> # <ide><path>activesupport/lib/active_support/core_ext/array/grouping.rb <ide> def in_groups_of(number, fill_with = nil) <ide> # ["6", "7"] <ide> def in_groups(number, fill_with = nil) <ide> # size / number gives minor group size; <del> # size % number gives how many objects need extra accomodation; <add> # size % number gives how many objects need extra accommodation; <ide> # each group hold either division or division + 1 items. <ide> division = size / number <ide> modulo = size % number <ide><path>activesupport/lib/active_support/core_ext/range/overlaps.rb <ide> class Range <del> # Compare two ranges and see if they overlap eachother <add> # Compare two ranges and see if they overlap each other <ide> # (1..5).overlaps?(4..6) # => true <ide> # (1..5).overlaps?(7..9) # => false <ide> def overlaps?(other) <ide><path>activesupport/lib/active_support/dependencies.rb <ide> def qualified_const_defined?(path) <ide> <ide> if Module.method(:const_defined?).arity == 1 <ide> # Does this module define this constant? <del> # Wrapper to accomodate changing Module#const_defined? in Ruby 1.9 <add> # Wrapper to accommodate changing Module#const_defined? in Ruby 1.9 <ide> def local_const_defined?(mod, const) <ide> mod.const_defined?(const) <ide> end <ide><path>activesupport/lib/active_support/multibyte.rb <ide> def self.proxy_class=(klass) <ide> @proxy_class = klass <ide> end <ide> <del> # Returns the currect proxy class <add> # Returns the current proxy class <ide> def self.proxy_class <ide> @proxy_class ||= ActiveSupport::Multibyte::Chars <ide> end <ide><path>activesupport/lib/active_support/notifications.rb <ide> module ActiveSupport <ide> # <ide> # event = @events.first <ide> # event.name #=> :render <del> # event.duration #=> 10 (in miliseconds) <add> # event.duration #=> 10 (in milliseconds) <ide> # event.result #=> "Foo" <ide> # event.payload #=> { :extra => :information } <ide> # <ide><path>activesupport/lib/active_support/time_with_zone.rb <ide> module ActiveSupport <ide> # <ide> # See Time and TimeZone for further documentation of these methods. <ide> # <del> # TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangable. Examples: <add> # TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangeable. Examples: <ide> # <ide> # t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00 <ide> # t.hour # => 13 <ide><path>activesupport/lib/active_support/values/time_zone.rb <ide> def formatted_offset(colon=true, alternate_utc_string = nil) <ide> utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon) <ide> end <ide> <del> # Compare this time zone to the parameter. The two are comapred first on <add> # Compare this time zone to the parameter. The two are compared first on <ide> # their offsets, and then by name. <ide> def <=>(zone) <ide> result = (utc_offset <=> zone.utc_offset)
42
Python
Python
update runtest settings to include staticfiles app
24ed6dcfdadb5c1e7b18a1b1dfabad871ee91f09
<ide><path>rest_framework/runtests/settings.py <ide> 'django.contrib.sessions', <ide> 'django.contrib.sites', <ide> 'django.contrib.messages', <add> 'django.contrib.staticfiles', <ide> # Uncomment the next line to enable the admin: <ide> # 'django.contrib.admin', <ide> # Uncomment the next line to enable admin documentation:
1
Ruby
Ruby
remove useless begin..end
70c83f49f8fcefdf52c2ed22706a14e29559cea5
<ide><path>railties/lib/rails/application.rb <ide> def reload_routes! <ide> def key_generator <ide> # number of iterations selected based on consultation with the google security <ide> # team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220 <del> @caching_key_generator ||= begin <add> @caching_key_generator ||= <ide> if secrets.secret_key_base <ide> key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000) <ide> ActiveSupport::CachingKeyGenerator.new(key_generator) <ide> else <ide> ActiveSupport::LegacyKeyGenerator.new(config.secret_token) <ide> end <del> end <ide> end <ide> <ide> # Returns a message verifier object.
1
Python
Python
remove invalid information
b2634ff922176acd12ddd3725434d3dfaaf25422
<ide><path>numpy/core/code_generators/ufunc_docstrings.py <ide> def add_newdoc(place, name, doc): <ide> Errors result if second argument is also supplied with scalar input or <ide> if first and second arguments have different shapes. <ide> <del> Numpy's definitions for positive infinity (PINF) and negative infinity <del> (NINF) may be change in the future versions. <del> <ide> Examples <ide> -------- <ide> >>> np.isinf(np.inf) <ide><path>numpy/lib/ufunclike.py <ide> def isposinf(x, y=None): <ide> Errors result if second argument is also supplied with scalar input or <ide> if first and second arguments have different shapes. <ide> <del> Numpy's definitions for positive infinity (PINF) and negative infinity <del> (NINF) may be change in the future versions. <del> <del> <ide> Examples <ide> -------- <ide> >>> np.isposinf(np.PINF)
2
PHP
PHP
add tests for hasone & belongsto saving
baa696a0d2fff00888af1c4655fa3dbd03ea69c5
<ide><path>Cake/Test/TestCase/ORM/Association/BelongsToTest.php <ide> public function testCascadeDelete() { <ide> $this->assertTrue($association->cascadeDelete($entity)); <ide> } <ide> <add>/** <add> * Test that save() ignores non entity values. <add> * <add> * @return void <add> */ <add> public function testSaveOnlyEntities() { <add> $mock = $this->getMock('Cake\ORM\Table', [], [], '', false); <add> $config = [ <add> 'sourceTable' => $this->client, <add> 'targetTable' => $mock, <add> ]; <add> $mock->expects($this->never()) <add> ->method('save'); <add> <add> $entity = new Entity([ <add> 'title' => 'A Title', <add> 'body' => 'A body', <add> 'author' => ['name' => 'Jose'] <add> ]); <add> <add> $association = new BelongsTo('Authors', $config); <add> $result = $association->save($entity); <add> $this->assertSame($result, $entity); <add> $this->assertNull($entity->author_id); <add> } <add> <ide> } <ide><path>Cake/Test/TestCase/ORM/Association/HasOneTest.php <ide> <ide> use Cake\Database\Expression\IdentifierExpression; <ide> use Cake\ORM\Association\HasOne; <add>use Cake\ORM\Entity; <ide> use Cake\ORM\Query; <ide> use Cake\ORM\Table; <ide> use Cake\ORM\TableRegistry; <ide> public function testAttachToNoFields() { <ide> $association->attachTo($query, ['includeFields' => false]); <ide> } <ide> <add>/** <add> * Test that save() ignores non entity values. <add> * <add> * @return void <add> */ <add> public function testSaveOnlyEntities() { <add> $mock = $this->getMock('Cake\ORM\Table', [], [], '', false); <add> $config = [ <add> 'sourceTable' => $this->user, <add> 'targetTable' => $mock, <add> ]; <add> $mock->expects($this->never()) <add> ->method('save'); <add> <add> $entity = new Entity([ <add> 'username' => 'Mark', <add> 'email' => 'mark@example.com', <add> 'profile' => ['twitter' => '@cakephp'] <add> ]); <add> <add> $association = new HasOne('Profiles', $config); <add> $result = $association->save($entity); <add> <add> $this->assertSame($result, $entity); <add> } <ide> }
2
PHP
PHP
remove typo in method comment
00b512a87686c847e9de758ef7275f5aacf87485
<ide><path>laravel/url.php <ide> public static function base() <ide> // By removing the basename of the script, we should be left with the path <ide> // in which the framework is installed. For example, if the framework is <ide> // installed to http://localhost/laravel/public, the path we'll get from <del> // from this statement will be "/laravel/public". <add> // this statement will be "/laravel/public". <ide> $path = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); <ide> <ide> return rtrim($protocol.$_SERVER['HTTP_HOST'].$path, '/');
1
Ruby
Ruby
use pkg_version accessor
58464287bc35282a5001a1f9a3f69cecc7c552c7
<ide><path>Library/Homebrew/cmd/bottle.rb <ide> def merge <ide> end <ide> end <ide> <del> version = f.version.to_s <del> version += "_#{f.revision}" if f.revision.to_i > 0 <del> <ide> HOMEBREW_REPOSITORY.cd do <ide> safe_system "git", "commit", "--no-edit", "--verbose", <del> "--message=#{f.name}: #{update_or_add} #{version} bottle.", <add> "--message=#{f.name}: #{update_or_add} #{f.pkg_version} bottle.", <ide> "--", f.path <ide> end <ide> end
1
Python
Python
avoid enumerate to avoid long waiting at 0%
9cf965c26056065d6476b2a4336a42423bef3600
<ide><path>bin/wiki_entity_linking/wikipedia_processor.py <ide> def read_el_docs_golds(nlp, entity_file_path, dev, line_ids, kb, labels_discard= <ide> if not labels_discard: <ide> labels_discard = [] <ide> <del> texts = [] <del> entities_list = [] <add> max_index = max(line_ids) <ide> <del> with entity_file_path.open("r", encoding="utf8") as file: <del> for i, line in enumerate(file): <add> with entity_file_path.open("r", encoding="utf8") as _file: <add> line = _file.readline() <add> i = 0 <add> while line and i < max_index: <ide> if i in line_ids: <ide> example = json.loads(line) <ide> article_id = example["article_id"] <ide> def read_el_docs_golds(nlp, entity_file_path, dev, line_ids, kb, labels_discard= <ide> if dev != is_dev(article_id) or not is_valid_article(clean_text): <ide> continue <ide> <del> texts.append(clean_text) <del> entities_list.append(entities) <del> <del> docs = nlp.pipe(texts, batch_size=50) <del> <del> for doc, entities in zip(docs, entities_list): <del> gold = _get_gold_parse(doc, entities, dev=dev, kb=kb, labels_discard=labels_discard) <del> if gold and len(gold.links) > 0: <del> yield doc, gold <add> doc = nlp(clean_text) <add> gold = _get_gold_parse(doc, entities, dev=dev, kb=kb, labels_discard=labels_discard) <add> if gold and len(gold.links) > 0: <add> yield doc, gold <add> i += 1 <add> line = _file.readline() <ide> <ide> <ide> def _get_gold_parse(doc, entities, dev, kb, labels_discard):
1
Python
Python
add distillation+finetuning option in run_squad
764a7923ec1ca27a3c35e6c3eb7c1574f75e741c
<ide><path>examples/run_squad.py <ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <del>""" Finetuning the library models for question-answering on SQuAD (Bert, XLM, XLNet).""" <add>""" Finetuning the library models for question-answering on SQuAD (DistilBERT, Bert, XLM, XLNet) with an optional step of distillation.""" <ide> <ide> from __future__ import absolute_import, division, print_function <ide> <ide> from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, <ide> TensorDataset) <ide> from torch.utils.data.distributed import DistributedSampler <add>import torch.nn.functional as F <add>import torch.nn as nn <ide> from tqdm import tqdm, trange <ide> <ide> from tensorboardX import SummaryWriter <ide> def set_seed(args): <ide> def to_list(tensor): <ide> return tensor.detach().cpu().tolist() <ide> <del>def train(args, train_dataset, model, tokenizer): <add>def train(args, train_dataset, model, tokenizer, teacher=None): <ide> """ Train the model """ <ide> if args.local_rank in [-1, 0]: <ide> tb_writer = SummaryWriter() <ide> def train(args, train_dataset, model, tokenizer): <ide> epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0]) <ide> for step, batch in enumerate(epoch_iterator): <ide> model.train() <add> if teacher is not None: <add> teacher.eval() <ide> batch = tuple(t.to(args.device) for t in batch) <ide> inputs = {'input_ids': batch[0], <ide> 'attention_mask': batch[1], <del> 'token_type_ids': None if args.model_type == 'xlm' else batch[2], <ide> 'start_positions': batch[3], <ide> 'end_positions': batch[4]} <add> if args.model_type != 'distilbert': <add> inputs['token_type_ids'] = None if args.model_type == 'xlm' else batch[2] <ide> if args.model_type in ['xlnet', 'xlm']: <ide> inputs.update({'cls_index': batch[5], <ide> 'p_mask': batch[6]}) <ide> outputs = model(**inputs) <del> loss = outputs[0] # model outputs are always tuple in transformers (see doc) <add> loss, start_logits_stu, end_logits_stu = outputs <add> <add> # Distillation loss <add> if teacher is not None: <add> if 'token_type_ids' not in inputs: <add> inputs['token_type_ids'] = None if args.teacher_type == 'xlm' else batch[2] <add> with torch.no_grad(): <add> start_logits_tea, end_logits_tea = teacher(input_ids=inputs['input_ids'], <add> token_type_ids=inputs['token_type_ids'], <add> attention_mask=inputs['attention_mask']) <add> assert start_logits_tea.size() == start_logits_stu.size() <add> assert end_logits_tea.size() == end_logits_stu.size() <add> <add> loss_fct = nn.KLDivLoss(reduction='batchmean') <add> loss_start = loss_fct(F.log_softmax(start_logits_stu/args.temperature, dim=-1), <add> F.softmax(start_logits_tea/args.temperature, dim=-1)) * (args.temperature**2) <add> loss_end = loss_fct(F.log_softmax(end_logits_stu/args.temperature, dim=-1), <add> F.softmax(end_logits_tea/args.temperature, dim=-1)) * (args.temperature**2) <add> loss_ce = (loss_start + loss_end)/2. <add> <add> loss = args.alpha_ce*loss_ce + args.alpha_squad*loss <ide> <ide> if args.n_gpu > 1: <ide> loss = loss.mean() # mean() to average on multi-gpu parallel (not distributed) training <ide> def evaluate(args, model, tokenizer, prefix=""): <ide> batch = tuple(t.to(args.device) for t in batch) <ide> with torch.no_grad(): <ide> inputs = {'input_ids': batch[0], <del> 'attention_mask': batch[1], <del> 'token_type_ids': None if args.model_type == 'xlm' else batch[2] # XLM don't use segment_ids <add> 'attention_mask': batch[1] <ide> } <add> if args.model_type != 'distilbert': <add> inputs['token_type_ids'] = None if args.model_type == 'xlm' else batch[2] # XLM don't use segment_ids <ide> example_indices = batch[3] <ide> if args.model_type in ['xlnet', 'xlm']: <ide> inputs.update({'cls_index': batch[4], <ide> def main(): <ide> parser.add_argument("--output_dir", default=None, type=str, required=True, <ide> help="The output directory where the model checkpoints and predictions will be written.") <ide> <add> # Distillation parameters (optional) <add> parser.add_argument('--teacher_type', default=None, type=str, <add> help="Teacher type. Teacher tokenizer and student (model) tokenizer must output the same tokenization. Only for distillation.") <add> parser.add_argument('--teacher_name_or_path', default=None, type=str, <add> help="Path to the already SQuAD fine-tuned teacher model. Only for distillation.") <add> parser.add_argument('--alpha_ce', default=0.5, type=float, <add> help="Distillation loss linear weight. Only for distillation.") <add> parser.add_argument('--alpha_squad', default=0.5, type=float, <add> help="True SQuAD loss linear weight. Only for distillation.") <add> parser.add_argument('--temperature', default=2.0, type=float, <add> help="Distillation temperature. Only for distillation.") <add> <ide> ## Other parameters <ide> parser.add_argument("--config_name", default="", type=str, <ide> help="Pretrained config name or path if not the same as model_name") <ide> def main(): <ide> tokenizer = tokenizer_class.from_pretrained(args.tokenizer_name if args.tokenizer_name else args.model_name_or_path, do_lower_case=args.do_lower_case) <ide> model = model_class.from_pretrained(args.model_name_or_path, from_tf=bool('.ckpt' in args.model_name_or_path), config=config) <ide> <add> if args.teacher_type is not None: <add> assert args.teacher_name_or_path is not None <add> assert args.alpha_ce > 0. <add> assert args.alpha_ce + args.alpha_squad > 0. <add> assert args.teacher_type != 'distilbert', "We constraint teachers not to be of type DistilBERT." <add> teacher_config_class, teacher_model_class, _ = MODEL_CLASSES[args.teacher_type] <add> teacher_config = teacher_config_class.from_pretrained(args.teacher_name_or_path) <add> teacher = teacher_model_class.from_pretrained(args.teacher_name_or_path, config=teacher_config) <add> teacher.to(args.device) <add> else: <add> teacher = None <add> <ide> if args.local_rank == 0: <ide> torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab <ide> <ide> def main(): <ide> # Training <ide> if args.do_train: <ide> train_dataset = load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False) <del> global_step, tr_loss = train(args, train_dataset, model, tokenizer) <add> global_step, tr_loss = train(args, train_dataset, model, tokenizer, teacher=teacher) <ide> logger.info(" global_step = %s, average loss = %s", global_step, tr_loss) <ide> <ide>
1
Ruby
Ruby
move origin_branch from utils/git
92d3eda91425db1b5bf41a7ac02cc2d500106d8f
<ide><path>Library/Homebrew/dev-cmd/bump-cask-pr.rb <ide> def bump_cask_pr <ide> old_hash = cask.sha256.to_s <ide> <ide> tap_full_name = cask.tap&.full_name <del> origin_branch = Utils::Git.origin_branch(cask.tap.path) if cask.tap <del> origin_branch ||= "origin/master" <add> default_remote_branch = cask.tap.path.git_origin_branch if cask.tap <add> default_remote_branch ||= "master" <ide> previous_branch = "-" <ide> <ide> check_open_pull_requests(cask, tap_full_name, args: args) <ide> def bump_cask_pr <ide> pr_info = { <ide> sourcefile_path: cask.sourcefile_path, <ide> old_contents: old_contents, <del> origin_branch: origin_branch, <add> remote_branch: default_remote_branch, <ide> branch_name: "bump-#{cask.token}-#{new_version.tr(",:", "-")}", <ide> commit_message: "Update #{cask.token} from #{old_version} to #{new_version}", <ide> previous_branch: previous_branch, <ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb <ide> def bump_formula_pr_args <ide> end <ide> <ide> def use_correct_linux_tap(formula, args:) <del> if OS.linux? && formula.tap.core_tap? <del> tap_full_name = formula.tap.full_name.gsub("linuxbrew", "homebrew") <del> homebrew_core_url = "https://github.com/#{tap_full_name}" <del> homebrew_core_remote = "homebrew" <del> homebrew_core_branch = "master" <del> origin_branch = "#{homebrew_core_remote}/#{homebrew_core_branch}" <del> previous_branch = Utils.popen_read("git -C \"#{formula.tap.path}\" symbolic-ref -q --short HEAD").chomp <del> previous_branch = "master" if previous_branch.empty? <del> formula_path = formula.path.to_s[%r{(Formula/.*)}, 1] <del> <del> if args.dry_run? || args.write? <del> ohai "git remote add #{homebrew_core_remote} #{homebrew_core_url}" <del> ohai "git fetch #{homebrew_core_remote} #{homebrew_core_branch}" <del> ohai "git cat-file -e #{origin_branch}:#{formula_path}" <del> ohai "git checkout #{origin_branch}" <del> return tap_full_name, origin_branch, previous_branch <del> else <del> formula.path.parent.cd do <del> unless Utils.popen_read("git remote -v").match?(%r{^homebrew.*Homebrew/homebrew-core.*$}) <del> ohai "Adding #{homebrew_core_remote} remote" <del> safe_system "git", "remote", "add", homebrew_core_remote, homebrew_core_url <del> end <del> ohai "Fetching #{origin_branch}" <del> safe_system "git", "fetch", homebrew_core_remote, homebrew_core_branch <del> if quiet_system "git", "cat-file", "-e", "#{origin_branch}:#{formula_path}" <del> ohai "#{formula.full_name} exists in #{origin_branch}" <del> safe_system "git", "checkout", origin_branch <del> return tap_full_name, origin_branch, previous_branch <del> end <del> end <del> end <add> default_origin_branch = formula.tap.path.git_origin_branch if formula.tap <add> <add> return formula.tap&.full_name, "origin", default_origin_branch, "-" if !OS.linux? || !formula.tap.core_tap? <add> <add> tap_full_name = formula.tap.full_name.gsub("linuxbrew", "homebrew") <add> homebrew_core_url = "https://github.com/#{tap_full_name}" <add> homebrew_core_remote = "homebrew" <add> previous_branch = formula.tap.path.git_branch || "master" <add> formula_path = formula.path.relative_path_from(formula.tap.path) <add> full_origin_branch = "#{homebrew_core_remote}/#{default_origin_branch}" <add> <add> if args.dry_run? || args.write? <add> ohai "git remote add #{homebrew_core_remote} #{homebrew_core_url}" <add> ohai "git fetch #{homebrew_core_remote} HEAD #{default_origin_branch}" <add> ohai "git cat-file -e #{full_origin_branch}:#{formula_path}" <add> ohai "git checkout #{full_origin_branch}" <add> return tap_full_name, homebrew_core_remote, default_origin_branch, previous_branch <ide> end <del> if formula.tap <del> origin_branch = Utils.popen_read("git", "-C", formula.tap.path.to_s, "symbolic-ref", "-q", "--short", <del> "refs/remotes/origin/HEAD").chomp.presence <add> <add> formula.tap.path.cd do <add> unless Utils.popen_read("git remote -v").match?(%r{^homebrew.*Homebrew/homebrew-core.*$}) <add> ohai "Adding #{homebrew_core_remote} remote" <add> safe_system "git", "remote", "add", homebrew_core_remote, homebrew_core_url <add> end <add> ohai "Fetching remote #{homebrew_core_remote}" <add> safe_system "git", "fetch", homebrew_core_remote, "HEAD", default_origin_branch <add> if quiet_system "git", "cat-file", "-e", "#{full_origin_branch}:#{formula_path}" <add> ohai "#{formula.full_name} exists in #{full_origin_branch}" <add> safe_system "git", "checkout", full_origin_branch <add> return tap_full_name, homebrew_core_remote, default_origin_branch, previous_branch <add> end <ide> end <del> origin_branch ||= "origin/master" <del> [formula.tap&.full_name, origin_branch, "-"] <ide> end <ide> <ide> def bump_formula_pr <ide> def bump_formula_pr <ide> <ide> odie "This formula is disabled!" if formula.disabled? <ide> <del> tap_full_name, origin_branch, previous_branch = use_correct_linux_tap(formula, args: args) <add> tap_full_name, remote, remote_branch, previous_branch = use_correct_linux_tap(formula, args: args) <ide> check_open_pull_requests(formula, tap_full_name, args: args) <ide> <ide> new_version = args.version <ide> def bump_formula_pr <ide> sourcefile_path: formula.path, <ide> old_contents: old_contents, <ide> additional_files: alias_rename, <del> origin_branch: origin_branch, <add> remote: remote, <add> remote_branch: remote_branch, <ide> branch_name: "bump-#{formula.name}-#{new_formula_version}", <ide> commit_message: "#{formula.name} #{new_formula_version}", <ide> previous_branch: previous_branch, <ide><path>Library/Homebrew/dev-cmd/pr-pull.rb <ide> def pr_pull <ide> _, user, repo, pr = *url_match <ide> odie "Not a GitHub pull request: #{arg}" unless pr <ide> <del> current_branch = tap.path.git_branch <del> origin_branch = Utils::Git.origin_branch(tap.path).split("/").last <del> <del> if current_branch != origin_branch || args.branch_okay? || args.clean? <del> opoo "Current branch is #{current_branch}: do you need to pull inside #{origin_branch}?" <add> if !tap.path.git_default_origin_branch? || args.branch_okay? || args.clean? <add> opoo "Current branch is #{tap.path.git_branch}: do you need to pull inside #{tap.path.git_origin_branch}?" <ide> end <ide> <ide> ohai "Fetching #{tap} pull request ##{pr}" <ide><path>Library/Homebrew/diagnostic.rb <ide> def check_tap_git_branch <ide> return unless Utils::Git.available? <ide> <ide> commands = Tap.map do |tap| <del> next unless tap.path.git? <del> next if tap.path.git_origin.blank? <add> next if tap.path.git_default_origin_branch? <ide> <del> branch = tap.path.git_branch <del> next if branch.blank? <del> <del> origin_branch = Utils::Git.origin_branch(tap.path)&.split("/")&.last <del> next if origin_branch == branch <del> <del> "git -C $(brew --repo #{tap.name}) checkout #{origin_branch}" <add> "git -C $(brew --repo #{tap.name}) checkout #{tap.path.git_origin_branch}" <ide> end.compact <ide> <ide> return if commands.blank? <ide><path>Library/Homebrew/extend/git_repository.rb <ide> def git_branch <ide> Utils.popen_read("git", "rev-parse", "--abbrev-ref", "HEAD", chdir: self).chomp.presence <ide> end <ide> <add> # Gets the name of the default origin HEAD branch. <add> sig { returns(T.nilable(String)) } <add> def git_origin_branch <add> return unless git? && Utils::Git.available? <add> <add> Utils.popen_read("git", "symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD", chdir: self) <add> .chomp.presence&.split("/")&.last <add> end <add> <add> # Returns true if the repository's current branch matches the default origin branch. <add> sig { returns(T.nilable(T::Boolean)) } <add> def git_default_origin_branch? <add> git_origin_branch == git_branch <add> end <add> <ide> # Returns the date of the last commit, in YYYY-MM-DD format. <ide> sig { returns(T.nilable(String)) } <ide> def git_last_commit_date <ide><path>Library/Homebrew/utils/git.rb <ide> def setup_gpg! <ide> end <ide> <ide> def origin_branch(repo) <del> Utils.popen_read(git, "-C", repo, "symbolic-ref", "-q", "--short", <del> "refs/remotes/origin/HEAD").chomp.presence <add> odeprecated "Utils::Git.origin_branch(repo)", "Pathname(repo).git_origin_branch" <add> Pathname(repo).extend(GitRepositoryExtension).git_origin_branch <ide> end <ide> <ide> def current_branch(repo) <ide><path>Library/Homebrew/utils/github.rb <ide> def create_bump_pr(info, args:) <ide> sourcefile_path = info[:sourcefile_path] <ide> old_contents = info[:old_contents] <ide> additional_files = info[:additional_files] || [] <del> origin_branch = info[:origin_branch] <add> remote = info[:remote] || "origin" <add> remote_branch = info[:remote_branch] <ide> branch = info[:branch_name] <ide> commit_message = info[:commit_message] <ide> previous_branch = info[:previous_branch] <ide> def create_bump_pr(info, args:) <ide> pr_message = info[:pr_message] <ide> <ide> sourcefile_path.parent.cd do <del> _, base_branch = origin_branch.split("/") <ide> git_dir = Utils.popen_read("git rev-parse --git-dir").chomp <ide> shallow = !git_dir.empty? && File.exist?("#{git_dir}/shallow") <ide> changed_files = [sourcefile_path] <ide> def create_bump_pr(info, args:) <ide> ohai "try to fork repository with GitHub API" unless args.no_fork? <ide> ohai "git fetch --unshallow origin" if shallow <ide> ohai "git add #{changed_files.join(" ")}" <del> ohai "git checkout --no-track -b #{branch} #{origin_branch}" <add> ohai "git checkout --no-track -b #{branch} #{remote}/#{remote_branch}" <ide> ohai "git commit --no-edit --verbose --message='#{commit_message}'" \ <ide> " -- #{changed_files.join(" ")}" <ide> ohai "git push --set-upstream $HUB_REMOTE #{branch}:#{branch}" <ide> ohai "git checkout --quiet #{previous_branch}" <del> ohai "create pull request with GitHub API (base branch: #{base_branch})" <add> ohai "create pull request with GitHub API (base branch: #{remote_branch})" <ide> else <ide> <ide> unless args.commit? <ide> def create_bump_pr(info, args:) <ide> end <ide> <ide> safe_system "git", "add", *changed_files <del> safe_system "git", "checkout", "--no-track", "-b", branch, origin_branch unless args.commit? <add> safe_system "git", "checkout", "--no-track", "-b", branch, "#{remote}/#{remote_branch}" unless args.commit? <ide> safe_system "git", "commit", "--no-edit", "--verbose", <ide> "--message=#{commit_message}", <ide> "--", *changed_files <ide> def create_bump_pr(info, args:) <ide> <ide> begin <ide> url = GitHub.create_pull_request(tap_full_name, commit_message, <del> "#{username}:#{branch}", base_branch, pr_message)["html_url"] <add> "#{username}:#{branch}", remote_branch, pr_message)["html_url"] <ide> if args.no_browse? <ide> puts url <ide> else
7
Javascript
Javascript
create polyvinyl type
f0aad07234dbd63f08c0a1030030c75cd9ac0803
<ide><path>client/new-framework/polyvinyl.js <del>// originally base off of https://github.com/gulpjs/vinyl <del>import path from 'path'; <del>import replaceExt from 'replace-ext'; <del> <del>export default class File { <del> constructor({ <del> path, <del> history = [], <del> base, <del> contents = '' <del> } = {}) { <del> // Record path change <del> this.history = path ? [path] : history; <del> this.base = base || this.cwd; <del> this.contents = contents; <del> this._isPolyVinyl = true; <del> this.error = null; <del> } <del> <del> static isPolyVinyl = function(file) { <del> return file && file._isPolyVinyl === true || false; <del> }; <del> <del> isEmpty() { <del> return !this._contents; <del> } <del> <del> get contents() { <del> return this._contents; <del> } <del> <del> set contents(val) { <del> if (typeof val !== 'string') { <del> throw new TypeError('File.contents can only a String'); <del> } <del> this._contents = val; <del> } <del> <del> get basename() { <del> if (!this.path) { <del> throw new Error('No path specified! Can not get basename.'); <del> } <del> return path.basename(this.path); <del> } <del> <del> set basename(basename) { <del> if (!this.path) { <del> throw new Error('No path specified! Can not set basename.'); <del> } <del> this.path = path.join(path.dirname(this.path), basename); <del> } <del> <del> get extname() { <del> if (!this.path) { <del> throw new Error('No path specified! Can not get extname.'); <del> } <del> return path.extname(this.path); <del> } <del> <del> set extname(extname) { <del> if (!this.path) { <del> throw new Error('No path specified! Can not set extname.'); <del> } <del> this.path = replaceExt(this.path, extname); <del> } <del> <del> get path() { <del> return this.history[this.history.length - 1]; <del> } <del> <del> set path(path) { <del> if (typeof path !== 'string') { <del> throw new TypeError('path should be string'); <del> } <del> <del> // Record history only when path changed <del> if (path && path !== this.path) { <del> this.history.push(path); <del> } <del> } <del> <del> get error() { <del> return this._error; <del> } <del> <del> set error(err) { <del> if (typeof err !== 'object') { <del> throw new TypeError('error must be an object or null'); <del> } <del> this.error = err; <del> } <del>}
1
Ruby
Ruby
fix radio_button_tag comment
11a89674aff171155043fa284035243982842d8d
<ide><path>actionview/lib/action_view/helpers/form_tag_helper.rb <ide> def check_box_tag(name, value = "1", checked = false, options = {}) <ide> # # => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" /> <ide> # <ide> # radio_button_tag 'time_slot', "3:00 p.m.", false, disabled: true <del> # # => <input disabled="disabled" id="time_slot_300_pm" name="time_slot" type="radio" value="3:00 p.m." /> <add> # # => <input disabled="disabled" id="time_slot_3:00_p.m." name="time_slot" type="radio" value="3:00 p.m." /> <ide> # <ide> # radio_button_tag 'color', "green", true, class: "color_input" <ide> # # => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" />
1
PHP
PHP
remove preference for snake case from model
ca5b9bdcde45ea49dd85be465cc62cdd0daf18b1
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function belongsTo($related, $foreignKey = null) <ide> * Define an polymorphic, inverse one-to-one or many relationship. <ide> * <ide> * @param string $name <add> * @param string $type <add> * @param string $id <ide> * @return Illuminate\Database\Eloquent\Relations\BelongsTo <ide> */ <del> public function morphTo($name = null) <add> public function morphTo($name = null, $type = null, $id = null) <ide> { <ide> // If no name is provided, we will use the backtrace to get the function name <ide> // since that is most likely the name of the polymorphic interface. We can <ide> public function morphTo($name = null) <ide> $name = snake_case($caller['function']); <ide> } <ide> <del> return $this->belongsTo($this->{"{$name}_type"}, "{$name}_id"); <add> // Next we will guess the type and ID if necessary. The type and IDs may also <add> // be passed into the function so that the developers may manually specify <add> // them on the relations. Otherwise, we will just make a great estimate. <add> $type = $type ?: $name.'_type'; <add> <add> $id = $id ?: $id.'_id'; <add> <add> return $this->belongsTo($this->{$type}, $id); <ide> } <ide> <ide> /** <ide> public function relationsToArray() <ide> */ <ide> public function getAttribute($key) <ide> { <del> $snake = snake_case($key); <del> <del> $inAttributes = array_key_exists($snake, $this->attributes); <add> $inAttributes = array_key_exists($$key, $this->attributes); <ide> <ide> // If the key references an attribute, we can just go ahead and return the <ide> // plain attribute value from the model. This allows every attribute to <ide> // be dynamically accessed through the _get method without accessors. <del> if ($inAttributes or $this->hasGetMutator($snake)) <add> if ($inAttributes or $this->hasGetMutator($$key)) <ide> { <del> return $this->getPlainAttribute($snake); <add> return $this->getPlainAttribute($$key); <ide> } <ide> <ide> // If the key already exists in the relationships array, it just means the <ide> // relationship has already been loaded, so we'll just return it out of <ide> // here because there is no need to query within the relations twice. <del> if (array_key_exists($snake, $this->relations)) <add> if (array_key_exists($$key, $this->relations)) <ide> { <del> return $this->relations[$snake]; <add> return $this->relations[$$key]; <ide> } <ide> <ide> // If the "attribute" exists as a method on the model, we will just assume <ide> public function getAttribute($key) <ide> { <ide> $relations = $this->$key()->getResults(); <ide> <del> return $this->relations[$snake] = $relations; <add> return $this->relations[$$key] = $relations; <ide> } <ide> } <ide> <ide> public function hasGetMutator($key) <ide> */ <ide> public function setAttribute($key, $value) <ide> { <del> $key = snake_case($key); <del> <ide> // First we will check for the presence of a mutator for the set operation <ide> // which simply lets the developers tweak the attribute as it is set on <ide> // the model, such as "json_encoding" an listing of data for storage.
1
Javascript
Javascript
fix failing tests
7c4e925553ac3a0bdfcc14ba44d19c5719ab6c95
<ide><path>packages/ember-runtime/tests/helpers/array.js <ide> const ArrayTestsObserverClass = EmberObject.extend({ <ide> return this; <ide> }, <ide> <del> observe(obj) { <add> observe(obj, ...keys) { <ide> if (obj.addObserver) { <del> let keys = Array.prototype.slice.call(arguments, 1); <ide> let loc = keys.length; <ide> <ide> while (--loc >= 0) { <ide><path>packages/ember-runtime/tests/mutable-array/unshiftObjects-test.js <ide> class UnshiftObjectsTests extends AbstractTestCase { <ide> this.assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once'); <ide> this.assert.equal(observer.timesCalled('length'), 1, 'should have notified length once'); <ide> <del> this.assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject'); <add> this.assert.equal(observer.validate('firstObject'), true, 'should NOT have notified firstObject'); <ide> this.assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject'); <ide> } <ide> }
2
Javascript
Javascript
add asobject compat mode for ember-htmlbars
73499f627f1c6151dc05ce38f82f1b4b8db578e4
<ide><path>packages/ember-htmlbars/lib/compat/precompile.js <del>import { compile } from "htmlbars-compiler/compiler"; <add>import { compile, compileSpec } from "htmlbars-compiler/compiler"; <ide> <del>export default compile; <add>export default function(string) { <add> var asObject = arguments[1] === undefined ? true : arguments[1]; <add> var compileFunc = asObject ? compile : compileSpec; <add> <add> return compileFunc(string); <add>} <add><path>packages/ember-htmlbars/tests/compat/precompile_test.js <del><path>packages/ember-handlebars-compiler/tests/precompile_type_test.js <ide> var parse = EmberHandlebars.parse; <ide> var template = 'Hello World'; <ide> var result; <ide> <del>QUnit.module("Ember.Handlebars.precompileType"); <add>QUnit.module("ember-htmlbars: Ember.Handlebars.precompile"); <ide> <del>if (!Ember.FEATURES.isEnabled('ember-htmlbars')) { <del> // precompile does not accept the same args with ember-htmlbars/system/compile <del> // Do we need to support `asObject` param? <add>var templateType; <add>if (Ember.FEATURES.isEnabled('ember-htmlbars')) { <add> templateType = 'function'; <add>} else { <add> templateType = 'object'; <add>} <ide> <ide> test("precompile creates an object when asObject isn't defined", function(){ <ide> result = precompile(template); <del> equal(typeof(result), "object"); <add> equal(typeof(result), templateType); <ide> }); <ide> <ide> test("precompile creates an object when asObject is true", function(){ <ide> result = precompile(template, true); <del> equal(typeof(result), "object"); <add> equal(typeof(result), templateType); <ide> }); <ide> <ide> test("precompile creates a string when asObject is false", function(){ <ide> result = precompile(template, false); <ide> equal(typeof(result), "string"); <ide> }); <ide> <add>if (!Ember.FEATURES.isEnabled('ember-htmlbars')) { <add> <ide> test("precompile creates an object when passed an AST", function(){ <ide> var ast = parse(template); <ide> result = precompile(ast);
2
Javascript
Javascript
allow retrying symbolication
d6b9ec1c1f5d1f6e44c2b8beedab2381ae281584
<ide><path>Libraries/YellowBox/Data/YellowBoxSymbolication.js <ide> export type Stack = Array<StackFrame>; <ide> const cache: Map<CacheKey, Promise<Stack>> = new Map(); <ide> <ide> const YellowBoxSymbolication = { <add> delete(stack: Stack): void { <add> cache.delete(getCacheKey(stack)); <add> }, <add> <ide> symbolicate(stack: Stack): Promise<Stack> { <ide> const key = getCacheKey(stack); <ide> <ide><path>Libraries/YellowBox/Data/YellowBoxWarning.js <ide> class YellowBoxWarning { <ide> : this.stack; <ide> } <ide> <add> retrySymbolicate(callback: () => void): SymbolicationRequest { <add> YellowBoxSymbolication.delete(this.stack); <add> return this.symbolicate(callback); <add> } <add> <ide> symbolicate(callback: () => void): SymbolicationRequest { <ide> let aborted = false; <ide> <ide><path>Libraries/YellowBox/UI/YellowBoxInspector.js <ide> class YellowBoxInspector extends React.Component<Props, State> { <ide> <View style={styles.bodyHeading}> <ide> <Text style={styles.bodyHeadingText}>Stack</Text> <ide> <YellowBoxInspectorSourceMapStatus <add> onPress={ <add> warning.symbolicated.status === 'FAILED' <add> ? this._handleRetrySymbolication <add> : null <add> } <ide> status={warning.symbolicated.status} <ide> /> <ide> </View> <ide> class YellowBoxInspector extends React.Component<Props, State> { <ide> this._cancelSymbolication(); <ide> } <ide> <add> _handleRetrySymbolication = () => { <add> this._cancelSymbolication(); <add> this.forceUpdate(() => { <add> const warning = this.props.warnings[this.state.selectedIndex]; <add> this._symbolication = warning.retrySymbolicate(() => { <add> this.forceUpdate(); <add> }); <add> }); <add> }; <add> <ide> _handleSymbolication(): void { <ide> const warning = this.props.warnings[this.state.selectedIndex]; <ide> if (warning.symbolicated.status !== 'COMPLETE') { <ide><path>Libraries/YellowBox/UI/YellowBoxInspectorSourceMapStatus.js <ide> const Easing = require('Easing'); <ide> const React = require('React'); <ide> const StyleSheet = require('StyleSheet'); <ide> const Text = require('Text'); <del>const View = require('View'); <ide> const YellowBoxImageSource = require('YellowBoxImageSource'); <add>const YellowBoxPressable = require('YellowBoxPressable'); <ide> const YellowBoxStyle = require('YellowBoxStyle'); <ide> <ide> import type {CompositeAnimation} from 'AnimatedImplementation'; <ide> import type AnimatedInterpolation from 'AnimatedInterpolation'; <add>import type {PressEvent} from 'CoreEventTypes'; <ide> <ide> type Props = $ReadOnly<{| <add> onPress?: ?(event: PressEvent) => void, <ide> status: 'COMPLETE' | 'FAILED' | 'NONE' | 'PENDING', <ide> |}>; <ide> <ide> class YellowBoxInspectorSourceMapStatus extends React.Component<Props, State> { <ide> } <ide> <ide> return image == null ? null : ( <del> <View <add> <YellowBoxPressable <add> backgroundColor={{ <add> default: YellowBoxStyle.getTextColor(0.8), <add> pressed: YellowBoxStyle.getTextColor(0.6), <add> }} <add> hitSlop={{bottom: 8, left: 8, right: 8, top: 8}} <add> onPress={this.props.onPress} <ide> style={StyleSheet.compose( <ide> styles.root, <ide> this.props.status === 'PENDING' ? styles.pending : null, <ide> class YellowBoxInspectorSourceMapStatus extends React.Component<Props, State> { <ide> )} <ide> /> <ide> <Text style={styles.text}>Source Map</Text> <del> </View> <add> </YellowBoxPressable> <ide> ); <ide> } <ide> <ide> class YellowBoxInspectorSourceMapStatus extends React.Component<Props, State> { <ide> const styles = StyleSheet.create({ <ide> root: { <ide> alignItems: 'center', <del> backgroundColor: YellowBoxStyle.getTextColor(0.8), <ide> borderRadius: 12, <ide> flexDirection: 'row', <ide> height: 24,
4
Javascript
Javascript
use constructor name
b1c8f15c5f169e021f7c46eb7b219de95fe97603
<ide><path>lib/util.js <ide> function formatValue(ctx, value, recurseTimes, ln) { <ide> return ctx.stylize('[Circular]', 'special'); <ide> <ide> if (recurseTimes != null) { <del> if (recurseTimes < 0) { <del> if (Array.isArray(value)) <del> return ctx.stylize('[Array]', 'special'); <del> return ctx.stylize('[Object]', 'special'); <del> } <add> if (recurseTimes < 0) <add> return ctx.stylize(`[${constructor ? constructor.name : 'Object'}]`, <add> 'special'); <ide> recurseTimes -= 1; <ide> } <ide> <ide><path>test/parallel/test-util-inspect.js <ide> if (typeof Symbol !== 'undefined') { <ide> 'MapSubclass { \'foo\' => 42 }'); <ide> assert.strictEqual(util.inspect(new PromiseSubclass(() => {})), <ide> 'PromiseSubclass { <pending> }'); <add> assert.strictEqual( <add> util.inspect({ a: { b: new ArraySubclass([1, [2], 3]) } }, { depth: 1 }), <add> '{ a: { b: [ArraySubclass] } }' <add> ); <ide> } <ide> <ide> // Empty and circular before depth
2
PHP
PHP
use the `pass` option when matching routes
82a94ab10a741dce48f2bd2df50b210167eb2124
<ide><path>src/Routing/Route/Route.php <ide> public function match(array $url, array $context = []) { <ide> return false; <ide> } <ide> <add> // If this route uses pass option, and the passed elements are <add> // not set, rekey elements. <add> if (isset($this->options['pass'])) { <add> foreach ($this->options['pass'] as $i => $name) { <add> if (isset($url[$i]) && !isset($url[$name])) { <add> $url[$name] = $url[$i]; <add> unset($url[$i]); <add> } <add> } <add> } <add> <ide> // check that all the key names are in the url <ide> $keyNames = array_flip($this->keys); <ide> if (array_intersect_key($keyNames, $url) !== $keyNames) { <ide><path>tests/TestCase/Routing/Route/RouteTest.php <ide> public function testMatchWithHostKeys() { <ide> * <ide> * @return void <ide> */ <del> public function testGreedyRouteFailurePassedArg() { <add> public function testMatchGreedyRouteFailurePassedArg() { <ide> $route = new Route('/:controller/:action', array('plugin' => null)); <ide> $result = $route->match(array('controller' => 'posts', 'action' => 'view', '0')); <ide> $this->assertFalse($result); <ide> public function testMatchWithPassedArgs() { <ide> $this->assertFalse($result); <ide> } <ide> <add>/** <add> * Test that the pass option lets you use positional arguments for the <add> * route elements that were named. <add> * <add> * @return void <add> */ <add> public function testMatchWithPassOption() { <add> $route = new Route( <add> '/blog/:id-:slug', <add> ['controller' => 'Blog', 'action' => 'view'], <add> ['pass' => ['id', 'slug']] <add> ); <add> $result = $route->match([ <add> 'controller' => 'Blog', <add> 'action' => 'view', <add> 'id' => 1, <add> 'slug' => 'second' <add> ]); <add> $this->assertEquals('/blog/1-second', $result); <add> <add> $result = $route->match([ <add> 'controller' => 'Blog', <add> 'action' => 'view', <add> 1, <add> 'second' <add> ]); <add> $this->assertEquals('/blog/1-second', $result); <add> <add> $result = $route->match([ <add> 'controller' => 'Blog', <add> 'action' => 'view', <add> 1, <add> 'second', <add> 'query' => 'string' <add> ]); <add> $this->assertEquals('/blog/1-second?query=string', $result); <add> <add> $result = $route->match([ <add> 'controller' => 'Blog', <add> 'action' => 'view', <add> 1 => 2, <add> 2 => 'second' <add> ]); <add> $this->assertFalse($result, 'Positional args must match exactly.'); <add> } <add> <add>/** <add> * Test that match() with pass and greedy routes. <add> * <add> * @return void <add> */ <add> public function testMatchWithPassOptionGreedy() { <add> $route = new Route( <add> '/blog/:id-:slug/*', <add> ['controller' => 'Blog', 'action' => 'view'], <add> ['pass' => ['id', 'slug']] <add> ); <add> $result = $route->match([ <add> 'controller' => 'Blog', <add> 'action' => 'view', <add> 'id' => 1, <add> 'slug' => 'second', <add> 'third', <add> 'fourth', <add> 'query' => 'string' <add> ]); <add> $this->assertEquals('/blog/1-second/third/fourth?query=string', $result); <add> <add> $result = $route->match([ <add> 'controller' => 'Blog', <add> 'action' => 'view', <add> 1, <add> 'second', <add> 'third', <add> 'fourth', <add> 'query' => 'string' <add> ]); <add> $this->assertEquals('/blog/1-second/third/fourth?query=string', $result); <add> } <add> <ide> /** <ide> * Test that extensions work. <ide> *
2
Ruby
Ruby
tell the user why we didn't bump a package
9ad3a9cefe8e7dd592cd11b743dc2c45cc414363
<ide><path>Library/Homebrew/dev-cmd/bump.rb <ide> def retrieve_and_display_info_and_open_pr(formula_or_cask, name, repositories, a <ide> EOS <ide> <ide> return unless args.open_pr? <add> <add> if repology_latest > current_version && <add> repology_latest > livecheck_latest && <add> livecheck_strategy == "GithubLatest" <add> puts "#{title_name} was not bumped to the Repology version because that " \ <add> "version is not the latest release on GitHub." <add> end <add> <ide> return unless new_version <ide> return if pull_requests <ide>
1
Text
Text
add protocols on layer 4
118d46bc8e45f8ff87ef201b6024e4a1c5bf710b
<ide><path>guide/english/network-engineering/osi-layers/index.md <ide> In the diagram above, to the extreme left is the unit of data that is used in ea <ide> <ide> * _**Layer 3 - Network Layer:**_ The network layer is responsible for forwarding packets to other networks. Usually, a network is divided into multiple subnets and the network layer with the help of routers forwards packets between such networks to establish a Wide Area Network (WAN). <ide> <del>* _**Layer 4 - Transport Layer:**_ The transport layer ensures that messages are delivered error-free, in sequence, and with no losses or duplications. It relieves the higher layer protocols from any concern with the transfer of data between them and their peers. <add>* _**Layer 4 - Transport Layer:**_ The transport layer ensures that messages are delivered error-free, in sequence, and with no losses or duplications. It relieves the higher layer protocols from any concern with the transfer of data between them and their peers. On this layer have 2 protocols, TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). <ide> <ide> * _**Layer 5 - Session Layer:**_ The session layer allows session establishment between processes running on different stations. <ide>
1
Python
Python
remove bert pretraining files for now
5676d6f799afd75f17a4b14c6ca2ee11f1a5ea08
<ide><path>create_pretraining_data_pytorch.py <del># coding=utf-8 <del># Copyright 2018 The Google AI Language Team 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># http://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>"""Create masked LM/next sentence masked_lm TF examples for BERT.""" <del> <del>from __future__ import absolute_import <del>from __future__ import division <del>from __future__ import print_function <del> <del>import collections <del>import random <del> <del>import tokenization <del>import tensorflow as tf <del> <del>import argparse <del> <del>parser = argparse.ArgumentParser() <del> <del>## Required parameters <del>parser.add_argument("--input_file", default=None, type=str, required=True, <del> help="Input raw text file (or comma-separated list of files).") <del>parser.add_argument("--output_file", default=None, type=str, required=True, <del> help="Output TF example file (or comma-separated list of files).") <del>parser.add_argument("--vocab_file", default=None, type=str, required=True, <del> help="The vocabulary file that the BERT model was trained on.") <del> <del>## Other parameters <del>parser.add_argument("--do_lower_case", default=True, action='store_true', <del> help="Whether to lower case the input text. Should be True for uncased " <del> "models and False for cased models.") <del>parser.add_argument("--max_seq_length", default=128, type=int, help="Maximum sequence length.") <del>parser.add_argument("--max_predictions_per_seq", default=20, type=int, <del> help="Maximum number of masked LM predictions per sequence.") <del>parser.add_argument("--random_seed", default=12345, type=int, help="Random seed for data generation.") <del>parser.add_argument("--dupe_factor", default=10, type=int, <del> help="Number of times to duplicate the input data (with different masks).") <del>parser.add_argument("--masked_lm_prob", default=0.15, type=float, help="Masked LM probability.") <del>parser.add_argument("--short_seq_prob", default=0.1, type=float, <del> help="Probability of creating sequences which are shorter than the maximum length.") <del> <del>args = parser.parse_args() <del> <del> <del>class TrainingInstance(object): <del> """A single training instance (sentence pair).""" <del> <del> def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels, <del> is_random_next): <del> self.tokens = tokens <del> self.segment_ids = segment_ids <del> self.is_random_next = is_random_next <del> self.masked_lm_positions = masked_lm_positions <del> self.masked_lm_labels = masked_lm_labels <del> <del> def __str__(self): <del> s = "" <del> s += "tokens: %s\n" % (" ".join( <del> [tokenization.printable_text(x) for x in self.tokens])) <del> s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids])) <del> s += "is_random_next: %s\n" % self.is_random_next <del> s += "masked_lm_positions: %s\n" % (" ".join( <del> [str(x) for x in self.masked_lm_positions])) <del> s += "masked_lm_labels: %s\n" % (" ".join( <del> [tokenization.printable_text(x) for x in self.masked_lm_labels])) <del> s += "\n" <del> return s <del> <del> def __repr__(self): <del> return self.__str__() <del> <del> <del>def write_instance_to_example_files(instances, tokenizer, max_seq_length, <del> max_predictions_per_seq, output_files): <del> """Create TF example files from `TrainingInstance`s.""" <del> writers = [] <del> for output_file in output_files: <del> writers.append(tf.python_io.TFRecordWriter(output_file)) <del> <del> writer_index = 0 <del> <del> total_written = 0 <del> for (inst_index, instance) in enumerate(instances): <del> input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) <del> input_mask = [1] * len(input_ids) <del> segment_ids = list(instance.segment_ids) <del> assert len(input_ids) <= max_seq_length <del> <del> while len(input_ids) < max_seq_length: <del> input_ids.append(0) <del> input_mask.append(0) <del> segment_ids.append(0) <del> <del> assert len(input_ids) == max_seq_length <del> assert len(input_mask) == max_seq_length <del> assert len(segment_ids) == max_seq_length <del> <del> masked_lm_positions = list(instance.masked_lm_positions) <del> masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels) <del> masked_lm_weights = [1.0] * len(masked_lm_ids) <del> <del> while len(masked_lm_positions) < max_predictions_per_seq: <del> masked_lm_positions.append(0) <del> masked_lm_ids.append(0) <del> masked_lm_weights.append(0.0) <del> <del> next_sentence_label = 1 if instance.is_random_next else 0 <del> <del> features = collections.OrderedDict() <del> features["input_ids"] = create_int_feature(input_ids) <del> features["input_mask"] = create_int_feature(input_mask) <del> features["segment_ids"] = create_int_feature(segment_ids) <del> features["masked_lm_positions"] = create_int_feature(masked_lm_positions) <del> features["masked_lm_ids"] = create_int_feature(masked_lm_ids) <del> features["masked_lm_weights"] = create_float_feature(masked_lm_weights) <del> features["next_sentence_labels"] = create_int_feature([next_sentence_label]) <del> <del> tf_example = tf.train.Example(features=tf.train.Features(feature=features)) <del> <del> writers[writer_index].write(tf_example.SerializeToString()) <del> writer_index = (writer_index + 1) % len(writers) <del> <del> total_written += 1 <del> <del> if inst_index < 20: <del> tf.logging.info("*** Example ***") <del> tf.logging.info("tokens: %s" % " ".join( <del> [tokenization.printable_text(x) for x in instance.tokens])) <del> <del> for feature_name in features.keys(): <del> feature = features[feature_name] <del> values = [] <del> if feature.int64_list.value: <del> values = feature.int64_list.value <del> elif feature.float_list.value: <del> values = feature.float_list.value <del> tf.logging.info( <del> "%s: %s" % (feature_name, " ".join([str(x) for x in values]))) <del> <del> for writer in writers: <del> writer.close() <del> <del> tf.logging.info("Wrote %d total instances", total_written) <del> <del> <del>def create_int_feature(values): <del> feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) <del> return feature <del> <del> <del>def create_float_feature(values): <del> feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) <del> return feature <del> <del> <del>def create_training_instances(input_files, tokenizer, max_seq_length, <del> dupe_factor, short_seq_prob, masked_lm_prob, <del> max_predictions_per_seq, rng): <del> """Create `TrainingInstance`s from raw text.""" <del> all_documents = [[]] <del> <del> # Input file format: <del> # (1) One sentence per line. These should ideally be actual sentences, not <del> # entire paragraphs or arbitrary spans of text. (Because we use the <del> # sentence boundaries for the "next sentence prediction" task). <del> # (2) Blank lines between documents. Document boundaries are needed so <del> # that the "next sentence prediction" task doesn't span between documents. <del> for input_file in input_files: <del> with tf.gfile.GFile(input_file, "r") as reader: <del> while True: <del> line = tokenization.convert_to_unicode(reader.readline()) <del> if not line: <del> break <del> line = line.strip() <del> <del> # Empty lines are used as document delimiters <del> if not line: <del> all_documents.append([]) <del> tokens = tokenizer.tokenize(line) <del> if tokens: <del> all_documents[-1].append(tokens) <del> <del> # Remove empty documents <del> all_documents = [x for x in all_documents if x] <del> rng.shuffle(all_documents) <del> <del> vocab_words = list(tokenizer.vocab.keys()) <del> instances = [] <del> for _ in range(dupe_factor): <del> for document_index in range(len(all_documents)): <del> instances.extend( <del> create_instances_from_document( <del> all_documents, document_index, max_seq_length, short_seq_prob, <del> masked_lm_prob, max_predictions_per_seq, vocab_words, rng)) <del> <del> rng.shuffle(instances) <del> return instances <del> <del> <del>def create_instances_from_document( <del> all_documents, document_index, max_seq_length, short_seq_prob, <del> masked_lm_prob, max_predictions_per_seq, vocab_words, rng): <del> """Creates `TrainingInstance`s for a single document.""" <del> document = all_documents[document_index] <del> <del> # Account for [CLS], [SEP], [SEP] <del> max_num_tokens = max_seq_length - 3 <del> <del> # We *usually* want to fill up the entire sequence since we are padding <del> # to `max_seq_length` anyways, so short sequences are generally wasted <del> # computation. However, we *sometimes* <del> # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter <del> # sequences to minimize the mismatch between pre-training and fine-tuning. <del> # The `target_seq_length` is just a rough target however, whereas <del> # `max_seq_length` is a hard limit. <del> target_seq_length = max_num_tokens <del> if rng.random() < short_seq_prob: <del> target_seq_length = rng.randint(2, max_num_tokens) <del> <del> # We DON'T just concatenate all of the tokens from a document into a long <del> # sequence and choose an arbitrary split point because this would make the <del> # next sentence prediction task too easy. Instead, we split the input into <del> # segments "A" and "B" based on the actual "sentences" provided by the user <del> # input. <del> instances = [] <del> current_chunk = [] <del> current_length = 0 <del> i = 0 <del> while i < len(document): <del> segment = document[i] <del> current_chunk.append(segment) <del> current_length += len(segment) <del> if i == len(document) - 1 or current_length >= target_seq_length: <del> if current_chunk: <del> # `a_end` is how many segments from `current_chunk` go into the `A` <del> # (first) sentence. <del> a_end = 1 <del> if len(current_chunk) >= 2: <del> a_end = rng.randint(1, len(current_chunk) - 1) <del> <del> tokens_a = [] <del> for j in range(a_end): <del> tokens_a.extend(current_chunk[j]) <del> <del> tokens_b = [] <del> # Random next <del> is_random_next = False <del> if len(current_chunk) == 1 or rng.random() < 0.5: <del> is_random_next = True <del> target_b_length = target_seq_length - len(tokens_a) <del> <del> # This should rarely go for more than one iteration for large <del> # corpora. However, just to be careful, we try to make sure that <del> # the random document is not the same as the document <del> # we're processing. <del> for _ in range(10): <del> random_document_index = rng.randint(0, len(all_documents) - 1) <del> if random_document_index != document_index: <del> break <del> <del> random_document = all_documents[random_document_index] <del> random_start = rng.randint(0, len(random_document) - 1) <del> for j in range(random_start, len(random_document)): <del> tokens_b.extend(random_document[j]) <del> if len(tokens_b) >= target_b_length: <del> break <del> # We didn't actually use these segments so we "put them back" so <del> # they don't go to waste. <del> num_unused_segments = len(current_chunk) - a_end <del> i -= num_unused_segments <del> # Actual next <del> else: <del> is_random_next = False <del> for j in range(a_end, len(current_chunk)): <del> tokens_b.extend(current_chunk[j]) <del> truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng) <del> <del> assert len(tokens_a) >= 1 <del> assert len(tokens_b) >= 1 <del> <del> tokens = [] <del> segment_ids = [] <del> tokens.append("[CLS]") <del> segment_ids.append(0) <del> for token in tokens_a: <del> tokens.append(token) <del> segment_ids.append(0) <del> <del> tokens.append("[SEP]") <del> segment_ids.append(0) <del> <del> for token in tokens_b: <del> tokens.append(token) <del> segment_ids.append(1) <del> tokens.append("[SEP]") <del> segment_ids.append(1) <del> <del> (tokens, masked_lm_positions, <del> masked_lm_labels) = create_masked_lm_predictions( <del> tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng) <del> instance = TrainingInstance( <del> tokens=tokens, <del> segment_ids=segment_ids, <del> is_random_next=is_random_next, <del> masked_lm_positions=masked_lm_positions, <del> masked_lm_labels=masked_lm_labels) <del> instances.append(instance) <del> current_chunk = [] <del> current_length = 0 <del> i += 1 <del> <del> return instances <del> <del> <del>def create_masked_lm_predictions(tokens, masked_lm_prob, <del> max_predictions_per_seq, vocab_words, rng): <del> """Creates the predictis for the masked LM objective.""" <del> <del> cand_indexes = [] <del> for (i, token) in enumerate(tokens): <del> if token == "[CLS]" or token == "[SEP]": <del> continue <del> cand_indexes.append(i) <del> <del> rng.shuffle(cand_indexes) <del> <del> output_tokens = list(tokens) <del> <del> masked_lm = collections.namedtuple("masked_lm", ["index", "label"]) # pylint: disable=invalid-name <del> <del> num_to_predict = min(max_predictions_per_seq, <del> max(1, int(round(len(tokens) * masked_lm_prob)))) <del> <del> masked_lms = [] <del> covered_indexes = set() <del> for index in cand_indexes: <del> if len(masked_lms) >= num_to_predict: <del> break <del> if index in covered_indexes: <del> continue <del> covered_indexes.add(index) <del> <del> masked_token = None <del> # 80% of the time, replace with [MASK] <del> if rng.random() < 0.8: <del> masked_token = "[MASK]" <del> else: <del> # 10% of the time, keep original <del> if rng.random() < 0.5: <del> masked_token = tokens[index] <del> # 10% of the time, replace with random word <del> else: <del> masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] <del> <del> output_tokens[index] = masked_token <del> <del> masked_lms.append(masked_lm(index=index, label=tokens[index])) <del> <del> masked_lms = sorted(masked_lms, key=lambda x: x.index) <del> <del> masked_lm_positions = [] <del> masked_lm_labels = [] <del> for p in masked_lms: <del> masked_lm_positions.append(p.index) <del> masked_lm_labels.append(p.label) <del> <del> return (output_tokens, masked_lm_positions, masked_lm_labels) <del> <del> <del>def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): <del> """Truncates a pair of sequences to a maximum sequence length.""" <del> while True: <del> total_length = len(tokens_a) + len(tokens_b) <del> if total_length <= max_num_tokens: <del> break <del> <del> trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b <del> assert len(trunc_tokens) >= 1 <del> <del> # We want to sometimes truncate from the front and sometimes from the <del> # back to add more randomness and avoid biases. <del> if rng.random() < 0.5: <del> del trunc_tokens[0] <del> else: <del> trunc_tokens.pop() <del> <del> <del>def main(_): <del> tf.logging.set_verbosity(tf.logging.INFO) <del> <del> tokenizer = tokenization.FullTokenizer( <del> vocab_file=args.vocab_file, do_lower_case=args.do_lower_case) <del> <del> input_files = [] <del> for input_pattern in args.input_file.split(","): <del> input_files.extend(tf.gfile.Glob(input_pattern)) <del> <del> tf.logging.info("*** Reading from input files ***") <del> for input_file in input_files: <del> tf.logging.info(" %s", input_file) <del> <del> rng = random.Random(args.random_seed) <del> instances = create_training_instances( <del> input_files, tokenizer, args.max_seq_length, args.dupe_factor, <del> args.short_seq_prob, args.masked_lm_prob, args.max_predictions_per_seq, <del> rng) <del> <del> output_files = args.output_file.split(",") <del> tf.logging.info("*** Writing to output files ***") <del> for output_file in output_files: <del> tf.logging.info(" %s", output_file) <del> <del> write_instance_to_example_files(instances, tokenizer, args.max_seq_length, <del> args.max_predictions_per_seq, output_files) <del> <del> <del>if __name__ == "__main__": <del> tf.app.run() <ide><path>run_pretraining_pytorch.py <del># coding=utf-8 <del># Copyright 2018 The Google AI Language Team 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># http://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>"""Run masked LM/next sentence masked_lm pre-training for BERT.""" <del> <del>from __future__ import absolute_import <del>from __future__ import division <del>from __future__ import print_function <del> <del>import os <del>import modeling <del>import optimization <del>import tensorflow as tf <del>import argparse <del> <del> <del>def model_fn_builder(bert_config, init_checkpoint, learning_rate, <del> num_train_steps, num_warmup_steps, use_tpu, <del> use_one_hot_embeddings): <del> """Returns `model_fn` closure for TPUEstimator.""" <del> <del> def model_fn(features, labels, mode, params): # pylint: disable=unused-argument <del> """The `model_fn` for TPUEstimator.""" <del> <del> tf.logging.info("*** Features ***") <del> for name in sorted(features.keys()): <del> tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) <del> <del> input_ids = features["input_ids"] <del> input_mask = features["input_mask"] <del> segment_ids = features["segment_ids"] <del> masked_lm_positions = features["masked_lm_positions"] <del> masked_lm_ids = features["masked_lm_ids"] <del> masked_lm_weights = features["masked_lm_weights"] <del> next_sentence_labels = features["next_sentence_labels"] <del> <del> is_training = (mode == tf.estimator.ModeKeys.TRAIN) <del> <del> model = modeling.BertModel( <del> config=bert_config, <del> is_training=is_training, <del> input_ids=input_ids, <del> input_mask=input_mask, <del> token_type_ids=segment_ids, <del> use_one_hot_embeddings=use_one_hot_embeddings) <del> <del> (masked_lm_loss, <del> masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output( <del> bert_config, model.get_sequence_output(), model.get_embedding_table(), <del> masked_lm_positions, masked_lm_ids, masked_lm_weights) <del> <del> (next_sentence_loss, next_sentence_example_loss, <del> next_sentence_log_probs) = get_next_sentence_output( <del> bert_config, model.get_pooled_output(), next_sentence_labels) <del> <del> total_loss = masked_lm_loss + next_sentence_loss <del> <del> tvars = tf.trainable_variables() <del> <del> initialized_variable_names = {} <del> scaffold_fn = None <del> if init_checkpoint: <del> (assignment_map, <del> initialized_variable_names) = modeling.get_assigment_map_from_checkpoint( <del> tvars, init_checkpoint) <del> if use_tpu: <del> <del> def tpu_scaffold(): <del> tf.train.init_from_checkpoint(init_checkpoint, assignment_map) <del> return tf.train.Scaffold() <del> <del> scaffold_fn = tpu_scaffold <del> else: <del> tf.train.init_from_checkpoint(init_checkpoint, assignment_map) <del> <del> tf.logging.info("**** Trainable Variables ****") <del> for var in tvars: <del> init_string = "" <del> if var.name in initialized_variable_names: <del> init_string = ", *INIT_FROM_CKPT*" <del> tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape, <del> init_string) <del> <del> output_spec = None <del> if mode == tf.estimator.ModeKeys.TRAIN: <del> train_op = optimization.create_optimizer( <del> total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) <del> <del> output_spec = tf.contrib.tpu.TPUEstimatorSpec( <del> mode=mode, <del> loss=total_loss, <del> train_op=train_op, <del> scaffold_fn=scaffold_fn) <del> elif mode == tf.estimator.ModeKeys.EVAL: <del> <del> def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids, <del> masked_lm_weights, next_sentence_example_loss, <del> next_sentence_log_probs, next_sentence_labels): <del> """Computes the loss and accuracy of the model.""" <del> masked_lm_log_probs = tf.reshape(masked_lm_log_probs, <del> [-1, masked_lm_log_probs.shape[-1]]) <del> masked_lm_predictions = tf.argmax( <del> masked_lm_log_probs, axis=-1, output_type=tf.int32) <del> masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1]) <del> masked_lm_ids = tf.reshape(masked_lm_ids, [-1]) <del> masked_lm_weights = tf.reshape(masked_lm_weights, [-1]) <del> masked_lm_accuracy = tf.metrics.accuracy( <del> labels=masked_lm_ids, <del> predictions=masked_lm_predictions, <del> weights=masked_lm_weights) <del> masked_lm_mean_loss = tf.metrics.mean( <del> values=masked_lm_example_loss, weights=masked_lm_weights) <del> <del> next_sentence_log_probs = tf.reshape( <del> next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]]) <del> next_sentence_predictions = tf.argmax( <del> next_sentence_log_probs, axis=-1, output_type=tf.int32) <del> next_sentence_labels = tf.reshape(next_sentence_labels, [-1]) <del> next_sentence_accuracy = tf.metrics.accuracy( <del> labels=next_sentence_labels, predictions=next_sentence_predictions) <del> next_sentence_mean_loss = tf.metrics.mean( <del> values=next_sentence_example_loss) <del> <del> return { <del> "masked_lm_accuracy": masked_lm_accuracy, <del> "masked_lm_loss": masked_lm_mean_loss, <del> "next_sentence_accuracy": next_sentence_accuracy, <del> "next_sentence_loss": next_sentence_mean_loss, <del> } <del> <del> eval_metrics = (metric_fn, [ <del> masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids, <del> masked_lm_weights, next_sentence_example_loss, <del> next_sentence_log_probs, next_sentence_labels <del> ]) <del> output_spec = tf.contrib.tpu.TPUEstimatorSpec( <del> mode=mode, <del> loss=total_loss, <del> eval_metrics=eval_metrics, <del> scaffold_fn=scaffold_fn) <del> else: <del> raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode)) <del> <del> return output_spec <del> <del> return model_fn <del> <del> <del>def get_masked_lm_output(bert_config, input_tensor, output_weights, positions, <del> label_ids, label_weights): <del> """Get loss and log probs for the masked LM.""" <del> input_tensor = gather_indexes(input_tensor, positions) <del> <del> with tf.variable_scope("cls/predictions"): <del> # We apply one more non-linear transformation before the output layer. <del> # This matrix is not used after pre-training. <del> with tf.variable_scope("transform"): <del> input_tensor = tf.layers.dense( <del> input_tensor, <del> units=bert_config.hidden_size, <del> activation=modeling.get_activation(bert_config.hidden_act), <del> kernel_initializer=modeling.create_initializer( <del> bert_config.initializer_range)) <del> input_tensor = modeling.layer_norm(input_tensor) <del> <del> # The output weights are the same as the input embeddings, but there is <del> # an output-only bias for each token. <del> output_bias = tf.get_variable( <del> "output_bias", <del> shape=[bert_config.vocab_size], <del> initializer=tf.zeros_initializer()) <del> logits = tf.matmul(input_tensor, output_weights, transpose_b=True) <del> logits = tf.nn.bias_add(logits, output_bias) <del> log_probs = tf.nn.log_softmax(logits, axis=-1) <del> <del> label_ids = tf.reshape(label_ids, [-1]) <del> label_weights = tf.reshape(label_weights, [-1]) <del> <del> one_hot_labels = tf.one_hot( <del> label_ids, depth=bert_config.vocab_size, dtype=tf.float32) <del> <del> # The `positions` tensor might be zero-padded (if the sequence is too <del> # short to have the maximum number of predictions). The `label_weights` <del> # tensor has a value of 1.0 for every real prediction and 0.0 for the <del> # padding predictions. <del> per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1]) <del> numerator = tf.reduce_sum(label_weights * per_example_loss) <del> denominator = tf.reduce_sum(label_weights) + 1e-5 <del> loss = numerator / denominator <del> <del> return (loss, per_example_loss, log_probs) <del> <del> <del>def get_next_sentence_output(bert_config, input_tensor, labels): <del> """Get loss and log probs for the next sentence prediction.""" <del> <del> # Simple binary classification. Note that 0 is "next sentence" and 1 is <del> # "random sentence". This weight matrix is not used after pre-training. <del> with tf.variable_scope("cls/seq_relationship"): <del> output_weights = tf.get_variable( <del> "output_weights", <del> shape=[2, bert_config.hidden_size], <del> initializer=modeling.create_initializer(bert_config.initializer_range)) <del> output_bias = tf.get_variable( <del> "output_bias", shape=[2], initializer=tf.zeros_initializer()) <del> <del> logits = tf.matmul(input_tensor, output_weights, transpose_b=True) <del> logits = tf.nn.bias_add(logits, output_bias) <del> log_probs = tf.nn.log_softmax(logits, axis=-1) <del> labels = tf.reshape(labels, [-1]) <del> one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32) <del> per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) <del> loss = tf.reduce_mean(per_example_loss) <del> return (loss, per_example_loss, log_probs) <del> <del> <del>def gather_indexes(sequence_tensor, positions): <del> """Gathers the vectors at the specific positions over a minibatch.""" <del> sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3) <del> batch_size = sequence_shape[0] <del> seq_length = sequence_shape[1] <del> width = sequence_shape[2] <del> <del> flat_offsets = tf.reshape( <del> tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1]) <del> flat_positions = tf.reshape(positions + flat_offsets, [-1]) <del> flat_sequence_tensor = tf.reshape(sequence_tensor, <del> [batch_size * seq_length, width]) <del> output_tensor = tf.gather(flat_sequence_tensor, flat_positions) <del> return output_tensor <del> <del> <del>def input_fn_builder(input_files, <del> max_seq_length, <del> max_predictions_per_seq, <del> is_training, <del> num_cpu_threads=4): <del> """Creates an `input_fn` closure to be passed to TPUEstimator.""" <del> <del> def input_fn(params): <del> """The actual input function.""" <del> batch_size = params["batch_size"] <del> <del> name_to_features = { <del> "input_ids": <del> tf.FixedLenFeature([max_seq_length], tf.int64), <del> "input_mask": <del> tf.FixedLenFeature([max_seq_length], tf.int64), <del> "segment_ids": <del> tf.FixedLenFeature([max_seq_length], tf.int64), <del> "masked_lm_positions": <del> tf.FixedLenFeature([max_predictions_per_seq], tf.int64), <del> "masked_lm_ids": <del> tf.FixedLenFeature([max_predictions_per_seq], tf.int64), <del> "masked_lm_weights": <del> tf.FixedLenFeature([max_predictions_per_seq], tf.float32), <del> "next_sentence_labels": <del> tf.FixedLenFeature([1], tf.int64), <del> } <del> <del> # For training, we want a lot of parallel reading and shuffling. <del> # For eval, we want no shuffling and parallel reading doesn't matter. <del> if is_training: <del> d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files)) <del> d = d.repeat() <del> d = d.shuffle(buffer_size=len(input_files)) <del> <del> # `cycle_length` is the number of parallel files that get read. <del> cycle_length = min(num_cpu_threads, len(input_files)) <del> <del> # `sloppy` mode means that the interleaving is not exact. This adds <del> # even more randomness to the training pipeline. <del> d = d.apply( <del> tf.contrib.data.parallel_interleave( <del> tf.data.TFRecordDataset, <del> sloppy=is_training, <del> cycle_length=cycle_length)) <del> d = d.shuffle(buffer_size=100) <del> else: <del> d = tf.data.TFRecordDataset(input_files) <del> # Since we evaluate for a fixed number of steps we don't want to encounter <del> # out-of-range exceptions. <del> d = d.repeat() <del> <del> # We must `drop_remainder` on training because the TPU requires fixed <del> # size dimensions. For eval, we assume we are evaling on the CPU or GPU <del> # and we *don"t* want to drop the remainder, otherwise we wont cover <del> # every sample. <del> d = d.apply( <del> tf.contrib.data.map_and_batch( <del> lambda record: _decode_record(record, name_to_features), <del> batch_size=batch_size, <del> num_parallel_batches=num_cpu_threads, <del> drop_remainder=True)) <del> return d <del> <del> return input_fn <del> <del> <del>def _decode_record(record, name_to_features): <del> """Decodes a record to a TensorFlow example.""" <del> example = tf.parse_single_example(record, name_to_features) <del> <del> # tf.Example only supports tf.int64, but the TPU only supports tf.int32. <del> # So cast all int64 to int32. <del> for name in list(example.keys()): <del> t = example[name] <del> if t.dtype == tf.int64: <del> t = tf.to_int32(t) <del> example[name] = t <del> <del> return example <del> <del> <del>def main(_): <del> parser = argparse.ArgumentParser() <del> <del> ## Required parameters <del> parser.add_argument("--bert_config_file", default=None, type=str, required=True, <del> help="The config json file corresponding to the pre-trained BERT model. " <del> "This specifies the model architecture.") <del> parser.add_argument("--input_file", default=None, type=str, required=True, <del> help="Input TF example files (can be a glob or comma separated).") <del> parser.add_argument("--output_dir", default=None, type=str, required=True, <del> help="The output directory where the model checkpoints will be written.") <del> <del> ## Other parameters <del> parser.add_argument("--init_checkpoint", default=None, type=str, <del> help="Initial checkpoint (usually from a pre-trained BERT model).") <del> parser.add_argument("--max_seq_length", default=128, type=int, <del> help="The maximum total input sequence length after WordPiece tokenization. Sequences longer " <del> "than this will be truncated, and sequences shorter than this will be padded. " <del> "Must match data generation.") <del> parser.add_argument("--max_predictions_per_seq", default=20, type=int, <del> help="Maximum number of masked LM predictions per sequence. Must match data generation.") <del> parser.add_argument("--do_train", default=False, action='store_true', help="Whether to run training.") <del> parser.add_argument("--do_eval", default=False, action='store_true', help="Whether to run eval on the dev set.") <del> parser.add_argument("--train_batch_size", default=32, type=int, help="Total batch size for training.") <del> parser.add_argument("--eval_batch_size", default=8, type=int, help="Total batch size for eval.") <del> parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") <del> parser.add_argument("--num_train_steps", default=100000, type=int, help="Number of training steps.") <del> parser.add_argument("--num_warmup_steps", default=10000, type=int, help="Number of warmup steps.") <del> parser.add_argument("--save_checkpoints_steps", default=1000, type=int, <del> help="How often to save the model checkpoint.") <del> parser.add_argument("--iterations_per_loop", default=1000, type=int, <del> help="How many steps to make in each estimator call.") <del> parser.add_argument("--max_eval_steps", default=100, type=int, help="Maximum number of eval steps.") <del> ### BEGIN - TO DELETE EVENTUALLY --> NO SENSE IN PYTORCH ### <del> parser.add_argument("--use_tpu", default=False, action='store_true', help="Whether to use TPU or GPU/CPU.") <del> parser.add_argument("--tpu_name", default=None, type=str, <del> help="The Cloud TPU to use for training. This should be either the name used when creating the " <del> "Cloud TPU, or a grpc://ip.address.of.tpu:8470 url.") <del> parser.add_argument("--tpu_zone", default=None, type=str, <del> help="[Optional] GCE zone where the Cloud TPU is located in. If not specified, we will attempt " <del> "to automatically detect the GCE project from metadata.") <del> parser.add_argument("--gcp_project", default=None, type=str, <del> help="[Optional] Project name for the Cloud TPU-enabled project. If not specified, " <del> "we will attempt to automatically detect the GCE project from metadata.") <del> parser.add_argument("--master", default=None, type=str, help="[Optional] TensorFlow master URL.") <del> parser.add_argument("--num_tpu_cores", default=8, type=int, <del> help="Only used if `use_tpu` is True. Total number of TPU cores to use.") <del> ### END - TO DELETE EVENTUALLY --> NO SENSE IN PYTORCH ### <del> <del> args = parser.parse_args() <del> <del> tf.logging.set_verbosity(tf.logging.INFO) <del> <del> if not args.do_train and not args.do_eval: <del> raise ValueError("At least one of `do_train` or `do_eval` must be True.") <del> <del> bert_config = modeling.BertConfig.from_json_file(args.bert_config_file) <del> <del> tf.gfile.MakeDirs(args.output_dir) <del> <del> input_files = [] <del> for input_pattern in args.input_file.split(","): <del> input_files.extend(tf.gfile.Glob(input_pattern)) <del> <del> tf.logging.info("*** Input Files ***") <del> for input_file in input_files: <del> tf.logging.info(" %s" % input_file) <del> <del> tpu_cluster_resolver = None <del> if args.use_tpu and args.tpu_name: <del> tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( <del> args.tpu_name, zone=args.tpu_zone, project=args.gcp_project) <del> <del> is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 <del> run_config = tf.contrib.tpu.RunConfig( <del> cluster=tpu_cluster_resolver, <del> master=args.master, <del> model_dir=args.output_dir, <del> save_checkpoints_steps=args.save_checkpoints_steps, <del> tpu_config=tf.contrib.tpu.TPUConfig( <del> iterations_per_loop=args.iterations_per_loop, <del> num_shards=args.num_tpu_cores, <del> per_host_input_for_training=is_per_host)) <del> <del> model_fn = model_fn_builder( <del> bert_config=bert_config, <del> init_checkpoint=args.init_checkpoint, <del> learning_rate=args.learning_rate, <del> num_train_steps=args.num_train_steps, <del> num_warmup_steps=args.num_warmup_steps, <del> use_tpu=args.use_tpu, <del> use_one_hot_embeddings=args.use_tpu) <del> <del> # If TPU is not available, this will fall back to normal Estimator on CPU <del> # or GPU. <del> estimator = tf.contrib.tpu.TPUEstimator( <del> use_tpu=args.use_tpu, <del> model_fn=model_fn, <del> config=run_config, <del> train_batch_size=args.train_batch_size, <del> eval_batch_size=args.eval_batch_size) <del> <del> if args.do_train: <del> tf.logging.info("***** Running training *****") <del> tf.logging.info(" Batch size = %d", args.train_batch_size) <del> train_input_fn = input_fn_builder( <del> input_files=input_files, <del> max_seq_length=args.max_seq_length, <del> max_predictions_per_seq=args.max_predictions_per_seq, <del> is_training=True) <del> estimator.train(input_fn=train_input_fn, max_steps=args.num_train_steps) <del> <del> if args.do_eval: <del> tf.logging.info("***** Running evaluation *****") <del> tf.logging.info(" Batch size = %d", args.eval_batch_size) <del> <del> eval_input_fn = input_fn_builder( <del> input_files=input_files, <del> max_seq_length=args.max_seq_length, <del> max_predictions_per_seq=args.max_predictions_per_seq, <del> is_training=False) <del> <del> result = estimator.evaluate( <del> input_fn=eval_input_fn, steps=args.max_eval_steps) <del> <del> output_eval_file = os.path.join(args.output_dir, "eval_results.txt") <del> with tf.gfile.GFile(output_eval_file, "w") as writer: <del> tf.logging.info("***** Eval results *****") <del> for key in sorted(result.keys()): <del> tf.logging.info(" %s = %s", key, str(result[key])) <del> writer.write("%s = %s\n" % (key, str(result[key]))) <del> <del> <del>if __name__ == "__main__": <del> tf.app.run()
2
Ruby
Ruby
handle edge cases in the previous patch
558ee6e95ccd6c2098595f2edfa59e8aa9108167
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> def app_name <ide> end <ide> <ide> def defined_app_const_base <del> Rails.application.class.name.sub(/::Application$/, "") if Rails.application.instance_of?(Rails::Application) <add> Rails.respond_to?(:application) && defined?(Rails::Application) && <add> Rails.application.is_a?(Rails::Application) && Rails.application.class.name.sub(/::Application$/, "") <ide> end <ide> <ide> def app_const_base
1
Go
Go
fix os tweaks call
233aa636d7b3dafa418c4be496645658772cd72d
<ide><path>libnetwork/drivers/overlay/overlay.go <ide> func Fini(drv driverapi.Driver) { <ide> } <ide> <ide> func (d *driver) configure() error { <add> <add> // Apply OS specific kernel configs if needed <add> d.initOS.Do(applyOStweaks) <add> <ide> if d.store == nil { <ide> return nil <ide> } <ide> func (d *driver) configure() error { <ide> return d.initializeVxlanIdm() <ide> } <ide> <del> // Apply OS specific kernel configs if needed <del> d.initOS.Do(applyOStweaks) <del> <ide> return nil <ide> } <ide>
1
Python
Python
fix broken static check on master
b0d6069d25cf482309af40eec068bcccb2b62552
<ide><path>airflow/providers/apache/hive/hooks/hive.py <ide> import time <ide> from collections import OrderedDict <ide> from tempfile import NamedTemporaryFile, TemporaryDirectory <del>from typing import Any, Dict, List, Optional, Text, Union <add>from typing import Any, Dict, List, Optional, Union <ide> <ide> import pandas <ide> import unicodecsv as csv <ide> def _prepare_hiveconf(d: Dict[Any, Any]) -> List[Any]: <ide> <ide> def run_cli( <ide> self, <del> hql: Union[str, Text], <add> hql: Union[str, str], <ide> schema: Optional[str] = None, <ide> verbose: bool = True, <ide> hive_conf: Optional[Dict[Any, Any]] = None, <ide> def run_cli( <ide> <ide> return stdout <ide> <del> def test_hql(self, hql: Union[str, Text]) -> None: <add> def test_hql(self, hql: Union[str, str]) -> None: <ide> """Test an hql statement using the hive cli and EXPLAIN""" <ide> create, insert, other = [], [], [] <ide> for query in hql.split(';'): # naive <ide> def get_conn(self, schema: Optional[str] = None) -> Any: <ide> <ide> def _get_results( <ide> self, <del> hql: Union[str, Text, List[str]], <add> hql: Union[str, str, List[str]], <ide> schema: str = 'default', <ide> fetch_size: Optional[int] = None, <ide> hive_conf: Optional[Dict[Any, Any]] = None, <ide> def _get_results( <ide> <ide> def get_results( <ide> self, <del> hql: Union[str, Text], <add> hql: Union[str, str], <ide> schema: str = 'default', <ide> fetch_size: Optional[int] = None, <ide> hive_conf: Optional[Dict[Any, Any]] = None, <ide> def get_results( <ide> <ide> def to_csv( <ide> self, <del> hql: Union[str, Text], <add> hql: Union[str, str], <ide> csv_filepath: str, <ide> schema: str = 'default', <ide> delimiter: str = ',', <ide> def to_csv( <ide> self.log.info("Done. Loaded a total of %s rows.", i) <ide> <ide> def get_records( <del> self, hql: Union[str, Text], schema: str = 'default', hive_conf: Optional[Dict[Any, Any]] = None <add> self, hql: Union[str, str], schema: str = 'default', hive_conf: Optional[Dict[Any, Any]] = None <ide> ) -> Any: <ide> """ <ide> Get a set of records from a Hive query. <ide> def get_records( <ide> <ide> def get_pandas_df( # type: ignore <ide> self, <del> hql: Union[str, Text], <add> hql: Union[str, str], <ide> schema: str = 'default', <ide> hive_conf: Optional[Dict[Any, Any]] = None, <ide> **kwargs,
1
PHP
PHP
fix import ordering
1c068b459b5928b55a87dbf39e40d711792be620
<ide><path>tests/TestCase/Http/MiddlewareStackTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Http; <ide> <del>use Cake\TestSuite\TestCase; <ide> use Cake\Http\MiddlewareStack; <add>use Cake\TestSuite\TestCase; <ide> use TestApp\Middleware\SampleMiddleware; <ide> <ide> /**
1
Ruby
Ruby
rewrite missing_options in a more obvious way
6b9a929e40933db5e21ba91913445212f1d2b1c1
<ide><path>Library/Homebrew/dependency.rb <ide> def satisfied?(inherited_options) <ide> end <ide> <ide> def missing_options(inherited_options) <del> missing = options | inherited_options <del> missing -= Tab.for_formula(to_formula).used_options <del> missing <add> required = options | inherited_options <add> required - Tab.for_formula(to_formula).used_options <ide> end <ide> <ide> def modify_build_environment
1
PHP
PHP
fix failing tests
1585f119bfc695356d5dc866b663937bb75c0d7c
<ide><path>src/Console/Command/Task/SimpleBakeTask.php <ide> public function main($name = null) { <ide> if (empty($name)) { <ide> return $this->error('You must provide a name to bake a ' . $this->name()); <ide> } <del> $name = Inflector::classify($name); <add> $name = Inflector::camelize($name); <ide> $this->bake($name); <ide> $this->bakeTest($name); <ide> } <ide><path>tests/TestCase/Console/Command/BakeShellTest.php <ide> public function testMain() { <ide> ->method('out') <ide> ->with($this->stringContains('The following commands')); <ide> <del> $this->Shell->expects($this->exactly(18)) <add> $this->Shell->expects($this->exactly(19)) <ide> ->method('out'); <ide> <ide> $this->Shell->loadTasks(); <ide> public function testLoadTasksCoreAndApp() { <ide> $this->Shell->loadTasks(); <ide> $expected = [ <ide> 'Behavior', <add> 'Cell', <ide> 'Component', <ide> 'Controller', <ide> 'Fixture', <ide><path>tests/TestCase/Console/Command/CompletionShellTest.php <ide> public function testSubCommandsCorePlugin() { <ide> $this->Shell->runCommand(['subcommands', 'CORE.bake']); <ide> $output = $this->out->output; <ide> <del> $expected = "behavior component controller fixture helper model plugin project shell test view widget zerg\n"; <add> $expected = "behavior cell component controller fixture helper model plugin project shell test view widget zerg\n"; <ide> $this->assertEquals($expected, $output); <ide> } <ide> <ide> public function testSubCommands() { <ide> $this->Shell->runCommand(['subcommands', 'bake']); <ide> $output = $this->out->output; <ide> <del> $expected = "behavior component controller fixture helper model plugin project shell test view widget zerg\n"; <add> $expected = "behavior cell component controller fixture helper model plugin project shell test view widget zerg\n"; <ide> $this->assertEquals($expected, $output); <ide> } <ide>
3
Java
Java
add @functionalinterface on candidate interfaces
e4b0486c5a7dbf8e323f89b1539cbaca7d1a5932
<ide><path>spring-aop/src/main/java/org/aopalliance/intercept/MethodInterceptor.java <ide> * <ide> * @author Rod Johnson <ide> */ <add>@FunctionalInterface <ide> public interface MethodInterceptor extends Interceptor { <ide> <ide> /** <ide><path>spring-aop/src/main/java/org/springframework/aop/ClassFilter.java <ide> /* <del> * Copyright 2002-2007 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see Pointcut <ide> * @see MethodMatcher <ide> */ <add>@FunctionalInterface <ide> public interface ClassFilter { <ide> <ide> /** <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/TargetSourceCreator.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Rod Johnson <ide> * @author Juergen Hoeller <ide> */ <add>@FunctionalInterface <ide> public interface TargetSourceCreator { <ide> <ide> /** <ide><path>spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncUncaughtExceptionHandler.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Stephane Nicoll <ide> * @since 4.1 <ide> */ <add>@FunctionalInterface <ide> public interface AsyncUncaughtExceptionHandler { <ide> <ide> /** <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/BeanFactoryPostProcessor.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see BeanPostProcessor <ide> * @see PropertyResourceConfigurer <ide> */ <add>@FunctionalInterface <ide> public interface BeanFactoryPostProcessor { <ide> <ide> /** <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/parsing/SourceExtractor.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see org.springframework.beans.BeanMetadataElement#getSource() <ide> * @see org.springframework.beans.factory.config.BeanDefinition <ide> */ <add>@FunctionalInterface <ide> public interface SourceExtractor { <ide> <ide> /** <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerResolver.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see NamespaceHandler <ide> * @see org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader <ide> */ <add>@FunctionalInterface <ide> public interface NamespaceHandlerResolver { <ide> <ide> /** <ide><path>spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessagePreparator.java <ide> * @see JavaMailSender#send(MimeMessagePreparator[]) <ide> * @see MimeMessageHelper <ide> */ <add>@FunctionalInterface <ide> public interface MimeMessagePreparator { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/cache/Cache.java <ide> public interface Cache { <ide> /** <ide> * A (wrapper) object representing a cache value. <ide> */ <add> @FunctionalInterface <ide> interface ValueWrapper { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java <ide> public int hashCode() { <ide> * Callback interface providing {@link CacheOperation} instance(s) based on <ide> * a given {@link CacheAnnotationParser}. <ide> */ <add> @FunctionalInterface <ide> protected interface CacheOperationProvider { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperationInvoker.java <ide> * @author Stephane Nicoll <ide> * @since 4.1 <ide> */ <add>@FunctionalInterface <ide> public interface CacheOperationInvoker { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheResolver.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Stephane Nicoll <ide> * @since 4.1 <ide> */ <add>@FunctionalInterface <ide> public interface CacheResolver { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/KeyGenerator.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Phillip Webb <ide> * @since 3.1 <ide> */ <add>@FunctionalInterface <ide> public interface KeyGenerator { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/context/ApplicationListener.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @param <E> the specific ApplicationEvent subclass to listen to <ide> * @see org.springframework.context.event.ApplicationEventMulticaster <ide> */ <add>@FunctionalInterface <ide> public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/context/annotation/Condition.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see Conditional <ide> * @see ConditionContext <ide> */ <add>@FunctionalInterface <ide> public interface Condition { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java <ide> private Class<?> createClass(Enhancer enhancer) { <ide> * must remain public in order to allow access to subclasses generated from other <ide> * packages (i.e. user code). <ide> */ <add> @FunctionalInterface <ide> public interface EnhancedConfiguration extends BeanFactoryAware { <ide> } <ide> <ide> public interface EnhancedConfiguration extends BeanFactoryAware { <ide> * Conditional {@link Callback}. <ide> * @see ConditionalCallbackFilter <ide> */ <add> @FunctionalInterface <ide> private interface ConditionalCallback extends Callback { <ide> <ide> boolean isMatch(Method candidateMethod); <ide><path>spring-context/src/main/java/org/springframework/context/annotation/ScopeMetadataResolver.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 2.5 <ide> * @see org.springframework.context.annotation.Scope <ide> */ <add>@FunctionalInterface <ide> public interface ScopeMetadataResolver { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/format/Parser.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 3.0 <ide> * @param <T> the type of object this Parser produces <ide> */ <add>@FunctionalInterface <ide> public interface Parser<T> { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/format/Printer.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 3.0 <ide> * @param <T> the type of object this Printer prints <ide> */ <add>@FunctionalInterface <ide> public interface Printer<T> { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java <ide> private void notifyListenersOfUnregistration(ObjectName objectName) { <ide> /** <ide> * Internal callback interface for the autodetection process. <ide> */ <del> private static interface AutodetectCallback { <add> @FunctionalInterface <add> private interface AutodetectCallback { <ide> <ide> /** <ide> * Called during the autodetection process to decide whether <ide><path>spring-context/src/main/java/org/springframework/jmx/export/naming/ObjectNamingStrategy.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see org.springframework.jmx.export.MBeanExporter <ide> * @see javax.management.ObjectName <ide> */ <add>@FunctionalInterface <ide> public interface ObjectNamingStrategy { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/jmx/export/notification/NotificationPublisher.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see NotificationPublisherAware <ide> * @see org.springframework.jmx.export.MBeanExporter <ide> */ <add>@FunctionalInterface <ide> public interface NotificationPublisher { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/jndi/JndiCallback.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see JndiTemplate <ide> * @see org.springframework.jdbc.core.JdbcTemplate <ide> */ <add>@FunctionalInterface <ide> public interface JndiCallback<T> { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/SchedulingConfigurer.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see EnableScheduling <ide> * @see ScheduledTaskRegistrar <ide> */ <add>@FunctionalInterface <ide> public interface SchedulingConfigurer { <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/scripting/groovy/GroovyObjectCustomizer.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 2.0.2 <ide> * @see GroovyScriptFactory <ide> */ <add>@FunctionalInterface <ide> public interface GroovyObjectCustomizer { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/MethodIntrospector.java <ide> public static Method selectInvocableMethod(Method method, Class<?> targetType) { <ide> * A callback interface for metadata lookup on a given method. <ide> * @param <T> the type of metadata returned <ide> */ <add> @FunctionalInterface <ide> public interface MetadataLookup<T> { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/OrderComparator.java <ide> else if (value instanceof List) { <ide> * Strategy interface to provide an order source for a given object. <ide> * @since 4.1 <ide> */ <add> @FunctionalInterface <ide> public interface OrderSourceProvider { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/convert/converter/Converter.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @param <S> the source type <ide> * @param <T> the target type <ide> */ <add>@FunctionalInterface <ide> public interface Converter<S, T> { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/io/ProtocolResolver.java <ide> * @since 4.3 <ide> * @see DefaultResourceLoader#addProtocolResolver <ide> */ <add>@FunctionalInterface <ide> public interface ProtocolResolver { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/serializer/Deserializer.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Mark Fisher <ide> * @since 3.0.5 <ide> */ <add>@FunctionalInterface <ide> public interface Deserializer<T> { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/serializer/Serializer.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Mark Fisher <ide> * @since 3.0.5 <ide> */ <add>@FunctionalInterface <ide> public interface Serializer<T> { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/task/TaskDecorator.java <ide> * @see TaskExecutor#execute(Runnable) <ide> * @see SimpleAsyncTaskExecutor#setTaskDecorator <ide> */ <add>@FunctionalInterface <ide> public interface TaskDecorator { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/task/TaskExecutor.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 2.0 <ide> * @see java.util.concurrent.Executor <ide> */ <add>@FunctionalInterface <ide> public interface TaskExecutor extends Executor { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/core/type/filter/TypeFilter.java <ide> /* <del> * Copyright 2002-2007 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Mark Fisher <ide> * @since 2.5 <ide> */ <add>@FunctionalInterface <ide> public interface TypeFilter { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/AutoPopulatingList.java <ide> public int hashCode() { <ide> * Factory interface for creating elements for an index-based access <ide> * data structure such as a {@link java.util.List}. <ide> */ <add> @FunctionalInterface <ide> public interface ElementFactory<E> { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/ErrorHandler.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Mark Fisher <ide> * @since 3.0 <ide> */ <add>@FunctionalInterface <ide> public interface ErrorHandler { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java <ide> else if (StringUtils.substringMatch(buf, index, this.simplePrefix)) { <ide> /** <ide> * Strategy interface used to resolve replacement values for placeholders contained in Strings. <ide> */ <del> public static interface PlaceholderResolver { <add> @FunctionalInterface <add> public interface PlaceholderResolver { <ide> <ide> /** <ide> * Resolve the supplied placeholder name to the replacement value. <ide><path>spring-core/src/main/java/org/springframework/util/ReflectionUtils.java <ide> public static void clearCache() { <ide> /** <ide> * Action to take on each method. <ide> */ <add> @FunctionalInterface <ide> public interface MethodCallback { <ide> <ide> /** <ide> public interface MethodCallback { <ide> /** <ide> * Callback optionally used to filter methods to be operated on by a method callback. <ide> */ <add> @FunctionalInterface <ide> public interface MethodFilter { <ide> <ide> /** <ide> public interface MethodFilter { <ide> /** <ide> * Callback interface invoked on each field in the hierarchy. <ide> */ <add> @FunctionalInterface <ide> public interface FieldCallback { <ide> <ide> /** <ide> public interface FieldCallback { <ide> /** <ide> * Callback optionally used to filter fields to be operated on by a field callback. <ide> */ <add> @FunctionalInterface <ide> public interface FieldFilter { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/StringValueResolver.java <ide> /* <del> * Copyright 2002-2007 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see org.springframework.beans.factory.config.BeanDefinitionVisitor#BeanDefinitionVisitor(StringValueResolver) <ide> * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer <ide> */ <add>@FunctionalInterface <ide> public interface StringValueResolver { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/backoff/BackOff.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 4.1 <ide> * @see BackOffExecution <ide> */ <add>@FunctionalInterface <ide> public interface BackOff { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/backoff/BackOffExecution.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 4.1 <ide> * @see BackOff <ide> */ <add>@FunctionalInterface <ide> public interface BackOffExecution { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/concurrent/FailureCallback.java <ide> * @author Sebastien Deleuze <ide> * @since 4.1 <ide> */ <add>@FunctionalInterface <ide> public interface FailureCallback { <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/concurrent/SuccessCallback.java <ide> * @author Sebastien Deleuze <ide> * @since 4.1 <ide> */ <add>@FunctionalInterface <ide> public interface SuccessCallback<T> { <ide> <ide> /** <ide><path>spring-expression/src/main/java/org/springframework/expression/ConstructorResolver.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Andy Clement <ide> * @since 3.0 <ide> */ <add>@FunctionalInterface <ide> public interface ConstructorResolver { <ide> <ide> /** <ide><path>spring-expression/src/main/java/org/springframework/expression/MethodFilter.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Andy Clement <ide> * @since 3.0.1 <ide> */ <add>@FunctionalInterface <ide> public interface MethodFilter { <ide> <ide> /** <ide><path>spring-expression/src/main/java/org/springframework/expression/TypeLocator.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Andy Clement <ide> * @since 3.0 <ide> */ <add>@FunctionalInterface <ide> public interface TypeLocator { <ide> <ide> /** <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/CodeFlow.java <ide> public String getClassname() { <ide> return clazzName; <ide> } <ide> <add> @FunctionalInterface <ide> public interface FieldAdder { <del> public void generateField(ClassWriter cw, CodeFlow codeflow); <add> void generateField(ClassWriter cw, CodeFlow codeflow); <ide> } <ide> <add> @FunctionalInterface <ide> public interface ClinitAdder { <del> public void generateCode(MethodVisitor mv, CodeFlow codeflow); <add> void generateCode(MethodVisitor mv, CodeFlow codeflow); <ide> } <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCallback.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see JdbcTemplate#execute(String, CallableStatementCallback) <ide> * @see JdbcTemplate#execute(CallableStatementCreator, CallableStatementCallback) <ide> */ <add>@FunctionalInterface <ide> public interface CallableStatementCallback<T> { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCreator.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see JdbcTemplate#call <ide> * @see SqlProvider <ide> */ <add>@FunctionalInterface <ide> public interface CallableStatementCreator { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/ConnectionCallback.java <ide> * @see JdbcTemplate#query <ide> * @see JdbcTemplate#update <ide> */ <add>@FunctionalInterface <ide> public interface ConnectionCallback<T> { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/ParameterMapper.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see CallableStatementCreatorFactory#newCallableStatementCreator(ParameterMapper) <ide> * @see org.springframework.jdbc.object.StoredProcedure#execute(ParameterMapper) <ide> */ <add>@FunctionalInterface <ide> public interface ParameterMapper { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/ParameterizedPreparedStatementSetter.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 3.1 <ide> * @see JdbcTemplate#batchUpdate(String, java.util.Collection, int, ParameterizedPreparedStatementSetter) <ide> */ <add>@FunctionalInterface <ide> public interface ParameterizedPreparedStatementSetter<T> { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCallback.java <ide> * @see JdbcTemplate#execute(String, PreparedStatementCallback) <ide> * @see JdbcTemplate#execute(PreparedStatementCreator, PreparedStatementCallback) <ide> */ <add>@FunctionalInterface <ide> public interface PreparedStatementCallback<T> { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreator.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see JdbcTemplate#update(PreparedStatementCreator) <ide> * @see SqlProvider <ide> */ <add>@FunctionalInterface <ide> public interface PreparedStatementCreator { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementSetter.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see JdbcTemplate#update(String, PreparedStatementSetter) <ide> * @see JdbcTemplate#query(String, PreparedStatementSetter, ResultSetExtractor) <ide> */ <add>@FunctionalInterface <ide> public interface PreparedStatementSetter { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/ResultSetExtractor.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see RowMapper <ide> * @see org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor <ide> */ <add>@FunctionalInterface <ide> public interface ResultSetExtractor<T> { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/RowCallbackHandler.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see ResultSetExtractor <ide> * @see RowCountCallbackHandler <ide> */ <add>@FunctionalInterface <ide> public interface RowCallbackHandler { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/RowMapper.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see ResultSetExtractor <ide> * @see org.springframework.jdbc.object.MappingSqlQuery <ide> */ <add>@FunctionalInterface <ide> public interface RowMapper<T> { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/StatementCallback.java <ide> * @since 16.03.2004 <ide> * @see JdbcTemplate#execute(StatementCallback) <ide> */ <add>@FunctionalInterface <ide> public interface StatementCallback<T> { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/DatabasePopulator.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see DatabasePopulatorUtils <ide> * @see DataSourceInitializer <ide> */ <add>@FunctionalInterface <ide> public interface DatabasePopulator { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/DataSourceLookup.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 2.0 <ide> * @see org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager#setDataSourceLookup <ide> */ <add>@FunctionalInterface <ide> public interface DataSourceLookup { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/DatabaseMetaDataCallback.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Thomas Risberg <ide> * @see JdbcUtils#extractDatabaseMetaData <ide> */ <add>@FunctionalInterface <ide> public interface DatabaseMetaDataCallback { <ide> <ide> /** <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLExceptionTranslator.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Juergen Hoeller <ide> * @see org.springframework.dao.DataAccessException <ide> */ <add>@FunctionalInterface <ide> public interface SQLExceptionTranslator { <ide> <ide> /** <ide><path>spring-jms/src/main/java/org/springframework/jms/annotation/JmsListenerConfigurer.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see EnableJms <ide> * @see JmsListenerEndpointRegistrar <ide> */ <add>@FunctionalInterface <ide> public interface JmsListenerConfigurer { <ide> <ide> /** <ide><path>spring-jms/src/main/java/org/springframework/jms/core/BrowserCallback.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see JmsTemplate#browse(BrowserCallback) <ide> * @see JmsTemplate#browseSelected(String, BrowserCallback) <ide> */ <add>@FunctionalInterface <ide> public interface BrowserCallback<T> { <ide> <ide> /** <ide><path>spring-jms/src/main/java/org/springframework/jms/core/MessageCreator.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Mark Pollack <ide> * @since 1.1 <ide> */ <add>@FunctionalInterface <ide> public interface MessageCreator { <ide> <ide> /** <ide><path>spring-jms/src/main/java/org/springframework/jms/core/ProducerCallback.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see JmsTemplate#execute(javax.jms.Destination, ProducerCallback) <ide> * @see JmsTemplate#execute(String, ProducerCallback) <ide> */ <add>@FunctionalInterface <ide> public interface ProducerCallback<T> { <ide> <ide> /** <ide><path>spring-jms/src/main/java/org/springframework/jms/core/SessionCallback.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 1.1 <ide> * @see JmsTemplate#execute(SessionCallback) <ide> */ <add>@FunctionalInterface <ide> public interface SessionCallback<T> { <ide> <ide> /** <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/SessionAwareMessageListener.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see org.springframework.jms.listener.endpoint.JmsMessageEndpointManager <ide> * @see javax.jms.MessageListener <ide> */ <add>@FunctionalInterface <ide> public interface SessionAwareMessageListener<M extends Message> { <ide> <ide> /** <ide><path>spring-jms/src/main/java/org/springframework/jms/support/destination/DestinationResolver.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see org.springframework.jms.support.destination.DynamicDestinationResolver <ide> * @see org.springframework.jms.support.destination.JndiDestinationResolver <ide> */ <add>@FunctionalInterface <ide> public interface DestinationResolver { <ide> <ide> /** <ide><path>spring-messaging/src/main/java/org/springframework/messaging/MessageHandler.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Iwein Fuld <ide> * @since 4.0 <ide> */ <add>@FunctionalInterface <ide> public interface MessageHandler { <ide> <ide> /** <ide><path>spring-messaging/src/main/java/org/springframework/messaging/converter/ContentTypeResolver.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <add>@FunctionalInterface <ide> public interface ContentTypeResolver { <ide> <ide> /** <ide><path>spring-messaging/src/main/java/org/springframework/messaging/core/DestinationResolver.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Mark Fisher <ide> * @since 4.0 <ide> */ <add>@FunctionalInterface <ide> public interface DestinationResolver<D> { <ide> <ide> /** <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/user/SimpSubscriptionMatcher.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Rossen Stoyanchev <ide> * @since 4.2 <ide> */ <add>@FunctionalInterface <ide> public interface SimpSubscriptionMatcher { <ide> <ide> /** <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/user/UserDestinationResolver.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see org.springframework.messaging.simp.user.DefaultUserDestinationResolver <ide> * @see UserDestinationMessageHandler <ide> */ <add>@FunctionalInterface <ide> public interface UserDestinationResolver { <ide> <ide> /** <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/ReconnectStrategy.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <add>@FunctionalInterface <ide> public interface ReconnectStrategy { <ide> <ide> /** <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/HibernateCallback.java <ide> * @see HibernateTemplate <ide> * @see HibernateTransactionManager <ide> */ <add>@FunctionalInterface <ide> public interface HibernateCallback<T> { <ide> <ide> /** <ide><path>spring-test/src/main/java/org/springframework/test/context/ActiveProfilesResolver.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 4.0 <ide> * @see ActiveProfiles <ide> */ <add>@FunctionalInterface <ide> public interface ActiveProfilesResolver { <ide> <ide> /** <ide><path>spring-test/src/main/java/org/springframework/test/web/client/RequestMatcher.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Craig Walls <ide> * @since 3.2 <ide> */ <add>@FunctionalInterface <ide> public interface RequestMatcher { <ide> <ide> /** <ide><path>spring-test/src/main/java/org/springframework/test/web/client/ResponseCreator.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Craig Walls <ide> * @since 3.2 <ide> */ <add>@FunctionalInterface <ide> public interface ResponseCreator { <ide> <ide> /** <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/ResultHandler.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <add>@FunctionalInterface <ide> public interface ResultHandler { <ide> <ide> /** <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/ResultMatcher.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <add>@FunctionalInterface <ide> public interface ResultMatcher { <ide> <ide> /** <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/WebRequestMatcher.java <ide> * @see org.springframework.test.web.servlet.htmlunit.HostRequestMatcher <ide> * @see org.springframework.test.web.servlet.htmlunit.UrlRegexRequestMatcher <ide> */ <add>@FunctionalInterface <ide> public interface WebRequestMatcher { <ide> <ide> /** <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/RequestPostProcessor.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Rob Winch <ide> * @since 3.2 <ide> */ <add>@FunctionalInterface <ide> public interface RequestPostProcessor { <ide> <ide> /** <ide><path>spring-tx/src/main/java/org/springframework/dao/support/PersistenceExceptionTranslator.java <ide> * @author Juergen Hoeller <ide> * @since 2.0 <ide> */ <add>@FunctionalInterface <ide> public interface PersistenceExceptionTranslator { <ide> <ide> /** <ide><path>spring-tx/src/main/java/org/springframework/jca/cci/core/ConnectionCallback.java <ide> * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, javax.resource.cci.Record) <ide> * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, RecordCreator, RecordExtractor) <ide> */ <add>@FunctionalInterface <ide> public interface ConnectionCallback<T> { <ide> <ide> /** <ide><path>spring-tx/src/main/java/org/springframework/jca/cci/core/InteractionCallback.java <ide> * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, javax.resource.cci.Record) <ide> * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, RecordCreator, RecordExtractor) <ide> */ <add>@FunctionalInterface <ide> public interface InteractionCallback<T> { <ide> <ide> /** <ide><path>spring-tx/src/main/java/org/springframework/jca/cci/core/RecordCreator.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see CciTemplate#createMappedRecord(String) <ide> * @see CciTemplate#setOutputRecordCreator(RecordCreator) <ide> */ <add>@FunctionalInterface <ide> public interface RecordCreator { <ide> <ide> /** <ide><path>spring-tx/src/main/java/org/springframework/jca/cci/core/RecordExtractor.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, RecordCreator, RecordExtractor) <ide> * @see javax.resource.cci.ResultSet <ide> */ <add>@FunctionalInterface <ide> public interface RecordExtractor<T> { <ide> <ide> /** <ide><path>spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java <ide> public String toString() { <ide> * Simple callback interface for proceeding with the target invocation. <ide> * Concrete interceptors/aspects adapt this to their invocation mechanism. <ide> */ <add> @FunctionalInterface <ide> protected interface InvocationCallback { <ide> <ide> Object proceedWithInvocation() throws Throwable; <ide><path>spring-tx/src/main/java/org/springframework/transaction/support/TransactionCallback.java <ide> * @see TransactionTemplate <ide> * @see CallbackPreferringPlatformTransactionManager <ide> */ <add>@FunctionalInterface <ide> public interface TransactionCallback<T> { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/http/StreamingHttpOutputMessage.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public interface StreamingHttpOutputMessage extends HttpOutputMessage { <ide> * It is useful with HTTP client libraries that provide indirect access to an <ide> * {@link OutputStream} via a callback mechanism. <ide> */ <add> @FunctionalInterface <ide> interface Body { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/http/client/ClientHttpRequestExecution.java <ide> /* <del> * Copyright 2002-2011 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see ClientHttpRequestInterceptor <ide> * @since 3.1 <ide> */ <add>@FunctionalInterface <ide> public interface ClientHttpRequestExecution { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/http/client/ClientHttpRequestFactory.java <ide> /* <del> * Copyright 2002-2009 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Arjen Poutsma <ide> * @since 3.0 <ide> */ <add>@FunctionalInterface <ide> public interface ClientHttpRequestFactory { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/http/client/ClientHttpRequestInterceptor.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Arjen Poutsma <ide> * @since 3.1 <ide> */ <add>@FunctionalInterface <ide> public interface ClientHttpRequestInterceptor { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/remoting/httpinvoker/HttpInvokerRequestExecutor.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 1.1 <ide> * @see HttpInvokerClientInterceptor#setHttpInvokerRequestExecutor <ide> */ <add>@FunctionalInterface <ide> public interface HttpInvokerRequestExecutor { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/web/HttpRequestHandler.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see org.springframework.remoting.caucho.HessianServiceExporter <ide> * @see org.springframework.remoting.caucho.BurlapServiceExporter <ide> */ <add>@FunctionalInterface <ide> public interface HttpRequestHandler { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationStrategy.java <ide> * @author Rossen Stoyanchev <ide> * @since 3.2 <ide> */ <add>@FunctionalInterface <ide> public interface ContentNegotiationStrategy { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/web/bind/support/WebArgumentResolver.java <ide> * @since 2.5.2 <ide> * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#setCustomArgumentResolvers <ide> */ <add>@FunctionalInterface <ide> public interface WebArgumentResolver { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/web/client/AsyncRequestCallback.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see org.springframework.web.client.AsyncRestTemplate#execute <ide> * @since 4.0 <ide> */ <add>@FunctionalInterface <ide> public interface AsyncRequestCallback { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/web/client/RequestCallback.java <ide> /* <del> * Copyright 2002-2009 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see RestTemplate#execute <ide> * @since 3.0 <ide> */ <add>@FunctionalInterface <ide> public interface RequestCallback { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/web/client/ResponseExtractor.java <ide> /* <del> * Copyright 2002-2009 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @since 3.0 <ide> * @see RestTemplate#execute <ide> */ <add>@FunctionalInterface <ide> public interface ResponseExtractor<T> { <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public <S> void afterCompletion(NativeWebRequest request, DeferredResult<S> defe <ide> /** <ide> * Handles a DeferredResult value when set. <ide> */ <add> @FunctionalInterface <ide> public interface DeferredResultHandler { <ide> <ide> void handleResult(Object result); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/HandlerMethodMappingNamingStrategy.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Rossen Stoyanchev <ide> * @since 4.1 <ide> */ <add>@FunctionalInterface <ide> public interface HandlerMethodMappingNamingStrategy<T> { <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/Controller.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @see org.springframework.web.context.ServletContextAware <ide> * @see org.springframework.web.context.support.WebApplicationObjectSupport <ide> */ <add>@FunctionalInterface <ide> public interface Controller { <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterAdapter.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.3 <ide> */ <add>@FunctionalInterface <ide> public interface ResponseBodyEmitterAdapter { <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBody.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Rossen Stoyanchev <ide> * @since 4.2 <ide> */ <add>@FunctionalInterface <ide> public interface StreamingResponseBody { <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/AppCacheManifestTransformer.java <ide> public Resource transform(HttpServletRequest request, Resource resource, Resourc <ide> } <ide> <ide> <del> private static interface SectionTransformer { <add> @FunctionalInterface <add> private interface SectionTransformer { <ide> <ide> /** <ide> * Transforms a line in a section of the manifest. <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/CssLinkResourceTransformer.java <ide> private boolean hasScheme(String link) { <ide> } <ide> <ide> <del> protected static interface CssLinkParser { <add> @FunctionalInterface <add> protected interface CssLinkParser { <ide> <ide> void parseLink(String content, Set<CssLinkInfo> linkInfos); <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceTransformer.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * @author Rossen Stoyanchev <ide> * @since 4.1 <ide> */ <add>@FunctionalInterface <ide> public interface ResourceTransformer { <ide> <ide> /**
110
Javascript
Javascript
remove dead code
b0307a33ebb338405590345f281885cb6e17404d
<ide><path>src/ng/parse.js <ide> CONSTANTS['this'].sharedGetter = true; <ide> <ide> //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter <ide> var OPERATORS = extend(createMap(), { <del> /* jshint bitwise : false */ <ide> '+':function(self, locals, a,b){ <ide> a=a(self, locals); b=b(self, locals); <ide> if (isDefined(a)) { <ide> var OPERATORS = extend(createMap(), { <ide> '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, <ide> '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, <ide> '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, <del> '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, <ide> '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, <ide> '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, <ide> '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, <ide> var OPERATORS = extend(createMap(), { <ide> '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, <ide> '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, <ide> '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, <del> '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, <ide> '!':function(self, locals, a){return !a(self, locals);}, <ide> <ide> //Tokenized as operators but parsed as assignment/filters <ide> '=':true, <ide> '|':true <ide> }); <del>/* jshint bitwise: true */ <ide> var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; <ide> <ide>
1
Python
Python
update isfortran docs with return value
be9a134202e097d7d279425bdb137409084fe115
<ide><path>numpy/core/numeric.py <ide> def count_nonzero(a, axis=None): <ide> @set_module('numpy') <ide> def isfortran(a): <ide> """ <del> Returns True if the array is Fortran contiguous but *not* C contiguous. <del> <add> Check if the array is Fortran contiguous but *not* C contiguous. <add> <ide> This function is obsolete and, because of changes due to relaxed stride <ide> checking, its return value for the same array may differ for versions <ide> of NumPy >= 1.10.0 and previous versions. If you only want to check if an <ide> array is Fortran contiguous use ``a.flags.f_contiguous`` instead. <del> <add> <ide> Parameters <ide> ---------- <ide> a : ndarray <ide> Input array. <add> <add> Returns <add> ------- <add> isfortran : bool <add> Returns True if the array is Fortran contiguous but *not* C contiguous. <ide> <ide> <ide> Examples
1
Javascript
Javascript
add unit test for nested event managers
17a06e487e23cacc890b9c9a8177f97e4fb9acf5
<ide><path>packages/sproutcore-touch/tests/system/nested_event_managers.js <add>// ========================================================================== <add>// Project: SproutCore Runtime <add>// Copyright: ©2011 Strobe Inc. and contributors. <add>// License: Licensed under MIT license (see license.js) <add>// ========================================================================== <add> <add>var set = SC.set; <add>var get = SC.get; <add>var application; <add> <add>module("Nested event managers", { <add> setup: function() { <add> application = SC.Application.create(); <add> }, <add> <add> teardown: function() { <add> application.destroy(); <add> } <add>}); <add> <add>test("Nested event managers should get called appropriately", function() { <add> <add> SC.Gestures.register('nestedEventManagerTestGesture',SC.Gesture.extend({ <add> touchStart: function(evt, view, manager) { <add> this.notifyViewOfGestureEvent(view, 'nestedEventManagerTestGestureStart'); <add> manager.redispatchEventToView(view,'touchstart'); <add> } <add> })); <add> <add> SC.Gestures.register('nestedViewTestGesture',SC.Gesture.extend({ <add> touchStart: function(evt, view, manager) { <add> this.notifyViewOfGestureEvent(view, 'nestedViewTestGestureStart'); <add> manager.redispatchEventToView(view,'touchstart'); <add> } <add> })); <add> <add> var callNumber = 0; <add> <add> var view = SC.ContainerView.create({ <add> <add> childViews: ['nestedView'], <add> <add> nestedView: SC.View.extend({ <add> elementId: 'nestedTestView', <add> <add> nestedViewTestGestureStart: function() { <add> equals(callNumber,0,'nested manager called first'); <add> callNumber++; <add> }, <add> <add> touchStart: function() { <add> equals(callNumber,1,'nested view called second'); <add> callNumber++; <add> } <add> }), <add> <add> nestedEventManagerTestGestureStart: function() { <add> equals(callNumber,2,'parent manager called third'); <add> callNumber++; <add> }, <add> <add> touchStart: function() { <add> equals(callNumber,3,'parent view called fourth'); <add> callNumber++; <add> } <add> }); <add> <add> SC.run(function(){ <add> view.append(); <add> }); <add> <add> var gestures = get(get(view, 'eventManager'), 'gestures'); <add> <add> ok(gestures); <add> equals(gestures.length,1); <add> <add> $('#nestedTestView').trigger('touchstart'); <add> <add>}); <add>
1
Javascript
Javascript
ignore events on text nodes
5a1e30a868b96753504a4a29a60a820f9c81ed76
<ide><path>src/renderers/shared/shared/event/EventPluginHub.js <ide> var EventPluginHub = { <ide> return null; <ide> } <ide> } else { <add> if (typeof inst._currentElement === 'string') { <add> // Text node, let it bubble through. <add> return null; <add> } <ide> const props = inst._currentElement.props; <ide> listener = props[registrationName]; <ide> if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, props)) {
1
PHP
PHP
simplify log levels
2bf2b1680b7d70a9ed9aa11ac271e10c26ccc4c7
<ide><path>src/Illuminate/Log/Writer.php <ide> class Writer implements LogContract, PsrLoggerInterface { <ide> */ <ide> protected $dispatcher; <ide> <add> /** <add> * The Log levels. <add> * <add> * @var array <add> */ <add> protected $levels = [ <add> 'debug' => MonologLogger::DEBUG, <add> 'info' => MonologLogger::INFO, <add> 'notice' => MonologLogger::NOTICE, <add> 'warning' => MonologLogger::WARNING, <add> 'error' => MonologLogger::ERROR, <add> 'critical' => MonologLogger::CRITICAL, <add> 'alert' => MonologLogger::ALERT, <add> 'emergency' => MonologLogger::EMERGENCY, <add> ]; <add> <ide> /** <ide> * Create a new log writer instance. <ide> * <ide> protected function formatMessage($message) <ide> */ <ide> protected function parseLevel($level) <ide> { <del> switch ($level) <add> return array_get($this->levels, $level, function () <ide> { <del> case 'debug': <del> return MonologLogger::DEBUG; <del> <del> case 'info': <del> return MonologLogger::INFO; <del> <del> case 'notice': <del> return MonologLogger::NOTICE; <del> <del> case 'warning': <del> return MonologLogger::WARNING; <del> <del> case 'error': <del> return MonologLogger::ERROR; <del> <del> case 'critical': <del> return MonologLogger::CRITICAL; <del> <del> case 'alert': <del> return MonologLogger::ALERT; <del> <del> case 'emergency': <del> return MonologLogger::EMERGENCY; <del> <del> default: <del> throw new \InvalidArgumentException("Invalid log level."); <del> } <add> throw new \InvalidArgumentException("Invalid log level."); <add> }); <ide> } <ide> <ide> /**
1
Python
Python
use spdx license expression in project metadata
e0b0af6c7af9f7a127ae0321dc4e798433c89592
<ide><path>setup.py <ide> def run_tests(self): <ide> author=meta['author'], <ide> author_email=meta['contact'], <ide> url=meta['homepage'], <del> license='BSD', <add> license='BSD-3-Clause', <ide> platforms=['any'], <ide> install_requires=install_requires(), <ide> python_requires=">=3.7",
1
PHP
PHP
fix bug when using raw_where with eloquent
4a52aabd15485e6c047238372142aaae9609dbb8
<ide><path>laravel/database/grammars/grammar.php <ide> protected function where_not_null($where) <ide> /** <ide> * Compile a raw WHERE clause. <ide> * <del> * @param string $where <add> * @param array $where <ide> * @return string <ide> */ <ide> protected function where_raw($where) <ide> { <del> return $where; <add> return $where['sql']; <ide> } <ide> <ide> /**
1
Python
Python
use amax and amin in ma.py
f2f568d9572d2b37139095a1caec4021cd5e0327
<ide><path>scipy/base/ma.py <ide> import umath <ide> import oldnumeric <ide> import function_base <add>from function_base import amax, amin <ide> from numeric import e, pi, newaxis, ndarray <ide> from oldnumeric import typecodes <ide> from numerictypes import * <ide> def __call__ (self, a, b=None): <ide> if b is None: <ide> m = getmask(a) <ide> if m is None: <del> d = min(filled(a).ravel()) <add> d = amin(filled(a).ravel()) <ide> return d <ide> ac = a.compressed() <ide> if len(ac) == 0: <ide> return masked <ide> else: <del> return min(ac.raw_data()) <add> return amin(ac.raw_data()) <ide> else: <ide> return where(less(a, b), a, b)[...] <ide> <ide> def __call__ (self, a, b=None): <ide> if b is None: <ide> m = getmask(a) <ide> if m is None: <del> d = max(filled(a).ravel()) <add> d = amax(filled(a).ravel()) <ide> return d <ide> ac = a.compressed() <ide> if len(ac) == 0: <ide> return masked <ide> else: <del> return max(ac.raw_data()) <add> return amax(ac.raw_data()) <ide> else: <ide> return where(greater(a, b), a, b)[...] <ide> <ide><path>scipy/base/records.py <ide> def _parseFormats(self, formats, aligned=0): <ide> self._formats[i] = `_repeat`+self._f_formats[i] <ide> if (_repeat != 1): <ide> self._f_formats[i] = (self._f_formats[i], _repeat) <del> <del> <add> <ide> self._fmt = _fmt <ide> # This pads record so next record is aligned if self._rec_align is <ide> # true. Otherwise next the record starts right after the end
2
Ruby
Ruby
avoid type casting in uniqueness validator
aa062318c451512035c10898a1af95943b1a3803
<ide><path>activerecord/lib/active_record/validations/uniqueness.rb <ide> def validate_each(record, attribute, value) <ide> <ide> record.errors.add(attribute, :taken, error_options) <ide> end <add> rescue RangeError <ide> end <ide> <ide> protected <ide> def build_relation(klass, table, attribute, value) #:nodoc: <ide> <ide> column = klass.columns_hash[attribute_name] <ide> cast_type = klass.type_for_attribute(attribute_name) <del> value = cast_type.serialize(value) <del> value = klass.connection.type_cast(value) <ide> <ide> comparison = if !options[:case_sensitive] && !value.nil? <ide> # will use SQL LOWER function before comparison, unless it detects a case insensitive collation <ide> def build_relation(klass, table, attribute, value) #:nodoc: <ide> if value.nil? <ide> klass.unscoped.where(comparison) <ide> else <del> bind = Relation::QueryAttribute.new(attribute_name, value, Type::Value.new) <add> bind = Relation::QueryAttribute.new(attribute_name, value, cast_type) <ide> klass.unscoped.where(comparison, bind) <ide> end <del> rescue RangeError <del> klass.none <ide> end <ide> <ide> def scope_relation(record, table, relation)
1
Python
Python
use common tf_utils
e5c71d51346027a704b980324387a4ba058d8538
<ide><path>official/nlp/xlnet/xlnet_modeling.py <ide> import numpy as np <ide> <ide> import tensorflow as tf <add>from official.modeling import tf_utils <ide> from official.nlp.xlnet import data_utils <ide> <ide> <ide> def is_special_none_tensor(tensor): <ide> return tensor.shape.ndims == 0 and tensor.dtype == tf.int32 <ide> <ide> <del>def unpack_inputs(inputs): <del> """Unpacks a tuple of `inputs` tensors to a tuple. <del> <del> Args: <del> inputs: A list of tensors. <del> <del> Returns: <del> A tuple of tensors. If any input is a special constant tensor, replace it <del> with None. <del> """ <del> inputs = tf.nest.flatten(inputs) <del> outputs = [] <del> for x in inputs: <del> if is_special_none_tensor(x): <del> outputs.append(None) <del> else: <del> outputs.append(x) <del> x = tuple(outputs) <del> <del> # To trick the very pointless 'unbalanced-tuple-unpacking' pylint check <del> # from triggering. <del> if len(x) == 1: <del> return x[0] <del> return tuple(outputs) <del> <del> <del>def pack_inputs(inputs): <del> """Packs a list of `inputs` tensors to a tuple. <del> <del> Args: <del> inputs: A list of tensors. <del> <del> Returns: <del> A tuple of tensors. If any input is None, replace it with a special constant <del> tensor. <del> """ <del> inputs = tf.nest.flatten(inputs) <del> outputs = [] <del> for x in inputs: <del> if x is None: <del> outputs.append(tf.constant(0, shape=[], dtype=tf.int32)) <del> else: <del> outputs.append(x) <del> return tuple(outputs) <del> <del> <ide> class PositionalEmbedding(tf.keras.layers.Layer): <ide> """Generates relative positional embeddings used in Transformer-XL and XLNet.""" <ide> <ide> def build(self, unused_input_shapes): <ide> <ide> def __call__(self, q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, <ide> r_w_bias, r_r_bias, r_s_bias, attn_mask, **kwargs): <del> inputs = pack_inputs([ <add> inputs = tf_utils.pack_inputs([ <ide> q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias, <ide> r_r_bias, r_s_bias, attn_mask <ide> ]) <ide> def __call__(self, q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, <ide> def call(self, inputs): <ide> """Implements call() for the layer.""" <ide> (q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias, <del> r_r_bias, r_s_bias, attn_mask) = unpack_inputs(inputs) <add> r_r_bias, r_s_bias, attn_mask) = tf_utils.unpack_inputs(inputs) <ide> <ide> # content based attention score <ide> ac = tf.einsum('ibnd,jbnd->ijbn', q_head + r_w_bias, k_head_h) <ide> def build(self, unused_input_shapes): <ide> <ide> def __call__(self, h, g, r, r_w_bias, r_r_bias, seg_mat, r_s_bias, seg_embed, <ide> attn_mask_h, attn_mask_g, mems, target_mapping, **kwargs): <del> inputs = pack_inputs([ <add> inputs = tf_utils.pack_inputs([ <ide> h, g, r, r_w_bias, r_r_bias, seg_mat, r_s_bias, seg_embed, attn_mask_h, <ide> attn_mask_g, mems, target_mapping, <ide> ]) <ide> def __call__(self, h, g, r, r_w_bias, r_r_bias, seg_mat, r_s_bias, seg_embed, <ide> def call(self, inputs): <ide> """Implements call() for the layer.""" <ide> (h, g, r, r_w_bias, r_r_bias, seg_mat, r_s_bias, seg_embed, attn_mask_h, <del> attn_mask_g, mems, target_mapping) = unpack_inputs(inputs) <add> attn_mask_g, mems, target_mapping) = tf_utils.unpack_inputs(inputs) <ide> <ide> if mems is not None and mems.shape.ndims > 1: <ide> cat = tf.concat([mems, h], 0) <ide> def build(self, unused_input_shapes): <ide> super(LMLossLayer, self).build(unused_input_shapes) <ide> <ide> def __call__(self, hidden, target, lookup_table, target_mask, **kwargs): <del> inputs = pack_inputs([hidden, target, lookup_table, target_mask]) <add> inputs = tf_utils.pack_inputs([hidden, target, lookup_table, target_mask]) <ide> return super(LMLossLayer, self).__call__(inputs, **kwargs) <ide> <ide> def call(self, inputs): <ide> """Implements call() for the layer.""" <del> (hidden, target, lookup_table, tgt_mask) = unpack_inputs(inputs) <add> (hidden, target, lookup_table, tgt_mask) = tf_utils.unpack_inputs(inputs) <ide> if self.use_proj: <ide> hidden = self.proj_layer_norm(self.proj_layer(hidden)) <ide> if self.tie_weight: <ide> def build(self, unused_input_shapes): <ide> super(ClassificationLossLayer, self).build(unused_input_shapes) <ide> <ide> def __call__(self, hidden, labels, **kwargs): <del> inputs = pack_inputs([hidden, labels]) <add> inputs = tf_utils.pack_inputs([hidden, labels]) <ide> return super(ClassificationLossLayer, self).__call__(inputs, **kwargs) <ide> <ide> def call(self, inputs): <ide> """Implements call() for the layer.""" <del> (hidden, labels) = unpack_inputs(inputs) <add> (hidden, labels) = tf_utils.unpack_inputs(inputs) <ide> <ide> logits = self.proj_layer(hidden) <ide> one_hot_target = tf.one_hot(labels, self.n_class, dtype=hidden.dtype) # pytype: disable=attribute-error
1
Python
Python
fix tfbert tests in python 3.5
798da627ebb24cf729bb55575e69e5d8caf91332
<ide><path>pytorch_transformers/tests/modeling_tf_auto_test.py <ide> <ide> from pytorch_transformers import is_tf_available <ide> <del># if is_tf_available(): <del>if False: <add>if is_tf_available(): <ide> from pytorch_transformers import (AutoConfig, BertConfig, <ide> TFAutoModel, TFBertModel, <ide> TFAutoModelWithLMHead, TFBertForMaskedLM, <ide> def test_model_from_pretrained(self): <ide> self.assertTrue(h5py.version.hdf5_version.startswith("1.10")) <ide> <ide> logging.basicConfig(level=logging.INFO) <del> for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> for model_name in ['bert-base-uncased']: <ide> config = AutoConfig.from_pretrained(model_name, force_download=True) <ide> self.assertIsNotNone(config) <ide> self.assertIsInstance(config, BertConfig) <ide> def test_model_from_pretrained(self): <ide> <ide> def test_lmhead_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <del> for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> for model_name in ['bert-base-uncased']: <ide> config = AutoConfig.from_pretrained(model_name, force_download=True) <ide> self.assertIsNotNone(config) <ide> self.assertIsInstance(config, BertConfig) <ide> def test_lmhead_model_from_pretrained(self): <ide> <ide> def test_sequence_classification_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <del> for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> for model_name in ['bert-base-uncased']: <ide> config = AutoConfig.from_pretrained(model_name, force_download=True) <ide> self.assertIsNotNone(config) <ide> self.assertIsInstance(config, BertConfig) <ide> def test_sequence_classification_model_from_pretrained(self): <ide> <ide> def test_question_answering_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <del> for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> for model_name in ['bert-base-uncased']: <ide> config = AutoConfig.from_pretrained(model_name, force_download=True) <ide> self.assertIsNotNone(config) <ide> self.assertIsInstance(config, BertConfig) <ide><path>pytorch_transformers/tests/modeling_tf_bert_test.py <ide> def test_for_token_classification(self): <ide> @pytest.mark.slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/pytorch_transformers_test/" <del> for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> for model_name in ['bert-base-uncased']: <ide> model = TFBertModel.from_pretrained(model_name, cache_dir=cache_dir) <ide> shutil.rmtree(cache_dir) <ide> self.assertIsNotNone(model)
2
Python
Python
fix incorrect assertion syntax in example
90c90b69cf35c0457ae52e97e363b82562fe1920
<ide><path>examples/deep_dream.py <ide> def deprocess_image(x): <ide> loss = K.variable(0.) <ide> for layer_name in settings['features']: <ide> # Add the L2 norm of the features of a layer to the loss. <del> assert (layer_name in layer_dict.keys(), <del> 'Layer ' + layer_name + ' not found in model.') <add> if layer_name not in layer_dict: <add> raise ValueError('Layer ' + layer_name + ' not found in model.') <ide> coeff = settings['features'][layer_name] <ide> x = layer_dict[layer_name].output <ide> # We avoid border artifacts by only involving non-border pixels in the loss.
1
PHP
PHP
fix cs errors
c997f20e07d9cb7b5be9c3e5067b5da059d227f2
<ide><path>src/Core/functions.php <ide> * Define DS as short form of DIRECTORY_SEPARATOR. <ide> */ <ide> define('DS', DIRECTORY_SEPARATOR); <del> <ide> } <ide> <ide> if (!function_exists('h')) { <ide><path>src/Network/Http/Auth/Oauth.php <ide> public function authentication(Request $request, array $credentials) <ide> <ide> default: <ide> throw new Exception(sprintf('Unknown Oauth signature method %s', $credentials['method'])); <del> <ide> } <ide> $request->header('Authorization', $value); <ide> } <ide><path>src/Utility/Hash.php <ide> public static function extract($data, $path) <ide> $next = $filter; <ide> } <ide> $context = [$_key => $next]; <del> <ide> } <ide> return $context[$_key]; <ide> } <ide> protected static function _matches($data, $selector) <ide> ) { <ide> return false; <ide> } <del> <ide> } <ide> return true; <ide> } <ide><path>src/Validation/Validation.php <ide> public static function decimal($check, $places = null, $regex = null) <ide> <ide> if ($places === null) { <ide> $regex = "/^{$sign}(?:{$lnum}|{$dnum}){$exp}$/"; <del> <ide> } elseif ($places === true) { <ide> if (is_float($check) && floor($check) === $check) { <ide> $check = sprintf("%.1f", $check); <ide> } <ide> $regex = "/^{$sign}{$dnum}{$exp}$/"; <del> <ide> } elseif (is_numeric($places)) { <ide> $places = '[0-9]{' . $places . '}'; <ide> $dnum = "(?:[0-9]*[\.]{$places}|{$lnum}[\.]{$places})"; <ide><path>tests/TestCase/Filesystem/FileTest.php <ide> public function testWrite() <ide> $this->assertEquals($data, file_get_contents($tmpFile)); <ide> $this->assertTrue(is_resource($TmpFile->handle)); <ide> $TmpFile->close(); <del> <ide> } <ide> unlink($tmpFile); <ide> }
5
Javascript
Javascript
shorten deprecation warning
3d61e14704bb82ffc1442e6f6c3756f4432b03b4
<ide><path>lib/buffer.js <ide> function alignPool() { <ide> } <ide> <ide> var bufferWarn = true; <del>const bufferWarning = 'The Buffer() and new Buffer() constructors are not ' + <del> 'recommended for use due to security and usability ' + <del> 'concerns. Please use the Buffer.alloc(), ' + <del> 'Buffer.allocUnsafe(), or Buffer.from() construction ' + <del> 'methods instead.'; <add>const bufferWarning = 'Buffer() is deprecated due to security and usability ' + <add> 'issues. Please use the Buffer.alloc(), ' + <add> 'Buffer.allocUnsafe(), or Buffer.from() methods instead.'; <ide> <ide> function showFlaggedDeprecation() { <ide> if (bufferWarn) { <ide><path>test/parallel/test-buffer-pending-deprecation.js <ide> <ide> const common = require('../common'); <ide> <del>const bufferWarning = 'The Buffer() and new Buffer() constructors are not ' + <del> 'recommended for use due to security and usability ' + <del> 'concerns. Please use the Buffer.alloc(), ' + <del> 'Buffer.allocUnsafe(), or Buffer.from() construction ' + <del> 'methods instead.'; <add>const bufferWarning = 'Buffer() is deprecated due to security and usability ' + <add> 'issues. Please use the Buffer.alloc(), ' + <add> 'Buffer.allocUnsafe(), or Buffer.from() methods instead.'; <ide> <ide> common.expectWarning('DeprecationWarning', bufferWarning, 'DEP0005'); <ide>
2
Javascript
Javascript
improve text perf
4ce03582a0013e60417dedbf2f760d00e687e540
<ide><path>Libraries/Text/Text.js <ide> */ <ide> 'use strict'; <ide> <del>var NativeMethodsMixin = require('NativeMethodsMixin'); <del>var Platform = require('Platform'); <del>var React = require('React'); <del>var ReactInstanceMap = require('ReactInstanceMap'); <del>var ReactNativeViewAttributes = require('ReactNativeViewAttributes'); <del>var StyleSheetPropType = require('StyleSheetPropType'); <del>var TextStylePropTypes = require('TextStylePropTypes'); <del>var Touchable = require('Touchable'); <del> <del>var createReactNativeComponentClass = <add>const NativeMethodsMixin = require('NativeMethodsMixin'); <add>const Platform = require('Platform'); <add>const React = require('React'); <add>const ReactInstanceMap = require('ReactInstanceMap'); <add>const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); <add>const StyleSheetPropType = require('StyleSheetPropType'); <add>const TextStylePropTypes = require('TextStylePropTypes'); <add>const Touchable = require('Touchable'); <add> <add>const createReactNativeComponentClass = <ide> require('createReactNativeComponentClass'); <del>var merge = require('merge'); <add>const merge = require('merge'); <ide> <del>var stylePropType = StyleSheetPropType(TextStylePropTypes); <add>const stylePropType = StyleSheetPropType(TextStylePropTypes); <ide> <del>var viewConfig = { <add>const viewConfig = { <ide> validAttributes: merge(ReactNativeViewAttributes.UIView, { <ide> isHighlighted: true, <ide> numberOfLines: true, <ide> var viewConfig = { <ide> * ``` <ide> */ <ide> <del>var Text = React.createClass({ <del> <del> mixins: [Touchable.Mixin, NativeMethodsMixin], <del> <add>const Text = React.createClass({ <ide> propTypes: { <ide> /** <ide> * Used to truncate the text with an elipsis after computing the text <ide> var Text = React.createClass({ <ide> */ <ide> allowFontScaling: React.PropTypes.bool, <ide> }, <del> <del> viewConfig: viewConfig, <del> <del> getInitialState: function(): Object { <del> return merge(this.touchableGetInitialState(), { <del> isHighlighted: false, <del> }); <del> }, <del> getDefaultProps: function(): Object { <add> getDefaultProps(): Object { <ide> return { <add> accessible: true, <ide> allowFontScaling: true, <ide> }; <ide> }, <del> <del> onStartShouldSetResponder: function(): bool { <del> var shouldSetFromProps = this.props.onStartShouldSetResponder && <del> this.props.onStartShouldSetResponder(); <del> return shouldSetFromProps || !!this.props.onPress; <del> }, <del> <del> /* <del> * Returns true to allow responder termination <del> */ <del> handleResponderTerminationRequest: function(): bool { <del> // Allow touchable or props.onResponderTerminationRequest to deny <del> // the request <del> var allowTermination = this.touchableHandleResponderTerminationRequest(); <del> if (allowTermination && this.props.onResponderTerminationRequest) { <del> allowTermination = this.props.onResponderTerminationRequest(); <del> } <del> return allowTermination; <del> }, <del> <del> handleResponderGrant: function(e: SyntheticEvent, dispatchID: string) { <del> this.touchableHandleResponderGrant(e, dispatchID); <del> this.props.onResponderGrant && <del> this.props.onResponderGrant.apply(this, arguments); <del> }, <del> <del> handleResponderMove: function(e: SyntheticEvent) { <del> this.touchableHandleResponderMove(e); <del> this.props.onResponderMove && <del> this.props.onResponderMove.apply(this, arguments); <del> }, <del> <del> handleResponderRelease: function(e: SyntheticEvent) { <del> this.touchableHandleResponderRelease(e); <del> this.props.onResponderRelease && <del> this.props.onResponderRelease.apply(this, arguments); <del> }, <del> <del> handleResponderTerminate: function(e: SyntheticEvent) { <del> this.touchableHandleResponderTerminate(e); <del> this.props.onResponderTerminate && <del> this.props.onResponderTerminate.apply(this, arguments); <del> }, <del> <del> touchableHandleActivePressIn: function() { <del> if (this.props.suppressHighlighting || !this.props.onPress) { <del> return; <del> } <del> this.setState({ <del> isHighlighted: true, <del> }); <del> }, <del> <del> touchableHandleActivePressOut: function() { <del> if (this.props.suppressHighlighting || !this.props.onPress) { <del> return; <del> } <del> this.setState({ <add> getInitialState: function(): Object { <add> return merge(Touchable.Mixin.touchableGetInitialState(), { <ide> isHighlighted: false, <ide> }); <ide> }, <del> <del> touchableHandlePress: function() { <del> this.props.onPress && this.props.onPress(); <del> }, <del> <del> touchableGetPressRectOffset: function(): RectOffset { <del> return PRESS_RECT_OFFSET; <del> }, <del> <del> getChildContext: function(): Object { <add> mixins: [NativeMethodsMixin], <add> viewConfig: viewConfig, <add> getChildContext(): Object { <ide> return {isInAParentText: true}; <ide> }, <del> <ide> childContextTypes: { <ide> isInAParentText: React.PropTypes.bool <ide> }, <del> <del> render: function() { <del> var props = {}; <del> for (var key in this.props) { <del> props[key] = this.props[key]; <del> } <del> // Text is accessible by default <del> if (props.accessible !== false) { <del> props.accessible = true; <add> contextTypes: { <add> isInAParentText: React.PropTypes.bool <add> }, <add> /** <add> * Only assigned if touch is needed. <add> */ <add> _handlers: (null: ?Object), <add> /** <add> * These are assigned lazily the first time the responder is set to make plain <add> * text nodes as cheap as possible. <add> */ <add> touchableHandleActivePressIn: (null: ?Function), <add> touchableHandleActivePressOut: (null: ?Function), <add> touchableHandlePress: (null: ?Function), <add> touchableGetPressRectOffset: (null: ?Function), <add> render(): ReactElement { <add> let newProps = this.props; <add> if (this.props.onStartShouldSetResponder || this.props.onPress) { <add> if (!this._handlers) { <add> this._handlers = { <add> onStartShouldSetResponder: (): bool => { <add> const shouldSetFromProps = this.props.onStartShouldSetResponder && <add> this.props.onStartShouldSetResponder(); <add> const setResponder = shouldSetFromProps || !!this.props.onPress; <add> if (setResponder && !this.touchableHandleActivePressIn) { <add> // Attach and bind all the other handlers only the first time a touch <add> // actually happens. <add> for (let key in Touchable.Mixin) { <add> if (typeof Touchable.Mixin[key] === 'function') { <add> (this: any)[key] = Touchable.Mixin[key].bind(this); <add> } <add> } <add> this.touchableHandleActivePressIn = () => { <add> if (this.props.suppressHighlighting || !this.props.onPress) { <add> return; <add> } <add> this.setState({ <add> isHighlighted: true, <add> }); <add> }; <add> <add> this.touchableHandleActivePressOut = () => { <add> if (this.props.suppressHighlighting || !this.props.onPress) { <add> return; <add> } <add> this.setState({ <add> isHighlighted: false, <add> }); <add> }; <add> <add> this.touchableHandlePress = () => { <add> this.props.onPress && this.props.onPress(); <add> }; <add> <add> this.touchableGetPressRectOffset = function(): RectOffset { <add> return PRESS_RECT_OFFSET; <add> }; <add> } <add> return setResponder; <add> }, <add> onResponderGrant: (e: SyntheticEvent, dispatchID: string) => { <add> this.touchableHandleResponderGrant(e, dispatchID); <add> this.props.onResponderGrant && <add> this.props.onResponderGrant.apply(this, arguments); <add> }, <add> onResponderMove: (e: SyntheticEvent) => { <add> this.touchableHandleResponderMove(e); <add> this.props.onResponderMove && <add> this.props.onResponderMove.apply(this, arguments); <add> }, <add> onResponderRelease: (e: SyntheticEvent) => { <add> this.touchableHandleResponderRelease(e); <add> this.props.onResponderRelease && <add> this.props.onResponderRelease.apply(this, arguments); <add> }, <add> onResponderTerminate: (e: SyntheticEvent) => { <add> this.touchableHandleResponderTerminate(e); <add> this.props.onResponderTerminate && <add> this.props.onResponderTerminate.apply(this, arguments); <add> }, <add> onResponderTerminationRequest: (): bool => { <add> // Allow touchable or props.onResponderTerminationRequest to deny <add> // the request <add> var allowTermination = this.touchableHandleResponderTerminationRequest(); <add> if (allowTermination && this.props.onResponderTerminationRequest) { <add> allowTermination = this.props.onResponderTerminationRequest(); <add> } <add> return allowTermination; <add> }, <add> }; <add> } <add> newProps = { <add> ...this.props, <add> ...this._handlers, <add> isHighlighted: this.state.isHighlighted, <add> }; <ide> } <del> props.isHighlighted = this.state.isHighlighted; <del> props.onStartShouldSetResponder = this.onStartShouldSetResponder; <del> props.onResponderTerminationRequest = <del> this.handleResponderTerminationRequest; <del> props.onResponderGrant = this.handleResponderGrant; <del> props.onResponderMove = this.handleResponderMove; <del> props.onResponderRelease = this.handleResponderRelease; <del> props.onResponderTerminate = this.handleResponderTerminate; <del> <del> // TODO: Switch to use contextTypes and this.context after React upgrade <del> var context = ReactInstanceMap.get(this)._context; <del> if (context.isInAParentText) { <del> return <RCTVirtualText {...props} />; <add> if (this.context.isInAParentText) { <add> return <RCTVirtualText {...newProps} />; <ide> } else { <del> return <RCTText {...props} />; <add> return <RCTText {...newProps} />; <ide> } <ide> }, <ide> });
1
Javascript
Javascript
remove unnecessary import of `metafor`
36371e07fa7bff743e9ed15b1ee420845ed6be90
<ide><path>packages/ember-glimmer/lib/utils/references.js <ide> import { <ide> set, <ide> tagFor, <ide> didRender, <del> meta as metaFor, <ide> watchKey, <ide> isFeatureEnabled, <ide> runInDebug <ide> export class RootPropertyReference extends PropertyReference { <ide> } <ide> <ide> if (isFeatureEnabled('mandatory-setter')) { <del> watchKey(parentValue, propertyKey, metaFor(parentValue)); <add> watchKey(parentValue, propertyKey); <ide> } <ide> } <ide> <ide> export class NestedPropertyReference extends PropertyReference { <ide> <ide> if (typeof parentValue === 'object' && parentValue) { <ide> if (isFeatureEnabled('mandatory-setter')) { <del> let meta = metaFor(parentValue); <del> watchKey(parentValue, _propertyKey, meta); <add> watchKey(parentValue, _propertyKey); <ide> } <ide> <ide> if (isFeatureEnabled('ember-glimmer-detect-backtracking-rerender') ||
1
Python
Python
apply reviewer comments
5db1d5fb64ff35429205aec4b6927a4b2c6b552b
<ide><path>numpy/f2py/rules.py <ide> def buildmodule(m, um): <ide> 'C It contains Fortran 77 wrappers to fortran functions.\n') <ide> lines = [] <ide> for l in ('\n\n'.join(funcwrappers) + '\n').split('\n'): <del> i = l.find('!') <del> if i >= 0 and i < 66: <add> if 0 <= l.find('!') < 66: <ide> # don't split comment lines <ide> lines.append(l + '\n') <ide> elif l and l[0] == ' ': <ide> def buildmodule(m, um): <ide> '! It contains Fortran 90 wrappers to fortran functions.\n') <ide> lines = [] <ide> for l in ('\n\n'.join(funcwrappers2) + '\n').split('\n'): <del> i = l.find('!') <del> if i >= 0 and i < 72: <add> if 0 <= l.find('!') < 72: <ide> # don't split comment lines <ide> lines.append(l + '\n') <ide> elif len(l) > 72 and l[0] == ' ': <ide><path>numpy/f2py/tests/test_callback.py <ide> class TestF90Callback(util.F2PyTest): <ide> <ide> suffix = '.f90' <ide> <del> code = """ <add> code = textwrap.dedent(""" <ide> function gh17797(f, y) result(r) <ide> external f <ide> integer(8) :: r, f <ide> integer(8), dimension(:) :: y <ide> r = f(0) <ide> r = r + sum(y) <ide> end function gh17797 <del> """ <add> """) <ide> <ide> def test_gh17797(self): <ide>
2
Javascript
Javascript
fix invariant parity for ssr
1454f9c10c4f487bd87227aad0162d0c888b20e3
<ide><path>src/renderers/dom/ReactDOMNodeStreamRenderer.js <ide> function renderToStream(element) { <ide> if (disableNewFiberFeatures) { <ide> invariant( <ide> React.isValidElement(element), <del> 'renderToStream(): You must pass a valid ReactElement.', <add> 'renderToStream(): Invalid component element.', <ide> ); <ide> } <ide> return new ReactMarkupReadableStream(element, false); <ide> function renderToStaticStream(element) { <ide> if (disableNewFiberFeatures) { <ide> invariant( <ide> React.isValidElement(element), <del> 'renderToStaticStream(): You must pass a valid ReactElement.', <add> 'renderToStaticStream(): Invalid component element.', <ide> ); <ide> } <ide> return new ReactMarkupReadableStream(element, true); <ide><path>src/renderers/dom/ReactDOMStringRenderer.js <ide> function renderToString(element) { <ide> if (disableNewFiberFeatures) { <ide> invariant( <ide> React.isValidElement(element), <del> 'renderToString(): You must pass a valid ReactElement.', <add> 'renderToString(): Invalid component element.', <ide> ); <ide> } <ide> var renderer = new ReactPartialRenderer(element, false); <ide> function renderToStaticMarkup(element) { <ide> if (disableNewFiberFeatures) { <ide> invariant( <ide> React.isValidElement(element), <del> 'renderToStaticMarkup(): You must pass a valid ReactElement.', <add> 'renderToStaticMarkup(): Invalid component element.', <ide> ); <ide> } <ide> var renderer = new ReactPartialRenderer(element, true); <ide><path>src/renderers/dom/shared/__tests__/ReactDOMServerIntegration-test.js <ide> let ReactTestUtils; <ide> <ide> const stream = require('stream'); <ide> <add>const TEXT_NODE_TYPE = 3; <add>const COMMENT_NODE_TYPE = 8; <add> <ide> // Helper functions for rendering tests <ide> // ==================================== <ide> <ide> const clientCleanRender = (element, errorCount = 0) => { <ide> const clientRenderOnServerString = async (element, errorCount = 0) => { <ide> const markup = await renderIntoString(element, errorCount); <ide> resetModules(); <add> <ide> var domElement = document.createElement('div'); <ide> domElement.innerHTML = markup; <del> const serverElement = domElement.firstChild; <del> const clientElement = await renderIntoDom(element, domElement, errorCount); <del> // assert that the DOM element hasn't been replaced. <del> // Note that we cannot use expect(serverElement).toBe(clientElement) because <del> // of jest bug #1772 <del> expect(serverElement === clientElement).toBe(true); <del> return clientElement; <add> let serverNode = domElement.firstChild; <add> <add> const firstClientNode = await renderIntoDom(element, domElement, errorCount); <add> let clientNode = firstClientNode; <add> <add> // Make sure all top level nodes match up <add> while (serverNode || clientNode) { <add> expect(serverNode != null).toBe(true); <add> expect(clientNode != null).toBe(true); <add> expect(clientNode.nodeType).toBe(serverNode.nodeType); <add> if (clientNode.nodeType === TEXT_NODE_TYPE) { <add> // Text nodes are stateless so we can just compare values. <add> // This works around a current issue where hydration replaces top-level <add> // text node, but otherwise works. <add> // TODO: we can remove this branch if we add explicit hydration opt-in. <add> // https://github.com/facebook/react/issues/10189 <add> expect(serverNode.nodeValue).toBe(clientNode.nodeValue); <add> } else { <add> // Assert that the DOM element hasn't been replaced. <add> // Note that we cannot use expect(serverNode).toBe(clientNode) because <add> // of jest bug #1772. <add> expect(serverNode === clientNode).toBe(true); <add> } <add> serverNode = serverNode.nextSibling; <add> clientNode = clientNode.nextSibling; <add> } <add> return firstClientNode; <ide> }; <ide> <ide> function BadMarkupExpected() {} <ide> function itClientRenders(desc, testFn) { <ide> }); <ide> } <ide> <del>function itThrows(desc, testFn) { <add>function itThrows(desc, testFn, partialMessage) { <ide> it(`throws ${desc}`, () => { <ide> return testFn().then( <ide> () => expect(false).toBe('The promise resolved and should not have.'), <del> () => {}, <add> err => { <add> expect(err).toBeInstanceOf(Error); <add> expect(err.message).toContain(partialMessage); <add> }, <ide> ); <ide> }); <ide> } <ide> <del>function itThrowsWhenRendering(desc, testFn) { <del> itThrows(`when rendering ${desc} with server string render`, () => <del> testFn(serverRender), <add>function itThrowsWhenRendering(desc, testFn, partialMessage) { <add> itThrows( <add> `when rendering ${desc} with server string render`, <add> () => testFn(serverRender), <add> partialMessage, <ide> ); <del> itThrows(`when rendering ${desc} with clean client render`, () => <del> testFn(clientCleanRender), <add> itThrows( <add> `when rendering ${desc} with clean client render`, <add> () => testFn(clientCleanRender), <add> partialMessage, <ide> ); <ide> <ide> // we subtract one from the warning count here because the throw means that it won't <ide> function itThrowsWhenRendering(desc, testFn) { <ide> testFn((element, warningCount = 0) => <ide> clientRenderOnBadMarkup(element, warningCount - 1), <ide> ), <add> partialMessage, <ide> ); <ide> } <ide> <ide> function resetModules() { <ide> // TODO: can we express this test with only public API? <ide> ExecutionEnvironment = require('ExecutionEnvironment'); <ide> <add> require('ReactFeatureFlags').disableNewFiberFeatures = false; <ide> PropTypes = require('prop-types'); <ide> React = require('react'); <ide> ReactDOM = require('react-dom'); <ide> function resetModules() { <ide> if (typeof onAfterResetModules === 'function') { <ide> onAfterResetModules(); <ide> } <del> <add> require('ReactFeatureFlags').disableNewFiberFeatures = false; <ide> ReactDOMServer = require('react-dom/server'); <ide> <ide> // Finally, reset modules one more time before importing the stream renderer. <ide> jest.resetModuleRegistry(); <ide> if (typeof onAfterResetModules === 'function') { <ide> onAfterResetModules(); <ide> } <del> <add> require('ReactFeatureFlags').disableNewFiberFeatures = false; <ide> ReactDOMNodeStream = require('react-dom/node-stream'); <ide> } <ide> <ide> describe('ReactDOMServerIntegration', () => { <ide> }); <ide> <ide> describe('basic rendering', function() { <del> beforeEach(() => { <del> onAfterResetModules = () => { <del> const ReactFeatureFlags = require('ReactFeatureFlags'); <del> ReactFeatureFlags.disableNewFiberFeatures = false; <del> }; <del> <del> resetModules(); <del> }); <del> <del> afterEach(() => { <del> onAfterResetModules = null; <del> }); <del> <ide> itRenders('a blank div', async render => { <ide> const e = await render(<div />); <ide> expect(e.tagName).toBe('DIV'); <ide> describe('ReactDOMServerIntegration', () => { <ide> }); <ide> <ide> if (ReactDOMFeatureFlags.useFiber) { <del> itRenders('a array type children as a child', async render => { <add> itRenders('a string', async render => { <add> let e = await render('Hello'); <add> expect(e.nodeType).toBe(3); <add> expect(e.nodeValue).toMatch('Hello'); <add> }); <add> <add> itRenders('a number', async render => { <add> let e = await render(42); <add> expect(e.nodeType).toBe(3); <add> expect(e.nodeValue).toMatch('42'); <add> }); <add> <add> itRenders('an array with one child', async render => { <add> let e = await render([<div key={1}>text1</div>]); <add> let parent = e.parentNode; <add> expect(parent.childNodes[0].tagName).toBe('DIV'); <add> }); <add> <add> itRenders('an array with several children', async render => { <ide> let Header = props => { <ide> return <p>header</p>; <ide> }; <ide> describe('ReactDOMServerIntegration', () => { <ide> expect(parent.childNodes[4].tagName).toBe('H3'); <ide> }); <ide> <del> itRenders('a single array element children as a child', async render => { <del> let e = await render([<div key={1}>text1</div>]); <del> let parent = e.parentNode; <del> expect(parent.childNodes[0].tagName).toBe('DIV'); <del> }); <del> <del> itRenders('a nested array children as a child', async render => { <add> itRenders('a nested array', async render => { <ide> let e = await render([ <ide> [<div key={1}>text1</div>], <ide> <span key={1}>text2</span>, <ide> describe('ReactDOMServerIntegration', () => { <ide> expect(parent.childNodes[2].tagName).toBe('P'); <ide> }); <ide> <del> itRenders('an iterable as a child', async render => { <add> itRenders('an iterable', async render => { <ide> const threeDivIterable = { <ide> '@@iterator': function() { <ide> var i = 0; <ide> describe('ReactDOMServerIntegration', () => { <ide> }); <ide> <ide> describe('elements and children', function() { <del> // helper functions. <del> const TEXT_NODE_TYPE = 3; <del> const COMMENT_NODE_TYPE = 8; <del> <ide> function expectNode(node, type, value) { <ide> expect(node).not.toBe(null); <ide> expect(node.nodeType).toBe(type); <ide> describe('ReactDOMServerIntegration', () => { <ide> }); <ide> <ide> describe('components that throw errors', function() { <del> itThrowsWhenRendering('a string component', async render => { <del> const StringComponent = () => 'foo'; <del> await render(<StringComponent />, 1); <del> }); <add> itThrowsWhenRendering( <add> 'a function returning undefined', <add> async render => { <add> const UndefinedComponent = () => undefined; <add> await render(<UndefinedComponent />, 1); <add> }, <add> ReactDOMFeatureFlags.useFiber <add> ? 'UndefinedComponent(...): Nothing was returned from render. ' + <add> 'This usually means a return statement is missing. Or, to ' + <add> 'render nothing, return null.' <add> : 'A valid React element (or null) must be returned. ' + <add> 'You may have returned undefined, an array or some other invalid object.', <add> ); <ide> <del> itThrowsWhenRendering('an undefined component', async render => { <del> const UndefinedComponent = () => undefined; <del> await render(<UndefinedComponent />, 1); <del> }); <add> itThrowsWhenRendering( <add> 'a class returning undefined', <add> async render => { <add> class UndefinedComponent extends React.Component { <add> render() { <add> return undefined; <add> } <add> } <add> await render(<UndefinedComponent />, 1); <add> }, <add> ReactDOMFeatureFlags.useFiber <add> ? 'UndefinedComponent(...): Nothing was returned from render. ' + <add> 'This usually means a return statement is missing. Or, to ' + <add> 'render nothing, return null.' <add> : 'A valid React element (or null) must be returned. ' + <add> 'You may have returned undefined, an array or some other invalid object.', <add> ); <ide> <del> itThrowsWhenRendering('a number component', async render => { <del> const NumberComponent = () => 54; <del> await render(<NumberComponent />, 1); <del> }); <add> itThrowsWhenRendering( <add> 'a function returning an object', <add> async render => { <add> const ObjectComponent = () => ({x: 123}); <add> await render(<ObjectComponent />, 1); <add> }, <add> ReactDOMFeatureFlags.useFiber <add> ? 'Objects are not valid as a React child (found: object with keys ' + <add> '{x}). If you meant to render a collection of children, use ' + <add> 'an array instead.' <add> : 'A valid React element (or null) must be returned. ' + <add> 'You may have returned undefined, an array or some other invalid object.', <add> ); <ide> <del> itThrowsWhenRendering('null', render => render(null)); <del> itThrowsWhenRendering('false', render => render(false)); <del> itThrowsWhenRendering('undefined', render => render(undefined)); <del> itThrowsWhenRendering('number', render => render(30)); <del> itThrowsWhenRendering('string', render => render('foo')); <add> itThrowsWhenRendering( <add> 'a class returning an object', <add> async render => { <add> class ObjectComponent extends React.Component { <add> render() { <add> return {x: 123}; <add> } <add> } <add> await render(<ObjectComponent />, 1); <add> }, <add> ReactDOMFeatureFlags.useFiber <add> ? 'Objects are not valid as a React child (found: object with keys ' + <add> '{x}). If you meant to render a collection of children, use ' + <add> 'an array instead.' <add> : 'A valid React element (or null) must be returned. ' + <add> 'You may have returned undefined, an array or some other invalid object.', <add> ); <add> <add> itThrowsWhenRendering( <add> 'top-level object', <add> async render => { <add> await render({x: 123}); <add> }, <add> ReactDOMFeatureFlags.useFiber <add> ? 'Objects are not valid as a React child (found: object with keys ' + <add> '{x}). If you meant to render a collection of children, use ' + <add> 'an array instead.' <add> : 'Invalid component element.', <add> ); <ide> }); <ide> }); <ide> <ide> describe('ReactDOMServerIntegration', () => { <ide> itThrowsWhenRendering( <ide> 'if getChildContext exists without childContextTypes', <ide> render => { <del> class Component extends React.Component { <add> class MyComponent extends React.Component { <ide> render() { <ide> return <div />; <ide> } <ide> getChildContext() { <ide> return {foo: 'bar'}; <ide> } <ide> } <del> return render(<Component />); <add> return render(<MyComponent />); <ide> }, <add> 'MyComponent.getChildContext(): childContextTypes must be defined ' + <add> 'in order to use getChildContext().', <ide> ); <ide> <ide> itThrowsWhenRendering( <ide> 'if getChildContext returns a value not in childContextTypes', <ide> render => { <del> class Component extends React.Component { <add> class MyComponent extends React.Component { <ide> render() { <ide> return <div />; <ide> } <ide> getChildContext() { <ide> return {value1: 'foo', value2: 'bar'}; <ide> } <ide> } <del> Component.childContextTypes = {value1: PropTypes.string}; <del> return render(<Component />); <add> MyComponent.childContextTypes = {value1: PropTypes.string}; <add> return render(<MyComponent />); <ide> }, <add> 'MyComponent.getChildContext(): key "value2" is not defined in childContextTypes.', <ide> ); <ide> }); <ide> <ide><path>src/renderers/dom/shared/__tests__/ReactServerRendering-test.js <ide> describe('ReactDOMServer', () => { <ide> ).toThrowError( <ide> ReactDOMFeatureFlags.useFiber <ide> ? 'Objects are not valid as a React child (found: object with keys {x})' <del> : 'renderToString(): You must pass a valid ReactElement.', <add> : 'renderToString(): Invalid component element.', <ide> ); <ide> }); <ide> }); <ide> describe('ReactDOMServer', () => { <ide> ).toThrowError( <ide> ReactDOMFeatureFlags.useFiber <ide> ? 'Objects are not valid as a React child (found: object with keys {x})' <del> : 'renderToStaticMarkup(): You must pass a valid ReactElement.', <add> : 'renderToStaticMarkup(): Invalid component element.', <ide> ); <ide> }); <ide> <ide><path>src/renderers/dom/stack/server/ReactServerRendering.js <ide> function renderToStringImpl(element, makeStaticMarkup) { <ide> function renderToString(element) { <ide> invariant( <ide> React.isValidElement(element), <del> 'renderToString(): You must pass a valid ReactElement.', <add> 'renderToString(): Invalid component element.', <ide> ); <ide> return renderToStringImpl(element, false); <ide> } <ide> function renderToString(element) { <ide> function renderToStaticMarkup(element) { <ide> invariant( <ide> React.isValidElement(element), <del> 'renderToStaticMarkup(): You must pass a valid ReactElement.', <add> 'renderToStaticMarkup(): Invalid component element.', <ide> ); <ide> return renderToStringImpl(element, true); <ide> } <ide><path>src/renderers/shared/server/ReactPartialRenderer.js <ide> function createOpenTagMarkup( <ide> return ret; <ide> } <ide> <add>function validateRenderResult(child, type) { <add> if (child === undefined) { <add> invariant( <add> false, <add> '%s(...): Nothing was returned from render. This usually means a ' + <add> 'return statement is missing. Or, to render nothing, ' + <add> 'return null.', <add> getComponentName(type) || 'Component', <add> ); <add> } <add>} <add> <ide> function resolve(child, context) { <ide> while (React.isValidElement(child)) { <ide> if (__DEV__) { <ide> function resolve(child, context) { <ide> inst = Component(child.props, publicContext, updater); <ide> if (inst == null || inst.render == null) { <ide> child = inst; <add> validateRenderResult(child, Component); <ide> continue; <ide> } <ide> } <ide> function resolve(child, context) { <ide> child = null; <ide> } <ide> } <add> validateRenderResult(child, Component); <ide> <ide> var childContext; <ide> if (typeof inst.getChildContext === 'function') {
6
Java
Java
preserve etag http header for versioned resources
473cf9c40e266a416930249569550d19e92c2494
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void handleRequest(HttpServletRequest request, HttpServletResponse respon <ide> } <ide> <ide> if (request.getHeader(HttpHeaders.RANGE) == null) { <del> setETagHeader(request, response); <ide> setHeaders(response, resource, mediaType); <ide> writeContent(response, resource); <ide> } <ide> protected MediaType getMediaType(Resource resource) { <ide> return mediaType; <ide> } <ide> <del> /** <del> * Set the ETag header if the version string of the served resource is present. <del> * Version strings can be resolved by {@link VersionStrategy} implementations and then <del> * set as a request attribute by {@link VersionResourceResolver}. <del> * @param request current servlet request <del> * @param response current servlet response <del> * @see VersionResourceResolver <del> */ <del> protected void setETagHeader(HttpServletRequest request, HttpServletResponse response) { <del> String versionString = (String) request.getAttribute(VersionResourceResolver.RESOURCE_VERSION_ATTRIBUTE); <del> if (versionString != null) { <del> response.setHeader(HttpHeaders.ETAG, "\"" + versionString + "\""); <del> } <del> } <del> <ide> /** <ide> * Set headers on the given servlet response. <ide> * Called for GET requests as well as HEAD requests. <ide> protected void setHeaders(HttpServletResponse response, Resource resource, Media <ide> throw new IOException("Resource content too long (beyond Integer.MAX_VALUE): " + resource); <ide> } <ide> response.setContentLength((int) length); <del> <ide> if (mediaType != null) { <ide> response.setContentType(mediaType.toString()); <ide> } <del> <ide> if (resource instanceof EncodedResource) { <ide> response.setHeader(HttpHeaders.CONTENT_ENCODING, ((EncodedResource) resource).getContentEncoding()); <ide> } <del> <add> if (resource instanceof VersionedResource) { <add> response.setHeader(HttpHeaders.ETAG, "\"" + ((VersionedResource) resource).getVersion() + "\""); <add> } <ide> response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes"); <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/VersionResourceResolver.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.web.servlet.resource; <ide> <add>import java.io.File; <add>import java.io.IOException; <add>import java.io.InputStream; <add>import java.net.URI; <add>import java.net.URL; <ide> import java.util.ArrayList; <ide> import java.util.Collections; <ide> import java.util.Comparator; <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.servlet.http.HttpServletRequest; <ide> <add>import org.springframework.core.io.AbstractResource; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.util.AntPathMatcher; <ide> import org.springframework.util.StringUtils; <ide> */ <ide> public class VersionResourceResolver extends AbstractResourceResolver { <ide> <del> public static final String RESOURCE_VERSION_ATTRIBUTE = <del> VersionResourceResolver.class.getName() + ".resourceVersion"; <del> <del> <ide> private AntPathMatcher pathMatcher = new AntPathMatcher(); <ide> <ide> /** Map from path pattern -> VersionStrategy */ <ide> protected Resource resolveResourceInternal(HttpServletRequest request, String re <ide> String actualVersion = versionStrategy.getResourceVersion(baseResource); <ide> if (candidateVersion.equals(actualVersion)) { <ide> if (logger.isTraceEnabled()) { <del> logger.trace("Resource matches extracted version ["+ candidateVersion + "]"); <add> logger.trace("Resource matches extracted version [" + candidateVersion + "]"); <ide> } <del> if (request != null) { <del> request.setAttribute(RESOURCE_VERSION_ATTRIBUTE, candidateVersion); <del> } <del> return baseResource; <add> return new FileNameVersionedResource(baseResource, candidateVersion); <ide> } <ide> else { <ide> if (logger.isTraceEnabled()) { <ide> protected VersionStrategy getStrategyForPath(String requestPath) { <ide> return null; <ide> } <ide> <add> private class FileNameVersionedResource extends AbstractResource implements VersionedResource { <add> <add> private final Resource original; <add> <add> private final String version; <add> <add> public FileNameVersionedResource(Resource original, String version) { <add> this.original = original; <add> this.version = version; <add> } <add> <add> @Override <add> public boolean exists() { <add> return this.original.exists(); <add> } <add> <add> @Override <add> public boolean isReadable() { <add> return this.original.isReadable(); <add> } <add> <add> @Override <add> public boolean isOpen() { <add> return this.original.isOpen(); <add> } <add> <add> @Override <add> public URL getURL() throws IOException { <add> return this.original.getURL(); <add> } <add> <add> @Override <add> public URI getURI() throws IOException { <add> return this.original.getURI(); <add> } <add> <add> @Override <add> public File getFile() throws IOException { <add> return this.original.getFile(); <add> } <add> <add> @Override <add> public String getFilename() { <add> return this.original.getFilename(); <add> } <add> <add> @Override <add> public long contentLength() throws IOException { <add> return this.original.contentLength(); <add> } <add> <add> @Override <add> public long lastModified() throws IOException { <add> return this.original.lastModified(); <add> } <add> <add> @Override <add> public Resource createRelative(String relativePath) throws IOException { <add> return this.original.createRelative(relativePath); <add> } <add> <add> @Override <add> public String getDescription() { <add> return original.getDescription(); <add> } <add> <add> @Override <add> public InputStream getInputStream() throws IOException { <add> return original.getInputStream(); <add> } <add> <add> @Override <add> public String getVersion() { <add> return this.version; <add> } <add> <add> } <add> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/VersionedResource.java <add>/* <add> * Copyright 2002-2016 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.web.servlet.resource; <add> <add>import org.springframework.core.io.Resource; <add> <add>/** <add> * Interface for a resource descriptor that describes its version <add> * with a version string that can be derived from its content and/or metadata. <add> * <add> * @author Brian Clozel <add> * @since 4.2 <add> * @see VersionResourceResolver <add> */ <add>public interface VersionedResource extends Resource { <add> <add> String getVersion(); <add>} <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void setUp() throws Exception { <ide> @Test <ide> public void getResource() throws Exception { <ide> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); <del> this.request.setAttribute(VersionResourceResolver.RESOURCE_VERSION_ATTRIBUTE, "versionString"); <ide> this.handler.handleRequest(this.request, this.response); <ide> <ide> assertEquals("text/css", this.response.getContentType()); <ide> assertEquals(17, this.response.getContentLength()); <ide> assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); <ide> assertTrue(this.response.containsHeader("Last-Modified")); <ide> assertEquals(this.response.getHeader("Last-Modified"), resourceLastModifiedDate("test/foo.css")); <del> assertEquals("\"versionString\"", this.response.getHeader("ETag")); <ide> assertEquals("h1 { color:red; }", this.response.getContentAsString()); <ide> } <ide> <ide> public void getResourceNoCache() throws Exception { <ide> assertEquals(this.response.getHeader("Last-Modified"), resourceLastModifiedDate("test/foo.css")); <ide> } <ide> <add> @Test <add> public void getVersionedResource() throws Exception { <add> VersionResourceResolver versionResolver = new VersionResourceResolver() <add> .addFixedVersionStrategy("versionString", "/**"); <add> this.handler.setResourceResolvers(Arrays.asList(versionResolver, new PathResourceResolver())); <add> this.handler.afterPropertiesSet(); <add> <add> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "versionString/foo.css"); <add> this.handler.handleRequest(this.request, this.response); <add> <add> assertEquals("\"versionString\"", this.response.getHeader("ETag")); <add> } <add> <ide> @Test <ide> @SuppressWarnings("deprecation") <ide> public void getResourceHttp10BehaviorCache() throws Exception { <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> <add>import static org.hamcrest.Matchers.instanceOf; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide> <ide> public void resolveResourceSuccess() throws Exception { <ide> this.resolver <ide> .setStrategyMap(Collections.singletonMap("/**", this.versionStrategy)); <ide> Resource actual = this.resolver.resolveResourceInternal(request, versionFile, this.locations, this.chain); <del> assertEquals(expected, actual); <add> assertEquals(expected.getFilename(), actual.getFilename()); <ide> verify(this.versionStrategy, times(1)).getResourceVersion(expected); <del> assertEquals(version, request.getAttribute(VersionResourceResolver.RESOURCE_VERSION_ATTRIBUTE)); <add> assertThat(actual, instanceOf(VersionedResource.class)); <add> assertEquals(version, ((VersionedResource)actual).getVersion()); <ide> } <ide> <ide> @Test
5
Python
Python
fix startswith operation on character arrays
9f036ecd5ae67db2af4d486199f2b64c73670acb
<ide><path>numpy/core/defchararray.py <ide> def _typedmethod(self, name, myiter, dtype): <ide> for k, val in enumerate(myiter): <ide> newval = [] <ide> for chk in val[1:]: <del> if chk.dtype is object_ and chk.item() is None: <add> if not chk or (chk.dtype is object_ and chk.item() is None): <ide> break <ide> newval.append(chk) <ide> this_str = val[0].rstrip('\x00')
1
Text
Text
simplify documentation. use good defaults
e6ef62d197dc6e02d2c37665e850d6db618f1016
<ide><path>src/ORM/README.md <ide> ConnectionManager::setConfig('default', [ <ide> 'database' => 'test', <ide> 'username' => 'root', <ide> 'password' => 'secret', <del> 'cacheMetadata' => false // If set to `true` you need to install the optional "cakephp/cache" package. <add> 'cacheMetadata' => true, <add> 'quoteIdentifiers' => false, <ide> ]); <ide> ``` <ide>
1
Text
Text
fix style for rescue responses doc [ci skip]
d76380cf1ccec7ffeff19827ae9b6d9b71327418
<ide><path>guides/source/configuring.md <ide> encrypted cookies salt value. Defaults to `'signed encrypted cookie'`. <ide> <ide> ```ruby <ide> config.action_dispatch.rescue_responses = { <del> 'ActionController::RoutingError' => :not_found, <del> 'AbstractController::ActionNotFound' => :not_found, <del> 'ActionController::MethodNotAllowed' => :method_not_allowed, <del> 'ActionController::UnknownHttpMethod' => :method_not_allowed, <del> 'ActionController::NotImplemented' => :not_implemented, <del> 'ActionController::UnknownFormat' => :not_acceptable, <del> 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity, <del> 'ActionDispatch::ParamsParser::ParseError' => :bad_request, <del> 'ActionController::BadRequest' => :bad_request, <del> 'ActionController::ParameterMissing' => :bad_request, <del> 'ActiveRecord::RecordNotFound' => :not_found, <del> 'ActiveRecord::StaleObjectError' => :conflict, <del> 'ActiveRecord::RecordInvalid' => :unprocessable_entity, <del> 'ActiveRecord::RecordNotSaved' => :unprocessable_entity <add> 'ActionController::RoutingError' => :not_found, <add> 'AbstractController::ActionNotFound' => :not_found, <add> 'ActionController::MethodNotAllowed' => :method_not_allowed, <add> 'ActionController::UnknownHttpMethod' => :method_not_allowed, <add> 'ActionController::NotImplemented' => :not_implemented, <add> 'ActionController::UnknownFormat' => :not_acceptable, <add> 'ActionDispatch::ParamsParser::ParseError' => :bad_request, <add> 'ActionController::BadRequest' => :bad_request, <add> 'ActionController::ParameterMissing' => :bad_request, <add> 'ActiveRecord::RecordNotFound' => :not_found, <add> 'ActiveRecord::StaleObjectError' => :conflict, <add> 'ActiveRecord::RecordInvalid' => :unprocessable_entity, <add> 'ActiveRecord::RecordNotSaved' => :unprocessable_entity, <add> 'ActionController::InvalidAuthenticityToken' <add> => :unprocessable_entity <ide> } <ide> ``` <ide> <del> Any execptions that are not configured will be assigned to 500 Internal server error. <add> Any execption that is not configured will be assigned to 500 Internal server error. <ide> <ide> * `ActionDispatch::Callbacks.before` takes a block of code to run before the request. <ide>
1
Text
Text
update showline location in defaults
e529775d5ed82c431e60fc8ef5c64b39ff0c69d8
<ide><path>docs/docs/configuration/index.md <ide> The following example would set the `showLine` option to 'false' for all line da <ide> <ide> ```javascript <ide> // Do not show lines for all datasets by default <del>Chart.defaults.datasets.line.showLine = false; <add>Chart.defaults.controllers.line.showLine = false; <ide> <ide> // This chart would show a line only for the third dataset <ide> var chart = new Chart(ctx, {
1
Python
Python
add missing indent in docstring
0c339d4238d55cc3dd45236f5e7ccff503e007bf
<ide><path>numpy/lib/arraysetops.py <ide> def in1d(ar1, ar2, assume_unique=False, invert=False, kind=None): <ide> False where an element of `ar1` is in `ar2` and True otherwise). <ide> Default is False. ``np.in1d(a, b, invert=True)`` is equivalent <ide> to (but is faster than) ``np.invert(in1d(a, b))``. <del> kind : {None, 'mergesort', 'dictionary'}, optional <add> kind : {None, 'mergesort', 'dictionary'}, optional <ide> The algorithm to use. This will not affect the final result, <ide> but will affect the speed. Default will select automatically <ide> based on memory considerations.
1
Mixed
Go
add network --format flag to ls
a8aaafc4a3fc716bdb2c4e571e34c66eb80bbab2
<ide><path>api/client/cli.go <ide> func (cli *DockerCli) ImagesFormat() string { <ide> return cli.configFile.ImagesFormat <ide> } <ide> <add>// NetworksFormat returns the format string specified in the configuration. <add>// String contains columns and format specification, for example {{ID}}\t{{Name}} <add>func (cli *DockerCli) NetworksFormat() string { <add> return cli.configFile.NetworksFormat <add>} <add> <ide> func (cli *DockerCli) setRawTerminal() error { <ide> if os.Getenv("NORAW") == "" { <ide> if cli.isTerminalIn { <ide><path>api/client/formatter/custom.go <ide> const ( <ide> labelsHeader = "LABELS" <ide> nameHeader = "NAME" <ide> driverHeader = "DRIVER" <add> scopeHeader = "SCOPE" <ide> ) <ide> <ide> type subContext interface { <ide><path>api/client/formatter/network.go <add>package formatter <add> <add>import ( <add> "bytes" <add> "fmt" <add> "strings" <add> <add> "github.com/docker/docker/pkg/stringid" <add> "github.com/docker/engine-api/types" <add>) <add> <add>const ( <add> defaultNetworkTableFormat = "table {{.ID}}\t{{.Name}}\t{{.Driver}}\t{{.Scope}}" <add> <add> networkIDHeader = "NETWORK ID" <add> ipv6Header = "IPV6" <add> internalHeader = "INTERNAL" <add>) <add> <add>// NetworkContext contains network specific information required by the formatter, <add>// encapsulate a Context struct. <add>type NetworkContext struct { <add> Context <add> // Networks <add> Networks []types.NetworkResource <add>} <add> <add>func (ctx NetworkContext) Write() { <add> switch ctx.Format { <add> case tableFormatKey: <add> if ctx.Quiet { <add> ctx.Format = defaultQuietFormat <add> } else { <add> ctx.Format = defaultNetworkTableFormat <add> } <add> case rawFormatKey: <add> if ctx.Quiet { <add> ctx.Format = `network_id: {{.ID}}` <add> } else { <add> ctx.Format = `network_id: {{.ID}}\nname: {{.Name}}\ndriver: {{.Driver}}\nscope: {{.Scope}}\n` <add> } <add> } <add> <add> ctx.buffer = bytes.NewBufferString("") <add> ctx.preformat() <add> <add> tmpl, err := ctx.parseFormat() <add> if err != nil { <add> return <add> } <add> <add> for _, network := range ctx.Networks { <add> networkCtx := &networkContext{ <add> trunc: ctx.Trunc, <add> n: network, <add> } <add> err = ctx.contextFormat(tmpl, networkCtx) <add> if err != nil { <add> return <add> } <add> } <add> <add> ctx.postformat(tmpl, &networkContext{}) <add>} <add> <add>type networkContext struct { <add> baseSubContext <add> trunc bool <add> n types.NetworkResource <add>} <add> <add>func (c *networkContext) ID() string { <add> c.addHeader(networkIDHeader) <add> if c.trunc { <add> return stringid.TruncateID(c.n.ID) <add> } <add> return c.n.ID <add>} <add> <add>func (c *networkContext) Name() string { <add> c.addHeader(nameHeader) <add> return c.n.Name <add>} <add> <add>func (c *networkContext) Driver() string { <add> c.addHeader(driverHeader) <add> return c.n.Driver <add>} <add> <add>func (c *networkContext) Scope() string { <add> c.addHeader(scopeHeader) <add> return c.n.Scope <add>} <add> <add>func (c *networkContext) IPv6() string { <add> c.addHeader(ipv6Header) <add> return fmt.Sprintf("%v", c.n.EnableIPv6) <add>} <add> <add>func (c *networkContext) Internal() string { <add> c.addHeader(internalHeader) <add> return fmt.Sprintf("%v", c.n.Internal) <add>} <add> <add>func (c *networkContext) Labels() string { <add> c.addHeader(labelsHeader) <add> if c.n.Labels == nil { <add> return "" <add> } <add> <add> var joinLabels []string <add> for k, v := range c.n.Labels { <add> joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v)) <add> } <add> return strings.Join(joinLabels, ",") <add>} <add> <add>func (c *networkContext) Label(name string) string { <add> n := strings.Split(name, ".") <add> r := strings.NewReplacer("-", " ", "_", " ") <add> h := r.Replace(n[len(n)-1]) <add> <add> c.addHeader(h) <add> <add> if c.n.Labels == nil { <add> return "" <add> } <add> return c.n.Labels[name] <add>} <ide><path>api/client/formatter/network_test.go <add>package formatter <add> <add>import ( <add> "bytes" <add> "strings" <add> "testing" <add> <add> "github.com/docker/docker/pkg/stringid" <add> "github.com/docker/engine-api/types" <add>) <add> <add>func TestNetworkContext(t *testing.T) { <add> networkID := stringid.GenerateRandomID() <add> <add> var ctx networkContext <add> cases := []struct { <add> networkCtx networkContext <add> expValue string <add> expHeader string <add> call func() string <add> }{ <add> {networkContext{ <add> n: types.NetworkResource{ID: networkID}, <add> trunc: false, <add> }, networkID, networkIDHeader, ctx.ID}, <add> {networkContext{ <add> n: types.NetworkResource{ID: networkID}, <add> trunc: true, <add> }, stringid.TruncateID(networkID), networkIDHeader, ctx.ID}, <add> {networkContext{ <add> n: types.NetworkResource{Name: "network_name"}, <add> }, "network_name", nameHeader, ctx.Name}, <add> {networkContext{ <add> n: types.NetworkResource{Driver: "driver_name"}, <add> }, "driver_name", driverHeader, ctx.Driver}, <add> {networkContext{ <add> n: types.NetworkResource{EnableIPv6: true}, <add> }, "true", ipv6Header, ctx.IPv6}, <add> {networkContext{ <add> n: types.NetworkResource{EnableIPv6: false}, <add> }, "false", ipv6Header, ctx.IPv6}, <add> {networkContext{ <add> n: types.NetworkResource{Internal: true}, <add> }, "true", internalHeader, ctx.Internal}, <add> {networkContext{ <add> n: types.NetworkResource{Internal: false}, <add> }, "false", internalHeader, ctx.Internal}, <add> {networkContext{ <add> n: types.NetworkResource{}, <add> }, "", labelsHeader, ctx.Labels}, <add> {networkContext{ <add> n: types.NetworkResource{Labels: map[string]string{"label1": "value1", "label2": "value2"}}, <add> }, "label1=value1,label2=value2", labelsHeader, ctx.Labels}, <add> } <add> <add> for _, c := range cases { <add> ctx = c.networkCtx <add> v := c.call() <add> if strings.Contains(v, ",") { <add> compareMultipleValues(t, v, c.expValue) <add> } else if v != c.expValue { <add> t.Fatalf("Expected %s, was %s\n", c.expValue, v) <add> } <add> <add> h := ctx.fullHeader() <add> if h != c.expHeader { <add> t.Fatalf("Expected %s, was %s\n", c.expHeader, h) <add> } <add> } <add>} <add> <add>func TestNetworkContextWrite(t *testing.T) { <add> contexts := []struct { <add> context NetworkContext <add> expected string <add> }{ <add> <add> // Errors <add> { <add> NetworkContext{ <add> Context: Context{ <add> Format: "{{InvalidFunction}}", <add> }, <add> }, <add> `Template parsing error: template: :1: function "InvalidFunction" not defined <add>`, <add> }, <add> { <add> NetworkContext{ <add> Context: Context{ <add> Format: "{{nil}}", <add> }, <add> }, <add> `Template parsing error: template: :1:2: executing "" at <nil>: nil is not a command <add>`, <add> }, <add> // Table format <add> { <add> NetworkContext{ <add> Context: Context{ <add> Format: "table", <add> }, <add> }, <add> `NETWORK ID NAME DRIVER SCOPE <add>networkID1 foobar_baz foo local <add>networkID2 foobar_bar bar local <add>`, <add> }, <add> { <add> NetworkContext{ <add> Context: Context{ <add> Format: "table", <add> Quiet: true, <add> }, <add> }, <add> `networkID1 <add>networkID2 <add>`, <add> }, <add> { <add> NetworkContext{ <add> Context: Context{ <add> Format: "table {{.Name}}", <add> }, <add> }, <add> `NAME <add>foobar_baz <add>foobar_bar <add>`, <add> }, <add> { <add> NetworkContext{ <add> Context: Context{ <add> Format: "table {{.Name}}", <add> Quiet: true, <add> }, <add> }, <add> `NAME <add>foobar_baz <add>foobar_bar <add>`, <add> }, <add> // Raw Format <add> { <add> NetworkContext{ <add> Context: Context{ <add> Format: "raw", <add> }, <add> }, `network_id: networkID1 <add>name: foobar_baz <add>driver: foo <add>scope: local <add> <add>network_id: networkID2 <add>name: foobar_bar <add>driver: bar <add>scope: local <add> <add>`, <add> }, <add> { <add> NetworkContext{ <add> Context: Context{ <add> Format: "raw", <add> Quiet: true, <add> }, <add> }, <add> `network_id: networkID1 <add>network_id: networkID2 <add>`, <add> }, <add> // Custom Format <add> { <add> NetworkContext{ <add> Context: Context{ <add> Format: "{{.Name}}", <add> }, <add> }, <add> `foobar_baz <add>foobar_bar <add>`, <add> }, <add> } <add> <add> for _, context := range contexts { <add> networks := []types.NetworkResource{ <add> {ID: "networkID1", Name: "foobar_baz", Driver: "foo", Scope: "local"}, <add> {ID: "networkID2", Name: "foobar_bar", Driver: "bar", Scope: "local"}, <add> } <add> out := bytes.NewBufferString("") <add> context.context.Output = out <add> context.context.Networks = networks <add> context.context.Write() <add> actual := out.String() <add> if actual != context.expected { <add> t.Fatalf("Expected \n%s, got \n%s", context.expected, actual) <add> } <add> // Clean buffer <add> out.Reset() <add> } <add>} <ide><path>api/client/network/list.go <ide> package network <ide> <ide> import ( <del> "fmt" <ide> "sort" <del> "text/tabwriter" <ide> <ide> "golang.org/x/net/context" <ide> <ide> "github.com/docker/docker/api/client" <add> "github.com/docker/docker/api/client/formatter" <ide> "github.com/docker/docker/cli" <del> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/engine-api/types" <ide> "github.com/docker/engine-api/types/filters" <ide> "github.com/spf13/cobra" <ide> func (r byNetworkName) Less(i, j int) bool { return r[i].Name < r[j].Name } <ide> type listOptions struct { <ide> quiet bool <ide> noTrunc bool <add> format string <ide> filter []string <ide> } <ide> <ide> func newListCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> flags := cmd.Flags() <ide> flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display volume names") <ide> flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate the output") <add> flags.StringVar(&opts.format, "format", "", "Pretty-print networks using a Go template") <ide> flags.StringSliceVarP(&opts.filter, "filter", "f", []string{}, "Provide filter values (i.e. 'dangling=true')") <ide> <ide> return cmd <ide> func runList(dockerCli *client.DockerCli, opts listOptions) error { <ide> return err <ide> } <ide> <del> w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0) <del> if !opts.quiet { <del> fmt.Fprintf(w, "NETWORK ID\tNAME\tDRIVER\tSCOPE") <del> fmt.Fprintf(w, "\n") <add> f := opts.format <add> if len(f) == 0 { <add> if len(dockerCli.NetworksFormat()) > 0 && !opts.quiet { <add> f = dockerCli.NetworksFormat() <add> } else { <add> f = "table" <add> } <ide> } <ide> <ide> sort.Sort(byNetworkName(networkResources)) <del> for _, networkResource := range networkResources { <del> ID := networkResource.ID <del> netName := networkResource.Name <del> driver := networkResource.Driver <del> scope := networkResource.Scope <del> if !opts.noTrunc { <del> ID = stringid.TruncateID(ID) <del> } <del> if opts.quiet { <del> fmt.Fprintln(w, ID) <del> continue <del> } <del> fmt.Fprintf(w, "%s\t%s\t%s\t%s\t", <del> ID, <del> netName, <del> driver, <del> scope) <del> fmt.Fprint(w, "\n") <add> <add> networksCtx := formatter.NetworkContext{ <add> Context: formatter.Context{ <add> Output: dockerCli.Out(), <add> Format: f, <add> Quiet: opts.quiet, <add> Trunc: !opts.noTrunc, <add> }, <add> Networks: networkResources, <ide> } <del> w.Flush() <add> <add> networksCtx.Write() <add> <ide> return nil <ide> } <ide><path>cliconfig/configfile/file.go <ide> type ConfigFile struct { <ide> HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"` <ide> PsFormat string `json:"psFormat,omitempty"` <ide> ImagesFormat string `json:"imagesFormat,omitempty"` <add> NetworksFormat string `json:"networksFormat,omitempty"` <ide> DetachKeys string `json:"detachKeys,omitempty"` <ide> CredentialsStore string `json:"credsStore,omitempty"` <ide> Filename string `json:"-"` // Note: for internal use only <ide><path>docs/reference/commandline/network_ls.md <ide> Aliases: <ide> <ide> Options: <ide> -f, --filter value Provide filter values (i.e. 'dangling=true') (default []) <add> --format string Pretty-print networks using a Go template <ide> --help Print usage <ide> --no-trunc Do not truncate the output <ide> -q, --quiet Only display volume names <ide> $ docker network rm `docker network ls --filter type=custom -q` <ide> A warning will be issued when trying to remove a network that has containers <ide> attached. <ide> <add>## Formatting <add> <add>The formatting options (`--format`) pretty-prints networks output <add>using a Go template. <add> <add>Valid placeholders for the Go template are listed below: <add> <add>Placeholder | Description <add>------------|------------------------------------------------------------------------------------------ <add>`.ID` | Network ID <add>`.Name` | Network name <add>`.Driver` | Network driver <add>`.Scope` | Network scope (local, global) <add>`.IPv6` | Whether IPv6 is enabled on the network or not. <add>`.Internal` | Whether the network is internal or not. <add>`.Labels` | All labels assigned to the network. <add>`.Label` | Value of a specific label for this network. For example `{{.Label "project.version"}}` <add> <add>When using the `--format` option, the `network ls` command will either <add>output the data exactly as the template declares or, when using the <add>`table` directive, includes column headers as well. <add> <add>The following example uses a template without headers and outputs the <add>`ID` and `Driver` entries separated by a colon for all networks: <add> <add>```bash <add>$ docker network ls --format "{{.ID}}: {{.Driver}}" <add>afaaab448eb2: bridge <add>d1584f8dc718: host <add>391df270dc66: null <add>``` <add> <ide> ## Related information <ide> <ide> * [network disconnect ](network_disconnect.md) <ide><path>integration-cli/docker_cli_network_unix_test.go <ide> import ( <ide> "net/http" <ide> "net/http/httptest" <ide> "os" <add> "path/filepath" <ide> "strings" <ide> "time" <ide> <ide> func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) { <ide> } <ide> } <ide> <add>func (s *DockerSuite) TestNetworkLsFormat(c *check.C) { <add> testRequires(c, DaemonIsLinux) <add> out, _ := dockerCmd(c, "network", "ls", "--format", "{{.Name}}") <add> lines := strings.Split(strings.TrimSpace(string(out)), "\n") <add> <add> expected := []string{"bridge", "host", "none"} <add> var names []string <add> for _, l := range lines { <add> names = append(names, l) <add> } <add> c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names)) <add>} <add> <add>func (s *DockerSuite) TestNetworkLsFormatDefaultFormat(c *check.C) { <add> testRequires(c, DaemonIsLinux) <add> <add> config := `{ <add> "networksFormat": "{{ .Name }} default" <add>}` <add> d, err := ioutil.TempDir("", "integration-cli-") <add> c.Assert(err, checker.IsNil) <add> defer os.RemoveAll(d) <add> <add> err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644) <add> c.Assert(err, checker.IsNil) <add> <add> out, _ := dockerCmd(c, "--config", d, "network", "ls") <add> lines := strings.Split(strings.TrimSpace(string(out)), "\n") <add> <add> expected := []string{"bridge default", "host default", "none default"} <add> var names []string <add> for _, l := range lines { <add> names = append(names, l) <add> } <add> c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names)) <add>} <add> <ide> func (s *DockerNetworkSuite) TestDockerNetworkCreatePredefined(c *check.C) { <ide> predefined := []string{"bridge", "host", "none", "default"} <ide> for _, net := range predefined { <ide><path>man/docker-network-ls.1.md <ide> docker-network-ls - list networks <ide> # SYNOPSIS <ide> **docker network ls** <ide> [**-f**|**--filter**[=*[]*]] <add>[**--format**=*"TEMPLATE"*] <ide> [**--no-trunc**[=*true*|*false*]] <ide> [**-q**|**--quiet**[=*true*|*false*]] <ide> [**--help**] <ide> attached. <ide> **-f**, **--filter**=*[]* <ide> filter output based on conditions provided. <ide> <add>**--format**="*TEMPLATE*" <add> Pretty-print networks using a Go template. <add> Valid placeholders: <add> .ID - Network ID <add> .Name - Network name <add> .Driver - Network driver <add> .Scope - Network scope (local, global) <add> .IPv6 - Whether IPv6 is enabled on the network or not <add> .Internal - Whether the network is internal or not <add> .Labels - All labels assigned to the network <add> .Label - Value of a specific label for this network. For example `{{.Label "project.version"}}` <add> <ide> **--no-trunc**=*true*|*false* <ide> Do not truncate the output <ide>
9
Text
Text
standardize usage of hostname vs. host name
486ffa2abcee3be1210044a1654df2fb50eaa42f
<ide><path>doc/api/dns.md <ide> changes: <ide> the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a <ide> bug in the name resolution service used by the operating system. <ide> <del>Resolves a hostname (e.g. `'nodejs.org'`) into the first found A (IPv4) or <add>Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or <ide> AAAA (IPv6) record. All `option` properties are optional. If `options` is an <ide> integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 <ide> and IPv6 addresses are both returned if found. <ide> properties `address` and `family`. <ide> <ide> On error, `err` is an [`Error`][] object, where `err.code` is the error code. <ide> Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when <del>the hostname does not exist but also when the lookup fails in other ways <add>the host name does not exist but also when the lookup fails in other ways <ide> such as no available file descriptors. <ide> <ide> `dns.lookup()` does not necessarily have anything to do with the DNS protocol. <ide> added: v0.11.14 <ide> * `hostname` {string} e.g. `example.com` <ide> * `service` {string} e.g. `http` <ide> <del>Resolves the given `address` and `port` into a hostname and service using <add>Resolves the given `address` and `port` into a host name and service using <ide> the operating system's underlying `getnameinfo` implementation. <ide> <ide> If `address` is not a valid IP address, a `TypeError` will be thrown. <ide> If this method is invoked as its [`util.promisify()`][]ed version, it returns a <ide> added: v0.1.27 <ide> --> <ide> <del>* `hostname` {string} Hostname to resolve. <add>* `hostname` {string} Host name to resolve. <ide> * `rrtype` {string} Resource record type. **Default:** `'A'`. <ide> * `callback` {Function} <ide> * `err` {Error} <ide> * `records` {string[] | Object[] | Object} <ide> <del>Uses the DNS protocol to resolve a hostname (e.g. `'nodejs.org'`) into an array <add>Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array <ide> of the resource records. The `callback` function has arguments <ide> `(err, records)`. When successful, `records` will be an array of resource <ide> records. The type and structure of individual results varies based on `rrtype`: <ide> changes: <ide> specifically `options.ttl`. <ide> --> <ide> <del>* `hostname` {string} Hostname to resolve. <add>* `hostname` {string} Host name to resolve. <ide> * `options` {Object} <ide> * `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. <ide> When `true`, the callback receives an array of <ide> changes: <ide> specifically `options.ttl`. <ide> --> <ide> <del>* `hostname` {string} Hostname to resolve. <add>* `hostname` {string} Host name to resolve. <ide> * `options` {Object} <ide> * `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. <ide> When `true`, the callback receives an array of <ide> added: v0.1.16 <ide> * `hostnames` {string[]} <ide> <ide> Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an <del>array of hostnames. <add>array of host names. <ide> <ide> On error, `err` is an [`Error`][] object, where `err.code` is <ide> one of the [DNS error codes][]. <ide> added: v10.6.0 <ide> expected to change in the not too distant future. <ide> New code should use `{ verbatim: true }`. <ide> <del>Resolves a hostname (e.g. `'nodejs.org'`) into the first found A (IPv4) or <add>Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or <ide> AAAA (IPv6) record. All `option` properties are optional. If `options` is an <ide> integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 <ide> and IPv6 addresses are both returned if found. <ide> being an array of objects with the properties `address` and `family`. <ide> On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` <ide> is the error code. <ide> Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when <del>the hostname does not exist but also when the lookup fails in other ways <add>the host name does not exist but also when the lookup fails in other ways <ide> such as no available file descriptors. <ide> <ide> [`dnsPromises.lookup()`][] does not necessarily have anything to do with the DNS <ide> added: v10.6.0 <ide> * `address` {string} <ide> * `port` {number} <ide> <del>Resolves the given `address` and `port` into a hostname and service using <add>Resolves the given `address` and `port` into a host name and service using <ide> the operating system's underlying `getnameinfo` implementation. <ide> <ide> If `address` is not a valid IP address, a `TypeError` will be thrown. <ide> dnsPromises.lookupService('127.0.0.1', 22).then((result) => { <ide> added: v10.6.0 <ide> --> <ide> <del>* `hostname` {string} Hostname to resolve. <add>* `hostname` {string} Host name to resolve. <ide> * `rrtype` {string} Resource record type. **Default:** `'A'`. <ide> <del>Uses the DNS protocol to resolve a hostname (e.g. `'nodejs.org'`) into an array <add>Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array <ide> of the resource records. When successful, the `Promise` is resolved with an <ide> array of resource records. The type and structure of individual results vary <ide> based on `rrtype`: <ide> is one of the [DNS error codes](#dns_error_codes). <ide> added: v10.6.0 <ide> --> <ide> <del>* `hostname` {string} Hostname to resolve. <add>* `hostname` {string} Host name to resolve. <ide> * `options` {Object} <ide> * `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. <ide> When `true`, the `Promise` is resolved with an array of <ide> addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). <ide> added: v10.6.0 <ide> --> <ide> <del>* `hostname` {string} Hostname to resolve. <add>* `hostname` {string} Host name to resolve. <ide> * `options` {Object} <ide> * `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. <ide> When `true`, the `Promise` is resolved with an array of <ide> added: v10.6.0 <ide> * `ip` {string} <ide> <ide> Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an <del>array of hostnames. <add>array of host names. <ide> <ide> On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` <ide> is one of the [DNS error codes](#dns_error_codes). <ide> Each DNS query can return one of the following error codes: <ide> * `dns.NOTIMP`: DNS server does not implement requested operation. <ide> * `dns.REFUSED`: DNS server refused query. <ide> * `dns.BADQUERY`: Misformatted DNS query. <del>* `dns.BADNAME`: Misformatted hostname. <add>* `dns.BADNAME`: Misformatted host name. <ide> * `dns.BADFAMILY`: Unsupported address family. <ide> * `dns.BADRESP`: Misformatted DNS reply. <ide> * `dns.CONNREFUSED`: Could not contact DNS servers. <ide> Each DNS query can return one of the following error codes: <ide> * `dns.DESTRUCTION`: Channel is being destroyed. <ide> * `dns.BADSTR`: Misformatted string. <ide> * `dns.BADFLAGS`: Illegal flags specified. <del>* `dns.NONAME`: Given hostname is not numeric. <add>* `dns.NONAME`: Given host name is not numeric. <ide> * `dns.BADHINTS`: Illegal hints flags specified. <ide> * `dns.NOTINITIALIZED`: c-ares library initialization not yet performed. <ide> * `dns.LOADIPHLPAPI`: Error loading `iphlpapi.dll`. <ide> implications for some applications, see the [`UV_THREADPOOL_SIZE`][] <ide> documentation for more information. <ide> <ide> Various networking APIs will call `dns.lookup()` internally to resolve <del>host names. If that is an issue, consider resolving the hostname to an address <add>host names. If that is an issue, consider resolving the host name to an address <ide> using `dns.resolve()` and using the address instead of a host name. Also, some <ide> networking APIs (such as [`socket.connect()`][] and [`dgram.createSocket()`][]) <ide> allow the default resolver, `dns.lookup()`, to be replaced.
1
Java
Java
add immutable multivaluemap wrapper
0a58419df4fee5e50b6831c065c1a14bedc5f5f8
<ide><path>spring-core/src/main/java/org/springframework/util/CollectionUtils.java <ide> public static <K, V> MultiValueMap<K, V> unmodifiableMultiValueMap( <ide> MultiValueMap<? extends K, ? extends V> targetMap) { <ide> <ide> Assert.notNull(targetMap, "'targetMap' must not be null"); <del> Map<K, List<V>> result = newLinkedHashMap(targetMap.size()); <del> targetMap.forEach((key, value) -> { <del> List<? extends V> values = Collections.unmodifiableList(value); <del> result.put(key, (List<V>) values); <del> }); <del> Map<K, List<V>> unmodifiableMap = Collections.unmodifiableMap(result); <del> return toMultiValueMap(unmodifiableMap); <add> if (targetMap instanceof UnmodifiableMultiValueMap) { <add> return (MultiValueMap<K, V>) targetMap; <add> } <add> return new UnmodifiableMultiValueMap<>(targetMap); <ide> } <ide> <ide> <ide><path>spring-core/src/main/java/org/springframework/util/UnmodifiableMultiValueMap.java <add>/* <add> * Copyright 2002-2021 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util; <add> <add>import java.io.Serializable; <add>import java.util.Collection; <add>import java.util.Collections; <add>import java.util.Comparator; <add>import java.util.Iterator; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.Set; <add>import java.util.Spliterator; <add>import java.util.function.BiConsumer; <add>import java.util.function.BiFunction; <add>import java.util.function.Consumer; <add>import java.util.function.Function; <add>import java.util.function.Predicate; <add>import java.util.stream.Stream; <add>import java.util.stream.StreamSupport; <add> <add>import org.springframework.lang.Nullable; <add> <add>/** <add> * Unmodifiable wrapper for {@link MultiValueMap}. <add> * <add> * @author Arjen Poutsma <add> * @since 6.0 <add> * @param <K> the key type <add> * @param <V> the value element type <add> */ <add>final class UnmodifiableMultiValueMap<K,V> implements MultiValueMap<K,V>, Serializable { <add> <add> private static final long serialVersionUID = -8697084563854098920L; <add> <add> <add> private final MultiValueMap<K, V> delegate; <add> <add> @Nullable <add> private transient Set<K> keySet; <add> <add> @Nullable <add> private transient Set<Entry<K, List<V>>> entrySet; <add> <add> @Nullable <add> private transient Collection<List<V>> values; <add> <add> <add> @SuppressWarnings("unchecked") <add> public UnmodifiableMultiValueMap(MultiValueMap<? extends K, ? extends V> delegate) { <add> Assert.notNull(delegate, "Delegate must not be null"); <add> this.delegate = (MultiValueMap<K, V>) delegate; <add> } <add> <add> // delegation <add> <add> @Override <add> public int size() { <add> return this.delegate.size(); <add> } <add> <add> @Override <add> public boolean isEmpty() { <add> return this.delegate.isEmpty(); <add> } <add> <add> @Override <add> public boolean containsKey(Object key) { <add> return this.delegate.containsKey(key); <add> } <add> <add> @Override <add> public boolean containsValue(Object value) { <add> return this.delegate.containsValue(value); <add> } <add> <add> @Override <add> @Nullable <add> public List<V> get(Object key) { <add> List<V> result = this.delegate.get(key); <add> return result != null ? Collections.unmodifiableList(result) : null; <add> } <add> <add> @Override <add> public V getFirst(K key) { <add> return this.delegate.getFirst(key); <add> } <add> <add> @Override <add> public List<V> getOrDefault(Object key, List<V> defaultValue) { <add> List<V> result = this.delegate.getOrDefault(key, defaultValue); <add> if (result != defaultValue) { <add> result = Collections.unmodifiableList(result); <add> } <add> return result; <add> } <add> <add> @Override <add> public void forEach(BiConsumer<? super K, ? super List<V>> action) { <add> this.delegate.forEach((k, vs) -> action.accept(k, Collections.unmodifiableList(vs))); <add> } <add> <add> @Override <add> public Map<K, V> toSingleValueMap() { <add> return this.delegate.toSingleValueMap(); <add> } <add> <add> @Override <add> public int hashCode() { <add> return this.delegate.hashCode(); <add> } <add> <add> @Override <add> public boolean equals(Object obj) { <add> return this == obj || this.delegate.equals(obj); <add> } <add> <add> @Override <add> public String toString() { <add> return this.delegate.toString(); <add> } <add> <add> // lazy init <add> <add> @Override <add> public Set<K> keySet() { <add> if (this.keySet == null) { <add> this.keySet = Collections.unmodifiableSet(this.delegate.keySet()); <add> } <add> return this.keySet; <add> } <add> <add> @Override <add> public Set<Entry<K, List<V>>> entrySet() { <add> if (this.entrySet == null) { <add> this.entrySet = new UnmodifiableEntrySet<>(this.delegate.entrySet()); <add> } <add> return this.entrySet; <add> } <add> <add> @Override <add> public Collection<List<V>> values() { <add> if (this.values == null) { <add> this.values = new UnmodifiableValueCollection<>(this.delegate.values()); <add> } <add> return this.values; <add> } <add> <add> // unsupported <add> <add> @Nullable <add> @Override <add> public List<V> put(K key, List<V> value) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public List<V> putIfAbsent(K key, List<V> value) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void putAll(Map<? extends K, ? extends List<V>> m) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public List<V> remove(Object key) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void add(K key, @Nullable V value) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void addAll(K key, List<? extends V> values) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void addAll(MultiValueMap<K, V> values) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void addIfAbsent(K key, @Nullable V value) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void set(K key, @Nullable V value) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void setAll(Map<K, V> values) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void replaceAll(BiFunction<? super K, ? super List<V>, ? extends List<V>> function) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean remove(Object key, Object value) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean replace(K key, List<V> oldValue, List<V> newValue) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public List<V> replace(K key, List<V> value) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public List<V> computeIfAbsent(K key, Function<? super K, ? extends List<V>> mappingFunction) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public List<V> computeIfPresent(K key, <add> BiFunction<? super K, ? super List<V>, ? extends List<V>> remappingFunction) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public List<V> compute(K key, <add> BiFunction<? super K, ? super List<V>, ? extends List<V>> remappingFunction) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public List<V> merge(K key, List<V> value, <add> BiFunction<? super List<V>, ? super List<V>, ? extends List<V>> remappingFunction) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void clear() { <add> throw new UnsupportedOperationException(); <add> } <add> <add> <add> private static class UnmodifiableEntrySet<K,V> implements Set<Map.Entry<K, List<V>>>, Serializable { <add> <add> private static final long serialVersionUID = 2407578793783925203L; <add> <add> <add> private final Set<Entry<K, List<V>>> delegate; <add> <add> <add> @SuppressWarnings("unchecked") <add> public UnmodifiableEntrySet(Set<? extends Entry<? extends K, ? extends List<? extends V>>> delegate) { <add> this.delegate = (Set<Entry<K, List<V>>>) delegate; <add> } <add> <add> // delegation <add> <add> @Override <add> public int size() { <add> return this.delegate.size(); <add> } <add> <add> @Override <add> public boolean isEmpty() { <add> return this.delegate.isEmpty(); <add> } <add> <add> @Override <add> public boolean contains(Object o) { <add> return this.delegate.contains(o); <add> } <add> <add> @Override <add> public boolean containsAll(Collection<?> c) { <add> return this.delegate.containsAll(c); <add> } <add> <add> @Override <add> public Iterator<Entry<K, List<V>>> iterator() { <add> Iterator<? extends Entry<? extends K, ? extends List<? extends V>>> iterator = this.delegate.iterator(); <add> return new Iterator<>() { <add> @Override <add> public boolean hasNext() { <add> return iterator.hasNext(); <add> } <add> <add> @Override <add> public Entry<K, List<V>> next() { <add> return new UnmodifiableEntry<>(iterator.next()); <add> } <add> }; <add> } <add> <add> @Override <add> public Object[] toArray() { <add> Object[] result = this.delegate.toArray(); <add> filterArray(result); <add> return result; <add> } <add> <add> @Override <add> public <T> T[] toArray(T[] a) { <add> T[] result = this.delegate.toArray(a); <add> filterArray(result); <add> return result; <add> } <add> <add> @SuppressWarnings("unchecked") <add> private void filterArray(Object[] result) { <add> for (int i = 0; i < result.length; i++) { <add> if (result[i] instanceof Map.Entry<?,?> entry) { <add> result[i] = new UnmodifiableEntry<>((Entry<K, List<V>>) entry); <add> } <add> } <add> } <add> <add> @Override <add> public void forEach(Consumer<? super Entry<K, List<V>>> action) { <add> this.delegate.forEach(e -> action.accept(new UnmodifiableEntry<>(e))); <add> } <add> <add> @Override <add> public Stream<Entry<K, List<V>>> stream() { <add> return StreamSupport.stream(spliterator(), false); <add> } <add> <add> @Override <add> public Stream<Entry<K, List<V>>> parallelStream() { <add> return StreamSupport.stream(spliterator(), true); <add> } <add> <add> @Override <add> public Spliterator<Entry<K, List<V>>> spliterator() { <add> return new UnmodifiableEntrySpliterator<>(this.delegate.spliterator()); <add> } <add> <add> @Override <add> public int hashCode() { <add> return this.delegate.hashCode(); <add> } <add> <add> @Override <add> public boolean equals(Object obj) { <add> if (this == obj) { <add> return true; <add> } <add> else if (obj instanceof Set<?> other) { <add> return other.size() == this.delegate.size() && <add> containsAll(other); <add> } <add> return false; <add> } <add> <add> @Override <add> public String toString() { <add> return this.delegate.toString(); <add> } <add> <add> // unsupported <add> <add> @Override <add> public boolean add(Entry<K, List<V>> kListEntry) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean remove(Object o) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean removeIf(Predicate<? super Entry<K, List<V>>> filter) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean addAll(Collection<? extends Entry<K, List<V>>> c) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean retainAll(Collection<?> c) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean removeAll(Collection<?> c) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void clear() { <add> throw new UnsupportedOperationException(); <add> } <add> <add> <add> private static class UnmodifiableEntrySpliterator<K,V> implements Spliterator<Entry<K,List<V>>> { <add> <add> private final Spliterator<Entry<K, List<V>>> delegate; <add> <add> <add> @SuppressWarnings("unchecked") <add> public UnmodifiableEntrySpliterator( <add> Spliterator<? extends Entry<? extends K, ? extends List<? extends V>>> delegate) { <add> this.delegate = (Spliterator<Entry<K, List<V>>>) delegate; <add> } <add> <add> @Override <add> public boolean tryAdvance(Consumer<? super Entry<K, List<V>>> action) { <add> return this.delegate.tryAdvance(entry -> action.accept(new UnmodifiableEntry<>(entry))); <add> } <add> <add> @Override <add> public void forEachRemaining(Consumer<? super Entry<K, List<V>>> action) { <add> this.delegate.forEachRemaining(entry -> action.accept(new UnmodifiableEntry<>(entry))); <add> } <add> <add> @Override <add> @Nullable <add> public Spliterator<Entry<K, List<V>>> trySplit() { <add> Spliterator<? extends Entry<? extends K, ? extends List<? extends V>>> split = this.delegate.trySplit(); <add> if (split != null) { <add> return new UnmodifiableEntrySpliterator<>(split); <add> } <add> else { <add> return null; <add> } <add> } <add> <add> @Override <add> public long estimateSize() { <add> return this.delegate.estimateSize(); <add> } <add> <add> @Override <add> public long getExactSizeIfKnown() { <add> return this.delegate.getExactSizeIfKnown(); <add> } <add> <add> @Override <add> public int characteristics() { <add> return this.delegate.characteristics(); <add> } <add> <add> @Override <add> public boolean hasCharacteristics(int characteristics) { <add> return this.delegate.hasCharacteristics(characteristics); <add> } <add> <add> @Override <add> public Comparator<? super Entry<K, List<V>>> getComparator() { <add> return this.delegate.getComparator(); <add> } <add> } <add> <add> <add> private static class UnmodifiableEntry<K,V> implements Map.Entry<K,List<V>> { <add> <add> private final Entry<K, List<V>> delegate; <add> <add> <add> @SuppressWarnings("unchecked") <add> public UnmodifiableEntry(Entry<? extends K, ? extends List<? extends V>> delegate) { <add> Assert.notNull(delegate, "Delegate must not be null"); <add> this.delegate = (Entry<K, List<V>>) delegate; <add> } <add> <add> @Override <add> public K getKey() { <add> return this.delegate.getKey(); <add> } <add> <add> @Override <add> public List<V> getValue() { <add> return Collections.unmodifiableList(this.delegate.getValue()); <add> } <add> <add> @Override <add> public List<V> setValue(List<V> value) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public int hashCode() { <add> return this.delegate.hashCode(); <add> } <add> <add> @Override <add> public boolean equals(Object obj) { <add> if (this == obj) { <add> return true; <add> } <add> else if (obj instanceof Map.Entry<?, ?> other) { <add> return getKey().equals(other.getKey()) && <add> getValue().equals(other.getValue()); <add> } <add> return false; <add> } <add> <add> @Override <add> public String toString() { <add> return this.delegate.toString(); <add> } <add> } <add> } <add> <add> <add> private static class UnmodifiableValueCollection<T> implements Collection<List<T>>, Serializable { <add> <add> private static final long serialVersionUID = 5518377583904339588L; <add> <add> private final Collection<List<T>> delegate; <add> <add> <add> public UnmodifiableValueCollection(Collection<List<T>> delegate) { <add> this.delegate = delegate; <add> } <add> <add> // delegation <add> <add> @Override <add> public int size() { <add> return this.delegate.size(); <add> } <add> <add> @Override <add> public boolean isEmpty() { <add> return this.delegate.isEmpty(); <add> } <add> <add> @Override <add> public boolean contains(Object o) { <add> return this.delegate.contains(o); <add> } <add> <add> @Override <add> public boolean containsAll(Collection<?> c) { <add> return this.delegate.containsAll(c); <add> } <add> <add> @Override <add> public Object[] toArray() { <add> Object[] result = this.delegate.toArray(); <add> filterArray(result); <add> return result; <add> } <add> <add> @Override <add> public <T> T[] toArray(T[] a) { <add> T[] result = this.delegate.toArray(a); <add> filterArray(result); <add> return result; <add> } <add> <add> private void filterArray(Object[] array) { <add> for (int i = 0; i < array.length; i++) { <add> if (array[i] instanceof List<?> list) { <add> array[i] = Collections.unmodifiableList(list); <add> } <add> } <add> } <add> <add> @Override <add> public Iterator<List<T>> iterator() { <add> Iterator<List<T>> iterator = this.delegate.iterator(); <add> return new Iterator<>() { <add> @Override <add> public boolean hasNext() { <add> return iterator.hasNext(); <add> } <add> <add> @Override <add> public List<T> next() { <add> return Collections.unmodifiableList(iterator.next()); <add> } <add> }; <add> } <add> <add> @Override <add> public void forEach(Consumer<? super List<T>> action) { <add> this.delegate.forEach(list -> action.accept(Collections.unmodifiableList(list))); <add> } <add> <add> @Override <add> public Spliterator<List<T>> spliterator() { <add> return new UnmodifiableValueSpliterator<>(this.delegate.spliterator()); <add> } <add> <add> @Override <add> public Stream<List<T>> stream() { <add> return StreamSupport.stream(spliterator(), false); <add> } <add> <add> @Override <add> public Stream<List<T>> parallelStream() { <add> return StreamSupport.stream(spliterator(), true); <add> } <add> <add> @Override <add> public int hashCode() { <add> return this.delegate.hashCode(); <add> } <add> <add> @Override <add> public boolean equals(Object obj) { <add> return this == obj || this.delegate.equals(obj); <add> } <add> <add> @Override <add> public String toString() { <add> return this.delegate.toString(); <add> } <add> <add> // unsupported <add> <add> @Override <add> public boolean add(List<T> ts) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean remove(Object o) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean addAll(Collection<? extends List<T>> c) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean removeAll(Collection<?> c) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean retainAll(Collection<?> c) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean removeIf(Predicate<? super List<T>> filter) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void clear() { <add> throw new UnsupportedOperationException(); <add> } <add> <add> <add> private static class UnmodifiableValueSpliterator<T> implements Spliterator<List<T>> { <add> <add> private final Spliterator<List<T>> delegate; <add> <add> <add> public UnmodifiableValueSpliterator(Spliterator<List<T>> delegate) { <add> this.delegate = delegate; <add> } <add> <add> @Override <add> public boolean tryAdvance(Consumer<? super List<T>> action) { <add> return this.delegate.tryAdvance(l -> action.accept(Collections.unmodifiableList(l))); <add> } <add> <add> @Override <add> public void forEachRemaining(Consumer<? super List<T>> action) { <add> this.delegate.forEachRemaining(l -> action.accept(Collections.unmodifiableList(l))); <add> } <add> <add> @Override <add> @Nullable <add> public Spliterator<List<T>> trySplit() { <add> Spliterator<List<T>> split = this.delegate.trySplit(); <add> if (split != null) { <add> return new UnmodifiableValueSpliterator<>(split); <add> } <add> else { <add> return null; <add> } <add> } <add> <add> @Override <add> public long estimateSize() { <add> return this.delegate.estimateSize(); <add> } <add> <add> @Override <add> public long getExactSizeIfKnown() { <add> return this.delegate.getExactSizeIfKnown(); <add> } <add> <add> @Override <add> public int characteristics() { <add> return this.delegate.characteristics(); <add> } <add> <add> @Override <add> public boolean hasCharacteristics(int characteristics) { <add> return this.delegate.hasCharacteristics(characteristics); <add> } <add> <add> @Override <add> public Comparator<? super List<T>> getComparator() { <add> return this.delegate.getComparator(); <add> } <add> } <add> <add> } <add>} <ide><path>spring-core/src/test/java/org/springframework/util/UnmodifiableMultiValueMapTests.java <add>/* <add> * Copyright 2002-2021 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util; <add> <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.Iterator; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.Set; <add> <add>import org.assertj.core.api.ThrowableTypeAssert; <add>import org.junit.jupiter.api.Test; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add>import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <add>import static org.assertj.core.api.Assertions.entry; <add>import static org.mockito.BDDMockito.given; <add>import static org.mockito.Mockito.mock; <add> <add>/** <add> * @author Arjen Poutsma <add> */ <add>class UnmodifiableMultiValueMapTests { <add> <add> @Test <add> void delegation() { <add> MultiValueMap<String, String> mock = mock(MultiValueMap.class); <add> UnmodifiableMultiValueMap<String, String> map = new UnmodifiableMultiValueMap<>(mock); <add> <add> given(mock.size()).willReturn(1); <add> assertThat(map.size()).isEqualTo(1); <add> <add> given(mock.isEmpty()).willReturn(false); <add> assertThat(map.isEmpty()).isFalse(); <add> <add> given(mock.containsKey("foo")).willReturn(true); <add> assertThat(map.containsKey("foo")).isTrue(); <add> <add> given(mock.containsValue(List.of("bar"))).willReturn(true); <add> assertThat(map.containsValue(List.of("bar"))).isTrue(); <add> <add> List<String> list = new ArrayList<>(); <add> list.add("bar"); <add> given(mock.get("foo")).willReturn(list); <add> List<String> result = map.get("foo"); <add> assertThat(result).isNotNull().containsExactly("bar"); <add> assertThatUnsupportedOperationException().isThrownBy(() -> result.add("baz")); <add> <add> given(mock.getOrDefault("foo", List.of("bar"))).willReturn(List.of("baz")); <add> assertThat(map.getOrDefault("foo", List.of("bar"))).containsExactly("baz"); <add> <add> given(mock.toSingleValueMap()).willReturn(Map.of("foo", "bar")); <add> assertThat(map.toSingleValueMap()).containsExactly(entry("foo", "bar")); <add> } <add> <add> @Test <add> void unsupported() { <add> UnmodifiableMultiValueMap<String, String> map = new UnmodifiableMultiValueMap<>(new LinkedMultiValueMap<>()); <add> <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.put("foo", List.of("bar"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.putIfAbsent("foo", List.of("bar"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.putAll(Map.of("foo", List.of("bar")))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.remove("foo")); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.add("foo", "bar")); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.addAll("foo", List.of("bar"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.addAll(new LinkedMultiValueMap<>())); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.addIfAbsent("foo", "baz")); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.set("foo", "baz")); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.setAll(Map.of("foo", "baz"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.replaceAll((s, strings) -> strings)); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.remove("foo", List.of("bar"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.replace("foo", List.of("bar"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.replace("foo", List.of("bar"), List.of("baz"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.computeIfAbsent("foo", s -> List.of("bar"))); <add> assertThatUnsupportedOperationException().isThrownBy( <add> () -> map.computeIfPresent("foo", (s1, s2) -> List.of("bar"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.compute("foo", (s1, s2) -> List.of("bar"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.merge("foo", List.of("bar"), (s1, s2) -> s1)); <add> assertThatUnsupportedOperationException().isThrownBy(() -> map.clear()); <add> } <add> <add> @Test <add> void entrySetDelegation() { <add> MultiValueMap<String, String> mockMap = mock(MultiValueMap.class); <add> Set<Map.Entry<String, List<String>>> mockSet = mock(Set.class); <add> given(mockMap.entrySet()).willReturn(mockSet); <add> Set<Map.Entry<String, List<String>>> set = new UnmodifiableMultiValueMap<>(mockMap).entrySet(); <add> <add> given(mockSet.size()).willReturn(1); <add> assertThat(set.size()).isEqualTo(1); <add> <add> given(mockSet.isEmpty()).willReturn(false); <add> assertThat(set.isEmpty()).isFalse(); <add> <add> given(mockSet.contains("foo")).willReturn(true); <add> assertThat(set.contains("foo")).isTrue(); <add> <add> List<Map.Entry<String, List<String>>> mockEntries = List.of(mock(Map.Entry.class)); <add> given(mockSet.containsAll(mockEntries)).willReturn(true); <add> assertThat(set.containsAll(mockEntries)).isTrue(); <add> <add> Iterator<Map.Entry<String, List<String>>> mockIterator = mock(Iterator.class); <add> given(mockSet.iterator()).willReturn(mockIterator); <add> given(mockIterator.hasNext()).willReturn(false); <add> assertThat(set.iterator()).isExhausted(); <add> } <add> <add> @Test <add> void entrySetUnsupported() { <add> Set<Map.Entry<String, List<String>>> set = new UnmodifiableMultiValueMap<String, String>(new LinkedMultiValueMap<>()).entrySet(); <add> <add> assertThatUnsupportedOperationException().isThrownBy(() -> set.add(mock(Map.Entry.class))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> set.remove("foo")); <add> assertThatUnsupportedOperationException().isThrownBy(() -> set.removeIf(e -> true)); <add> assertThatUnsupportedOperationException().isThrownBy(() -> set.addAll(mock(List.class))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> set.retainAll(mock(List.class))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> set.removeAll(mock(List.class))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> set.clear()); <add> } <add> <add> @Test <add> void valuesDelegation() { <add> MultiValueMap<String, String> mockMap = mock(MultiValueMap.class); <add> Collection<List<String>> mockValues = mock(Collection.class); <add> given(mockMap.values()).willReturn(mockValues); <add> Collection<List<String>> values = new UnmodifiableMultiValueMap<>(mockMap).values(); <add> <add> given(mockValues.size()).willReturn(1); <add> assertThat(values.size()).isEqualTo(1); <add> <add> given(mockValues.isEmpty()).willReturn(false); <add> assertThat(values.isEmpty()).isFalse(); <add> <add> given(mockValues.contains(List.of("foo"))).willReturn(true); <add> assertThat(mockValues.contains(List.of("foo"))).isTrue(); <add> <add> given(mockValues.containsAll(List.of(List.of("foo")))).willReturn(true); <add> assertThat(mockValues.containsAll(List.of(List.of("foo")))).isTrue(); <add> <add> Iterator<List<String>> mockIterator = mock(Iterator.class); <add> given(mockValues.iterator()).willReturn(mockIterator); <add> given(mockIterator.hasNext()).willReturn(false); <add> assertThat(values.iterator()).isExhausted(); <add> } <add> <add> @Test <add> void valuesUnsupported() { <add> Collection<List<String>> values = <add> new UnmodifiableMultiValueMap<String, String>(new LinkedMultiValueMap<>()).values(); <add> <add> assertThatUnsupportedOperationException().isThrownBy(() -> values.add(List.of("foo"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> values.remove(List.of("foo"))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> values.addAll(List.of(List.of("foo")))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> values.removeAll(List.of(List.of("foo")))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> values.retainAll(List.of(List.of("foo")))); <add> assertThatUnsupportedOperationException().isThrownBy(() -> values.removeIf(s -> true)); <add> assertThatUnsupportedOperationException().isThrownBy(() -> values.clear()); <add> } <add> <add> private static ThrowableTypeAssert<UnsupportedOperationException> assertThatUnsupportedOperationException() { <add> return assertThatExceptionOfType(UnsupportedOperationException.class); <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java <ide> private UriComponents buildInternal(EncodingHint hint) { <ide> result = new OpaqueUriComponents(this.scheme, this.ssp, this.fragment); <ide> } <ide> else { <add> MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(this.queryParams); <ide> HierarchicalUriComponents uric = new HierarchicalUriComponents(this.scheme, this.fragment, <del> this.userInfo, this.host, this.port, this.pathBuilder.build(), this.queryParams, <add> this.userInfo, this.host, this.port, this.pathBuilder.build(), queryParams, <ide> hint == EncodingHint.FULLY_ENCODED); <ide> result = (hint == EncodingHint.ENCODE_TEMPLATE ? uric.encodeTemplate(this.charset) : uric); <ide> }
4
Text
Text
remove es6 notice from readme
3ba9efe3af770e63abcb8d5de020c5d07ff73d27
<ide><path>README.md <ide> <ide> A lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates. <ide> <del>- - - - - - - <del> <del>**Important notice**: Moment is undergoing major refactoring for version <del>**2.10**, that would result in ES6 code that is transpiled to ES5 for <del>different environments: node, browser global, AMD, various build/packaging <del>systems. <del> <del>You might be required to rewrite your pull request on top once we merge it in. <del> <del>- - - - - - - <del> <ide> ## [Documentation](http://momentjs.com/docs/) <ide> <ide> ## Port to ES6 (version 2.10.0)
1
Javascript
Javascript
change scoping of variables with let
fcae05e4b5ee7c0817ca0c9f0bc3df012c1664c7
<ide><path>lib/url.js <ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { <ide> <ide> // find the first instance of any hostEndingChars <ide> var hostEnd = -1; <del> for (var i = 0; i < hostEndingChars.length; i++) { <del> var hec = rest.indexOf(hostEndingChars[i]); <add> for (let i = 0; i < hostEndingChars.length; i++) { <add> const hec = rest.indexOf(hostEndingChars[i]); <ide> if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) <ide> hostEnd = hec; <ide> } <ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { <ide> <ide> // the host is the remaining to the left of the first non-host char <ide> hostEnd = -1; <del> for (var i = 0; i < nonHostChars.length; i++) { <del> var hec = rest.indexOf(nonHostChars[i]); <add> for (let i = 0; i < nonHostChars.length; i++) { <add> const hec = rest.indexOf(nonHostChars[i]); <ide> if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) <ide> hostEnd = hec; <ide> } <ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { <ide> // validate a little. <ide> if (!ipv6Hostname) { <ide> var hostparts = this.hostname.split(/\./); <del> for (var i = 0, l = hostparts.length; i < l; i++) { <add> for (let i = 0, l = hostparts.length; i < l; i++) { <ide> var part = hostparts[i]; <ide> if (!part) continue; <ide> if (!part.match(hostnamePartPattern)) { <ide> var newpart = ''; <del> for (var j = 0, k = part.length; j < k; j++) { <add> for (let j = 0, k = part.length; j < k; j++) { <ide> if (part.charCodeAt(j) > 127) { <ide> // we replace non-ASCII char with a temporary placeholder <ide> // we need this to make sure size of hostname is not <ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { <ide> // First, make 100% sure that any "autoEscape" chars get <ide> // escaped, even if encodeURIComponent doesn't think they <ide> // need to be. <del> for (var i = 0, l = autoEscape.length; i < l; i++) { <add> for (let i = 0, l = autoEscape.length; i < l; i++) { <ide> var ae = autoEscape[i]; <ide> if (rest.indexOf(ae) === -1) <ide> continue; <ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { <ide> <ide> //to support http.request <ide> if (this.pathname || this.search) { <del> var p = this.pathname || ''; <del> var s = this.search || ''; <add> const p = this.pathname || ''; <add> const s = this.search || ''; <ide> this.path = p + s; <ide> } <ide> <ide> Url.prototype.resolveObject = function(relative) { <ide> if (!relative.host && <ide> !/^file:?$/.test(relative.protocol) && <ide> !hostlessProtocol[relative.protocol]) { <del> var relPath = (relative.pathname || '').split('/'); <add> const relPath = (relative.pathname || '').split('/'); <ide> while (relPath.length && !(relative.host = relPath.shift())); <ide> if (!relative.host) relative.host = ''; <ide> if (!relative.hostname) relative.hostname = ''; <ide> Url.prototype.resolveObject = function(relative) { <ide> var mustEndAbs = (isRelAbs || isSourceAbs || <ide> (result.host && relative.pathname)); <ide> const removeAllDots = mustEndAbs; <del> var srcPath = result.pathname && result.pathname.split('/') || []; <del> var relPath = relative.pathname && relative.pathname.split('/') || []; <add> let srcPath = result.pathname && result.pathname.split('/') || []; <add> const relPath = relative.pathname && relative.pathname.split('/') || []; <ide> const psychotic = result.protocol && !slashedProtocol[result.protocol]; <ide> <ide> // if the url is a non-slashed url, then relative <ide> Url.prototype.resolveObject = function(relative) { <ide> //occasionally the auth can get stuck only in host <ide> //this especially happens in cases like <ide> //url.resolveObject('mailto:local1@domain1', 'local2@domain2') <del> var authInHost = result.host && result.host.indexOf('@') > 0 ? <add> const authInHost = result.host && result.host.indexOf('@') > 0 ? <ide> result.host.split('@') : false; <ide> if (authInHost) { <ide> result.auth = authInHost.shift(); <ide> Url.prototype.resolveObject = function(relative) { <ide> // strip single dots, resolve double dots to parent dir <ide> // if the path tries to go above the root, `up` ends up > 0 <ide> var up = 0; <del> for (var i = srcPath.length; i >= 0; i--) { <add> for (let i = srcPath.length; i >= 0; i--) { <ide> last = srcPath[i]; <ide> if (last === '.') { <ide> spliceOne(srcPath, i); <ide> Url.prototype.resolveObject = function(relative) { <ide> //occasionally the auth can get stuck only in host <ide> //this especially happens in cases like <ide> //url.resolveObject('mailto:local1@domain1', 'local2@domain2') <del> var authInHost = result.host && result.host.indexOf('@') > 0 ? <add> const authInHost = result.host && result.host.indexOf('@') > 0 ? <ide> result.host.split('@') : false; <ide> if (authInHost) { <ide> result.auth = authInHost.shift();
1
Java
Java
add onsubscribe hook to parallelflowable operators
22c5e0bfe0ca9a68cd726d23fb696fe56a059a84
<ide><path>src/main/java/io/reactivex/rxjava3/core/Scheduler.java <ide> public abstract class Scheduler { <ide> /** <ide> * Value representing whether to use {@link System#nanoTime()}, or default as clock for {@link #now(TimeUnit)} <del> * and {@link Scheduler.Worker#now(TimeUnit)} <add> * and {@link Scheduler.Worker#now(TimeUnit)}. <ide> * <p> <ide> * Associated system parameter: <ide> * <ul> <ide> public abstract class Scheduler { <ide> * @throws NullPointerException if {@code unit} is {@code null} <ide> */ <ide> static long computeNow(TimeUnit unit) { <del> if(!IS_DRIFT_USE_NANOTIME) { <add> if (!IS_DRIFT_USE_NANOTIME) { <ide> return unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS); <ide> } <ide> return unit.convert(System.nanoTime(), TimeUnit.NANOSECONDS); <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelCollect.java <ide> public ParallelCollect(ParallelFlowable<? extends T> source, <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super C>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelConcatMap.java <ide> import io.reactivex.rxjava3.internal.operators.flowable.FlowableConcatMap; <ide> import io.reactivex.rxjava3.internal.util.ErrorMode; <ide> import io.reactivex.rxjava3.parallel.ParallelFlowable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <ide> <ide> import java.util.Objects; <ide> <ide> public int parallelism() { <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super R>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelDoOnNextTry.java <ide> public ParallelDoOnNextTry(ParallelFlowable<T> source, Consumer<? super T> onNex <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super T>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelFilter.java <ide> public ParallelFilter(ParallelFlowable<T> source, Predicate<? super T> predicate <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super T>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelFilterTry.java <ide> public ParallelFilterTry(ParallelFlowable<T> source, Predicate<? super T> predic <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super T>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelFlatMap.java <ide> import io.reactivex.rxjava3.functions.Function; <ide> import io.reactivex.rxjava3.internal.operators.flowable.FlowableFlatMap; <ide> import io.reactivex.rxjava3.parallel.ParallelFlowable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <ide> <ide> /** <ide> * Flattens the generated Publishers on each rail. <ide> public int parallelism() { <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super R>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelFlatMapIterable.java <ide> import io.reactivex.rxjava3.functions.Function; <ide> import io.reactivex.rxjava3.internal.operators.flowable.FlowableFlattenIterable; <ide> import io.reactivex.rxjava3.parallel.ParallelFlowable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <ide> <ide> /** <ide> * Flattens the generated {@link Iterable}s on each rail. <ide> public int parallelism() { <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super R>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelFromArray.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.rxjava3.parallel.ParallelFlowable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <ide> <ide> /** <ide> * Wraps multiple Publishers into a ParallelFlowable which runs them <ide> public int parallelism() { <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super T>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelFromPublisher.java <ide> import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper; <ide> import io.reactivex.rxjava3.internal.util.BackpressureHelper; <ide> import io.reactivex.rxjava3.parallel.ParallelFlowable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <ide> <ide> /** <ide> * Dispatches the values from upstream in a round robin fashion to subscribers which are <ide> public int parallelism() { <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super T>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelMap.java <ide> public ParallelMap(ParallelFlowable<T> source, Function<? super T, ? extends R> <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super R>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelMapTry.java <ide> public ParallelMapTry(ParallelFlowable<T> source, Function<? super T, ? extends <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super R>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelPeek.java <ide> public ParallelPeek(ParallelFlowable<T> source, <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super T>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelReduce.java <ide> public ParallelReduce(ParallelFlowable<? extends T> source, Supplier<R> initialS <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super R>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelRunOn.java <ide> public ParallelRunOn(ParallelFlowable<? extends T> parent, <ide> } <ide> <ide> @Override <del> public void subscribe(final Subscriber<? super T>[] subscribers) { <add> public void subscribe(Subscriber<? super T>[] subscribers) { <add> subscribers = RxJavaPlugins.onSubscribe(this, subscribers); <add> <ide> if (!validate(subscribers)) { <ide> return; <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/plugins/RxJavaPlugins.java <ide> public final class RxJavaPlugins { <ide> @Nullable <ide> static volatile BiFunction<? super Completable, ? super CompletableObserver, ? extends CompletableObserver> onCompletableSubscribe; <ide> <add> @SuppressWarnings("rawtypes") <add> @Nullable <add> static volatile BiFunction<? super ParallelFlowable, ? super Subscriber[], ? extends Subscriber[]> onParallelSubscribe; <add> <ide> @Nullable <ide> static volatile BooleanSupplier onBeforeBlocking; <ide> <ide> public static void reset() { <ide> setOnMaybeSubscribe(null); <ide> <ide> setOnParallelAssembly(null); <add> setOnParallelSubscribe(null); <ide> <ide> setFailOnNonBlockingScheduler(false); <ide> setOnBeforeBlocking(null); <ide> public static <T> MaybeObserver<? super T> onSubscribe(@NonNull Maybe<T> source, <ide> return observer; <ide> } <ide> <add> /** <add> * Calls the associated hook function. <add> * @param <T> the value type <add> * @param source the hook's input value <add> * @param subscribers the array of subscribers <add> * @return the value returned by the hook <add> */ <add> @SuppressWarnings({ "rawtypes" }) <add> @NonNull <add> public static <T> Subscriber<@NonNull ? super T>[] onSubscribe(@NonNull ParallelFlowable<T> source, @NonNull Subscriber<@NonNull ? super T>[] subscribers) { <add> BiFunction<? super ParallelFlowable, ? super Subscriber[], ? extends Subscriber[]> f = onParallelSubscribe; <add> if (f != null) { <add> return apply(f, source, subscribers); <add> } <add> return subscribers; <add> } <add> <ide> /** <ide> * Calls the associated hook function. <ide> * @param <T> the value type <ide> public static void setOnParallelAssembly(@Nullable Function<? super ParallelFlow <ide> return onParallelAssembly; <ide> } <ide> <add> /** <add> * Sets the specific hook function. <add> * @param handler the hook function to set, null allowed <add> * @since 3.0.11 - experimental <add> */ <add> @SuppressWarnings("rawtypes") <add> @Experimental <add> public static void setOnParallelSubscribe(@Nullable BiFunction<? super ParallelFlowable, ? super Subscriber[], ? extends Subscriber[]> handler) { <add> if (lockdown) { <add> throw new IllegalStateException("Plugins can't be changed anymore"); <add> } <add> onParallelSubscribe = handler; <add> } <add> <add> /** <add> * Returns the current hook function. <add> * @return the hook function, may be null <add> * @since 3.0.11 - experimental <add> */ <add> @SuppressWarnings("rawtypes") <add> @Experimental <add> @Nullable <add> public static BiFunction<? super ParallelFlowable, ? super Subscriber[], ? extends Subscriber[]> getOnParallelSubscribe() { <add> return onParallelSubscribe; <add> } <add> <ide> /** <ide> * Calls the associated hook function. <ide> * <p>History: 2.0.6 - experimental; 2.1 - beta <ide><path>src/test/java/io/reactivex/rxjava3/plugins/RxJavaPluginsTest.java <ide> public void onComplete() { <ide> .assertComplete(); <ide> } <ide> <add> @SuppressWarnings("rawtypes") <add> @Test <add> public void parallelFlowableStart() { <add> try { <add> RxJavaPlugins.setOnParallelSubscribe(new BiFunction<ParallelFlowable, Subscriber[], Subscriber[]>() { <add> @Override <add> public Subscriber[] apply(ParallelFlowable f, final Subscriber[] t) { <add> return new Subscriber[] { new Subscriber() { <add> <add> @Override <add> public void onSubscribe(Subscription s) { <add> t[0].onSubscribe(s); <add> } <add> <add> @SuppressWarnings("unchecked") <add> @Override <add> public void onNext(Object value) { <add> t[0].onNext((Integer)value - 9); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> t[0].onError(e); <add> } <add> <add> @Override <add> public void onComplete() { <add> t[0].onComplete(); <add> } <add> <add> } <add> }; <add> } <add> }); <add> <add> Flowable.range(10, 3) <add> .parallel(1) <add> .sequential() <add> .test() <add> .assertValues(1, 2, 3) <add> .assertNoErrors() <add> .assertComplete(); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> // make sure the reset worked <add> Flowable.range(10, 3) <add> .parallel(1) <add> .sequential() <add> .test() <add> .assertValues(10, 11, 12) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <ide> @SuppressWarnings("rawtypes") <ide> @Test <ide> public void singleCreate() { <ide> public void onComplete() { <ide> } <ide> <ide> AllSubscriber all = new AllSubscriber(); <add> Subscriber[] allArray = { all }; <ide> <ide> assertNull(RxJavaPlugins.onSubscribe(Observable.never(), null)); <ide> <ide> public void onComplete() { <ide> <ide> assertSame(all, RxJavaPlugins.onSubscribe(Maybe.never(), all)); <ide> <add> assertNull(RxJavaPlugins.onSubscribe(Flowable.never().parallel(), null)); <add> <add> assertSame(allArray, RxJavaPlugins.onSubscribe(Flowable.never().parallel(), allArray)); <add> <ide> final Scheduler s = ImmediateThinScheduler.INSTANCE; <ide> Supplier<Scheduler> c = new Supplier<Scheduler>() { <ide> @Override
17
Javascript
Javascript
use const in secondary_toolbar.js
5ea91273918423d844475a52d16924f5eafb2869
<ide><path>web/secondary_toolbar.js <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add>/* eslint no-var: error, prefer-const: error */ <ide> <ide> import { SCROLLBAR_PADDING, ScrollMode, SpreadMode } from './ui_utils'; <ide> import { CursorTool } from './pdf_cursor_tools'; <ide> class SecondaryToolbar { <ide> for (const { element, eventName, close, eventDetails, } of this.buttons) { <ide> element.addEventListener('click', (evt) => { <ide> if (eventName !== null) { <del> let details = { source: this, }; <del> for (let property in eventDetails) { <add> const details = { source: this, }; <add> for (const property in eventDetails) { <ide> details[property] = eventDetails[property]; <ide> } <ide> this.eventBus.dispatch(eventName, details);
1
PHP
PHP
add support for persistent smtp connections
1879c3f8a7ed2ce34398defff664c9e5bf666aa3
<ide><path>src/Network/Email/SmtpTransport.php <ide> class SmtpTransport extends AbstractTransport { <ide> 'username' => null, <ide> 'password' => null, <ide> 'client' => null, <del> 'tls' => false <add> 'tls' => false, <add> 'autoDisconnect' => true, <add> 'keepAlive' => false <ide> ]; <ide> <ide> /** <ide> class SmtpTransport extends AbstractTransport { <ide> */ <ide> protected $_lastResponse = array(); <ide> <add>/** <add> * Destructor <add> * <add> * Tries to disconnect in case `autoDisconnect` is enabled. <add> */ <add> public function __destruct() { <add> try { <add> if ($this->_config['autoDisconnect']) { <add> $this->disconnect(); <add> } <add> } <add> catch (\Exception $e) { // avoid fatal error on script termination <add> } <add> } <add> <add>/** <add> * Connect to the SMTP server. <add> * <add> * This method tries to connect only in case there is no open <add> * connection available already. <add> * <add> * @return void <add> */ <add> public function connect() { <add> if (!$this->connected()) { <add> $this->_connect(); <add> } <add> } <add> <add>/** <add> * Check whether an open connection to the SMTP server is available. <add> * <add> * @return bool <add> */ <add> public function connected() { <add> return $this->_socket !== null && $this->_socket->connected; <add> } <add> <add>/** <add> * Disconnect from the SMTP server. <add> * <add> * This method tries to disconnect only in case there is an open <add> * connection available. <add> * <add> * @return void <add> */ <add> public function disconnect() { <add> if ($this->connected()) { <add> $this->_disconnect(); <add> } <add> } <add> <ide> /** <ide> * Returns the response of the last sent SMTP command. <ide> * <ide> public function getLastResponse() { <ide> public function send(Email $email) { <ide> $this->_cakeEmail = $email; <ide> <del> $this->_connect(); <del> $this->_auth(); <add> if (!$this->connected()) { <add> $this->_connect(); <add> $this->_auth(); <add> } else { <add> $this->_smtpSend('RSET'); <add> } <add> <ide> $this->_sendRcpt(); <ide> $this->_sendData(); <del> $this->_disconnect(); <add> <add> if (!$this->_config['keepAlive']) { <add> $this->_disconnect(); <add> } <ide> <ide> return $this->_content; <ide> } <ide> protected function _smtpSend($data, $checkCode = '250') { <ide> } <ide> } <ide> <del>} <add>} <ide>\ No newline at end of file <ide><path>tests/TestCase/Network/Email/SmtpTransportTest.php <ide> public function testSendData() { <ide> */ <ide> public function testQuit() { <ide> $this->socket->expects($this->at(0))->method('write')->with("QUIT\r\n"); <add> $this->socket->connected = true; <ide> $this->SmtpTransport->disconnect(); <ide> } <ide> <ide> public function testBufferResponseLines() { <ide> $result = $this->SmtpTransport->getLastResponse(); <ide> $this->assertEquals($expected, $result); <ide> } <add> <add>/** <add> * testAutoDisconnect method <add> * <add> * @return void <add> */ <add> public function testAutoDisconnect() { <add> $this->SmtpTransport->config(array('autoDisconnect' => true)); <add> $this->socket->expects($this->at(0))->method('write')->with("QUIT\r\n"); <add> $this->socket->connected = true; <add> unset($this->SmtpTransport); <add> } <add> <add>/** <add> * testKeepAlive method <add> * <add> * @return void <add> */ <add> public function testKeepAlive() { <add> $this->SmtpTransport->config(array('keepAlive' => true, 'autoDisconnect' => false)); <add> <add> $email = $this->getMock('Cake\Network\Email\Email', array('message')); <add> $email->from('noreply@cakephp.org', 'CakePHP Test'); <add> $email->to('cake@cakephp.org', 'CakePHP'); <add> $email->messageID('<4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>'); <add> $email->subject('Testing SMTP'); <add> $date = date(DATE_RFC2822); <add> $email->setHeaders(array('X-Mailer' => Email::EMAIL_CLIENT, 'Date' => $date)); <add> $email->expects($this->exactly(2)) <add> ->method('message') <add> ->will($this->returnValue(array('First Line', 'Second Line', '.Third Line', ''))); <add> <add> $data = "From: CakePHP Test <noreply@cakephp.org>\r\n"; <add> $data .= "To: CakePHP <cake@cakephp.org>\r\n"; <add> $data .= "X-Mailer: CakePHP Email\r\n"; <add> $data .= "Date: " . $date . "\r\n"; <add> $data .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>\r\n"; <add> $data .= "Subject: Testing SMTP\r\n"; <add> $data .= "MIME-Version: 1.0\r\n"; <add> $data .= "Content-Type: text/plain; charset=UTF-8\r\n"; <add> $data .= "Content-Transfer-Encoding: 8bit\r\n"; <add> $data .= "\r\n"; <add> $data .= "First Line\r\n"; <add> $data .= "Second Line\r\n"; <add> $data .= "..Third Line\r\n"; // RFC5321 4.5.2.Transparency <add> $data .= "\r\n"; <add> $data .= "\r\n\r\n.\r\n"; <add> <add> $this->socket->expects($this->never())->method('disconnect'); <add> <add> $this->socket->expects($this->at(0))->method('connect')->will($this->returnValue(true)); <add> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(2))->method('read')->will($this->returnValue("220 Welcome message\r\n")); <add> $this->socket->expects($this->at(3))->method('write')->with("EHLO localhost\r\n"); <add> $this->socket->expects($this->at(4))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250 OK\r\n")); <add> <add> $this->socket->expects($this->at(6))->method('write')->with("MAIL FROM:<noreply@cakephp.org>\r\n"); <add> $this->socket->expects($this->at(7))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(8))->method('read')->will($this->returnValue("250 OK\r\n")); <add> $this->socket->expects($this->at(9))->method('write')->with("RCPT TO:<cake@cakephp.org>\r\n"); <add> $this->socket->expects($this->at(10))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(11))->method('read')->will($this->returnValue("250 OK\r\n")); <add> <add> $this->socket->expects($this->at(12))->method('write')->with("DATA\r\n"); <add> $this->socket->expects($this->at(13))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(14))->method('read')->will($this->returnValue("354 OK\r\n")); <add> $this->socket->expects($this->at(15))->method('write')->with($data); <add> $this->socket->expects($this->at(16))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(17))->method('read')->will($this->returnValue("250 OK\r\n")); <add> <add> $this->socket->expects($this->at(18))->method('write')->with("RSET\r\n"); <add> $this->socket->expects($this->at(19))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(20))->method('read')->will($this->returnValue("250 OK\r\n")); <add> <add> $this->socket->expects($this->at(21))->method('write')->with("MAIL FROM:<noreply@cakephp.org>\r\n"); <add> $this->socket->expects($this->at(22))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(23))->method('read')->will($this->returnValue("250 OK\r\n")); <add> $this->socket->expects($this->at(24))->method('write')->with("RCPT TO:<cake@cakephp.org>\r\n"); <add> $this->socket->expects($this->at(25))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(26))->method('read')->will($this->returnValue("250 OK\r\n")); <add> <add> $this->socket->expects($this->at(27))->method('write')->with("DATA\r\n"); <add> $this->socket->expects($this->at(28))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(29))->method('read')->will($this->returnValue("354 OK\r\n")); <add> $this->socket->expects($this->at(30))->method('write')->with($data); <add> $this->socket->expects($this->at(31))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(32))->method('read')->will($this->returnValue("250 OK\r\n")); <add> <add> $this->SmtpTransport->send($email); <add> $this->socket->connected = true; <add> $this->SmtpTransport->send($email); <add> } <add> <add>/** <add> * testSendDefaults method <add> * <add> * @return void <add> */ <add> public function testSendDefaults() { <add> $email = $this->getMock('Cake\Network\Email\Email', array('message')); <add> $email->from('noreply@cakephp.org', 'CakePHP Test'); <add> $email->to('cake@cakephp.org', 'CakePHP'); <add> $email->messageID('<4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>'); <add> $email->subject('Testing SMTP'); <add> $date = date(DATE_RFC2822); <add> $email->setHeaders(array('X-Mailer' => Email::EMAIL_CLIENT, 'Date' => $date)); <add> $email->expects($this->once()) <add> ->method('message') <add> ->will($this->returnValue(array('First Line', 'Second Line', '.Third Line', ''))); <add> <add> $data = "From: CakePHP Test <noreply@cakephp.org>\r\n"; <add> $data .= "To: CakePHP <cake@cakephp.org>\r\n"; <add> $data .= "X-Mailer: CakePHP Email\r\n"; <add> $data .= "Date: " . $date . "\r\n"; <add> $data .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>\r\n"; <add> $data .= "Subject: Testing SMTP\r\n"; <add> $data .= "MIME-Version: 1.0\r\n"; <add> $data .= "Content-Type: text/plain; charset=UTF-8\r\n"; <add> $data .= "Content-Transfer-Encoding: 8bit\r\n"; <add> $data .= "\r\n"; <add> $data .= "First Line\r\n"; <add> $data .= "Second Line\r\n"; <add> $data .= "..Third Line\r\n"; // RFC5321 4.5.2.Transparency <add> $data .= "\r\n"; <add> $data .= "\r\n\r\n.\r\n"; <add> <add> $this->socket->expects($this->at(0))->method('connect')->will($this->returnValue(true)); <add> <add> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(2))->method('read')->will($this->returnValue("220 Welcome message\r\n")); <add> $this->socket->expects($this->at(3))->method('write')->with("EHLO localhost\r\n"); <add> $this->socket->expects($this->at(4))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250 OK\r\n")); <add> <add> $this->socket->expects($this->at(6))->method('write')->with("MAIL FROM:<noreply@cakephp.org>\r\n"); <add> $this->socket->expects($this->at(7))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(8))->method('read')->will($this->returnValue("250 OK\r\n")); <add> $this->socket->expects($this->at(9))->method('write')->with("RCPT TO:<cake@cakephp.org>\r\n"); <add> $this->socket->expects($this->at(10))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(11))->method('read')->will($this->returnValue("250 OK\r\n")); <add> <add> $this->socket->expects($this->at(12))->method('write')->with("DATA\r\n"); <add> $this->socket->expects($this->at(13))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(14))->method('read')->will($this->returnValue("354 OK\r\n")); <add> $this->socket->expects($this->at(15))->method('write')->with($data); <add> $this->socket->expects($this->at(16))->method('read')->will($this->returnValue(false)); <add> $this->socket->expects($this->at(17))->method('read')->will($this->returnValue("250 OK\r\n")); <add> <add> $this->socket->expects($this->at(18))->method('disconnect'); <add> <add> $this->SmtpTransport->send($email); <add> } <ide> }
2
PHP
PHP
use array values first
00e9ed76483ea6ad1264676e7b1095b23e16a433
<ide><path>src/Illuminate/Database/Eloquent/Collection.php <ide> public function getQueueableRelations() <ide> if (count($relations) === 0 || $relations === [[]]) { <ide> return []; <ide> } elseif (count($relations) === 1) { <del> return $relations[0]; <add> return array_values($relations)[0]; <ide> } else { <ide> return array_intersect(...$relations); <ide> }
1
Java
Java
add flushing support
aeb35787d7214f5f9d0636cce19105dec2a53193
<ide><path>spring-web-reactive/src/main/java/org/springframework/core/io/buffer/FlushingDataBuffer.java <add>/* <add> * Copyright 2002-2016 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.core.io.buffer; <add> <add>import java.io.InputStream; <add>import java.io.OutputStream; <add>import java.nio.ByteBuffer; <add>import java.util.function.IntPredicate; <add> <add>import org.springframework.util.Assert; <add> <add>/** <add> * {@link DataBuffer} wrapper that indicates the file or the socket writing this buffer <add> * should be flushed. <add> * <add> * @author Sebastien Deleuze <add> */ <add>public class FlushingDataBuffer implements DataBuffer { <add> <add> private final DataBuffer buffer; <add> <add> public FlushingDataBuffer(DataBuffer buffer) { <add> Assert.notNull(buffer); <add> this.buffer = buffer; <add> } <add> <add> @Override <add> public DataBufferFactory factory() { <add> return this.buffer.factory(); <add> } <add> <add> @Override <add> public int indexOf(IntPredicate predicate, int fromIndex) { <add> return this.buffer.indexOf(predicate, fromIndex); <add> } <add> <add> @Override <add> public int lastIndexOf(IntPredicate predicate, int fromIndex) { <add> return this.buffer.lastIndexOf(predicate, fromIndex); <add> } <add> <add> @Override <add> public int readableByteCount() { <add> return this.buffer.readableByteCount(); <add> } <add> <add> @Override <add> public byte read() { <add> return this.buffer.read(); <add> } <add> <add> @Override <add> public DataBuffer read(byte[] destination) { <add> return this.buffer.read(destination); <add> } <add> <add> @Override <add> public DataBuffer read(byte[] destination, int offset, int length) { <add> return this.buffer.read(destination, offset, length); <add> } <add> <add> @Override <add> public DataBuffer write(byte b) { <add> return this.buffer.write(b); <add> } <add> <add> @Override <add> public DataBuffer write(byte[] source) { <add> return this.buffer.write(source); <add> } <add> <add> @Override <add> public DataBuffer write(byte[] source, int offset, int length) { <add> return this.write(source, offset, length); <add> } <add> <add> @Override <add> public DataBuffer write(DataBuffer... buffers) { <add> return this.buffer.write(buffers); <add> } <add> <add> @Override <add> public DataBuffer write(ByteBuffer... buffers) { <add> return this.buffer.write(buffers); <add> } <add> <add> @Override <add> public DataBuffer slice(int index, int length) { <add> return this.buffer.slice(index, length); <add> } <add> <add> @Override <add> public ByteBuffer asByteBuffer() { <add> return this.buffer.asByteBuffer(); <add> } <add> <add> @Override <add> public InputStream asInputStream() { <add> return this.buffer.asInputStream(); <add> } <add> <add> @Override <add> public OutputStream asOutputStream() { <add> return this.buffer.asOutputStream(); <add> } <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/http/ReactiveHttpOutputMessage.java <ide> <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferFactory; <add>import org.springframework.core.io.buffer.FlushingDataBuffer; <ide> <ide> /** <ide> * A "reactive" HTTP output message that accepts output as a {@link Publisher}. <ide> public interface ReactiveHttpOutputMessage extends HttpMessage { <ide> * flushed before depending on the configuration, the HTTP engine and the amount of <ide> * data sent). <ide> * <add> * <p>Each {@link FlushingDataBuffer} element will trigger a flush. <add> * <ide> * @param body the body content publisher <ide> * @return a publisher that indicates completion or error. <ide> */ <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpResponse.java <ide> <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferFactory; <add>import org.springframework.core.io.buffer.FlushingDataBuffer; <ide> import org.springframework.core.io.buffer.NettyDataBuffer; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.http.ResponseCookie; <ide> public void setStatusCode(HttpStatus status) { <ide> <ide> @Override <ide> protected Mono<Void> writeWithInternal(Publisher<DataBuffer> publisher) { <del> return this.channel.send(Flux.from(publisher).map(this::toByteBuf)); <add> return Flux.from(publisher) <add> .window() <add> .concatMap(w -> this.channel.send(w <add> .takeUntil(db -> db instanceof FlushingDataBuffer) <add> .map(this::toByteBuf))) <add> .then(); <ide> } <ide> <ide> @Override <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/RxNettyServerHttpResponse.java <ide> package org.springframework.http.server.reactive; <ide> <ide> import io.netty.buffer.ByteBuf; <add>import io.netty.buffer.CompositeByteBuf; <ide> import io.netty.buffer.Unpooled; <ide> import io.netty.handler.codec.http.HttpResponseStatus; <ide> import io.netty.handler.codec.http.cookie.Cookie; <ide> import rx.Observable; <ide> <ide> import org.springframework.core.io.buffer.DataBuffer; <add>import org.springframework.core.io.buffer.FlushingDataBuffer; <ide> import org.springframework.core.io.buffer.NettyDataBuffer; <ide> import org.springframework.core.io.buffer.NettyDataBufferFactory; <ide> import org.springframework.http.HttpStatus; <ide> public void setStatusCode(HttpStatus status) { <ide> } <ide> <ide> @Override <del> protected Mono<Void> writeWithInternal(Publisher<DataBuffer> publisher) { <del> Observable<ByteBuf> content = <del> RxJava1ObservableConverter.from(publisher).map(this::toByteBuf); <del> Observable<Void> completion = this.response.write(content); <del> return RxJava1ObservableConverter.from(completion).then(); <add> protected Mono<Void> writeWithInternal(Publisher<DataBuffer> body) { <add> Observable<ByteBuf> content = RxJava1ObservableConverter.from(body).map(this::toByteBuf); <add> return RxJava1ObservableConverter.from(this.response.write(content, bb -> bb instanceof FlushingByteBuf)).then(); <ide> } <ide> <ide> private ByteBuf toByteBuf(DataBuffer buffer) { <del> if (buffer instanceof NettyDataBuffer) { <del> return ((NettyDataBuffer) buffer).getNativeBuffer(); <del> } <del> else { <del> return Unpooled.wrappedBuffer(buffer.asByteBuffer()); <del> } <add> ByteBuf byteBuf = (buffer instanceof NettyDataBuffer ? ((NettyDataBuffer) buffer).getNativeBuffer() : Unpooled.wrappedBuffer(buffer.asByteBuffer())); <add> return (buffer instanceof FlushingDataBuffer ? new FlushingByteBuf(byteBuf) : byteBuf); <ide> } <ide> <ide> @Override <ide> protected void writeCookies() { <ide> } <ide> } <ide> <add> private class FlushingByteBuf extends CompositeByteBuf { <add> <add> public FlushingByteBuf(ByteBuf byteBuf) { <add> super(byteBuf.alloc(), byteBuf.isDirect(), 1); <add> this.addComponent(true, byteBuf); <add> } <add> } <add> <ide> /* <ide> While the underlying implementation of {@link ZeroCopyHttpOutputMessage} seems to <ide> work; it does bypass {@link #applyBeforeCommit} and more importantly it doesn't change <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferFactory; <ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory; <add>import org.springframework.core.io.buffer.FlushingDataBuffer; <ide> import org.springframework.core.io.buffer.support.DataBufferUtils; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.util.Assert; <ide> public void onWritePossible() throws IOException { <ide> <ide> logger.trace("written: " + written + " total: " + total); <ide> if (written == total) { <add> if (dataBuffer instanceof FlushingDataBuffer) { <add> flush(output); <add> } <ide> releaseBuffer(); <ide> if (!completed) { <ide> subscription.request(1); <ide> private int writeDataBuffer() throws IOException { <ide> return bytesWritten; <ide> } <ide> <add> private void flush(ServletOutputStream output) { <add> if (output.isReady()) { <add> logger.trace("Flushing"); <add> try { <add> output.flush(); <add> } <add> catch (IOException ignored) { <add> } <add> } <add> } <add> <ide> private void releaseBuffer() { <ide> DataBufferUtils.release(dataBuffer); <ide> dataBuffer = null; <ide> public void onError(Throwable ex) { <ide> } <ide> } <ide> <del>} <add>} <ide>\ No newline at end of file <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/UndertowHttpHandlerAdapter.java <ide> <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferFactory; <add>import org.springframework.core.io.buffer.FlushingDataBuffer; <add>import org.springframework.core.io.buffer.support.DataBufferUtils; <ide> import org.springframework.util.Assert; <ide> <ide> /** <ide> private static class ResponseBodySubscriber implements Subscriber<DataBuffer> { <ide> <ide> private volatile ByteBuffer byteBuffer; <ide> <add> private volatile DataBuffer dataBuffer; <add> <ide> private volatile boolean completed = false; <ide> <ide> private Subscription subscription; <ide> public void onNext(DataBuffer dataBuffer) { <ide> logger.trace("onNext. buffer: " + dataBuffer); <ide> <ide> this.byteBuffer = dataBuffer.asByteBuffer(); <add> this.dataBuffer = dataBuffer; <ide> } <ide> <ide> @Override <ide> private void closeChannel(StreamSinkChannel channel) { <ide> } <ide> } <ide> catch (IOException ignored) { <del> logger.error(ignored, ignored); <del> <ide> } <ide> } <ide> <ide> public void handleEvent(StreamSinkChannel channel) { <ide> logger.trace("written: " + written + " total: " + total); <ide> <ide> if (written == total) { <add> if (dataBuffer instanceof FlushingDataBuffer) { <add> flush(channel); <add> } <ide> releaseBuffer(); <ide> if (!completed) { <ide> subscription.request(1); <ide> else if (subscription != null) { <ide> <ide> } <ide> <del> private void releaseBuffer() { <del> byteBuffer = null; <del> <del> } <del> <ide> private int writeByteBuffer(StreamSinkChannel channel) throws IOException { <ide> int written; <ide> int totalWritten = 0; <ide> private int writeByteBuffer(StreamSinkChannel channel) throws IOException { <ide> return totalWritten; <ide> } <ide> <add> private void flush(StreamSinkChannel channel) throws IOException { <add> logger.trace("Flushing"); <add> channel.flush(); <add> } <add> <add> private void releaseBuffer() { <add> DataBufferUtils.release(dataBuffer); <add> dataBuffer = null; <add> byteBuffer = null; <add> } <add> <ide> } <ide> <ide> } <ide> <del>} <add>} <ide>\ No newline at end of file <ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/reactive/FlushingIntegrationTests.java <add>/* <add> * Copyright 2002-2016 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.http.server.reactive; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import static org.springframework.web.client.reactive.HttpRequestBuilders.get; <add>import static org.springframework.web.client.reactive.WebResponseExtractors.bodyStream; <add>import reactor.core.publisher.Flux; <add>import reactor.core.publisher.Mono; <add>import reactor.core.test.TestSubscriber; <add> <add>import org.springframework.core.io.buffer.DataBuffer; <add>import org.springframework.core.io.buffer.FlushingDataBuffer; <add>import org.springframework.http.client.reactive.ReactorHttpClientRequestFactory; <add>import org.springframework.web.client.reactive.WebClient; <add> <add>/** <add> * @author Sebastien Deleuze <add> */ <add>public class FlushingIntegrationTests extends AbstractHttpHandlerIntegrationTests { <add> <add> private WebClient webClient; <add> <add> @Before <add> public void setup() throws Exception { <add> super.setup(); <add> this.webClient = new WebClient(new ReactorHttpClientRequestFactory()); <add> } <add> <add> @Test <add> public void testFlushing() throws Exception { <add> Mono<String> result = this.webClient <add> .perform(get("http://localhost:" + port)) <add> .extract(bodyStream(String.class)) <add> .take(2) <add> .reduce((s1, s2) -> s1 + s2); <add> <add> TestSubscriber <add> .subscribe(result) <add> .await() <add> .assertValues("data0data1"); <add> } <add> <add> <add> @Override <add> protected HttpHandler createHttpHandler() { <add> return new FlushingHandler(); <add> } <add> <add> private static class FlushingHandler implements HttpHandler { <add> <add> @Override <add> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { <add> Flux<DataBuffer> responseBody = Flux <add> .interval(50) <add> .take(2) <add> .concatWith(Flux.never()) <add> .map(l -> { <add> byte[] data = ("data" + l).getBytes(); <add> DataBuffer buffer = response.bufferFactory().allocateBuffer(data.length); <add> buffer.write(data); <add> return new FlushingDataBuffer(buffer); <add> }); <add> return response.writeWith(responseBody); <add> } <add> } <add>}
7