content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
remove callback thereby stripping js comments
1c65d5d34ac2e9d054a11df7c3f9304f62ba6388
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/declare-a-read-only-variable-with-the-const-keyword.md <ide> Change the code so that all variables are declared using `let` or `const`. Use ` <ide> `var` should not exist in your code. <ide> <ide> ```js <del>(getUserInput) => assert(!getUserInput('index').match(/var/g)); <add>assert.notMatch(code, /var/g); <ide> ``` <ide> <ide> You should change `fCC` to all uppercase. <ide> <ide> ```js <del>(getUserInput) => { <del> assert(getUserInput('index').match(/(FCC)/)); <del> assert(!getUserInput('index').match(/fCC/)); <del>} <add>assert.match(code, /(FCC)/); <add>assert.notMatch(code, /(fCC)/); <ide> ``` <ide> <ide> `FCC` should be a constant variable declared with `const`. <ide> assert.match(code, /const\s+FCC/); <ide> `fact` should be declared with `let`. <ide> <ide> ```js <del>(getUserInput) => assert(getUserInput('index').match(/(let fact)/g)); <add>assert.match(code, /(let\s+fact)/g); <ide> ``` <ide> <ide> `console.log` should be changed to print the `FCC` and `fact` variables. <ide> <ide> ```js <del>(getUserInput) => <del> assert(getUserInput('index').match(/console\.log\(\s*FCC\s*\,\s*fact\s*\)\s*;?/g)); <add>assert.match(code, /console\.log\(\s*FCC\s*\,\s*fact\s*\)\s*;?/g); <ide> ``` <ide> <ide> # --seed-- <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/explore-differences-between-the-var-and-let-keywords.md <ide> Update the code so it only uses the `let` keyword. <ide> `var` should not exist in the code. <ide> <ide> ```js <del>(getUserInput) => assert(!getUserInput('index').match(/var/g)); <add>assert.notMatch(code, /var/g); <ide> ``` <ide> <ide> `catName` should be the string `Oliver`. <ide> <ide> ```js <del>assert(catName === 'Oliver'); <add>assert.equal(catName, 'Oliver'); <ide> ``` <ide> <ide> `catSound` should be the string `Meow!` <ide> <ide> ```js <del>assert(catSound === 'Meow!'); <add>assert.equal(catSound, 'Meow!'); <ide> ``` <ide> <ide> # --seed--
2
Javascript
Javascript
fix handling of asterisk in sni context
f572b91c3ea71e6854cb699ae728a320662bc261
<ide><path>lib/_tls_wrap.js <ide> Server.prototype.addContext = function(servername, credentials) { <ide> <ide> var re = new RegExp('^' + <ide> servername.replace(/([\.^$+?\-\\[\]{}])/g, '\\$1') <del> .replace(/\*/g, '.*') + <add> .replace(/\*/g, '[^\.]*') + <ide> '$'); <ide> this._contexts.push([re, crypto.createCredentials(credentials).context]); <ide> }; <ide><path>test/simple/test-tls-sni-server-client.js <ide> var clientsOptions = [{ <ide> ca: [loadPEM('ca1-cert')], <ide> servername: 'a.example.com', <ide> rejectUnauthorized: false <del>},{ <add>}, { <ide> port: serverPort, <ide> key: loadPEM('agent2-key'), <ide> cert: loadPEM('agent2-cert'), <ide> ca: [loadPEM('ca2-cert')], <ide> servername: 'b.test.com', <ide> rejectUnauthorized: false <del>},{ <add>}, { <add> port: serverPort, <add> key: loadPEM('agent2-key'), <add> cert: loadPEM('agent2-cert'), <add> ca: [loadPEM('ca2-cert')], <add> servername: 'a.b.test.com', <add> rejectUnauthorized: false <add>}, { <ide> port: serverPort, <ide> key: loadPEM('agent3-key'), <ide> cert: loadPEM('agent3-cert'), <ide> server.addContext('*.test.com', SNIContexts['asterisk.test.com']); <ide> server.listen(serverPort, startTest); <ide> <ide> function startTest() { <del> function connectClient(options, callback) { <add> var i = 0; <add> function start() { <add> // No options left <add> if (i === clientsOptions.length) <add> return server.close(); <add> <add> var options = clientsOptions[i++]; <ide> var client = tls.connect(options, function() { <ide> clientResults.push( <ide> client.authorizationError && <ide> /Hostname\/IP doesn't/.test(client.authorizationError)); <ide> client.destroy(); <ide> <del> callback(); <add> // Continue <add> start(); <ide> }); <ide> }; <ide> <del> connectClient(clientsOptions[0], function() { <del> connectClient(clientsOptions[1], function() { <del> connectClient(clientsOptions[2], function() { <del> server.close(); <del> }); <del> }); <del> }); <add> start(); <ide> } <ide> <ide> process.on('exit', function() { <ide> assert.deepEqual(serverResults, ['a.example.com', 'b.test.com', <del> 'c.wrong.com']); <del> assert.deepEqual(clientResults, [true, true, false]); <add> 'a.b.test.com', 'c.wrong.com']); <add> assert.deepEqual(clientResults, [true, true, false, false]); <ide> });
2
Text
Text
add some faq entries
53cbfc62226255e2435cde10624bcafb54502fbb
<ide><path>docs/guides/faq.md <ide> * [Q: Can Video.js be required in node.js?](#q-can-videojs-be-required-in-nodejs) <ide> * [Q: Does Video.js work with webpack?](#q-does-videojs-work-with-webpack) <ide> * [Q: Does Video.js work with react?](#q-does-videojs-work-with-react) <add>* [Q: Can the big play button be centered?](#q-can-the-big-play-button-be-centered) <add>* [Q: Can the big play button be shown when paused?](#q-can-the-big-play-button-be-shown-when-paused) <add>* [Q: Why is the picture-in-picture button different in Firefox?](#q-why-is-the-picture-in-picture-button-different-in-firefox) <ide> <ide> ## Q: What is Video.js? <ide> <ide> Yes! See the [Webpack and Video.js configuration guide][webpack-guide]. <ide> <ide> Yes! See [ReactJS integration example][react-guide]. <ide> <add>## Q: Can the big play button be centered? <add> <add>The default skin offsets the button to not obscure the poster image, but just add a `vjs-big-play-centered` class to the player to have it centred. <add> <add>## Q: Can the big play button be shown when paused? <add> <add>Add a `vjs-show-big-play-button-on-pause` class to the player to display the button when paused. <add> <add>## Q: Why is the picture-in-picture button different in Firefox? <add> <add>Firefox does not support the HTML video Picture-in-Picture (PIP) API, so it is not possible to have a custom button in the Video.js controls. Firefox has its own overlay PIP button, and its [own logic for whether to display it][firefox-pip]. <add> <ide> [ads]: https://github.com/videojs/videojs-contrib-ads <ide> <ide> [audio-tracks]: /docs/guides/audio-tracks.md <ide> Yes! See [ReactJS integration example][react-guide]. <ide> <ide> [eme]: https://github.com/videojs/videojs-contrib-eme <ide> <add>[firefox-pip]: https://firefox-source-docs.mozilla.org/toolkit/components/pictureinpicture/pictureinpicture/index.html#the-picture-in-picture-toggle <add> <ide> [flash-eol]: https://www.adobe.com/products/flashplayer/end-of-life.html <ide> <ide> [generator]: https://github.com/videojs/generator-videojs-plugin <ide><path>docs/guides/troubleshooting.md <ide> * [Problems with playback](#problems-with-playback) <ide> * [Video.js Errors](#videojs-errors) <ide> * [vdata123456 errors](#vdata123456-errors) <add>* [Problems with setup options](#problems-with-setup-options) <ide> <ide> ## Problems with media formats <ide> <ide> a component. <ide> <ide> To fix this issue please make sure that all event listeners are cleaned up on dispose. <ide> <add>## Problems with setup options <add> <add>If a player is inititalized without the expected setup options, it's usually because of using both the `data-setup` attribute and the `videojs()` constructor. Take this example: <add> <add>```html <add><video-js id="my_video" data-setup='{"autoplay": "any"}'></video-js> <add> <add><script> <add> const myPlayer = videojs('my_video'); <add></script> <add>``` <add> <add>Here you might expect the player to be initialized with the `autoplay` option set, but it will not be. While Video.js sets up player embeds that have a `data-setup` attribute automatically when the page is loaded, in this case the player will have _already been setup_ in the script tag. The `data-setup` option will never be applied. <add> <add>This can be more confusing if `videojs('my_video')` is used in an async script as different behavior will occur depending on when the script is executed. <add> <add>It's better to not use `data-setup` and use the `videojs()` constructor once to set up the player, and/or only use the explicit getter `videojs.getPlayer('my_video')` to get a player reference. <add> <ide> [hosting-media]: #problems-when-hosting-media <ide> <ide> [text-tracks]: /docs/guides/text-tracks.md
2
Python
Python
prevent sequential scan of task instance table
cfc0d6c1113e70e9591c369920e5f750fab13459
<ide><path>airflow/models/dag.py <ide> def clear( <ide> conditions = [] <ide> for dag in self.subdags + [self]: <ide> conditions.append( <del> TI.dag_id.like(dag.dag_id) & <add> (TI.dag_id == dag.dag_id) & <ide> TI.task_id.in_(dag.task_ids) <ide> ) <ide> tis = tis.filter(or_(*conditions))
1
PHP
PHP
enable strict files for test files
77a2488bcdcb981fc03fdf40d47ea72b82a3175c
<ide><path>tests/TestCase/Http/ActionDispatcherTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/BaseApplicationTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/ClientTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/ControllerFactoryTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide><path>tests/TestCase/Http/Cookie/CookieTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide><path>tests/TestCase/Http/CorsBuilderTest.php <ide> <?php <add>declare(strict_types=1); <ide> namespace Cake\Test\TestCase\Http; <ide> <ide> use Cake\Http\CorsBuilder; <ide><path>tests/TestCase/Http/MiddlewareQueueTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/ResponseEmitterTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/ResponseTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function testWithStringBody() <ide> $this->assertNotSame($response, $newResponse); <ide> <ide> $response = new Response(); <del> $newResponse = $response->withStringBody(1337); <add> $newResponse = $response->withStringBody('1337'); <ide> $body = $newResponse->getBody(); <ide> $this->assertSame('1337', (string)$body); <ide> $this->assertNotSame($response, $newResponse); <ide><path>tests/TestCase/Http/RunnerTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/ServerRequestFactoryTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/ServerRequestTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function testIsSsl() <ide> { <ide> $request = new ServerRequest(); <ide> <del> $request = $request->withEnv('HTTPS', 1); <del> $this->assertTrue($request->is('ssl')); <del> <ide> $request = $request->withEnv('HTTPS', 'on'); <ide> $this->assertTrue($request->is('ssl')); <ide> <ide> public function testIsSsl() <ide> $request = $request->withEnv('HTTPS', 'off'); <ide> $this->assertFalse($request->is('ssl')); <ide> <del> $request = $request->withEnv('HTTPS', false); <del> $this->assertFalse($request->is('ssl')); <del> <ide> $request = $request->withEnv('HTTPS', ''); <ide> $this->assertFalse($request->is('ssl')); <ide> } <ide><path>tests/TestCase/Http/ServerTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/Session/CacheSessionTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CacheSessionTest <ide> * <ide><path>tests/TestCase/Http/Session/DatabaseSessionTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * DatabaseSessionTest file <ide> * <ide><path>tests/TestCase/Http/SessionTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Http/server_mocks.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * A set of 'mocks' that replace the PHP global functions to aid testing. <ide> */
18
Python
Python
save model as artifact
30fa0b780f30efacdfe3f0964bb1b941b22aa8d5
<ide><path>src/transformers/integrations.py <ide> Integrations with other Python libraries. <ide> """ <ide> import math <add>import numbers <ide> import os <add>import re <add>import tempfile <add>from pathlib import Path <ide> <add>from .file_utils import ENV_VARS_TRUE_VALUES <ide> from .trainer_utils import EvaluationStrategy <ide> from .utils import logging <ide> <ide> def setup(self, args, state, model, reinit, **kwargs): <ide> <https://docs.wandb.com/huggingface>`__. You can also override the following environment variables: <ide> <ide> Environment: <add> WANDB_LOG_MODEL (:obj:`bool`, `optional`, defaults to :obj:`False`): <add> Whether or not to log model as artifact at the end of training. <ide> WANDB_WATCH (:obj:`str`, `optional` defaults to :obj:`"gradients"`): <ide> Can be :obj:`"gradients"`, :obj:`"all"` or :obj:`"false"`. Set to :obj:`"false"` to disable gradient <ide> logging or :obj:`"all"` to log gradients and parameters. <ide> def setup(self, args, state, model, reinit, **kwargs): <ide> if not is_torch_tpu_available() and os.getenv("WANDB_WATCH") != "false": <ide> wandb.watch(model, log=os.getenv("WANDB_WATCH", "gradients"), log_freq=max(100, args.logging_steps)) <ide> <add> # log outputs <add> self._log_model = os.getenv("WANDB_LOG_MODEL", "FALSE").upper() in ENV_VARS_TRUE_VALUES.union({"TRUE"}) <add> <ide> def on_train_begin(self, args, state, control, model=None, **kwargs): <ide> hp_search = state.is_hyper_param_search <ide> if not self._initialized or hp_search: <del> print(args.run_name) <ide> self.setup(args, state, model, reinit=hp_search, **kwargs) <ide> <add> def on_train_end(self, args, state, control, model=None, tokenizer=None, **kwargs): <add> # commit last step <add> wandb.log({}) <add> if self._log_model and self._initialized and state.is_world_process_zero: <add> from .trainer import Trainer <add> <add> fake_trainer = Trainer(args=args, model=model, tokenizer=tokenizer) <add> with tempfile.TemporaryDirectory() as temp_dir: <add> fake_trainer.save_model(temp_dir) <add> # use run name and ensure it's a valid Artifact name <add> artifact_name = re.sub(r"[^a-zA-Z0-9_\.\-]", "", wandb.run.name) <add> metadata = ( <add> { <add> k: v <add> for k, v in dict(wandb.summary).items() <add> if isinstance(v, numbers.Number) and not k.startswith("_") <add> } <add> if not args.load_best_model_at_end <add> else { <add> f"eval/{args.metric_for_best_model}": state.best_metric, <add> "train/total_floss": state.total_flos, <add> } <add> ) <add> artifact = wandb.Artifact(name=f"run-{artifact_name}", type="model", metadata=metadata) <add> for f in Path(temp_dir).glob("*"): <add> if f.is_file(): <add> with artifact.new_file(f.name, mode="wb") as fa: <add> fa.write(f.read_bytes()) <add> wandb.run.log_artifact(artifact) <add> <ide> def on_log(self, args, state, control, model=None, logs=None, **kwargs): <ide> if not self._initialized: <ide> self.setup(args, state, model, reinit=False) <ide><path>src/transformers/trainer.py <ide> def __init__( <ide> "You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method." <ide> ) <ide> callbacks = DEFAULT_CALLBACKS if callbacks is None else DEFAULT_CALLBACKS + callbacks <del> self.callback_handler = CallbackHandler(callbacks, self.model, self.optimizer, self.lr_scheduler) <add> self.callback_handler = CallbackHandler( <add> callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler <add> ) <ide> self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) <ide> <ide> # Will be set to True by `self._setup_loggers()` on first call to `self.log()`. <ide><path>src/transformers/trainer_callback.py <ide> class TrainerCallback: <ide> The object that is returned to the :class:`~transformers.Trainer` and can be used to make some decisions. <ide> model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`): <ide> The model being trained. <add> tokenizer (:class:`~transformers.PreTrainedTokenizer`): <add> The tokenizer used for encoding the data. <ide> optimizer (:obj:`torch.optim.Optimizer`): <ide> The optimizer used for the training steps. <ide> lr_scheduler (:obj:`torch.optim.lr_scheduler.LambdaLR`): <ide> def on_prediction_step(self, args: TrainingArguments, state: TrainerState, contr <ide> class CallbackHandler(TrainerCallback): <ide> """ Internal class that just calls the list of callbacks in order. """ <ide> <del> def __init__(self, callbacks, model, optimizer, lr_scheduler): <add> def __init__(self, callbacks, model, tokenizer, optimizer, lr_scheduler): <ide> self.callbacks = [] <ide> for cb in callbacks: <ide> self.add_callback(cb) <ide> self.model = model <add> self.tokenizer = tokenizer <ide> self.optimizer = optimizer <ide> self.lr_scheduler = lr_scheduler <ide> self.train_dataloader = None <ide> def call_event(self, event, args, state, control, **kwargs): <ide> state, <ide> control, <ide> model=self.model, <add> tokenizer=self.tokenizer, <ide> optimizer=self.optimizer, <ide> lr_scheduler=self.lr_scheduler, <ide> train_dataloader=self.train_dataloader,
3
Javascript
Javascript
add missing lod.islod
14d58824ea8973d4200e7c021623024ac7252a9b
<ide><path>src/objects/LOD.js <ide> LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { <ide> <ide> constructor: LOD, <ide> <add> isLOD: true, <add> <ide> copy: function ( source ) { <ide> <ide> Object3D.prototype.copy.call( this, source, false );
1
Javascript
Javascript
add mustcall in test-timers-clearimmediate
c4054970868dbfd7bff47c2f0acf4c79714b9d1b
<ide><path>test/parallel/test-timers-clearImmediate.js <ide> 'use strict'; <del>require('../common'); <del>const assert = require('assert'); <add>const common = require('../common'); <ide> <ide> const N = 3; <del>let count = 0; <add> <ide> function next() { <del> const immediate = setImmediate(function() { <del> clearImmediate(immediate); <del> ++count; <del> }); <add> const fn = common.mustCall(() => clearImmediate(immediate)); <add> const immediate = setImmediate(fn); <ide> } <del>for (let i = 0; i < N; ++i) <del> next(); <ide> <del>process.on('exit', () => { <del> assert.strictEqual(count, N, `Expected ${N} immediate callback executions`); <del>}); <add>for (let i = 0; i < N; i++) { <add> next(); <add>}
1
Text
Text
fix typo in md files
1e9b07d82cb9f9171f95d9db59cd664b652987d2
<ide><path>research/deeplab/g3doc/faq.md <del>#FAQ <add># FAQ <ide> ___ <ide> Q1: What if I want to use other network backbones, such as ResNet [1], instead of only those provided ones (e.g., Xception)? <ide> <ide><path>research/deeplab/g3doc/installation.md <ide> to avoid running this manually, you can add it as a new line to the end of your <ide> # Testing the Installation <ide> <ide> You can test if you have successfully installed the Tensorflow DeepLab by <del>running the following command: <add>running the following commands: <add> <add>Quick test by running model_test.py: <ide> <ide> ```bash <ide> # From tensorflow/models/research/ <ide> python deeplab/model_test.py <ide> ``` <add> <add>Quick running the whole code on the PASCAL VOC 2012 dataset: <add> <add>```bash <add># From tensorflow/models/research/deeplab <add>sh local_test.sh <add>``` <add>
2
Javascript
Javascript
add https to helmet whitelist
a621ff31907948f75db34f17bf6a607c3bdb1fec
<ide><path>server/server.js <ide> var trusted = [ <ide> '104.236.218.15', <ide> '*.freecodecamp.com', <ide> 'http://www.freecodecamp.com', <add> 'https://www.freecodecamp.com', <add> 'https://freecodecamp.com', <ide> 'ws://freecodecamp.com/', <ide> 'ws://www.freecodecamp.com/', <ide> '*.gstatic.com',
1
Javascript
Javascript
remove array.from(s) and remove iifes
2a54dda3e982872c90e246b27ced2fbe2e5513da
<ide><path>src/config.js <ide> class Config { <ide> getSchema (keyPath) { <ide> const keys = splitKeyPath(keyPath) <ide> let { schema } = this <del> for (let key of Array.from(keys)) { <add> for (let key of keys) { <ide> let childSchema <ide> if (schema.type === 'object') { <ide> childSchema = schema.properties != null ? schema.properties[key] : undefined <ide> class Config { <ide> try { <ide> endTransaction = fn => (...args) => { <ide> this.endTransaction() <del> return fn(...Array.from(args || [])) <add> return fn(...args) <ide> } <ide> const result = callback() <ide> return new Promise((resolve, reject) => { <ide> class Config { <ide> } <ide> <ide> pushAtKeyPath (keyPath, value) { <del> let left <del> const arrayValue = (left = this.get(keyPath)) != null ? left : [] <add> const left = this.get(keyPath) <add> const arrayValue = (left == null ? [] : left) <ide> const result = arrayValue.push(value) <ide> this.set(keyPath, arrayValue) <ide> return result <ide> } <ide> <ide> unshiftAtKeyPath (keyPath, value) { <del> let left <del> const arrayValue = (left = this.get(keyPath)) != null ? left : [] <add> const left = this.get(keyPath) <add> const arrayValue = (left == null ? [] : left) <ide> const result = arrayValue.unshift(value) <ide> this.set(keyPath, arrayValue) <ide> return result <ide> } <ide> <ide> removeAtKeyPath (keyPath, value) { <del> let left <del> const arrayValue = (left = this.get(keyPath)) != null ? left : [] <add> const left = this.get(keyPath) <add> const arrayValue = (left == null ? [] : left) <ide> const result = _.remove(arrayValue, value) <ide> this.set(keyPath, arrayValue) <ide> return result <ide> class Config { <ide> <ide> let rootSchema = this.schema <ide> if (keyPath) { <del> for (let key of Array.from(splitKeyPath(keyPath))) { <add> for (let key of splitKeyPath(keyPath)) { <ide> rootSchema.type = 'object' <ide> if (rootSchema.properties == null) { rootSchema.properties = {} } <ide> const { properties } = rootSchema <ide> class Config { <ide> } <ide> <ide> loadUserConfig () { <del> let error <ide> if (this.shouldNotAccessFileSystem()) { return } <ide> if (this.savePending) { return } <ide> <ide> class Config { <ide> fs.makeTreeSync(path.dirname(this.configFilePath)) <ide> CSON.writeFileSync(this.configFilePath, {}, {flag: 'wx'}) // fails if file exists <ide> } <del> } catch (error1) { <del> error = error1 <add> } catch (error) { <ide> if (error.code !== 'EEXIST') { <ide> this.configFileHasErrors = true <ide> this.notifyFailure(`Failed to initialize \`${path.basename(this.configFilePath)}\``, error.stack) <ide> class Config { <ide> <ide> this.resetUserSettings(userConfig) <ide> this.configFileHasErrors = false <del> } catch (error2) { <del> error = error2 <add> } catch (error) { <ide> this.configFileHasErrors = true <ide> const message = `Failed to load \`${path.basename(this.configFilePath)}\`` <ide> <ide> class Config { <ide> this.watchSubscriptionPromise = watchPath(this.configFilePath, {}, events => { <ide> return (() => { <ide> const result = [] <del> for (let {action} of Array.from(events)) { <add> for (let {action} of events) { <ide> if (['created', 'modified', 'renamed'].includes(action) && (this.watchSubscriptionPromise != null)) { <ide> result.push(this.requestLoad()) <ide> } else { <ide> sizes. See [this document][watches] for more info. <ide> } <ide> <ide> notifyFailure (errorMessage, detail) { <del> return (this.notificationManager != null ? this.notificationManager.addError(errorMessage, {detail, dismissable: true}) : undefined) <add> if (this.notificationManager == null) { return } <add> this.notificationManager.addError(errorMessage, {detail, dismissable: true}) <ide> } <ide> <ide> save () { <ide> sizes. See [this document][watches] for more info. <ide> this.settingsLoaded = true <ide> for (let key in newSettings) { const value = newSettings[key]; this.set(key, value, {save: false}) } <ide> if (this.pendingOperations.length) { <del> for (let op of Array.from(this.pendingOperations)) { op() } <add> for (let op of this.pendingOperations) { op() } <ide> this.pendingOperations = [] <ide> } <ide> }) <ide> sizes. See [this document][watches] for more info. <ide> if ((defaults != null) && isPlainObject(defaults)) { <ide> const keys = splitKeyPath(keyPath) <ide> this.transact(() => { <del> return (() => { <del> const result = [] <del> for (let key in defaults) { <del> const childValue = defaults[key] <del> if (!defaults.hasOwnProperty(key)) { continue } <del> result.push(this.setDefaults(keys.concat([key]).join('.'), childValue)) <del> } <del> return result <del> })() <add> const result = [] <add> for (let key in defaults) { <add> const childValue = defaults[key] <add> if (!defaults.hasOwnProperty(key)) { continue } <add> result.push(this.setDefaults(keys.concat([key]).join('.'), childValue)) <add> } <add> return result <ide> }) <ide> } else { <ide> try { <ide> sizes. See [this document][watches] for more info. <ide> while (++i < arguments.length) { <ide> const object = arguments[i] <ide> if (isPlainObject(result) && isPlainObject(object)) { <del> for (let key of Array.from(Object.keys(object))) { <add> for (let key of Object.keys(object)) { <ide> result[key] = this.deepDefaults(result[key], object[key]) <ide> } <ide> } else { <ide> sizes. See [this document][watches] for more info. <ide> */ <ide> <ide> priorityForSource (source) { <del> if (source === this.getUserConfigPath()) { <del> return 1000 <del> } else { <del> return 0 <del> } <add> return (source === this.getUserConfigPath()) ? 1000 : 0; <ide> } <ide> <ide> emitChangeEvent () { <del> if (!(this.transactDepth > 0)) { return this.emitter.emit('did-change') } <add> if (this.transactDepth <= 0) { return this.emitter.emit('did-change') } <ide> } <ide> <ide> resetUserScopedSettings (newScopedSettings) {
1
Text
Text
update spelling on installation guide
073ea9a4ef68e0e4381e5ac011edda582c659dce
<ide><path>docs/how-to-catch-outgoing-emails-locally.md <ide> Download the latest version of MailHog from [MailHog's official repository](http <ide> <ide> When the download completes, click to open the file. A Windows firewall notification may appear, requesting access permission for MailHog. A standard Windows command line prompt will open where MailHog will be running once firewall access is granted. <ide> <del>Close MailHog by closing the command prompt window. To start MailHog again, click on the MailHog executable (.exe) file that was downloaded initially - it is not necessary to download a new MailHog intallation file. <add>Close MailHog by closing the command prompt window. To start MailHog again, click on the MailHog executable (.exe) file that was downloaded initially - it is not necessary to download a new MailHog installation file. <ide> <ide> Start [using MailHog](#using-mailhog). <ide>
1
PHP
PHP
avoid multiple runtimeexception
3237de6e719d818b02853fad5d4ddcae247ab11d
<ide><path>src/Network/Session.php <ide> public function start() { <ide> } <ide> <ide> if (ini_get('session.use_cookies') && headers_sent($file, $line)) { <del> throw new \RuntimeException( <del> sprintf('Cannot start session, headers already sent in "%s" at line %d', $file, $line) <del> ); <add> return; <ide> } <ide> <ide> if (!session_start()) {
1
Text
Text
fix typo in rails plugins guide
879c18df83ec019da08d8ba7688b5722af5981bb
<ide><path>guides/source/plugins.md <ide> Run `rake` to run the test. This test should fail because we haven't implemented <ide> <ide> Great - now you are ready to start development. <ide> <del>Then in `lib/yaffle.rb` require `lib/core_ext`: <add>Then in `lib/yaffle.rb` add `require "yaffle/core_ext"`: <ide> <ide> ```ruby <ide> # yaffle/lib/yaffle.rb
1
Java
Java
fix failing test
8270d82bda85f227780f03e6cdcac9ae721118ad
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java <ide> protected ContentRequestMatchers() { <ide> /** <ide> * Assert the request content type as a String. <ide> */ <del> public RequestMatcher mimeType(String expectedContentType) { <del> return mimeType(MediaType.parseMediaType(expectedContentType)); <add> public RequestMatcher contentType(String expectedContentType) { <add> return contentType(MediaType.parseMediaType(expectedContentType)); <ide> } <ide> <ide> /** <ide> * Assert the request content type as a {@link MediaType}. <ide> */ <del> public RequestMatcher mimeType(final MediaType expectedContentType) { <add> public RequestMatcher contentType(final MediaType expectedContentType) { <ide> return new RequestMatcher() { <ide> public void match(ClientHttpRequest request) throws IOException, AssertionError { <ide> MediaType actualContentType = request.getHeaders().getContentType(); <ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/client/match/ContentRequestMatchersTests.java <ide> public void setUp() { <ide> public void testContentType() throws Exception { <ide> this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON); <ide> <del> MockRestRequestMatchers.content().mimeType("application/json").match(this.request); <del> MockRestRequestMatchers.content().mimeType(MediaType.APPLICATION_JSON).match(this.request); <add> MockRestRequestMatchers.content().contentType("application/json").match(this.request); <add> MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_JSON).match(this.request); <ide> } <ide> <ide> @Test(expected=AssertionError.class) <ide> public void testContentTypeNoMatch1() throws Exception { <ide> this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON); <ide> <del> MockRestRequestMatchers.content().mimeType("application/xml").match(this.request); <add> MockRestRequestMatchers.content().contentType("application/xml").match(this.request); <ide> } <ide> <ide> @Test(expected=AssertionError.class) <ide> public void testContentTypeNoMatch2() throws Exception { <ide> this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON); <ide> <del> MockRestRequestMatchers.content().mimeType(MediaType.APPLICATION_ATOM_XML).match(this.request); <add> MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_ATOM_XML).match(this.request); <ide> } <ide> <ide> @Test <ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/ContentRequestMatcherTests.java <ide> public void setup() { <ide> <ide> @Test <ide> public void contentType() throws Exception { <del> this.mockServer.expect(content().mimeType("application/json;charset=UTF-8")).andRespond(withSuccess()); <add> this.mockServer.expect(content().contentType("application/json;charset=UTF-8")).andRespond(withSuccess()); <ide> this.restTemplate.put(new URI("/foo"), new Person()); <ide> this.mockServer.verify(); <ide> } <ide> <ide> @Test <ide> public void contentTypeNoMatch() throws Exception { <del> this.mockServer.expect(content().mimeType("application/json;charset=UTF-8")).andRespond(withSuccess()); <add> this.mockServer.expect(content().contentType("application/json;charset=UTF-8")).andRespond(withSuccess()); <ide> try { <ide> this.restTemplate.put(new URI("/foo"), "foo"); <ide> } <ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/HeaderRequestMatcherTests.java <ide> public void setup() { <ide> public void testString() throws Exception { <ide> <ide> this.mockServer.expect(requestTo("/person/1")) <del> .andExpect(header("Accept", "application/json")) <add> .andExpect(header("Accept", "application/json, application/*+json")) <ide> .andRespond(withSuccess(RESPONSE_BODY, MediaType.APPLICATION_JSON)); <ide> <ide> this.restTemplate.getForObject(new URI("/person/1"), Person.class); <ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/JsonPathRequestMatcherTests.java <ide> public void setup() { <ide> @Test <ide> public void testExists() throws Exception { <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/json;charset=UTF-8")) <add> .andExpect(content().contentType("application/json;charset=UTF-8")) <ide> .andExpect(jsonPath("$.composers[0]").exists()) <ide> .andExpect(jsonPath("$.composers[1]").exists()) <ide> .andExpect(jsonPath("$.composers[2]").exists()) <ide> public void testExists() throws Exception { <ide> @Test <ide> public void testDoesNotExist() throws Exception { <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/json;charset=UTF-8")) <add> .andExpect(content().contentType("application/json;charset=UTF-8")) <ide> .andExpect(jsonPath("$.composers[?(@.name = 'Edvard Grieeeeeeg')]").doesNotExist()) <ide> .andExpect(jsonPath("$.composers[?(@.name = 'Robert Schuuuuuuman')]").doesNotExist()) <ide> .andExpect(jsonPath("$.composers[-1]").doesNotExist()) <ide> public void testDoesNotExist() throws Exception { <ide> @Test <ide> public void testEqualTo() throws Exception { <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/json;charset=UTF-8")) <add> .andExpect(content().contentType("application/json;charset=UTF-8")) <ide> .andExpect(jsonPath("$.composers[0].name").value("Johann Sebastian Bach")) <ide> .andExpect(jsonPath("$.performers[1].name").value("Yehudi Menuhin")) <ide> .andExpect(jsonPath("$.composers[0].name").value(equalTo("Johann Sebastian Bach"))) // Hamcrest <ide> public void testEqualTo() throws Exception { <ide> @Test <ide> public void testHamcrestMatcher() throws Exception { <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/json;charset=UTF-8")) <add> .andExpect(content().contentType("application/json;charset=UTF-8")) <ide> .andExpect(jsonPath("$.composers[0].name", startsWith("Johann"))) <ide> .andExpect(jsonPath("$.performers[0].name", endsWith("Ashkenazy"))) <ide> .andExpect(jsonPath("$.performers[1].name", containsString("di Me"))) <ide> public void testHamcrestMatcherWithParameterizedJsonPath() throws Exception { <ide> String performerName = "$.performers[%s].name"; <ide> <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/json;charset=UTF-8")) <add> .andExpect(content().contentType("application/json;charset=UTF-8")) <ide> .andExpect(jsonPath(composerName, 0).value(startsWith("Johann"))) <ide> .andExpect(jsonPath(performerName, 0).value(endsWith("Ashkenazy"))) <ide> .andExpect(jsonPath(performerName, 1).value(containsString("di Me"))) <ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/XmlContentRequestMatcherTests.java <ide> public void setup() { <ide> @Test <ide> public void testXmlEqualTo() throws Exception { <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/xml")) <add> .andExpect(content().contentType("application/xml")) <ide> .andExpect(content().xml(PEOPLE_XML)) <ide> .andRespond(withSuccess()); <ide> <ide> public void testXmlEqualTo() throws Exception { <ide> public void testHamcrestNodeMatcher() throws Exception { <ide> <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/xml")) <add> .andExpect(content().contentType("application/xml")) <ide> .andExpect(content().node(hasXPath("/people/composers/composer[1]"))) <ide> .andRespond(withSuccess()); <ide> <ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/XpathRequestMatcherTests.java <ide> public void testExists() throws Exception { <ide> String performer = "/ns:people/performers/performer[%s]"; <ide> <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/xml")) <add> .andExpect(content().contentType("application/xml")) <ide> .andExpect(xpath(composer, NS, 1).exists()) <ide> .andExpect(xpath(composer, NS, 2).exists()) <ide> .andExpect(xpath(composer, NS, 3).exists()) <ide> public void testDoesNotExist() throws Exception { <ide> String performer = "/ns:people/performers/performer[%s]"; <ide> <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/xml")) <add> .andExpect(content().contentType("application/xml")) <ide> .andExpect(xpath(composer, NS, 0).doesNotExist()) <ide> .andExpect(xpath(composer, NS, 5).doesNotExist()) <ide> .andExpect(xpath(performer, NS, 0).doesNotExist()) <ide> public void testString() throws Exception { <ide> String performerName = "/ns:people/performers/performer[%s]/name"; <ide> <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/xml")) <add> .andExpect(content().contentType("application/xml")) <ide> .andExpect(xpath(composerName, NS, 1).string("Johann Sebastian Bach")) <ide> .andExpect(xpath(composerName, NS, 2).string("Johannes Brahms")) <ide> .andExpect(xpath(composerName, NS, 3).string("Edvard Grieg")) <ide> public void testNumber() throws Exception { <ide> String composerDouble = "/ns:people/composers/composer[%s]/someDouble"; <ide> <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/xml")) <add> .andExpect(content().contentType("application/xml")) <ide> .andExpect(xpath(composerDouble, NS, 1).number(21d)) <ide> .andExpect(xpath(composerDouble, NS, 2).number(.0025)) <ide> .andExpect(xpath(composerDouble, NS, 3).number(1.6035)) <ide> public void testBoolean() throws Exception { <ide> String performerBooleanValue = "/ns:people/performers/performer[%s]/someBoolean"; <ide> <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/xml")) <add> .andExpect(content().contentType("application/xml")) <ide> .andExpect(xpath(performerBooleanValue, NS, 1).booleanValue(false)) <ide> .andExpect(xpath(performerBooleanValue, NS, 2).booleanValue(true)) <ide> .andRespond(withSuccess()); <ide> public void testBoolean() throws Exception { <ide> public void testNodeCount() throws Exception { <ide> <ide> this.mockServer.expect(requestTo("/composers")) <del> .andExpect(content().mimeType("application/xml")) <add> .andExpect(content().contentType("application/xml")) <ide> .andExpect(xpath("/ns:people/composers/composer", NS).nodeCount(4)) <ide> .andExpect(xpath("/ns:people/performers/performer", NS).nodeCount(2)) <ide> .andExpect(xpath("/ns:people/composers/composer", NS).nodeCount(lessThan(5))) // Hamcrest..
7
Python
Python
add error message if docbin zlib decompress fails
26296ab223b809cef5bd1fd997a4112119815864
<ide><path>spacy/errors.py <ide> class Errors: <ide> E1013 = ("Invalid morph: the MorphAnalysis must have the same vocab as the " <ide> "token itself. To set the morph from this MorphAnalysis, set from " <ide> "the string value with: `token.set_morph(str(other_morph))`.") <add> E1014 = ("Error loading DocBin data. It doesn't look like the data is in " <add> "DocBin (.spacy) format. If your data is in spaCy v2's JSON " <add> "training format, convert it using `python -m spacy convert " <add> "file.json .`.") <ide> <ide> <ide> # Deprecated model shortcuts, only used in errors and warnings <ide><path>spacy/tokens/_serialize.py <ide> def from_bytes(self, bytes_data: bytes) -> "DocBin": <ide> <ide> DOCS: https://nightly.spacy.io/api/docbin#from_bytes <ide> """ <del> msg = srsly.msgpack_loads(zlib.decompress(bytes_data)) <add> try: <add> msg = srsly.msgpack_loads(zlib.decompress(bytes_data)) <add> except zlib.error: <add> raise ValueError(Errors.E1014) <ide> self.attrs = msg["attrs"] <ide> self.strings = set(msg["strings"]) <ide> lengths = numpy.frombuffer(msg["lengths"], dtype="int32")
2
Ruby
Ruby
remove opt link in keg#uninstall
76e86891e4846b6b728ac87d3af76820e662d975
<ide><path>Library/Homebrew/cmd/uninstall.rb <ide> def uninstall <ide> puts "Uninstalling #{keg}..." <ide> keg.unlink <ide> keg.uninstall <del> rm_opt_link keg.fname <ide> rm_pin keg.fname <ide> end <ide> end <ide> def uninstall <ide> end <ide> end <ide> <del> rm_opt_link name <ide> rm_pin name <ide> end <ide> end <ide> def uninstall <ide> puts "Use `brew remove --force #{e.name}` to remove all versions." <ide> end <ide> <del> def rm_opt_link name <del> optlink = HOMEBREW_PREFIX.join("opt", name) <del> optlink.unlink if optlink.symlink? <del> end <del> <ide> def rm_pin name <ide> Formulary.factory(name).unpin rescue nil <ide> end <ide><path>Library/Homebrew/keg.rb <ide> def initialize path <ide> def uninstall <ide> rmtree <ide> parent.rmdir_if_possible <add> <add> opt = HOMEBREW_PREFIX.join("opt", fname) <add> if opt.symlink? && self == opt.resolved_path <add> opt.unlink <add> opt.parent.rmdir_if_possible <add> end <ide> end <ide> <ide> def unlink
2
Python
Python
prepare pypi release
018e55be7c77f168abaea898233ccec035bb39d0
<ide><path>keras/__init__.py <ide> from .models import Model <ide> from .models import Sequential <ide> <del>__version__ = '2.1.0' <add>__version__ = '2.1.1' <ide><path>setup.py <ide> <ide> <ide> setup(name='Keras', <del> version='2.1.0', <add> version='2.1.1', <ide> description='Deep Learning for Python', <ide> author='Francois Chollet', <ide> author_email='[email protected]', <ide> url='https://github.com/fchollet/keras', <del> download_url='https://github.com/fchollet/keras/tarball/2.1.0', <add> download_url='https://github.com/fchollet/keras/tarball/2.1.1', <ide> license='MIT', <ide> install_requires=['numpy>=1.9.1', <ide> 'scipy>=0.14',
2
Go
Go
remove unused functions and enable disabled tests
67e4d36e46196dcebe60320036826d02c5626cc7
<ide><path>integration-cli/docker_cli_daemon_plugins_test.go <ide> import ( <ide> "strings" <ide> "testing" <ide> <del> "github.com/docker/docker/pkg/mount" <ide> "golang.org/x/sys/unix" <ide> "gotest.tools/assert" <ide> "gotest.tools/icmd" <ide> func (s *DockerDaemonSuite) TestPluginVolumeRemoveOnRestart(c *testing.T) { <ide> assert.NilError(c, err, out) <ide> } <ide> <del>func existsMountpointWithPrefix(mountpointPrefix string) (bool, error) { <del> mounts, err := mount.GetMounts(nil) <del> if err != nil { <del> return false, err <del> } <del> for _, mnt := range mounts { <del> if strings.HasPrefix(mnt.Mountpoint, mountpointPrefix) { <del> return true, nil <del> } <del> } <del> return false, nil <del>} <del> <ide> func (s *DockerDaemonSuite) TestPluginListFilterEnabled(c *testing.T) { <ide> testRequires(c, IsAmd64, Network) <ide> <ide><path>integration-cli/docker_cli_pull_local_test.go <ide> func testConcurrentPullWholeRepo(c *testing.T) { <ide> } <ide> } <ide> <del>func (s *DockerRegistrySuite) testConcurrentPullWholeRepo(c *testing.T) { <add>func (s *DockerRegistrySuite) TestConcurrentPullWholeRepo(c *testing.T) { <ide> testConcurrentPullWholeRepo(c) <ide> } <ide> <del>func (s *DockerSchema1RegistrySuite) testConcurrentPullWholeRepo(c *testing.T) { <add>func (s *DockerSchema1RegistrySuite) TestConcurrentPullWholeRepo(c *testing.T) { <ide> testConcurrentPullWholeRepo(c) <ide> } <ide> <ide> func testConcurrentFailingPull(c *testing.T) { <ide> } <ide> } <ide> <del>func (s *DockerRegistrySuite) testConcurrentFailingPull(c *testing.T) { <add>func (s *DockerRegistrySuite) TestConcurrentFailingPull(c *testing.T) { <ide> testConcurrentFailingPull(c) <ide> } <ide> <del>func (s *DockerSchema1RegistrySuite) testConcurrentFailingPull(c *testing.T) { <add>func (s *DockerSchema1RegistrySuite) TestConcurrentFailingPull(c *testing.T) { <ide> testConcurrentFailingPull(c) <ide> } <ide> <ide><path>integration-cli/docker_utils_test.go <ide> func inspectMountPointJSON(j, destination string) (types.MountPoint, error) { <ide> return *m, nil <ide> } <ide> <del>// Deprecated: use cli.Inspect <del>func inspectImage(c *testing.T, name, filter string) string { <del> c.Helper() <del> args := []string{"inspect", "--type", "image"} <del> if filter != "" { <del> format := fmt.Sprintf("{{%s}}", filter) <del> args = append(args, "-f", format) <del> } <del> args = append(args, name) <del> result := icmd.RunCommand(dockerBinary, args...) <del> result.Assert(c, icmd.Success) <del> return strings.TrimSpace(result.Combined()) <del>} <del> <ide> func getIDByName(c *testing.T, name string) string { <ide> c.Helper() <ide> id, err := inspectFieldWithError(name, "Id") <ide><path>integration-cli/events_utils_test.go <ide> func parseEvents(c *testing.T, out, match string) { <ide> assert.Assert(c, matched, "Matcher: %s did not match %s", match, matches["action"]) <ide> } <ide> } <del> <del>func parseEventsWithID(c *testing.T, out, match, id string) { <del> events := strings.Split(strings.TrimSpace(out), "\n") <del> for _, event := range events { <del> matches := eventstestutils.ScanMap(event) <del> assert.Assert(c, matchEventID(matches, id)) <del> <del> matched, err := regexp.MatchString(match, matches["action"]) <del> assert.NilError(c, err) <del> assert.Assert(c, matched, "Matcher: %s did not match %s", match, matches["action"]) <del> } <del>} <ide><path>integration-cli/fixtures_linux_daemon_test.go <ide> import ( <ide> "gotest.tools/assert" <ide> ) <ide> <del>type testingT interface { <del> logT <del> Fatalf(string, ...interface{}) <del>} <del> <del>type logT interface { <del> Logf(string, ...interface{}) <del>} <del> <ide> func ensureSyscallTest(c *testing.T) { <ide> defer testEnv.ProtectImage(c, "syscall-test:latest") <ide>
5
Python
Python
allow multiple inputs
870d7f7f936bab348589d8d0bcc4d252c6ed832f
<ide><path>keras/layers/core.py <ide> def get_output_shape_for(self, input_shape): <ide> # otherwise, we default to the input shape <ide> return input_shape <ide> elif type(self._output_shape) in {tuple, list}: <del> nb_samples = input_shape[0] if input_shape else None <add> if type(input_shape) is list: <add> nb_samples = input_shape[0][0] <add> else: <add> nb_samples = input_shape[0] if input_shape else None <ide> return (nb_samples,) + tuple(self._output_shape) <ide> else: <ide> shape = self._output_shape(input_shape)
1
PHP
PHP
add bigint support for postgres
7bad865d6e4e89c114b04c14a92ac30599fb678b
<ide><path>lib/Cake/Model/Datasource/Database/Postgres.php <ide> class Postgres extends DboSource { <ide> 'string' => array('name' => 'varchar', 'limit' => '255'), <ide> 'text' => array('name' => 'text'), <ide> 'integer' => array('name' => 'integer', 'formatter' => 'intval'), <add> 'biginteger' => array('name' => 'bigint', 'limit' => '20'), <ide> 'float' => array('name' => 'float', 'formatter' => 'floatval'), <ide> 'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), <ide> 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), <ide> public function column($real) { <ide> return 'datetime'; <ide> case (strpos($col, 'time') === 0): <ide> return 'time'; <add> case ($col == 'bigint'): <add> return 'biginteger'; <ide> case (strpos($col, 'int') !== false && $col != 'interval'): <ide> return 'integer'; <ide> case (strpos($col, 'char') !== false || $col == 'uuid'): <ide> public function buildColumn($column) { <ide> if (!isset($col['length']) && !isset($col['limit'])) { <ide> unset($column['length']); <ide> } <del> $out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column)); <add> $out = parent::buildColumn($column); <add> <add> $out = preg_replace( <add> '/integer\([0-9]+\)/', <add> 'integer', <add> $out <add> ); <add> $out = preg_replace( <add> '/bigint\([0-9]+\)/', <add> 'bigint', <add> $out <add> ); <add> <ide> $out = str_replace('integer serial', 'serial', $out); <ide> if (strpos($out, 'timestamp DEFAULT')) { <ide> if (isset($column['null']) && $column['null']) { <ide><path>lib/Cake/Test/Case/Model/Datasource/Database/PostgresTest.php <ide> public function testColumnParsing() { <ide> $this->assertEquals('string', $this->Dbo2->column('character varying')); <ide> $this->assertEquals('time', $this->Dbo2->column('time without time zone')); <ide> $this->assertEquals('datetime', $this->Dbo2->column('timestamp without time zone')); <add> <add> $result = $this->Dbo2->column('bigint'); <add> $expected = 'biginteger'; <add> $this->assertEquals($expected, $result); <ide> } <ide> <ide> /** <ide> public function testCakeSchema() { <ide> id serial NOT NULL, <ide> "varchar" character varying(40) NOT NULL, <ide> "full_length" character varying NOT NULL, <add> "huge_int" bigint NOT NULL, <ide> "timestamp" timestamp without time zone, <ide> "date" date, <ide> CONSTRAINT test_data_types_pkey PRIMARY KEY (id) <ide> public function testCakeSchema() { <ide> 'connection' => 'test', <ide> 'models' => array('DatatypeTest') <ide> )); <del> $schema->tables = array('datatype_tests' => $result['tables']['missing']['datatype_tests']); <add> $schema->tables = array( <add> 'datatype_tests' => $result['tables']['missing']['datatype_tests'] <add> ); <ide> $result = $db1->createSchema($schema, 'datatype_tests'); <ide> <ide> $this->assertNotRegExp('/timestamp DEFAULT/', $result); <ide> $this->assertRegExp('/\"full_length\"\s*text\s.*,/', $result); <del> $this->assertRegExp('/timestamp\s*,/', $result); <add> $this->assertContains('timestamp ,', $result); <add> $this->assertContains('"huge_int" bigint NOT NULL,', $result); <ide> <ide> $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests')); <ide>
2
Ruby
Ruby
remove guard from certain parsing logic
d6202384d750909c67b3be79b4dc1b80722c829d
<ide><path>Library/Homebrew/utils/curl.rb <ide> def curl_http_content_headers_and_checksum( <ide> user_agent: user_agent <ide> ) <ide> <del> if status.success? <del> parsed_output = parse_curl_output(output) <del> responses = parsed_output[:responses] <add> parsed_output = parse_curl_output(output) <add> responses = parsed_output[:responses] <ide> <del> final_url = curl_response_last_location(responses) <del> headers = if responses.last.present? <del> status_code = responses.last[:status_code] <del> responses.last[:headers] <del> else <del> {} <del> end <del> etag = headers["etag"][ETAG_VALUE_REGEX, 1] if headers["etag"].present? <del> content_length = headers["content-length"] <add> final_url = curl_response_last_location(responses) <add> headers = if responses.last.present? <add> status_code = responses.last[:status_code] <add> responses.last[:headers] <add> else <add> {} <add> end <add> etag = headers["etag"][ETAG_VALUE_REGEX, 1] if headers["etag"].present? <add> content_length = headers["content-length"] <ide> <add> if status.success? <ide> file_contents = File.read(file.path) <ide> file_hash = Digest::SHA2.hexdigest(file_contents) if hash_needed <ide> end
1
Java
Java
update copyright date
969aa8ad4768b08751ca8e3791f4dc62605d0e20
<ide><path>spring-test/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2020 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><path>spring-test/src/test/java/org/springframework/test/util/JsonPathExpectationsHelperTests.java <ide> /* <del> * Copyright 2004-2020 the original author or authors. <add> * Copyright 2002-2020 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><path>spring-test/src/test/java/org/springframework/test/web/servlet/result/JsonPathResultMatchersTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 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.
3
Javascript
Javascript
adapt unit tests
94efa8f58fdf654175c7a33236f5011ebe19fc06
<ide><path>Libraries/CustomComponents/Navigator/Navigation/__tests__/NavigationEvent-test.js <del> <ide> /** <ide> * Copyright (c) 2015, Facebook, Inc. All rights reserved. <ide> * <ide> describe('NavigationEvent', () => { <ide> it('recycles', () => { <ide> var event1 = NavigationEvent.pool('foo', {}, 123); <ide> event1.dispose(); <del> expect(event1.type).toBe(null); <add> expect(event1.type).toBeFalsy(); <ide> expect(event1.data).toBe(null); <ide> expect(event1.target).toBe(null); <ide> <ide> describe('NavigationEvent', () => { <ide> expect(event2).toBe(event1); <ide> }); <ide> }); <del> <del>
1
Text
Text
update the lxc version to 1.0.7 in packagers.md
17373ca54b9caf2bc24d8a69c6b9639d167cb0cb
<ide><path>project/PACKAGERS.md <ide> the client will even run on alternative platforms such as Mac OS X / Darwin. <ide> Some of Docker's features are activated by using optional command-line flags or <ide> by having support for them in the kernel or userspace. A few examples include: <ide> <del>* LXC execution driver (requires version 1.0 or later of the LXC utility scripts) <add>* LXC execution driver (requires version 1.0.7 or later of lxc and the lxc-libs) <ide> * AUFS graph driver (requires AUFS patches/support enabled in the kernel, and at <ide> least the "auplink" utility from aufs-tools) <ide> * BTRFS graph driver (requires BTRFS support enabled in the kernel)
1
Ruby
Ruby
add custom exception for untapped formulae
3872f78d666ab6ed765773907cdbd84cdb5e28ad
<ide><path>Library/Homebrew/exceptions.rb <ide> class FormulaUnavailableError < RuntimeError <ide> attr_reader :name <ide> attr_accessor :dependent <ide> <add> def initialize name <add> @name = name <add> end <add> <ide> def dependent_s <ide> "(dependency of #{dependent})" if dependent and dependent != name <ide> end <ide> <ide> def to_s <del> if name =~ HOMEBREW_TAP_FORMULA_REGEX then <<-EOS.undent <del> No available formula for #$3 #{dependent_s} <del> Please tap it and then try again: brew tap #$1/#$2 <del> EOS <del> else <del> "No available formula for #{name} #{dependent_s}" <del> end <add> "No available formula for #{name} #{dependent_s}" <ide> end <add>end <add> <add>class TapFormulaUnavailableError < FormulaUnavailableError <add> attr_reader :user, :repo, :shortname <ide> <ide> def initialize name <del> @name = name <add> super <add> @user, @repo, @shortname = name.split("/", 3) <add> end <add> <add> def to_s; <<-EOS.undent <add> No available formula for #{shortname} #{dependent_s} <add> Please tap it and then try again: brew tap #{user}/#{repo} <add> EOS <ide> end <ide> end <ide> <ide><path>Library/Homebrew/formulary.rb <ide> def initialize tapped_name <ide> end <ide> <ide> def get_formula <del> klass.new(tapped_name, path) <add> klass.new(name, path) <add> rescue FormulaUnavailableError => e <add> raise TapFormulaUnavailableError.new(e.name) <ide> end <ide> end <ide>
2
Go
Go
fix daemon panic on restoring containers
c75de8e33cc0db5236eef6146f2de06533b46aa8
<ide><path>libcontainerd/client_linux.go <ide> func (clnt *client) Restore(containerID string, options ...CreateOption) error { <ide> clnt.remote.Lock() <ide> return nil <ide> } <add> // relock because of the defer <add> clnt.remote.Lock() <ide> <ide> clnt.deleteContainer(containerID) <ide>
1
Go
Go
remove pidfile type, rename new() to write()
43d6eb7173e0402f395df39f0c4de8615c325787
<ide><path>cmd/dockerd/daemon.go <ide> func (cli *DaemonCli) start(opts *daemonOptions) (err error) { <ide> potentiallyUnderRuntimeDir := []string{cli.Config.ExecRoot} <ide> <ide> if cli.Pidfile != "" { <del> pf, err := pidfile.New(cli.Pidfile) <del> if err != nil { <add> if err := pidfile.Write(cli.Pidfile); err != nil { <ide> return errors.Wrap(err, "failed to start daemon") <ide> } <ide> potentiallyUnderRuntimeDir = append(potentiallyUnderRuntimeDir, cli.Pidfile) <ide> defer func() { <del> if err := pf.Remove(); err != nil { <add> if err := os.Remove(cli.Pidfile); err != nil { <ide> logrus.Error(err) <ide> } <ide> }() <ide><path>pkg/pidfile/pidfile.go <ide> import ( <ide> "github.com/docker/docker/pkg/system" <ide> ) <ide> <del>// PIDFile is a file used to store the process ID of a running process. <del>type PIDFile struct { <del> path string <del>} <del> <ide> func checkPIDFileAlreadyExists(path string) error { <ide> pidByte, err := os.ReadFile(path) <ide> if err != nil { <ide> func checkPIDFileAlreadyExists(path string) error { <ide> return nil <ide> } <ide> <del>// New creates a PIDfile using the specified path. <del>func New(path string) (*PIDFile, error) { <add>// Write writes a "PID file" at the specified path. It returns an error if the <add>// file exists and contains a valid PID of a running process, or when failing <add>// to write the file. <add>func Write(path string) error { <ide> if err := checkPIDFileAlreadyExists(path); err != nil { <del> return nil, err <add> return err <ide> } <del> // Note MkdirAll returns nil if a directory already exists <ide> if err := system.MkdirAll(filepath.Dir(path), 0o755); err != nil { <del> return nil, err <del> } <del> if err := os.WriteFile(path, []byte(strconv.Itoa(os.Getpid())), 0o644); err != nil { <del> return nil, err <add> return err <ide> } <del> <del> return &PIDFile{path: path}, nil <del>} <del> <del>// Remove removes the PIDFile. <del>func (file PIDFile) Remove() error { <del> return os.Remove(file.path) <add> return os.WriteFile(path, []byte(strconv.Itoa(os.Getpid())), 0o644) <ide> } <ide><path>pkg/pidfile/pidfile_test.go <ide> package pidfile // import "github.com/docker/docker/pkg/pidfile" <ide> <ide> import ( <del> "os" <ide> "path/filepath" <ide> "testing" <ide> ) <ide> <del>func TestNewAndRemove(t *testing.T) { <del> dir, err := os.MkdirTemp(os.TempDir(), "test-pidfile") <del> if err != nil { <del> t.Fatal("Could not create test directory") <del> } <del> <del> path := filepath.Join(dir, "testfile") <del> file, err := New(path) <add>func TestWrite(t *testing.T) { <add> path := filepath.Join(t.TempDir(), "testfile") <add> err := Write(path) <ide> if err != nil { <ide> t.Fatal("Could not create test file", err) <ide> } <ide> <del> _, err = New(path) <add> err = Write(path) <ide> if err == nil { <ide> t.Fatal("Test file creation not blocked") <ide> } <del> <del> if err := file.Remove(); err != nil { <del> t.Fatal("Could not delete created test file") <del> } <del>} <del> <del>func TestRemoveInvalidPath(t *testing.T) { <del> file := PIDFile{path: filepath.Join("foo", "bar")} <del> <del> if err := file.Remove(); err == nil { <del> t.Fatal("Non-existing file doesn't give an error on delete") <del> } <ide> }
3
PHP
PHP
stop the beforedispatch event on redirect routes
4d71b248ca7b7af1565988675ca02063aa5c9fb2
<ide><path>src/Routing/Filter/RoutingFilter.php <ide> public function beforeDispatch(Event $event) <ide> $request->addParams($params); <ide> } <ide> } catch (RedirectException $e) { <add> $event->stopPropagation(); <ide> $response = $event->data['response']; <ide> $response->statusCode($e->getCode()); <ide> $response->header('Location', $e->getMessage()); <ide><path>tests/TestCase/Routing/Filter/RoutingFilterTest.php <ide> public function testBeforeDispatchRedirectRoute() <ide> $this->assertInstanceOf('Cake\Network\Response', $response); <ide> $this->assertSame('http://localhost/articles', $response->header()['Location']); <ide> $this->assertSame(301, $response->statusCode()); <add> $this->assertTrue($event->isStopped()); <ide> } <ide> <ide> /**
2
Text
Text
remove forbiddenattributeserror from examples
db6ce8de4ca1ec6b70dafbcc703ce67db022c382
<ide><path>guides/source/action_controller_overview.md <ide> By default, adding values to the flash will make them available to the next requ <ide> ```ruby <ide> class ClientsController < ApplicationController <ide> def create <del> @client = Client.new(params[:client]) <add> @client = Client.new(client_params) <ide> if @client.save <ide> # ... <ide> else <ide> class CommentsController < ApplicationController <ide> end <ide> <ide> def create <del> @comment = Comment.new(params[:comment]) <add> @comment = Comment.new(comment_params) <ide> if @comment.save <ide> flash[:notice] = "Thanks for your comment!" <ide> if params[:remember_name]
1
Text
Text
add missing comma
3250888e05e6c0c98efa0b20f1d5f30ce3e7d1d8
<ide><path>docs/apm-rest-api.md <ide> Returns: <ide> ```json <ide> { <ide> "name": "0.96.0", <del> "notes": "[HTML release notes]" <add> "notes": "[HTML release notes]", <ide> "pub_date": "2014-05-19T15:52:06.000Z", <ide> "url": "https://www.atom.io/api/updates/download" <ide> }
1
Ruby
Ruby
sync the visibility of `sql_for_insert` to private
f39492c75a5bae6d5ce37515e0de80431e5f96ff
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb <ide> def sql_for_insert(sql, pk, id_value, sequence_name, binds) # :nodoc: <ide> <ide> super <ide> end <del> protected :sql_for_insert <add> private :sql_for_insert <ide> <ide> def exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil) <ide> if use_insert_returning? || pk == false
1
Javascript
Javascript
restore getchar in jpegstream
6dc6f5d533f7614ca0af940265ae09cc6868d452
<ide><path>pdf.js <ide> var JpegStream = (function() { <ide> constructor.prototype = { <ide> getImage: function() { <ide> return this.domImage; <add> }, <add> getChar: function() { <add> error("internal error: getChar is not valid on JpegStream"); <ide> } <ide> }; <ide>
1
Ruby
Ruby
add outer joins for matching nodes
0480b8c717c3a76c8d7fa30236d5a843c8a675b2
<ide><path>activerecord/lib/active_record/associations/join_dependency.rb <ide> def join_constraints(outer_joins) <ide> oj = outer_joins.first <ide> <ide> if join_root.match? oj.join_root <del> outer_joins.each { |oj| merge_outer_joins! oj } <del> make_joins join_root <add> joins = make_joins join_root <add> joins + walk(join_root, oj.join_root) <ide> else <ide> make_joins(join_root) + outer_joins.flat_map { |join| <ide> join.join_root.children.flat_map { |child| <ide> def table_alias_for(reflection, parent, join) <ide> name <ide> end <ide> <add> def walk(left, right) <add> intersection, missing = right.children.map { |node1| <add> [left.children.find { |node2| node1.match? node2 }, node1] <add> }.partition(&:first) <add> <add> ojs = missing.flat_map { |_,n| <add> make_the_joins left, n <add> } <add> <add> intersection.flat_map { |l,r| walk l, r }.concat ojs <add> end <add> <ide> def merge_node(left, right) <ide> intersection, missing = right.children.map { |node1| <ide> [left.children.find { |node2| node1.match? node2 }, node1]
1
PHP
PHP
remove unused variable
bcb8a98e22e270824cca8b7c7898acefd537aedb
<ide><path>src/Illuminate/Auth/SessionGuard.php <ide> protected function hasValidCredentials($user, $credentials) <ide> protected function fireAttemptEvent(array $credentials, $remember, $login) <ide> { <ide> if ($this->events) { <del> $payload = [$credentials, $remember, $login]; <del> <ide> $this->events->fire(new Events\Attempting( <ide> $credentials, $remember, $login <ide> ));
1
Text
Text
changelog entries for and
04b6ae4d186195008b7801df19ebba295f042288
<ide><path>activerecord/CHANGELOG.md <add>* `reload` no longer merges with the existing attributes. <add> The attribute hash is fully replaced. The record is put into the same state <add> as it would be with `Model.find(model.id)`. <add> <add> *Sean Griffin* <add> <add>* The object returned from `select_all` must respond to `column_types`. <add> If this is not the case a `NoMethodError` is raised. <add> <add> *Sean Griffin* <add> <ide> * `has_many :through` associations will no longer save the through record <ide> twice when added in an `after_create` callback defined before the <ide> associations.
1
Java
Java
use static accessors in defaultsimpuserregistry
3eb2c5e22f3a114b8f8c989bd7ef079590b24c4a
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/DefaultSimpUserRegistry.java <ide> import org.springframework.core.Ordered; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessageHeaders; <ide> import org.springframework.messaging.simp.SimpMessageHeaderAccessor; <ide> import org.springframework.messaging.simp.user.DestinationUserNameProvider; <ide> import org.springframework.messaging.simp.user.SimpSession; <ide> import org.springframework.messaging.simp.user.SimpSubscription; <ide> import org.springframework.messaging.simp.user.SimpSubscriptionMatcher; <ide> import org.springframework.messaging.simp.user.SimpUser; <ide> import org.springframework.messaging.simp.user.SimpUserRegistry; <del>import org.springframework.messaging.support.MessageHeaderAccessor; <ide> import org.springframework.util.Assert; <ide> <ide> /** <ide> public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { <ide> public void onApplicationEvent(ApplicationEvent event) { <ide> AbstractSubProtocolEvent subProtocolEvent = (AbstractSubProtocolEvent) event; <ide> Message<?> message = subProtocolEvent.getMessage(); <add> MessageHeaders headers = message.getHeaders(); <ide> <del> SimpMessageHeaderAccessor accessor = <del> MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class); <del> Assert.state(accessor != null, "No SimpMessageHeaderAccessor"); <del> <del> String sessionId = accessor.getSessionId(); <add> String sessionId = SimpMessageHeaderAccessor.getSessionId(headers); <ide> Assert.state(sessionId != null, "No session id"); <ide> <ide> if (event instanceof SessionSubscribeEvent) { <ide> LocalSimpSession session = this.sessions.get(sessionId); <ide> if (session != null) { <del> String id = accessor.getSubscriptionId(); <del> String destination = accessor.getDestination(); <add> String id = SimpMessageHeaderAccessor.getSubscriptionId(headers); <add> String destination = SimpMessageHeaderAccessor.getDestination(headers); <ide> if (id != null && destination != null) { <ide> session.addSubscription(id, destination); <ide> } <ide> else if (event instanceof SessionDisconnectEvent) { <ide> else if (event instanceof SessionUnsubscribeEvent) { <ide> LocalSimpSession session = this.sessions.get(sessionId); <ide> if (session != null) { <del> String subscriptionId = accessor.getSubscriptionId(); <add> String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers); <ide> if (subscriptionId != null) { <ide> session.removeSubscription(subscriptionId); <ide> }
1
Ruby
Ruby
fix bind values in insert statements
e33c568f5e07e8caf7d36e8a8ca1a793b1781dc4
<ide><path>lib/arel/visitors/mysql.rb <ide> def visit_Arel_Nodes_UpdateStatement o, collector <ide> collector = visit o.relation, collector <ide> <ide> unless o.values.empty? <del> collector << "SET " <add> collector << " SET " <ide> collector = inject_join o.values, collector, ', ' <ide> end <ide> <ide> unless o.wheres.empty? <del> collector << "SET " <add> collector << " WHERE " <ide> collector = inject_join o.wheres, collector, ' AND ' <ide> end <ide> <ide> unless o.orders.empty? <del> collector << "ORDER BY " <del> collector = inject_join o.wheres, collector, ', ' <add> collector << " ORDER BY " <add> collector = inject_join o.orders, collector, ', ' <ide> end <ide> <ide> if o.limit <ide><path>lib/arel/visitors/to_sql.rb <ide> def column_cache(table) <ide> def visit_Arel_Nodes_Values o, collector <ide> collector << "VALUES (" <ide> <del> collector << o.expressions.zip(o.columns).map { |value, attr| <add> len = o.expressions.length - 1 <add> o.expressions.zip(o.columns).each_with_index { |(value, attr), i| <ide> if Nodes::SqlLiteral === value <del> value <add> collector = visit value, collector <ide> else <del> quote(value, attr && column_for(attr)) <add> collector << quote(value, attr && column_for(attr)).to_s <ide> end <del> }.join(', ') <add> unless i == len <add> collector << ', ' <add> end <add> } <ide> <ide> collector << ")" <ide> end
2
Java
Java
fix regression in static setter method support
7a19fd575045333b970e645f6db8a15302484038
<ide><path>spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java <ide> <ide> /** <ide> * Decorator for a standard {@link BeanInfo} object, e.g. as created by <del> * {@link Introspector#getBeanInfo(Class)}, designed to discover and register non-void <del> * returning setter methods. For example: <add> * {@link Introspector#getBeanInfo(Class)}, designed to discover and register static <add> * and/or non-void returning setter methods. For example: <ide> * <pre>{@code <ide> * public class Bean { <ide> * private Foo foo; <ide> public ExtendedBeanInfo(BeanInfo delegate) throws IntrospectionException { <ide> new SimpleNonIndexedPropertyDescriptor(pd)); <ide> } <ide> <del> for (Method method : findNonVoidWriteMethods(delegate.getMethodDescriptors())) { <del> handleNonVoidWriteMethod(method); <add> for (Method method : findCandidateWriteMethods(delegate.getMethodDescriptors())) { <add> handleCandidateWriteMethod(method); <ide> } <ide> } <ide> <ide> <del> private List<Method> findNonVoidWriteMethods(MethodDescriptor[] methodDescriptors) { <add> private List<Method> findCandidateWriteMethods(MethodDescriptor[] methodDescriptors) { <ide> List<Method> matches = new ArrayList<Method>(); <ide> for (MethodDescriptor methodDescriptor : methodDescriptors) { <ide> Method method = methodDescriptor.getMethod(); <del> if (isNonVoidWriteMethod(method)) { <add> if (isCandidateWriteMethod(method)) { <ide> matches.add(method); <ide> } <ide> } <ide> return matches; <ide> } <ide> <del> public static boolean isNonVoidWriteMethod(Method method) { <add> public static boolean isCandidateWriteMethod(Method method) { <ide> String methodName = method.getName(); <ide> Class<?>[] parameterTypes = method.getParameterTypes(); <ide> int nParams = parameterTypes.length; <ide> if (methodName.length() > 3 && methodName.startsWith("set") && <ide> Modifier.isPublic(method.getModifiers()) && <del> !void.class.isAssignableFrom(method.getReturnType()) && <add> ( <add> !void.class.isAssignableFrom(method.getReturnType()) || <add> Modifier.isStatic(method.getModifiers()) <add> ) && <ide> (nParams == 1 || (nParams == 2 && parameterTypes[0].equals(int.class)))) { <ide> return true; <ide> } <ide> return false; <ide> } <ide> <del> private void handleNonVoidWriteMethod(Method method) throws IntrospectionException { <add> private void handleCandidateWriteMethod(Method method) throws IntrospectionException { <ide> int nParams = method.getParameterTypes().length; <ide> String propertyName = propertyNameFor(method); <ide> Class<?> propertyType = method.getParameterTypes()[nParams-1]; <ide><path>spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfoFactory.java <ide> public BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException { <ide> */ <ide> private boolean supports(Class<?> beanClass) { <ide> for (Method method : beanClass.getMethods()) { <del> if (ExtendedBeanInfo.isNonVoidWriteMethod(method)) { <add> if (ExtendedBeanInfo.isCandidateWriteMethod(method)) { <ide> return true; <ide> } <ide> } <ide><path>spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java <ide> public void testWildcardedGenericEnum() { <ide> assertEquals(TestEnum.TEST_VALUE, consumer.getEnumValue()); <ide> } <ide> <add> @Test <add> public void cornerSpr10115() { <add> Spr10115Bean foo = new Spr10115Bean(); <add> BeanWrapperImpl bwi = new BeanWrapperImpl(); <add> bwi.setWrappedInstance(foo); <add> bwi.setPropertyValue("prop1", "val1"); <add> assertEquals("val1", Spr10115Bean.prop1); <add> } <add> <add> <add> static class Spr10115Bean { <add> private static String prop1; <add> <add> public static void setProp1(String prop1) { <add> Spr10115Bean.prop1 = prop1; <add> } <add> } <add> <ide> <ide> private static class Foo { <ide> <ide><path>spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java <ide> public void setAddress(int index, String addr) { } <ide> assertThat(hasIndexedWriteMethodForProperty(bi, "address"), is(true)); <ide> } <ide> } <add> <add> @Test <add> public void shouldSupportStaticWriteMethod() throws IntrospectionException { <add> { <add> BeanInfo bi = Introspector.getBeanInfo(WithStaticWriteMethod.class); <add> assertThat(hasReadMethodForProperty(bi, "prop1"), is(false)); <add> assertThat(hasWriteMethodForProperty(bi, "prop1"), is(false)); <add> assertThat(hasIndexedReadMethodForProperty(bi, "prop1"), is(false)); <add> assertThat(hasIndexedWriteMethodForProperty(bi, "prop1"), is(false)); <add> } <add> { <add> BeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(WithStaticWriteMethod.class)); <add> assertThat(hasReadMethodForProperty(bi, "prop1"), is(false)); <add> assertThat(hasWriteMethodForProperty(bi, "prop1"), is(true)); <add> assertThat(hasIndexedReadMethodForProperty(bi, "prop1"), is(false)); <add> assertThat(hasIndexedWriteMethodForProperty(bi, "prop1"), is(false)); <add> } <add> } <add> <add> static class WithStaticWriteMethod { <add> @SuppressWarnings("unused") <add> public static void setProp1(String prop1) { <add> } <add> } <ide> }
4
Javascript
Javascript
add test for isvaliddescriptor
697bf73c5f37049b1e9b048aa23007ca50f4b26d
<ide><path>src/core/__tests__/ReactDescriptor-test.js <add>/** <add> * Copyright 2013-2014 Facebook, Inc. <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> * @jsx React.DOM <add> * @emails react-core <add> */ <add> <add>"use strict"; <add> <add>var React; <add>var ReactDescriptor; <add> <add>describe('ReactDescriptor', function() { <add> beforeEach(function() { <add> React = require('React'); <add> ReactDescriptor = require('ReactDescriptor'); <add> }); <add> <add> it('should identify valid descriptors correctly', function() { <add> var Component = React.createClass({ <add> render: function() { <add> return <div />; <add> } <add> }); <add> <add> expect(ReactDescriptor.isValidDescriptor(<div />)).toEqual(true); <add> expect(ReactDescriptor.isValidDescriptor(<Component />)).toEqual(true); <add> <add> expect(ReactDescriptor.isValidDescriptor(null)).toEqual(false); <add> expect(ReactDescriptor.isValidDescriptor(true)).toEqual(false); <add> expect(ReactDescriptor.isValidDescriptor({})).toEqual(false); <add> expect(ReactDescriptor.isValidDescriptor("string")).toEqual(false); <add> expect(ReactDescriptor.isValidDescriptor(React.DOM.div)).toEqual(false); <add> expect(ReactDescriptor.isValidDescriptor(Component)).toEqual(false); <add> }); <add>});
1
Python
Python
add multisoftmax class
b10d0cce05ee6ff90362f0571ae386ab03da01ad
<ide><path>spacy/_ml.py <ide> def getitem_fwd(X, drop=0.): <ide> return layerize(getitem_fwd) <ide> <ide> <del>def build_tagger_model(nr_class, **cfg): <add>@describe.attributes( <add> W=Synapses("Weights matrix", <add> lambda obj: (obj.nO, obj.nI), <add> lambda W, ops: None) <add>) <add>class MultiSoftmax(Affine): <add> '''Neural network layer that predicts several multi-class attributes at once. <add> For instance, we might predict one class with 6 variables, and another with 5. <add> We predict the 11 neurons required for this, and then softmax them such <add> that columns 0-6 make a probability distribution and coumns 6-11 make another. <add> ''' <add> name = 'multisoftmax' <add> <add> def __init__(self, out_sizes, nI=None, **kwargs): <add> Model.__init__(self, **kwargs) <add> self.out_sizes = out_sizes <add> self.nO = sum(out_sizes) <add> self.nI = nI <add> <add> def predict(self, input__BI): <add> output__BO = self.ops.affine(self.W, self.b, input__BI) <add> i = 0 <add> for out_size in self.out_sizes: <add> self.ops.softmax(output__BO[:, i : i+out_size], inplace=True) <add> i += out_size <add> return output__BO <add> <add> def begin_update(self, input__BI, drop=0.): <add> output__BO = self.predict(input__BI) <add> def finish_update(grad__BO, sgd=None): <add> self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True) <add> self.d_b += grad__BO.sum(axis=0) <add> grad__BI = self.ops.gemm(grad__BO, self.W) <add> if sgd is not None: <add> sgd(self._mem.weights, self._mem.gradient, key=self.id) <add> return grad__BI <add> return output__BO, finish_update <add> <add> <add>def build_tagger_model(class_nums, **cfg): <ide> embed_size = util.env_opt('embed_size', 7000) <ide> if 'token_vector_width' in cfg: <ide> token_vector_width = cfg['token_vector_width'] <ide> def build_tagger_model(nr_class, **cfg): <ide> tok2vec = Tok2Vec(token_vector_width, embed_size, <ide> subword_features=subword_features, <ide> pretrained_vectors=pretrained_vectors) <del> softmax = with_flatten(Softmax(nr_class, token_vector_width)) <add> softmax = with_flatten( <add> MultiSoftmax(class_nums, token_vector_width)) <ide> model = ( <ide> tok2vec <ide> >> softmax
1
Javascript
Javascript
remove ballmer example
1876bc2432286b0378ee48449ca5bf9145e6691f
<ide><path>examples/ballmer-peak/example.js <del>'use strict'; <del> <del>function computeBallmerPeak(x) { <del> // see: http://ask.metafilter.com/76859/Make-a-function-of-this-graph-Thats-like-an-antigraph <del> x = x * 100; <del> return ( <del> 1 - 1 / (1 + Math.exp(-(x - 6))) *.5 + Math.exp(-Math.pow(Math.abs(x - 10), 2) * 10) <del> ) / 1.6; <del>} <del> <del>function percentage(x) { <del> return isNaN(x) ? 'N/A' : (100 - Math.round(x * 100)) + '%'; <del>} <del> <del>var BallmerPeakCalculator = React.createClass({ <del> getInitialState: function() { <del> return {bac: 0}; <del> }, <del> handleChange: function(event) { <del> this.setState({bac: event.target.value}); <del> }, <del> render: function() { <del> var pct = percentage(computeBallmerPeak(this.state.bac)); <del> return ( <del> <div> <del> <img src="./ballmer_peak.png" /> <del> <p>Credit due to <a href="http://xkcd.com/323/">xkcd</a>.</p> <del> <h4>Compute your Ballmer Peak:</h4> <del> <p> <del> If your BAC is{' '} <del> <input type="text" onChange={this.handleChange} value={this.state.bac} /> <del> {', '}then <b>{pct}</b> of your lines of code will be bug free. <del> </p> <del> </div> <del> ); <del> } <del>}); <del> <del>React.render( <del> <BallmerPeakCalculator />, <del> document.getElementById('container') <del>);
1
Javascript
Javascript
display timeend with suitable time unit
66043e18128dc80457f4e184b7ed7faedcd93ca7
<ide><path>lib/internal/console/constructor.js <ide> const kTraceBegin = 'b'.charCodeAt(0); <ide> const kTraceEnd = 'e'.charCodeAt(0); <ide> const kTraceInstant = 'n'.charCodeAt(0); <ide> <add>const kSecond = 1000; <add>const kMinute = 60 * kSecond; <add>const kHour = 60 * kMinute; <add> <ide> const { <ide> isArray: ArrayIsArray, <ide> from: ArrayFrom, <ide> function timeLogImpl(self, name, label, data) { <ide> } <ide> const duration = process.hrtime(time); <ide> const ms = duration[0] * 1000 + duration[1] / 1e6; <add> <add> const formatted = formatTime(ms); <add> <ide> if (data === undefined) { <del> self.log('%s: %sms', label, ms.toFixed(3)); <add> self.log('%s: %s', label, formatted); <ide> } else { <del> self.log('%s: %sms', label, ms.toFixed(3), ...data); <add> self.log('%s: %s', label, formatted, ...data); <ide> } <ide> return true; <ide> } <ide> <add>function formatTime(ms) { <add> let value = ms; <add> let unit = 'ms'; <add> <add> if (ms >= kHour) { <add> value = ms / kHour; <add> unit = 'h'; <add> } else if (ms >= kMinute) { <add> value = ms / kMinute; <add> unit = 'min'; <add> } else if (ms >= kSecond) { <add> value = ms / kSecond; <add> unit = 's'; <add> } <add> <add> return value.toFixed(3) + unit; <add>} <add> <ide> const keyKey = 'Key'; <ide> const valuesKey = 'Values'; <ide> const indexKey = '(index)'; <ide> Console.prototype.groupCollapsed = Console.prototype.group; <ide> module.exports = { <ide> Console, <ide> kBindStreamsLazy, <del> kBindProperties <add> kBindProperties, <add> formatTime // exported for tests <ide> }; <ide><path>test/parallel/test-console-formatTime.js <add>'use strict'; <add>// Flags: --expose-internals <add>require('../common'); <add>const { formatTime } = require('internal/console/constructor'); <add>const assert = require('assert'); <add> <add>const test1 = formatTime(100); <add>const test2 = formatTime(1500); <add>const test3 = formatTime(60300); <add>const test4 = formatTime(4000000); <add> <add>assert.strictEqual(test1, '100.000ms'); <add>assert.strictEqual(test2, '1.500s'); <add>assert.strictEqual(test3, '1.005min'); <add>assert.strictEqual(test4, '1.111h'); <ide><path>test/parallel/test-console.js <ide> assert.ok(strings[0].includes('foo: { bar: { baz:')); <ide> assert.ok(strings[0].includes('quux')); <ide> assert.ok(strings.shift().includes('quux: true')); <ide> <del>assert.ok(/^label: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^__proto__: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^constructor: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^hasOwnProperty: \d+\.\d{3}ms$/.test(strings.shift().trim())); <add>assert.ok(/^label: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^__proto__: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^constructor: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^hasOwnProperty: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <ide> <ide> // Verify that console.time() coerces label values to strings as expected <del>assert.ok(/^: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^\[object Object\]: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^\[object Object\]: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^null: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^default: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^default: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^NaN: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del> <del>assert.ok(/^log1: \d+\.\d{3}ms$/.test(strings.shift().trim())); <del>assert.ok(/^log1: \d+\.\d{3}ms test$/.test(strings.shift().trim())); <del>assert.ok(/^log1: \d+\.\d{3}ms {} \[ 1, 2, 3 ]$/.test(strings.shift().trim())); <del>assert.ok(/^log1: \d+\.\d{3}ms$/.test(strings.shift().trim())); <add>assert.ok(/^: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^\[object Object\]: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^\[object Object\]: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^null: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^default: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^default: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^NaN: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add> <add>assert.ok(/^log1: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <add>assert.ok(/^log1: \d+\.\d{3}(ms|s|min|h) test$/.test(strings.shift().trim())); <add>assert.ok(/^log1: \d+\.\d{3}(ms|s|min|h) {} \[ 1, 2, 3 ]$/.test(strings.shift().trim())); <add>assert.ok(/^log1: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim())); <ide> <ide> // Make sure that we checked all strings <ide> assert.strictEqual(strings.length, 0);
3
Text
Text
add charcode/keycode/which to key event docs
b366e363676ea55f878237bc44aca1f450415343
<ide><path>docs/docs/ref-05-events.md <ide> Properties: <ide> <ide> ```javascript <ide> boolean altKey <del>String char <ide> boolean ctrlKey <add>Number charCode <ide> String key <add>Number keyCode <ide> String locale <ide> Number location <ide> boolean metaKey <ide> boolean repeat <ide> boolean shiftKey <add>Number which <ide> ``` <ide> <ide>
1
Ruby
Ruby
fix #after_validation example [ci skip]
1ca957c5bb6d33a84a0a69681e66de79c702930d
<ide><path>activemodel/lib/active_model/validations/callbacks.rb <ide> def before_validation(*args, &block) <ide> # private <ide> # <ide> # def set_status <del> # self.status = (errors.empty?) ? true : false <add> # self.status = errors.empty? <ide> # end <ide> # end <ide> #
1
Python
Python
avoid crach on olds kernels (issue #554)
3a7856831c0d797f82a3bb47d581e1c54dd5120d
<ide><path>glances/core/glances_processes.py <ide> def __get_process_stats(self, proc, <ide> # Get the process IO counters <ide> proc_io = proc.io_counters() <ide> io_new = [proc_io.read_bytes, proc_io.write_bytes] <del> except (psutil.AccessDenied, psutil.NoSuchProcess): <add> except (psutil.AccessDenied, psutil.NoSuchProcess, NotImplementedError): <ide> # Access denied to process IO (no root account) <ide> # NoSuchProcess (process die between first and second grab) <ide> # Put 0 in all values (for sort) and io_tag = 0 (for
1
Javascript
Javascript
add 2 additional tests for polish language
2da08c94599e77ca027044b93927c0146a1e415c
<ide><path>test/lang/pl.js <ide> exports["lang:pl"] = { <ide> }, <ide> <ide> "from" : function (test) { <del> test.expect(32); <add> test.expect(34); <ide> <ide> var start = moment([2007, 1, 28]); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "kilka sekund", "44 seconds = a few seconds"); <ide> exports["lang:pl"] = { <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "rok", "1 year = a year"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "5 lat", "5 years = 5 years"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 112}), true), "112 lat", "112 years = 112 years"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y: 122}), true), "122 lata", "122 years = 122 years"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 213}), true), "213 lat", "213 years = 213 years"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y: 223}), true), "223 lata", "223 years = 223 years"); <ide> test.done(); <ide> }, <ide>
1
Javascript
Javascript
add names to components in hello-world example
f13ca3055ca31fc5c03d8e9fc187c0fba15a2245
<ide><path>examples/hello-world/pages/about.js <del>export default () => <div>About us</div> <add>export default function AboutPage() { <add> return <div>About us</div> <add>} <ide><path>examples/hello-world/pages/day/index.js <del>export default () => <div>Hello Day</div> <add>export default function DayPage() { <add> return <div>Hello Day</div> <add>} <ide><path>examples/hello-world/pages/index.js <ide> import Link from 'next/link' <del>export default () => ( <del> <div> <del> Hello World.{' '} <del> <Link href="/about"> <del> <a>About</a> <del> </Link> <del> </div> <del>) <add> <add>export function IndexPage() { <add> return ( <add> <div> <add> Hello World.{' '} <add> <Link href="/about"> <add> <a>About</a> <add> </Link> <add> </div> <add> ) <add>}
3
Text
Text
fix remote name in airflow publishing guide
716c6355224b1d40b6475c2fa60f0b967204fce6
<ide><path>dev/README_RELEASE_AIRFLOW.md <ide> The Release Candidate artifacts we vote upon should be the exact ones we vote ag <ide> - Tag & Push the latest constraints files. This pushes constraints with rc suffix (this is expected)! <ide> <ide> ```shell script <del> git checkout constraints-${VERSION_CONSTRAINT_BRANCH} <add> git checkout origin/constraints-${VERSION_CONSTRAINT_BRANCH} <ide> git tag -s "constraints-${VERSION}" <ide> git push origin "constraints-${VERSION}" <ide> ```
1
Text
Text
remove stray g
d4dfdd17ff7fce23ebfb7edf7a95bda1abfda905
<ide><path>docs/publishing-a-package.md <ide> This guide will show you how to publish a package or theme to the <ide> [atom.io][atomio] package registry. <ide> <del>Publishing a package allows other people to install it and use it in Atomg. It <add>Publishing a package allows other people to install it and use it in Atom. It <ide> is a great way to share what you've made and get feedback and contributions from <ide> others. <ide>
1
Mixed
Javascript
add `maxoutputlength` option
278aae28e14da89e6bd6d91c07ded2dc5f8fe8c3
<ide><path>doc/api/zlib.md <ide> These advanced options are available for controlling decompression: <ide> <!-- YAML <ide> added: v0.11.1 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/33516 <add> description: The `maxOutputLength` option is supported now. <ide> - version: v9.4.0 <ide> pr-url: https://github.com/nodejs/node/pull/16042 <ide> description: The `dictionary` option can be an `ArrayBuffer`. <ide> ignored by the decompression classes. <ide> * `dictionary` {Buffer|TypedArray|DataView|ArrayBuffer} (deflate/inflate only, <ide> empty dictionary by default) <ide> * `info` {boolean} (If `true`, returns an object with `buffer` and `engine`.) <add>* `maxOutputLength` {integer} Limits output size when using <add> [convenience methods][]. **Default:** [`buffer.kMaxLength`][] <ide> <ide> See the [`deflateInit2` and `inflateInit2`][] documentation for more <ide> information. <ide> <ide> ## Class: `BrotliOptions` <ide> <!-- YAML <ide> added: v11.7.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/33516 <add> description: The `maxOutputLength` option is supported now. <ide> --> <ide> <ide> <!--type=misc--> <ide> Each Brotli-based class takes an `options` object. All options are optional. <ide> * `finishFlush` {integer} **Default:** `zlib.constants.BROTLI_OPERATION_FINISH` <ide> * `chunkSize` {integer} **Default:** `16 * 1024` <ide> * `params` {Object} Key-value object containing indexed [Brotli parameters][]. <add>* `maxOutputLength` {integer} Limits output size when using <add> [convenience methods][]. **Default:** [`buffer.kMaxLength`][] <ide> <ide> For example: <ide> <ide> Decompress a chunk of data with [`Unzip`][]. <ide> [`BrotliCompress`]: #zlib_class_zlib_brotlicompress <ide> [`BrotliDecompress`]: #zlib_class_zlib_brotlidecompress <ide> [`Buffer`]: buffer.html#buffer_class_buffer <add>[`buffer.kMaxLength`]: buffer.html#buffer_buffer_kmaxlength <ide> [`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 <ide> [`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView <ide> [`DeflateRaw`]: #zlib_class_zlib_deflateraw <ide> Decompress a chunk of data with [`Unzip`][]. <ide> [Memory Usage Tuning]: #zlib_memory_usage_tuning <ide> [RFC 7932]: https://www.rfc-editor.org/rfc/rfc7932.txt <ide> [Streams API]: stream.md <add>[convenience methods]: #zlib_convenience_methods <ide> [zlib documentation]: https://zlib.net/manual.html#Constants <ide> [zlib.createGzip example]: #zlib_zlib <ide><path>lib/internal/errors.js <ide> const kTypes = [ <ide> 'symbol' <ide> ]; <ide> <del>const { kMaxLength } = internalBinding('buffer'); <del> <ide> const MainContextError = Error; <ide> const ErrorToString = Error.prototype.toString; <ide> const overrideStackTrace = new WeakMap(); <ide> E('ERR_BUFFER_OUT_OF_BOUNDS', <ide> return 'Attempt to access memory outside buffer bounds'; <ide> }, RangeError); <ide> E('ERR_BUFFER_TOO_LARGE', <del> `Cannot create a Buffer larger than 0x${kMaxLength.toString(16)} bytes`, <add> 'Cannot create a Buffer larger than %s bytes', <ide> RangeError); <ide> E('ERR_CANNOT_WATCH_SIGINT', 'Cannot watch for SIGINT signals', Error); <ide> E('ERR_CHILD_CLOSED_BEFORE_REPLY', <ide><path>lib/zlib.js <ide> function zlibBufferOnData(chunk) { <ide> else <ide> this.buffers.push(chunk); <ide> this.nread += chunk.length; <add> if (this.nread > this._maxOutputLength) { <add> this.close(); <add> this.removeAllListeners('end'); <add> this.cb(new ERR_BUFFER_TOO_LARGE(this._maxOutputLength)); <add> } <ide> } <ide> <ide> function zlibBufferOnError(err) { <ide> function zlibBufferOnError(err) { <ide> function zlibBufferOnEnd() { <ide> let buf; <ide> let err; <del> if (this.nread >= kMaxLength) { <del> err = new ERR_BUFFER_TOO_LARGE(); <del> } else if (this.nread === 0) { <add> if (this.nread === 0) { <ide> buf = Buffer.alloc(0); <ide> } else { <ide> const bufs = this.buffers; <ide> const checkRangesOrGetDefault = hideStackFrames( <ide> // The base class for all Zlib-style streams. <ide> function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) { <ide> let chunkSize = Z_DEFAULT_CHUNK; <add> let maxOutputLength = kMaxLength; <ide> // The ZlibBase class is not exported to user land, the mode should only be <ide> // passed in by us. <ide> assert(typeof mode === 'number'); <ide> function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) { <ide> opts.finishFlush, 'options.finishFlush', <ide> Z_NO_FLUSH, Z_BLOCK, finishFlush); <ide> <add> maxOutputLength = checkRangesOrGetDefault( <add> opts.maxOutputLength, 'options.maxOutputLength', <add> 1, kMaxLength, kMaxLength); <add> <ide> if (opts.encoding || opts.objectMode || opts.writableObjectMode) { <ide> opts = { ...opts }; <ide> opts.encoding = null; <ide> function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) { <ide> this._finishFlushFlag = finishFlush; <ide> this._defaultFullFlushFlag = fullFlush; <ide> this._info = opts && opts.info; <add> this._maxOutputLength = maxOutputLength; <ide> } <ide> ObjectSetPrototypeOf(ZlibBase.prototype, Transform.prototype); <ide> ObjectSetPrototypeOf(ZlibBase, Transform); <ide> function processChunkSync(self, chunk, flushFlag) { <ide> else <ide> buffers.push(out); <ide> nread += out.byteLength; <add> <add> if (nread > self._maxOutputLength) { <add> _close(self); <add> throw new ERR_BUFFER_TOO_LARGE(self._maxOutputLength); <add> } <add> <ide> } else { <ide> assert(have === 0, 'have should not go down'); <ide> } <ide> function processChunkSync(self, chunk, flushFlag) { <ide> self.bytesWritten = inputRead; <ide> _close(self); <ide> <del> if (nread >= kMaxLength) { <del> throw new ERR_BUFFER_TOO_LARGE(); <del> } <del> <ide> if (nread === 0) <ide> return Buffer.alloc(0); <ide> <ide><path>test/parallel/test-zlib-brotli-kmaxlength-rangeerror.js <ide> const assert = require('assert'); <ide> // large Buffers. <ide> const buffer = require('buffer'); <ide> const oldkMaxLength = buffer.kMaxLength; <del>buffer.kMaxLength = 128; <add>buffer.kMaxLength = 64; <ide> const zlib = require('zlib'); <ide> buffer.kMaxLength = oldkMaxLength; <ide> <ide><path>test/parallel/test-zlib-kmaxlength-rangeerror.js <ide> const assert = require('assert'); <ide> // large Buffers. <ide> const buffer = require('buffer'); <ide> const oldkMaxLength = buffer.kMaxLength; <del>buffer.kMaxLength = 128; <add>buffer.kMaxLength = 64; <ide> const zlib = require('zlib'); <ide> buffer.kMaxLength = oldkMaxLength; <ide> <ide><path>test/parallel/test-zlib-maxOutputLength.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const zlib = require('zlib'); <add> <add>const encoded = Buffer.from('G38A+CXCIrFAIAM=', 'base64'); <add> <add>// Async <add>zlib.brotliDecompress(encoded, { maxOutputLength: 64 }, common.expectsError({ <add> code: 'ERR_BUFFER_TOO_LARGE', <add> message: 'Cannot create a Buffer larger than 64 bytes' <add>})); <add> <add>// Sync <add>assert.throws(function() { <add> zlib.brotliDecompressSync(encoded, { maxOutputLength: 64 }); <add>}, RangeError); <add> <add>// Async <add>zlib.brotliDecompress(encoded, { maxOutputLength: 256 }, function(err) { <add> assert.strictEqual(err, null); <add>}); <add> <add>// Sync <add>zlib.brotliDecompressSync(encoded, { maxOutputLength: 256 });
6
Python
Python
respect the no_skip value
284b530c631e7e7d110b519d54f591d66c754e13
<ide><path>spacy/cli/project/run.py <ide> def check_rerun( <ide> strict_version (bool): <ide> RETURNS (bool): Whether to re-run the command. <ide> """ <add> # Always rerun if no-skip is set <add> if command.get("no_skip", False): <add> return True <ide> lock_path = project_dir / PROJECT_LOCK <ide> if not lock_path.exists(): # We don't have a lockfile, run command <ide> return True
1
Go
Go
add integration test for history option
08150150bbc4477cbcf8286bc15a1cf8b4428e35
<ide><path>integration-cli/docker_cli_history_test.go <ide> package main <ide> import ( <ide> "fmt" <ide> "os/exec" <add> "regexp" <add> "strconv" <ide> "strings" <ide> <ide> "github.com/go-check/check" <ide> func (s *DockerSuite) TestHistoryImageWithComment(c *check.C) { <ide> } <ide> <ide> } <add> <add>func (s *DockerSuite) TestHistoryHumanOptionFalse(c *check.C) { <add> out, _, _ := runCommandWithOutput(exec.Command(dockerBinary, "history", "--human=false", "busybox")) <add> lines := strings.Split(out, "\n") <add> sizeColumnRegex, _ := regexp.Compile("SIZE +") <add> indices := sizeColumnRegex.FindStringIndex(lines[0]) <add> startIndex := indices[0] <add> endIndex := indices[1] <add> for i := 1; i < len(lines)-1; i++ { <add> if endIndex > len(lines[i]) { <add> endIndex = len(lines[i]) <add> } <add> sizeString := lines[i][startIndex:endIndex] <add> if _, err := strconv.Atoi(strings.TrimSpace(sizeString)); err != nil { <add> c.Fatalf("The size '%s' was not an Integer", sizeString) <add> } <add> } <add>} <add> <add>func (s *DockerSuite) TestHistoryHumanOptionTrue(c *check.C) { <add> out, _, _ := runCommandWithOutput(exec.Command(dockerBinary, "history", "--human=true", "busybox")) <add> lines := strings.Split(out, "\n") <add> sizeColumnRegex, _ := regexp.Compile("SIZE +") <add> humanSizeRegex, _ := regexp.Compile("^\\d+.*B$") // Matches human sizes like 10 MB, 3.2 KB, etc <add> indices := sizeColumnRegex.FindStringIndex(lines[0]) <add> startIndex := indices[0] <add> endIndex := indices[1] <add> for i := 1; i < len(lines)-1; i++ { <add> if endIndex > len(lines[i]) { <add> endIndex = len(lines[i]) <add> } <add> sizeString := lines[i][startIndex:endIndex] <add> if matchSuccess := humanSizeRegex.MatchString(strings.TrimSpace(sizeString)); !matchSuccess { <add> c.Fatalf("The size '%s' was not in human format", sizeString) <add> } <add> } <add>}
1
Javascript
Javascript
refine flags and handling of enablelegacyfbsupport
d5e4b3ae1d5f7d76bb3894e8d814fd4ba19dcfd5
<ide><path>packages/legacy-events/EventSystemFlags.js <ide> export type EventSystemFlags = number; <ide> <ide> export const PLUGIN_EVENT_SYSTEM = 1; <ide> export const RESPONDER_EVENT_SYSTEM = 1 << 1; <del>export const IS_PASSIVE = 1 << 2; <del>export const IS_ACTIVE = 1 << 3; <del>export const PASSIVE_NOT_SUPPORTED = 1 << 4; <del>export const IS_REPLAYED = 1 << 5; <del>export const IS_FIRST_ANCESTOR = 1 << 6; <del>export const IS_TARGET_EVENT_ONLY = 1 << 7; <add>export const USE_EVENT_SYSTEM = 1 << 2; <add>export const IS_TARGET_PHASE_ONLY = 1 << 3; <add>export const IS_PASSIVE = 1 << 4; <add>export const PASSIVE_NOT_SUPPORTED = 1 << 5; <add>export const IS_REPLAYED = 1 << 6; <add>export const IS_FIRST_ANCESTOR = 1 << 7; <ide> export const LEGACY_FB_SUPPORT = 1 << 8; <ide><path>packages/react-dom/src/__tests__/ReactDOM-test.js <ide> let React; <ide> let ReactDOM; <ide> let ReactDOMServer; <ide> let ReactTestUtils; <add>const ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> <ide> describe('ReactDOM', () => { <ide> beforeEach(() => { <ide> describe('ReactDOM', () => { <ide> document.body.appendChild(container); <ide> try { <ide> ReactDOM.render(<Wrapper />, container); <add> let expected; <add> <add> if ( <add> ReactFeatureFlags.enableModernEventSystem & <add> ReactFeatureFlags.enableLegacyFBSupport <add> ) { <add> // We expect to duplicate the 2nd handler because this test is <add> // not really designed around how the legacy FB support system works. <add> // This is because the above test sync fires a click() event <add> // during that of another click event, which causes the FB support system <add> // to duplicate adding an event listener. In practice this would never <add> // happen, as we only apply the legacy FB logic for "click" events, <add> // which would never stack this way in product code. <add> expected = [ <add> '1st node clicked', <add> "2nd node clicked imperatively from 1st's handler", <add> "2nd node clicked imperatively from 1st's handler", <add> ]; <add> } else { <add> expected = [ <add> '1st node clicked', <add> "2nd node clicked imperatively from 1st's handler", <add> ]; <add> } <ide> <del> const expected = [ <del> '1st node clicked', <del> "2nd node clicked imperatively from 1st's handler", <del> ]; <ide> expect(actual).toEqual(expected); <ide> } finally { <ide> document.body.removeChild(container); <ide><path>packages/react-dom/src/__tests__/ReactDOMComponent-test.js <ide> describe('ReactDOMComponent', () => { <ide> let ReactTestUtils; <ide> let ReactDOM; <ide> let ReactDOMServer; <add> const ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> <ide> function normalizeCodeLocInfo(str) { <ide> return str && str.replace(/\(at .+?:\d+\)/g, '(at **)'); <ide> describe('ReactDOMComponent', () => { <ide> // might depend on this. <ide> // <ide> // @see https://github.com/facebook/react/pull/12919#issuecomment-395224674 <del> expect(eventOrder).toEqual([ <del> 'document capture', <del> 'inner capture', <del> 'inner bubble', <del> 'outer capture', <del> 'outer bubble', <del> 'document bubble', <del> ]); <add> if ( <add> ReactFeatureFlags.enableModernEventSystem & <add> ReactFeatureFlags.enableLegacyFBSupport <add> ) { <add> // The order will change here, as the legacy FB support adds <add> // the event listener onto the document after the one above has. <add> expect(eventOrder).toEqual([ <add> 'document capture', <add> 'document bubble', <add> 'inner capture', <add> 'inner bubble', <add> 'outer capture', <add> 'outer bubble', <add> ]); <add> } else { <add> expect(eventOrder).toEqual([ <add> 'document capture', <add> 'inner capture', <add> 'inner bubble', <add> 'outer capture', <add> 'outer bubble', <add> 'document bubble', <add> ]); <add> } <ide> } finally { <ide> document.body.removeChild(container); <ide> } <ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js <ide> import {HostComponent} from 'react-reconciler/src/ReactWorkTags'; <ide> import { <ide> RESPONDER_EVENT_SYSTEM, <ide> IS_PASSIVE, <add> PLUGIN_EVENT_SYSTEM, <add> USE_EVENT_SYSTEM, <ide> } from 'legacy-events/EventSystemFlags'; <ide> import { <ide> isManagedDOMElement, <ide> export function registerEvent( <ide> type, <ide> rootContainerInstance, <ide> listenerMap, <add> PLUGIN_EVENT_SYSTEM | USE_EVENT_SYSTEM, <ide> passive, <ide> priority, <ide> ); <ide><path>packages/react-dom/src/events/DOMLegacyEventPluginSystem.js <ide> import { <ide> HostComponent, <ide> HostText, <ide> } from 'react-reconciler/src/ReactWorkTags'; <del>import {IS_FIRST_ANCESTOR} from 'legacy-events/EventSystemFlags'; <add>import { <add> IS_FIRST_ANCESTOR, <add> PLUGIN_EVENT_SYSTEM, <add>} from 'legacy-events/EventSystemFlags'; <ide> import {batchedEventUpdates} from 'legacy-events/ReactGenericBatching'; <ide> import {runEventsInBatch} from 'legacy-events/EventBatching'; <ide> import {plugins} from 'legacy-events/EventPluginRegistry'; <ide> export function legacyTrapBubbledEvent( <ide> element: Document | Element, <ide> listenerMap?: ElementListenerMap, <ide> ): void { <del> const listener = addTrappedEventListener(element, topLevelType, false); <add> const listener = addTrappedEventListener( <add> element, <add> topLevelType, <add> PLUGIN_EVENT_SYSTEM, <add> false, <add> ); <ide> if (listenerMap) { <ide> listenerMap.set(topLevelType, {passive: undefined, listener}); <ide> } <ide> export function legacyTrapCapturedEvent( <ide> element: Document | Element, <ide> listenerMap: ElementListenerMap, <ide> ): void { <del> const listener = addTrappedEventListener(element, topLevelType, true); <add> const listener = addTrappedEventListener( <add> element, <add> topLevelType, <add> PLUGIN_EVENT_SYSTEM, <add> true, <add> ); <ide> listenerMap.set(topLevelType, {passive: undefined, listener}); <ide> } <ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js <ide> import {batchedEventUpdates} from 'legacy-events/ReactGenericBatching'; <ide> import {executeDispatchesInOrder} from 'legacy-events/EventPluginUtils'; <ide> import {plugins} from 'legacy-events/EventPluginRegistry'; <ide> import { <add> PLUGIN_EVENT_SYSTEM, <ide> LEGACY_FB_SUPPORT, <ide> IS_REPLAYED, <del> IS_TARGET_EVENT_ONLY, <add> IS_TARGET_PHASE_ONLY, <add> USE_EVENT_SYSTEM, <ide> } from 'legacy-events/EventSystemFlags'; <ide> <ide> import {HostRoot, HostPortal} from 'react-reconciler/src/ReactWorkTags'; <ide> export function listenToTopLevelEvent( <ide> topLevelType: DOMTopLevelEventType, <ide> targetContainer: EventTarget, <ide> listenerMap: ElementListenerMap, <add> eventSystemFlags: EventSystemFlags, <ide> passive?: boolean, <ide> priority?: EventPriority, <ide> capture?: boolean, <ide> export function listenToTopLevelEvent( <ide> const listener = addTrappedEventListener( <ide> targetContainer, <ide> topLevelType, <add> eventSystemFlags, <ide> isCapturePhase, <ide> false, <ide> passive, <ide> export function listenToEvent( <ide> <ide> for (let i = 0; i < dependencies.length; i++) { <ide> const dependency = dependencies[i]; <del> listenToTopLevelEvent(dependency, rootContainerElement, listenerMap); <add> listenToTopLevelEvent( <add> dependency, <add> rootContainerElement, <add> listenerMap, <add> PLUGIN_EVENT_SYSTEM, <add> ); <ide> } <ide> } <ide> <ide> function willDeferLaterForLegacyFBSupport( <ide> addTrappedEventListener( <ide> targetContainer, <ide> topLevelType, <add> PLUGIN_EVENT_SYSTEM | LEGACY_FB_SUPPORT, <ide> false, <ide> isDeferredListenerForLegacyFBSupport, <ide> ); <ide> export function dispatchEventForPluginEventSystem( <ide> ): void { <ide> let ancestorInst = targetInst; <ide> if (targetContainer !== null) { <del> if (eventTargetEventListenerStore.has(targetContainer)) { <add> if (eventSystemFlags & IS_TARGET_PHASE_ONLY) { <ide> // For TargetEvent nodes (i.e. document, window) <ide> ancestorInst = null; <del> eventSystemFlags |= IS_TARGET_EVENT_ONLY; <ide> } else { <ide> const targetContainerNode = ((targetContainer: any): Node); <ide> <ide> export function dispatchEventForPluginEventSystem( <ide> (eventSystemFlags & LEGACY_FB_SUPPORT) === 0 && <ide> // We also don't want to defer during event replaying. <ide> (eventSystemFlags & IS_REPLAYED) === 0 && <add> // We don't want to apply the legacy FB support for the useEvent API. <add> (eventSystemFlags & USE_EVENT_SYSTEM) === 0 && <ide> willDeferLaterForLegacyFBSupport(topLevelType, targetContainer) <ide> ) { <ide> return; <ide> export function attachListenerToManagedDOMElement( <ide> type, <ide> containerEventTarget, <ide> listenerMap, <add> PLUGIN_EVENT_SYSTEM | USE_EVENT_SYSTEM, <ide> passive, <ide> priority, <ide> ); <ide> export function attachTargetEventListener(listener: ReactDOMListener): void { <ide> type, <ide> eventTarget, <ide> listenerMap, <add> PLUGIN_EVENT_SYSTEM | USE_EVENT_SYSTEM | IS_TARGET_PHASE_ONLY, <ide> passive, <ide> priority, <ide> capture, <ide><path>packages/react-dom/src/events/ReactDOMEventListener.js <ide> import { <ide> import {HostRoot, SuspenseComponent} from 'react-reconciler/src/ReactWorkTags'; <ide> import { <ide> type EventSystemFlags, <add> LEGACY_FB_SUPPORT, <ide> PLUGIN_EVENT_SYSTEM, <ide> RESPONDER_EVENT_SYSTEM, <ide> IS_PASSIVE, <del> IS_ACTIVE, <ide> PASSIVE_NOT_SUPPORTED, <del> LEGACY_FB_SUPPORT, <ide> } from 'legacy-events/EventSystemFlags'; <ide> <ide> import { <ide> export function addResponderEventSystemEvent( <ide> if (passiveBrowserEventsSupported) { <ide> eventFlags |= IS_PASSIVE; <ide> } else { <del> eventFlags |= IS_ACTIVE; <ide> eventFlags |= PASSIVE_NOT_SUPPORTED; <ide> passive = false; <ide> } <del> } else { <del> eventFlags |= IS_ACTIVE; <ide> } <ide> // Check if interactive and wrap in discreteUpdates <ide> const listener = dispatchEvent.bind( <ide> export function addResponderEventSystemEvent( <ide> export function addTrappedEventListener( <ide> targetContainer: EventTarget, <ide> topLevelType: DOMTopLevelEventType, <add> eventSystemFlags: EventSystemFlags, <ide> capture: boolean, <ide> isDeferredListenerForLegacyFBSupport?: boolean, <ide> passive?: boolean, <ide> export function addTrappedEventListener( <ide> if (passive === true && !passiveBrowserEventsSupported) { <ide> passive = false; <ide> } <del> const eventSystemFlags = <del> enableLegacyFBSupport && isDeferredListenerForLegacyFBSupport <del> ? PLUGIN_EVENT_SYSTEM | LEGACY_FB_SUPPORT <del> : PLUGIN_EVENT_SYSTEM; <ide> <ide> listener = listenerWrapper.bind( <ide> null, <ide> function dispatchDiscreteEvent( <ide> container, <ide> nativeEvent, <ide> ) { <del> flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp); <add> if ( <add> !enableLegacyFBSupport || <add> // If we have Legacy FB support, it means we've already <add> // flushed for this event and we don't need to do it again. <add> (eventSystemFlags & LEGACY_FB_SUPPORT) === 0 <add> ) { <add> flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp); <add> } <ide> discreteUpdates( <ide> dispatchEvent, <ide> topLevelType, <ide><path>packages/react-dom/src/events/ReactDOMEventReplaying.js <ide> import { <ide> TOP_FOCUS, <ide> TOP_BLUR, <ide> } from './DOMTopLevelEventTypes'; <del>import {IS_REPLAYED} from 'legacy-events/EventSystemFlags'; <add>import {IS_REPLAYED, PLUGIN_EVENT_SYSTEM} from 'legacy-events/EventSystemFlags'; <ide> import {legacyListenToTopLevelEvent} from './DOMLegacyEventPluginSystem'; <ide> import {listenToTopLevelEvent} from './DOMModernPluginEventSystem'; <ide> <ide> function trapReplayableEventForContainer( <ide> container: Container, <ide> listenerMap: ElementListenerMap, <ide> ) { <del> listenToTopLevelEvent(topLevelType, ((container: any): Element), listenerMap); <add> listenToTopLevelEvent( <add> topLevelType, <add> ((container: any): Element), <add> listenerMap, <add> PLUGIN_EVENT_SYSTEM, <add> ); <ide> } <ide> <ide> function trapReplayableEventForDocument( <ide><path>packages/react-dom/src/events/SimpleEventPlugin.js <ide> import type {PluginModule} from 'legacy-events/PluginModuleType'; <ide> import type {EventSystemFlags} from 'legacy-events/EventSystemFlags'; <ide> <ide> import SyntheticEvent from 'legacy-events/SyntheticEvent'; <add>import {IS_TARGET_PHASE_ONLY} from 'legacy-events/EventSystemFlags'; <ide> <ide> import * as DOMTopLevelEventTypes from './DOMTopLevelEventTypes'; <ide> import { <ide> import SyntheticWheelEvent from './SyntheticWheelEvent'; <ide> import getEventCharCode from './getEventCharCode'; <ide> import accumulateTwoPhaseListeners from './accumulateTwoPhaseListeners'; <ide> import accumulateEventTargetListeners from './accumulateEventTargetListeners'; <del>import {IS_TARGET_EVENT_ONLY} from 'legacy-events/EventSystemFlags'; <add> <ide> import {enableUseEventAPI} from 'shared/ReactFeatureFlags'; <ide> <ide> // Only used in DEV for exhaustiveness validation. <ide> const SimpleEventPlugin: PluginModule<MouseEvent> = { <ide> if ( <ide> enableUseEventAPI && <ide> eventSystemFlags !== undefined && <del> eventSystemFlags & IS_TARGET_EVENT_ONLY && <add> eventSystemFlags & IS_TARGET_PHASE_ONLY && <ide> targetContainer != null <ide> ) { <ide> accumulateEventTargetListeners(event, targetContainer);
9
Python
Python
remove absl workaround as it's no longer needed
d1ba56d8d8a4da183bfe7f0b30e0ec1220ebf6ea
<ide><path>src/transformers/__init__.py <ide> <ide> __version__ = "4.16.0.dev0" <ide> <del># Work around to update TensorFlow's absl.logging threshold which alters the <del># default Python logging output behavior when present. <del># see: https://github.com/abseil/abseil-py/issues/99 <del># and: https://github.com/tensorflow/tensorflow/issues/26691#issuecomment-500369493 <del>try: <del> import absl.logging <del>except ImportError: <del> pass <del>else: <del> absl.logging.set_verbosity("info") <del> absl.logging.set_stderrthreshold("info") <del> absl.logging._warn_preinit_stderr = False <ide> <ide> from typing import TYPE_CHECKING <ide>
1
Python
Python
prepare 0.3.3 release (last release before 1.0)
bdd70d06d3590828deeaa6e41c08bba1e6c74abc
<ide><path>keras/__init__.py <del>__version__ = '0.3.2' <add>__version__ = '0.3.3' <ide><path>setup.py <ide> <ide> <ide> setup(name='Keras', <del> version='0.3.2', <add> version='0.3.3', <ide> description='Deep Learning for Python', <ide> author='Francois Chollet', <ide> author_email='[email protected]', <ide> url='https://github.com/fchollet/keras', <del> download_url='https://github.com/fchollet/keras/tarball/0.3.2', <add> download_url='https://github.com/fchollet/keras/tarball/0.3.3', <ide> license='MIT', <ide> install_requires=['theano', 'pyyaml', 'six'], <ide> extras_require={
2
Python
Python
correct the spelling of bleu metric
679d68a11be278b798e468bacafa710b544f807a
<ide><path>examples/pytorch/translation/run_translation.py <ide> class DataTrainingArguments: <ide> validation_file: Optional[str] = field( <ide> default=None, <ide> metadata={ <del> "help": "An optional input evaluation data file to evaluate the metrics (sacreblue) on a jsonlines file." <add> "help": "An optional input evaluation data file to evaluate the metrics (sacrebleu) on a jsonlines file." <ide> }, <ide> ) <ide> test_file: Optional[str] = field( <ide> default=None, <del> metadata={"help": "An optional input test data file to evaluate the metrics (sacreblue) on a jsonlines file."}, <add> metadata={"help": "An optional input test data file to evaluate the metrics (sacrebleu) on a jsonlines file."}, <ide> ) <ide> overwrite_cache: bool = field( <ide> default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} <ide><path>examples/pytorch/translation/run_translation_no_trainer.py <ide> def postprocess_text(preds, labels): <ide> if args.with_tracking: <ide> accelerator.log( <ide> { <del> "blue": eval_metric["score"], <add> "bleu": eval_metric["score"], <ide> "train_loss": total_loss.item() / len(train_dataloader), <ide> "epoch": epoch, <ide> "step": completed_steps,
2
PHP
PHP
allow url #hash for scoped paginator links
72cbe47abd5167c936671e566067609d587c5021
<ide><path>src/View/Helper/PaginatorHelper.php <ide> public function generateUrlParams(array $options = [], $model = null) <ide> if (!empty($paging['scope'])) { <ide> $scope = $paging['scope']; <ide> $currentParams = $this->_config['options']['url']; <add> <add> if (isset($url['#'])) { <add> $currentParams['#'] = $url['#']; <add> unset($url['#']); <add> } <add> <ide> // Merge existing query parameters in the scope. <ide> if (isset($currentParams['?'][$scope]) && is_array($currentParams['?'][$scope])) { <ide> $url += $currentParams['?'][$scope]; <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function testGenerateUrlMultiplePagination() <ide> $result = $this->Paginator->generateUrl(['sort' => 'name']); <ide> $expected = '/posts/index?article%5Bpage%5D=3&amp;article%5Bsort%5D=name'; <ide> $this->assertEquals($expected, $result); <add> <add> $result = $this->Paginator->generateUrl(['#' => 'foo']); <add> $expected = '/posts/index?article%5Bpage%5D=3#foo'; <add> $this->assertEquals($expected, $result); <ide> } <ide> <ide> /**
2
Go
Go
remove some unused code
b9966f3a81e89640d0de8fa5ae8d38213df0b8fe
<ide><path>container/monitor.go <ide> const ( <ide> loggerCloseTimeout = 10 * time.Second <ide> ) <ide> <del>// supervisor defines the interface that a supervisor must implement <del>type supervisor interface { <del> // LogContainerEvent generates events related to a given container <del> LogContainerEvent(*Container, string) <del> // Cleanup ensures that the container is properly unmounted <del> Cleanup(*Container) <del> // StartLogging starts the logging driver for the container <del> StartLogging(*Container) error <del> // Run starts a container <del> Run(c *Container) error <del> // IsShuttingDown tells whether the supervisor is shutting down or not <del> IsShuttingDown() bool <del>} <del> <ide> // Reset puts a container into a state where it can be restarted again. <ide> func (container *Container) Reset(lock bool) { <ide> if lock { <ide><path>daemon/logger/awslogs/cwlogsiface_mock_test.go <ide> func (m *mockmetadataclient) Region() (string, error) { <ide> output := <-m.regionResult <ide> return output.successResult, output.errorResult <ide> } <del> <del>func test() { <del> _ = &logStream{ <del> client: newMockClient(), <del> } <del>} <ide><path>docker/daemon_none.go <ide> import "github.com/docker/docker/cli" <ide> const daemonUsage = "" <ide> <ide> var daemonCli cli.Handler <del> <del>// notifySystem sends a message to the host when the server is ready to be used <del>func notifySystem() { <del>}
3
PHP
PHP
remove redundant code
b34eb2573a51ef03ee3c6c6f88b4bf581d47969b
<ide><path>src/Database/Statement/BufferedStatement.php <ide> class BufferedStatement extends StatementDecorator <ide> * <ide> * @var bool <ide> */ <del> protected $_allFetched = true; <add> protected $_allFetched = false; <ide> <ide> /** <ide> * Current record pointer <ide> class BufferedStatement extends StatementDecorator <ide> */ <ide> protected $_counter = 0; <ide> <del> /** <del> * Constructor <del> * <del> * @param \Cake\Database\StatementInterface|null $statement Statement implementation such as PDOStatement <del> * @param \Cake\Database\Driver|null $driver Driver instance <del> */ <del> public function __construct($statement = null, $driver = null) <del> { <del> parent::__construct($statement, $driver); <del> $this->_reset(); <del> } <del> <ide> /** <ide> * Execute the statement and return the results. <ide> *
1
Go
Go
open the journald following descriptor earlier
ab62ecf393b92d1e644f82c4711b6618b7c572a5
<ide><path>daemon/logger/journald/read.go <ide> func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadCon <ide> } <ide> cursor = s.drainJournal(logWatcher, config, j, "") <ide> if config.Follow { <del> // Create a pipe that we can poll at the same time as the journald descriptor. <del> if C.pipe(&pipes[0]) == C.int(-1) { <del> logWatcher.Err <- fmt.Errorf("error opening journald close notification pipe") <add> // Allocate a descriptor for following the journal, if we'll <add> // need one. Do it here so that we can report if it fails. <add> if fd := C.sd_journal_get_fd(j); fd < C.int(0) { <add> logWatcher.Err <- fmt.Errorf("error opening journald follow descriptor: %q", C.GoString(C.strerror(-fd))) <ide> } else { <del> s.followJournal(logWatcher, config, j, pipes, cursor) <del> // Let followJournal handle freeing the journal context <del> // object and closing the channel. <del> following = true <add> // Create a pipe that we can poll at the same time as <add> // the journald descriptor. <add> if C.pipe(&pipes[0]) == C.int(-1) { <add> logWatcher.Err <- fmt.Errorf("error opening journald close notification pipe") <add> } else { <add> s.followJournal(logWatcher, config, j, pipes, cursor) <add> // Let followJournal handle freeing the journal context <add> // object and closing the channel. <add> following = true <add> } <ide> } <ide> } <ide> return
1
Text
Text
promote 0x to tier 4
952cc0a038498c48857fa8f2e65f779204d87973
<ide><path>doc/contributing/diagnostic-tooling-support-tiers.md <ide> The tools are currently assigned to Tiers as follows: <ide> <ide> ## Tier 4 <ide> <del>| Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <del>| --------- | ------------- | ----------------------------- | ----------------------- | ----------- | <del>| | | | | | <add>| Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier | <add>| --------- | --------------------------------------------- | ----------------------------- | ----------------------- | ----------- | <add>| Profiling | [0x](https://github.com/davidmarkclements/0x) | No | No | 3 | <ide> <ide> ## Not yet classified <ide> <ide> The tools are currently assigned to Tiers as follows: <ide> | Tracing | Systemtap | No | Partial | ? | <ide> | Profiling | DTrace | No | Partial | 3 | <ide> | Profiling | Windows Xperf | No | ? | ? | <del>| Profiling | 0x | No | No | 4 | <ide> | F/P/T | appmetrics | No | No | ? | <ide> | M/T | eBPF tracing tool | No | No | ? |
1
Python
Python
update pretrain command
008e1ee1dd1bd624eff198cbdedc504c36f82693
<ide><path>spacy/cli/pretrain.py <ide> from spacy.attrs import ID, HEAD <ide> from spacy.util import minibatch, minibatch_by_words, use_gpu, compounding, ensure_path <ide> from spacy._ml import Tok2Vec, flatten, chain, zero_init, create_default_optimizer <del>from thinc.v2v import Affine <add>from thinc.v2v import Affine, Maxout <ide> from thinc.api import wrap <add>from thinc.misc import LayerNorm as LN <ide> <ide> <ide> def prefer_gpu(): <ide> def create_pretraining_model(nlp, tok2vec): <ide> Each array in the output needs to have one row per token in the doc. <ide> ''' <ide> output_size = nlp.vocab.vectors.data.shape[1] <del> output_layer = zero_init(Affine(output_size, drop_factor=0.0)) <add> output_layer = chain( <add> LN(Maxout(300, pieces=3)), <add> zero_init(Affine(output_size, drop_factor=0.0)) <add> ) <ide> # This is annoying, but the parser etc have the flatten step after <ide> # the tok2vec. To load the weights in cleanly, we need to match <ide> # the shape of the models' components exactly. So what we cann <ide> def create_pretraining_model(nlp, tok2vec): <ide> <ide> def masked_language_model(vocab, model, mask_prob=0.15): <ide> '''Convert a model into a BERT-style masked language model''' <del> vocab_words = [lex.text for lex in vocab if lex.prob != 0.0] <del> vocab_probs = [lex.prob for lex in vocab if lex.prob != 0.0] <del> vocab_words = vocab_words[:10000] <del> vocab_probs = vocab_probs[:10000] <del> vocab_probs = numpy.exp(numpy.array(vocab_probs, dtype='f')) <del> vocab_probs /= vocab_probs.sum() <del> <add> <add> random_words = RandomWords(vocab) <ide> def mlm_forward(docs, drop=0.): <del> mask, docs = apply_mask(docs, vocab_words, vocab_probs, <del> mask_prob=mask_prob) <add> mask, docs = apply_mask(docs, random_words, mask_prob=mask_prob) <ide> mask = model.ops.asarray(mask).reshape((mask.shape[0], 1)) <ide> output, backprop = model.begin_update(docs, drop=drop) <ide> <ide> def mlm_backward(d_output, sgd=None): <ide> return wrap(mlm_forward, model) <ide> <ide> <del>def apply_mask(docs, vocab_texts, vocab_probs, mask_prob=0.15): <add>def apply_mask(docs, random_words, mask_prob=0.15): <ide> N = sum(len(doc) for doc in docs) <ide> mask = numpy.random.uniform(0., 1.0, (N,)) <ide> mask = mask >= mask_prob <ide> def apply_mask(docs, vocab_texts, vocab_probs, mask_prob=0.15): <ide> words = [] <ide> for token in doc: <ide> if not mask[i]: <del> word = replace_word(token.text, vocab_texts, vocab_probs) <add> word = replace_word(token.text, random_words) <ide> else: <ide> word = token.text <ide> words.append(word) <ide> def apply_mask(docs, vocab_texts, vocab_probs, mask_prob=0.15): <ide> return mask, masked_docs <ide> <ide> <del>def replace_word(word, vocab_texts, vocab_probs, mask='[MASK]'): <add>def replace_word(word, random_words, mask='[MASK]'): <ide> roll = random.random() <ide> if roll < 0.8: <ide> return mask <ide> elif roll < 0.9: <del> index = numpy.random.choice(len(vocab_texts), p=vocab_probs) <del> return vocab_texts[index] <add> return random_words.next() <ide> else: <ide> return word <ide> <add>class RandomWords(object): <add> def __init__(self, vocab): <add> self.words = [lex.text for lex in vocab if lex.prob != 0.0] <add> self.probs = [lex.prob for lex in vocab if lex.prob != 0.0] <add> self.words = self.words[:10000] <add> self.probs = self.probs[:10000] <add> self.probs = numpy.exp(numpy.array(self.probs, dtype='f')) <add> self.probs /= self.probs.sum() <add> self._cache = [] <add> <add> def next(self): <add> if not self._cache: <add> self._cache.extend(numpy.random.choice(len(self.words), 10000, <add> p=self.probs)) <add> index = self._cache.pop() <add> return self.words[index] <add> <ide> <ide> class ProgressTracker(object): <del> def __init__(self, frequency=100000): <add> def __init__(self, frequency=1000000): <ide> self.loss = 0.0 <ide> self.prev_loss = 0.0 <ide> self.nr_word = 0 <ide> self.words_per_epoch = Counter() <ide> self.frequency = frequency <ide> self.last_time = time.time() <ide> self.last_update = 0 <add> self.epoch_loss = 0.0 <ide> <ide> def update(self, epoch, loss, docs): <ide> self.loss += loss <add> self.epoch_loss += loss <ide> words_in_batch = sum(len(doc) for doc in docs) <ide> self.words_per_epoch[epoch] += words_in_batch <ide> self.nr_word += words_in_batch <ide> def update(self, epoch, loss, docs): <ide> seed=("Seed for random number generators", "option", "s", float), <ide> nr_iter=("Number of iterations to pretrain", "option", "i", int), <ide> ) <del>def pretrain(texts_loc, vectors_model, output_dir, width=128, depth=4, <del> embed_rows=5000, use_vectors=False, dropout=0.2, nr_iter=100, seed=0): <add>def pretrain(texts_loc, vectors_model, output_dir, width=96, depth=4, <add> embed_rows=2000, use_vectors=False, dropout=0.2, nr_iter=1000, seed=0): <ide> """ <ide> Pre-train the 'token-to-vector' (tok2vec) layer of pipeline components, <ide> using an approximate language-modelling objective. Specifically, we load <ide> def pretrain(texts_loc, vectors_model, output_dir, width=128, depth=4, <ide> print('Epoch', '#Words', 'Loss', 'w/s') <ide> texts = stream_texts() if texts_loc == '-' else load_texts(texts_loc) <ide> for epoch in range(nr_iter): <del> for batch in minibatch(texts, size=256): <del> docs = make_docs(nlp, batch) <add> for batch in minibatch_by_words(((text, None) for text in texts), size=5000): <add> docs = make_docs(nlp, [text for (text, _) in batch]) <ide> loss = make_update(model, docs, optimizer, drop=dropout) <ide> progress = tracker.update(epoch, loss, docs) <ide> if progress: <ide> def pretrain(texts_loc, vectors_model, output_dir, width=128, depth=4, <ide> file_.write(model.tok2vec.to_bytes()) <ide> with (output_dir / 'log.jsonl').open('a') as file_: <ide> file_.write(json.dumps({'nr_word': tracker.nr_word, <del> 'loss': tracker.loss, 'epoch': epoch}) + '\n') <add> 'loss': tracker.loss, 'epoch_loss': tracker.epoch_loss, <add> 'epoch': epoch}) + '\n') <add> tracker.epoch_loss = 0.0 <ide> if texts_loc != '-': <ide> texts = load_texts(texts_loc)
1
Javascript
Javascript
remove bogus @param fields
ba731ab850e1d9587572ce367cec124c207adf8d
<ide><path>src/ng/directive/input.js <ide> var VALID_CLASS = 'ng-valid', <ide> * }; <ide> * ``` <ide> * <del> * @param {string} name The name of the validator. <del> * @param {Function} validationFn The validation function that will be run. <del> * <ide> * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the <ide> * view value has changed. It is called with no arguments, and its return value is ignored. <ide> * This can be used in place of additional $watches against the model value.
1
Javascript
Javascript
add rebeccapurple test
4b6bd05a3256adae42b4e0ed68839ff9f317ba1a
<ide><path>test/color/rgb-test.js <ide> suite.addBatch({ <ide> assert.rgbEqual(d3.rgb("aliceblue"), 240, 248, 255); <ide> assert.rgbEqual(d3.rgb("yellow"), 255, 255, 0); <ide> }, <add> "parses \"rebeccapurple\"": function(d3) { <add> assert.rgbEqual(d3.rgb("rebeccapurple"), 102, 51, 153); <add> }, <ide> "parses and converts HSL format (e.g., \"hsl(60, 100%, 20%)\")": function(d3) { <ide> assert.rgbEqual(d3.rgb("hsl(60, 100%, 20%)"), 102, 102, 0); <ide> },
1
Python
Python
add regression test for
6b4bdd1a6645899fe87fb144d9012ec488580651
<ide><path>numpy/core/tests/test_regression.py <ide> def test_zeros(self): <ide> except Exception, e: <ide> self.fail("Got exception of type %s instead of ValueError" % type(e)) <ide> <add> def test_huge_arange(self): <add> """Regression test for #1062.""" <add> # Set a size which cannot fit into a 64 bits signed integer <add> sz = 2 ** 64 <add> a = np.arange(sz) <add> self.failUnless(np.size == sz) <add> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Ruby
Ruby
fix typos in the description of the test
120751d2d482119f688c44d20bda78e7f4abc8f6
<ide><path>test/test_table.rb <ide> module Arel <ide> end <ide> <ide> describe Table do <del> describe 'when checking existence of a table' do <del> it 'should be precent in the table cache despite the class of its name' do <add> describe 'when checking the existence of a table' do <add> it 'should be present in the table cache despite the class of its name' do <ide> [ 'users', :users ].each do |name| <ide> relation = Table.new name <ide> relation.send(:tables).key?(relation.name).must_equal true
1
Ruby
Ruby
add to_json method
c34b4c3abd0654733a072df5efbfafb04e1d8d4f
<ide><path>Library/Homebrew/requirements/macos_requirement.rb <ide> def message(type: :formula) <ide> versions newer than #{@version.pretty_name} due to an upstream incompatibility. <ide> EOS <ide> when :cask <del> "This cask does not on macOS versions newer than #{@version.pretty_name}." <add> "This cask does not run on macOS versions newer than #{@version.pretty_name}." <ide> end <ide> else <ide> if @version.respond_to?(:to_ary) <del> *versions, last = @version.map(:pretty_name) <add> *versions, last = @version.map(&:pretty_name) <ide> return "macOS #{versions.join(", ")} or #{last} is required." <ide> end <ide> <ide> def display_s <ide> <ide> "macOS #{@comparator} #{@version}" <ide> end <add> <add> def to_json(*args) <add> comp = @comparator.to_s <add> return { comp => @version.map(&:to_s) }.to_json(*args) if @version.is_a?(Array) <add> <add> { comp => [@version.to_s] }.to_json(*args) <add> end <ide> end
1
Javascript
Javascript
add support to tag-hyphenated elements
534f13025aeb59a7d5893ce62efafa0b066a4934
<ide><path>src/core/var/rsingleTag.js <ide> define(function() { <ide> // Match a standalone tag <del> return (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); <add> return (/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/); <ide> }); <ide><path>test/unit/core.js <ide> test("jQuery('html')", function() { <ide> equal( jQuery( "\\<div\\>" ).length, 0, "Ignore escaped html characters" ); <ide> }); <ide> <add>test("jQuery(tag-hyphenated elements) gh-1987", function() { <add> expect( 17 ); <add> <add> jQuery.each( "thead tbody tfoot colgroup caption tr th td".split(" "), function( i, name ) { <add> var j = jQuery("<" + name + "-d></" + name + "-d>"); <add> ok( j[0], "Create a tag-hyphenated elements" ); <add> ok( jQuery.nodeName(j[0], name.toUpperCase() + "-D"), "Tag-hyphenated element has expected node name" ); <add> }); <add> <add> var j = jQuery("<tr-multiple-hyphens></tr-multiple-hyphens>"); <add> ok( jQuery.nodeName(j[0], "TR-MULTIPLE-HYPHENS"), "Element with multiple hyphens in its tag has expected node name" ); <add>}); <add> <ide> test("jQuery('massive html #7990')", function() { <ide> expect( 3 ); <ide>
2
Javascript
Javascript
use a single lane per priority level
d3d2451a08c9afcc561f66383211ce2274d864e6
<ide><path>packages/react-reconciler/src/ReactFiberLane.new.js <ide> export const SyncLane: Lane = /* */ 0b0000000000000000000 <ide> export const SyncBatchedLane: Lane = /* */ 0b0000000000000000000000000000010; <ide> <ide> export const InputDiscreteHydrationLane: Lane = /* */ 0b0000000000000000000000000000100; <del>const InputDiscreteLanes: Lanes = /* */ 0b0000000000000000000000000011000; <add>const InputDiscreteLane: Lanes = /* */ 0b0000000000000000000000000001000; <ide> <ide> const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000100000; <del>const InputContinuousLanes: Lanes = /* */ 0b0000000000000000000000011000000; <add>const InputContinuousLane: Lanes = /* */ 0b0000000000000000000000001000000; <ide> <ide> export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000100000000; <del>export const DefaultLanes: Lanes = /* */ 0b0000000000000000000111000000000; <add>export const DefaultLane: Lanes = /* */ 0b0000000000000000000001000000000; <ide> <ide> const TransitionHydrationLane: Lane = /* */ 0b0000000000000000001000000000000; <ide> const TransitionLanes: Lanes = /* */ 0b0000000001111111110000000000000; <del>const FirstTransitionLane: Lane = /* */ 0b0000000000000000010000000000000; <add>const TransitionLane1: Lane = /* */ 0b0000000000000000010000000000000; <add>const TransitionLane2: Lane = /* */ 0b0000000000000000100000000000000; <add>const TransitionLane3: Lane = /* */ 0b0000000000000001000000000000000; <add>const TransitionLane4: Lane = /* */ 0b0000000000000010000000000000000; <add>const TransitionLane5: Lane = /* */ 0b0000000000000100000000000000000; <add>const TransitionLane6: Lane = /* */ 0b0000000000001000000000000000000; <add>const TransitionLane7: Lane = /* */ 0b0000000000010000000000000000000; <add>const TransitionLane8: Lane = /* */ 0b0000000000100000000000000000000; <add>const TransitionLane9: Lane = /* */ 0b0000000001000000000000000000000; <ide> <ide> const RetryLanes: Lanes = /* */ 0b0000011110000000000000000000000; <add>const RetryLane1: Lane = /* */ 0b0000000010000000000000000000000; <add>const RetryLane2: Lane = /* */ 0b0000000100000000000000000000000; <add>const RetryLane3: Lane = /* */ 0b0000001000000000000000000000000; <add>const RetryLane4: Lane = /* */ 0b0000010000000000000000000000000; <ide> <del>const FirstRetryLane: Lanes = /* */ 0b0000000010000000000000000000000; <del>export const SomeRetryLane: Lane = FirstRetryLane; <add>export const SomeRetryLane: Lane = RetryLane1; <ide> <ide> export const SelectiveHydrationLane: Lane = /* */ 0b0000100000000000000000000000000; <ide> <ide> const NonIdleLanes = /* */ 0b0000111111111111111111111111111; <ide> <ide> export const IdleHydrationLane: Lane = /* */ 0b0001000000000000000000000000000; <del>const IdleLanes: Lanes = /* */ 0b0110000000000000000000000000000; <add>const IdleLane: Lanes = /* */ 0b0010000000000000000000000000000; <ide> <ide> export const OffscreenLane: Lane = /* */ 0b1000000000000000000000000000000; <ide> <ide> export const NoTimestamp = -1; <ide> <ide> let currentUpdateLanePriority: LanePriority = NoLanePriority; <ide> <del>let nextTransitionLane: Lane = FirstTransitionLane; <del>let nextRetryLane: Lane = FirstRetryLane; <add>let nextTransitionLane: Lane = TransitionLane1; <add>let nextRetryLane: Lane = RetryLane1; <ide> <ide> export function getCurrentUpdateLanePriority(): LanePriority { <ide> return currentUpdateLanePriority; <ide> export function setCurrentUpdateLanePriority(newLanePriority: LanePriority) { <ide> let return_highestLanePriority: LanePriority = DefaultLanePriority; <ide> <ide> function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes { <del> if ((SyncLane & lanes) !== NoLanes) { <del> return_highestLanePriority = SyncLanePriority; <del> return SyncLane; <del> } <del> if ((SyncBatchedLane & lanes) !== NoLanes) { <del> return_highestLanePriority = SyncBatchedLanePriority; <del> return SyncBatchedLane; <del> } <del> if ((InputDiscreteHydrationLane & lanes) !== NoLanes) { <del> return_highestLanePriority = InputDiscreteHydrationLanePriority; <del> return InputDiscreteHydrationLane; <del> } <del> const inputDiscreteLanes = InputDiscreteLanes & lanes; <del> if (inputDiscreteLanes !== NoLanes) { <del> return_highestLanePriority = InputDiscreteLanePriority; <del> return inputDiscreteLanes; <del> } <del> if ((lanes & InputContinuousHydrationLane) !== NoLanes) { <del> return_highestLanePriority = InputContinuousHydrationLanePriority; <del> return InputContinuousHydrationLane; <del> } <del> const inputContinuousLanes = InputContinuousLanes & lanes; <del> if (inputContinuousLanes !== NoLanes) { <del> return_highestLanePriority = InputContinuousLanePriority; <del> return inputContinuousLanes; <del> } <del> if ((lanes & DefaultHydrationLane) !== NoLanes) { <del> return_highestLanePriority = DefaultHydrationLanePriority; <del> return DefaultHydrationLane; <del> } <del> const defaultLanes = DefaultLanes & lanes; <del> if (defaultLanes !== NoLanes) { <del> return_highestLanePriority = DefaultLanePriority; <del> return defaultLanes; <del> } <del> if ((lanes & TransitionHydrationLane) !== NoLanes) { <del> return_highestLanePriority = TransitionHydrationPriority; <del> return TransitionHydrationLane; <del> } <del> const transitionLanes = TransitionLanes & lanes; <del> if (transitionLanes !== NoLanes) { <del> return_highestLanePriority = TransitionPriority; <del> return transitionLanes; <del> } <del> const retryLanes = RetryLanes & lanes; <del> if (retryLanes !== NoLanes) { <del> return_highestLanePriority = RetryLanePriority; <del> return retryLanes; <del> } <del> if (lanes & SelectiveHydrationLane) { <del> return_highestLanePriority = SelectiveHydrationLanePriority; <del> return SelectiveHydrationLane; <del> } <del> if ((lanes & IdleHydrationLane) !== NoLanes) { <del> return_highestLanePriority = IdleHydrationLanePriority; <del> return IdleHydrationLane; <del> } <del> const idleLanes = IdleLanes & lanes; <del> if (idleLanes !== NoLanes) { <del> return_highestLanePriority = IdleLanePriority; <del> return idleLanes; <del> } <del> if ((OffscreenLane & lanes) !== NoLanes) { <del> return_highestLanePriority = OffscreenLanePriority; <del> return OffscreenLane; <del> } <del> if (__DEV__) { <del> console.error('Should have found matching lanes. This is a bug in React.'); <add> switch (getHighestPriorityLane(lanes)) { <add> case SyncLane: <add> return_highestLanePriority = SyncLanePriority; <add> return SyncLane; <add> case SyncBatchedLane: <add> return_highestLanePriority = SyncBatchedLanePriority; <add> return SyncBatchedLane; <add> case InputDiscreteHydrationLane: <add> return_highestLanePriority = InputDiscreteHydrationLanePriority; <add> return InputDiscreteHydrationLane; <add> case InputDiscreteLane: <add> return_highestLanePriority = InputDiscreteLanePriority; <add> return InputDiscreteLane; <add> case InputContinuousHydrationLane: <add> return_highestLanePriority = InputContinuousHydrationLanePriority; <add> return InputContinuousHydrationLane; <add> case InputContinuousLane: <add> return_highestLanePriority = InputContinuousLanePriority; <add> return InputContinuousLane; <add> case DefaultHydrationLane: <add> return_highestLanePriority = DefaultHydrationLanePriority; <add> return DefaultHydrationLane; <add> case DefaultLane: <add> return_highestLanePriority = DefaultLanePriority; <add> return DefaultLane; <add> case TransitionHydrationLane: <add> return_highestLanePriority = TransitionHydrationPriority; <add> return TransitionHydrationLane; <add> case TransitionLane1: <add> case TransitionLane2: <add> case TransitionLane3: <add> case TransitionLane4: <add> case TransitionLane5: <add> case TransitionLane6: <add> case TransitionLane7: <add> case TransitionLane8: <add> case TransitionLane9: <add> return_highestLanePriority = TransitionPriority; <add> return lanes & TransitionLanes; <add> case RetryLane1: <add> case RetryLane2: <add> case RetryLane3: <add> case RetryLane4: <add> return_highestLanePriority = RetryLanePriority; <add> return lanes & RetryLanes; <add> case SelectiveHydrationLane: <add> return_highestLanePriority = SelectiveHydrationLanePriority; <add> return SelectiveHydrationLane; <add> case IdleHydrationLane: <add> return_highestLanePriority = IdleHydrationLanePriority; <add> return IdleHydrationLane; <add> case IdleLane: <add> return_highestLanePriority = IdleLanePriority; <add> return IdleLane; <add> case OffscreenLane: <add> return_highestLanePriority = OffscreenLanePriority; <add> return OffscreenLane; <add> default: <add> if (__DEV__) { <add> console.error( <add> 'Should have found matching lanes. This is a bug in React.', <add> ); <add> } <add> // This shouldn't be reachable, but as a fallback, return the entire bitmask. <add> return_highestLanePriority = DefaultLanePriority; <add> return lanes; <ide> } <del> // This shouldn't be reachable, but as a fallback, return the entire bitmask. <del> return_highestLanePriority = DefaultLanePriority; <del> return lanes; <ide> } <ide> <ide> export function schedulerPriorityToLanePriority( <ide> export function findUpdateLane(lanePriority: LanePriority): Lane { <ide> return SyncLane; <ide> case SyncBatchedLanePriority: <ide> return SyncBatchedLane; <del> case InputDiscreteLanePriority: { <del> return pickArbitraryLane(InputDiscreteLanes); <del> } <del> case InputContinuousLanePriority: { <del> return pickArbitraryLane(InputContinuousLanes); <del> } <del> case DefaultLanePriority: { <del> return pickArbitraryLane(DefaultLanes); <del> } <add> case InputDiscreteLanePriority: <add> return InputDiscreteLane; <add> case InputContinuousLanePriority: <add> return InputContinuousLane; <add> case DefaultLanePriority: <add> return DefaultLane; <ide> case TransitionPriority: // Should be handled by findTransitionLane instead <ide> case RetryLanePriority: // Should be handled by findRetryLane instead <ide> break; <ide> case IdleLanePriority: <del> return pickArbitraryLane(IdleLanes); <add> return IdleLane; <ide> default: <ide> // The remaining priorities are not valid for updates <ide> break; <ide> export function claimNextTransitionLane(): Lane { <ide> const lane = nextTransitionLane; <ide> nextTransitionLane <<= 1; <ide> if ((nextTransitionLane & TransitionLanes) === 0) { <del> nextTransitionLane = FirstTransitionLane; <add> nextTransitionLane = TransitionLane1; <ide> } <ide> return lane; <ide> } <ide> export function claimNextRetryLane(): Lane { <ide> const lane = nextRetryLane; <ide> nextRetryLane <<= 1; <ide> if ((nextRetryLane & RetryLanes) === 0) { <del> nextRetryLane = FirstRetryLane; <add> nextRetryLane = RetryLane1; <ide> } <ide> return lane; <ide> } <ide> export function markRootUpdated( <ide> // We don't do this if the incoming update is idle, because we never process <ide> // idle updates until after all the regular updates have finished; there's no <ide> // way it could unblock a transition. <del> if ((updateLane & IdleLanes) === NoLanes) { <add> if (updateLane !== IdleLane) { <ide> root.suspendedLanes = NoLanes; <ide> root.pingedLanes = NoLanes; <ide> } <ide> export function markRootExpired(root: FiberRoot, expiredLanes: Lanes) { <ide> } <ide> <ide> export function markDiscreteUpdatesExpired(root: FiberRoot) { <del> root.expiredLanes |= InputDiscreteLanes & root.pendingLanes; <add> if (root.pendingLanes & InputDiscreteLane) { <add> root.expiredLanes |= InputDiscreteLane; <add> } <ide> } <ide> <ide> export function hasDiscreteLanes(lanes: Lanes) { <del> return (lanes & InputDiscreteLanes) !== NoLanes; <add> return (lanes & InputDiscreteLane) !== NoLanes; <ide> } <ide> <ide> export function markRootMutableRead(root: FiberRoot, updateLane: Lane) { <ide><path>packages/react-reconciler/src/ReactFiberLane.old.js <ide> export const SyncLane: Lane = /* */ 0b0000000000000000000 <ide> export const SyncBatchedLane: Lane = /* */ 0b0000000000000000000000000000010; <ide> <ide> export const InputDiscreteHydrationLane: Lane = /* */ 0b0000000000000000000000000000100; <del>const InputDiscreteLanes: Lanes = /* */ 0b0000000000000000000000000011000; <add>const InputDiscreteLane: Lanes = /* */ 0b0000000000000000000000000001000; <ide> <ide> const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000100000; <del>const InputContinuousLanes: Lanes = /* */ 0b0000000000000000000000011000000; <add>const InputContinuousLane: Lanes = /* */ 0b0000000000000000000000001000000; <ide> <ide> export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000100000000; <del>export const DefaultLanes: Lanes = /* */ 0b0000000000000000000111000000000; <add>export const DefaultLane: Lanes = /* */ 0b0000000000000000000001000000000; <ide> <ide> const TransitionHydrationLane: Lane = /* */ 0b0000000000000000001000000000000; <ide> const TransitionLanes: Lanes = /* */ 0b0000000001111111110000000000000; <del>const FirstTransitionLane: Lane = /* */ 0b0000000000000000010000000000000; <add>const TransitionLane1: Lane = /* */ 0b0000000000000000010000000000000; <add>const TransitionLane2: Lane = /* */ 0b0000000000000000100000000000000; <add>const TransitionLane3: Lane = /* */ 0b0000000000000001000000000000000; <add>const TransitionLane4: Lane = /* */ 0b0000000000000010000000000000000; <add>const TransitionLane5: Lane = /* */ 0b0000000000000100000000000000000; <add>const TransitionLane6: Lane = /* */ 0b0000000000001000000000000000000; <add>const TransitionLane7: Lane = /* */ 0b0000000000010000000000000000000; <add>const TransitionLane8: Lane = /* */ 0b0000000000100000000000000000000; <add>const TransitionLane9: Lane = /* */ 0b0000000001000000000000000000000; <ide> <ide> const RetryLanes: Lanes = /* */ 0b0000011110000000000000000000000; <add>const RetryLane1: Lane = /* */ 0b0000000010000000000000000000000; <add>const RetryLane2: Lane = /* */ 0b0000000100000000000000000000000; <add>const RetryLane3: Lane = /* */ 0b0000001000000000000000000000000; <add>const RetryLane4: Lane = /* */ 0b0000010000000000000000000000000; <ide> <del>const FirstRetryLane: Lanes = /* */ 0b0000000010000000000000000000000; <del>export const SomeRetryLane: Lane = FirstRetryLane; <add>export const SomeRetryLane: Lane = RetryLane1; <ide> <ide> export const SelectiveHydrationLane: Lane = /* */ 0b0000100000000000000000000000000; <ide> <ide> const NonIdleLanes = /* */ 0b0000111111111111111111111111111; <ide> <ide> export const IdleHydrationLane: Lane = /* */ 0b0001000000000000000000000000000; <del>const IdleLanes: Lanes = /* */ 0b0110000000000000000000000000000; <add>const IdleLane: Lanes = /* */ 0b0010000000000000000000000000000; <ide> <ide> export const OffscreenLane: Lane = /* */ 0b1000000000000000000000000000000; <ide> <ide> export const NoTimestamp = -1; <ide> <ide> let currentUpdateLanePriority: LanePriority = NoLanePriority; <ide> <del>let nextTransitionLane: Lane = FirstTransitionLane; <del>let nextRetryLane: Lane = FirstRetryLane; <add>let nextTransitionLane: Lane = TransitionLane1; <add>let nextRetryLane: Lane = RetryLane1; <ide> <ide> export function getCurrentUpdateLanePriority(): LanePriority { <ide> return currentUpdateLanePriority; <ide> export function setCurrentUpdateLanePriority(newLanePriority: LanePriority) { <ide> let return_highestLanePriority: LanePriority = DefaultLanePriority; <ide> <ide> function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes { <del> if ((SyncLane & lanes) !== NoLanes) { <del> return_highestLanePriority = SyncLanePriority; <del> return SyncLane; <del> } <del> if ((SyncBatchedLane & lanes) !== NoLanes) { <del> return_highestLanePriority = SyncBatchedLanePriority; <del> return SyncBatchedLane; <del> } <del> if ((InputDiscreteHydrationLane & lanes) !== NoLanes) { <del> return_highestLanePriority = InputDiscreteHydrationLanePriority; <del> return InputDiscreteHydrationLane; <del> } <del> const inputDiscreteLanes = InputDiscreteLanes & lanes; <del> if (inputDiscreteLanes !== NoLanes) { <del> return_highestLanePriority = InputDiscreteLanePriority; <del> return inputDiscreteLanes; <del> } <del> if ((lanes & InputContinuousHydrationLane) !== NoLanes) { <del> return_highestLanePriority = InputContinuousHydrationLanePriority; <del> return InputContinuousHydrationLane; <del> } <del> const inputContinuousLanes = InputContinuousLanes & lanes; <del> if (inputContinuousLanes !== NoLanes) { <del> return_highestLanePriority = InputContinuousLanePriority; <del> return inputContinuousLanes; <del> } <del> if ((lanes & DefaultHydrationLane) !== NoLanes) { <del> return_highestLanePriority = DefaultHydrationLanePriority; <del> return DefaultHydrationLane; <del> } <del> const defaultLanes = DefaultLanes & lanes; <del> if (defaultLanes !== NoLanes) { <del> return_highestLanePriority = DefaultLanePriority; <del> return defaultLanes; <del> } <del> if ((lanes & TransitionHydrationLane) !== NoLanes) { <del> return_highestLanePriority = TransitionHydrationPriority; <del> return TransitionHydrationLane; <del> } <del> const transitionLanes = TransitionLanes & lanes; <del> if (transitionLanes !== NoLanes) { <del> return_highestLanePriority = TransitionPriority; <del> return transitionLanes; <del> } <del> const retryLanes = RetryLanes & lanes; <del> if (retryLanes !== NoLanes) { <del> return_highestLanePriority = RetryLanePriority; <del> return retryLanes; <del> } <del> if (lanes & SelectiveHydrationLane) { <del> return_highestLanePriority = SelectiveHydrationLanePriority; <del> return SelectiveHydrationLane; <del> } <del> if ((lanes & IdleHydrationLane) !== NoLanes) { <del> return_highestLanePriority = IdleHydrationLanePriority; <del> return IdleHydrationLane; <del> } <del> const idleLanes = IdleLanes & lanes; <del> if (idleLanes !== NoLanes) { <del> return_highestLanePriority = IdleLanePriority; <del> return idleLanes; <del> } <del> if ((OffscreenLane & lanes) !== NoLanes) { <del> return_highestLanePriority = OffscreenLanePriority; <del> return OffscreenLane; <del> } <del> if (__DEV__) { <del> console.error('Should have found matching lanes. This is a bug in React.'); <add> switch (getHighestPriorityLane(lanes)) { <add> case SyncLane: <add> return_highestLanePriority = SyncLanePriority; <add> return SyncLane; <add> case SyncBatchedLane: <add> return_highestLanePriority = SyncBatchedLanePriority; <add> return SyncBatchedLane; <add> case InputDiscreteHydrationLane: <add> return_highestLanePriority = InputDiscreteHydrationLanePriority; <add> return InputDiscreteHydrationLane; <add> case InputDiscreteLane: <add> return_highestLanePriority = InputDiscreteLanePriority; <add> return InputDiscreteLane; <add> case InputContinuousHydrationLane: <add> return_highestLanePriority = InputContinuousHydrationLanePriority; <add> return InputContinuousHydrationLane; <add> case InputContinuousLane: <add> return_highestLanePriority = InputContinuousLanePriority; <add> return InputContinuousLane; <add> case DefaultHydrationLane: <add> return_highestLanePriority = DefaultHydrationLanePriority; <add> return DefaultHydrationLane; <add> case DefaultLane: <add> return_highestLanePriority = DefaultLanePriority; <add> return DefaultLane; <add> case TransitionHydrationLane: <add> return_highestLanePriority = TransitionHydrationPriority; <add> return TransitionHydrationLane; <add> case TransitionLane1: <add> case TransitionLane2: <add> case TransitionLane3: <add> case TransitionLane4: <add> case TransitionLane5: <add> case TransitionLane6: <add> case TransitionLane7: <add> case TransitionLane8: <add> case TransitionLane9: <add> return_highestLanePriority = TransitionPriority; <add> return lanes & TransitionLanes; <add> case RetryLane1: <add> case RetryLane2: <add> case RetryLane3: <add> case RetryLane4: <add> return_highestLanePriority = RetryLanePriority; <add> return lanes & RetryLanes; <add> case SelectiveHydrationLane: <add> return_highestLanePriority = SelectiveHydrationLanePriority; <add> return SelectiveHydrationLane; <add> case IdleHydrationLane: <add> return_highestLanePriority = IdleHydrationLanePriority; <add> return IdleHydrationLane; <add> case IdleLane: <add> return_highestLanePriority = IdleLanePriority; <add> return IdleLane; <add> case OffscreenLane: <add> return_highestLanePriority = OffscreenLanePriority; <add> return OffscreenLane; <add> default: <add> if (__DEV__) { <add> console.error( <add> 'Should have found matching lanes. This is a bug in React.', <add> ); <add> } <add> // This shouldn't be reachable, but as a fallback, return the entire bitmask. <add> return_highestLanePriority = DefaultLanePriority; <add> return lanes; <ide> } <del> // This shouldn't be reachable, but as a fallback, return the entire bitmask. <del> return_highestLanePriority = DefaultLanePriority; <del> return lanes; <ide> } <ide> <ide> export function schedulerPriorityToLanePriority( <ide> export function findUpdateLane(lanePriority: LanePriority): Lane { <ide> return SyncLane; <ide> case SyncBatchedLanePriority: <ide> return SyncBatchedLane; <del> case InputDiscreteLanePriority: { <del> return pickArbitraryLane(InputDiscreteLanes); <del> } <del> case InputContinuousLanePriority: { <del> return pickArbitraryLane(InputContinuousLanes); <del> } <del> case DefaultLanePriority: { <del> return pickArbitraryLane(DefaultLanes); <del> } <add> case InputDiscreteLanePriority: <add> return InputDiscreteLane; <add> case InputContinuousLanePriority: <add> return InputContinuousLane; <add> case DefaultLanePriority: <add> return DefaultLane; <ide> case TransitionPriority: // Should be handled by findTransitionLane instead <ide> case RetryLanePriority: // Should be handled by findRetryLane instead <ide> break; <ide> case IdleLanePriority: <del> return pickArbitraryLane(IdleLanes); <add> return IdleLane; <ide> default: <ide> // The remaining priorities are not valid for updates <ide> break; <ide> export function claimNextTransitionLane(): Lane { <ide> const lane = nextTransitionLane; <ide> nextTransitionLane <<= 1; <ide> if ((nextTransitionLane & TransitionLanes) === 0) { <del> nextTransitionLane = FirstTransitionLane; <add> nextTransitionLane = TransitionLane1; <ide> } <ide> return lane; <ide> } <ide> export function claimNextRetryLane(): Lane { <ide> const lane = nextRetryLane; <ide> nextRetryLane <<= 1; <ide> if ((nextRetryLane & RetryLanes) === 0) { <del> nextRetryLane = FirstRetryLane; <add> nextRetryLane = RetryLane1; <ide> } <ide> return lane; <ide> } <ide> export function markRootUpdated( <ide> // We don't do this if the incoming update is idle, because we never process <ide> // idle updates until after all the regular updates have finished; there's no <ide> // way it could unblock a transition. <del> if ((updateLane & IdleLanes) === NoLanes) { <add> if (updateLane !== IdleLane) { <ide> root.suspendedLanes = NoLanes; <ide> root.pingedLanes = NoLanes; <ide> } <ide> export function markRootExpired(root: FiberRoot, expiredLanes: Lanes) { <ide> } <ide> <ide> export function markDiscreteUpdatesExpired(root: FiberRoot) { <del> root.expiredLanes |= InputDiscreteLanes & root.pendingLanes; <add> if (root.pendingLanes & InputDiscreteLane) { <add> root.expiredLanes |= InputDiscreteLane; <add> } <ide> } <ide> <ide> export function hasDiscreteLanes(lanes: Lanes) { <del> return (lanes & InputDiscreteLanes) !== NoLanes; <add> return (lanes & InputDiscreteLane) !== NoLanes; <ide> } <ide> <ide> export function markRootMutableRead(root: FiberRoot, updateLane: Lane) {
2
Javascript
Javascript
update eslint-check.js to object style
87b9a77290cd8727936ef15ea7f460519f8d91f5
<ide><path>tools/eslint-rules/eslint-check.js <ide> const utils = require('./rules-utils.js'); <ide> const msg = 'Please add a skipIfEslintMissing() call to allow this test to ' + <ide> 'be skipped when Node.js is built from a source tarball.'; <ide> <del>module.exports = function(context) { <del> const missingCheckNodes = []; <del> let commonModuleNode = null; <del> let hasEslintCheck = false; <add>module.exports = { <add> meta: { <add> fixable: 'code', <add> }, <add> create: function(context) { <add> const missingCheckNodes = []; <add> let commonModuleNode = null; <add> let hasEslintCheck = false; <ide> <del> function testEslintUsage(context, node) { <del> if (utils.isRequired(node, ['../../tools/node_modules/eslint'])) { <del> missingCheckNodes.push(node); <del> } <add> function testEslintUsage(context, node) { <add> if (utils.isRequired(node, ['../../tools/node_modules/eslint'])) { <add> missingCheckNodes.push(node); <add> } <ide> <del> if (utils.isCommonModule(node)) { <del> commonModuleNode = node; <add> if (utils.isCommonModule(node)) { <add> commonModuleNode = node; <add> } <ide> } <del> } <ide> <del> function checkMemberExpression(context, node) { <del> if (utils.usesCommonProperty(node, ['skipIfEslintMissing'])) { <del> hasEslintCheck = true; <add> function checkMemberExpression(context, node) { <add> if (utils.usesCommonProperty(node, ['skipIfEslintMissing'])) { <add> hasEslintCheck = true; <add> } <ide> } <del> } <ide> <del> function reportIfMissing(context) { <del> if (!hasEslintCheck) { <del> missingCheckNodes.forEach((node) => { <del> context.report({ <del> node, <del> message: msg, <del> fix: (fixer) => { <del> if (commonModuleNode) { <del> return fixer.insertTextAfter( <del> commonModuleNode, <del> '\ncommon.skipIfEslintMissing();' <del> ); <add> function reportIfMissing(context) { <add> if (!hasEslintCheck) { <add> missingCheckNodes.forEach((node) => { <add> context.report({ <add> node, <add> message: msg, <add> fix: (fixer) => { <add> if (commonModuleNode) { <add> return fixer.insertTextAfter( <add> commonModuleNode, <add> '\ncommon.skipIfEslintMissing();' <add> ); <add> } <ide> } <del> } <add> }); <ide> }); <del> }); <add> } <ide> } <del> } <ide> <del> return { <del> 'CallExpression': (node) => testEslintUsage(context, node), <del> 'MemberExpression': (node) => checkMemberExpression(context, node), <del> 'Program:exit': () => reportIfMissing(context) <del> }; <del>}; <del> <del>module.exports.meta = { <del> fixable: 'code' <add> return { <add> 'CallExpression': (node) => testEslintUsage(context, node), <add> 'MemberExpression': (node) => checkMemberExpression(context, node), <add> 'Program:exit': () => reportIfMissing(context) <add> }; <add> } <ide> };
1
Javascript
Javascript
remove extra comments and empty test
396dd7f11c7551d3250c38909f333904cd85f14e
<ide><path>packages/ember-glimmer/lib/helpers/get.js <ide> import { isConst } from 'glimmer-reference'; <ide> <ide> export default { <ide> isInternalHelper: true, <del> // toReference(args) { <ide> <ide> toReference(args) { <ide> let sourceReference = args.positional.at(0); <ide> export default { <ide> return new GetHelperReference(sourceReference, propertyPathReference); <ide> } <ide> } <del> // return new GetHelperReference(args); <del> // } <ide> }; <del> <ide><path>packages/ember-glimmer/tests/integration/helpers/get-test.js <ide> moduleFor('Helpers test: {{get}}', class extends RenderingTest { <ide> this.assert.strictEqual(get(this.context, 'source.banana'), 'some value'); <ide> } <ide> }); <del>
2
Python
Python
add a test case for invalid app key scenario
174af8f8f78300304caf5787c20cd74bc26dd832
<ide><path>libcloud/test/common/test_ovh.py <ide> class BaseOvhMockHttp(MockHttp): <ide> <ide> def _get_method_name(self, type, use_param, qs, path): <add> if type: <add> meth_name = '_json%s_%s_%s' % (FORMAT_URL.sub('_', path), 'get', type) <add> return meth_name <ide> return "_json" <ide> <ide> def _json(self, method, url, body, headers): <ide><path>libcloud/test/compute/test_ovh.py <ide> from mock import patch <ide> <ide> from libcloud.utils.py3 import httplib <add>from libcloud.common.exceptions import BaseHTTPError <add>from libcloud.http import LibcloudConnection <ide> <ide> from libcloud.compute.drivers.ovh import OvhNodeDriver <ide> <ide> def _json_1_0_cloud_subsidiaryPrice_flavorId_foo_id_ovhSubsidiary_US_get(self, m <ide> body = self.fixtures.load('pricing_get.json') <ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <ide> <add> def _json_1_0_cloud_project_project_id_instance_get_invalid_app_key_error(self, method, url, body, headers): <add> body = '{"message":"Invalid application key"}' <add> return (httplib.UNAUTHORIZED, body, {}, httplib.responses[httplib.OK]) <add> <ide> <ide> @patch('libcloud.common.ovh.OvhConnection._timedelta', 42) <ide> class OvhTests(unittest.TestCase): <ide> def setUp(self): <ide> OvhMockHttp.type = None <ide> self.driver = OvhNodeDriver(*OVH_PARAMS) <ide> <add> def test_list_nodes_invalid_region(self): <add> OvhNodeDriver.connectionCls.conn_class = LibcloudConnection <add> driver = OvhNodeDriver(*OVH_PARAMS, region='invalid') <add> <add> expected_msg = r'invalid region argument was passed.*Used host: invalid.api.ovh.com.*' <add> self.assertRaisesRegex(ValueError, expected_msg, driver.list_nodes) <add> <add> expected_msg = r'invalid region argument was passed.*Used host: invalid.api.ovh.com.*' <add> self.assertRaisesRegex(ValueError, expected_msg, driver.connection.request_consumer_key, '1') <add> <add> def test_invalid_application_key_correct_error(self): <add> OvhMockHttp.type = 'invalid_app_key_error' <add> driver = OvhNodeDriver('appkeyinvalid', 'application_secret', 'project_id', <add> 'consumer_key') <add> <add> expected_msg = r'Invalid application key' <add> self.assertRaisesRegex(BaseHTTPError, expected_msg, driver.list_nodes) <add> <ide> def test_list_locations(self): <ide> images = self.driver.list_locations() <ide> self.assertTrue(len(images) > 0) <ide> def test_destroy_volume_snapshot(self): <ide> def test_get_pricing(self): <ide> self.driver.ex_get_pricing('foo-id') <ide> <add> <ide> if __name__ == '__main__': <ide> sys.exit(unittest.main())
2
Text
Text
link minitest assertions documentation
e96e840ede2a7400f3acc73ab819ff91de068a1d
<ide><path>guides/source/testing.md <ide> Ideally, you would like to include a test for everything which could possibly br <ide> <ide> By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned. <ide> <del>There are a bunch of different types of assertions you can use. <del>Here's an extract of the assertions you can use with `minitest`, the default testing library used by Rails. The `[msg]` parameter is an optional string message you can specify to make your test failure messages clearer. It's not required. <add>There are a bunch of different types of assertions you can use. Here's an <add>extract of the <add>[assertions](http://docs.seattlerb.org/minitest/Minitest/Assertions.html) you <add>can use with [minitest](https://github.com/seattlerb/minitest), the default <add>testing library used by Rails. The `[msg]` parameter is an optional string <add>message you can specify to make your test failure messages clearer. It's not <add>required. <ide> <ide> | Assertion | Purpose | <ide> | ---------------------------------------------------------------- | ------- |
1
Javascript
Javascript
fix coding style in test/unit/function_spec.js
3cd64a85ba9082587fd2b69a6ca1d84b6adb3cae
<ide><path>test/unit/function_spec.js <ide> describe('function', function() { <ide> this.addMatchers({ <ide> toMatchArray: function(expected) { <ide> var actual = this.actual; <del> if (actual.length != expected.length) <add> if (actual.length != expected.length) { <ide> return false; <add> } <ide> for (var i = 0; i < expected.length; i++) { <ide> var a = actual[i], b = expected[i]; <ide> if (isArray(b)) { <del> if (a.length != b.length) <add> if (a.length != b.length) { <ide> return false; <add> } <ide> for (var j = 0; j < a.length; j++) { <ide> var suba = a[j], subb = b[j]; <del> if (suba !== subb) <add> if (suba !== subb) { <ide> return false; <add> } <ide> } <ide> } else { <del> if (a !== b) <add> if (a !== b) { <ide> return false; <add> } <ide> } <ide> } <ide> return true;
1
Ruby
Ruby
initialize instance variables
dc2352c58f0f05d9df171538483f31d42e9f0668
<ide><path>actionpack/lib/action_dispatch/middleware/session/abstract_store.rb <ide> def initialize(by, env) <ide> @env = env <ide> @delegate = {} <ide> @loaded = false <add> @exists = nil # we haven't checked yet <ide> end <ide> <ide> def destroy <ide> def inspect <ide> end <ide> <ide> def exists? <del> return @exists if instance_variable_defined?(:@exists) <add> return @exists unless @exists.nil? <ide> @exists = @by.send(:session_exists?, @env) <ide> end <ide> <ide> def load_for_write! <ide> end <ide> <ide> def load! <del> id, session = @by.send(:load_session, @env) <add> id, session = @by.load_session @env <ide> @env[ENV_SESSION_OPTIONS_KEY][:id] = id <ide> @delegate.replace(stringify_keys(session)) <ide> @loaded = true <ide> end <ide> <ide> def stringify_keys(other) <del> hash = {} <del> other.each do |key, value| <add> other.each_with_object({}) { |(key, value), hash| <ide> hash[key.to_s] = value <del> end <del> hash <add> } <ide> end <ide> end <ide> end
1
Text
Text
fix portuguese translations
d4f8b00c84207b1ec40f2d601b9cda4d1c064767
<ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/use-each-to-map-over-items-in-a-list.portuguese.md <ide> localeTitle: Use @each para mapear itens em uma lista <ide> --- <ide> <ide> ## Description <del><section id="description"> O último desafio mostrou como o <code>@for</code> diretiva usa um valor inicial e final para fazer um loop em um determinado número de vezes. O Sass também oferece a diretiva <code>@each</code> que faz um loop sobre cada item em uma lista ou mapa. Em cada iteração, a variável é atribuída ao valor atual da lista ou do mapa. <blockquote> @each $ color em azul, vermelho, verde { <br> . # {$ color} -text {color: $ color;} <br> } </blockquote> Um mapa tem uma sintaxe ligeiramente diferente. Aqui está um exemplo: <blockquote> $ colors: (color1: azul, color2: vermelho, color3: verde); <br><br> @ cada tecla $, $ cor em $ cores { <br> . # {$ color} -text {color: $ color;} <br> } </blockquote> Observe que a variável <code>$key</code> é necessária para referenciar as chaves no mapa. Caso contrário, o CSS compilado teria <code>color1</code> , <code>color2</code> ... nele. Ambos os exemplos de código acima são convertidos no seguinte CSS: <blockquote> .blue-text { <br> cor azul; <br> } <br><br> .red-text { <br> cor vermelha; <br> } <br><br> .green-text { <br> cor verde; <br> } </blockquote></section> <add><section id="description"> <add> <add>O último desafio mostrou como a diretiva <code>@for</code> usa um valor inicial e final para repetir um certo número de vezes. O Sass também oferece a diretiva <code>@each</code>, que percorre cada item em uma lista ou mapa. Em cada iteração, a variável é atribuída ao valor atual da lista ou mapa. <add> <add>```scss <add>@each $color in blue, red, green { <add> .#{$color}-text {color: $color;} <add>} <add>``` <add> <add>Um mapa tem uma sintaxe ligeiramente diferente. Aqui está um exemplo: <add> <add>```scss <add>$colors: (color1: blue, color2: red, color3: green); <add> <add>@each $key, $color in $colors { <add> .#{$color}-text {color: $color;} <add>} <add>``` <add> <add>Observe que a variável <code>$key</code> é necessária para referenciar as chaves no mapa. Caso contrário, o CSS compilado teria <code>color1</code>, <code>color2</code> ... nele. <add>Os dois exemplos de código acima são convertidos no seguinte CSS: <add> <add>```scss <add>.blue-text { <add> color: blue; <add>} <add> <add>.red-text { <add> color: red; <add>} <add> <add>.green-text { <add> color: green; <add>} <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> Escreva uma diretiva <code>@each</code> que passe por uma lista: <code>blue, black, red</code> e atribua cada variável a uma classe <code>.color-bg</code> , onde a parte &quot;color&quot; muda para cada item. Cada classe deve definir a <code>background-color</code> da respectiva cor. </section> <add><section id="instructions"> <add> <add>Escreva uma diretiva <code>@each</code> que passe por uma lista: <code>blue, black, red</code> e atribua cada variável a uma classe <code>.color-bg</code> , onde a parte &quot;color&quot; muda para cada item. Cada classe deve definir a <code>background-color</code> da respectiva cor. <add> <add></section> <ide> <ide> ## Tests <ide> <section id='tests'>
1
Text
Text
add node 12 to the first list of versions
e029b927c2a291b78bb27202a14bff09628b75a6
<ide><path>CHANGELOG.md <ide> <ide> Select a Node.js version below to view the changelog history: <ide> <del>* [Node.js 11](doc/changelogs/CHANGELOG_V11.md) - **Current** <add>* [Node.js 12](doc/changelogs/CHANGELOG_V12.md) - **Current** <add>* [Node.js 11](doc/changelogs/CHANGELOG_V11.md) - Current <ide> * [Node.js 10](doc/changelogs/CHANGELOG_V10.md) — **Long Term Support** <ide> * [Node.js 9](doc/changelogs/CHANGELOG_V9.md) — End-of-Life <ide> * [Node.js 8](doc/changelogs/CHANGELOG_V8.md) — Long Term Support
1
Mixed
Javascript
use objects with null prototype in agent
2ef9a76ece1e403d1dd7019fceb8f258607e7a69
<ide><path>doc/api/http.md <ide> terminates them. <ide> ### `agent.freeSockets` <ide> <!-- YAML <ide> added: v0.11.4 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/36409 <add> description: The property now has a `null` prototype. <ide> --> <ide> <ide> * {Object} <ide> can have open. Unlike `maxSockets`, this parameter applies across all origins. <ide> ### `agent.requests` <ide> <!-- YAML <ide> added: v0.5.9 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/36409 <add> description: The property now has a `null` prototype. <ide> --> <ide> <ide> * {Object} <ide> sockets. Do not modify. <ide> ### `agent.sockets` <ide> <!-- YAML <ide> added: v0.3.6 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/36409 <add> description: The property now has a `null` prototype. <ide> --> <ide> <ide> * {Object} <ide><path>lib/_http_agent.js <ide> <ide> const { <ide> NumberIsNaN, <add> ObjectCreate, <ide> ObjectKeys, <ide> ObjectSetPrototypeOf, <ide> ObjectValues, <ide> function Agent(options) { <ide> this.defaultPort = 80; <ide> this.protocol = 'http:'; <ide> <del> this.options = { ...options }; <add> this.options = { __proto__: null, ...options }; <ide> <ide> // Don't confuse net and make it think that we're connecting to a pipe <ide> this.options.path = null; <del> this.requests = {}; <del> this.sockets = {}; <del> this.freeSockets = {}; <add> this.requests = ObjectCreate(null); <add> this.sockets = ObjectCreate(null); <add> this.freeSockets = ObjectCreate(null); <ide> this.keepAliveMsecs = this.options.keepAliveMsecs || 1000; <ide> this.keepAlive = this.options.keepAlive || false; <ide> this.maxSockets = this.options.maxSockets || Agent.defaultMaxSockets; <ide> Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, <ide> // Legacy API: addRequest(req, host, port, localAddress) <ide> if (typeof options === 'string') { <ide> options = { <add> __proto__: null, <ide> host: options, <ide> port, <ide> localAddress <ide> }; <ide> } <ide> <del> options = { ...options, ...this.options }; <add> options = { __proto__: null, ...options, ...this.options }; <ide> if (options.socketPath) <ide> options.path = options.socketPath; <ide> <ide> Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, <ide> }; <ide> <ide> Agent.prototype.createSocket = function createSocket(req, options, cb) { <del> options = { ...options, ...this.options }; <add> options = { __proto__: null, ...options, ...this.options }; <ide> if (options.socketPath) <ide> options.path = options.socketPath; <ide> <ide> Agent.prototype.removeSocket = function removeSocket(s, options) { <ide> // There might be older requests in a different origin, but <ide> // if the origin which releases the socket has pending requests <ide> // that will be prioritized. <del> for (const prop in this.requests) { <add> for (const prop of ObjectKeys(this.requests)) { <ide> // Check whether this specific origin is already at maxSockets <ide> if (this.sockets[prop] && this.sockets[prop].length) break; <ide> debug('removeSocket, have a request with different origin,' + <ide><path>test/parallel/test-http-client-agent.js <ide> server.listen(0, common.mustCall(() => { <ide> })); <ide> <ide> const countdown = new Countdown(max, () => { <del> assert(!http.globalAgent.sockets.hasOwnProperty(name)); <del> assert(!http.globalAgent.requests.hasOwnProperty(name)); <add> assert(!(name in http.globalAgent.sockets)); <add> assert(!(name in http.globalAgent.requests)); <ide> server.close(); <ide> }); <ide> <ide><path>test/parallel/test-http-client-override-global-agent.js <ide> server.listen(0, common.mustCall(() => { <ide> http.globalAgent = agent; <ide> <ide> makeRequest(); <del> assert(agent.sockets.hasOwnProperty(name)); // Agent has indeed been used <add> assert(name in agent.sockets); // Agent has indeed been used <ide> })); <ide> <ide> function makeRequest() { <ide><path>test/parallel/test-http-connect-req-res.js <ide> server.listen(0, common.mustCall(function() { <ide> <ide> // Make sure this request got removed from the pool. <ide> const name = `localhost:${server.address().port}`; <del> assert(!http.globalAgent.sockets.hasOwnProperty(name)); <del> assert(!http.globalAgent.requests.hasOwnProperty(name)); <add> assert(!(name in http.globalAgent.sockets)); <add> assert(!(name in http.globalAgent.requests)); <ide> <ide> // Make sure this socket has detached. <ide> assert(!socket.ondata); <ide><path>test/parallel/test-http-connect.js <ide> server.listen(0, common.mustCall(() => { <ide> req.on('connect', common.mustCall((res, socket, firstBodyChunk) => { <ide> // Make sure this request got removed from the pool. <ide> const name = `localhost:${server.address().port}`; <del> assert(!http.globalAgent.sockets.hasOwnProperty(name)); <del> assert(!http.globalAgent.requests.hasOwnProperty(name)); <add> assert(!(name in http.globalAgent.sockets)); <add> assert(!(name in http.globalAgent.requests)); <ide> <ide> // Make sure this socket has detached. <ide> assert(!socket.ondata); <ide><path>test/parallel/test-http-keep-alive.js <ide> server.listen(0, common.mustCall(function() { <ide> }, common.mustCall((response) => { <ide> response.on('end', common.mustCall(() => { <ide> assert.strictEqual(agent.sockets[name].length, 1); <del> assert(!agent.requests.hasOwnProperty(name)); <add> assert(!(name in agent.requests)); <ide> server.close(); <ide> })); <ide> response.resume(); <ide> })); <ide> })); <ide> <ide> process.on('exit', () => { <del> assert(!agent.sockets.hasOwnProperty(name)); <del> assert(!agent.requests.hasOwnProperty(name)); <add> assert(!(name in agent.sockets)); <add> assert(!(name in agent.requests)); <ide> }); <ide><path>test/parallel/test-http-upgrade-agent.js <ide> server.listen(0, '127.0.0.1', common.mustCall(function() { <ide> assert.deepStrictEqual(expectedHeaders, res.headers); <ide> <ide> // Make sure this request got removed from the pool. <del> assert(!http.globalAgent.sockets.hasOwnProperty(name)); <add> assert(!(name in http.globalAgent.sockets)); <ide> <ide> req.on('close', common.mustCall(function() { <ide> socket.end(); <ide><path>test/parallel/test-https-client-override-global-agent.js <ide> server.listen(0, common.mustCall(() => { <ide> https.globalAgent = agent; <ide> <ide> makeRequest(); <del> assert(agent.sockets.hasOwnProperty(name)); // Agent has indeed been used <add> assert(name in agent.sockets); // Agent has indeed been used <ide> })); <ide> <ide> function makeRequest() {
9
Python
Python
accept json= parameter for payload
fd78c65cabae2241a4c1d3a792e00620049cbf3e
<ide><path>airflow/hooks/http_hook.py <ide> def get_conn(self, headers=None): <ide> <ide> return session <ide> <del> def run(self, endpoint, data=None, headers=None, extra_options=None): <del> """ <add> def run(self, endpoint, data=None, headers=None, extra_options=None, **request_kwargs): <add> r""" <ide> Performs the request <ide> <ide> :param endpoint: the endpoint to be called i.e. resource/v1/query? <ide> def run(self, endpoint, data=None, headers=None, extra_options=None): <ide> i.e. {'check_response': False} to avoid checking raising exceptions on non <ide> 2XX or 3XX status codes <ide> :type extra_options: dict <add> :param \**request_kwargs: Additional kwargs to pass when creating a request. <add> For example, ``run(json=obj)`` is passed as ``requests.Request(json=obj)`` <ide> """ <ide> extra_options = extra_options or {} <ide> <ide> def run(self, endpoint, data=None, headers=None, extra_options=None): <ide> req = requests.Request(self.method, <ide> url, <ide> params=data, <del> headers=headers) <add> headers=headers, <add> **request_kwargs) <ide> elif self.method == 'HEAD': <ide> # HEAD doesn't use params <ide> req = requests.Request(self.method, <ide> url, <del> headers=headers) <add> headers=headers, <add> **request_kwargs) <ide> else: <ide> # Others use data <ide> req = requests.Request(self.method, <ide> url, <ide> data=data, <del> headers=headers) <add> headers=headers, <add> **request_kwargs) <ide> <ide> prepped_request = session.prepare_request(req) <ide> self.log.info("Sending '%s' to url: %s", self.method, url) <ide><path>tests/hooks/test_http_hook.py <ide> import requests <ide> import requests_mock <ide> import tenacity <add>from parameterized import parameterized <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.hooks.http_hook import HttpHook <ide> def test_connection_without_host(self, mock_get_connection): <ide> hook.get_conn({}) <ide> self.assertEqual(hook.base_url, 'http://') <ide> <add> @parameterized.expand([ <add> 'GET', <add> 'POST', <add> ]) <add> @requests_mock.mock() <add> def test_json_request(self, method, mock_requests): <add> obj1 = {'a': 1, 'b': 'abc', 'c': [1, 2, {"d": 10}]} <add> <add> def match_obj1(request): <add> return request.json() == obj1 <add> <add> mock_requests.request( <add> method=method, <add> url='//test:8080/v1/test', <add> additional_matcher=match_obj1 <add> ) <add> <add> with mock.patch( <add> 'airflow.hooks.base_hook.BaseHook.get_connection', <add> side_effect=get_airflow_connection <add> ): <add> # will raise NoMockAddress exception if obj1 != request.json() <add> HttpHook(method=method).run('v1/test', json=obj1) <add> <ide> <ide> send_email_test = mock.Mock()
2
Text
Text
add clicksign to inthewild.md
c046c49d45975e99d7038fa9e19ff5429d16d1f9
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Clairvoyant](https://clairvoyantsoft.com) [[@shekharv](https://github.com/shekharv)] <ide> 1. [Classmethod, Inc.](https://classmethod.jp/) [[@shoito](https://github.com/shoito)] <ide> 1. [Cleartax](https://cleartax.in/) [[@anks](https://github.com/anks) & [@codebuff](https://github.com/codebuff)] <add>1. [Clicksign](https://clicksign.com/) [[@mbbernstein](https://github.com/mbbernstein) & [@jorgeac12](https://github.com/jorgeac12) & [@franklin390](https://github.com/franklin390)] <ide> 1. [Cloudera](https://www.cloudera.com/) [[@phraniiac](https://github.com/phraniiac) & [@VivekPemawat](https://github.com/VivekPemawat)] <ide> 1. [Clover Health](https://www.cloverhealth.com) [[@gwax](https://github.com/gwax) & [@vansivallab](https://github.com/vansivallab)] <ide> 1. [Colgate-Palmolive](https://www.colgatepalmolive.com/) [[@fhoda](https://github.com/fhoda)]
1
Python
Python
add head_mask and decoder_head_mask to fsmt
0c6c0afc0e06bc2e8277e16bc5e57e470232f63b
<ide><path>src/transformers/models/fsmt/modeling_fsmt.py <ide> also be used by default. If you want to change padding behavior, you should read <ide> :func:`modeling_fstm._prepare_fstm_decoder_inputs` and modify. See diagram 1 in the paper for more info on <ide> the default strategy <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the head is **masked**. <ide> encoder_outputs (:obj:`Tuple(torch.FloatTensor)`, `optional`): <ide> Tuple consists of (:obj:`last_hidden_state`, `optional`: :obj:`hidden_states`, `optional`: <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)` is a <ide> def triu_onnx(x, diagonal=0): <ide> <ide> <ide> def _prepare_fsmt_decoder_inputs( <del> config, input_ids, decoder_input_ids=None, decoder_padding_mask=None, causal_mask_dtype=torch.float32 <add> config, <add> input_ids, <add> decoder_input_ids=None, <add> decoder_padding_mask=None, <add> causal_mask_dtype=torch.float32, <ide> ): <ide> """ <ide> Prepare masks that ignore padding tokens in the decoder and a causal mask for the decoder if none are provided. <ide> def __init__(self, config: FSMTConfig): <ide> self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) <ide> self.final_layer_norm = LayerNorm(self.embed_dim) <ide> <del> def forward(self, x, encoder_padding_mask, output_attentions=False): <add> def forward(self, x, encoder_padding_mask, layer_head_mask, output_attentions=False): <ide> """ <ide> Args: <del> x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` <del> encoder_padding_mask (ByteTensor): binary ByteTensor of shape <add> x (:obj:`torch.Tensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <add> encoder_padding_mask (:obj:`torch.ByteTensor`): binary ByteTensor of shape <ide> `(batch, src_len)` where padding elements are indicated by ``1``. <ide> for t_tgt, t_src is excluded (or masked out), =0 means it is <ide> included in attention <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <ide> <ide> Returns: <ide> encoded output of shape `(seq_len, batch, embed_dim)` <ide> """ <ide> residual = x <ide> x, attn_weights = self.self_attn( <del> query=x, key=x, key_padding_mask=encoder_padding_mask, output_attentions=output_attentions <add> query=x, <add> key=x, <add> key_padding_mask=encoder_padding_mask, <add> layer_head_mask=layer_head_mask, <add> output_attentions=output_attentions, <ide> ) <ide> x = F.dropout(x, p=self.dropout, training=self.training) <ide> x = residual + x <ide> def __init__(self, config: FSMTConfig, embed_tokens): <ide> ) # type: List[EncoderLayer] <ide> <ide> def forward( <del> self, input_ids, attention_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True <add> self, <add> input_ids, <add> attention_mask=None, <add> head_mask=None, <add> output_attentions=False, <add> output_hidden_states=False, <add> return_dict=True, <ide> ): <ide> """ <ide> Args: <del> input_ids (LongTensor): tokens in the source language of shape <add> input_ids (:obj:`torch.LongTensor`): tokens in the source language of shape <ide> `(batch, src_len)` <del> attention_mask (torch.LongTensor): indicating which indices are padding tokens <add> attention_mask (:obj:`torch.LongTensor`): indicating which indices are padding tokens <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <ide> <ide> Returns: <ide> BaseModelOutput or Tuple comprised of: <ide> <del> - **x** (Tensor): the last encoder layer's output of shape `(src_len, batch, embed_dim)` <del> - **encoder_states** (tuple(torch.FloatTensor)): all intermediate hidden states of shape `(src_len, <del> batch, embed_dim)`. Only populated if *output_hidden_states:* is True. <del> - **all_attentions** (tuple(torch.FloatTensor)): Attention weights for each layer. <add> - **x** (:obj:`torch.Tensor`): the last encoder layer's output of shape `(src_len, batch, embed_dim)` <add> - **encoder_states** (:obj:`Tuple(torch.FloatTensor`)): all intermediate hidden states of shape <add> `(src_len, batch, embed_dim)`. Only populated if *output_hidden_states:* is True. <add> - **all_attentions** (:obj:`Tuple(torch.FloatTensor`)): Attention weights for each layer. <ide> During training might not be of length n_layers because of layer dropout. <ide> """ <ide> # check attention mask and invert <ide> def forward( <ide> <ide> encoder_states = () if output_hidden_states else None <ide> all_attentions = () if output_attentions else None <del> for encoder_layer in self.layers: <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> x = x.transpose(0, 1) # T x B x C -> B x T x C <ide> encoder_states += (x,) <ide> def forward( <ide> if self.training and (dropout_probability < self.layerdrop): # skip the layer <ide> attn = None <ide> else: <del> x, attn = encoder_layer(x, attention_mask, output_attentions=output_attentions) <add> x, attn = encoder_layer( <add> x, <add> attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> output_attentions=output_attentions, <add> ) <ide> <ide> if output_attentions: <ide> all_attentions = all_attentions + (attn,) <ide> def forward( <ide> encoder_attn_mask=None, <ide> layer_state=None, <ide> causal_mask=None, <add> layer_head_mask=None, <add> encoder_layer_head_mask=None, <ide> decoder_padding_mask=None, <ide> output_attentions=False, <ide> ): <ide> def forward( <ide> layer_state=layer_state, # adds keys to layer state <ide> key_padding_mask=decoder_padding_mask, <ide> attn_mask=causal_mask, <add> layer_head_mask=layer_head_mask, <ide> output_attentions=output_attentions, <ide> ) <ide> x = F.dropout(x, p=self.dropout, training=self.training) <ide> def forward( <ide> key=encoder_hidden_states, <ide> key_padding_mask=encoder_attn_mask, <ide> layer_state=layer_state, # mutates layer state <add> layer_head_mask=encoder_layer_head_mask, <ide> output_attentions=output_attentions, <ide> ) <ide> x = F.dropout(x, p=self.dropout, training=self.training) <ide> def forward( <ide> encoder_padding_mask, <ide> decoder_padding_mask, <ide> decoder_causal_mask, <add> head_mask=None, <add> encoder_head_mask=None, <ide> past_key_values=None, <ide> use_cache=False, <ide> output_attentions=False, <ide> def forward( <ide> EMNLP 2019). <ide> <ide> Args: <del> input_ids (LongTensor): previous decoder outputs of shape <del> `(batch, tgt_len)`, for teacher forcing <add> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch, tgt_len)`): <add> previous decoder outputs for teacher forcing <ide> encoder_hidden_states: output from the encoder, used for <ide> encoder-side attention <ide> encoder_padding_mask: for ignoring pad tokens <ide> past_key_values (dict or None): dictionary used for storing state during generation <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> encoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention <add> on hidden heads. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <ide> <ide> Returns: <ide> BaseModelOutputWithPast or tuple: <ide> def forward( <ide> all_self_attns = () if output_attentions else None <ide> all_cross_attns = () if output_attentions else None <ide> next_decoder_cache = [] <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide> def forward( <ide> decoder_padding_mask=decoder_padding_mask, <ide> layer_state=layer_state, <ide> causal_mask=decoder_causal_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> encoder_layer_head_mask=(encoder_head_mask[idx] if encoder_head_mask is not None else None), <ide> output_attentions=output_attentions, <ide> ) <ide> <ide> def forward( <ide> key_padding_mask: Optional[Tensor] = None, <ide> layer_state: Optional[Dict[str, Optional[Tensor]]] = None, <ide> attn_mask: Optional[Tensor] = None, <add> layer_head_mask: Optional[Tensor] = None, <ide> output_attentions=False, <ide> ) -> Tuple[Tensor, Optional[Tensor]]: <ide> """Input shape: Time(SeqLen) x Batch x Channel""" <ide> def forward( <ide> <ide> attn_weights = F.softmax(attn_weights, dim=-1) <ide> <add> if layer_head_mask is not None: <add> assert layer_head_mask.size() == ( <add> self.num_heads, <add> ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <add> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <add> <ide> if output_attentions: <ide> # make sure that attn_weights are included in graph <ide> attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs: Optional[Tuple] = None, <ide> past_key_values=None, <ide> use_cache=None, <ide> def forward( <ide> encoder_outputs = self.encoder( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <ide> def forward( <ide> attention_mask, <ide> decoder_padding_mask, <ide> decoder_causal_mask=causal_mask, <add> head_mask=decoder_head_mask, <add> encoder_head_mask=head_mask, <ide> past_key_values=past_key_values, <ide> use_cache=use_cache, <ide> output_attentions=output_attentions, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> labels=None, <ide> def forward( <ide> decoder_input_ids=decoder_input_ids, <ide> encoder_outputs=encoder_outputs, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> past_key_values=past_key_values, <ide> use_cache=use_cache, <ide> output_attentions=output_attentions, <ide><path>tests/test_modeling_fsmt.py <ide> def prepare_fsmt_inputs_dict( <ide> config, <ide> input_ids, <ide> attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> ): <ide> if attention_mask is None: <ide> attention_mask = input_ids.ne(config.pad_token_id) <add> if head_mask is None: <add> head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device) <add> if decoder_head_mask is None: <add> decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device) <ide> return { <ide> "input_ids": input_ids, <ide> "attention_mask": attention_mask, <add> "head_mask": head_mask, <add> "decoder_head_mask": decoder_head_mask, <ide> } <ide> <ide> <ide> class FSMTModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): <ide> all_generative_model_classes = (FSMTForConditionalGeneration,) if is_torch_available() else () <ide> is_encoder_decoder = True <ide> test_pruning = False <del> test_head_masking = False <ide> test_missing_keys = False <ide> <ide> def setUp(self):
2
Java
Java
improve completable.delay operator internals
27c63b6a4c2074657aed4e7ee6e39a52173bbed5
<ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableDelay.java <ide> package io.reactivex.internal.operators.completable; <ide> <ide> import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.disposables.*; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> <ide> public final class CompletableDelay extends Completable { <ide> <ide> public CompletableDelay(CompletableSource source, long delay, TimeUnit unit, Sch <ide> <ide> @Override <ide> protected void subscribeActual(final CompletableObserver s) { <del> final CompositeDisposable set = new CompositeDisposable(); <del> <del> source.subscribe(new Delay(set, s)); <add> source.subscribe(new Delay(s, delay, unit, scheduler, delayError)); <ide> } <ide> <del> final class Delay implements CompletableObserver { <add> static final class Delay extends AtomicReference<Disposable> <add> implements CompletableObserver, Runnable, Disposable { <add> <add> private static final long serialVersionUID = 465972761105851022L; <add> <add> final CompletableObserver downstream; <add> <add> final long delay; <add> <add> final TimeUnit unit; <ide> <del> private final CompositeDisposable set; <del> final CompletableObserver s; <add> final Scheduler scheduler; <ide> <del> Delay(CompositeDisposable set, CompletableObserver s) { <del> this.set = set; <del> this.s = s; <add> final boolean delayError; <add> <add> Throwable error; <add> <add> Delay(CompletableObserver downstream, long delay, TimeUnit unit, Scheduler scheduler, boolean delayError) { <add> this.downstream = downstream; <add> this.delay = delay; <add> this.unit = unit; <add> this.scheduler = scheduler; <add> this.delayError = delayError; <add> } <add> <add> @Override <add> public void onSubscribe(Disposable d) { <add> if (DisposableHelper.setOnce(this, d)) { <add> downstream.onSubscribe(this); <add> } <ide> } <ide> <ide> @Override <ide> public void onComplete() { <del> set.add(scheduler.scheduleDirect(new OnComplete(), delay, unit)); <add> DisposableHelper.replace(this, scheduler.scheduleDirect(this, delay, unit)); <ide> } <ide> <ide> @Override <ide> public void onError(final Throwable e) { <del> set.add(scheduler.scheduleDirect(new OnError(e), delayError ? delay : 0, unit)); <add> error = e; <add> DisposableHelper.replace(this, scheduler.scheduleDirect(this, delayError ? delay : 0, unit)); <ide> } <ide> <ide> @Override <del> public void onSubscribe(Disposable d) { <del> set.add(d); <del> s.onSubscribe(set); <add> public void dispose() { <add> DisposableHelper.dispose(this); <ide> } <ide> <del> final class OnComplete implements Runnable { <del> @Override <del> public void run() { <del> s.onComplete(); <del> } <add> @Override <add> public boolean isDisposed() { <add> return DisposableHelper.isDisposed(get()); <ide> } <ide> <del> final class OnError implements Runnable { <del> private final Throwable e; <del> <del> OnError(Throwable e) { <del> this.e = e; <del> } <del> <del> @Override <del> public void run() { <del> s.onError(e); <add> @Override <add> public void run() { <add> Throwable e = error; <add> error = null; <add> if (e != null) { <add> downstream.onError(e); <add> } else { <add> downstream.onComplete(); <ide> } <ide> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java <ide> <ide> package io.reactivex.internal.operators.completable; <ide> <del>import java.util.concurrent.CountDownLatch; <del>import java.util.concurrent.TimeUnit; <add>import static org.junit.Assert.assertNotEquals; <add> <add>import java.util.concurrent.*; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <del>import io.reactivex.functions.Consumer; <ide> import org.junit.Test; <ide> <del>import io.reactivex.Completable; <del>import io.reactivex.schedulers.Schedulers; <del> <del>import static org.junit.Assert.assertNotEquals; <add>import io.reactivex.*; <add>import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.*; <add>import io.reactivex.observers.TestObserver; <add>import io.reactivex.schedulers.*; <ide> <ide> public class CompletableDelayTest { <ide> <ide> public void accept(Throwable throwable) throws Exception { <ide> assertNotEquals(Thread.currentThread(), thread.get()); <ide> } <ide> <add> @Test <add> public void disposed() { <add> TestHelper.checkDisposed(Completable.never().delay(1, TimeUnit.MINUTES)); <add> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeCompletable(new Function<Completable, CompletableSource>() { <add> @Override <add> public CompletableSource apply(Completable c) throws Exception { <add> return c.delay(1, TimeUnit.MINUTES); <add> } <add> }); <add> } <add> <add> @Test <add> public void normal() { <add> Completable.complete() <add> .delay(1, TimeUnit.MILLISECONDS) <add> .test() <add> .awaitDone(5, TimeUnit.SECONDS) <add> .assertResult(); <add> } <add> <add> @Test <add> public void errorNotDelayed() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> TestObserver<Void> to = Completable.error(new TestException()) <add> .delay(100, TimeUnit.MILLISECONDS, scheduler, false) <add> .test(); <add> <add> to.assertEmpty(); <add> <add> scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); <add> <add> to.assertFailure(TestException.class); <add> <add> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); <add> <add> to.assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void errorDelayed() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> TestObserver<Void> to = Completable.error(new TestException()) <add> .delay(100, TimeUnit.MILLISECONDS, scheduler, true) <add> .test(); <add> <add> to.assertEmpty(); <add> <add> scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); <add> <add> to.assertEmpty(); <add> <add> scheduler.advanceTimeBy(99, TimeUnit.MILLISECONDS); <add> <add> to.assertFailure(TestException.class); <add> } <ide> }
2
Go
Go
add support for tty in composefile v3
de15de6b4d90f8d707d92ab2f8b6a63e0742e8ce
<ide><path>cli/command/stack/deploy.go <ide> func convertService( <ide> User: service.User, <ide> Mounts: mounts, <ide> StopGracePeriod: service.StopGracePeriod, <add> TTY: service.Tty, <ide> }, <ide> Resources: resources, <ide> RestartPolicy: restartPolicy,
1
Javascript
Javascript
ignore symbols and functions in select tag
de5102c4cd9a0ece37872c5a1c6b1e1345b8afef
<ide><path>packages/react-dom/src/__tests__/ReactDOMSelect-test.js <ide> describe('ReactDOMSelect', () => { <ide> expect(node.options[1].selected).toBe(false); // b <ide> expect(node.options[2].selected).toBe(false); // c <ide> }); <add> <add> describe('When given a Symbol value', () => { <add> it('treats initial Symbol value as an empty string', () => { <add> let node; <add> <add> expect(() => { <add> node = ReactTestUtils.renderIntoDocument( <add> <select onChange={noop} value={Symbol('foobar')}> <add> <option value={Symbol('foobar')}>A Symbol!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> }).toWarnDev('Invalid value for prop `value`'); <add> <add> expect(node.value).toBe(''); <add> }); <add> <add> it('treats updated Symbol value as an empty string', () => { <add> let node; <add> <add> expect(() => { <add> node = ReactTestUtils.renderIntoDocument( <add> <select onChange={noop} value="monkey"> <add> <option value={Symbol('foobar')}>A Symbol!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> }).toWarnDev('Invalid value for prop `value`'); <add> <add> expect(node.value).toBe('monkey'); <add> <add> node = ReactTestUtils.renderIntoDocument( <add> <select onChange={noop} value={Symbol('foobar')}> <add> <option value={Symbol('foobar')}>A Symbol!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> <add> expect(node.value).toBe(''); <add> }); <add> <add> it('treats initial Symbol defaultValue as an empty string', () => { <add> let node; <add> <add> expect(() => { <add> node = ReactTestUtils.renderIntoDocument( <add> <select defaultValue={Symbol('foobar')}> <add> <option value={Symbol('foobar')}>A Symbol!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> }).toWarnDev('Invalid value for prop `value`'); <add> <add> expect(node.value).toBe(''); <add> }); <add> <add> it('treats updated Symbol defaultValue as an empty string', () => { <add> let node; <add> <add> expect(() => { <add> node = ReactTestUtils.renderIntoDocument( <add> <select defaultValue="monkey"> <add> <option value={Symbol('foobar')}>A Symbol!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> }).toWarnDev('Invalid value for prop `value`'); <add> <add> expect(node.value).toBe('monkey'); <add> <add> node = ReactTestUtils.renderIntoDocument( <add> <select defaultValue={Symbol('foobar')}> <add> <option value={Symbol('foobar')}>A Symbol!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> <add> expect(node.value).toBe(''); <add> }); <add> }); <add> <add> describe('When given a function value', () => { <add> it('treats initial function value as an empty string', () => { <add> let node; <add> <add> expect(() => { <add> node = ReactTestUtils.renderIntoDocument( <add> <select onChange={noop} value={() => {}}> <add> <option value={() => {}}>A function!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> }).toWarnDev('Invalid value for prop `value`'); <add> <add> expect(node.value).toBe(''); <add> }); <add> <add> it('treats initial function defaultValue as an empty string', () => { <add> let node; <add> <add> expect(() => { <add> node = ReactTestUtils.renderIntoDocument( <add> <select defaultValue={() => {}}> <add> <option value={() => {}}>A function!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> }).toWarnDev('Invalid value for prop `value`'); <add> <add> expect(node.value).toBe(''); <add> }); <add> <add> it('treats updated function value as an empty string', () => { <add> let node; <add> <add> expect(() => { <add> node = ReactTestUtils.renderIntoDocument( <add> <select onChange={noop} value="monkey"> <add> <option value={() => {}}>A function!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> }).toWarnDev('Invalid value for prop `value`'); <add> <add> expect(node.value).toBe('monkey'); <add> <add> node = ReactTestUtils.renderIntoDocument( <add> <select onChange={noop} value={() => {}}> <add> <option value={() => {}}>A function!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> <add> expect(node.value).toBe(''); <add> }); <add> <add> it('treats updated function defaultValue as an empty string', () => { <add> let node; <add> <add> expect(() => { <add> node = ReactTestUtils.renderIntoDocument( <add> <select defaultValue="monkey"> <add> <option value={() => {}}>A function!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> }).toWarnDev('Invalid value for prop `value`'); <add> <add> expect(node.value).toBe('monkey'); <add> <add> node = ReactTestUtils.renderIntoDocument( <add> <select defaultValue={() => {}}> <add> <option value={() => {}}>A function!</option> <add> <option value="monkey">A monkey!</option> <add> <option value="giraffe">A giraffe!</option> <add> </select>, <add> ); <add> <add> expect(node.value).toBe(''); <add> }); <add> }); <ide> }); <ide><path>packages/react-dom/src/client/ReactDOMFiberOption.js <ide> import React from 'react'; <ide> import warning from 'shared/warning'; <ide> import {validateDOMNesting, updatedAncestorInfo} from './validateDOMNesting'; <add>import {getToStringValue, toString} from './ToStringValue'; <ide> <ide> let didWarnSelectedSetOnOption = false; <ide> <ide> export function validateProps(element: Element, props: Object) { <ide> export function postMountWrapper(element: Element, props: Object) { <ide> // value="" should make a value attribute (#6219) <ide> if (props.value != null) { <del> element.setAttribute('value', props.value); <add> element.setAttribute('value', toString(getToStringValue(props.value))); <ide> } <ide> } <ide> <ide><path>packages/react-dom/src/client/ReactDOMFiberSelect.js <ide> import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCur <ide> import warning from 'shared/warning'; <ide> <ide> import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes'; <add>import {getToStringValue, toString} from './ToStringValue'; <add>import type {ToStringValue} from './ToStringValue'; <ide> <ide> let didWarnValueDefaultValue; <ide> <ide> if (__DEV__) { <ide> <ide> type SelectWithWrapperState = HTMLSelectElement & { <ide> _wrapperState: { <del> initialValue: ?string, <add> initialValue: ?ToStringValue, <ide> wasMultiple: boolean, <ide> }, <ide> }; <ide> function updateOptions( <ide> } else { <ide> // Do not set `select.value` as exact behavior isn't consistent across all <ide> // browsers for all cases. <del> let selectedValue = '' + (propValue: string); <add> let selectedValue = toString(getToStringValue((propValue: any))); <ide> let defaultSelected = null; <ide> for (let i = 0; i < options.length; i++) { <ide> if (options[i].value === selectedValue) {
3
Javascript
Javascript
fix subtraction of runtimes
651e2ff0cb5665710234095fea4a5cc32436aa59
<ide><path>lib/util/runtime.js <ide> const subtractRuntime = (a, b) => { <ide> return undefined; <ide> } else if (typeof a === "string") { <ide> if (typeof b === "string") { <del> return undefined; <add> return a; <ide> } else if (b.has(a)) { <ide> return undefined; <ide> } else { <ide><path>test/configCases/side-effects/issue-13063/another.js <add>require("./vendors").UiSelectButton2(); <ide><path>test/configCases/side-effects/issue-13063/test.config.js <add>module.exports = { <add> findBundle: function () { <add> return ["./vendors.js", "./tst_examples_uiform.js"]; <add> } <add>}; <ide><path>test/configCases/side-effects/issue-13063/tst_examples_uiform.js <add>it("should not crash", () => { <add> require("./vendors").UiSelectButton(); <add> require("./vendors").UiSelectButton2(); <add>}); <ide><path>test/configCases/side-effects/issue-13063/tst_examples_uitable.js <add>import { UiButton } from "./vendors"; <add> <add>it("should not crash", () => { <add> UiButton(); <add>}); <ide><path>test/configCases/side-effects/issue-13063/vendors/index.js <add>import uuid from "./uuid"; <add>import { checkIsNonemptyString } from "./types"; <add>export { UiSelectButton } from "./select"; <add>export { UiSelectButton2 } from "./select2"; <add> <add>export function UiButton() { <add> checkIsNonemptyString(); <add> uuid(); <add>} <ide><path>test/configCases/side-effects/issue-13063/vendors/select.js <add>import uuid from "./uuid"; <add>import { checkIsNonemptyString } from "./types"; <add> <add>export function UiSelectButton() { <add> checkIsNonemptyString(); <add> uuid(); <add>} <add> <add>console.log.bind(console); <ide><path>test/configCases/side-effects/issue-13063/vendors/select2.js <add>import uuid from "./uuid"; <add> <add>export function UiSelectButton2() { <add> uuid(); <add>} <add> <add>console.log.bind(console); <ide><path>test/configCases/side-effects/issue-13063/vendors/types.js <add>export function checkIsNonemptyString() {} <ide><path>test/configCases/side-effects/issue-13063/vendors/uuid.js <add>export default function uuid() {} <ide><path>test/configCases/side-effects/issue-13063/webpack.config.js <add>module.exports = { <add> entry: { <add> tst_examples_uiform: "./tst_examples_uiform", <add> tst_examples_uitable: "./tst_examples_uitable", <add> another: "./another" <add> }, <add> output: { <add> pathinfo: "verbose", <add> filename: "[name].js" <add> }, <add> target: "web", <add> optimization: { <add> sideEffects: true, <add> concatenateModules: true, <add> splitChunks: { <add> cacheGroups: { <add> vendors: { <add> chunks: "all", <add> test: /vendors/, <add> enforce: true, <add> name: "vendors" <add> } <add> } <add> } <add> } <add>};
11
Javascript
Javascript
fix event handler method name in specs
e92cf0fe70b529f294a0206b7e403c99b0c4e7b0
<ide><path>spec/text-editor-component-spec.js <ide> describe('TextEditorComponent', () => { <ide> const {component, element, editor} = buildComponent() <ide> const {lineHeight} = component.measurements <ide> <del> component.didMouseDownOnLines({ <add> component.didMouseDownOnContent({ <ide> detail: 1, <ide> clientX: clientLeftForCharacter(component, 0, editor.lineLengthForScreenRow(0)) + 1, <ide> clientY: clientTopForLine(component, 0) + lineHeight / 2 <ide> }) <ide> expect(editor.getCursorScreenPosition()).toEqual([0, editor.lineLengthForScreenRow(0)]) <ide> <del> component.didMouseDownOnLines({ <add> component.didMouseDownOnContent({ <ide> detail: 1, <ide> clientX: (clientLeftForCharacter(component, 3, 0) + clientLeftForCharacter(component, 3, 1)) / 2, <ide> clientY: clientTopForLine(component, 1) + lineHeight / 2 <ide> }) <ide> expect(editor.getCursorScreenPosition()).toEqual([1, 0]) <ide> <del> component.didMouseDownOnLines({ <add> component.didMouseDownOnContent({ <ide> detail: 1, <ide> clientX: (clientLeftForCharacter(component, 3, 14) + clientLeftForCharacter(component, 3, 15)) / 2, <ide> clientY: clientTopForLine(component, 3) + lineHeight / 2 <ide> }) <ide> expect(editor.getCursorScreenPosition()).toEqual([3, 14]) <ide> <del> component.didMouseDownOnLines({ <add> component.didMouseDownOnContent({ <ide> detail: 1, <ide> clientX: (clientLeftForCharacter(component, 3, 14) + clientLeftForCharacter(component, 3, 15)) / 2 + 1, <ide> clientY: clientTopForLine(component, 3) + lineHeight / 2 <ide> describe('TextEditorComponent', () => { <ide> editor.getBuffer().setTextInRange([[3, 14], [3, 15]], '🐣') <ide> await component.getNextUpdatePromise() <ide> <del> component.didMouseDownOnLines({ <add> component.didMouseDownOnContent({ <ide> detail: 1, <ide> clientX: (clientLeftForCharacter(component, 3, 14) + clientLeftForCharacter(component, 3, 16)) / 2, <ide> clientY: clientTopForLine(component, 3) + lineHeight / 2 <ide> }) <ide> expect(editor.getCursorScreenPosition()).toEqual([3, 14]) <ide> <del> component.didMouseDownOnLines({ <add> component.didMouseDownOnContent({ <ide> detail: 1, <ide> clientX: (clientLeftForCharacter(component, 3, 14) + clientLeftForCharacter(component, 3, 16)) / 2 + 1, <ide> clientY: clientTopForLine(component, 3) + lineHeight / 2 <ide> describe('TextEditorComponent', () => { <ide> it('selects words on double-click', () => { <ide> const {component, editor} = buildComponent() <ide> const {clientX, clientY} = clientPositionForCharacter(component, 1, 16) <del> component.didMouseDownOnLines({detail: 1, clientX, clientY}) <del> component.didMouseDownOnLines({detail: 2, clientX, clientY}) <add> component.didMouseDownOnContent({detail: 1, clientX, clientY}) <add> component.didMouseDownOnContent({detail: 2, clientX, clientY}) <ide> expect(editor.getSelectedScreenRange()).toEqual([[1, 13], [1, 21]]) <ide> }) <ide> <ide> it('selects lines on triple-click', () => { <ide> const {component, editor} = buildComponent() <ide> const {clientX, clientY} = clientPositionForCharacter(component, 1, 16) <del> component.didMouseDownOnLines({detail: 1, clientX, clientY}) <del> component.didMouseDownOnLines({detail: 2, clientX, clientY}) <del> component.didMouseDownOnLines({detail: 3, clientX, clientY}) <add> component.didMouseDownOnContent({detail: 1, clientX, clientY}) <add> component.didMouseDownOnContent({detail: 2, clientX, clientY}) <add> component.didMouseDownOnContent({detail: 3, clientX, clientY}) <ide> expect(editor.getSelectedScreenRange()).toEqual([[1, 0], [2, 0]]) <ide> }) <ide> <ide> describe('TextEditorComponent', () => { <ide> expect(editor.getCursorScreenPositions()).toEqual([[0, 0]]) <ide> <ide> // add cursor at 1, 16 <del> component.didMouseDownOnLines( <add> component.didMouseDownOnContent( <ide> Object.assign(clientPositionForCharacter(component, 1, 16), { <ide> detail: 1, <ide> metaKey: true <ide> describe('TextEditorComponent', () => { <ide> expect(editor.getCursorScreenPositions()).toEqual([[0, 0], [1, 16]]) <ide> <ide> // remove cursor at 0, 0 <del> component.didMouseDownOnLines( <add> component.didMouseDownOnContent( <ide> Object.assign(clientPositionForCharacter(component, 0, 0), { <ide> detail: 1, <ide> metaKey: true <ide> describe('TextEditorComponent', () => { <ide> expect(editor.getCursorScreenPositions()).toEqual([[1, 16]]) <ide> <ide> // cmd-click cursor at 1, 16 but don't remove it because it's the last one <del> component.didMouseDownOnLines( <add> component.didMouseDownOnContent( <ide> Object.assign(clientPositionForCharacter(component, 1, 16), { <ide> detail: 1, <ide> metaKey: true <ide> describe('TextEditorComponent', () => { <ide> [[1, 16], [1, 16]], <ide> [[2, 10], [2, 15]] <ide> ]) <del> component.didMouseDownOnLines( <add> component.didMouseDownOnContent( <ide> Object.assign(clientPositionForCharacter(component, 2, 13), { <ide> detail: 1, <ide> metaKey: true <ide> describe('TextEditorComponent', () => { <ide> ]) <ide> <ide> // ctrl-click does not add cursors on macOS <del> component.didMouseDownOnLines( <add> component.didMouseDownOnContent( <ide> Object.assign(clientPositionForCharacter(component, 1, 4), { <ide> detail: 1, <ide> ctrlKey: true <ide> describe('TextEditorComponent', () => { <ide> mockedPlatform = 'win32' <ide> <ide> // ctrl-click adds cursors on platforms *other* than macOS <del> component.didMouseDownOnLines( <add> component.didMouseDownOnContent( <ide> Object.assign(clientPositionForCharacter(component, 1, 16), { <ide> detail: 1, <ide> ctrlKey: true <ide> describe('TextEditorComponent', () => { <ide> editor.addCursorAtScreenPosition([1, 16]) <ide> expect(editor.getCursorScreenPositions()).toEqual([[0, 0], [1, 16]]) <ide> <del> component.didMouseDownOnLines( <add> component.didMouseDownOnContent( <ide> Object.assign(clientPositionForCharacter(component, 1, 16), { <ide> detail: 1, <ide> metaKey: true <ide> }) <ide> ) <del> component.didMouseDownOnLines( <add> component.didMouseDownOnContent( <ide> Object.assign(clientPositionForCharacter(component, 1, 16), { <ide> detail: 2, <ide> metaKey: true <ide> describe('TextEditorComponent', () => { <ide> expect(editor.getCursorScreenPositions()).toEqual([[0, 0], [1, 16]]) <ide> <ide> const {clientX, clientY} = clientPositionForCharacter(component, 1, 16) <del> component.didMouseDownOnLines({detail: 1, metaKey: true, clientX, clientY}) <del> component.didMouseDownOnLines({detail: 2, metaKey: true, clientX, clientY}) <del> component.didMouseDownOnLines({detail: 3, metaKey: true, clientX, clientY}) <add> component.didMouseDownOnContent({detail: 1, metaKey: true, clientX, clientY}) <add> component.didMouseDownOnContent({detail: 2, metaKey: true, clientX, clientY}) <add> component.didMouseDownOnContent({detail: 3, metaKey: true, clientX, clientY}) <ide> <ide> expect(editor.getSelectedScreenRanges()).toEqual([ <ide> [[0, 0], [0, 0]], <ide> describe('TextEditorComponent', () => { <ide> const {component, element, editor} = buildComponent() <ide> <ide> editor.setCursorScreenPosition([2, 18]) <del> component.didMouseDownOnLines(Object.assign({ <add> component.didMouseDownOnContent(Object.assign({ <ide> detail: 1, <ide> shiftKey: true <ide> }, clientPositionForCharacter(component, 1, 4))) <ide> expect(editor.getSelectedScreenRange()).toEqual([[1, 4], [2, 18]]) <ide> <del> component.didMouseDownOnLines(Object.assign({ <add> component.didMouseDownOnContent(Object.assign({ <ide> detail: 1, <ide> shiftKey: true <ide> }, clientPositionForCharacter(component, 4, 4)))
1
Python
Python
emit error on duplicated dag id
09674537cb12f46ca53054314aea4d8eec9c2e43
<ide><path>airflow/example_dags/tutorial_taskflow_api_etl_virtualenv.py <ide> <ide> # [START instantiate_dag] <ide> @dag(default_args=default_args, schedule_interval=None, start_date=days_ago(2), tags=['example']) <del>def tutorial_taskflow_api_etl(): <add>def tutorial_taskflow_api_etl_virtualenv(): <ide> """ <ide> ### TaskFlow API Tutorial Documentation <ide> This is a simple ETL data pipeline example which demonstrates the use of <ide> def load(total_order_value: float): <ide> <ide> <ide> # [START dag_invocation] <del>tutorial_etl_dag = tutorial_taskflow_api_etl() <add>tutorial_etl_dag = tutorial_taskflow_api_etl_virtualenv() <ide> # [END dag_invocation] <ide> <ide> # [END tutorial] <ide><path>airflow/exceptions.py <ide> class AirflowDagCycleException(AirflowException): <ide> """Raise when there is a cycle in Dag definition""" <ide> <ide> <add>class AirflowDagDuplicatedIdException(AirflowException): <add> """Raise when a Dag's ID is already used by another Dag""" <add> <add> def __init__(self, dag_id: str, incoming: str, existing: str) -> None: <add> super().__init__(dag_id, incoming, existing) <add> self.dag_id = dag_id <add> self.incoming = incoming <add> self.existing = existing <add> <add> def __str__(self) -> str: <add> return f"Ignoring DAG {self.dag_id} from {self.incoming} - also found in {self.existing}" <add> <add> <ide> class AirflowClusterPolicyViolation(AirflowException): <ide> """Raise when there is a violation of a Cluster Policy in Dag definition""" <ide> <ide><path>airflow/models/dagbag.py <ide> <ide> from airflow import settings <ide> from airflow.configuration import conf <del>from airflow.exceptions import AirflowClusterPolicyViolation, AirflowDagCycleException, SerializedDagNotFound <add>from airflow.exceptions import ( <add> AirflowClusterPolicyViolation, <add> AirflowDagCycleException, <add> AirflowDagDuplicatedIdException, <add> SerializedDagNotFound, <add>) <ide> from airflow.stats import Stats <ide> from airflow.utils import timezone <ide> from airflow.utils.dag_cycle_tester import test_cycle <ide> def get_dag(self, dag_id, session: Session = None): <ide> # If the dag corresponding to root_dag_id is absent or expired <ide> is_missing = root_dag_id not in self.dags <ide> is_expired = orm_dag.last_expired and dag and dag.last_loaded < orm_dag.last_expired <add> if is_expired: <add> # Remove associated dags so we can re-add them. <add> self.dags = { <add> key: dag <add> for key, dag in self.dags.items() <add> if root_dag_id != key and not (dag.is_subdag and root_dag_id == dag.parent_dag.dag_id) <add> } <ide> if is_missing or is_expired: <del> # Reprocess source file <add> # Reprocess source file. <ide> found_dags = self.process_file( <ide> filepath=correct_maybe_zipped(orm_dag.fileloc), only_if_updated=False <ide> ) <ide> def _process_modules(self, filepath, mods, file_last_changed_on_disk): <ide> self.log.exception("Failed to bag_dag: %s", dag.full_filepath) <ide> self.import_errors[dag.full_filepath] = f"Invalid Cron expression: {cron_e}" <ide> self.file_last_changed[dag.full_filepath] = file_last_changed_on_disk <del> except (AirflowDagCycleException, AirflowClusterPolicyViolation) as exception: <add> except ( <add> AirflowDagCycleException, <add> AirflowDagDuplicatedIdException, <add> AirflowClusterPolicyViolation, <add> ) as exception: <ide> self.log.exception("Failed to bag_dag: %s", dag.full_filepath) <ide> self.import_errors[dag.full_filepath] = str(exception) <ide> self.file_last_changed[dag.full_filepath] = file_last_changed_on_disk <ide> def _process_modules(self, filepath, mods, file_last_changed_on_disk): <ide> def bag_dag(self, dag, root_dag): <ide> """ <ide> Adds the DAG into the bag, recurses into sub dags. <del> Throws AirflowDagCycleException if a cycle is detected in this dag or its subdags <add> <add> :raises: AirflowDagCycleException if a cycle is detected in this dag or its subdags. <add> :raises: AirflowDagDuplicatedIdException if this dag or its subdags already exists in the bag. <add> """ <add> self._bag_dag(dag=dag, root_dag=root_dag, recursive=True) <add> <add> def _bag_dag(self, *, dag, root_dag, recursive): <add> """Actual implementation of bagging a dag. <add> <add> The only purpose of this is to avoid exposing ``recursive`` in ``bag_dag()``, <add> intended to only be used by the ``_bag_dag()`` implementation. <ide> """ <ide> test_cycle(dag) # throws if a task cycle is found <ide> <ide> def bag_dag(self, dag, root_dag): <ide> subdags = dag.subdags <ide> <ide> try: <del> for subdag in subdags: <del> subdag.full_filepath = dag.full_filepath <del> subdag.parent_dag = dag <del> subdag.is_subdag = True <del> self.bag_dag(dag=subdag, root_dag=root_dag) <del> <add> # DAG.subdags automatically performs DFS search, so we don't recurse <add> # into further _bag_dag() calls. <add> if recursive: <add> for subdag in subdags: <add> subdag.full_filepath = dag.full_filepath <add> subdag.parent_dag = dag <add> subdag.is_subdag = True <add> self._bag_dag(dag=subdag, root_dag=root_dag, recursive=False) <add> <add> prev_dag = self.dags.get(dag.dag_id) <add> if prev_dag and prev_dag.full_filepath != dag.full_filepath: <add> raise AirflowDagDuplicatedIdException( <add> dag_id=dag.dag_id, <add> incoming=dag.full_filepath, <add> existing=self.dags[dag.dag_id].full_filepath, <add> ) <ide> self.dags[dag.dag_id] = dag <ide> self.log.debug('Loaded DAG %s', dag) <del> except AirflowDagCycleException as cycle_exception: <add> except (AirflowDagCycleException, AirflowDagDuplicatedIdException): <ide> # There was an error in bagging the dag. Remove it from the list of dags <ide> self.log.exception('Exception bagging dag: %s', dag.dag_id) <ide> # Only necessary at the root level since DAG.subdags automatically <ide> # performs DFS to search through all subdags <del> if dag == root_dag: <add> if recursive: <ide> for subdag in subdags: <ide> if subdag.dag_id in self.dags: <ide> del self.dags[subdag.dag_id] <del> raise cycle_exception <add> raise <ide> <ide> def collect_dags( <ide> self, <ide><path>airflow/providers/papermill/example_dags/example_papermill.py <ide> def check_notebook(inlets, execution_date): <ide> <ide> <ide> with DAG( <del> dag_id='example_papermill_operator', <add> dag_id='example_papermill_operator_2', <ide> default_args=default_args, <ide> schedule_interval='0 0 * * *', <ide> start_date=days_ago(2), <ide><path>tests/api_connexion/endpoints/test_log_endpoint.py <ide> def _prepare_db(self): <ide> dagbag = self.app.dag_bag # pylint: disable=no-member <ide> dag = DAG(self.DAG_ID, start_date=timezone.parse(self.default_time)) <ide> dag.sync_to_db() <add> dagbag.dags.pop(self.DAG_ID, None) <ide> dagbag.bag_dag(dag=dag, root_dag=dag) <ide> with create_session() as session: <ide> self.ti = TaskInstance( <ide> def test_get_logs_of_removed_task(self, session): <ide> # Recreate DAG without tasks <ide> dagbag = self.app.dag_bag # pylint: disable=no-member <ide> dag = DAG(self.DAG_ID, start_date=timezone.parse(self.default_time)) <add> del dagbag.dags[self.DAG_ID] <ide> dagbag.bag_dag(dag=dag, root_dag=dag) <ide> <ide> key = self.app.config["SECRET_KEY"] <ide><path>tests/core/test_impersonation_tests.py <ide> def create_user(): <ide> <ide> @pytest.mark.quarantined <ide> class TestImpersonation(unittest.TestCase): <del> def setUp(self): <del> check_original_docker_image() <del> grant_permissions() <del> add_default_pool_if_not_exists() <del> self.dagbag = models.DagBag( <add> @classmethod <add> def setUpClass(cls): <add> cls.dagbag = models.DagBag( <ide> dag_folder=TEST_DAG_FOLDER, <ide> include_examples=False, <ide> ) <ide> logger.info('Loaded DAGS:') <del> logger.info(self.dagbag.dagbag_report()) <add> logger.info(cls.dagbag.dagbag_report()) <ide> <add> def setUp(self): <add> check_original_docker_image() <add> grant_permissions() <add> add_default_pool_if_not_exists() <ide> create_user() <ide> <ide> def tearDown(self): <ide><path>tests/dags/test_backfill_pooled_tasks.py <del># <del># Licensed to the Apache Software Foundation (ASF) under one <del># or more contributor license agreements. See the NOTICE file <del># distributed with this work for additional information <del># regarding copyright ownership. The ASF licenses this file <del># to you under the Apache License, Version 2.0 (the <del># "License"); you may not use this file except in compliance <del># with the License. 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, <del># software distributed under the License is distributed on an <del># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <del># KIND, either express or implied. See the License for the <del># specific language governing permissions and limitations <del># under the License. <del> <del> <del>""" <del>DAG designed to test what happens when a DAG with pooled tasks is run <del>by a BackfillJob. <del>Addresses issue #1225. <del>""" <del>from datetime import datetime <del> <del>from airflow.models import DAG <del>from airflow.operators.dummy import DummyOperator <del> <del>dag = DAG(dag_id='test_backfill_pooled_task_dag') <del>task = DummyOperator( <del> task_id='test_backfill_pooled_task', <del> dag=dag, <del> pool='test_backfill_pooled_task_pool', <del> owner='airflow', <del> start_date=datetime(2016, 2, 1), <del>) <ide><path>tests/dags/test_dag_with_no_tags.py <ide> "start_date": DEFAULT_DATE, <ide> } <ide> <del>with DAG(dag_id="test_only_dummy_tasks", default_args=default_args, schedule_interval='@once') as dag: <add>with DAG(dag_id="test_dag_with_no_tags", default_args=default_args, schedule_interval='@once') as dag: <ide> task_a = DummyOperator(task_id="test_task_a") <ide><path>tests/models/test_dagbag.py <ide> def test_process_file_that_contains_multi_bytes_char(self): <ide> dagbag = models.DagBag(dag_folder=self.empty_dir, include_examples=False) <ide> assert [] == dagbag.process_file(f.name) <ide> <add> def test_process_file_duplicated_dag_id(self): <add> """Loading a DAG with ID that already existed in a DAG bag should result in an import error.""" <add> dagbag = models.DagBag(dag_folder=self.empty_dir, include_examples=False) <add> <add> def create_dag(): <add> from airflow.decorators import dag <add> <add> @dag(default_args={'owner': 'owner1'}) <add> def my_flow(): <add> pass <add> <add> my_dag = my_flow() # noqa # pylint: disable=unused-variable <add> <add> source_lines = [line[12:] for line in inspect.getsource(create_dag).splitlines(keepends=True)[1:]] <add> with NamedTemporaryFile("w+", encoding="utf8") as tf_1, NamedTemporaryFile( <add> "w+", encoding="utf8" <add> ) as tf_2: <add> tf_1.writelines(source_lines) <add> tf_2.writelines(source_lines) <add> tf_1.flush() <add> tf_2.flush() <add> <add> found_1 = dagbag.process_file(tf_1.name) <add> assert len(found_1) == 1 and found_1[0].dag_id == "my_flow" <add> assert dagbag.import_errors == {} <add> dags_in_bag = dagbag.dags <add> <add> found_2 = dagbag.process_file(tf_2.name) <add> assert len(found_2) == 0 <add> assert dagbag.import_errors[tf_2.name].startswith("Ignoring DAG") <add> assert dagbag.dags == dags_in_bag # Should not change. <add> <ide> def test_zip_skip_log(self): <ide> """ <ide> test the loading of a DAG from within a zip file that skips another file because <ide><path>tests/www/test_views.py <ide> def setUp(self): <ide> self.login() <ide> <ide> dagbag = self.app.dag_bag <add> dagbag.dags.pop(self.DAG_ID, None) <add> dagbag.dags.pop(self.DAG_ID_REMOVED, None) <ide> dag = DAG(self.DAG_ID, start_date=self.DEFAULT_DATE) <ide> dag_removed = DAG(self.DAG_ID_REMOVED, start_date=self.DEFAULT_DATE) <ide> dagbag.bag_dag(dag=dag, root_dag=dag) <ide> def __init__(self, test, endpoint): <ide> <ide> def setup(self): <ide> dagbag = self.test.app.dag_bag <add> dagbag.dags.pop(self.DAG_ID, None) <ide> dag = DAG(self.DAG_ID, start_date=self.DEFAULT_DATE) <ide> dagbag.bag_dag(dag=dag, root_dag=dag) <ide> for run_data in self.RUNS_DATA:
10
PHP
PHP
fix invalid change by phpcs fixer
b5ea41d2c7fd49534ff53498aa92f019dafb7f85
<ide><path>src/Validation/ValidatorAwareTrait.php <ide> protected function createValidator(string $name): Validator <ide> throw new RuntimeException($message); <ide> } <ide> <del> $validator = new $this()->_validatorClass(); <add> // @codingStandardsIgnoreLine <add> $validator = new $this->_validatorClass(); <ide> $validator = $this->$method($validator); <ide> if ($this instanceof EventDispatcherInterface) { <ide> $event = defined(self::class . '::BUILD_VALIDATOR_EVENT') ? self::BUILD_VALIDATOR_EVENT : 'Model.buildValidator';
1
Text
Text
remove duplicate changelog entry
4a9298223813bf32f90082c53999cb04e7d1a49e
<ide><path>CHANGELOG.md <ide> * [BUGFIX] Make errors thrown by Ember use `Ember.Error` consistently. <ide> * [BUGFIX] Ensure controllers instantiated by the `{{render}}` helper are properly torn down. <ide> * [BUGFIX] sync back burner: workaround IE's issue with try/finally without Catch. Also no longer force deoptimization of the run loop queue flush. <del>* [BREAKING BUGFIX] An empty array are treated as falsy value in `bind-attr` to be in consistent with `if` helper. Breaking for apps that relies on the previous behaviour which treats an empty array as truthy value in `bind-attr`. <ide> * [BUGFIX] Ember.onerror now uses Backburner's error handler. <ide> * [BUGFIX] Do not rely on Array.prototype.map for logging version. <ide> * [BUGFIX] RSVP errors go to Ember.onerror if present.
1
PHP
PHP
change method order
5be7f261e8a2f03d6fa6be99eb79e261a880421d
<ide><path>src/Illuminate/Cache/TaggedCache.php <ide> public function flush() <ide> $this->tags->reset(); <ide> } <ide> <add> /** <add> * {@inheritdoc} <add> */ <add> protected function itemKey($key) <add> { <add> return $this->taggedItemKey($key); <add> } <add> <ide> /** <ide> * Get a fully qualified key for a tagged item. <ide> * <ide> public function taggedItemKey($key) <ide> { <ide> return sha1($this->tags->getNamespace()).':'.$key; <ide> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> protected function itemKey($key) <del> { <del> return $this->taggedItemKey($key); <del> } <ide> }
1
Go
Go
fix comparison against wrong constant
b92d91d6a1e1e29a24e0a9cbf78b2440a8258ab4
<ide><path>libnetwork/networkdb/delegate.go <ide> func (nDB *NetworkDB) handleTableEvent(tEvent *TableEvent) bool { <ide> // If it is a delete event and we did not have a state for it, don't propagate to the application <ide> // If the residual reapTime is lower or equal to 1/6 of the total reapTime don't bother broadcasting it around <ide> // most likely the cluster is already aware of it, if not who will sync with this node will catch the state too. <del> return e.reapTime > reapPeriod/6 <add> // This also avoids that deletion of entries close to their garbage collection ends up circuling around forever <add> return e.reapTime > reapEntryInterval/6 <ide> } <ide> <ide> var op opType
1
PHP
PHP
add additional tests to config repository
d1208ecab470b80389f940d2e46c7879c82ccabb
<ide><path>tests/Config/RepositoryTest.php <ide> class RepositoryTest extends TestCase <ide> */ <ide> protected $config; <ide> <del> public function setUp() <add> protected function setUp() <ide> { <ide> $this->repository = new Repository($this->config = [ <ide> 'foo' => 'bar', <ide> public function testPush() <ide> $this->repository->push('array', 'xxx'); <ide> $this->assertSame('xxx', $this->repository->get('array.2')); <ide> } <add> <add> public function testAll() <add> { <add> $this->assertSame($this->config, $this->repository->all()); <add> } <add> <add> public function testOffsetUnset() <add> { <add> $this->assertArrayHasKey('associate', $this->repository->all()); <add> $this->assertSame($this->config['associate'], $this->repository->get('associate')); <add> <add> unset($this->repository['associate']); <add> <add> $this->assertArrayHasKey('associate', $this->repository->all()); <add> $this->assertNull($this->repository->get('associate')); <add> } <ide> }
1
Python
Python
add pytorch model for new german distilbert model
22333945fbd1f5eff8cfb664ac6f63363e6b72d4
<ide><path>transformers/modeling_distilbert.py <ide> <ide> DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP = { <ide> 'distilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-pytorch_model.bin", <del> 'distilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-distilled-squad-pytorch_model.bin" <add> 'distilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-distilled-squad-pytorch_model.bin", <add> 'distilbert-base-german-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-german-cased-pytorch_model.bin" <ide> } <ide> <ide>
1
Ruby
Ruby
remove useless method
64df657026010a6c0500a17f64cd39a9996dc58e
<ide><path>actionpack/lib/action_controller/metal/live.rb <ide> def build_buffer(response, body) <ide> body.each { |part| buf.write part } <ide> buf <ide> end <del> <del> def handle_conditional_get! <del> super unless committed? <del> end <ide> end <ide> <ide> def process(name)
1
Ruby
Ruby
add missing verbose puts
20eeb5aca03915bc071a9f42b0bb3fc188fc1818
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def merge(args:) <ide> <ide> all_bottle_hash = { formula_name => all_bottle_formula_hash } <ide> <del> "Copying #{local_filename} to #{all_local_filename}" if args.verbose? <add> puts "Copying #{local_filename} to #{all_local_filename}" if args.verbose? <ide> FileUtils.cp local_filename, all_local_filename <ide> <ide> all_local_json_path = Pathname(all_local_json_filename) <ide> all_local_json_path.unlink if all_local_json_path.exist? <ide> all_local_json_path.write(JSON.pretty_generate(all_bottle_hash)) <ide> end <ide> <del> "Removing #{local_filename} and #{local_json_filename}" if args.verbose? <add> puts "Removing #{local_filename} and #{local_json_filename}" if args.verbose? <ide> FileUtils.rm_f [local_filename, local_json_filename] <ide> end <ide> end
1
Ruby
Ruby
add available languages to cask info command
92311901c9d85e0e43147386535118b66ca718cd
<ide><path>Library/Homebrew/cask/lib/hbc/cli/info.rb <ide> def self.info(cask) <ide> installation_info(cask) <ide> repo_info(cask) <ide> name_info(cask) <add> language_info(cask) <ide> artifact_info(cask) <ide> Installer.print_caveats(cask) <ide> end <ide> def self.name_info(cask) <ide> puts cask.name.empty? ? Formatter.error("None") : cask.name <ide> end <ide> <add> def self.language_info(cask) <add> return if cask.languages.empty? <add> <add> ohai "Languages" <add> puts cask.languages.join(", ") <add> end <add> <ide> def self.repo_info(cask) <ide> user, repo, token = QualifiedToken.parse(Hbc.all_tokens.detect { |t| t.split("/").last == cask.token }) <ide> <ide><path>Library/Homebrew/cask/lib/hbc/dsl.rb <ide> class DSL <ide> :gpg, <ide> :homepage, <ide> :language, <add> :languages, <ide> :name, <ide> :sha256, <ide> :staged_path, <ide> def language_eval <ide> @language = @language_blocks.default.call <ide> end <ide> <add> def languages <add> return [] if @language_blocks.nil? <add> <add> @language_blocks.keys.flatten <add> end <add> <ide> def url(*args, &block) <ide> set_unique_stanza(:url, args.empty? && !block_given?) do <ide> begin <ide><path>Library/Homebrew/test/cask/cli/info_spec.rb <ide> EOS <ide> end <ide> <add> it "should print languages if the Cask provided any" do <add> expect { <add> Hbc::CLI::Info.run("with-languages") <add> }.to output(<<-EOS.undent).to_stdout <add> with-languages: 1.2.3 <add> http://example.com/local-caffeine <add> Not installed <add> From: https://github.com/caskroom/homebrew-spec/blob/master/Casks/with-languages.rb <add> ==> Name <add> None <add> ==> Languages <add> zh, en-US <add> ==> Artifacts <add> Caffeine.app (App) <add> EOS <add> end <add> <add> it 'should not print "Languages" section divider if the languages block has no output' do <add> expect { <add> Hbc::CLI::Info.run("with-conditional-languages") <add> }.to output(<<-EOS.undent).to_stdout <add> with-conditional-languages: 1.2.3 <add> http://example.com/local-caffeine <add> Not installed <add> From: https://github.com/caskroom/homebrew-spec/blob/master/Casks/with-conditional-languages.rb <add> ==> Name <add> None <add> ==> Artifacts <add> Caffeine.app (App) <add> EOS <add> end <add> <ide> describe "when no Cask is specified" do <ide> it "raises an exception" do <ide> expect { <ide><path>Library/Homebrew/test/cask/dsl_spec.rb <ide> expect(cask.call.sha256).to eq("xyz789") <ide> expect(cask.call.url.to_s).to eq("https://example.org/en-US.zip") <ide> end <add> <add> it "returns empty array if no languages specified" do <add> cask = lambda do <add> Hbc::Cask.new("cask-with-apps") do <add> url "https://example.org/file.zip" <add> end <add> end <add> <add> expect(cask.call.languages).to be_empty <add> end <add> <add> it "returns an array of available languages" do <add> cask = lambda do <add> Hbc::Cask.new("cask-with-apps") do <add> language "zh" do <add> sha256 "abc123" <add> "zh-CN" <add> end <add> <add> language "en-US", default: true do <add> sha256 "xyz789" <add> "en-US" <add> end <add> <add> url "https://example.org/file.zip" <add> end <add> end <add> <add> expect(cask.call.languages).to eq(["zh", "en-US"]) <add> end <ide> end <ide> <ide> describe "app stanza" do <ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-conditional-languages.rb <add>cask 'with-conditional-languages' do <add> version '1.2.3' <add> sha256 '67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94' <add> <add> url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip" <add> homepage 'http://example.com/local-caffeine' <add> <add> app 'Caffeine.app' <add>end <ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-languages.rb <add>cask 'with-languages' do <add> version '1.2.3' <add> <add> language "zh" do <add> sha256 "abc123" <add> "zh-CN" <add> end <add> <add> language "en-US", default: true do <add> sha256 "xyz789" <add> "en-US" <add> end <add> <add> url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip" <add> homepage 'http://example.com/local-caffeine' <add> <add> app 'Caffeine.app' <add>end
6
Python
Python
update linode tests for new create_node api
d9efb0b3cc51a8c84f209da2c48ce93b26a68a73
<ide><path>test/test_linode.py <ide> # <ide> <ide> from libcloud.drivers.linode import LinodeNodeDriver <del>from libcloud.base import Node <add>from libcloud.base import Node, NodeOptions, NodeAuthPassword <ide> from test import MockHttp, TestCaseMixin <ide> <ide> import unittest <ide> def test_destroy_node(self): <ide> <ide> def test_create_node(self): <ide> # Will exception on failure <del> size = self.driver.list_sizes()[0] <del> distro = self.driver.list_images()[6] <del> self.driver.linode_set_datacenter(2) <del> node = self.driver.create_node("Test", distro, size, root="test123") <add> no = NodeOptions(location=self.driver.list_locations()[0], <add> size=self.driver.list_sizes()[0], <add> image=self.driver.list_images()[6], <add> auth=NodeAuthPassword("test123"), driver=self.driver) <add> node = self.driver.create_node("Test", no) <ide> <ide> def test_list_sizes(self): <ide> sizes = self.driver.list_sizes() <ide> def test_list_images(self): <ide> <ide> def test_create_node_response(self): <ide> # should return a node object <del> size = self.driver.list_sizes()[0] <del> image = self.driver.list_images()[0] <del> kwargs = {'root': 'foobar'} <del> node = self.driver.create_node('node-name',image, size, **kwargs) <add> no = NodeOptions(location=self.driver.list_locations()[0], <add> size=self.driver.list_sizes()[0], <add> image=self.driver.list_images()[0], <add> auth=NodeAuthPassword("foobar"), driver=self.driver) <add> node = self.driver.create_node("node-name", no) <ide> self.assertTrue(isinstance(node, Node)) <ide> <ide>
1
Python
Python
add day of month tokenizer exceptions for danish
6aa241bcec8c9bacac5c9a793fc8a255a291cac5
<ide><path>spacy/lang/da/tokenizer_exceptions.py <ide> "øv.", "øvr.", "årg.", "årh.", ""]: <ide> _exc[orth] = [{ORTH: orth}] <ide> <add># Dates <add>for h in range(1, 31 + 1): <add> for period in ["."]: <add> _exc["%d%s" % (h, period)] = [ <add> {ORTH: "%d." % h}] <add> <ide> _custom_base_exc = { <ide> "i.": [ <ide> {ORTH: "i", LEMMA: "i", NORM: "i"}, <ide><path>spacy/tests/lang/da/test_exceptions.py <ide> def test_da_tokenizer_handles_ambiguous_abbr(da_tokenizer, text): <ide> tokens = da_tokenizer(text) <ide> assert len(tokens) == 2 <ide> <add>@pytest.mark.parametrize('text', ["1.", "10.", "31."]) <add>def test_da_tokenizer_handles_dates(da_tokenizer, text): <add> tokens = da_tokenizer(text) <add> assert len(tokens) == 1 <add> <ide> def test_da_tokenizer_handles_exc_in_text(da_tokenizer): <ide> text = "Det er bl.a. ikke meningen" <ide> tokens = da_tokenizer(text)
2
Javascript
Javascript
add app to showcase - rnf beacon toolkit
4c3c15fd8978f37c24237033e7e4db3a254e131f
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://itunes.apple.com/us/app/repairshopr-payments-lite/id1023262888?mt=8', <ide> author: 'Jed Tiotuico', <ide> }, <add> { <add> name: 'RNF Beacon Toolkit', <add> icon: 'http://a1.mzstatic.com/eu/r30/Purple20/v4/99/79/5e/99795e25-e1f7-28bc-efcf-fd3c87f02f4e/icon175x175.png', <add> linkAppStore: 'https://itunes.apple.com/gb/app/rnf-beacon-toolkit/id1110757307', <add> author: 'RNF Digital', <add> }, <ide> { <ide> name: 'Rota Employer - Hire On Demand', <ide> link: 'https://itunes.apple.com/us/app/rota-employer-hire-on-demand/id1042270305?mt=8',
1