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 | add node about concurrency on /system/df endpoint | 8e0d43dda7724d8f7e33022789622bb452c15a9a | <ide><path>docs/api/version-history.md
<ide> keywords: "API, Docker, rcli, REST, documentation"
<ide> computes and returns data only for the specified object type.
<ide> The parameter can be specified multiple times to select several object types.
<ide> Supported values are: `container`, `image`, `volume`, `build-cache`.
<add>* `GET /system/df` can now be used concurrently. If a request is made while a
<add> previous request is still being processed, the request will receive the result
<add> of the already running calculation, once completed. Previously, an error
<add> (`a disk usage operation is already running`) would be returned in this
<add> situation. This change is not versioned, and affects all API versions if the
<add> daemon has this patch.
<ide>
<ide> ## v1.41 API changes
<ide> | 1 |
PHP | PHP | fix incorrect __construct params for mock object | 89959afa63b108c5457a9f32fda4536cf6dea958 | <ide><path>lib/Cake/Test/Case/Console/ShellDispatcherTest.php
<ide> public function testGetShell() {
<ide> */
<ide> public function testDispatchShellWithMain() {
<ide> $Dispatcher = new TestShellDispatcher();
<del> $Mock = $this->getMock('Shell', array(), array(&$Dispatcher), 'MockWithMainShell');
<add> $Mock = $this->getMock('Shell', array(), array(), 'MockWithMainShell');
<ide>
<ide> $Mock->expects($this->once())->method('initialize');
<ide> $Mock->expects($this->once())->method('loadTasks');
<ide> public function testDispatchShellWithMain() {
<ide> */
<ide> public function testDispatchShellWithoutMain() {
<ide> $Dispatcher = new TestShellDispatcher();
<del> $Shell = $this->getMock('Shell', array(), array(&$Dispatcher), 'MockWithoutMainShell');
<add> $Shell = $this->getMock('Shell', array(), array(), 'MockWithoutMainShell');
<ide>
<del> $Shell = new MockWithoutMainShell($Dispatcher);
<add> $Shell = new MockWithoutMainShell();
<ide> $this->mockObjects[] = $Shell;
<ide>
<ide> $Shell->expects($this->once())->method('initialize'); | 1 |
Python | Python | add stack to numpy backend | 29e740e0965be5f460f67692a284a9a2deb6bb04 | <ide><path>keras/backend/numpy_backend.py
<ide> def _remove_blanks(inds, num_classes):
<ide> return inds[inds < (num_classes - 1)]
<ide>
<ide>
<add>def stack(x, axis=0):
<add> return np.stack(x, axis=axis)
<add>
<add>
<ide> square = np.square
<ide> abs = np.abs
<ide> exp = np.exp
<ide><path>keras/backend/tensorflow_backend.py
<ide> def stack(x, axis=0):
<ide>
<ide> # Returns
<ide> A tensor.
<add>
<add> {{np_implementation}}
<ide> """
<ide> return tf.stack(x, axis=axis)
<ide>
<ide><path>tests/keras/backend/backend_test.py
<ide> def test_sparse_concat(self):
<ide> assert k_s_d.shape == k_d.shape
<ide> assert_allclose(k_s_d, k_d, atol=1e-05)
<ide>
<add> def test_stack(self):
<add> tensor_list = [np.random.randn(5, 4, 6, 10) for _ in range(5)]
<add> stack_axis = 3
<add> results = []
<add> if WITH_NP[0] == KC:
<add> check_two_tensor_operation('stack', (5, 4, 6, 10),
<add> (5, 4, 6, 10), WITH_NP,
<add> axis=stack_axis, concat_args=True)
<add> else:
<add> for k in WITH_NP:
<add> tensor_list_var = [k.variable(tensor) for tensor in tensor_list]
<add> out = k.eval(k.stack(tensor_list_var, axis=stack_axis))
<add> results.append(out)
<add>
<add> assert_list_pairwise(results)
<add>
<ide> @pytest.mark.skipif(K.backend() == 'cntk', reason='Not supported.')
<ide> def test_map(self):
<ide> x = np.random.rand(10, 3).astype(np.float32) | 3 |
Text | Text | add info on becoming a team member | f271e0ce481ead2a7692c984c141f5bb4d697429 | <ide><path>CONTRIBUTING.md
<ide> We use Grunt for managing the build. Here are some useful Grunt tasks:
<ide> those in Pull Requests)
<ide> * `grunt transpile:fr,ru` Build custom locale bundles `moment-with-locales.custom.js` and `locales.custom.js` inside `build/umd/min` containing just French and Russian.
<ide> * `grunt size` Print size statistics.
<add>
<add>Becoming a moment team member
<add>=============================
<add>
<add>Moment's team members have extra powers and responsibilities. If you want to
<add>become one -- be active in our repositories by answering issues, reviewing PRs,
<add>discussing changes, submitting PRs for open bugs. Any help on
<add>[moment/moment](https://github.com/moment/moment),
<add>[moment/momentjs.com](https://github.com/moment/momentjs.com),
<add>[moment/moment-timezone](https://github.com/moment/moment-timezone) will be
<add>noticed.
<add>
<add>Once you've proven to be trustworthy, submit your request to the
<add>[gitter chat](https://gitter.im/moment/moment), and it will be reviewed by the
<add>existing team.
<add>
<add>Once you become a member:
<add>* you can tell your friends
<add>* you can close issues submitted by others
<add>
<add>But also:
<add>* be active in the repositories
<add>* pick up work nobody else wants to
<add>* attent a montly meeting
<add>* participate in the internal slack group | 1 |
Ruby | Ruby | unlink the lock file after unlocking it | 37dcbbaf65e0faf918069f1689ba332e58f2e6ac | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def fetch
<ide> end
<ide> ensure
<ide> download_lock&.unlock
<add> download_lock&.path&.unlink
<ide> end
<ide>
<ide> def clear_cache | 1 |
Mixed | Text | update discuss links to github discussions links | 8a6581b5c57dee2408ec5ce3bf9c2aa8f1f054b2 | <ide><path>CONTRIBUTING.md
<ide> This project and everyone participating in it is governed by the [Atom Code of C
<ide>
<ide> We have an official message board with a detailed FAQ and where the community chimes in with helpful advice if you have questions.
<ide>
<del>* [Discuss, the official Atom and Electron message board](https://discuss.atom.io)
<del>* [Atom FAQ](https://discuss.atom.io/c/faq)
<del>
<del>If chat is more your speed, you can join the Atom and Electron Slack team:
<del>
<del>* [Join the Atom and Electron Slack Team](https://atom-slack.herokuapp.com/)
<del> * Even though Slack is a chat service, sometimes it takes several hours for community members to respond — please be patient!
<del> * Use the `#atom` channel for general questions or discussion about Atom
<del> * Use the `#electron` channel for questions about Electron
<del> * Use the `#packages` channel for questions or discussion about writing or contributing to Atom packages (both core and community)
<del> * Use the `#ui` channel for questions and discussion about Atom UI and themes
<del> * There are many other channels available, check the channel list
<add>* [Github Discussions, the official Atom](https://github.com/atom/atom/discussions)
<add>* [Atom FAQ](https://github.com/atom/atom/discussions)
<ide>
<ide> ## What should I know before I get started?
<ide>
<ide> Here's a list of the big ones:
<ide>
<ide> There are many more, but this list should be a good starting point. For more information on how to work with Atom's official packages, see [Contributing to Atom Packages][contributing-to-official-atom-packages].
<ide>
<del>Also, because Atom is so extensible, it's possible that a feature you've become accustomed to in Atom or an issue you're encountering isn't coming from a bundled package at all, but rather a [community package](https://atom.io/packages) you've installed. Each community package has its own repository too, the [Atom FAQ](https://discuss.atom.io/c/faq) has instructions on how to [contact the maintainers of any Atom community package or theme.](https://discuss.atom.io/t/i-have-a-question-about-a-specific-atom-community-package-where-is-the-best-place-to-ask-it/25581)
<add>Also, because Atom is so extensible, it's possible that a feature you've become accustomed to in Atom or an issue you're encountering isn't coming from a bundled package at all, but rather a [community package](https://atom.io/packages) you've installed. Each community package has its own repository too.
<ide>
<ide> #### Package Conventions
<ide>
<ide> There are a few conventions that have developed over time around packages:
<ide>
<ide> ### Design Decisions
<ide>
<del>When we make a significant decision in how we maintain the project and what we can or cannot support, we will document it in the [atom/design-decisions repository](https://github.com/atom/design-decisions). If you have a question around how we do things, check to see if it is documented there. If it is *not* documented there, please open a new topic on [Discuss, the official Atom message board](https://discuss.atom.io) and ask your question.
<add>When we make a significant decision in how we maintain the project and what we can or cannot support, we will document it in the [atom/design-decisions repository](https://github.com/atom/design-decisions). If you have a question around how we do things, check to see if it is documented there. If it is *not* documented there, please open a new topic on [Github Discussions, the official Atom message board](https://github.com/atom/atom/discussions) and ask your question.
<ide>
<ide> ## How Can I Contribute?
<ide>
<ide> Before creating bug reports, please check [this list](#before-submitting-a-bug-r
<ide> #### Before Submitting A Bug Report
<ide>
<ide> * **Check the [debugging guide](https://flight-manual.atom.io/hacking-atom/sections/debugging/).** You might be able to find the cause of the problem and fix things yourself. Most importantly, check if you can reproduce the problem [in the latest version of Atom](https://flight-manual.atom.io/hacking-atom/sections/debugging/#update-to-the-latest-version), if the problem happens when you run Atom in [safe mode](https://flight-manual.atom.io/hacking-atom/sections/debugging/#check-if-the-problem-shows-up-in-safe-mode), and if you can get the desired behavior by changing [Atom's or packages' config settings](https://flight-manual.atom.io/hacking-atom/sections/debugging/#check-atom-and-package-settings).
<del>* **Check the [FAQs on the forum](https://discuss.atom.io/c/faq)** for a list of common questions and problems.
<add>* **Check the [discussions](https://github.com/atom/atom/discussions)** for a list of common questions and problems.
<ide> * **Determine [which repository the problem should be reported in](#atom-and-packages)**.
<ide> * **Perform a [cursory search](https://github.com/search?q=+is%3Aissue+user%3Aatom)** to see if the problem has already been reported. If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one.
<ide>
<ide><path>README.md
<ide> Atom is a hackable text editor for the 21st century, built on [Electron](https:/
<ide>
<ide> 
<ide>
<del>Visit [atom.io](https://atom.io) to learn more or visit the [Atom forum](https://discuss.atom.io).
<add>Visit [atom.io](https://atom.io) to learn more or visit the [Atom forum](https://github.com/atom/atom/discussions).
<ide>
<ide> Follow [@AtomEditor](https://twitter.com/atomeditor) on Twitter for important
<ide> announcements.
<ide><path>SUPPORT.md
<ide> If you're looking for support for Atom there are a lot of options, check out:
<ide>
<ide> * User Documentation — [The Atom Flight Manual](https://flight-manual.atom.io)
<ide> * Developer Documentation — [Atom API Documentation](https://atom.io/docs/api/latest)
<del>* FAQ — [The Atom FAQ on Discuss](https://discuss.atom.io/c/faq)
<del>* Message Board — [Discuss, the official Atom and Electron message board](https://discuss.atom.io)
<del>* Chat — [Join the Atom Slack team](https://atom-slack.herokuapp.com/)
<add>* Message Board — [Github Discussions, the official Atom message board](https://github.com/atom/atom/discussions)
<ide>
<del>On Discuss and in the Atom Slack team, there are a bunch of helpful community members that should be willing to point you in the right direction.
<add>On Atoms Github Discussions board, there are a bunch of helpful community members that should be willing to point you in the right direction.
<ide><path>packages/dalek/README.md
<ide> When people install core Atom packages as if they are community packages, it can
<ide>
<ide> ## I have more questions. Where can I ask them?
<ide>
<del>Please feel free to ask on [the official Atom message board](https://discuss.atom.io/c/support).
<add>Please feel free to ask on [the official Atom message board](https://github.com/atom/atom/discussions).
<ide><path>packages/welcome/lib/welcome-view.js
<ide> export default class WelcomeView {
<ide> </li>
<ide> <li>
<ide> The Atom forum at{' '}
<del> <a href="http://discuss.atom.io" dataset={{ event: 'discuss' }}>
<del> discuss.atom.io
<add> <a
<add> href="https://github.com/atom/atom/discussions"
<add> dataset={{ event: 'discussions' }}
<add> >
<add> Github Discussions
<ide> </a>
<ide> </li>
<ide> <li>
<ide><path>src/main-process/atom-application.js
<ide> module.exports = class AtomApplication extends EventEmitter {
<ide> shell.openExternal('http://flight-manual.atom.io')
<ide> );
<ide> this.on('application:open-discussions', () =>
<del> shell.openExternal('https://discuss.atom.io')
<add> shell.openExternal('https://github.com/atom/atom/discussions')
<ide> );
<ide> this.on('application:open-faq', () =>
<ide> shell.openExternal('https://atom.io/faq') | 6 |
Python | Python | add set_pricing function | 48fcce4ea6a7d9721d1139e1ad34ea93d62e0a32 | <ide><path>libcloud/pricing.py
<ide> def get_pricing(driver_type, driver_name, pricing_file_path=None):
<ide> PRICING_DATA[driver_type][driver_name] = pricing
<ide> return pricing
<ide>
<add>def set_pricing(driver_type, driver_name, pricing):
<add> """
<add> Populate the driver pricing dictionary.
<add>
<add> @type driver_type: C{str}
<add> @param driver_type: Driver type ('compute' or 'storage')
<add>
<add> @type driver_name: C{str}
<add> @param driver_name: Driver name
<add>
<add> @type pricing: C{dict}
<add> @param pricing: Dictionary where a key is a size ID and a value is a price.
<add> """
<add>
<add> PRICING_DATA[driver_type][driver_name] = pricing
<add>
<ide> def get_size_price(driver_type, driver_name, size_id):
<ide> """
<ide> Return price for the provided size. | 1 |
Python | Python | fix typo in js2c.py | fcf2da098ab24c1454c5b31eefbc8f6dd9e9c743 | <ide><path>tools/js2c.py
<ide>
<ide> """
<ide> This is a utility for converting JavaScript source code into uint16_t[],
<del>that are used for embeding JavaScript code into the Node.js binary.
<add>that are used for embedding JavaScript code into the Node.js binary.
<ide> """
<ide> import argparse
<ide> import os | 1 |
Go | Go | deny finit_module in default seccomp profile | 0d5306a0b69c912a981f3a4bd41b80beb1207851 | <ide><path>daemon/execdriver/native/seccomp_default.go
<ide> var defaultSeccompProfile = &configs.Seccomp{
<ide> Action: configs.Errno,
<ide> Args: []*configs.Arg{},
<ide> },
<add> {
<add> // Deny manipulation and functions on kernel modules.
<add> Name: "finit_module",
<add> Action: configs.Errno,
<add> Args: []*configs.Arg{},
<add> },
<ide> {
<ide> // Deny retrieval of exported kernel and module symbols
<ide> Name: "get_kernel_syms", | 1 |
Python | Python | add a new decision tree (not used for the moment) | 2d20e5967c1782b0f455c81b97418501f421ea6f | <ide><path>glances/plugins/glances_alert.py
<ide> 'thresholds_min': 2},
<ide> ]
<ide>
<add># @TODO: change the algo to use the following decision tree
<add># Source: Inspire by https://scoutapm.com/blog/slow_server_flow_chart
<add># _yes means threshold >= 2
<add># _no means threshold < 2
<add># With threshold:
<add># - 0: OK
<add># - 1: CAREFUL
<add># - 2: WARNING
<add># - 3: CRITICAL
<add>tree_new = {
<add> 'cpu_iowait': {
<add> '_yes': {
<add> 'memswap': {
<add> '_yes': {
<add> 'mem': {
<add> '_yes': {
<add> # Once you've identified the offenders, the resolution will again depend on whether their memory usage seems
<add> # business-as-usual or not. For example, a memory leak can be satisfactorily addressed by a one-time or periodic
<add> # restart of the process.
<add> # - if memory usage seems anomalous: kill the offending processes.
<add> # - if memory usage seems business-as-usual: add RAM to the server, or split high-memory using services to other servers.
<add> '_msg': "Memory issue"
<add> },
<add> '_no': {
<add> # ???
<add> '_msg': "Swap issue"
<add> }
<add> }
<add> },
<add> '_no': {
<add> # Low swap means you have a "real" IO wait problem. The next step is to see what's hogging your IO.
<add> # iotop is an awesome tool for identifying io offenders. Two things to note:
<add> # unless you've already installed iotop, it's probably not already on your system.
<add> # Recommendation: install it before you need it - - it's no fun trying to install a troubleshooting
<add> # tool on an overloaded machine (iotop requies a Linux of 2.62 or above)
<add> '_msg': "I/O issue"
<add> }
<add> }
<add> },
<add> '_no': {
<add> 'cpu_total': {
<add> '_yes': {
<add> 'cpu_user': {
<add> '_yes': {
<add> # We expect the usertime percentage to be high.
<add> # There's most likely a program or service you've configured on you server that's hogging CPU.
<add> # Checking the % user time just confirms this. When you see that the % usertime is high,
<add> # it's time to see what executable is monopolizing the CPU
<add> # Once you've confirmed that the % usertime is high, check the process list(also provided by top).
<add> # Be default, top sorts the process list by % CPU, so you can just look at the top process or processes.
<add> # If there's a single process hogging the CPU in a way that seems abnormal, it's an anomalous situation
<add> # that a service restart can fix. If there are are multiple processes taking up CPU resources, or it
<add> # there's one process that takes lots of resources while otherwise functioning normally, than your setup
<add> # may just be underpowered. You'll need to upgrade your server(add more cores), or split services out onto
<add> # other boxes. In either case, you have a resolution:
<add> # - if situation seems anomalous: kill the offending processes.
<add> # - if situation seems typical given history: upgrade server or add more servers.
<add> '_msg': "CPU issue with user process(es)"
<add> },
<add> '_no': {
<add> 'cpu_steal': {
<add> '_yes': {
<add> '_msg': "CPU issue with stolen time. System running the hypervisor may be too busy."
<add> },
<add> '_no': {
<add> '_msg': "CPU issue with system process(es)"
<add> }
<add> }
<add> }
<add> }
<add> },
<add> '_no': {
<add> '_yes': {
<add> # ???
<add> '_msg': "Memory issue"
<add> },
<add> '_no': {
<add> # Your slowness isn't due to CPU or IO problems, so it's likely an application-specific issue.
<add> # It's also possible that the slowness is being caused by another server in your cluster, or
<add> # by an external service you rely on.
<add> # start by checking important applications for uncharacteristic slowness(the DB is a good place to start),
<add> # think through which parts of your infrastructure could be slowed down externally. For example, do you
<add> # use an externally hosted email service that could slow down critical parts of your application?
<add> # If you suspect another server in your cluster, strace and lsof can provide information on what the
<add> # process is doing or waiting on. Strace will show you which file descriptors are being read or written
<add> # to(or being attempted to be read from) and lsof can give you a mapping of those file descriptors to
<add> # network connections.
<add> '_msg': "External issue"
<add> }
<add> }
<add> }
<add> }
<add> }
<add>}
<add>
<ide>
<ide> def global_message():
<ide> """Parse the decision tree and return the message. | 1 |
Python | Python | support multiple prediction files for squad task | c8f9cf196aa7a9c9554e6005782fd3d71f8d80e4 | <ide><path>official/nlp/bert/run_squad_helper.py
<ide> def define_common_squad_flags():
<ide> flags.DEFINE_integer('train_batch_size', 32, 'Total batch size for training.')
<ide> # Predict processing related.
<ide> flags.DEFINE_string('predict_file', None,
<del> 'Prediction data path with train tfrecords.')
<add> 'SQuAD prediction json file path. '
<add> '`predict` mode supports multiple files: one can use '
<add> 'wildcard to specify multiple files and it can also be '
<add> 'multiple file patterns separated by comma. Note that '
<add> '`eval` mode only supports a single predict file.')
<ide> flags.DEFINE_bool(
<ide> 'do_lower_case', True,
<ide> 'Whether to lower case the input text. Should be True for uncased '
<ide> def _dataset_fn(ctx=None):
<ide> return _dataset_fn
<ide>
<ide>
<del>def predict_squad_customized(strategy,
<del> input_meta_data,
<del> bert_config,
<del> checkpoint_path,
<del> predict_tfrecord_path,
<del> num_steps):
<del> """Make predictions using a Bert-based squad model."""
<del> predict_dataset_fn = get_dataset_fn(
<del> predict_tfrecord_path,
<del> input_meta_data['max_seq_length'],
<del> FLAGS.predict_batch_size,
<del> is_training=False)
<del> predict_iterator = iter(
<del> strategy.experimental_distribute_datasets_from_function(
<del> predict_dataset_fn))
<del>
<add>def get_squad_model_to_predict(strategy, bert_config, checkpoint_path,
<add> input_meta_data):
<add> """Gets a squad model to make predictions."""
<ide> with strategy.scope():
<ide> # Prediction always uses float32, even if training uses mixed precision.
<ide> tf.keras.mixed_precision.experimental.set_policy('float32')
<ide> def predict_squad_customized(strategy,
<ide> logging.info('Restoring checkpoints from %s', checkpoint_path)
<ide> checkpoint = tf.train.Checkpoint(model=squad_model)
<ide> checkpoint.restore(checkpoint_path).expect_partial()
<add> return squad_model
<add>
<add>
<add>def predict_squad_customized(strategy,
<add> input_meta_data,
<add> predict_tfrecord_path,
<add> num_steps,
<add> squad_model):
<add> """Make predictions using a Bert-based squad model."""
<add> predict_dataset_fn = get_dataset_fn(
<add> predict_tfrecord_path,
<add> input_meta_data['max_seq_length'],
<add> FLAGS.predict_batch_size,
<add> is_training=False)
<add> predict_iterator = iter(
<add> strategy.experimental_distribute_datasets_from_function(
<add> predict_dataset_fn))
<ide>
<ide> @tf.function
<ide> def predict_step(iterator):
<ide> def clip_by_global_norm_callback(grads_and_vars):
<ide> post_allreduce_callbacks=[clip_by_global_norm_callback])
<ide>
<ide>
<del>def prediction_output_squad(
<del> strategy, input_meta_data, tokenizer, bert_config, squad_lib, checkpoint):
<add>def prediction_output_squad(strategy, input_meta_data, tokenizer, squad_lib,
<add> predict_file, squad_model):
<ide> """Makes predictions for a squad dataset."""
<ide> doc_stride = input_meta_data['doc_stride']
<ide> max_query_length = input_meta_data['max_query_length']
<ide> # Whether data should be in Ver 2.0 format.
<ide> version_2_with_negative = input_meta_data.get('version_2_with_negative',
<ide> False)
<ide> eval_examples = squad_lib.read_squad_examples(
<del> input_file=FLAGS.predict_file,
<add> input_file=predict_file,
<ide> is_training=False,
<ide> version_2_with_negative=version_2_with_negative)
<ide>
<ide> def _append_feature(feature, is_padding):
<ide>
<ide> num_steps = int(dataset_size / FLAGS.predict_batch_size)
<ide> all_results = predict_squad_customized(
<del> strategy, input_meta_data, bert_config,
<del> checkpoint, eval_writer.filename, num_steps)
<add> strategy, input_meta_data, eval_writer.filename, num_steps, squad_model)
<ide>
<ide> all_predictions, all_nbest_json, scores_diff_json = (
<ide> squad_lib.postprocess_output(
<ide> def _append_feature(feature, is_padding):
<ide>
<ide>
<ide> def dump_to_files(all_predictions, all_nbest_json, scores_diff_json,
<del> squad_lib, version_2_with_negative):
<add> squad_lib, version_2_with_negative, file_prefix=''):
<ide> """Save output to json files."""
<del> output_prediction_file = os.path.join(FLAGS.model_dir, 'predictions.json')
<del> output_nbest_file = os.path.join(FLAGS.model_dir, 'nbest_predictions.json')
<del> output_null_log_odds_file = os.path.join(FLAGS.model_dir, 'null_odds.json')
<add> output_prediction_file = os.path.join(FLAGS.model_dir,
<add> '%spredictions.json' % file_prefix)
<add> output_nbest_file = os.path.join(FLAGS.model_dir,
<add> '%snbest_predictions.json' % file_prefix)
<add> output_null_log_odds_file = os.path.join(FLAGS.model_dir, file_prefix,
<add> '%snull_odds.json' % file_prefix)
<ide> logging.info('Writing predictions to: %s', (output_prediction_file))
<ide> logging.info('Writing nbest to: %s', (output_nbest_file))
<ide>
<ide> def dump_to_files(all_predictions, all_nbest_json, scores_diff_json,
<ide> squad_lib.write_to_json_files(scores_diff_json, output_null_log_odds_file)
<ide>
<ide>
<add>def _get_matched_files(input_path):
<add> """Returns all files that matches the input_path."""
<add> input_patterns = input_path.strip().split(',')
<add> all_matched_files = []
<add> for input_pattern in input_patterns:
<add> input_pattern = input_pattern.strip()
<add> if not input_pattern:
<add> continue
<add> matched_files = tf.io.gfile.glob(input_pattern)
<add> if not matched_files:
<add> raise ValueError('%s does not match any files.' % input_pattern)
<add> else:
<add> all_matched_files.extend(matched_files)
<add> return sorted(all_matched_files)
<add>
<add>
<ide> def predict_squad(strategy,
<ide> input_meta_data,
<ide> tokenizer,
<ide> def predict_squad(strategy,
<ide> """Get prediction results and evaluate them to hard drive."""
<ide> if init_checkpoint is None:
<ide> init_checkpoint = tf.train.latest_checkpoint(FLAGS.model_dir)
<del> all_predictions, all_nbest_json, scores_diff_json = prediction_output_squad(
<del> strategy, input_meta_data, tokenizer,
<del> bert_config, squad_lib, init_checkpoint)
<del> dump_to_files(all_predictions, all_nbest_json, scores_diff_json, squad_lib,
<del> input_meta_data.get('version_2_with_negative', False))
<add>
<add> all_predict_files = _get_matched_files(FLAGS.predict_file)
<add> squad_model = get_squad_model_to_predict(strategy, bert_config,
<add> init_checkpoint, input_meta_data)
<add> for idx, predict_file in enumerate(all_predict_files):
<add> all_predictions, all_nbest_json, scores_diff_json = prediction_output_squad(
<add> strategy, input_meta_data, tokenizer, squad_lib, predict_file,
<add> squad_model)
<add> if len(all_predict_files) == 1:
<add> file_prefix = ''
<add> else:
<add> # if predict_file is /path/xquad.ar.json, the `file_prefix` may be
<add> # "xquad.ar-0-"
<add> file_prefix = '%s-' % os.path.splitext(
<add> os.path.basename(all_predict_files[idx]))[0]
<add> dump_to_files(all_predictions, all_nbest_json, scores_diff_json, squad_lib,
<add> input_meta_data.get('version_2_with_negative', False),
<add> file_prefix)
<ide>
<ide>
<ide> def eval_squad(strategy,
<ide> def eval_squad(strategy,
<ide> """Get prediction results and evaluate them against ground truth."""
<ide> if init_checkpoint is None:
<ide> init_checkpoint = tf.train.latest_checkpoint(FLAGS.model_dir)
<add>
<add> all_predict_files = _get_matched_files(FLAGS.predict_file)
<add> if len(all_predict_files) != 1:
<add> raise ValueError('`eval_squad` only supports one predict file, '
<add> 'but got %s' % all_predict_files)
<add>
<add> squad_model = get_squad_model_to_predict(strategy, bert_config,
<add> init_checkpoint, input_meta_data)
<ide> all_predictions, all_nbest_json, scores_diff_json = prediction_output_squad(
<del> strategy, input_meta_data, tokenizer,
<del> bert_config, squad_lib, init_checkpoint)
<add> strategy, input_meta_data, tokenizer, squad_lib, all_predict_files[0],
<add> squad_model)
<ide> dump_to_files(all_predictions, all_nbest_json, scores_diff_json, squad_lib,
<ide> input_meta_data.get('version_2_with_negative', False))
<ide> | 1 |
Text | Text | add nel-visualisation to manual-usage | e61d93f8c3715d74038c9bd952fe60418fc6f144 | <ide><path>website/docs/usage/visualizers.md
<ide> position.
<ide> >
<ide> > ```python
<ide> > ex = [{"text": "But Google is starting from behind.",
<del>> "ents": [{"start": 4, "end": 10, "label": "ORG"}],
<add>> "ents": [{"start": 4, "end": 10, "label": "ORG", "kb_id": "Q95", "kb_url": "https://www.wikidata.org/entity/Q95"}],
<ide> > "title": None}]
<ide> > html = displacy.render(ex, style="ent", manual=True)
<ide> > ```
<ide> position.
<ide> ### ENT input
<ide> {
<ide> "text": "But Google is starting from behind.",
<del> "ents": [{"start": 4, "end": 10, "label": "ORG"}],
<add> "ents": [{"start": 4, "end": 10, "label": "ORG", "kb_id": "Q95", "kb_url": "https://www.wikidata.org/entity/Q95"}],
<ide> "title": None
<ide> }
<ide> ``` | 1 |
Text | Text | add xray things | 640dc6e3226645414d44ad7ec377884aa21765e2 | <ide><path>docs/focus/2018-04-09.md
<ide> - Improved handling (hopefully 🤞) of potential race condition when joining a portal with poor network connectivity ([atom/teletype-client#58](https://github.com/atom/teletype-client/pull/58))
<ide> - Published [Teletype 0.12.0](https://github.com/atom/teletype/releases/tag/v0.12.0) with the above improvements
<ide> - Xray
<add> - Started on support for shared remote workspaces by developing an RPC system for use between Xray peers.
<add> - See [this week's in-depth update](https://github.com/atom/xray/blob/master/docs/updates/2018_04_09.md) for details.
<ide> - Reactor Duty
<ide> - Fixed an issue that sometimes prevented the fuzzy-finder from showing local files when Teletype is installed ([atom/fuzzy-finder#343](https://github.com/atom/fuzzy-finder/issues/343))
<ide> - Shipped [Atom 1.25.1](https://github.com/atom/atom/releases/tag/v1.25.1) and [1.26.0-beta1](https://github.com/atom/atom/releases/tag/v1.26.0-beta1)
<ide> - Revive the React 16 and Enzyme port started in [atom/github#1174](https://github.com/atom/github/pull/1174). @smashwilson
<ide> - Tree-sitter
<ide> - Xray
<add> - Merge [initial implementation of shared workspaces](https://github.com/atom/xray/pull/61). | 1 |
Javascript | Javascript | add test for selection.html | f72cc3535904abd1364b1987b169f12bdacf6c76 | <ide><path>test/core/selection-html-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("selection.html");
<add>
<add>suite.addBatch({
<add> "select(body)": {
<add> topic: function() {
<add> return d3.select("body").html("");
<add> },
<add> "sets the inner HTML as a string": function(body) {
<add> body.html("<h1>Hello, world!</h1>");
<add> assert.equal(document.body.firstChild.tagName, "H1");
<add> assert.equal(document.body.firstChild.textContent, "Hello, world!");
<add> },
<add> "sets the inner HTML as a number": function(body) {
<add> body.html(42);
<add> assert.equal(document.body.innerHTML, "42");
<add> assert.equal(document.body.firstChild.nodeType, document.TEXT_NODE);
<add> },
<add> "sets the inner HTML as a function": function(body) {
<add> body.data(["Subject"]).html(function(d, i) { return "<b>" + d + "</b><i>" + i + "</i>"; });
<add> assert.equal(document.body.firstChild.tagName, "B");
<add> assert.equal(document.body.firstChild.textContent, "Subject");
<add> assert.equal(document.body.lastChild.tagName, "I");
<add> assert.equal(document.body.lastChild.textContent, "0");
<add> },
<add> /*
<add> unfiled jsdom bug
<add> "clears the inner HTML as null": function(body) {
<add> body.html(null);
<add> assert.equal(document.body.innerHTML, "");
<add> assert.isNull(document.body.firstChild);
<add> },
<add> */
<add> "clears the inner HTML as the empty string": function(body) {
<add> body.html("");
<add> assert.equal(document.body.innerHTML, "");
<add> assert.isNull(document.body.firstChild);
<add> },
<add> "clears the inner HTML as a function": function(body) {
<add> body.text(function() { return ""; });
<add> assert.equal(document.body.innerHTML, "");
<add> assert.isNull(document.body.firstChild);
<add> },
<add> "ignores null nodes": function() {
<add> var body = d3.select("body");
<add> body[0][0] = null;
<add> document.body.innerHTML = "<h1>foo</h1>";
<add> body.html("bar");
<add> assert.equal(document.body.textContent, "foo");
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "selectAll(div)": {
<add> topic: function() {
<add> return d3.select("body").html("").selectAll("div").data(d3.range(2)).enter().append("div");
<add> },
<add> "sets the inner HTML as a string": function(div) {
<add> div.html("<h1>Hello, world!</h1>");
<add> assert.equal(div[0][0].firstChild.tagName, "H1");
<add> assert.equal(div[0][0].firstChild.textContent, "Hello, world!");
<add> assert.equal(div[0][1].firstChild.tagName, "H1");
<add> assert.equal(div[0][1].firstChild.textContent, "Hello, world!");
<add> },
<add> "sets the inner HTML as a number": function(div) {
<add> div.html(42);
<add> assert.equal(div[0][0].innerHTML, "42");
<add> assert.equal(div[0][0].firstChild.nodeType, document.TEXT_NODE);
<add> },
<add> "sets the inner HTML as a function": function(div) {
<add> div.data(["foo", "bar"]).html(function(d, i) { return "<b>" + d + "</b><i>" + i + "</i>"; });
<add> assert.equal(div[0][0].firstChild.tagName, "B");
<add> assert.equal(div[0][0].firstChild.textContent, "foo");
<add> assert.equal(div[0][0].lastChild.tagName, "I");
<add> assert.equal(div[0][0].lastChild.textContent, "0");
<add> assert.equal(div[0][1].firstChild.tagName, "B");
<add> assert.equal(div[0][1].firstChild.textContent, "bar");
<add> assert.equal(div[0][1].lastChild.tagName, "I");
<add> assert.equal(div[0][1].lastChild.textContent, "1");
<add> },
<add> /*
<add> unfiled jsdom bug
<add> "clears the inner HTML as null": function(div) {
<add> div.html(null);
<add> assert.equal(div[0][0].innerHTML, "");
<add> assert.isNull(div[0][0].firstChild);
<add> assert.equal(div[0][1].innerHTML, "");
<add> assert.isNull(div[0][1].firstChild);
<add> },
<add> */
<add> "clears the inner HTML as a function": function(div) {
<add> div.html(function() { return ""; });
<add> assert.equal(div[0][0].innerHTML, "");
<add> assert.isNull(div[0][0].firstChild);
<add> assert.equal(div[0][1].innerHTML, "");
<add> assert.isNull(div[0][1].firstChild);
<add> },
<add> "ignores null nodes": function(div) {
<add> var some = d3.selectAll("div");
<add> some[0][0] = null;
<add> div[0][0].innerHTML = "<h1>foo</h1>";
<add> some.html("bar");
<add> assert.equal(div[0][0].textContent, "foo");
<add> assert.equal(div[0][1].textContent, "bar");
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 1 |
PHP | PHP | change default days to 30 for daily channel | c60ff606793f07595d85d2b90f0a91bdf83f7ce1 | <ide><path>config/logging.php
<ide> 'driver' => 'daily',
<ide> 'path' => storage_path('logs/laravel.log'),
<ide> 'level' => 'debug',
<del> 'days' => 7,
<add> 'days' => 30,
<ide> ],
<ide>
<ide> 'slack' => [ | 1 |
Javascript | Javascript | update $parsers ngmodelcontroller doc | 0c8a88ba092a251ba8d79092c590f45a6cd27de9 | <ide><path>src/ng/directive/input.js
<ide> var VALID_CLASS = 'ng-valid',
<ide> * @property {*} $modelValue The value in the model, that the control is bound to.
<ide> * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
<ide> the control reads value from the DOM. Each function is called, in turn, passing the value
<del> through to the next. Used to sanitize / convert the value as well as validation.
<del> For validation, the parsers should update the validity state using
<add> through to the next. The last return value is used to populate the model.
<add> Used to sanitize / convert the value as well as validation. For validation,
<add> the parsers should update the validity state using
<ide> {@link ngModel.NgModelController#$setValidity $setValidity()},
<ide> and return `undefined` for invalid values.
<ide> | 1 |
Python | Python | remove unused variables in tests | e6c0019c80d03b86e7fc051a9c51c55d9a4e7ba7 | <ide><path>tests/test_modeling_common.py
<ide> def test_headmasking(self):
<ide> multihead_outputs = head_mask.grad
<ide>
<ide> attentions = outputs[-1]
<del> hidden_states = outputs[-2]
<ide>
<ide> # Remove Nan
<ide> for t in attentions:
<ide> def test_inputs_embeds(self):
<ide> inputs_dict["decoder_inputs_embeds"] = wte(decoder_input_ids)
<ide>
<ide> with torch.no_grad():
<del> outputs = model(**inputs_dict)
<add> model(**inputs_dict)
<ide>
<ide>
<ide> class ConfigTester(object):
<ide><path>tests/test_modeling_tf_common.py
<ide> def test_inputs_embeds(self):
<ide> inputs_dict["encoder_inputs_embeds"] = self._get_embeds(wte, encoder_input_ids)
<ide> inputs_dict["decoder_inputs_embeds"] = self._get_embeds(wte, decoder_input_ids)
<ide>
<del> outputs = model(inputs_dict)
<add> model(inputs_dict)
<ide>
<ide>
<ide> def ids_tensor(shape, vocab_size, rng=None, name=None, dtype=None):
<ide><path>tests/test_modeling_tf_xlm.py
<ide> def create_and_check_xlm_qa(
<ide>
<ide> inputs = {"input_ids": input_ids, "lengths": input_lengths}
<ide>
<del> outputs = model(inputs)
<ide> start_logits, end_logits = model(inputs)
<ide>
<ide> result = {
<ide><path>tests/test_tokenization_common.py
<ide> def test_add_tokens_tokenizer(self):
<ide> self.assertEqual(all_size_2, all_size + len(new_toks))
<ide>
<ide> tokens = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l", add_special_tokens=False)
<del> out_string = tokenizer.decode(tokens)
<ide>
<ide> self.assertGreaterEqual(len(tokens), 4)
<ide> self.assertGreater(tokens[0], tokenizer.vocab_size - 1)
<ide> def test_add_tokens_tokenizer(self):
<ide> tokens = tokenizer.encode(
<ide> ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l", add_special_tokens=False
<ide> )
<del> out_string = tokenizer.decode(tokens)
<ide>
<ide> self.assertGreaterEqual(len(tokens), 6)
<ide> self.assertGreater(tokens[0], tokenizer.vocab_size - 1) | 4 |
Text | Text | fix util.inspect change history | 96c37b33126c6243f8ba4d190e5b7b1283104f36 | <ide><path>doc/api/util.md
<ide> stream.write('With ES6');
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> changes:
<del> - version: v12.19.0
<add> - version:
<add> - v14.6.0
<add> - v12.19.0
<ide> pr-url: https://github.com/nodejs/node/pull/33690
<ide> description: If `object` is from a different `vm.Context` now, a custom
<ide> inspection function on it will not receive context-specific | 1 |
Python | Python | fix a typo on blueprints module name | 5ecca4c0dae52c7645f9dbda6cbfc32ec76a3498 | <ide><path>flask/blueprints.py
<ide> def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
<ide> class Blueprint(_PackageBoundObject):
<ide> """Represents a blueprint. A blueprint is an object that records
<ide> functions that will be called with the
<del> :class:`~flask.blueprint.BlueprintSetupState` later to register functions
<add> :class:`~flask.blueprints.BlueprintSetupState` later to register functions
<ide> or other things on the main application. See :ref:`blueprints` for more
<ide> information.
<ide> | 1 |
Ruby | Ruby | add documentation for query_methods bang methods | 993ef9ed59e651aac0160a72ff032ce6faacf427 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def includes(*args)
<ide> args.empty? ? self : spawn.includes!(*args)
<ide> end
<ide>
<add> # Like #includes, but modifies the relation in place.
<ide> def includes!(*args)
<ide> args.reject! {|a| a.blank? }
<ide>
<ide> def eager_load(*args)
<ide> args.blank? ? self : spawn.eager_load!(*args)
<ide> end
<ide>
<add> # Like #eager_load, but modifies relation in place.
<add> # object.
<ide> def eager_load!(*args)
<ide> self.eager_load_values += args
<ide> self
<ide> def preload(*args)
<ide> args.blank? ? self : spawn.preload!(*args)
<ide> end
<ide>
<add> # Like #preload, but modifies relation in place.
<ide> def preload!(*args)
<ide> self.preload_values += args
<ide> self
<ide> def references(*args)
<ide> args.blank? ? self : spawn.references!(*args)
<ide> end
<ide>
<add> # Like #references, but modifies relation in place.
<ide> def references!(*args)
<ide> args.flatten!
<ide>
<ide> def select(value = Proc.new)
<ide> end
<ide> end
<ide>
<add> # Like #select, but modifies relation in place.
<ide> def select!(value)
<ide> self.select_values += Array.wrap(value)
<ide> self
<ide> def group(*args)
<ide> args.blank? ? self : spawn.group!(*args)
<ide> end
<ide>
<add> # Like #group, but modifies relation in place.
<ide> def group!(*args)
<ide> args.flatten!
<ide>
<ide> def order(*args)
<ide> args.blank? ? self : spawn.order!(*args)
<ide> end
<ide>
<add> # Like #order, but modifies relation in place.
<ide> def order!(*args)
<ide> args.flatten!
<ide>
<ide> def reorder(*args)
<ide> args.blank? ? self : spawn.reorder!(*args)
<ide> end
<ide>
<add> # Like #reorder, but modifies relation in place.
<ide> def reorder!(*args)
<ide> args.flatten!
<ide>
<ide> def joins(*args)
<ide> args.compact.blank? ? self : spawn.joins!(*args)
<ide> end
<ide>
<add> # Like #joins, but modifies relation in place.
<ide> def joins!(*args)
<ide> args.flatten!
<ide>
<ide> def having(opts, *rest)
<ide> opts.blank? ? self : spawn.having!(opts, *rest)
<ide> end
<ide>
<add> # Like #having, but modifies relation in place.
<ide> def having!(opts, *rest)
<ide> references!(PredicateBuilder.references(opts)) if Hash === opts
<ide>
<ide> def limit(value)
<ide> spawn.limit!(value)
<ide> end
<ide>
<add> # Like #limit, but modifies relation in place.
<ide> def limit!(value)
<ide> self.limit_value = value
<ide> self
<ide> def offset(value)
<ide> spawn.offset!(value)
<ide> end
<ide>
<add> # Like #offset, but modifies relation in place.
<ide> def offset!(value)
<ide> self.offset_value = value
<ide> self
<ide> end
<ide>
<ide> # Specifies locking settings (default to +true+). For more information
<del> # on locking, please see +ActiveRecord::Lockin+g.
<add> # on locking, please see +ActiveRecord::Locking+.
<ide> def lock(locks = true)
<ide> spawn.lock!(locks)
<ide> end
<ide>
<add> # Like #lock, but modifies relation in place.
<ide> def lock!(locks = true)
<ide> case locks
<ide> when String, TrueClass, NilClass
<ide> def readonly(value = true)
<ide> spawn.readonly!(value)
<ide> end
<ide>
<add> # Like #readonly, but modifies relation in place.
<ide> def readonly!(value = true)
<ide> self.readonly_value = value
<ide> self
<ide> def from(value, subquery_name = nil)
<ide> spawn.from!(value, subquery_name)
<ide> end
<ide>
<add> # Like #from, but modifies relation in place.
<ide> def from!(value, subquery_name = nil)
<ide> self.from_value = [value, subquery_name]
<ide> self
<ide> def uniq(value = true)
<ide> spawn.uniq!(value)
<ide> end
<ide>
<add> # Like #uniq, but modifies relation in place.
<ide> def uniq!(value = true)
<ide> self.uniq_value = value
<ide> self
<ide> def extending(*modules, &block)
<ide> end
<ide> end
<ide>
<add> # Like #extending, but modifies relation in place.
<ide> def extending!(*modules, &block)
<ide> modules << Module.new(&block) if block_given?
<ide>
<ide> def reverse_order
<ide> spawn.reverse_order!
<ide> end
<ide>
<add> # Like #reverse_order, but modifies relation in place.
<ide> def reverse_order!
<ide> self.reverse_order_value = !reverse_order_value
<ide> self | 1 |
Java | Java | add tests to jsonpathexpectationshelpertests | 8afea1bc784b2dd75af0f0db90b0c3c659139a0c | <ide><path>spring-test/src/test/java/org/springframework/test/util/JsonPathExpectationsHelperTests.java
<ide> */
<ide> public class JsonPathExpectationsHelperTests {
<ide>
<add> private static final String CONTENT = "{" + //
<add> "\"str\": \"foo\"," + //
<add> "\"nr\": 5," + //
<add> "\"bool\": true," + //
<add> "\"arr\": [\"bar\"]," + //
<add> "\"emptyArray\": []," + //
<add> "\"colorMap\": {\"red\": \"rojo\"}," + //
<add> "\"emptyMap\": {}," + //
<add> "}";
<add>
<add>
<ide> @Rule
<ide> public final ExpectedException exception = ExpectedException.none();
<ide>
<ide>
<add> @Test
<add> public void exists() throws Exception {
<add> new JsonPathExpectationsHelper("$.str").exists(CONTENT);
<add> }
<add>
<add> @Test
<add> public void doesNotExist() throws Exception {
<add> new JsonPathExpectationsHelper("$.bogus").doesNotExist(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValue() throws Exception {
<add> new JsonPathExpectationsHelper("$.nr").assertValue(CONTENT, 5);
<add> }
<add>
<ide> @Test
<ide> public void assertValueWithDifferentExpectedType() throws Exception {
<ide> exception.expect(AssertionError.class);
<ide> exception.expectMessage(equalTo("For JSON path \"$.nr\", type of value expected:<java.lang.String> but was:<java.lang.Integer>"));
<del> new JsonPathExpectationsHelper("$.nr").assertValue("{ \"nr\" : 5 }", "5");
<add> new JsonPathExpectationsHelper("$.nr").assertValue(CONTENT, "5");
<add> }
<add>
<add> @Test
<add> public void assertValueIsString() throws Exception {
<add> new JsonPathExpectationsHelper("$.str").assertValueIsString(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValueIsStringForNonString() throws Exception {
<add> exception.expect(AssertionError.class);
<add> new JsonPathExpectationsHelper("$.bool").assertValueIsString(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValueIsNumber() throws Exception {
<add> new JsonPathExpectationsHelper("$.nr").assertValueIsNumber(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValueIsNumberForNonNumber() throws Exception {
<add> exception.expect(AssertionError.class);
<add> new JsonPathExpectationsHelper("$.bool").assertValueIsNumber(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValueIsBoolean() throws Exception {
<add> new JsonPathExpectationsHelper("$.bool").assertValueIsBoolean(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValueIsBooleanForNonBoolean() throws Exception {
<add> exception.expect(AssertionError.class);
<add> new JsonPathExpectationsHelper("$.nr").assertValueIsBoolean(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValueIsArray() throws Exception {
<add> new JsonPathExpectationsHelper("$.arr").assertValueIsArray(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValueIsArrayForNonArray() throws Exception {
<add> exception.expect(AssertionError.class);
<add> new JsonPathExpectationsHelper("$.str").assertValueIsArray(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValueIsMap() throws Exception {
<add> new JsonPathExpectationsHelper("$.colorMap").assertValueIsMap(CONTENT);
<add> }
<add>
<add> @Test
<add> public void assertValueIsMapForNonMap() throws Exception {
<add> exception.expect(AssertionError.class);
<add> new JsonPathExpectationsHelper("$.str").assertValueIsMap(CONTENT);
<ide> }
<ide>
<ide> } | 1 |
Mixed | Javascript | send signal name to signal handlers | 9b2cf1c8ebdf9483aaa1f0d1b6770043c229a354 | <ide><path>doc/api/process.md
<ide> Signal events will be emitted when the Node.js process receives a signal. Please
<ide> refer to signal(7) for a listing of standard POSIX signal names such as
<ide> `SIGINT`, `SIGHUP`, etc.
<ide>
<add>The signal handler will receive the signal's name (`'SIGINT'`,
<add> `'SIGTERM'`, etc.) as the first argument.
<add>
<ide> The name of each event will be the uppercase common name for the signal (e.g.
<ide> `'SIGINT'` for `SIGINT` signals).
<ide>
<ide> process.stdin.resume();
<ide> process.on('SIGINT', () => {
<ide> console.log('Received SIGINT. Press Control-D to exit.');
<ide> });
<add>
<add>// Using a single function to handle multiple signals
<add>function handle(signal) {
<add> console.log(`Received ${signal}`);
<add>}
<add>
<add>process.on('SIGINT', handle);
<add>process.on('SIGTERM', handle);
<ide> ```
<ide>
<ide> *Note*: An easy way to send the `SIGINT` signal is with `<Ctrl>-C` in most
<ide><path>lib/internal/process.js
<ide> function setupSignalHandlers() {
<ide>
<ide> wrap.unref();
<ide>
<del> wrap.onsignal = function() { process.emit(type); };
<add> wrap.onsignal = function() { process.emit(type, type); };
<ide>
<ide> const signum = constants[type];
<ide> const err = wrap.start(signum);
<ide><path>test/parallel/test-signal-args.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>
<add>if (common.isWindows) {
<add> common.skip('Sending signals with process.kill is not supported on Windows');
<add>}
<add>
<add>process.once('SIGINT', common.mustCall((signal) => {
<add> assert.strictEqual(signal, 'SIGINT');
<add>}));
<add>
<add>process.kill(process.pid, 'SIGINT');
<add>
<add>process.once('SIGTERM', common.mustCall((signal) => {
<add> assert.strictEqual(signal, 'SIGTERM');
<add>}));
<add>
<add>process.kill(process.pid, 'SIGTERM');
<add>
<add>// Prevent Node.js from exiting due to empty event loop before signal handlers
<add>// are fired
<add>setImmediate(() => {}); | 3 |
Text | Text | correct information about record identification | f60bc890eee5c57819077c4808a4e9fa3761e9d6 | <ide><path>guides/source/form_helpers.md
<ide> form_with(model: @article, url: article_path(@article), method: "patch")
<ide> form_with(model: @article)
<ide> ```
<ide>
<del>Notice how the short-style `form_with` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.new_record?`. It also selects the correct path to submit to, and the name based on the class of the object.
<add>Notice how the short-style `form_with` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.persisted?`. It also selects the correct path to submit to, and the name based on the class of the object.
<ide>
<ide> WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify `:url`, and `:scope` (the model name) explicitly.
<ide> | 1 |
Text | Text | update description of `test_order` [ci skip] | e9a909c162eed0a1686a02ce1a239b69e44740d6 | <ide><path>guides/source/configuring.md
<ide> There are a few configuration options available in Active Support:
<ide>
<ide> * `config.active_support.bare` enables or disables the loading of `active_support/all` when booting Rails. Defaults to `nil`, which means `active_support/all` is loaded.
<ide>
<del>* `config.active_support.test_order` sets the order that test cases are executed. Possible values are `:random` and `:sorted`. This option is set to `:random` in `config/environments/test.rb` in newly-generated applications. If you have an application that does not specify a `test_order`, it will default to `:sorted`, *until* Rails 5.0, when the default will become `:random`.
<add>* `config.active_support.test_order` sets the order in which the test cases are executed. Possible values are `:random` and `:sorted`. Defaults to `:random`.
<ide>
<ide> * `config.active_support.escape_html_entities_in_json` enables or disables the escaping of HTML entities in JSON serialization. Defaults to `true`.
<ide> | 1 |
PHP | PHP | fix typos & strict errors | 869d556d072b47f4baa6a5a12d968b6e7218cfcb | <ide><path>lib/Cake/Test/Case/Routing/DispatcherTest.php
<ide> public function testTestPluginDispatch() {
<ide> *
<ide> * @return void
<ide> */
<del> public function testDispatcherFilterSuscriber() {
<add> public function testDispatcherFilterSubscriber() {
<ide> App::build(array(
<ide> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS),
<ide> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<ide><path>lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/Routing/Filter/Test2DispatcherFilter.php
<ide>
<ide> class Test2DispatcherFilter extends DispatcherFilter {
<ide>
<del> public function beforeDispatch($event) {
<add> public function beforeDispatch(CakeEvent $event) {
<ide> $event->data['response']->statusCode(500);
<ide> $event->stopPropagation();
<ide> return $event->data['response'];
<ide> }
<ide>
<del> public function afterDispatch($event) {
<add> public function afterDispatch(CakeEvent $event) {
<ide> $event->data['response']->statusCode(200);
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add>}
<ide><path>lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/Routing/Filter/TestDispatcherFilter.php
<ide>
<ide> class TestDispatcherFilter extends DispatcherFilter {
<ide>
<del> public function beforeDispatch($event) {
<add> public function beforeDispatch(CakeEvent $event) {
<ide> $event->data['request']->params['altered'] = true;
<ide> }
<ide>
<del> public function afterDispatch($event) {
<add> public function afterDispatch(CakeEvent $event) {
<ide> $event->data['response']->statusCode(304);
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add>} | 3 |
Python | Python | add a missing space in a deprecation message | e3d1a8dabce5d8204158baefc8dcbe4f47d7bb92 | <ide><path>src/transformers/optimization.py
<ide> def __init__(
<ide> if not no_deprecation_warning:
<ide> warnings.warn(
<ide> "This implementation of AdamW is deprecated and will be removed in a future version. Use the"
<del> "PyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warning=True` to disable this warning",
<add> " PyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warning=True` to disable this warning",
<ide> FutureWarning,
<ide> )
<ide> require_version("torch>=1.5.0") # add_ with alpha | 1 |
PHP | PHP | add addif method to message bag | 50efe099b59e75563298deb992017b4cabfb021d | <ide><path>src/Illuminate/Support/MessageBag.php
<ide> public function add($key, $message)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Add a message to the message bag if the given conditional is "true".
<add> *
<add> * @param bool $boolean
<add> * @param string $key
<add> * @param string $message
<add> * @return $this
<add> */
<add> public function addIf($boolean, $key, $message)
<add> {
<add> return $boolean ? $this->add($key, $message) : $this;
<add> }
<add>
<ide> /**
<ide> * Determine if a key and message combination already exists.
<ide> * | 1 |
Javascript | Javascript | refactor the previous history rewriting logic | cdea75dc397f4eb4d6fd1f7d8a388c7d11df3452 | <ide><path>web/pdf_history.js
<ide> var PDFHistory = (function () {
<ide>
<ide> var self = this;
<ide> window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
<del> evt.preventDefault();
<del> evt.stopPropagation();
<del>
<ide> if (!self.historyUnlocked) {
<ide> return;
<ide> }
<ide> if (evt.state) {
<ide> // Move back/forward in the history.
<ide> self._goTo(evt.state);
<del> } else {
<del> // Handle the user modifying the hash of a loaded document.
<del> self.previousHash = window.location.hash.substring(1);
<add> return;
<add> }
<add>
<add> // If the state is not set, then the user tried to navigate to a
<add> // different hash by manually editing the URL and pressing Enter, or by
<add> // clicking on an in-page link (e.g. the "current view" link).
<add> // Save the current view state to the browser history.
<ide>
<del> // If the history is empty when the hash changes,
<del> // update the previous entry in the browser history.
<del> if (self.uid === 0) {
<del> var previousParams = (self.previousHash && self.currentBookmark &&
<add> // Note: In Firefox, history.null could also be null after an in-page
<add> // navigation to the same URL, and without dispatching the popstate
<add> // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
<add>
<add> if (self.uid === 0) {
<add> // Replace the previous state if it was not explicitly set.
<add> var previousParams = (self.previousHash && self.currentBookmark &&
<ide> self.previousHash !== self.currentBookmark) ?
<ide> {hash: self.currentBookmark, page: self.currentPage} :
<ide> {page: 1};
<del> self.historyUnlocked = false;
<del> self.allowHashChange = false;
<del> window.history.back();
<del> self._pushToHistory(previousParams, false, true);
<del> window.history.forward();
<del> self.historyUnlocked = true;
<del> }
<del> self._pushToHistory({hash: self.previousHash}, false, true);
<del> self._updatePreviousBookmark();
<add> replacePreviousHistoryState(previousParams, function() {
<add> updateHistoryWithCurrentHash();
<add> });
<add> } else {
<add> updateHistoryWithCurrentHash();
<ide> }
<ide> }, false);
<ide>
<add>
<add> function updateHistoryWithCurrentHash() {
<add> self.previousHash = window.location.hash.slice(1);
<add> self._pushToHistory({hash: self.previousHash}, false, true);
<add> self._updatePreviousBookmark();
<add> }
<add>
<add> function replacePreviousHistoryState(params, callback) {
<add> // To modify the previous history entry, the following happens:
<add> // 1. history.back()
<add> // 2. _pushToHistory, which calls history.replaceState( ... )
<add> // 3. history.forward()
<add> // Because a navigation via the history API does not immediately update
<add> // the history state, the popstate event is used for synchronization.
<add> self.historyUnlocked = false;
<add>
<add> // Suppress the hashchange event to avoid side effects caused by
<add> // navigating back and forward.
<add> self.allowHashChange = false;
<add> window.addEventListener('popstate', rewriteHistoryAfterBack);
<add> history.back();
<add>
<add> function rewriteHistoryAfterBack() {
<add> window.removeEventListener('popstate', rewriteHistoryAfterBack);
<add> window.addEventListener('popstate', rewriteHistoryAfterForward);
<add> self._pushToHistory(params, false, true);
<add> history.forward();
<add> }
<add> function rewriteHistoryAfterForward() {
<add> window.removeEventListener('popstate', rewriteHistoryAfterForward);
<add> self.allowHashChange = true;
<add> self.historyUnlocked = true;
<add> callback();
<add> }
<add> }
<add>
<ide> function pdfHistoryBeforeUnload() {
<ide> var previousParams = self._getPreviousParams(null, true);
<ide> if (previousParams) {
<ide> var PDFHistory = (function () {
<ide> if (!this.initialized) {
<ide> return true;
<ide> }
<del> // If the current hash changes when moving back/forward in the history,
<del> // this will trigger a 'popstate' event *as well* as a 'hashchange' event.
<del> // Since the hash generally won't correspond to the exact the position
<del> // stored in the history's state object, triggering the 'hashchange' event
<del> // can thus corrupt the browser history.
<del> //
<del> // When the hash changes during a 'popstate' event, we *only* prevent the
<del> // first 'hashchange' event and immediately reset allowHashChange.
<del> // If it is not reset, the user would not be able to change the hash.
<del>
<del> var temp = this.allowHashChange;
<del> this.allowHashChange = true;
<del> return temp;
<add> return this.allowHashChange;
<ide> },
<ide>
<ide> _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() { | 1 |
Javascript | Javascript | pass children to hydration root constructor | c8e4789e21f6cb031b92b3bd8a905244bfd808b2 | <ide><path>packages/react-art/src/ReactART.js
<ide> class Surface extends React.Component {
<ide> this._mountNode = createContainer(
<ide> this._surface,
<ide> LegacyRoot,
<del> false,
<ide> null,
<ide> false,
<ide> false,
<ide><path>packages/react-dom/src/__tests__/ReactDOMRoot-test.js
<ide> describe('ReactDOMRoot', () => {
<ide> );
<ide> });
<ide>
<add> it('callback passed to legacy hydrate() API', () => {
<add> container.innerHTML = '<div>Hi</div>';
<add> ReactDOM.hydrate(<div>Hi</div>, container, () => {
<add> Scheduler.unstable_yieldValue('callback');
<add> });
<add> expect(container.textContent).toEqual('Hi');
<add> expect(Scheduler).toHaveYielded(['callback']);
<add> });
<add>
<ide> it('warns when unmounting with legacy API (no previous content)', () => {
<ide> const root = ReactDOMClient.createRoot(container);
<ide> root.render(<div>Hi</div>);
<ide><path>packages/react-dom/src/client/ReactDOMLegacy.js
<ide> import {
<ide>
<ide> import {
<ide> createContainer,
<add> createHydrationContainer,
<ide> findHostInstanceWithNoPortals,
<ide> updateContainer,
<ide> flushSync,
<ide> function noopOnRecoverableError() {
<ide>
<ide> function legacyCreateRootFromDOMContainer(
<ide> container: Container,
<del> forceHydrate: boolean,
<add> initialChildren: ReactNodeList,
<add> parentComponent: ?React$Component<any, any>,
<add> callback: ?Function,
<add> isHydrationContainer: boolean,
<ide> ): FiberRoot {
<del> // First clear any existing content.
<del> if (!forceHydrate) {
<add> if (isHydrationContainer) {
<add> if (typeof callback === 'function') {
<add> const originalCallback = callback;
<add> callback = function() {
<add> const instance = getPublicRootInstance(root);
<add> originalCallback.call(instance);
<add> };
<add> }
<add>
<add> const root = createHydrationContainer(
<add> initialChildren,
<add> callback,
<add> container,
<add> LegacyRoot,
<add> null, // hydrationCallbacks
<add> false, // isStrictMode
<add> false, // concurrentUpdatesByDefaultOverride,
<add> '', // identifierPrefix
<add> noopOnRecoverableError,
<add> // TODO(luna) Support hydration later
<add> null,
<add> );
<add> container._reactRootContainer = root;
<add> markContainerAsRoot(root.current, container);
<add>
<add> const rootContainerElement =
<add> container.nodeType === COMMENT_NODE ? container.parentNode : container;
<add> listenToAllSupportedEvents(rootContainerElement);
<add>
<add> flushSync();
<add> return root;
<add> } else {
<add> // First clear any existing content.
<ide> let rootSibling;
<ide> while ((rootSibling = container.lastChild)) {
<ide> container.removeChild(rootSibling);
<ide> }
<del> }
<ide>
<del> const root = createContainer(
<del> container,
<del> LegacyRoot,
<del> forceHydrate,
<del> null, // hydrationCallbacks
<del> false, // isStrictMode
<del> false, // concurrentUpdatesByDefaultOverride,
<del> '', // identifierPrefix
<del> noopOnRecoverableError, // onRecoverableError
<del> null, // transitionCallbacks
<del> );
<del> markContainerAsRoot(root.current, container);
<add> if (typeof callback === 'function') {
<add> const originalCallback = callback;
<add> callback = function() {
<add> const instance = getPublicRootInstance(root);
<add> originalCallback.call(instance);
<add> };
<add> }
<add>
<add> const root = createContainer(
<add> container,
<add> LegacyRoot,
<add> null, // hydrationCallbacks
<add> false, // isStrictMode
<add> false, // concurrentUpdatesByDefaultOverride,
<add> '', // identifierPrefix
<add> noopOnRecoverableError, // onRecoverableError
<add> null, // transitionCallbacks
<add> );
<add> container._reactRootContainer = root;
<add> markContainerAsRoot(root.current, container);
<add>
<add> const rootContainerElement =
<add> container.nodeType === COMMENT_NODE ? container.parentNode : container;
<add> listenToAllSupportedEvents(rootContainerElement);
<ide>
<del> const rootContainerElement =
<del> container.nodeType === COMMENT_NODE ? container.parentNode : container;
<del> listenToAllSupportedEvents(rootContainerElement);
<add> // Initial mount should not be batched.
<add> flushSync(() => {
<add> updateContainer(initialChildren, root, parentComponent, callback);
<add> });
<ide>
<del> return root;
<add> return root;
<add> }
<ide> }
<ide>
<ide> function warnOnInvalidCallback(callback: mixed, callerName: string): void {
<ide> function legacyRenderSubtreeIntoContainer(
<ide> warnOnInvalidCallback(callback === undefined ? null : callback, 'render');
<ide> }
<ide>
<del> let root = container._reactRootContainer;
<del> let fiberRoot: FiberRoot;
<del> if (!root) {
<add> const maybeRoot = container._reactRootContainer;
<add> let root: FiberRoot;
<add> if (!maybeRoot) {
<ide> // Initial mount
<del> root = container._reactRootContainer = legacyCreateRootFromDOMContainer(
<add> root = legacyCreateRootFromDOMContainer(
<ide> container,
<add> children,
<add> parentComponent,
<add> callback,
<ide> forceHydrate,
<ide> );
<del> fiberRoot = root;
<del> if (typeof callback === 'function') {
<del> const originalCallback = callback;
<del> callback = function() {
<del> const instance = getPublicRootInstance(fiberRoot);
<del> originalCallback.call(instance);
<del> };
<del> }
<del> // Initial mount should not be batched.
<del> flushSync(() => {
<del> updateContainer(children, fiberRoot, parentComponent, callback);
<del> });
<ide> } else {
<del> fiberRoot = root;
<add> root = maybeRoot;
<ide> if (typeof callback === 'function') {
<ide> const originalCallback = callback;
<ide> callback = function() {
<del> const instance = getPublicRootInstance(fiberRoot);
<add> const instance = getPublicRootInstance(root);
<ide> originalCallback.call(instance);
<ide> };
<ide> }
<ide> // Update
<del> updateContainer(children, fiberRoot, parentComponent, callback);
<add> updateContainer(children, root, parentComponent, callback);
<ide> }
<del> return getPublicRootInstance(fiberRoot);
<add> return getPublicRootInstance(root);
<ide> }
<ide>
<ide> export function findDOMNode(
<ide><path>packages/react-dom/src/client/ReactDOMRoot.js
<ide> export function createRoot(
<ide> const root = createContainer(
<ide> container,
<ide> ConcurrentRoot,
<del> false,
<ide> null,
<ide> isStrictMode,
<ide> concurrentUpdatesByDefaultOverride,
<ide> export function hydrateRoot(
<ide>
<ide> const root = createHydrationContainer(
<ide> initialChildren,
<add> null,
<ide> container,
<ide> ConcurrentRoot,
<ide> hydrationCallbacks,
<ide><path>packages/react-native-renderer/src/ReactFabric.js
<ide> function render(
<ide> root = createContainer(
<ide> containerTag,
<ide> concurrentRoot ? ConcurrentRoot : LegacyRoot,
<del> false,
<ide> null,
<ide> false,
<ide> null,
<ide><path>packages/react-native-renderer/src/ReactNativeRenderer.js
<ide> function render(
<ide> root = createContainer(
<ide> containerTag,
<ide> LegacyRoot,
<del> false,
<ide> null,
<ide> false,
<ide> null,
<ide><path>packages/react-noop-renderer/src/createReactNoop.js
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> root = NoopRenderer.createContainer(
<ide> container,
<ide> tag,
<del> false,
<ide> null,
<ide> null,
<ide> false,
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> const fiberRoot = NoopRenderer.createContainer(
<ide> container,
<ide> ConcurrentRoot,
<del> false,
<ide> null,
<ide> null,
<ide> false,
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> const fiberRoot = NoopRenderer.createContainer(
<ide> container,
<ide> LegacyRoot,
<del> false,
<ide> null,
<ide> null,
<ide> false,
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.new.js
<ide> function findHostInstanceWithWarning(
<ide> export function createContainer(
<ide> containerInfo: Container,
<ide> tag: RootTag,
<del> // TODO: We can remove hydration-specific stuff from createContainer once
<del> // we delete legacy mode. The new root API uses createHydrationContainer.
<del> hydrate: boolean,
<ide> hydrationCallbacks: null | SuspenseHydrationCallbacks,
<ide> isStrictMode: boolean,
<ide> concurrentUpdatesByDefaultOverride: null | boolean,
<ide> identifierPrefix: string,
<ide> onRecoverableError: (error: mixed) => void,
<ide> transitionCallbacks: null | TransitionTracingCallbacks,
<ide> ): OpaqueRoot {
<add> const hydrate = false;
<ide> return createFiberRoot(
<ide> containerInfo,
<ide> tag,
<ide> export function createContainer(
<ide>
<ide> export function createHydrationContainer(
<ide> initialChildren: ReactNodeList,
<add> // TODO: Remove `callback` when we delete legacy mode.
<add> callback: ?Function,
<ide> containerInfo: Container,
<ide> tag: RootTag,
<ide> hydrationCallbacks: null | SuspenseHydrationCallbacks,
<ide> export function createHydrationContainer(
<ide> // Caution: React DevTools currently depends on this property
<ide> // being called "element".
<ide> update.payload = {element: initialChildren};
<add> update.callback =
<add> callback !== undefined && callback !== null ? callback : null;
<ide> enqueueUpdate(current, update, lane);
<ide> scheduleInitialHydrationOnRoot(root, lane, eventTime);
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.old.js
<ide> function findHostInstanceWithWarning(
<ide> export function createContainer(
<ide> containerInfo: Container,
<ide> tag: RootTag,
<del> // TODO: We can remove hydration-specific stuff from createContainer once
<del> // we delete legacy mode. The new root API uses createHydrationContainer.
<del> hydrate: boolean,
<ide> hydrationCallbacks: null | SuspenseHydrationCallbacks,
<ide> isStrictMode: boolean,
<ide> concurrentUpdatesByDefaultOverride: null | boolean,
<ide> identifierPrefix: string,
<ide> onRecoverableError: (error: mixed) => void,
<ide> transitionCallbacks: null | TransitionTracingCallbacks,
<ide> ): OpaqueRoot {
<add> const hydrate = false;
<ide> return createFiberRoot(
<ide> containerInfo,
<ide> tag,
<ide> export function createContainer(
<ide>
<ide> export function createHydrationContainer(
<ide> initialChildren: ReactNodeList,
<add> // TODO: Remove `callback` when we delete legacy mode.
<add> callback: ?Function,
<ide> containerInfo: Container,
<ide> tag: RootTag,
<ide> hydrationCallbacks: null | SuspenseHydrationCallbacks,
<ide> export function createHydrationContainer(
<ide> // Caution: React DevTools currently depends on this property
<ide> // being called "element".
<ide> update.payload = {element: initialChildren};
<add> update.callback =
<add> callback !== undefined && callback !== null ? callback : null;
<ide> enqueueUpdate(current, update, lane);
<ide> scheduleInitialHydrationOnRoot(root, lane, eventTime);
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.internal.js
<ide> describe('ReactFiberHostContext', () => {
<ide> const container = Renderer.createContainer(
<ide> /* root: */ null,
<ide> ConcurrentRoot,
<del> false,
<ide> null,
<ide> false,
<ide> '',
<ide> describe('ReactFiberHostContext', () => {
<ide> const container = Renderer.createContainer(
<ide> rootContext,
<ide> ConcurrentRoot,
<del> false,
<ide> null,
<ide> false,
<ide> '',
<ide><path>packages/react-test-renderer/src/ReactTestRenderer.js
<ide> function create(element: React$Element<any>, options: TestRendererOptions) {
<ide> let root: FiberRoot | null = createContainer(
<ide> container,
<ide> isConcurrent ? ConcurrentRoot : LegacyRoot,
<del> false,
<ide> null,
<ide> isStrictMode,
<ide> concurrentUpdatesByDefault, | 11 |
Text | Text | revise "breaking changes to internal elements" | ab76eac3016db9d84cea045e9ab1be89ed35cb60 | <ide><path>COLLABORATOR_GUIDE.md
<ide> For more information, see [Deprecations](#deprecations).
<ide>
<ide> #### Breaking Changes to Internal Elements
<ide>
<del>Breaking changes to internal elements are permitted in semver-patch or
<del>semver-minor commits but Collaborators should take significant care when
<del>making and reviewing such changes. Before landing such commits, an effort
<del>must be made to determine the potential impact of the change in the ecosystem
<del>by analyzing current use and by validating such changes through ecosystem
<del>testing using the [Canary in the Goldmine](https://github.com/nodejs/citgm)
<del>tool. If a change cannot be made without ecosystem breakage, then TSC review is
<del>required before landing the change as anything less than semver-major.
<del>
<del>If a determination is made that a particular internal API (for instance, an
<del>underscore `_` prefixed property) is sufficiently relied upon by the ecosystem
<del>such that any changes may break user code, then serious consideration should be
<del>given to providing an alternative Public API for that functionality before any
<del>breaking changes are made.
<add>Breaking changes to internal elements may occur in semver-patch or semver-minor
<add>commits. Collaborators should take significant care when making and reviewing
<add>such changes. An effort must be made to determine the potential impact of the
<add>change in the ecosystem. Use
<add>[Canary in the Goldmine](https://github.com/nodejs/citgm) to test such changes.
<add>If a change will cause ecosystem breakage, then it is semver-major. Consider
<add>providing a Public API in such cases.
<ide>
<ide> #### When Breaking Changes Actually Break Things
<ide> | 1 |
Python | Python | add chain function | d68e48555e9f62cb334059664d61ae43ccfe02f7 | <ide><path>airflow/utils.py
<ide> def round_time(dt, delta, start_date=datetime.min):
<ide> # in the special case when start_date > dt the search for upper will
<ide> # immediately stop for upper == 1 which results in lower = upper // 2 = 0
<ide> # and this function returns start_date.
<add>
<add>def chain(*tasks):
<add> """
<add> Given a number of tasks, builds a dependency chain.
<add>
<add> chain(task_1, task_2, task_3, task_4)
<add>
<add> is equivalent to
<add>
<add> task_1.set_downstream(task_2)
<add> task_2.set_downstream(task_3)
<add> task_3.set_downstream(task_4)
<add> """
<add> for up_task, down_task in zip(tasks[:-1], tasks[1:]):
<add> up_task.set_downstream(down_task) | 1 |
Text | Text | add elai data to inthewild.md | 1c7fbaf99e67fabcec09044de507fa12538e2a90 | <ide><path>INTHEWILD.md
<ide> Currently, **officially** using Airflow:
<ide> 1. [Dynata](https://www.dynata.com) [[@neil3handari](https://github.com/neil3handari)]
<ide> 1. [EBANX](https://www.ebanx.com/) [[@estevammr](https://github.com/estevammr) & [@nathangngencissk](https://github.com/nathangngencissk) & [@raafaadg](https://github.com/raafaadg) & [@whrocha](https://github.com/whrocha)]
<ide> 1. [Easy Taxi](http://www.easytaxi.com/) [[@caique-lima](https://github.com/caique-lima) & [@diraol](https://github.com/diraol)]
<add>1. [Elai Data](https://www.elaidata.com/) [[@lgov](https://github.com/lgov)]
<ide> 1. [EllisDon](http://www.ellisdon.com/) [[@d2kalra](https://github.com/d2kalra) & [@zbasama](https://github.com/zbasama)]
<ide> 1. [Endesa](https://www.endesa.com) [[@drexpp](https://github.com/drexpp)]
<ide> 1. [Enigma](https://www.enigma.com) [[@hydrosquall](https://github.com/hydrosquall)] | 1 |
Ruby | Ruby | fix style in test/core_ext/enumerable_test.rb | 8d791726e1a9d3d98367ecb4771d6dcc44cf5508 | <ide><path>activesupport/test/core_ext/enumerable_test.rb
<ide> def test_doesnt_bust_constant_cache
<ide> end
<ide>
<ide> private
<del>
<del> def constant_cache_invalidations
<del> RubyVM.stat(:constant_cache_invalidations)
<del> rescue ArgumentError
<del> RubyVM.stat(:global_constant_state) # RUBY_VERSION < "3.2"
<del> end
<add> def constant_cache_invalidations
<add> RubyVM.stat(:constant_cache_invalidations)
<add> rescue ArgumentError
<add> RubyVM.stat(:global_constant_state) # RUBY_VERSION < "3.2"
<add> end
<ide> end | 1 |
Ruby | Ruby | install bundler 2 | 128300a754eb1539691ce868efbc51b268b9e802 | <ide><path>Library/Homebrew/utils/gems.rb
<ide> def setup_gem_environment!(gem_home: nil, gem_bindir: nil)
<ide> ENV["PATH"] = paths.compact.join(":")
<ide> end
<ide>
<del> def install_gem!(name, version = nil, setup_gem_environment: true)
<add> def install_gem!(name, version: nil, setup_gem_environment: true)
<ide> setup_gem_environment! if setup_gem_environment
<ide> return unless Gem::Specification.find_all_by_name(name, version).empty?
<ide>
<ide> def install_gem!(name, version = nil, setup_gem_environment: true)
<ide> odie_if_defined "failed to install the '#{name}' gem."
<ide> end
<ide>
<del> def install_gem_setup_path!(name, executable: name, setup_gem_environment: true)
<del> install_gem!(name, setup_gem_environment: setup_gem_environment)
<add> def install_gem_setup_path!(name, version: nil, executable: name, setup_gem_environment: true)
<add> install_gem!(name, version: version, setup_gem_environment: setup_gem_environment)
<ide> return if ENV["PATH"].split(":").any? do |path|
<ide> File.executable?("#{path}/#{executable}")
<ide> end
<ide> def install_gem_setup_path!(name, executable: name, setup_gem_environment: true)
<ide>
<ide> def install_bundler!
<ide> setup_gem_environment!(gem_home: Gem.user_dir, gem_bindir: gem_user_bindir)
<del> install_gem_setup_path!("bundler", executable: "bundle", setup_gem_environment: false)
<add> install_gem_setup_path!("bundler", version: ">=2", executable: "bundle", setup_gem_environment: false)
<ide> end
<ide>
<ide> def install_bundler_gems! | 1 |
Javascript | Javascript | fix changeeventplugin dependencies | 79beb71d69c8c0c6c6c3ee432f9d7c335ed3157a | <ide><path>src/eventPlugins/ChangeEventPlugin.js
<ide> var eventTypes = {
<ide> dependencies: [
<ide> topLevelTypes.topBlur,
<ide> topLevelTypes.topChange,
<add> topLevelTypes.topClick,
<ide> topLevelTypes.topFocus,
<ide> topLevelTypes.topInput,
<ide> topLevelTypes.topKeyDown,
<del> topLevelTypes.topKeyUp
<add> topLevelTypes.topKeyUp,
<add> topLevelTypes.topSelectionChange
<ide> ]
<ide> }
<ide> }; | 1 |
Ruby | Ruby | fix argumenterror message for without method | 70dec80388965074d51ebffa5e57526a426d3556 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def excluding(*records)
<ide> records.compact!
<ide>
<ide> unless records.all?(klass)
<del> raise ArgumentError, "You must only pass a single or collection of #{klass.name} objects to #excluding."
<add> raise ArgumentError, "You must only pass a single or collection of #{klass.name} objects to ##{__callee__}."
<ide> end
<ide>
<ide> spawn.excluding!(records)
<ide><path>activerecord/test/cases/excluding_test.rb
<ide> def test_does_not_exclude_records_when_no_arguments
<ide> def test_raises_on_record_from_different_class
<ide> error = assert_raises(ArgumentError) { Post.excluding(@post, comments(:greetings)) }
<ide> assert_equal "You must only pass a single or collection of Post objects to #excluding.", error.message
<add>
<add> error = assert_raises(ArgumentError) { Post.without(@post, comments(:greetings)) }
<add> assert_equal "You must only pass a single or collection of Post objects to #without.", error.message
<ide> end
<ide>
<ide> private | 2 |
Python | Python | use utility method to get the object download path | d6da648589f88d2536261f78b4e62781c3f015e3 | <ide><path>libcloud/storage/drivers/backblaze_b2.py
<ide> from libcloud.utils.py3 import b
<ide> from libcloud.utils.py3 import httplib
<ide> from libcloud.utils.py3 import urlparse
<add>from libcloud.utils.files import read_in_chunks
<ide>
<ide> from libcloud.common.base import ConnectionUserAndKey
<ide> from libcloud.common.base import JsonResponse
<ide> def __init__(self, *args, **kwargs):
<ide> self._auth_conn = BackblazeB2AuthConnection(*args, **kwargs)
<ide>
<ide> def request(self, action, params=None, data=None, headers=None,
<del> method='GET', raw=False, include_account_id=False):
<add> method='GET', raw=False, include_account_id=False,
<add> download_request=False):
<ide> params = params or {}
<ide> headers = headers or {}
<ide>
<ide> def upload_object(self, file_path, container, object_name, extra=None,
<ide>
<ide> def download_object(self, obj, destination_path, overwrite_existing=False,
<ide> delete_on_failure=True):
<del> # TODO: Escape name
<del> action = obj.container.name + '/' + obj.name
<del> response = self.connection.request(action=action, method='GET', raw=True)
<add> action = self._get_object_download_path(container=obj.container,
<add> obj=obj)
<add> response = self.connection.request(action=action, method='GET',
<add> raw=True)
<ide>
<ide> # TODO: Include metadata from response headers
<ide> return self._get_object(obj=obj, callback=self._save_object,
<ide> def download_object(self, obj, destination_path, overwrite_existing=False,
<ide> success_status_code=httplib.OK)
<ide>
<ide> def download_object_as_stream(self, obj, chunk_size=None):
<del> action = obj.container.name + '/' + obj.name
<del> response = self.connection.request(action=action, method='GET', raw=True)
<add> action = self._get_object_download_path(container=obj.container,
<add> obj=obj)
<add> response = self.connection.request(action=action, method='GET',
<add> raw=True)
<ide>
<ide> return self._get_object(obj=obj, callback=read_in_chunks,
<ide> response=response,
<ide> def _to_object(self, item, container=None):
<ide> obj = Object(name=item['fileName'], size=size, hash=hash, extra=extra,
<ide> meta_data=meta_data, container=container, driver=self)
<ide> return obj
<add>
<add> def _get_object_download_path(self, container, obj):
<add> """
<add> Return a path used in the download requests.
<add>
<add> :rtype: ``str``
<add> """
<add> path = container.name + '/' + obj.name
<add> return path | 1 |
Java | Java | remove cycles in compositeexception | eea2afa295410dc080cc20aa8b75ce649c459cec | <ide><path>rxjava-core/src/main/java/rx/exceptions/CompositeException.java
<ide> public final class CompositeException extends RuntimeException {
<ide> public CompositeException(String messagePrefix, Collection<Throwable> errors) {
<ide> List<Throwable> _exceptions = new ArrayList<Throwable>();
<ide> CompositeExceptionCausalChain _cause = new CompositeExceptionCausalChain();
<del> int count = 0;
<add> int count = errors.size();
<add> errors = removeDuplicatedCauses(errors);
<ide> for (Throwable e : errors) {
<del> count++;
<ide> attachCallingThreadStack(_cause, e);
<ide> _exceptions.add(e);
<ide> }
<ide> public synchronized Throwable getCause() {
<ide> return cause;
<ide> }
<ide>
<add> private Collection<Throwable> removeDuplicatedCauses(Collection<Throwable> errors) {
<add> Set<Throwable> duplicated = new HashSet<Throwable>();
<add> for (Throwable cause : errors) {
<add> for (Throwable error : errors) {
<add> if(cause == error || duplicated.contains(error)) {
<add> continue;
<add> }
<add> while (error.getCause() != null) {
<add> error = error.getCause();
<add> if (error == cause) {
<add> duplicated.add(cause);
<add> break;
<add> }
<add> }
<add> }
<add> }
<add> if (!duplicated.isEmpty()) {
<add> errors = new ArrayList<Throwable>(errors);
<add> errors.removeAll(duplicated);
<add> }
<add> return errors;
<add> }
<add>
<ide> @SuppressWarnings("unused")
<ide> // useful when debugging but don't want to make part of publicly supported API
<ide> private static String getStackTraceAsString(StackTraceElement[] stack) {
<ide><path>rxjava-core/src/test/java/rx/exceptions/CompositeExceptionTest.java
<ide> public void testMultipleWithSameCause() {
<ide>
<ide> }
<ide>
<add> @Test(timeout = 1000)
<add> public void testOneIsCauseOfAnother() {
<add> Throwable rootCause = new Throwable("RootCause");
<add> Throwable throwable = new Throwable("1", rootCause);
<add> CompositeException ce = new CompositeException("One is the cause of another",
<add> Arrays.asList(rootCause, throwable));
<add>
<add> assertEquals(1, ce.getExceptions().size());
<add> }
<add>
<ide> @Test(timeout = 1000)
<ide> public void testAttachCallingThreadStackParentThenChild() {
<ide> CompositeException.attachCallingThreadStack(ex1, ex2); | 2 |
Go | Go | refactor the init function in docker_utils.go | 50d5d55f566b65b506bf54ccf0d897a0cb95734e | <ide><path>integration-cli/docker_utils.go
<ide> import (
<ide> )
<ide>
<ide> func init() {
<del> cmd := exec.Command(dockerBinary, "images")
<add> cmd := exec.Command(dockerBinary, "images", "-f", "dangling=false", "--format", "{{.Repository}}:{{.Tag}}")
<ide> cmd.Env = appendBaseEnv(true)
<ide> out, err := cmd.CombinedOutput()
<ide> if err != nil {
<ide> panic(fmt.Errorf("err=%v\nout=%s\n", err, out))
<ide> }
<del> lines := strings.Split(string(out), "\n")[1:]
<del> for _, l := range lines {
<del> if l == "" {
<del> continue
<del> }
<del> fields := strings.Fields(l)
<del> imgTag := fields[0] + ":" + fields[1]
<del> // just for case if we have dangling images in tested daemon
<del> if imgTag != "<none>:<none>" {
<del> protectedImages[imgTag] = struct{}{}
<del> }
<add> images := strings.Split(strings.TrimSpace(string(out)), "\n")
<add> for _, img := range images {
<add> protectedImages[img] = struct{}{}
<ide> }
<ide>
<del> // Obtain the daemon platform so that it can be used by tests to make
<del> // intelligent decisions about how to configure themselves, and validate
<del> // that the target platform is valid.
<del> res, _, err := sockRequestRaw("GET", "/version", nil, "application/json")
<del> if err != nil || res == nil || (res != nil && res.StatusCode != http.StatusOK) {
<del> panic(fmt.Errorf("Init failed to get version: %v. Res=%v", err.Error(), res))
<add> res, body, err := sockRequestRaw("GET", "/info", nil, "application/json")
<add> if err != nil {
<add> panic(fmt.Errorf("Init failed to get /info: %v", err))
<ide> }
<add> defer body.Close()
<add> if res.StatusCode != http.StatusOK {
<add> panic(fmt.Errorf("Init failed to get /info. Res=%v", res))
<add> }
<add>
<ide> svrHeader, _ := httputils.ParseServerHeader(res.Header.Get("Server"))
<ide> daemonPlatform = svrHeader.OS
<ide> if daemonPlatform != "linux" && daemonPlatform != "windows" {
<ide> panic("Cannot run tests against platform: " + daemonPlatform)
<ide> }
<ide>
<del> // On Windows, extract out the version as we need to make selective
<del> // decisions during integration testing as and when features are implemented.
<del> if daemonPlatform == "windows" {
<del> if body, err := ioutil.ReadAll(res.Body); err == nil {
<del> var server types.Version
<del> if err := json.Unmarshal(body, &server); err == nil {
<del> // eg in "10.0 10550 (10550.1000.amd64fre.branch.date-time)" we want 10550
<del> windowsDaemonKV, _ = strconv.Atoi(strings.Split(server.KernelVersion, " ")[1])
<del> }
<del> }
<del> }
<del>
<ide> // Now we know the daemon platform, can set paths used by tests.
<del> _, body, err := sockRequest("GET", "/info", nil)
<add> var info types.Info
<add> err = json.NewDecoder(body).Decode(&info)
<ide> if err != nil {
<del> panic(err)
<add> panic(fmt.Errorf("Init failed to unmarshal docker info: %v", err))
<ide> }
<ide>
<del> var info types.Info
<del> err = json.Unmarshal(body, &info)
<ide> dockerBasePath = info.DockerRootDir
<ide> volumesConfigPath = filepath.Join(dockerBasePath, "volumes")
<ide> containerStoragePath = filepath.Join(dockerBasePath, "containers")
<ide> func init() {
<ide> if daemonPlatform == "windows" {
<ide> volumesConfigPath = strings.Replace(volumesConfigPath, `/`, `\`, -1)
<ide> containerStoragePath = strings.Replace(containerStoragePath, `/`, `\`, -1)
<add> // On Windows, extract out the version as we need to make selective
<add> // decisions during integration testing as and when features are implemented.
<add> // eg in "10.0 10550 (10550.1000.amd64fre.branch.date-time)" we want 10550
<add> windowsDaemonKV, _ = strconv.Atoi(strings.Split(info.KernelVersion, " ")[1])
<ide> } else {
<ide> volumesConfigPath = strings.Replace(volumesConfigPath, `\`, `/`, -1)
<ide> containerStoragePath = strings.Replace(containerStoragePath, `\`, `/`, -1) | 1 |
PHP | PHP | remove unnecessary variable assignment | e75304c7f87273cb11f70003dc34ce85a3c7807b | <ide><path>src/Error/ErrorTrap.php
<ide> public function handleError(
<ide> */
<ide> public function renderer(): ErrorRendererInterface
<ide> {
<del> $class = $this->_getConfig('errorRenderer');
<del> if (!$class) {
<del> $class = $this->chooseErrorRenderer();
<del> }
<add> /** @var class-string<\Cake\Error\ErrorRendererInterface> $class */
<add> $class = $this->_getConfig('errorRenderer') ?: $this->chooseErrorRenderer();
<ide> if (!in_array(ErrorRendererInterface::class, class_implements($class))) {
<ide> throw new InvalidArgumentException(
<ide> "Cannot use {$class} as an error renderer. It must implement \Cake\Error\ErrorRendererInterface."
<ide> );
<ide> }
<ide>
<del> /** @var \Cake\Error\ErrorRendererInterface $instance */
<del> $instance = new $class($this->_config);
<del>
<del> return $instance;
<add> return new $class($this->_config);
<ide> }
<ide>
<ide> /**
<ide> public function renderer(): ErrorRendererInterface
<ide> */
<ide> public function logger(): ErrorLoggerInterface
<ide> {
<del> $class = $this->_getConfig('logger');
<del> if (!$class) {
<del> $class = $this->_defaultConfig['logger'];
<del> }
<add> /** @var class-string<\Cake\Error\ErrorLoggerInterface> $class */
<add> $class = $this->_getConfig('logger', $this->_defaultConfig['logger']);
<ide> if (!in_array(ErrorLoggerInterface::class, class_implements($class))) {
<ide> throw new InvalidArgumentException(
<ide> "Cannot use {$class} as an error logger. It must implement \Cake\Error\ErrorLoggerInterface."
<ide> );
<ide> }
<ide>
<del> /** @var \Cake\Error\ErrorLoggerInterface $instance */
<del> $instance = new $class($this->_config);
<del>
<del> return $instance;
<add> return new $class($this->_config);
<ide> }
<ide> }
<ide><path>src/Error/ExceptionTrap.php
<ide> public function renderer(Throwable $exception, $request = null)
<ide> }
<ide>
<ide> if (is_string($class)) {
<del> /** @var class-string $class */
<add> /** @var class-string<\Cake\Error\ExceptionRendererInterface> $class */
<ide> if (!(method_exists($class, 'render') && method_exists($class, 'write'))) {
<ide> throw new InvalidArgumentException(
<ide> "Cannot use {$class} as an `exceptionRenderer`. " .
<ide> 'It must implement render() and write() methods.'
<ide> );
<ide> }
<ide>
<del> /** @var \Cake\Error\ExceptionRendererInterface $instance */
<del> $instance = new $class($exception, $request, $this->_config);
<del>
<del> return $instance;
<add> return new $class($exception, $request, $this->_config);
<ide> }
<ide>
<ide> return $class($exception, $request);
<ide> protected function chooseRenderer(): string
<ide> */
<ide> public function logger(): ErrorLoggerInterface
<ide> {
<del> $class = $this->_getConfig('logger');
<del> if (!$class) {
<del> $class = $this->_defaultConfig['logger'];
<del> }
<add> /** @var class-string<\Cake\Error\ErrorLoggerInterface> $class */
<add> $class = $this->_getConfig('logger', $this->_defaultConfig['logger']);
<ide> if (!in_array(ErrorLoggerInterface::class, class_implements($class))) {
<ide> throw new InvalidArgumentException(
<ide> "Cannot use {$class} as an exception logger. " .
<ide> "It must implement \Cake\Error\ErrorLoggerInterface."
<ide> );
<ide> }
<ide>
<del> /** @var \Cake\Error\ErrorLoggerInterface $instance */
<del> $instance = new $class($this->_config);
<del>
<del> return $instance;
<add> return new $class($this->_config);
<ide> }
<ide>
<ide> /** | 2 |
Text | Text | update links of pluralization in i18n guide | bb8e892ea07d1677cd93ac2f17aeb9c299926a7e | <ide><path>guides/source/i18n.md
<ide> end
<ide>
<ide> ### Pluralization
<ide>
<del>In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ([Arabic](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ar), [Japanese](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ja), [Russian](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ru) and many more) have different grammars that have additional or fewer [plural forms](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html). Thus, the I18n API provides a flexible pluralization feature.
<add>In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ([Arabic](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ar), [Japanese](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ja), [Russian](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ru) and many more) have different grammars that have additional or fewer [plural forms](http://cldr.unicode.org/index/cldr-spec/plural-rules). Thus, the I18n API provides a flexible pluralization feature.
<ide>
<ide> The `:count` interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:
<ide> | 1 |
Text | Text | add antsmartian to collaborators | c3474f511e7ca7fe7fb9182c7f3ce8e3b2e6e577 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Andreas Madsen** <amwebdk@gmail.com> (he/him)
<ide> * [AnnaMag](https://github.com/AnnaMag) -
<ide> **Anna M. Kedzierska** <anna.m.kedzierska@gmail.com>
<add>* [antsmartian](https://github.com/antsmartian) -
<add>**Anto Aravinth** <anto.aravinth.cse@gmail.com> (he/him)
<ide> * [apapirovski](https://github.com/apapirovski) -
<ide> **Anatoli Papirovski** <apapirovski@mac.com> (he/him)
<ide> * [aqrln](https://github.com/aqrln) - | 1 |
PHP | PHP | make view from command | a9f74f7e7f495f34418c1158d6c1ae3e80d3cd6d | <ide><path>src/Illuminate/Foundation/Console/ComponentMakeCommand.php
<ide> namespace Illuminate\Foundation\Console;
<ide>
<ide> use Illuminate\Console\GeneratorCommand;
<add>use Illuminate\Foundation\Inspiring;
<ide> use Illuminate\Support\Str;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide>
<ide> class ComponentMakeCommand extends GeneratorCommand
<ide> */
<ide> protected $type = 'Component';
<ide>
<add> /**
<add> * Execute the console command.
<add> *
<add> * @return void
<add> */
<add> public function handle()
<add> {
<add> if (parent::handle() === false && ! $this->option('force')) {
<add> return false;
<add> }
<add>
<add> if ($this->input->getParameterOption('--view') !== false) {
<add> $this->writeView();
<add> }
<add> }
<add>
<add> /**
<add> * Write the view for the component.
<add> *
<add> * @return void
<add> */
<add> protected function writeView()
<add> {
<add> $view = $this->option('view')
<add> ? $this->option('view')
<add> : 'components.'.Str::kebab(class_basename($this->argument('name')));
<add>
<add> $path = resource_path('views').'/'.str_replace('.', '/', $view);
<add>
<add> if (! $this->files->isDirectory(dirname($path))) {
<add> $this->files->makeDirectory(dirname($path), 0777, true, true);
<add> }
<add>
<add> file_put_contents(
<add> $path.'.blade.php',
<add> "<div>
<add> <!-- ".Inspiring::quote()." -->
<add></div>"
<add> );
<add> }
<add>
<ide> /**
<ide> * Build the class with the given name.
<ide> *
<ide> protected function getDefaultNamespace($rootNamespace)
<ide> protected function getOptions()
<ide> {
<ide> return [
<add> ['force', null, InputOption::VALUE_NONE, 'Create the class even if the component already exists'],
<ide> ['view', null, InputOption::VALUE_OPTIONAL, 'Create a new Blade template for the component'],
<ide> ];
<ide> } | 1 |
Javascript | Javascript | remove unneeded comma in webglprogram | b3491e78c1eeb6d8bf88509d6c2bf73774bb268e | <ide><path>src/renderers/webgl/WebGLProgram.js
<ide> function generateExtensions( extensions, parameters, rendererExtensions ) {
<ide> ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
<ide> ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
<ide> ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
<del> ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
<add> ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
<ide> ];
<ide>
<ide> return chunks.filter( filterEmptyLine ).join( '\n' ); | 1 |
Ruby | Ruby | allow extra arguments for observers | 24c068d67dab4559ab24f77482cd671563161ec2 | <ide><path>activemodel/lib/active_model/observing.rb
<ide> def inherited(subclass)
<ide> private
<ide> # Fires notifications to model's observers
<ide> #
<del> # def save
<del> # notify_observers(:before_save)
<del> # ...
<del> # notify_observers(:after_save)
<del> # end
<del> def notify_observers(method)
<del> self.class.notify_observers(method, self)
<add> # def save
<add> # notify_observers(:before_save)
<add> # ...
<add> # notify_observers(:after_save)
<add> # end
<add> #
<add> # Custom notifications can be sent in a similar fashion:
<add> #
<add> # notify_observers(:custom_notification, :foo)
<add> #
<add> # This will call +custom_notification+, passing as arguments
<add> # the current object and :foo.
<add> #
<add> def notify_observers(method, *extra_args)
<add> self.class.notify_observers(method, self, *extra_args)
<ide> end
<ide> end
<ide>
<ide> def observed_classes #:nodoc:
<ide>
<ide> # Send observed_method(object) if the method exists and
<ide> # the observer is enabled for the given object's class.
<del> def update(observed_method, object, &block) #:nodoc:
<add> def update(observed_method, object, *extra_args, &block) #:nodoc:
<ide> return unless respond_to?(observed_method)
<ide> return if disabled_for?(object)
<del> send(observed_method, object, &block)
<add> send(observed_method, object, *extra_args, &block)
<ide> end
<ide>
<ide> # Special method sent by the observed class when it is inherited.
<ide><path>activemodel/test/cases/observing_test.rb
<ide> class << self
<ide>
<ide> attr_accessor :stub
<ide>
<del> def on_spec(record)
<del> stub.event_with(record) if stub
<add> def on_spec(record, *args)
<add> stub.event_with(record, *args) if stub
<ide> end
<ide>
<ide> def around_save(record)
<ide> def teardown
<ide> Foo.send(:notify_observers, :on_spec, foo)
<ide> end
<ide>
<add> test "passes extra arguments" do
<add> foo = Foo.new
<add> FooObserver.instance.stub = stub
<add> FooObserver.instance.stub.expects(:event_with).with(foo, :bar)
<add> Foo.send(:notify_observers, :on_spec, foo, :bar)
<add> end
<add>
<ide> test "skips nonexistent observer event" do
<ide> foo = Foo.new
<ide> Foo.send(:notify_observers, :whatever, foo) | 2 |
Javascript | Javascript | remove the line requiring events | e2581696669003fdd691c167ff1500ef16dddb32 | <ide><path>lib/util.js
<ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<del>var events = require('events');
<del>
<del>
<ide> var formatRegExp = /%[sdj%]/g;
<ide> exports.format = function(f) {
<ide> if (typeof f !== 'string') { | 1 |
Javascript | Javascript | remove console.disableyellowbox support | b633cc130533f0731b2577123282c4530e4f0abe | <ide><path>Libraries/Core/ExceptionsManager.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<ide> * @format
<del> * @flow strict-local
<add> * @flow strict
<ide> */
<ide>
<ide> 'use strict';
<ide><path>Libraries/LogBox/Data/LogBoxData.js
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<del> * @flow strict-local
<add> * @flow strict
<ide> * @format
<ide> */
<ide>
<ide><path>Libraries/LogBox/Data/LogBoxLog.js
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<del> * @flow strict-local
<add> * @flow strict
<ide> * @format
<ide> */
<ide>
<ide><path>Libraries/LogBox/Data/LogBoxSymbolication.js
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<del> * @flow strict-local
<add> * @flow strict
<ide> * @format
<ide> */
<ide>
<ide><path>Libraries/LogBox/Data/parseLogBoxLog.js
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<del> * @flow strict-local
<add> * @flow strict
<ide> * @format
<ide> */
<ide>
<ide><path>Libraries/LogBox/LogBox.js
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<del> * @flow
<add> * @flow strict
<ide> * @format
<ide> */
<ide>
<ide> if (__DEV__) {
<ide> consoleErrorImpl = registerError;
<ide> consoleWarnImpl = registerWarning;
<ide>
<del> if ((console: any).disableYellowBox === true) {
<del> LogBoxData.setDisabled(true);
<del> console.warn(
<del> 'console.disableYellowBox has been deprecated and will be removed in a future release. Please use LogBox.ignoreAllLogs(value) instead.',
<del> );
<del> }
<del>
<del> (Object.defineProperty: any)(console, 'disableYellowBox', {
<del> configurable: true,
<del> get: () => LogBoxData.isDisabled(),
<del> set: value => {
<del> LogBoxData.setDisabled(value);
<del> console.warn(
<del> 'console.disableYellowBox has been deprecated and will be removed in a future release. Please use LogBox.ignoreAllLogs(value) instead.',
<del> );
<del> },
<del> });
<del>
<ide> if (Platform.isTesting) {
<ide> LogBoxData.setDisabled(true);
<ide> }
<ide> if (__DEV__) {
<ide> // After uninstalling: original > LogBox (noop) > OtherErrorHandler
<ide> consoleErrorImpl = originalConsoleError;
<ide> consoleWarnImpl = originalConsoleWarn;
<del> delete (console: any).disableLogBox;
<ide> },
<ide>
<ide> isInstalled(): boolean {
<ide> if (__DEV__) {
<ide> return typeof args[0] === 'string' && args[0].startsWith('(ADVICE)');
<ide> };
<ide>
<del> const isWarningModuleWarning = (...args: any) => {
<add> const isWarningModuleWarning = (...args: Array<mixed>) => {
<ide> return typeof args[0] === 'string' && args[0].startsWith('Warning: ');
<ide> };
<ide>
<ide><path>Libraries/LogBox/__tests__/LogBox-test.js
<ide> describe('LogBox', () => {
<ide> console.error = jest.fn();
<ide> console.log = jest.fn();
<ide> console.warn = jest.fn();
<del> console.disableYellowBox = false;
<ide> });
<ide>
<ide> afterEach(() => { | 7 |
Python | Python | make bigquery hook support pep 249 | 1aa30e21d6e5ceb7e5d65b0efdc987b39cdfd027 | <ide><path>airflow/contrib/hooks/bigquery_hook.py
<ide> import time
<ide>
<ide> from airflow.contrib.hooks.gc_base_hook import GoogleCloudBaseHook
<add>from airflow.hooks.dbapi_hook import DbApiHook
<ide> from apiclient.discovery import build
<ide> from pandas.io.gbq import GbqConnector, _parse_data as gbq_parse_data
<ide> from pandas.tools.merge import concat
<ide>
<ide> logging.getLogger("bigquery").setLevel(logging.INFO)
<ide>
<del>class BigQueryHook(GoogleCloudBaseHook):
<add>class BigQueryHook(GoogleCloudBaseHook, DbApiHook):
<ide> """
<ide> Interact with BigQuery. Connections must be defined with an extras JSON
<ide> field containing:
<ide> def __init__(self,
<ide> :param scope: The scope of the hook.
<ide> :type scope: string
<ide> """
<del> super(BigQueryHook, self).__init__(scope, bigquery_conn_id, delegate_to)
<add> super(BigQueryHook, self).__init__(
<add> scope=scope,
<add> conn_id=bigquery_conn_id,
<add> delegate_to=delegate_to)
<ide>
<ide> def get_conn(self):
<add> """
<add> Returns a BigQuery service object.
<add> """
<add> service = self.get_service()
<add> connection_extras = self._extras_dejson()
<add> project = connection_extras['project']
<add> return BigQueryConnection(service=service, project_id=project)
<add>
<add> def get_service(self):
<ide> """
<ide> Returns a BigQuery service object.
<ide> """
<ide> http_authorized = self._authorize()
<ide> return build('bigquery', 'v2', http=http_authorized)
<ide>
<del> def get_pandas_df(self, bql, parameters=None):
<del> """
<del> Returns a Pandas DataFrame for the results produced by a BigQuery
<del> query.
<add> def insert_rows(self, table, rows, target_fields=None, commit_every=1000):
<add> raise NotImplementedError()
<ide>
<del> :param bql: The BigQuery SQL to execute.
<del> :type bql: string
<del> """
<del> service = self.get_conn()
<del> connection_extras = self._extras_dejson()
<del> project = connection_extras['project']
<del> connector = BigQueryPandasConnector(project, service)
<del> schema, pages = connector.run_query(bql, verbose=False)
<del> dataframe_list = []
<add>class BigQueryConnection(object):
<add> """
<add> BigQuery does not have a notion of a persistent connection. Thus, these
<add> objects are small stateless factories for cursors, which do all the real
<add> work.
<add> """
<ide>
<del> while len(pages) > 0:
<del> page = pages.pop()
<del> dataframe_list.append(gbq_parse_data(schema, page))
<add> def __init__(self, *args, **kwargs):
<add> self._args = args
<add> self._kwargs = kwargs
<ide>
<del> if len(dataframe_list) > 0:
<del> return concat(dataframe_list, ignore_index=True)
<del> else:
<del> return gbq_parse_data(schema, [])
<add> def close(self):
<add> """ BigQueryConnection does not have anything to close. """
<add> pass
<add>
<add> def commit(self):
<add> """ BigQueryConnection does not support transactions. """
<add> pass
<add>
<add> def cursor(self):
<add> """ Return a new :py:class:`Cursor` object using the connection. """
<add> return BigQueryCursor(*self._args, **self._kwargs)
<ide>
<del> def run(self, bql, destination_dataset_table = False, write_disposition = 'WRITE_EMPTY'):
<add> def rollback(self):
<add> raise NotSupportedError("BigQueryConnection does not have transactions")
<add>
<add>class BigQueryBaseCursor(object):
<add> def __init__(self, service, project_id):
<add> self.service = service
<add> self.project_id = project_id
<add>
<add> def run_query(self, bql, destination_dataset_table = False, write_disposition = 'WRITE_EMPTY'):
<ide> """
<del> Executes a BigQuery SQL query. Either returns results and schema, or
<del> stores results in a BigQuery table, if destination is set. See here:
<add> Executes a BigQuery SQL query. Optionally persists results in a BigQuery
<add> table. See here:
<ide>
<ide> https://cloud.google.com/bigquery/docs/reference/v2/jobs
<ide>
<ide> def run(self, bql, destination_dataset_table = False, write_disposition = 'WRITE
<ide> :param write_disposition: What to do if the table already exists in
<ide> BigQuery.
<ide> """
<del> connection_extras = self._extras_dejson()
<del> project = connection_extras['project']
<ide> configuration = {
<ide> 'query': {
<del> 'query': bql,
<del> 'writeDisposition': write_disposition,
<add> 'query': bql
<ide> }
<ide> }
<ide>
<ide> if destination_dataset_table:
<ide> assert '.' in destination_dataset_table, \
<ide> 'Expected destination_dataset_table in the format of <dataset>.<table>. Got: {}'.format(destination_dataset_table)
<ide> destination_dataset, destination_table = destination_dataset_table.split('.', 1)
<del> configuration['query']['destinationTable'] = {
<del> 'projectId': project,
<del> 'datasetId': destination_dataset,
<del> 'tableId': destination_table,
<del> }
<add> configuration['query'].update({
<add> 'writeDisposition': write_disposition,
<add> 'destinationTable': {
<add> 'projectId': self.project_id,
<add> 'datasetId': destination_dataset,
<add> 'tableId': destination_table,
<add> }
<add> })
<ide>
<del> self.run_with_configuration(configuration)
<add> return self.run_with_configuration(configuration)
<ide>
<ide> def run_extract(self, source_dataset_table, destination_cloud_storage_uris, compression='NONE', export_format='CSV', field_delimiter=',', print_header=True):
<ide> """
<ide> def run_extract(self, source_dataset_table, destination_cloud_storage_uris, comp
<ide> assert '.' in source_dataset_table, \
<ide> 'Expected source_dataset_table in the format of <dataset>.<table>. Got: {}'.format(source_dataset_table)
<ide>
<del> connection_extras = self._extras_dejson()
<del> project = connection_extras['project']
<ide> source_dataset, source_table = source_dataset_table.split('.', 1)
<ide> configuration = {
<ide> 'extract': {
<ide> 'sourceTable': {
<del> 'projectId': project,
<add> 'projectId': self.project_id,
<ide> 'datasetId': source_dataset,
<ide> 'tableId': source_table,
<ide> },
<ide> def run_extract(self, source_dataset_table, destination_cloud_storage_uris, comp
<ide> }
<ide> }
<ide>
<del> self.run_with_configuration(configuration)
<add> return self.run_with_configuration(configuration)
<ide>
<ide> def run_with_configuration(self, configuration):
<ide> """
<ide> def run_with_configuration(self, configuration):
<ide> For more details about the configuration parameter.
<ide>
<ide> :param configuration: The configuration parameter maps directly to
<del> BigQuery's configuration field in the job object. See
<del> https://cloud.google.com/bigquery/docs/reference/v2/jobs for details.
<add> BigQuery's configuration field in the job object. See
<add> https://cloud.google.com/bigquery/docs/reference/v2/jobs for
<add> details.
<ide> """
<del> service = self.get_conn()
<del> connection_extras = self._extras_dejson()
<del> project = connection_extras['project']
<del> jobs = service.jobs()
<add> jobs = self.service.jobs()
<ide> job_data = {
<ide> 'configuration': configuration
<ide> }
<ide>
<ide> # Send query and wait for reply.
<ide> query_reply = jobs \
<del> .insert(projectId=project, body=job_data) \
<add> .insert(projectId=self.project_id, body=job_data) \
<ide> .execute()
<ide> job_id = query_reply['jobReference']['jobId']
<del> job = jobs.get(projectId=project, jobId=job_id).execute()
<add> job = jobs.get(projectId=self.project_id, jobId=job_id).execute()
<ide>
<ide> # Wait for query to finish.
<ide> while not job['status']['state'] == 'DONE':
<del> logging.info('Waiting for job to complete: %s, %s', project, job_id)
<add> logging.info('Waiting for job to complete: %s, %s', self.project_id, job_id)
<ide> time.sleep(5)
<del> job = jobs.get(projectId=project, jobId=job_id).execute()
<add> job = jobs.get(projectId=self.project_id, jobId=job_id).execute()
<ide>
<ide> # Check if job had errors.
<ide> if 'errorResult' in job['status']:
<ide> raise Exception('BigQuery job failed. Final error was: %s', job['status']['errorResult'])
<ide>
<del>class BigQueryPandasConnector(GbqConnector):
<add> return job_id
<add>
<add>class BigQueryCursor(BigQueryBaseCursor):
<ide> """
<del> This connector behaves identically to GbqConnector (from Pandas), except
<del> that it allows the service to be injected, and disables a call to
<del> self.get_credentials(). This allows Airflow to use BigQuery with Pandas
<del> without forcing a three legged OAuth connection. Instead, we can inject
<del> service account credentials into the binding.
<add> The PyHive PEP 249 implementation was used as a reference:
<add>
<add> https://github.com/dropbox/PyHive/blob/master/pyhive/presto.py
<add> https://github.com/dropbox/PyHive/blob/master/pyhive/common.py
<ide> """
<del> def __init__(self, project_id, service, reauth=False):
<del> self.test_google_api_imports()
<del> self.project_id = project_id
<del> self.reauth = reauth
<del> self.service = service
<add>
<add> def __init__(self, service, project_id):
<add> """
<add> # TODO param docs
<add> """
<add> super(BigQueryCursor, self).__init__(service=service, project_id=project_id)
<add> self.buffersize = None
<add> self.page_token = None
<add> self.job_id = None
<add> self.buffer = None
<add>
<add> @property
<add> def description(self):
<add> raise NotImplementedError
<add>
<add> def close(self):
<add> """ By default, do nothing """
<add> pass
<add>
<add> @property
<add> def rowcount(self):
<add> """ By default, return -1 to indicate that this is not supported. """
<add> return -1
<add>
<add> def execute(self, operation, parameters=None):
<add> """
<add> # TODO javadocs
<add> """
<add> bql = _bind_parameters(operation, parameters) if parameters else operation
<add> self.job_id = self.run_query(bql)
<add>
<add> def executemany(self, operation, seq_of_parameters):
<add> """
<add> Execute an operation multiple times with different parameters.
<add> """
<add> for parameters in seq_of_parameters:
<add> self.execute(operation, parameters)
<add>
<add> def fetchone(self):
<add> # TODO pydocs
<add> return self.next()
<add>
<add> def next(self):
<add> # TODO pydocs
<add> if not self.job_id:
<add> return None
<add>
<add> if not self.buffer or len(self.buffer) == 0:
<add> query_results = self.service.jobs().getQueryResults(projectId=self.project_id, jobId=self.job_id, pageToken=self.page_token).execute()
<add>
<add> if len(query_results['rows']) == 0:
<add> # Reset all state since we've exhausted the results.
<add> self.page_token = None
<add> self.job_id = None
<add> self.page_token = None
<add> return None
<add> else:
<add> self.page_token = query_results['page_token']
<add> rows = query_results['rows']
<add>
<add> for row in rows:
<add> self.buffer.append(map(lambda vs: vs['v'], row['f']))
<add>
<add> return self.buffer.pop(0)
<add>
<add> def fetchmany(self, size=None):
<add> """
<add> Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a
<add> list of tuples). An empty sequence is returned when no more rows are available.
<add> The number of rows to fetch per call is specified by the parameter. If it is not given, the
<add> cursor's arraysize determines the number of rows to be fetched. The method should try to
<add> fetch as many rows as indicated by the size parameter. If this is not possible due to the
<add> specified number of rows not being available, fewer rows may be returned.
<add> An :py:class:`~pyhive.exc.Error` (or subclass) exception is raised if the previous call to
<add> :py:meth:`execute` did not produce any result set or no call was issued yet.
<add> """
<add> if size is None:
<add> size = self.arraysize
<add> result = []
<add> for _ in xrange(size):
<add> one = self.fetchone()
<add> if one is None:
<add> break
<add> else:
<add> result.append(one)
<add> return result
<add>
<add> def fetchall(self):
<add> """
<add> Fetch all (remaining) rows of a query result, returning them as a sequence of sequences
<add> (e.g. a list of tuples).
<add> """
<add> result = []
<add> while True:
<add> one = self.fetchone()
<add> if one is None:
<add> break
<add> else:
<add> result.append(one)
<add> return result
<add>
<add> def get_arraysize(self):
<add> # PEP 249
<add> return self._buffersize if self.buffersize else 1
<add>
<add> def set_arraysize(self, arraysize):
<add> # PEP 249
<add> self.buffersize = arraysize
<add>
<add> arraysize = property(get_arraysize, set_arraysize)
<add>
<add> def setinputsizes(self, sizes):
<add> """ Does nothing by default """
<add> pass
<add>
<add> def setoutputsize(self, size, column=None):
<add> """ Does nothing by default """
<add> pass
<add>
<add>def _bind_parameters(operation, parameters):
<add> # inspired by MySQL Python Connector (conversion.py)
<add> string_parameters = {}
<add> for (name, value) in parameters.iteritems():
<add> if value is None:
<add> string_parameters[name] = 'NULL'
<add> elif isinstance(value, basestring):
<add> string_parameters[name] = "'" + _escape(value) + "'"
<add> else:
<add> string_parameters[name] = str(value)
<add> return operation % string_parameters
<add>
<add>def _escape(s):
<add> e = s
<add> e = e.replace('\\', '\\\\')
<add> e = e.replace('\n', '\\n')
<add> e = e.replace('\r', '\\r')
<add> e = e.replace("'", "\\'")
<add> e = e.replace('"', '\\"')
<add> return e
<ide><path>airflow/contrib/operators/bigquery_operator.py
<ide> def __init__(self,
<ide> def execute(self, context):
<ide> logging.info('Executing: %s', str(self.bql))
<ide> hook = BigQueryHook(bigquery_conn_id=self.bigquery_conn_id, delegate_to=self.delegate_to)
<del> hook.run(self.bql, self.destination_dataset_table, self.write_disposition)
<add> conn = hook.get_conn()
<add> cursor = conn.cursor()
<add> cursor.run_query(self.bql, self.destination_dataset_table, self.write_disposition)
<ide><path>airflow/contrib/operators/bigquery_to_gcs.py
<ide> def __init__(
<ide> def execute(self, context):
<ide> logging.info('Executing extract of %s into: %s', self.source_dataset_table, self.destination_cloud_storage_uris)
<ide> hook = BigQueryHook(bigquery_conn_id=self.bigquery_conn_id, delegate_to=self.delegate_to)
<del> hook.run_extract(
<add> conn = hook.get_conn()
<add> cursor = conn.cursor()
<add> cursor.run_extract(
<ide> self.source_dataset_table,
<ide> self.destination_cloud_storage_uris,
<ide> self.compression, | 3 |
Ruby | Ruby | fix documentation for #default | e1408971b8dfdd26d8dac4651bfa52683565f45a | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def mailer_name
<ide>
<ide> # Sets the defaults through app configuration:
<ide> #
<del> # config.action_mailer.default { from: "no-reply@example.org" }
<add> # config.action_mailer.default(from: "no-reply@example.org")
<ide> #
<ide> # Aliased by ::default_options=
<ide> def default(value = nil) | 1 |
Javascript | Javascript | remove unused parameter | ae6368dc6b7b02f65ba82e9661b6895855ee3cd5 | <ide><path>test/sequential/test-readline-interface.js
<ide> FakeInput.prototype.end = () => {};
<ide> crlfDelay
<ide> });
<ide> let callCount = 0;
<del> rli.on('line', function(line) {
<del> callCount++;
<del> });
<add> rli.on('line', () => callCount++);
<ide> fi.emit('data', '\r');
<ide> setTimeout(common.mustCall(() => {
<ide> fi.emit('data', '\n'); | 1 |
PHP | PHP | improve code readability | f6e1c7ca3d4ee9f7bbe8139fb490c7d9f3ae4637 | <ide><path>lib/Cake/Network/CakeResponse.php
<ide> public function header($header = null, $value = null) {
<ide> if (is_null($header)) {
<ide> return $this->_headers;
<ide> }
<del> if (!is_array($header)) {
<del> $header = array($header => $value);
<del> }
<del> foreach ($header as $h => $v) {
<del> if (is_numeric($h)) {
<del> list($h, $v) = array($v, null);
<add> $headers = is_array($header) ? $header : array($header => $value);
<add> foreach ($headers as $header => $value) {
<add> if (is_numeric($header)) {
<add> list($header, $value) = array($value, null);
<ide> }
<del> if (is_null($v)) {
<del> list($h, $v) = explode(':', $h, 2);
<add> if (is_null($value)) {
<add> list($header, $value) = explode(':', $header, 2);
<ide> }
<del> $this->_headers[$h] = (is_array($v)) ? array_map('trim', $v) : trim($v);
<add> $this->_headers[$header] = is_array($value) ? array_map('trim', $value) : trim($value);
<ide> }
<ide> return $this->_headers;
<ide> } | 1 |
Javascript | Javascript | add unittests to webglextensions | 384d1e9ac9c2d4f7b3e9f43ad980f2c5b915de92 | <ide><path>test/unit/src/renderers/webgl/WebGLExtensions.tests.js
<ide>
<ide> import { WebGLExtensions } from '../../../../../src/renderers/webgl/WebGLExtensions';
<ide>
<add>const WebglContextMock = function ( supportedExtensions ) {
<add>
<add> this.supportedExtensions = supportedExtensions || [];
<add> this.getExtension = function ( name ) {
<add>
<add> if ( this.supportedExtensions.indexOf( name ) > - 1 ) {
<add>
<add> return { 'name': name };
<add>
<add> } else {
<add>
<add> return null;
<add>
<add> }
<add>
<add> };
<add>
<add>};
<add>
<ide> export default QUnit.module( 'Renderers', () => {
<ide>
<ide> QUnit.module( 'WebGL', () => {
<ide>
<ide> QUnit.module( 'WebGLExtensions', () => {
<ide>
<ide> // INSTANCING
<del> QUnit.todo( "Instancing", ( assert ) => {
<add> QUnit.test( 'Instancing', ( assert ) => {
<add>
<add> const gl = new WebglContextMock();
<add> const extensions = new WebGLExtensions( gl );
<add> assert.ok( extensions !== undefined );
<add>
<add> } );
<add>
<add> QUnit.test( 'has', ( assert ) => {
<add>
<add> const gl = new WebglContextMock( [ 'Extension1', 'Extension2' ] );
<add> const extensions = new WebGLExtensions( gl );
<add> assert.ok( extensions.has( 'Extension1' ) );
<add> assert.ok( extensions.has( 'Extension2' ) );
<add> assert.ok( extensions.has( 'Extension1' ) );
<add> assert.notOk( extensions.has( 'NonExistingExtension' ) );
<add>
<add> } );
<add>
<add> QUnit.test( 'has (with aliasses)', ( assert ) => {
<add>
<add> const gl = new WebglContextMock( [ 'WEBKIT_WEBGL_depth_texture' ] );
<add> const extensions = new WebGLExtensions( gl );
<add> assert.ok( extensions.has( 'WEBGL_depth_texture' ) );
<add> assert.ok( extensions.has( 'WEBKIT_WEBGL_depth_texture' ) );
<add> assert.notOk( extensions.has( 'EXT_texture_filter_anisotropic' ) );
<add> assert.notOk( extensions.has( 'NonExistingExtension' ) );
<add>
<add> } );
<add>
<add> QUnit.test( 'get', ( assert ) => {
<add>
<add> const gl = new WebglContextMock( [ 'Extension1', 'Extension2' ] );
<add> const extensions = new WebGLExtensions( gl );
<add> assert.ok( extensions.get( 'Extension1' ) );
<add> assert.ok( extensions.get( 'Extension2' ) );
<add> assert.ok( extensions.get( 'Extension1' ) );
<add> assert.notOk( extensions.get( 'NonExistingExtension' ) );
<add>
<add> } );
<add>
<add> QUnit.test( 'get (with aliasses)', ( assert ) => {
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> const gl = new WebglContextMock( [ 'WEBKIT_WEBGL_depth_texture' ] );
<add> const extensions = new WebGLExtensions( gl );
<add> assert.ok( extensions.get( 'WEBGL_depth_texture' ) );
<add> assert.ok( extensions.get( 'WEBKIT_WEBGL_depth_texture' ) );
<add> assert.notOk( extensions.get( 'EXT_texture_filter_anisotropic' ) );
<add> assert.notOk( extensions.get( 'NonExistingExtension' ) );
<ide>
<ide> } );
<ide>
<del> // PUBLIC STUFF
<del> QUnit.todo( "get", ( assert ) => {
<add> QUnit.test( 'init', ( assert ) => {
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> const gl = new WebglContextMock();
<add> const extensions = new WebGLExtensions( gl );
<add> extensions.init( { isWebGL2: false } );
<add> assert.ok( extensions );
<add> const gl2 = new WebglContextMock();
<add> const extensions2 = new WebGLExtensions( gl2 );
<add> extensions2.init( { isWebGL2: true } );
<add> assert.ok( extensions2 );
<ide>
<ide> } );
<ide> | 1 |
PHP | PHP | fix failing tests | 25ee90ace4a8c8dc0af02fe250f2d11bda933e34 | <ide><path>lib/Cake/Test/Case/View/HelperTest.php
<ide> public function testUrlConversion() {
<ide> $this->assertEquals($result, '/controller/action/1?one=1&two=2');
<ide>
<ide> $result = $this->Helper->url(array('controller' => 'posts', 'action' => 'index', 'page' => '1" onclick="alert(\'XSS\');"'));
<del> $this->assertEquals($result, "/posts/index/page:1" onclick="alert('XSS');"");
<add> $this->assertEquals($result, "/posts/index/page:1%22%20onclick%3D%22alert%28%27XSS%27%29%3B%22");
<ide>
<ide> $result = $this->Helper->url('/controller/action/1/param:this+one+more');
<ide> $this->assertEquals($result, '/controller/action/1/param:this+one+more');
<ide> public function testUrlConversion() {
<ide> $result = $this->Helper->url(array(
<ide> 'controller' => 'posts', 'action' => 'index', 'param' => '%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24'
<ide> ));
<del> $this->assertEquals($result, "/posts/index/param:%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24");
<add> $this->assertEquals($result, "/posts/index/param:%257Baround%2520here%257D%255Bthings%255D%255Bare%255D%2524%2524");
<ide>
<ide> $result = $this->Helper->url(array(
<ide> 'controller' => 'posts', 'action' => 'index', 'page' => '1', | 1 |
Javascript | Javascript | replace crlf by lf in a fixture | 44bb140734a23bf57005dc39f34c707ed7e22469 | <ide><path>test/fixtures/test-error-first-line-offset.js
<del>error
<add>error | 1 |
Ruby | Ruby | update default match_data | 590aabe9d7d8d383c2be013e16e5fdf83942d584 | <ide><path>Library/Homebrew/livecheck/strategy/electron_builder.rb
<ide> def self.find_versions(url:, regex: nil, **_unused, &block)
<ide> raise ArgumentError, "#{T.must(name).demodulize} only supports a regex when using a `strategy` block"
<ide> end
<ide>
<del> match_data = { matches: {}, url: url }
<add> match_data = { matches: {}, regex: regex, url: url }
<ide>
<ide> match_data.merge!(Strategy.page_content(url))
<ide> content = match_data.delete(:content)
<ide><path>Library/Homebrew/livecheck/strategy/extract_plist.rb
<ide> def self.find_versions(cask:, regex: nil, **_unused, &block)
<ide> end
<ide> raise ArgumentError, "The #{T.must(name).demodulize} strategy only supports casks." unless T.unsafe(cask)
<ide>
<del> match_data = { matches: {} }
<add> match_data = { matches: {}, regex: regex }
<ide>
<ide> unversioned_cask_checker = UnversionedCaskChecker.new(cask)
<ide> items = unversioned_cask_checker.all_versions.transform_values { |v| Item.new(bundle_version: v) }
<ide><path>Library/Homebrew/livecheck/strategy/sparkle.rb
<ide> def self.find_versions(url:, regex: nil, **_unused, &block)
<ide> raise ArgumentError, "#{T.must(name).demodulize} only supports a regex when using a `strategy` block"
<ide> end
<ide>
<del> match_data = { matches: {}, url: url }
<add> match_data = { matches: {}, regex: regex, url: url }
<ide>
<ide> match_data.merge!(Strategy.page_content(url))
<ide> content = match_data.delete(:content) | 3 |
Go | Go | add agent initialization wait method in controller | a63fca344f857fbb7f51e16cbedae4e0929b2b2c | <ide><path>libnetwork/controller.go
<ide> type NetworkController interface {
<ide>
<ide> // SetClusterProvider sets cluster provider
<ide> SetClusterProvider(provider cluster.Provider)
<add>
<add> // Wait for agent initialization complete in libnetwork controller
<add> AgentInitWait()
<ide> }
<ide>
<ide> // NetworkWalker is a client provided function which will be used to walk the Networks.
<ide> type controller struct {
<ide> ingressSandbox *sandbox
<ide> sboxOnce sync.Once
<ide> agent *agent
<add> agentInitDone chan struct{}
<ide> sync.Mutex
<ide> }
<ide>
<ide> func New(cfgOptions ...config.Option) (NetworkController, error) {
<ide> sandboxes: sandboxTable{},
<ide> svcRecords: make(map[string]svcInfo),
<ide> serviceBindings: make(map[string]*service),
<add> agentInitDone: make(chan struct{}),
<ide> }
<ide>
<ide> if err := c.initStores(); err != nil {
<ide> func (c *controller) clusterAgentInit() {
<ide> }
<ide> return false
<ide> })
<add>
<add> if c.agent != nil {
<add> close(c.agentInitDone)
<add> }
<ide> }
<ide> }
<ide> if remoteAddr != "" {
<ide> func (c *controller) clusterAgentInit() {
<ide> }
<ide> }
<ide>
<add>// AgentInitWait waits for agent initialization to be completed in the
<add>// controller.
<add>func (c *controller) AgentInitWait() {
<add> <-c.agentInitDone
<add>}
<add>
<ide> func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
<ide> if c.cfg == nil {
<ide> return nil | 1 |
Ruby | Ruby | add input files to react-codegen script_phases | 959c6b795e96e39901ca8d952217bc81b7a9388a | <ide><path>scripts/react_native_pods.rb
<ide> def get_react_codegen_spec(options={})
<ide> return spec
<ide> end
<ide>
<add>def get_codegen_config_from_file(config_path, config_key)
<add> empty = {'libraries': []}
<add> if !File.exist?(config_path)
<add> return empty
<add> end
<add>
<add> config = JSON.parse(File.read(config_path))
<add> return config[config_key] ? config[config_key] : empty
<add>end
<add>
<ide> def get_react_codegen_script_phases(options={})
<ide> app_path = options[:app_path] ||= ''
<ide> if !app_path
<ide> def get_react_codegen_script_phases(options={})
<ide> # react_native_path should be relative already.
<ide> react_native_path = options[:react_native_path] ||= "../node_modules/react-native"
<ide>
<add> # Generate input files for in-app libaraies which will be used to check if the script needs to be run.
<add> # TODO: Ideally, we generate the input_files list from generate-artifacts.js and read the result here.
<add> # Or, generate this podspec in generate-artifacts.js as well.
<add> config_key = options[:config_key] ||= 'codegenConfig'
<add> app_package_path = File.join(app_path, 'package.json')
<add> app_codegen_config = get_codegen_config_from_file(app_package_path, config_key)
<add> file_list = []
<add> app_codegen_config['libraries'].each do |library|
<add> library_dir = File.join(app_path, library['jsSrcsDir'])
<add> file_list.concat (`find #{library_dir} -type f \\( -name "Native*.js" -or -name "*NativeComponent.js" \\)`.split("\n").sort)
<add> end
<add> input_files = file_list.map { |filename| "${PODS_ROOT}/../#{Pathname.new(filename).relative_path_from(Pod::Config.instance.installation_root)}" }
<add>
<ide> # Add a script phase to trigger generate artifact.
<ide> # Some code is duplicated so that it's easier to delete the old way and switch over to this once it's stabilized.
<ide> return {
<ide> 'name': 'Generate Specs',
<ide> 'execution_position': :before_compile,
<del> 'input_files' => ['${DERIVED_FILE_DIR}/.tmpfile'],
<add> 'input_files' => input_files,
<ide> 'show_env_vars_in_log': true,
<ide> 'output_files': ["${DERIVED_FILE_DIR}/react-codegen.log"],
<ide> 'script': %{set -o pipefail
<ide> set -e
<ide>
<del># A known hack to run this script every time.
<del># TODO: Further improvement will be to specify actual input files
<del># so that it doesn't have to rebuild libraries every time.
<del>touch "${SCRIPT_INPUT_FILE_0}"
<del>
<ide> pushd "${PODS_ROOT}/../" > /dev/null
<ide> POD_INSTALLATION_ROOT=$(pwd)
<ide> popd >/dev/null | 1 |
Ruby | Ruby | invoke html_escape on the proper receiver | 901973b4d73ceb46cedc2490d75122dce5d06f04 | <ide><path>actionpack/lib/action_view/helpers/number_helper.rb
<ide> def number_to_phone(number, options = {})
<ide> str << "+#{country_code}#{delimiter}" unless country_code.blank?
<ide> str << number
<ide> str << " x #{extension}" unless extension.blank?
<del> html_escape(str)
<add> ERB::Util.html_escape(str)
<ide> end
<ide>
<ide> # Formats a +number+ into a currency string (e.g., $13.65). You can customize the format | 1 |
Ruby | Ruby | simplify benchmarking and rescue | 3be9134d1cb882f4be3be8d57b2f8bde5ecde887 | <ide><path>actionpack/lib/action_controller/base.rb
<ide> class Base
<ide> # Controller specific instance variables which will not be accessible inside views.
<ide> @@protected_instance_variables = %w(@assigns @performed_redirect @performed_render @variables_added @request_origin @url @parent_controller
<ide> @action_name @before_filter_chain_aborted @action_cache_path @_session @_cookies @_headers @_params
<del> @_flash @_response)
<add> @_flash @_response @_runtime)
<ide>
<ide> # Prepends all the URL-generating helpers from AssetHelper. This makes it possible to easily move javascripts, stylesheets,
<ide> # and images to a dedicated asset server away from the main web server. Example:
<ide> def append_view_path(path)
<ide> #
<ide> # render :xml => post.to_xml, :status => :created, :location => post_url(post)
<ide> def render(options = nil, extra_options = {}, &block) #:doc:
<add> start = Time.now
<add> reset_db_runtime
<add>
<ide> raise DoubleRenderError, "Can only render or redirect once per action" if performed?
<ide>
<ide> if options.nil?
<ide> def render(options = nil, extra_options = {}, &block) #:doc:
<ide> render_for_file(default_template_name, options[:status], layout)
<ide> end
<ide> end
<add> ensure
<add> @_runtime[:render] = Time.now - start
<add> log_render_benchmark
<ide> end
<ide>
<ide> # Renders according to the same rules as <tt>render</tt>, but returns the result in a string instead
<ide> def assign_shortcuts(request, response)
<ide> @template = @_response.template
<ide>
<ide> @_headers = @_response.headers
<add> @_runtime = {}
<ide> end
<ide>
<ide> def initialize_current_url
<ide> def default_render #:nodoc:
<ide> end
<ide>
<ide> def perform_action
<add> start = Time.now
<add>
<ide> if action_methods.include?(action_name)
<ide> send(action_name)
<ide> default_render unless performed?
<ide> def perform_action
<ide> else
<ide> raise UnknownAction, "No action responded to #{action_name}. Actions: #{action_methods.sort.to_sentence}", caller
<ide> end
<add> rescue Exception => exception
<add> rescue_action(exception)
<add> ensure
<add> @_runtime[:perform_action] = Time.now - start
<add> log_benchmarks
<ide> end
<ide>
<ide> def performed?
<ide><path>actionpack/lib/action_controller/benchmarking.rb
<ide> module ActionController #:nodoc:
<ide> module Benchmarking #:nodoc:
<ide> def self.included(base)
<ide> base.extend(ClassMethods)
<del>
<del> base.class_eval do
<del> alias_method_chain :perform_action, :benchmark
<del> alias_method_chain :render, :benchmark
<del> end
<ide> end
<ide>
<ide> module ClassMethods
<ide> def silence
<ide> end
<ide> end
<ide>
<del> protected
<del> def render_with_benchmark(options = nil, extra_options = {}, &block)
<del> if logger
<del> if Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
<del> db_runtime = ActiveRecord::Base.connection.reset_runtime
<del> end
<add> private
<ide>
<del> render_output = nil
<del> @view_runtime = Benchmark::realtime { render_output = render_without_benchmark(options, extra_options, &block) }
<add> def log_benchmarks
<add> return unless logger
<ide>
<del> if Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
<del> @db_rt_before_render = db_runtime
<del> @db_rt_after_render = ActiveRecord::Base.connection.reset_runtime
<del> @view_runtime -= @db_rt_after_render
<del> end
<add> seconds = [ @_runtime[:perform_action], 0.0001 ].max
<add> logging_view = @_runtime.has_key?(:render)
<add> logging_active_record = Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
<ide>
<del> render_output
<del> else
<del> render_without_benchmark(options, extra_options, &block)
<del> end
<del> end
<add> log_message = "Completed in #{sprintf("%.0f", seconds * 1000)}ms"
<ide>
<del> private
<del> def perform_action_with_benchmark
<del> if logger
<del> seconds = [ Benchmark::measure{ perform_action_without_benchmark }.real, 0.0001 ].max
<del> logging_view = defined?(@view_runtime)
<del> logging_active_record = Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
<del>
<del> log_message = "Completed in #{sprintf("%.0f", seconds * 1000)}ms"
<del>
<del> if logging_view || logging_active_record
<del> log_message << " ("
<del> log_message << view_runtime if logging_view
<del>
<del> if logging_active_record
<del> log_message << ", " if logging_view
<del> log_message << active_record_runtime + ")"
<del> else
<del> ")"
<del> end
<del> end
<del>
<del> log_message << " | #{headers["Status"]}"
<del> log_message << " [#{complete_request_uri rescue "unknown"}]"
<del>
<del> logger.info(log_message)
<del> response.headers["X-Runtime"] = "#{sprintf("%.0f", seconds * 1000)}ms"
<add> if logging_view || logging_active_record
<add> log_message << " ("
<add> log_message << view_runtime if logging_view
<add>
<add> if logging_active_record
<add> log_message << ", " if logging_view
<add> log_message << active_record_runtime + ")"
<ide> else
<del> perform_action_without_benchmark
<add> ")"
<ide> end
<ide> end
<ide>
<del> def view_runtime
<del> "View: %.0f" % (@view_runtime * 1000)
<add> log_message << " | #{headers["Status"]}"
<add> log_message << " [#{complete_request_uri rescue "unknown"}]"
<add>
<add> logger.info(log_message)
<add> response.headers["X-Runtime"] = "#{sprintf("%.0f", seconds * 1000)}ms"
<add> end
<add>
<add> def view_runtime
<add> "View: %.0f" % (@_runtime[:render] * 1000)
<add> end
<add>
<add> def active_record_runtime
<add> db_runtime = ActiveRecord::Base.connection.reset_runtime
<add>
<add> if @_runtime[:db_before_render]
<add> db_runtime += @_runtime[:db_before_render]
<add> db_runtime += @_runtime[:db_after_render]
<add> end
<add>
<add> "DB: %.0f" % (db_runtime * 1000)
<add> end
<add>
<add> def log_render_benchmark
<add> return unless logger
<add>
<add> if @_runtime.has_key?(:db_before_render)
<add> @_runtime[:db_after_render] = ActiveRecord::Base.connection.reset_runtime
<add> @_runtime[:render] -= @_runtime[:db_after_render]
<ide> end
<add> end
<ide>
<del> def active_record_runtime
<del> db_runtime = ActiveRecord::Base.connection.reset_runtime
<del> db_runtime += @db_rt_before_render if @db_rt_before_render
<del> db_runtime += @db_rt_after_render if @db_rt_after_render
<del> "DB: %.0f" % (db_runtime * 1000)
<add> def reset_db_runtime
<add> if logger && Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
<add> @_runtime[:db_before_render] = ActiveRecord::Base.connection.reset_runtime
<ide> end
<add> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_controller/rescue.rb
<ide> def self.included(base) #:nodoc:
<ide>
<ide> base.extend(ClassMethods)
<ide> base.send :include, ActiveSupport::Rescuable
<del>
<del> base.class_eval do
<del> alias_method_chain :perform_action, :rescue
<del> end
<ide> end
<ide>
<ide> module ClassMethods
<ide> def rescue_action_without_handler(exception)
<ide> end
<ide>
<ide> private
<del> def perform_action_with_rescue #:nodoc:
<del> perform_action_without_rescue
<del> rescue Exception => exception
<del> rescue_action(exception)
<del> end
<del>
<ide> def rescues_path(template_name)
<ide> "#{File.dirname(__FILE__)}/templates/rescues/#{template_name}.erb"
<ide> end | 3 |
Ruby | Ruby | fix method scoping test for postgresql | 3848634a4b2be4ce911a6a7167119a627cb36327 | <ide><path>activerecord/test/method_scoping_test.rb
<ide> def test_merged_scoped_find
<ide> poor_jamis = developers(:poor_jamis)
<ide> Developer.with_scope(:find => { :conditions => "salary < 100000" }) do
<ide> Developer.with_scope(:find => { :offset => 1 }) do
<del> assert_equal(poor_jamis, Developer.find(:first))
<add> assert_equal(poor_jamis, Developer.find(:first, :order => 'id asc'))
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | replace fixturedir with fixtures methods | 4826ac537f408304a8a208a2365d3bb415065c14 | <ide><path>test/parallel/test-fs-read.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> const assert = require('assert');
<del>const path = require('path');
<ide> const fs = require('fs');
<del>const filepath = path.join(common.fixturesDir, 'x.txt');
<add>const filepath = fixtures.path('x.txt');
<ide> const fd = fs.openSync(filepath, 'r');
<ide>
<ide> const expected = Buffer.from('xyz\n'); | 1 |
Go | Go | fix error in utils tests | 2e3b660dd0d49dc78f4c486e952ea6db9c007d6a | <ide><path>utils/utils_test.go
<ide> func TestWriteBroadcaster(t *testing.T) {
<ide>
<ide> // Test 1: Both bufferA and bufferB should contain "foo"
<ide> bufferA := &dummyWriter{}
<del> writer.AddWriter(bufferA)
<add> writer.AddWriter(bufferA, "")
<ide> bufferB := &dummyWriter{}
<del> writer.AddWriter(bufferB)
<add> writer.AddWriter(bufferB, "")
<ide> writer.Write([]byte("foo"))
<ide>
<ide> if bufferA.String() != "foo" {
<ide> func TestWriteBroadcaster(t *testing.T) {
<ide> // Test2: bufferA and bufferB should contain "foobar",
<ide> // while bufferC should only contain "bar"
<ide> bufferC := &dummyWriter{}
<del> writer.AddWriter(bufferC)
<add> writer.AddWriter(bufferC, "")
<ide> writer.Write([]byte("bar"))
<ide>
<ide> if bufferA.String() != "foobar" {
<ide> func TestWriteBroadcaster(t *testing.T) {
<ide> t.Errorf("Buffer contains %v", bufferC.String())
<ide> }
<ide>
<del> // Test3: Test removal
<del> writer.RemoveWriter(bufferB)
<del> writer.Write([]byte("42"))
<del> if bufferA.String() != "foobar42" {
<del> t.Errorf("Buffer contains %v", bufferA.String())
<del> }
<del> if bufferB.String() != "foobar" {
<del> t.Errorf("Buffer contains %v", bufferB.String())
<del> }
<del> if bufferC.String() != "bar42" {
<del> t.Errorf("Buffer contains %v", bufferC.String())
<del> }
<del>
<del> // Test4: Test eviction on failure
<add> // Test3: Test eviction on failure
<ide> bufferA.failOnWrite = true
<ide> writer.Write([]byte("fail"))
<del> if bufferA.String() != "foobar42" {
<add> if bufferA.String() != "foobar" {
<ide> t.Errorf("Buffer contains %v", bufferA.String())
<ide> }
<del> if bufferC.String() != "bar42fail" {
<add> if bufferC.String() != "barfail" {
<ide> t.Errorf("Buffer contains %v", bufferC.String())
<ide> }
<ide> // Even though we reset the flag, no more writes should go in there
<ide> bufferA.failOnWrite = false
<ide> writer.Write([]byte("test"))
<del> if bufferA.String() != "foobar42" {
<add> if bufferA.String() != "foobar" {
<ide> t.Errorf("Buffer contains %v", bufferA.String())
<ide> }
<del> if bufferC.String() != "bar42failtest" {
<add> if bufferC.String() != "barfailtest" {
<ide> t.Errorf("Buffer contains %v", bufferC.String())
<ide> }
<ide>
<ide> func TestRaceWriteBroadcaster(t *testing.T) {
<ide> writer := NewWriteBroadcaster()
<ide> c := make(chan bool)
<ide> go func() {
<del> writer.AddWriter(devNullCloser(0))
<add> writer.AddWriter(devNullCloser(0), "")
<ide> c <- true
<ide> }()
<ide> writer.Write([]byte("hello")) | 1 |
Javascript | Javascript | add component stacks to some warnings | 82c7ca4cca90976cd1230e03ea1a4372a4276e67 | <ide><path>packages/react-dom/src/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', () => {
<ide> }
<ide> }).toWarnDev(
<ide> 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> });
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> }
<ide> }).toWarnDev(
<ide> 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> });
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> '<BR /> is using incorrect casing. ' +
<ide> 'Use PascalCase for React components, ' +
<ide> 'or lowercase for HTML elements.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> expect(returnedValue).not.toContain('</BR>');
<ide> });
<ide> describe('ReactDOMComponent', () => {
<ide> '<IMG /> is using incorrect casing. ' +
<ide> 'Use PascalCase for React components, ' +
<ide> 'or lowercase for HTML elements.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> });
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> ).toWarnDev(
<ide> 'The `aria` attribute is reserved for future use in React. ' +
<ide> 'Pass individual `aria-` attributes instead.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> });
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide>
<ide> expect(() => ReactTestUtils.renderIntoDocument(<bar />)).toWarnDev(
<ide> 'The tag <bar> is unrecognized in this browser',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> // Test deduplication
<ide> expect(() => ReactTestUtils.renderIntoDocument(<foo />)).toWarnDev(
<ide> 'The tag <foo> is unrecognized in this browser',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> ReactTestUtils.renderIntoDocument(<foo />);
<ide> // This is a funny case.
<ide> describe('ReactDOMComponent', () => {
<ide> // Corner case. Make sure out deduplication logic doesn't break with weird tag.
<ide> expect(() =>
<ide> ReactTestUtils.renderIntoDocument(<hasOwnProperty />),
<del> ).toWarnDev(
<del> [
<del> '<hasOwnProperty /> is using incorrect casing. ' +
<del> 'Use PascalCase for React components, ' +
<del> 'or lowercase for HTML elements.',
<del> 'The tag <hasOwnProperty> is unrecognized in this browser',
<del> ],
<del> {withoutStack: true}, // TODO: add a stack
<del> );
<add> ).toWarnDev([
<add> '<hasOwnProperty /> is using incorrect casing. ' +
<add> 'Use PascalCase for React components, ' +
<add> 'or lowercase for HTML elements.',
<add> 'The tag <hasOwnProperty> is unrecognized in this browser',
<add> ]);
<ide> } finally {
<ide> Object.prototype.toString = realToString; // eslint-disable-line no-extend-native
<ide> }
<ide> describe('ReactDOMComponent', () => {
<ide> expect(() => ReactDOM.render(<ShadyComponent />, node)).toWarnDev(
<ide> 'ShadyComponent is using shady DOM. Using shady DOM with React can ' +
<ide> 'cause things to break subtly.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> mountComponent({is: 'custom-shady-div2'});
<ide> } finally {
<ide> describe('ReactDOMComponent', () => {
<ide> expect(() => mountComponent({is: 'custom-shady-div'})).toWarnDev(
<ide> 'A component is using shady DOM. Using shady DOM with React can ' +
<ide> 'cause things to break subtly.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide>
<ide> // No additional warnings are expected
<ide> describe('ReactDOMComponent', () => {
<ide> it('should validate against use of innerHTML', () => {
<ide> expect(() =>
<ide> mountComponent({innerHTML: '<span>Hi Jim!</span>'}),
<del> ).toWarnDev('Directly setting property `innerHTML` is not permitted. ', {
<del> withoutStack: true, // TODO: add a stack
<del> });
<add> ).toWarnDev('Directly setting property `innerHTML` is not permitted. ');
<ide> });
<ide>
<ide> it('should validate against use of innerHTML without case sensitivity', () => {
<ide> expect(() =>
<ide> mountComponent({innerhtml: '<span>Hi Jim!</span>'}),
<del> ).toWarnDev('Directly setting property `innerHTML` is not permitted. ', {
<del> withoutStack: true, // TODO: add a stack
<del> });
<add> ).toWarnDev('Directly setting property `innerHTML` is not permitted. ');
<ide> });
<ide>
<ide> it('should validate use of dangerouslySetInnerHTML', () => {
<ide> describe('ReactDOMComponent', () => {
<ide> ReactTestUtils.renderIntoDocument(<div onFocusIn={() => {}} />),
<ide> ).toWarnDev(
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> expect(() =>
<ide> ReactTestUtils.renderIntoDocument(<div onFocusOut={() => {}} />),
<ide> ).toWarnDev(
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> });
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> ReactTestUtils.renderIntoDocument(<div onfocusin={() => {}} />),
<ide> ).toWarnDev(
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> expect(() =>
<ide> ReactTestUtils.renderIntoDocument(<div onfocusout={() => {}} />),
<ide> ).toWarnDev(
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> });
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> ReactDOMServer.renderToString(<div onFocusIn={() => {}} />),
<ide> ).toWarnDev(
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> expect(() =>
<ide> ReactDOMServer.renderToString(<div onFocusOut={() => {}} />),
<ide> ).toWarnDev(
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> });
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> ReactDOMServer.renderToString(<div onfocusin={() => {}} />),
<ide> ).toWarnDev(
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> expect(() =>
<ide> ReactDOMServer.renderToString(<div onfocusout={() => {}} />),
<ide> ).toWarnDev(
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> });
<ide>
<ide><path>packages/react-dom/src/__tests__/ReactDOMInput-test.js
<ide> describe('ReactDOMInput', () => {
<ide> 'both). Decide between using a controlled or uncontrolled input ' +
<ide> 'element and remove one of these props. More info: ' +
<ide> 'https://fb.me/react-controlled-components',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> ReactDOM.unmountComponentAtNode(container);
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> 'both). Decide between using a controlled or uncontrolled input ' +
<ide> 'element and remove one of these props. More info: ' +
<ide> 'https://fb.me/react-controlled-components',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> ReactDOM.unmountComponentAtNode(container);
<ide>
<ide><path>packages/react-dom/src/__tests__/ReactDOMSelect-test.js
<ide> describe('ReactDOMSelect', () => {
<ide> });
<ide>
<ide> it('should warn if selected is set on <option>', () => {
<del> expect(() =>
<del> ReactTestUtils.renderIntoDocument(
<add> function App() {
<add> return (
<ide> <select>
<ide> <option selected={true} />
<ide> <option selected={true} />
<del> </select>,
<del> ),
<del> ).toWarnDev(
<add> </select>
<add> );
<add> }
<add>
<add> expect(() => ReactTestUtils.renderIntoDocument(<App />)).toWarnDev(
<ide> 'Use the `defaultValue` or `value` props on <select> instead of ' +
<ide> 'setting `selected` on <option>.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide>
<del> ReactTestUtils.renderIntoDocument(
<del> <select>
<del> <option selected={true} />
<del> <option selected={true} />
<del> </select>,
<del> );
<add> ReactTestUtils.renderIntoDocument(<App />);
<ide> });
<ide>
<ide> it('should warn if value is null and multiple is true', () => {
<ide> describe('ReactDOMSelect', () => {
<ide> 'both). Decide between using a controlled or uncontrolled select ' +
<ide> 'element and remove one of these props. More info: ' +
<ide> 'https://fb.me/react-controlled-components',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide>
<ide> ReactTestUtils.renderIntoDocument(
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationAttributes-test.js
<ide> describe('ReactDOMServerIntegration', () => {
<ide> // so that it gets deduplicated later, and doesn't fail the test.
<ide> expect(() => {
<ide> ReactDOM.render(<nonstandard />, document.createElement('div'));
<del> }).toWarnDev('The tag <nonstandard> is unrecognized in this browser.', {
<del> withoutStack: true, // TODO: add a stack
<del> });
<add> }).toWarnDev('The tag <nonstandard> is unrecognized in this browser.');
<ide>
<ide> const e = await render(<nonstandard foo="bar" />);
<ide> expect(e.getAttribute('foo')).toBe('bar');
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationElements-test.js
<ide> describe('ReactDOMServerIntegration', () => {
<ide> // so that it gets deduplicated later, and doesn't fail the test.
<ide> expect(() => {
<ide> ReactDOM.render(<nonstandard />, document.createElement('div'));
<del> }).toWarnDev('The tag <nonstandard> is unrecognized in this browser.', {
<del> withoutStack: true, // TODO: add a stack
<del> });
<add> }).toWarnDev('The tag <nonstandard> is unrecognized in this browser.');
<ide>
<ide> const e = await render(<nonstandard>Text</nonstandard>);
<ide> expect(e.tagName).toBe('NONSTANDARD');
<ide><path>packages/react-dom/src/__tests__/ReactDOMTextarea-test.js
<ide> describe('ReactDOMTextarea', () => {
<ide> node = renderTextarea(stub, container);
<ide> }).toWarnDev(
<ide> 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide>
<ide> expect(node.value).toBe('giraffe');
<ide> describe('ReactDOMTextarea', () => {
<ide> node = renderTextarea(<textarea>{17}</textarea>);
<ide> }).toWarnDev(
<ide> 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> expect(node.value).toBe('17');
<ide> });
<ide> describe('ReactDOMTextarea', () => {
<ide> node = renderTextarea(<textarea>{false}</textarea>);
<ide> }).toWarnDev(
<ide> 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> expect(node.value).toBe('false');
<ide> });
<ide> describe('ReactDOMTextarea', () => {
<ide> node = renderTextarea(<textarea>{obj}</textarea>);
<ide> }).toWarnDev(
<ide> 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> expect(node.value).toBe('sharkswithlasers');
<ide> });
<ide> describe('ReactDOMTextarea', () => {
<ide> ),
<ide> ).toWarnDev(
<ide> 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> }).toThrow();
<ide>
<ide> describe('ReactDOMTextarea', () => {
<ide> )),
<ide> ).toWarnDev(
<ide> 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> }).not.toThrow();
<ide>
<ide> describe('ReactDOMTextarea', () => {
<ide> 'both). Decide between using a controlled or uncontrolled textarea ' +
<ide> 'and remove one of these props. More info: ' +
<ide> 'https://fb.me/react-controlled-components',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide>
<ide> // No additional warnings are expected
<ide><path>packages/react-dom/src/__tests__/ReactServerRendering-test.js
<ide> describe('ReactDOMServer', () => {
<ide> </svg>
<ide> </div>,
<ide> ),
<del> ).toWarnDev(
<del> [
<del> 'Warning: <inPUT /> is using incorrect casing. ' +
<del> 'Use PascalCase for React components, ' +
<del> 'or lowercase for HTML elements.',
<del> // linearGradient doesn't warn
<del> 'Warning: <iFrame /> is using incorrect casing. ' +
<del> 'Use PascalCase for React components, ' +
<del> 'or lowercase for HTML elements.',
<del> ],
<del> {withoutStack: true},
<del> );
<add> ).toWarnDev([
<add> 'Warning: <inPUT /> is using incorrect casing. ' +
<add> 'Use PascalCase for React components, ' +
<add> 'or lowercase for HTML elements.',
<add> // linearGradient doesn't warn
<add> 'Warning: <iFrame /> is using incorrect casing. ' +
<add> 'Use PascalCase for React components, ' +
<add> 'or lowercase for HTML elements.',
<add> ]);
<ide> });
<ide>
<ide> it('should warn about contentEditable and children', () => {
<ide><path>packages/react-dom/src/client/ReactDOMFiberComponent.js
<ide> export function createElement(
<ide> isCustomComponentTag = isCustomComponent(type, props);
<ide> // Should this check be gated by parent namespace? Not sure we want to
<ide> // allow <SVG> or <mATH>.
<del> warningWithoutStack(
<add> warning(
<ide> isCustomComponentTag || type === type.toLowerCase(),
<ide> '<%s /> is using incorrect casing. ' +
<ide> 'Use PascalCase for React components, ' +
<ide> export function createElement(
<ide> !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)
<ide> ) {
<ide> warnedUnknownTags[type] = true;
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'The tag <%s> is unrecognized in this browser. ' +
<ide> 'If you meant to render a React component, start its name with ' +
<ide> export function setInitialProperties(
<ide> !didWarnShadyDOM &&
<ide> (domElement: any).shadyRoot
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> '%s is using shady DOM. Using shady DOM with React can ' +
<ide> 'cause things to break subtly.',
<ide> export function diffHydratedProperties(
<ide> !didWarnShadyDOM &&
<ide> (domElement: any).shadyRoot
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> '%s is using shady DOM. Using shady DOM with React can ' +
<ide> 'cause things to break subtly.',
<ide><path>packages/react-dom/src/client/ReactDOMFiberInput.js
<ide> import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber';
<ide> import invariant from 'shared/invariant';
<ide> import warning from 'shared/warning';
<del>import warningWithoutStack from 'shared/warningWithoutStack';
<ide>
<ide> import * as DOMPropertyOperations from './DOMPropertyOperations';
<ide> import {getFiberCurrentPropsFromNode} from './ReactDOMComponentTree';
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> props.defaultChecked !== undefined &&
<ide> !didWarnCheckedDefaultChecked
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> '%s contains an input of type %s with both checked and defaultChecked props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnValueDefaultValue
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> '%s contains an input of type %s with both value and defaultValue props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide><path>packages/react-dom/src/client/ReactDOMFiberOption.js
<ide> */
<ide>
<ide> import React from 'react';
<del>import warningWithoutStack from 'shared/warningWithoutStack';
<add>import warning from 'shared/warning';
<ide>
<ide> let didWarnSelectedSetOnOption = false;
<ide>
<ide> export function validateProps(element: Element, props: Object) {
<ide> // TODO (yungsters): Remove support for `selected` in <option>.
<ide> if (__DEV__) {
<ide> if (props.selected != null && !didWarnSelectedSetOnOption) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'Use the `defaultValue` or `value` props on <select> instead of ' +
<ide> 'setting `selected` on <option>.',
<ide><path>packages/react-dom/src/client/ReactDOMFiberSelect.js
<ide>
<ide> // TODO: direct imports like some-package/src/* are bad. Fix me.
<ide> import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber';
<del>import warningWithoutStack from 'shared/warningWithoutStack';
<add>import warning from 'shared/warning';
<ide>
<ide> import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
<ide>
<ide> function checkSelectPropTypes(props) {
<ide> }
<ide> const isArray = Array.isArray(props[propName]);
<ide> if (props.multiple && !isArray) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'The `%s` prop supplied to <select> must be an array if ' +
<ide> '`multiple` is true.%s',
<ide> propName,
<ide> getDeclarationErrorAddendum(),
<ide> );
<ide> } else if (!props.multiple && isArray) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'The `%s` prop supplied to <select> must be a scalar ' +
<ide> 'value if `multiple` is false.%s',
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnValueDefaultValue
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'Select elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide><path>packages/react-dom/src/client/ReactDOMFiberTextarea.js
<ide> */
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warningWithoutStack from 'shared/warningWithoutStack';
<add>import warning from 'shared/warning';
<ide>
<ide> import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
<ide>
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnValDefaultVal
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'Textarea elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> let children = props.children;
<ide> if (children != null) {
<ide> if (__DEV__) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'Use the `defaultValue` or `value` props instead of setting ' +
<ide> 'children on <textarea>.',
<ide><path>packages/react-dom/src/server/ReactPartialRenderer.js
<ide> import React from 'react';
<ide> import invariant from 'shared/invariant';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import lowPriorityWarning from 'shared/lowPriorityWarning';
<add>import warning from 'shared/warning';
<ide> import warningWithoutStack from 'shared/warningWithoutStack';
<ide> import checkPropTypes from 'prop-types/checkPropTypes';
<ide> import describeComponentFrame from 'shared/describeComponentFrame';
<ide> class ReactDOMServerRenderer {
<ide> if (namespace === Namespaces.html) {
<ide> // Should this check be gated by parent namespace? Not sure we want to
<ide> // allow <SVG> or <mATH>.
<del> warningWithoutStack(
<add> warning(
<ide> tag === element.type,
<ide> '<%s /> is using incorrect casing. ' +
<ide> 'Use PascalCase for React components, ' +
<ide> class ReactDOMServerRenderer {
<ide> props.defaultChecked !== undefined &&
<ide> !didWarnDefaultChecked
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> '%s contains an input of type %s with both checked and defaultChecked props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide> class ReactDOMServerRenderer {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnDefaultInputValue
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> '%s contains an input of type %s with both value and defaultValue props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide> class ReactDOMServerRenderer {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnDefaultTextareaValue
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'Textarea elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> class ReactDOMServerRenderer {
<ide> let textareaChildren = props.children;
<ide> if (textareaChildren != null) {
<ide> if (__DEV__) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'Use the `defaultValue` or `value` props instead of setting ' +
<ide> 'children on <textarea>.',
<ide> class ReactDOMServerRenderer {
<ide> }
<ide> const isArray = Array.isArray(props[propName]);
<ide> if (props.multiple && !isArray) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'The `%s` prop supplied to <select> must be an array if ' +
<del> '`multiple` is true.%s',
<add> '`multiple` is true.',
<ide> propName,
<del> '', // getDeclarationErrorAddendum(),
<ide> );
<ide> } else if (!props.multiple && isArray) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'The `%s` prop supplied to <select> must be a scalar ' +
<del> 'value if `multiple` is false.%s',
<add> 'value if `multiple` is false.',
<ide> propName,
<del> '', // getDeclarationErrorAddendum(),
<ide> );
<ide> }
<ide> }
<ide> class ReactDOMServerRenderer {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnDefaultSelectValue
<ide> ) {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'Select elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide><path>packages/react-dom/src/shared/DOMProperty.js
<ide> * @flow
<ide> */
<ide>
<del>import warningWithoutStack from 'shared/warningWithoutStack';
<add>import warning from 'shared/warning';
<ide>
<ide> type PropertyType = 0 | 1 | 2 | 3 | 4 | 5 | 6;
<ide>
<ide> export function isAttributeNameSafe(attributeName: string): boolean {
<ide> }
<ide> illegalAttributeNameCache[attributeName] = true;
<ide> if (__DEV__) {
<del> warningWithoutStack(false, 'Invalid attribute name: `%s`', attributeName);
<add> warning(false, 'Invalid attribute name: `%s`', attributeName);
<ide> }
<ide> return false;
<ide> }
<ide><path>packages/react-dom/src/shared/ReactDOMUnknownPropertyHook.js
<ide> import {
<ide> possibleRegistrationNames,
<ide> } from 'events/EventPluginRegistry';
<ide> import warning from 'shared/warning';
<del>import warningWithoutStack from 'shared/warningWithoutStack';
<ide>
<ide> import {
<ide> ATTRIBUTE_NAME_CHAR,
<ide> if (__DEV__) {
<ide>
<ide> const lowerCasedName = name.toLowerCase();
<ide> if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' +
<ide> 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' +
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> if (lowerCasedName === 'innerhtml') {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'Directly setting property `innerHTML` is not permitted. ' +
<ide> 'For more information, lookup documentation on `dangerouslySetInnerHTML`.',
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> if (lowerCasedName === 'aria') {
<del> warningWithoutStack(
<add> warning(
<ide> false,
<ide> 'The `aria` attribute is reserved for future use in React. ' +
<ide> 'Pass individual `aria-` attributes instead.',
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> function updateContextProvider(current, workInProgress, renderExpirationTime) {
<ide> ? context._calculateChangedBits(oldValue, newValue)
<ide> : MAX_SIGNED_31_BIT_INT;
<ide> if (__DEV__) {
<del> warningWithoutStack(
<add> warning(
<ide> (changedBits & MAX_SIGNED_31_BIT_INT) === changedBits,
<ide> 'calculateChangedBits: Expected the return value to be a ' +
<ide> '31-bit integer. Instead received: %s',
<ide><path>packages/react-reconciler/src/__tests__/ReactNewContext-test.internal.js
<ide> describe('ReactNewContext', () => {
<ide> (a, b) => Math.pow(2, 32) - 1, // Return 32 bit int
<ide> );
<ide>
<del> ReactNoop.render(<Context.Provider value={1} />);
<add> function App(props) {
<add> return <Context.Provider value={props.value} />;
<add> }
<add>
<add> ReactNoop.render(<App value={1} />);
<ide> ReactNoop.flush();
<ide>
<ide> // Update
<del> ReactNoop.render(<Context.Provider value={2} />);
<add> ReactNoop.render(<App value={2} />);
<ide> expect(ReactNoop.flush).toWarnDev(
<ide> 'calculateChangedBits: Expected the return value to be a 31-bit ' +
<ide> 'integer. Instead received: 4294967295',
<del> {withoutStack: true}, // TODO: add a stack
<ide> );
<ide> });
<ide> | 17 |
Text | Text | add monsanto as collaborator | 717724611a9ef14290c881f95f2cdfc47369c9ab | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Petka Antonov** ([@petkaantonov](https://github.com/petkaantonov)) <petka_antonov@hotmail.com>
<ide> * **Yosuke Furukawa** ([@yosuke-furukawa](https://github.com/yosuke-furukawa)) <yosuke.furukawa@gmail.com>
<ide> * **Alex Kocharin** ([@rlidwka](https://github.com/rlidwka)) <alex@kocharin.ru>
<add>* **Christopher Monsanto** ([@monsanto](https://github.com/monsanto)) <chris@monsan.to>
<ide>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the io.js project. | 1 |
Text | Text | update stale feature messages | 8b8d0fb42685a693eb32682549da2c7a9cf053e3 | <ide><path>doc/contributing/feature-request-management.md
<ide> to the issue:
<ide> ```markdown
<ide> There has been no activity on this feature request for
<ide> 5 months and it is unlikely to be implemented.
<del>It will be closed after 6 months after the last non-automated comment unless there is renewed
<del>discussion or collaborators advocating that it be kept
<del>open. For more information on how the project manages
<del>feature requests please consult the
<del>[feature request management document](https://github.com/nodejs/node/blob/HEAD/doc/guides/feature-request-management.md).
<add>It will be closed 6 months after the last non-automated comment.
<add>
<add>For more information on how the project manages
<add>feature requests, please consult the
<add>[feature request management document](https://github.com/nodejs/node/blob/HEAD/doc/contributing/feature-request-management.md).
<ide> ```
<ide>
<ide> If there is no additional activity/discussion on the
<ide> closed:
<ide>
<ide> ```markdown
<ide> There has been no activity on this feature request
<del>and it is being closed. We value your input
<del>and if you feel closing this issue was not the
<del>right thing to do, please re-open it.
<add>and it is being closed. If you feel closing this issue is not the
<add>right thing to do, please leave a comment.
<ide>
<ide> For more information on how the project manages
<del>feature requests please consult the
<del>[feature request management document](https://github.com/nodejs/node/blob/HEAD/doc/guides/feature-request-management.md).
<add>feature requests, please consult the
<add>[feature request management document](https://github.com/nodejs/node/blob/HEAD/doc/contributing/feature-request-management.md).
<ide> ``` | 1 |
Text | Text | improve guide of command line injection [ci skip] | 8167f23621a35016956ebf8f7d3e19aa8f57b1bb | <ide><path>guides/source/security.md
<ide> If you use the [in_place_editor plugin](https://rubygems.org/gems/in_place_editi
<ide>
<ide> NOTE: _Use user-supplied command line parameters with caution._
<ide>
<del>If your application has to execute commands in the underlying operating system, there are several methods in Ruby: `exec(command)`, `syscall(command)`, `system(command)` and `command`. You will have to be especially careful with these functions if the user may enter the whole command, or a part of it. This is because in most shells, you can execute another command at the end of the first one, concatenating them with a semicolon (`;`) or a vertical bar (`|`).
<add>If your application has to execute commands in the underlying operating system, there are several methods in Ruby: `system(command)`, `exec(command)`, `spawn(command)` and `` `command` ``. You will have to be especially careful with these functions if the user may enter the whole command, or a part of it. This is because in most shells, you can execute another command at the end of the first one, concatenating them with a semicolon (`;`) or a vertical bar (`|`).
<add>
<add>```ruby
<add>user_input = "hello; rm *"
<add>system("/bin/echo #{user_input}")
<add># prints "hello", and deletes files in the current directory
<add>```
<ide>
<ide> A countermeasure is to _use the `system(command, parameters)` method which passes command line parameters safely_.
<ide>
<ide> system("/bin/echo","hello; rm *")
<ide> # prints "hello; rm *" and does not delete files
<ide> ```
<ide>
<add>#### Kernel#open's vulnerability
<add>
<add>`Kernel#open` executes OS command if the argument starts with a vertical bar (`|`).
<add>
<add>```ruby
<add>open('| ls') { |f| f.read }
<add># returns file list as a String via `ls` command
<add>```
<add>
<add>Countermeasures are to use `File.open`, `IO.open` or `URI#open` instead. They don't execute an OS command.
<add>
<add>```ruby
<add>File.open('| ls') { |f| f.read }
<add># doesn't execute `ls` command, just opens `| ls` file if it exists
<add>
<add>IO.open(0) { |f| f.read }
<add># opens stdin. doesn't accept a String as the argument
<add>
<add>require 'open-uri'
<add>URI('https://example.com').open { |f| f.read }
<add># opens the URI. `URI()` doesn't accept `| ls`
<add>```
<add>
<ide> ### Header Injection
<ide>
<ide> WARNING: _HTTP headers are dynamically generated and under certain circumstances user input may be injected. This can lead to false redirection, XSS, or HTTP response splitting._ | 1 |
Javascript | Javascript | determine unit automatically in test | 2564e708b55fe2f032c9e5ee4d00874baa089a9e | <ide><path>test/fixtures/scale.timeseries/financial-daily.js
<ide> module.exports = {
<ide> maxRotation: 0,
<ide> sampleSize: 100
<ide> },
<del> time: {
<del> unit: 'month'
<del> },
<ide> // manually set major ticks so that test passes in all time zones with moment adapter
<ide> afterBuildTicks: function(scale) {
<ide> const major = [0, 12, 24]; | 1 |
Javascript | Javascript | fix isip test | 9057d3f17eab0e22513410a27c75b95375f97de3 | <ide><path>test/simple/test-net-isip.js
<ide> assert.equal(net.isIP('2001:dead:beef:1::2008:6'), 6);
<ide> assert.equal(net.isIP('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'), 6);
<ide> assert.equal(net.isIP('::1'), 6);
<ide> assert.equal(net.isIP('::'), 6);
<del>assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:00001:0000'), 0);
<add>assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:12345:0000'), 0);
<ide> assert.equal(net.isIP('0'), 0);
<ide>
<ide> assert.equal(net.isIPv4('127.0.0.1'), true); | 1 |
Text | Text | add docs for "--containerd" in dockerd | cebb9543e1ae2263905562d1c54e380005d5fe4f | <ide><path>docs/reference/commandline/dockerd.md
<ide> The Docker daemon relies on a
<ide> (invoked via the `containerd` daemon) as its interface to the Linux
<ide> kernel `namespaces`, `cgroups`, and `SELinux`.
<ide>
<add>By default, the Docker daemon automatically starts `containerd`. If you want to
<add>control `containerd` startup, manually start `containerd` and pass the path to
<add>the `containerd` socket using the `--containerd` flag. For example:
<add>
<add>```bash
<add>$ dockerd --containerd /var/run/dev/docker-containerd.sock
<add>```
<add>
<ide> Runtimes can be registered with the daemon either via the
<ide> configuration file or using the `--add-runtime` command line argument.
<ide> | 1 |
Go | Go | handle ipv6 entries | f7c9214e29a81679916b953572173393d5e766e5 | <ide><path>pkg/discovery/discovery_test.go
<ide> func (s *DiscoverySuite) TestNewEntry(c *check.C) {
<ide> c.Assert(entry.Equals(&Entry{Host: "127.0.0.1", Port: "2375"}), check.Equals, true)
<ide> c.Assert(entry.String(), check.Equals, "127.0.0.1:2375")
<ide>
<add> entry, err = NewEntry("[2001:db8:0:f101::2]:2375")
<add> c.Assert(err, check.IsNil)
<add> c.Assert(entry.Equals(&Entry{Host: "2001:db8:0:f101::2", Port: "2375"}), check.Equals, true)
<add> c.Assert(entry.String(), check.Equals, "[2001:db8:0:f101::2]:2375")
<add>
<ide> _, err = NewEntry("127.0.0.1")
<ide> c.Assert(err, check.NotNil)
<ide> }
<ide> func (s *DiscoverySuite) TestCreateEntries(c *check.C) {
<ide> c.Assert(entries, check.DeepEquals, Entries{})
<ide> c.Assert(err, check.IsNil)
<ide>
<del> entries, err = CreateEntries([]string{"127.0.0.1:2375", "127.0.0.2:2375", ""})
<add> entries, err = CreateEntries([]string{"127.0.0.1:2375", "127.0.0.2:2375", "[2001:db8:0:f101::2]:2375", ""})
<ide> c.Assert(err, check.IsNil)
<ide> expected := Entries{
<ide> &Entry{Host: "127.0.0.1", Port: "2375"},
<ide> &Entry{Host: "127.0.0.2", Port: "2375"},
<add> &Entry{Host: "2001:db8:0:f101::2", Port: "2375"},
<ide> }
<ide> c.Assert(entries.Equals(expected), check.Equals, true)
<ide>
<ide><path>pkg/discovery/entry.go
<ide> package discovery
<ide>
<del>import (
<del> "fmt"
<del> "net"
<del>)
<add>import "net"
<ide>
<ide> // NewEntry creates a new entry.
<ide> func NewEntry(url string) (*Entry, error) {
<ide> func (e *Entry) Equals(cmp *Entry) bool {
<ide>
<ide> // String returns the string form of an entry.
<ide> func (e *Entry) String() string {
<del> return fmt.Sprintf("%s:%s", e.Host, e.Port)
<add> return net.JoinHostPort(e.Host, e.Port)
<ide> }
<ide>
<ide> // Entries is a list of *Entry with some helpers. | 2 |
Javascript | Javascript | fix linting issues | 02f092a2c1d4a77fbaf6a7e0e80a452634b7164c | <ide><path>packages/@ember/-internals/glimmer/tests/integration/application/engine-test.js
<ide> moduleFor(
<ide> },
<ide> })
<ide> );
<del> this.register(
<del> 'template:application_error',
<del> compile(
<del> 'Error! {{@model.message}}'
<del> )
<del> );
<add> this.register('template:application_error', compile('Error! {{@model.message}}'));
<ide> this.register(
<ide> 'route:post',
<ide> Route.extend({
<ide> moduleFor(
<ide> },
<ide> })
<ide> );
<del> this.register(
<del> 'template:error',
<del> compile(
<del> 'Error! {{@model.message}}'
<del> )
<del> );
<add> this.register('template:error', compile('Error! {{@model.message}}'));
<ide> this.register(
<ide> 'route:post',
<ide> Route.extend({
<ide> moduleFor(
<ide> },
<ide> })
<ide> );
<del> this.register(
<del> 'template:post_error',
<del> compile(
<del> 'Error! {{@model.message}}'
<del> )
<del> );
<add> this.register('template:post_error', compile('Error! {{@model.message}}'));
<ide> this.register(
<ide> 'route:post',
<ide> Route.extend({
<ide> moduleFor(
<ide> },
<ide> })
<ide> );
<del> this.register(
<del> 'template:post.error',
<del> compile(
<del> 'Error! {{@model.message}}'
<del> )
<del> );
<add> this.register('template:post.error', compile('Error! {{@model.message}}'));
<ide> this.register(
<ide> 'route:post.comments',
<ide> Route.extend({
<ide><path>packages/@ember/-internals/glimmer/tests/integration/application/rendering-test.js
<ide> moduleFor(
<ide> `);
<ide> }
<ide>
<del> async ['@test interior mutations on the model with tracked properties'](
<del> assert
<del> ) {
<add> async ['@test interior mutations on the model with tracked properties'](assert) {
<ide> class Model {
<ide> @tracked color;
<ide>
<ide> moduleFor(
<ide> `);
<ide> }
<ide>
<del> async ['@test exterior mutations on the model with tracked properties'](
<del> assert
<del> ) {
<add> async ['@test exterior mutations on the model with tracked properties'](assert) {
<ide> this.router.map(function () {
<ide> this.route('color', { path: '/:color' });
<ide> });
<ide> moduleFor(
<ide> });
<ide> }
<ide>
<del> async ['@test it emits a useful backtracking re-render assertion message'](
<del> assert
<del> ) {
<add> async ['@test it emits a useful backtracking re-render assertion message'](assert) {
<ide> this.router.map(function () {
<ide> this.route('routeWithError');
<ide> });
<ide><path>packages/@ember/-internals/glimmer/tests/integration/components/link-to/routing-angle-test.js
<ide> moduleFor(
<ide> });
<ide> }
<ide>
<del> async [`@test The <LinkTo /> component moves into the named route with context`](
<del> assert
<del> ) {
<add> async [`@test The <LinkTo /> component moves into the named route with context`](assert) {
<ide> this.router.map(function () {
<ide> this.route('about');
<ide> this.route('item', { path: '/item/:id' });
<ide><path>packages/@ember/-internals/glimmer/tests/integration/components/link-to/routing-curly-test.js
<ide> moduleFor(
<ide> });
<ide> }
<ide>
<del> async [`@test The {{link-to}} component moves into the named route with context`](
<del> assert
<del> ) {
<add> async [`@test The {{link-to}} component moves into the named route with context`](assert) {
<ide> this.router.map(function () {
<ide> this.route('about');
<ide> this.route('item', { path: '/item/:id' });
<ide><path>packages/@ember/-internals/glimmer/tests/integration/mount-test.js
<ide> moduleFor(
<ide> this._super(...arguments);
<ide> this.register(
<ide> 'template:application',
<del> compile(
<del> '<h2>Param Engine: {{@model.foo}}</h2>',
<del> {
<del> moduleName: 'my-app/templates/application.hbs',
<del> }
<del> )
<add> compile('<h2>Param Engine: {{@model.foo}}</h2>', {
<add> moduleName: 'my-app/templates/application.hbs',
<add> })
<ide> );
<ide> },
<ide> })
<ide><path>packages/ember/tests/homepage_example_test.js
<ide> import { moduleFor, ApplicationTestCase } from 'internal-test-helpers';
<ide> moduleFor(
<ide> 'The example renders correctly',
<ide> class extends ApplicationTestCase {
<del>
<del> async ['@test Render index template into application outlet'](
<del> assert
<del> ) {
<add> async ['@test Render index template into application outlet'](assert) {
<ide> this.addTemplate('application', '{{outlet}}');
<ide> this.addTemplate(
<ide> 'index',
<ide><path>packages/ember/tests/routing/model_loading_test.js
<ide> moduleFor(
<ide> });
<ide> }
<ide>
<del> [`@test The Specials Page getting its model by deserializing the params hash`](
<del> assert
<del> ) {
<add> [`@test The Specials Page getting its model by deserializing the params hash`](assert) {
<ide> this.router.map(function () {
<ide> this.route('home', { path: '/' });
<ide> this.route('special', { path: '/specials/:menu_item_id' });
<ide> moduleFor(
<ide> });
<ide> }
<ide>
<del> ['@test Moving from one page to another triggers the correct callbacks'](
<del> assert
<del> ) {
<add> ['@test Moving from one page to another triggers the correct callbacks'](assert) {
<ide> assert.expect(3);
<ide>
<ide> this.router.map(function () {
<ide> moduleFor(
<ide> });
<ide> }
<ide>
<del> ['@test Nested callbacks are not exited when moving to siblings'](
<del> assert
<del> ) {
<add> ['@test Nested callbacks are not exited when moving to siblings'](assert) {
<ide> let rootSetup = 0;
<ide> let rootRender = 0;
<ide> let rootModel = 0;
<ide><path>packages/ember/tests/routing/router_service_test/transitionTo_test.js
<ide> moduleFor(
<ide> });
<ide> }
<ide>
<del> async ['@test RouterService#transitionTo with dynamic segment'](
<del> assert
<del> ) {
<add> async ['@test RouterService#transitionTo with dynamic segment'](assert) {
<ide> assert.expect(3);
<ide>
<ide> let componentInstance;
<ide> moduleFor(
<ide> this.assertText('much dynamicism');
<ide> }
<ide>
<del> async ['@test RouterService#transitionTo with dynamic segment and model hook'](
<del> assert
<del> ) {
<add> async ['@test RouterService#transitionTo with dynamic segment and model hook'](assert) {
<ide> assert.expect(3);
<ide>
<ide> let componentInstance;
<ide><path>packages/ember/tests/routing/substates_test.js
<ide> moduleFor(
<ide> return promise;
<ide> }
<ide>
<del> async ['@test Default error event moves into nested route'](
<del> assert
<del> ) {
<add> async ['@test Default error event moves into nested route'](assert) {
<ide> await this.visit('/');
<ide>
<ide> this.addTemplate('grandma.error', 'ERROR: {{@model.msg}}');
<ide><path>packages/ember/tests/routing/template_rendering_test.js
<ide> moduleFor(
<ide> assert.equal(this.$('p').text(), 'YES I AM HOME', 'The homepage template was rendered');
<ide> }
<ide>
<del> async [`@test Model passed via renderTemplate model is set as controller's model`](
<del> assert
<del> ) {
<add> async [`@test Model passed via renderTemplate model is set as controller's model`](assert) {
<ide> this.addTemplate(
<ide> 'bio',
<ide> '<p>Model: {{@model.name}}</p><p>Controller: {{this.model.name}}</p>'
<ide> moduleFor(
<ide> });
<ide> }
<ide>
<del> async ["@test The template is not re-rendered when the route's model changes"](
<del> assert
<del> ) {
<add> async ["@test The template is not re-rendered when the route's model changes"](assert) {
<ide> this.router.map(function () {
<ide> this.route('page', { path: '/page/:name' });
<ide> }); | 10 |
Text | Text | add a note about the existence of 'next/script' | d368f76b4dff84a2db46ee50a09ae29003f11b30 | <ide><path>docs/api-reference/next/head.md
<ide> In this case only the second `<meta property="og:title" />` is rendered. `meta`
<ide>
<ide> `title`, `meta` or any other elements (e.g. `script`) need to be contained as **direct** children of the `Head` element,
<ide> or wrapped into maximum one level of `<React.Fragment>` or arrays—otherwise the tags won't be correctly picked up on client-side navigations.
<add>
<add>> We recommend using [next/script](/docs/basic-features/script.md) in your component instead of manually creating a `<script>` in `next/head`. | 1 |
Python | Python | remove unnecessary warning from train | e70a00fa76f50e6c49ece17b20d7c5246609ed35 | <ide><path>spacy/cli/train.py
<ide> def init_pipeline(
<ide> else:
<ide> msg.good(f"Loaded initialized pipeline from {init_path}")
<ide> return nlp
<del> msg.warn(
<del> "Not saving initialized model: no output directory specified. "
<del> "To speed up training, spaCy can save the initialized nlp object with "
<del> "the vocabulary, vectors and label scheme. To take advantage of this, "
<del> "provide an output directory."
<del> )
<ide> return init_nlp(config, **init_kwargs)
<ide>
<ide> | 1 |
Javascript | Javascript | unskip strict mode test | 4daccb827dffb1e4494219ca831ccb7613f5294c | <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/strict-mode-test.js
<ide> if (EMBER_STRICT_MODE) {
<ide> moduleFor(
<ide> 'Strict Mode - built ins',
<ide> class extends RenderingTestCase {
<del> '@skip Can use Input'() {
<add> '@test Can use Input'() {
<ide> let Foo = defineComponent({ Input }, '<Input/>');
<ide>
<ide> this.registerComponent('foo', { ComponentClass: Foo }); | 1 |
Javascript | Javascript | simplify filename checks | 5450e48f6931d7960da88a96ddaab9f19dd4c788 | <ide><path>lib/internal/worker.js
<ide> class Worker extends EventEmitter {
<ide> options.execArgv);
<ide> }
<ide> if (!options.eval) {
<del> if (!path.isAbsolute(filename) &&
<del> !filename.startsWith('./') &&
<del> !filename.startsWith('../') &&
<del> !filename.startsWith('.' + path.sep) &&
<del> !filename.startsWith('..' + path.sep)) {
<add> if (!path.isAbsolute(filename) && !/^\.\.?[\\/]/.test(filename)) {
<ide> throw new ERR_WORKER_PATH(filename);
<ide> }
<ide> filename = path.resolve(filename); | 1 |
PHP | PHP | fix argument number issue | 2b70af959aa79c756ebc612e25f045e5ebe11fb2 | <ide><path>tests/TestCase/Routing/RouteCollectionTest.php
<ide> public function testParseFallback()
<ide> $routes = new RouteBuilder($this->collection, '/', []);
<ide>
<ide> $routes->resources('Articles');
<del> $routes->connect('/:controller', ['action' => 'index'], [], ['routeClass' => 'InflectedRoute']);
<add> $routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);
<ide> $routes->connect('/:controller/:action', [], ['routeClass' => 'InflectedRoute']);
<ide>
<ide> $result = $this->collection->parse('/articles/add'); | 1 |
Go | Go | create labels when volume exists only remotely | 4d8598ad0506b29c12632c1b8ed92eb58fc2f0e2 | <ide><path>volume/store/store.go
<ide> func (s *VolumeStore) create(name, driverName string, opts, labels map[string]st
<ide> }
<ide>
<ide> if v != nil {
<del> return v, nil
<add> // there is an existing volume, if we already have this stored locally, return it.
<add> // TODO: there could be some inconsistent details such as labels here
<add> if vv, _ := s.getNamed(v.Name()); vv != nil {
<add> return vv, nil
<add> }
<ide> }
<ide>
<ide> // Since there isn't a specified driver name, let's see if any of the existing drivers have this volume name
<ide> if driverName == "" {
<del> v, _ := s.getVolume(name)
<add> v, _ = s.getVolume(name)
<ide> if v != nil {
<ide> return v, nil
<ide> }
<ide> }
<ide>
<ide> vd, err := volumedrivers.CreateDriver(driverName)
<del>
<ide> if err != nil {
<ide> return nil, &OpErr{Op: "create", Name: name, Err: err}
<ide> }
<ide>
<ide> logrus.Debugf("Registering new volume reference: driver %q, name %q", vd.Name(), name)
<del>
<del> if v, _ := vd.Get(name); v != nil {
<del> return v, nil
<del> }
<del> v, err = vd.Create(name, opts)
<del> if err != nil {
<del> if _, err := volumedrivers.ReleaseDriver(driverName); err != nil {
<del> logrus.WithError(err).WithField("driver", driverName).Error("Error releasing reference to volume driver")
<add> if v, _ = vd.Get(name); v == nil {
<add> v, err = vd.Create(name, opts)
<add> if err != nil {
<add> if _, err := volumedrivers.ReleaseDriver(driverName); err != nil {
<add> logrus.WithError(err).WithField("driver", driverName).Error("Error releasing reference to volume driver")
<add> }
<add> return nil, err
<ide> }
<del> return nil, err
<ide> }
<add>
<ide> s.globalLock.Lock()
<ide> s.labels[name] = labels
<ide> s.options[name] = opts
<ide><path>volume/store/store_test.go
<ide> import (
<ide> "strings"
<ide> "testing"
<ide>
<add> "github.com/docker/docker/volume"
<ide> "github.com/docker/docker/volume/drivers"
<ide> volumetestutils "github.com/docker/docker/volume/testutils"
<ide> )
<ide> func TestDerefMultipleOfSameRef(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> }
<add>
<add>func TestCreateKeepOptsLabelsWhenExistsRemotely(t *testing.T) {
<add> vd := volumetestutils.NewFakeDriver("fake")
<add> volumedrivers.Register(vd, "fake")
<add> dir, err := ioutil.TempDir("", "test-same-deref")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer os.RemoveAll(dir)
<add> s, err := New(dir)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Create a volume in the driver directly
<add> if _, err := vd.Create("foo", nil); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> v, err := s.Create("foo", "fake", nil, map[string]string{"hello": "world"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> switch dv := v.(type) {
<add> case volume.DetailedVolume:
<add> if dv.Labels()["hello"] != "world" {
<add> t.Fatalf("labels don't match")
<add> }
<add> default:
<add> t.Fatalf("got unexpected type: %T", v)
<add> }
<add>} | 2 |
Ruby | Ruby | clean the code a bit | 4eedb3928e5555e9d766f7c92637a6341c461efb | <ide><path>actionview/lib/action_view/helpers/tags/color_field.rb
<ide> module Tags # :nodoc:
<ide> class ColorField < TextField # :nodoc:
<ide> def render
<ide> options = @options.stringify_keys
<del> options["value"] = options.fetch("value") { validate_color_string(value(object)) }
<add> options["value"] ||= validate_color_string(value(object))
<ide> @options = options
<ide> super
<ide> end
<ide><path>actionview/lib/action_view/helpers/tags/datetime_field.rb
<ide> module Tags # :nodoc:
<ide> class DatetimeField < TextField # :nodoc:
<ide> def render
<ide> options = @options.stringify_keys
<del> options["value"] = options.fetch("value") { format_date(value(object)) }
<add> options["value"] ||= format_date(value(object))
<ide> options["min"] = format_date(options["min"])
<ide> options["max"] = format_date(options["max"])
<ide> @options = options | 2 |
Javascript | Javascript | add styled-jsx to babel plugins (#970) | 3143e0d0a1fc72c36f7483ad6bcdd8c4364416fe | <ide><path>server/build/webpack.js
<ide> export default async function createCompiler (dir, { dev = false, quiet = false
<ide> 'next/css': require.resolve('../../lib/css'),
<ide> 'next/head': require.resolve('../../lib/head'),
<ide> 'next/document': require.resolve('../../server/document'),
<del> 'next/router': require.resolve('../../lib/router')
<add> 'next/router': require.resolve('../../lib/router'),
<add> 'styled-jsx/style': require.resolve('styled-jsx/style')
<ide> }
<ide> }
<ide> ] | 1 |
Python | Python | fix relative imports | 73b577cb01b7f5460b55f83a1c4b1678e086dd68 | <ide><path>spacy/lang/bn/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide> from .lemmatizer import LEMMA_RULES
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class Bengali(Language):
<ide><path>spacy/lang/bn/morph_rules.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import LEMMA
<del>from ..deprecated import PRON_LEMMA
<add>from ...deprecated import PRON_LEMMA
<add>from ...symbols import LEMMA
<ide>
<ide>
<ide> MORPH_RULES = {
<ide><path>spacy/lang/bn/punctuation.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..language_data.punctuation import ALPHA_LOWER, LIST_ELLIPSES, QUOTES
<del>from ..language_data.punctuation import ALPHA_UPPER, LIST_QUOTES, UNITS
<del>from ..language_data.punctuation import CURRENCY, LIST_PUNCT, ALPHA, _QUOTES
<ide>
<ide>
<ide> CURRENCY_SYMBOLS = r"\$ ¢ £ € ¥ ฿ ৳"
<ide> r'(?<=[{a}])([{q}\)\]\(\[])(?=[\-{a}])'.format(a=ALPHA, q=_QUOTES.replace("'", "").strip().replace(" ", "")),
<ide> ]
<ide> )
<add>from ..char_classes import LIST_PUNCT, LIST_ELLIPSES, LIST_QUOTES, UNITS
<add>from ..char_classes import ALPHA_LOWER, ALPHA_UPPER, ALPHA, HYPHENS, QUOTES
<ide><path>spacy/lang/bn/tag_map.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import POS, PUNCT, ADJ, CONJ, SCONJ, NUM, DET, ADV, ADP, X, VERB
<del>from ..symbols import CCONJ, NOUN, PROPN, PART, INTJ, SPACE, PRON, AUX, SYM
<add>from ...symbols import POS, PUNCT, ADJ, CONJ, SCONJ, NUM, DET, ADV, ADP, X, VERB
<add>from ...symbols import CCONJ, NOUN, PROPN, PART, INTJ, SPACE, PRON, AUX, SYM
<ide>
<ide>
<ide> TAG_MAP = {
<ide><path>spacy/lang/bn/tokenizer_exceptions.py
<ide> # coding=utf-8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import *
<add>from ...symbols import ORTH, LEMMA
<ide>
<ide> TOKENIZER_EXCEPTIONS = {}
<ide>
<ide><path>spacy/lang/de/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide> from .lemmatizer import LOOKUP
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..lemmatizerlookup import Lemmatizer
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...lemmatizerlookup import Lemmatizer
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class German(Language):
<ide><path>spacy/lang/de/tag_map.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import POS, PUNCT, ADJ, CONJ, SCONJ, NUM, DET, ADV, ADP, X, VERB
<del>from ..symbols import NOUN, PROPN, PART, INTJ, SPACE, PRON, AUX
<add>from ...symbols import POS, PUNCT, ADJ, CONJ, SCONJ, NUM, DET, ADV, ADP, X, VERB
<add>from ...symbols import NOUN, PROPN, PART, INTJ, SPACE, PRON, AUX
<ide>
<ide>
<ide> TAG_MAP = {
<ide><path>spacy/lang/de/tokenizer_exceptions.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import ORTH, LEMMA, TAG, NORM
<del>from ..deprecated import PRON_LEMMA
<add>from ...symbols import ORTH, LEMMA, TAG, NORM
<add>from ...deprecated import PRON_LEMMA
<ide>
<ide>
<ide> _exc = {
<ide><path>spacy/lang/en/__init__.py
<ide> from .morph_rules import MORPH_RULES
<ide> from .lemmatizer import LEMMA_RULES, LEMMA_INDEX, LEMMA_EXC
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class English(Language):
<ide><path>spacy/lang/en/morph_rules.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import LEMMA
<del>from ..deprecated import PRON_LEMMA
<add>from ...symbols import LEMMA
<add>from ...deprecated import PRON_LEMMA
<ide>
<ide>
<ide> MORPH_RULES = {
<ide><path>spacy/lang/en/tag_map.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import POS, PUNCT, SYM, ADJ, CCONJ, NUM, DET, ADV, ADP, X, VERB
<del>from ..symbols import NOUN, PROPN, PART, INTJ, SPACE, PRON
<add>from ...symbols import POS, PUNCT, SYM, ADJ, CCONJ, NUM, DET, ADV, ADP, X, VERB
<add>from ...symbols import NOUN, PROPN, PART, INTJ, SPACE, PRON
<ide>
<ide>
<ide> TAG_MAP = {
<ide><path>spacy/lang/en/tokenizer_exceptions.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import ORTH, LEMMA, TAG, NORM
<del>from ..deprecated import PRON_LEMMA
<add>from ...symbols import ORTH, LEMMA, TAG, NORM
<add>from ...deprecated import PRON_LEMMA
<ide>
<ide>
<ide> _exc = {}
<ide><path>spacy/lang/es/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide> from .lemmatizer import LOOKUP
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..lemmatizerlookup import Lemmatizer
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...lemmatizerlookup import Lemmatizer
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class Spanish(Language):
<ide><path>spacy/lang/es/tokenizer_exceptions.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import ORTH, LEMMA, TAG, NORM, ADP, DET
<del>from ..deprecated import PRON_LEMMA
<add>from ...symbols import ORTH, LEMMA, TAG, NORM, ADP, DET
<add>from ...deprecated import PRON_LEMMA
<ide>
<ide>
<ide> _exc = {
<ide><path>spacy/lang/fi/__init__.py
<ide> from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
<ide> from .stop_words import STOP_WORDS
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class Finnish(Language):
<ide><path>spacy/lang/fi/tokenizer_exceptions.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import ORTH, LEMMA
<add>from ...symbols import ORTH, LEMMA
<ide>
<ide>
<ide> _exc = {}
<ide><path>spacy/lang/fr/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide> from .lemmatizer import LOOKUP
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..lemmatizerlookup import Lemmatizer
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...lemmatizerlookup import Lemmatizer
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class French(Language):
<ide><path>spacy/lang/fr/punctuation.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..language_data.punctuation import ALPHA, TOKENIZER_INFIXES, LIST_PUNCT
<del>from ..language_data.punctuation import LIST_ELLIPSES, LIST_QUOTES, CURRENCY
<del>from ..language_data.punctuation import UNITS, ALPHA_LOWER, QUOTES, ALPHA_UPPER
<add>from ..char_classes import TOKENIZER_INFIXES, LIST_PUNCT LIST_ELLIPSES
<add>from ..char_classes import LIST_QUOTES, CURRENCY, QUOTES, UNITS
<add>from ..char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
<ide>
<ide>
<ide> ELISION = " ' ’ ".strip().replace(' ', '').replace('\n', '')
<ide><path>spacy/lang/fr/tokenizer_exceptions.py
<ide>
<ide> import regex as re
<ide>
<del>from .punctuation import ELISION, HYPHENS
<ide> from ._tokenizer_exceptions_list import FR_BASE_EXCEPTIONS
<del>from ..symbols import ORTH, LEMMA, TAG, NORM
<del>from ..deprecated import PRON_LEMMA
<del>from ..language_data.tokenizer_exceptions import _URL_PATTERN
<del>from ..language_data.punctuation import ALPHA_LOWER
<add>from .punctuation import ELISION, HYPHENS
<add>from ..tokenizer_exceptions import URL_PATTERN
<add>from ..char_classes import ALPHA_LOWER
<add>from ...symbols import ORTH, LEMMA, TAG, NORM
<add>from ...deprecated import PRON_LEMMA
<ide>
<ide>
<ide> def upper_first_letter(text):
<ide><path>spacy/lang/he/__init__.py
<ide>
<ide> from .stop_words import STOP_WORDS
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class Hebrew(Language):
<ide><path>spacy/lang/hu/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide> from .lemmatizer import LOOKUP
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..lemmatizerlookup import Lemmatizer
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...lemmatizerlookup import Lemmatizer
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class Hungarian(Language):
<ide><path>spacy/lang/hu/punctuation.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..language_data.punctuation import ALPHA_LOWER, LIST_ELLIPSES, QUOTES
<del>from ..language_data.punctuation import ALPHA_UPPER, LIST_QUOTES, UNITS
<del>from ..language_data.punctuation import CURRENCY, LIST_PUNCT, ALPHA, _QUOTES
<ide>
<ide>
<ide> _currency_symbols = r"\$ ¢ £ € ¥ ฿"
<ide> r'(?<=[{a}])--(?=[{a}])'.format(a=ALPHA),
<ide> r'(?<=[{a}]),(?=[{a}])'.format(a=ALPHA),
<ide> r'(?<=[{a}])([{q}\)\]\(\[])(?=[\-{a}])'.format(a=ALPHA, q=_QUOTES.replace("'", "").strip().replace(" ", ""))])
<add>from ..char_classes import TOKENIZER_INFIXES, LIST_PUNCT LIST_ELLIPSES
<add>from ..char_classes import LIST_QUOTES, CURRENCY, QUOTES, UNITS
<add>from ..char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
<ide><path>spacy/lang/hu/tokenizer_exceptions.py
<ide>
<ide> import regex as re
<ide>
<del>from ..symbols import ORTH
<del>from ..language_data.punctuation import ALPHA_LOWER, CURRENCY
<del>from ..language_data.tokenizer_exceptions import _URL_PATTERN
<add>from ..punctuation import ALPHA_LOWER, CURRENCY
<add>from ..tokenizer_exceptions import URL_PATTERN
<add>from ...symbols import ORTH
<add>
<ide>
<ide>
<ide> _exc = {}
<ide><path>spacy/lang/it/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide> from .lemmatizer import LOOKUP
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..lemmatizerlookup import Lemmatizer
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...lemmatizerlookup import Lemmatizer
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class Italian(Language):
<ide><path>spacy/lang/ja/__init__.py
<ide> # encoding: utf8
<ide> from __future__ import unicode_literals, print_function
<ide>
<del>from ..language import Language
<del>from ..attrs import LANG
<del>from ..tokens import Doc
<add>from ...language import Language
<add>from ...attrs import LANG
<add>from ...tokens import Doc
<ide>
<ide>
<ide> class Japanese(Language):
<ide><path>spacy/lang/nb/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide> from .morph_rules import MORPH_RULES
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class Norwegian(Language):
<ide><path>spacy/lang/nb/morph_rules.py
<ide> # encoding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import LEMMA
<del>from ..deprecated import PRON_LEMMA
<add>from ...symbols import LEMMA
<add>from ...deprecated import PRON_LEMMA
<ide>
<ide>
<ide> # Used the table of pronouns at https://no.wiktionary.org/wiki/Tillegg:Pronomen_i_norsk
<ide><path>spacy/lang/nb/tokenizer_exceptions.py
<ide> # encoding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import ORTH, LEMMA
<add>from ...symbols import ORTH, LEMMA
<ide>
<ide>
<ide> _exc = {}
<ide><path>spacy/lang/nl/__init__.py
<ide>
<ide> from .stop_words import STOP_WORDS
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide>
<ide><path>spacy/lang/pt/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide> from .lemmatizer import LOOKUP
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..lemmatizerlookup import Lemmatizer
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...lemmatizerlookup import Lemmatizer
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class Portuguese(Language):
<ide><path>spacy/lang/pt/tokenizer_exceptions.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import ORTH, LEMMA, NORM
<del>from ..deprecated import PRON_LEMMA
<add>from ...symbols import ORTH, LEMMA, NORM
<add>from ...deprecated import PRON_LEMMA
<ide>
<ide>
<ide> _exc = {
<ide><path>spacy/lang/sv/__init__.py
<ide> from .morph_rules import MORPH_RULES
<ide> from .lemmatizer import LEMMA_RULES, LOOKUP
<ide>
<del>from ..language_data import BASE_EXCEPTIONS
<del>from ..language import Language
<del>from ..lemmatizerlookup import Lemmatizer
<del>from ..attrs import LANG
<del>from ..util import update_exc
<add>from ..tokenizer_exceptions import BASE_EXCEPTIONS
<add>from ...language import Language
<add>from ...lemmatizerlookup import Lemmatizer
<add>from ...attrs import LANG
<add>from ...util import update_exc
<ide>
<ide>
<ide> class Swedish(Language):
<ide><path>spacy/lang/sv/morph_rules.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import LEMMA
<del>from ..deprecated import PRON_LEMMA
<add>from ...symbols import LEMMA
<add>from ...deprecated import PRON_LEMMA
<ide>
<ide>
<ide> # Used the table of pronouns at https://sv.wiktionary.org/wiki/deras
<ide><path>spacy/lang/sv/tokenizer_exceptions.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..symbols import ORTH, LEMMA, TAG, NORM
<del>from ..deprecated import PRON_LEMMA
<add>from ...symbols import ORTH, LEMMA, TAG, NORM
<add>from ...deprecated import PRON_LEMMA
<ide>
<ide>
<ide> _exc = {}
<ide><path>spacy/lang/zh/__init__.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ..language import Language
<del>from ..tokens import Doc
<add>from ...language import Language
<add>from ...tokens import Doc
<ide>
<ide>
<ide> class Chinese(Language): | 35 |
Python | Python | add "medium" size to the elastichosts driver | 4c02f616a6c55e3d10961e8b7286ffbf0798e6fa | <ide><path>libcloud/compute/drivers/elastichosts.py
<ide> 'disk': 160,
<ide> 'bandwidth': None,
<ide> },
<add> 'medium': {
<add> 'id': 'medium',
<add> 'name': 'Medium instance',
<add> 'cpu': 3000,
<add> 'memory': 4096,
<add> 'disk': 500,
<add> 'bandwidth': None,
<add> },
<ide> 'large': {
<ide> 'id': 'large',
<ide> 'name': 'Large instance',
<ide><path>test/compute/test_elastichosts.py
<ide> def test_list_nodes(self):
<ide> nodes = self.driver.list_nodes()
<ide> self.assertTrue(isinstance(nodes, list))
<ide> self.assertEqual(len(nodes), 1)
<del>
<add>
<ide> node = nodes[0]
<ide> self.assertEqual(node.public_ip[0], "1.2.3.4")
<ide> self.assertEqual(node.public_ip[1], "1.2.3.5")
<ide> self.assertEqual(node.extra['smp'], 1)
<ide>
<ide> def test_list_sizes(self):
<ide> images = self.driver.list_sizes()
<del> self.assertEqual(len(images), 5)
<del> image = images[0]
<add> self.assertEqual(len(images), 6)
<add> image = [i for i in images if i.id == 'small'][0]
<ide> self.assertEqual(image.id, 'small')
<ide> self.assertEqual(image.name, 'Small instance')
<ide> self.assertEqual(image.cpu, 2000)
<ide> def test_list_images(self):
<ide> size = sizes[0]
<ide> self.assertEqual(size.id, '38df0986-4d85-4b76-b502-3878ffc80161')
<ide> self.assertEqual(size.name, 'CentOS Linux 5.5')
<del>
<add>
<ide> def test_list_locations_response(self):
<ide> pass
<ide>
<ide> def test_create_node(self):
<ide> class ElasticHostsHttp(MockHttp):
<ide>
<ide> fixtures = ComputeFileFixtures('elastichosts')
<del>
<add>
<ide> def _servers_b605ca90_c3e6_4cee_85f8_a8ebdf8f9903_reset(self, method, url, body, headers):
<ide> return (httplib.NO_CONTENT, body, {}, httplib.responses[httplib.NO_CONTENT])
<del>
<add>
<ide> def _servers_b605ca90_c3e6_4cee_85f8_a8ebdf8f9903_destroy(self, method, url, body, headers):
<ide> return (httplib.NO_CONTENT, body, {}, httplib.responses[httplib.NO_CONTENT])
<del>
<add>
<ide> def _drives_create(self, method, url, body, headers):
<ide> body = self.fixtures.load('drives_create.json')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<add>
<ide> def _drives_0012e24a_6eae_4279_9912_3432f698cec8_image_38df0986_4d85_4b76_b502_3878ffc80161_gunzip(self, method, url, body, headers):
<ide> return (httplib.NO_CONTENT, body, {}, httplib.responses[httplib.NO_CONTENT])
<ide>
<ide> def _drives_0012e24a_6eae_4279_9912_3432f698cec8_info(self, method, url, body, headers):
<ide> body = self.fixtures.load('drives_info.json')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<add>
<ide> def _servers_create(self, method, url, body, headers):
<ide> body = self.fixtures.load('servers_create.json')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) | 2 |
Javascript | Javascript | remove debugging code | 2247a74755d031926de49c2b1cfd8c26b764a29a | <ide><path>script/lib/create-rpm-package.js
<ide> module.exports = function(packagedAppPath) {
<ide> );
<ide> fs.copySync(packagedAppPath, rpmPackageApplicationDirPath);
<ide>
<del> try {
<del> fs.chmodSync(
<del> path.join(rpmPackageApplicationDirPath, 'chrome-sandbox'),
<del> '4755'
<del> );
<del> } catch (ex) {
<del> console.log('Chmod failed');
<del>
<del> spawnSync('find', [rpmPackageDirPath, '-name', 'chrome-sandbox'], {
<del> stdio: 'inherit'
<del> });
<del> }
<add> fs.chmodSync(
<add> path.join(rpmPackageApplicationDirPath, 'chrome-sandbox'),
<add> '4755'
<add> );
<ide>
<ide> console.log(`Copying icons into "${rpmPackageIconsDirPath}"`);
<ide> fs.copySync( | 1 |
Javascript | Javascript | handle blacktable2 array access correctly | 6688c3a1f5c1ff8d0071bba8d76e60df9f99ec2f | <ide><path>pdf.js
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> if (i < end)
<ide> code <<= end - i;
<ide> if (code >= limit) {
<del> var p = table[code];
<add> var p = table[code - ((limit == -1) ? 0 : limit)];
<ide> if (p[0] == i) {
<ide> this.eatBits(i);
<ide> return [true, p[1]]; | 1 |
Javascript | Javascript | eliminate unused variables | 81f55a1045800fd37a3249b3b6d95b6b7d02e9bb | <ide><path>packages/container/lib/main.js
<ide> define("container",
<ide> var factory = factoryFor(container, fullName);
<ide>
<ide> var splitName = fullName.split(":"),
<del> type = splitName[0], name = splitName[1],
<add> type = splitName[0],
<ide> value;
<ide>
<ide> if (option(container, fullName, 'instantiate') === false) {
<ide><path>packages/ember-handlebars/lib/ext.js
<ide> function evaluateMultiPropertyBoundHelper(context, fn, normalizedProperties, opt
<ide>
<ide> bindView = new Ember._SimpleHandlebarsView(null, null, !hash.unescaped, data);
<ide> bindView.normalizedValue = function() {
<del> var args = [], value, boundOption;
<add> var args = [], boundOption;
<ide>
<ide> // Copy over bound options.
<ide> for (boundOption in boundOptions) {
<ide><path>packages/ember-handlebars/lib/helpers/collection.js
<ide> Ember.Handlebars.registerHelper('collection', function(path, options) {
<ide> }
<ide> }
<ide>
<del> var tagName = hash.tagName || collectionPrototype.tagName;
<del>
<ide> if (fn) {
<ide> itemHash.template = fn;
<ide> delete options.fn;
<ide> Ember.Handlebars.registerHelper('collection', function(path, options) {
<ide> itemHash._context = Ember.computed.alias('content');
<ide> }
<ide>
<del> var viewString = view.toString();
<del>
<ide> var viewOptions = Ember.Handlebars.ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this);
<ide> hash.itemViewClass = itemViewClass.extend(viewOptions);
<ide>
<ide><path>packages/ember-handlebars/lib/helpers/view.js
<ide> EmberHandlebars.ViewHelper = Ember.Object.create({
<ide> },
<ide>
<ide> helper: function(thisContext, path, options) {
<del> var inverse = options.inverse,
<del> data = options.data,
<del> view = data.view,
<add> var data = options.data,
<ide> fn = options.fn,
<del> hash = options.hash,
<ide> newView;
<ide>
<ide> if ('string' === typeof path) {
<ide> EmberHandlebars.ViewHelper = Ember.Object.create({
<ide>
<ide> var viewOptions = this.propertiesFromHTMLOptions(options, thisContext);
<ide> var currentView = data.view;
<del> viewOptions.templateData = options.data;
<add> viewOptions.templateData = data;
<ide> var newViewProto = newView.proto ? newView.proto() : newView;
<ide>
<ide> if (fn) {
<ide><path>packages/ember-metal/lib/chains.js
<ide> function isProto(pvalue) {
<ide> // value for the key then the node won't actually watch it. For a root node
<ide> // pass null for parent and key and object for value.
<ide> var ChainNode = Ember._ChainNode = function(parent, key, value) {
<del> var obj;
<ide> this._parent = parent;
<ide> this._key = key;
<ide>
<ide><path>packages/ember-metal/lib/computed.js
<ide> Ember.computed.alias = function(dependentKey) {
<ide> */
<ide> Ember.computed.defaultTo = function(defaultPath) {
<ide> return Ember.computed(function(key, newValue, cachedValue) {
<del> var result;
<ide> if (arguments.length === 1) {
<ide> return cachedValue != null ? cachedValue : get(this, defaultPath);
<ide> }
<ide><path>packages/ember-metal/lib/property_set.js
<ide> require('ember-metal/property_events'); // propertyWillChange, propertyDidChange
<ide> var META_KEY = Ember.META_KEY,
<ide> MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER,
<ide> IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/,
<del> propertyWillChange = Ember.propertyWillChange,
<del> propertyDidChange = Ember.propertyDidChange,
<ide> getPath = Ember._getPath;
<ide>
<ide> /**
<ide><path>packages/ember-old-router/lib/router.js
<ide> require('ember-metal/utils'); // Ember.tryFinally
<ide>
<ide> var get = Ember.get, set = Ember.set;
<ide>
<del>var merge = function(original, hash) {
<del> for (var prop in hash) {
<del> if (!hash.hasOwnProperty(prop)) { continue; }
<del> if (original.hasOwnProperty(prop)) { continue; }
<del>
<del> original[prop] = hash[prop];
<del> }
<del>};
<del>
<ide> /**
<ide> `Ember.Router` is the subclass of `Ember.StateManager` responsible for
<ide> providing URL-based application state detection. The `Ember.Router` instance
<ide><path>packages/ember-routing/lib/vendor/router.js
<ide> define("router",
<ide> @return {Array} an Array of `[handler, parameter]` tuples
<ide> */
<ide> handleURL: function(url) {
<del> var results = this.recognizer.recognize(url),
<del> objects = [];
<add> var results = this.recognizer.recognize(url);
<ide>
<ide> if (!results) {
<ide> throw new Error("No route matched the URL '" + url + "'");
<ide> define("router",
<ide> var contexts = [].slice.call(arguments, 1);
<ide>
<ide> var currentHandlerInfos = this.currentHandlerInfos,
<del> found = false, names, object, handlerInfo, handlerObj;
<add> found = false, object, handlerInfo;
<ide>
<ide> for (var i=currentHandlerInfos.length-1; i>=0; i--) {
<ide> handlerInfo = currentHandlerInfos[i];
<ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.View = Ember.CoreView.extend(
<ide> @param {Ember.RenderBuffer} buffer
<ide> */
<ide> _applyAttributeBindings: function(buffer, attributeBindings) {
<del> var attributeValue, elem, type;
<add> var attributeValue, elem;
<ide>
<ide> a_forEach(attributeBindings, function(binding) {
<ide> var split = binding.split(':'),
<ide> Ember.View = Ember.CoreView.extend(
<ide> */
<ide> destroy: function() {
<ide> var childViews = this._childViews,
<del> parent = this._parentView,
<ide> // get parentView before calling super because it'll be destroyed
<ide> nonVirtualParentView = get(this, 'parentView'),
<ide> viewName = this.viewName, | 10 |
Python | Python | add a docstring for `reverse()' | 6f4fab81d2926af47e75e0c1bae4aad17c6bca91 | <ide><path>djangorestframework/utils/__init__.py
<ide> def dict2xml(input):
<ide>
<ide>
<ide> def reverse(viewname, request, *args, **kwargs):
<add> """
<add> Do the same as :py:func:`django.core.urlresolvers.reverse` but using
<add> *request* to build a fully qualified URL.
<add> """
<ide> return request.build_absolute_uri(django_reverse(viewname, *args, **kwargs)) | 1 |
Ruby | Ruby | replace argv.named with args.remaining | 8374c3713a37385acb1894facbcfe01fd7470da9 | <ide><path>Library/Homebrew/dev-cmd/extract.rb
<ide> def extract
<ide> extract_args.parse
<ide>
<ide> # Expect exactly two named arguments: formula and tap
<del> raise UsageError if ARGV.named.length != 2
<add> raise UsageError if args.remaining.length != 2
<ide>
<del> if ARGV.named.first !~ HOMEBREW_TAP_FORMULA_REGEX
<del> name = ARGV.named.first.downcase
<add> if args.remaining.first !~ HOMEBREW_TAP_FORMULA_REGEX
<add> name = args.remaining.first.downcase
<ide> source_tap = CoreTap.instance
<ide> else
<ide> name = Regexp.last_match(3).downcase
<ide> source_tap = Tap.fetch(Regexp.last_match(1), Regexp.last_match(2))
<ide> raise TapFormulaUnavailableError.new(source_tap, name) unless source_tap.installed?
<ide> end
<ide>
<del> destination_tap = Tap.fetch(ARGV.named.second)
<add> destination_tap = Tap.fetch(args.remaining.second)
<ide> odie "Cannot extract formula to homebrew/core!" if destination_tap.core_tap?
<ide> odie "Cannot extract formula to the same tap!" if destination_tap == source_tap
<ide> destination_tap.install unless destination_tap.installed? | 1 |
Go | Go | allow network with --config-from to be --internal | afcb9fb2999495caa2e55df952f4538f0f1b630c | <ide><path>libnetwork/controller.go
<ide> func (c *controller) NewNetwork(networkType, name string, id string, options ...
<ide> if err = t.applyConfigurationTo(network); err != nil {
<ide> return nil, types.InternalErrorf("Failed to apply configuration: %v", err)
<ide> }
<add> network.generic[netlabel.Internal] = network.internal
<ide> defer func() {
<ide> if err == nil {
<ide> if err := t.getEpCnt().IncEndpointCnt(); err != nil { | 1 |
Ruby | Ruby | handle scripterror in formula | ade8128a18ec3a053306e364e31687739de8c568 | <ide><path>Library/Homebrew/exceptions.rb
<ide> def format_list(class_list)
<ide> end
<ide> end
<ide>
<add>class FormulaUnreadableError < FormulaUnavailableError
<add> attr_reader :formula_error
<add>
<add> def initialize(name, error)
<add> super(name)
<add> @formula_error = error
<add> end
<add>
<add> def to_s
<add> "#{name}: " + formula_error.to_s
<add> end
<add>end
<add>
<ide> class TapFormulaAmbiguityError < RuntimeError
<ide> attr_reader :name, :paths, :formulae
<ide>
<ide><path>Library/Homebrew/formulary.rb
<ide> def self.load_formula(name, path, contents, namespace)
<ide>
<ide> mod = Module.new
<ide> const_set(namespace, mod)
<del> mod.module_eval(contents, path)
<add> begin
<add> mod.module_eval(contents, path)
<add> rescue ScriptError => e
<add> raise FormulaUnreadableError.new(name, e)
<add> end
<ide> class_name = class_s(name)
<ide>
<ide> begin
<ide><path>Library/Homebrew/test/exceptions_test.rb
<ide> class Baz < Formula; end
<ide> FormulaClassUnavailableError.new("foo", "foo.rb", "Foo", list).to_s
<ide> end
<ide>
<add> def test_formula_unreadable_error
<add> formula_error = LoadError.new("bar")
<add> assert_equal "foo: bar", FormulaUnreadableError.new("foo", formula_error).to_s
<add> end
<add>
<ide> def test_tap_unavailable_error
<ide> assert_equal "No available tap foo.\n", TapUnavailableError.new("foo").to_s
<ide> end | 3 |
Javascript | Javascript | use socket.once, not socket.on | f26362e9381d88d4c906e3624f90fc76e9087c20 | <ide><path>lib/http.js
<ide> OutgoingMessage.prototype._writeRaw = function(data, encoding) {
<ide> var timer = setTimeout(function() {
<ide> socket.emit('close');
<ide> });
<del> socket.on('close', function() {
<add> socket.once('close', function() {
<ide> clearTimeout(timer);
<ide> });
<ide> } | 1 |
Python | Python | fix datetime_data for python versions >= 2.7 | e014ff75420eeb809699935433ab4c61bd7f6f8b | <ide><path>numpy/lib/type_check.py
<ide> class DATETIMEMETA(ctypes.Structure):
<ide> # FIXME: This needs to be kept consistent with enum in ndarrayobject.h
<ide> from numpy.core.multiarray import DATETIMEUNITS
<ide> obj = ctypes.py_object(DATETIMEUNITS)
<del> result = func(obj)
<add> if sys.version_info[:2] >= (2,7):
<add> result = func(obj, ctypes.c_char_p(None))
<add> else:
<add> result = func(obj)
<ide> _unitnum2name = ctypes.cast(ctypes.c_void_p(result), ctypes.POINTER(ctypes.c_char_p))
<ide>
<ide> return (_unitnum2name[base], struct.num, struct.den, struct.events) | 1 |
PHP | PHP | add string|array|null typehint for data | 40cd2d94332427ec1884f7331d45886c1ca48436 | <ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> public function get($url)
<ide> * response.
<ide> *
<ide> * @param string|array $url The URL to request.
<del> * @param array $data The data for the request.
<add> * @param string|array|null $data The data for the request.
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<ide> public function post($url, $data = [])
<ide> * response.
<ide> *
<ide> * @param string|array $url The URL to request.
<del> * @param array $data The data for the request.
<add> * @param string|array|null $data The data for the request.
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<ide> public function patch($url, $data = [])
<ide> * response.
<ide> *
<ide> * @param string|array $url The URL to request.
<del> * @param array $data The data for the request.
<add> * @param string|array|null $data The data for the request.
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<ide> public function options($url)
<ide> *
<ide> * @param string|array $url The URL
<ide> * @param string $method The HTTP method
<del> * @param array|null $data The request data.
<add> * @param string|array|null $data The request data.
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<ide> protected function _handleError($exception)
<ide> *
<ide> * @param string|array $url The URL
<ide> * @param string $method The HTTP method
<del> * @param array|null $data The request data.
<add> * @param string|array|null $data The request data.
<ide> * @return array The request context
<ide> */
<ide> protected function _buildRequest($url, $method, $data) | 1 |
Javascript | Javascript | use "empty" object for empty query strings | e9dc6306ca97598d6a8fe9baa7c8a8ed002287b2 | <ide><path>lib/url.js
<ide> const slashedProtocol = {
<ide> };
<ide> const querystring = require('querystring');
<ide>
<add>// This constructor is used to store parsed query string values. Instantiating
<add>// this is faster than explicitly calling `Object.create(null)` to get a
<add>// "clean" empty object (tested with v8 v4.9).
<add>function ParsedQueryString() {}
<add>ParsedQueryString.prototype = Object.create(null);
<add>
<ide> function urlParse(url, parseQueryString, slashesDenoteHost) {
<ide> if (url instanceof Url) return url;
<ide>
<ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
<ide> }
<ide> } else if (parseQueryString) {
<ide> this.search = '';
<del> this.query = {};
<add> this.query = new ParsedQueryString();
<ide> }
<ide> return this;
<ide> }
<ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
<ide> } else if (parseQueryString) {
<ide> // no query string, but parseQueryString still requested
<ide> this.search = '';
<del> this.query = {};
<add> this.query = new ParsedQueryString();
<ide> }
<ide>
<ide> var firstIdx = (questionIdx !== -1 &&
<ide><path>test/parallel/test-url.js
<ide> var parseTestsWithQueryString = {
<ide> path: '/example',
<ide> href: '/example'
<ide> },
<del> '/example?query=value':{
<add> '/example?query=value': {
<ide> protocol: null,
<ide> slashes: null,
<ide> auth: null,
<ide> for (const u in parseTestsWithQueryString) {
<ide> }
<ide> }
<ide>
<add> assert.notStrictEqual(Object.getPrototypeOf(actual.query), Object.prototype);
<add>
<ide> assert.deepEqual(actual, expected);
<ide> }
<ide> | 2 |
PHP | PHP | make fatal errors into exception | 7f2d22f6fbab1dc98cac3669693a6d1f7b01c612 | <ide><path>src/Error/ErrorTrap.php
<ide> public function handleError(
<ide> if (!(error_reporting() & $code)) {
<ide> return false;
<ide> }
<del> $debug = Configure::read('debug');
<add> if ($code === E_USER_ERROR || $code === E_ERROR || $code === E_PARSE) {
<add> throw new FatalErrorException($description, $code, $file, $line);
<add> }
<add>
<ide> /** @var array $trace */
<ide> $trace = Debugger::trace(['start' => 1, 'format' => 'points']);
<ide> $error = new PhpError($code, $description, $file, $line, $trace);
<ide>
<add> $debug = Configure::read('debug');
<ide> $renderer = $this->renderer();
<ide> $logger = $this->logger();
<ide>
<ide><path>tests/TestCase/Error/ErrorTrapTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Error\ErrorLogger;
<ide> use Cake\Error\ErrorTrap;
<add>use Cake\Error\FatalErrorException;
<ide> use Cake\Error\PhpError;
<ide> use Cake\Error\Renderer\ConsoleErrorRenderer;
<ide> use Cake\Error\Renderer\HtmlErrorRenderer;
<ide> public function testRegisterAndRendering()
<ide> $this->assertStringContainsString('Oh no it was bad', $output);
<ide> }
<ide>
<add> public function testRegisterAndHandleFatalUserError()
<add> {
<add> $trap = new ErrorTrap(['errorRenderer' => TextErrorRenderer::class]);
<add> $trap->register();
<add> try {
<add> ob_start();
<add> trigger_error('Oh no it was bad', E_USER_ERROR);
<add> $output = ob_get_clean();
<add> $this->assertEmpty($output);
<add> } catch (FatalErrorException $e) {
<add> $this->assertEquals('Oh no it was bad', $e->getMessage());
<add> $this->assertEquals(E_USER_ERROR, $e->getCode());
<add> } finally {
<add> restore_error_handler();
<add> }
<add> }
<add>
<ide> public function testRegisterAndLogging()
<ide> {
<ide> Log::setConfig('test_error', [ | 2 |
Go | Go | add comments in graph.go | 99b36c2c326ccc11e726eee6ee78a0baf166ef96 | <ide><path>graph.go
<ide> import (
<ide> "time"
<ide> )
<ide>
<add>// A Graph is a store for versioned filesystem images, and the relationship between them.
<ide> type Graph struct {
<ide> Root string
<ide> }
<ide>
<add>// NewGraph instanciates a new graph at the given root path in the filesystem.
<add>// `root` will be created if it doesn't exist.
<ide> func NewGraph(root string) (*Graph, error) {
<ide> abspath, err := filepath.Abs(root)
<ide> if err != nil {
<ide> func (graph *Graph) IsNotExist(err error) bool {
<ide> return err != nil && strings.Contains(err.Error(), "does not exist")
<ide> }
<ide>
<add>// Exists returns true if an image is registered at the given id.
<add>// If the image doesn't exist or if an error is encountered, false is returned.
<ide> func (graph *Graph) Exists(id string) bool {
<ide> if _, err := graph.Get(id); err != nil {
<ide> return false
<ide> }
<ide> return true
<ide> }
<ide>
<add>// Get returns the image with the given id, or an error if the image doesn't exist.
<ide> func (graph *Graph) Get(id string) (*Image, error) {
<ide> // FIXME: return nil when the image doesn't exist, instead of an error
<ide> img, err := LoadImage(graph.imageRoot(id))
<ide> func (graph *Graph) Get(id string) (*Image, error) {
<ide> return img, nil
<ide> }
<ide>
<add>// Create creates a new image and registers it in the graph.
<ide> func (graph *Graph) Create(layerData Archive, container *Container, comment string) (*Image, error) {
<ide> img := &Image{
<ide> Id: GenerateId(),
<ide> func (graph *Graph) Create(layerData Archive, container *Container, comment stri
<ide> return img, nil
<ide> }
<ide>
<add>// Register imports a pre-existing image into the graph.
<add>// FIXME: pass img as first argument
<ide> func (graph *Graph) Register(layerData Archive, img *Image) error {
<ide> if err := ValidateId(img.Id); err != nil {
<ide> return err
<ide> func (graph *Graph) Register(layerData Archive, img *Image) error {
<ide> return nil
<ide> }
<ide>
<add>// Mktemp creates a temporary sub-directory inside the graph's filesystem.
<ide> func (graph *Graph) Mktemp(id string) (string, error) {
<ide> tmp, err := NewGraph(path.Join(graph.Root, ":tmp:"))
<ide> if err != nil {
<ide> func (graph *Graph) Mktemp(id string) (string, error) {
<ide> return tmp.imageRoot(id), nil
<ide> }
<ide>
<add>// Garbage returns the "garbage", a staging area for deleted images.
<add>// This allows images ot be deleted atomically by os.Rename(), instead of
<add>// os.RemoveAll() which is prone to race conditions
<ide> func (graph *Graph) Garbage() (*Graph, error) {
<ide> return NewGraph(path.Join(graph.Root, ":garbage:"))
<ide> }
<ide> func isNotEmpty(err error) bool {
<ide> return strings.Contains(err.Error(), " not empty")
<ide> }
<ide>
<add>// Delete atomically removes an image from the graph.
<ide> func (graph *Graph) Delete(id string) error {
<ide> garbage, err := graph.Garbage()
<ide> if err != nil {
<ide> func (graph *Graph) Delete(id string) error {
<ide> return nil
<ide> }
<ide>
<add>// Undelete moves an image back from the garbage to the main graph
<ide> func (graph *Graph) Undelete(id string) error {
<ide> garbage, err := graph.Garbage()
<ide> if err != nil {
<ide> func (graph *Graph) Undelete(id string) error {
<ide> return os.Rename(garbage.imageRoot(id), graph.imageRoot(id))
<ide> }
<ide>
<add>// GarbageCollect definitely deletes all images moved to the garbage
<ide> func (graph *Graph) GarbageCollect() error {
<ide> garbage, err := graph.Garbage()
<ide> if err != nil {
<ide> func (graph *Graph) GarbageCollect() error {
<ide> return os.RemoveAll(garbage.Root)
<ide> }
<ide>
<add>// Map returns a list of all images in the graph, addressable by ID
<ide> func (graph *Graph) Map() (map[string]*Image, error) {
<ide> // FIXME: this should replace All()
<ide> all, err := graph.All()
<ide> func (graph *Graph) Map() (map[string]*Image, error) {
<ide> return images, nil
<ide> }
<ide>
<add>// All returns a list of all images in the graph
<ide> func (graph *Graph) All() ([]*Image, error) {
<ide> var images []*Image
<ide> err := graph.WalkAll(func(image *Image) {
<ide> func (graph *Graph) All() ([]*Image, error) {
<ide> return images, err
<ide> }
<ide>
<add>// WalkAll iterates over each image in the graph, and passes it to a handler.
<add>// The walking order is undetermined.
<ide> func (graph *Graph) WalkAll(handler func(*Image)) error {
<ide> files, err := ioutil.ReadDir(graph.Root)
<ide> if err != nil {
<ide> func (graph *Graph) WalkAll(handler func(*Image)) error {
<ide> return nil
<ide> }
<ide>
<add>// ByParent returns a lookup table of images by their parent.
<add>// If an image of id ID has 3 children images, then the value for key ID
<add>// will be a list of 3 images.
<add>// If an image has no children, it will not have an entry in the table.
<ide> func (graph *Graph) ByParent() (map[string][]*Image, error) {
<ide> byParent := make(map[string][]*Image)
<ide> err := graph.WalkAll(func(image *Image) {
<ide> func (graph *Graph) ByParent() (map[string][]*Image, error) {
<ide> return byParent, err
<ide> }
<ide>
<add>// Heads returns all heads in the graph, keyed by id.
<add>// A head is an image which is not the parent of another image in the graph.
<ide> func (graph *Graph) Heads() (map[string]*Image, error) {
<ide> heads := make(map[string]*Image)
<ide> byParent, err := graph.ByParent() | 1 |
PHP | PHP | compare user instances in auth tests | 86d46309b0499cbc1b1ab8692a08c627d2e50940 | <ide><path>tests/Auth/AuthGuardTest.php
<ide> public function testUserMethodReturnsCachedUser()
<ide> $user = m::mock('Illuminate\Contracts\Auth\Authenticatable');
<ide> $mock = $this->getGuard();
<ide> $mock->setUser($user);
<del> $this->assertEquals($user, $mock->user());
<add> $this->assertSame($user, $mock->user());
<ide> }
<ide>
<ide> public function testNullIsReturnedForUserIfNoUserFound()
<ide> public function testUserIsSetToRetrievedUser()
<ide> $mock->getSession()->shouldReceive('get')->once()->andReturn(1);
<ide> $user = m::mock('Illuminate\Contracts\Auth\Authenticatable');
<ide> $mock->getProvider()->shouldReceive('retrieveById')->once()->with(1)->andReturn($user);
<del> $this->assertEquals($user, $mock->user());
<del> $this->assertEquals($user, $mock->getUser());
<add> $this->assertSame($user, $mock->user());
<add> $this->assertSame($user, $mock->getUser());
<ide> }
<ide>
<ide> public function testLogoutRemovesSessionTokenAndRememberMeCookie()
<ide> public function testLoginUsingIdLogsInWithUser()
<ide> $guard->getProvider()->shouldReceive('retrieveById')->once()->with(10)->andReturn($user);
<ide> $guard->shouldReceive('login')->once()->with($user, false);
<ide>
<del> $this->assertEquals($user, $guard->loginUsingId(10));
<add> $this->assertSame($user, $guard->loginUsingId(10));
<ide> }
<ide>
<ide> public function testLoginUsingIdFailure()
<ide> public function testOnceUsingIdSetsUser()
<ide> $guard->getProvider()->shouldReceive('retrieveById')->once()->with(10)->andReturn($user);
<ide> $guard->shouldReceive('setUser')->once()->with($user);
<ide>
<del> $this->assertEquals($user, $guard->onceUsingId(10));
<add> $this->assertSame($user, $guard->onceUsingId(10));
<ide> }
<ide>
<ide> public function testOnceUsingIdFailure()
<ide> public function testUserUsesRememberCookieIfItExists()
<ide> $user->shouldReceive('getAuthIdentifier')->once()->andReturn('bar');
<ide> $guard->getSession()->shouldReceive('set')->with($guard->getName(), 'bar')->once();
<ide> $session->shouldReceive('migrate')->once();
<del> $this->assertEquals($user, $guard->user());
<add> $this->assertSame($user, $guard->user());
<ide> $this->assertTrue($guard->viaRemember());
<ide> }
<ide> | 1 |
Ruby | Ruby | check git repos for validity before updating | 8a60d852b3ad4ba0dc6c59dc9a5d956eed300e1d | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def fetch
<ide> unless system "/usr/bin/which git"
<ide>
<ide> ohai "Cloning #{@url}"
<add>
<add> if @clone.exist?
<add> Dir.chdir(@clone) do
<add> # Check for interupted clone from a previous install
<add> unless system 'git', 'status', '-s'
<add> ohai "Removing invalid .git repo from cache"
<add> FileUtils.rm_rf @clone
<add> end
<add> end
<add> end
<add>
<ide> unless @clone.exist?
<ide> safe_system 'git', 'clone', @url, @clone # indeed, leave it verbose
<ide> else | 1 |
Javascript | Javascript | add destructors to pooled classes in reactchildren | 16d8f20576088690e0c5cd2a749f550b7217dde1 | <ide><path>src/isomorphic/children/ReactChildren.js
<ide> function ForEachBookKeeping(forEachFunction, forEachContext) {
<ide> this.context = forEachContext;
<ide> this.count = 0;
<ide> }
<add>ForEachBookKeeping.prototype.destructor = function() {
<add> this.func = null;
<add> this.context = null;
<add> this.count = 0;
<add>};
<ide> PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
<ide>
<ide> function forEachSingleChild(traverseContext, child, name) {
<ide> function MapBookKeeping(mapResult, mapFunction, mapContext) {
<ide> this.context = mapContext;
<ide> this.count = 0;
<ide> }
<add>MapBookKeeping.prototype.destructor = function() {
<add> this.result = null;
<add> this.func = null;
<add> this.context = null;
<add> this.count = 0;
<add>};
<ide> PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler);
<ide>
<ide> function mapSingleChildIntoContext(traverseContext, child, name) {
<ide><path>src/renderers/dom/client/eventPlugins/FallbackCompositionState.js
<ide> function FallbackCompositionState(root) {
<ide> }
<ide>
<ide> assign(FallbackCompositionState.prototype, {
<add> destructor: function() {
<add> this._root = null;
<add> this._startText = null;
<add> this._fallbackText = null;
<add> },
<add>
<ide> /**
<ide> * Get current text of input.
<ide> *
<ide><path>src/shared/utils/PooledClass.js
<ide> var standardReleaser = function(instance) {
<ide> instance instanceof Klass,
<ide> 'Trying to release an instance into a pool of a different type.'
<ide> );
<del> if (instance.destructor) {
<del> instance.destructor();
<del> }
<add> instance.destructor();
<ide> if (Klass.instancePool.length < Klass.poolSize) {
<ide> Klass.instancePool.push(instance);
<ide> }
<ide><path>src/shared/utils/__tests__/PooledClass-test.js
<ide> describe('Pooled class', function() {
<ide> beforeEach(function() {
<ide> PooledClass = require('PooledClass');
<ide> PoolableClass = function() {};
<add> PoolableClass.prototype.destructor = function() {};
<ide> PooledClass.addPoolingTo(PoolableClass);
<ide> });
<ide>
<ide> describe('Pooled class', function() {
<ide> var PoolableClassWithMultiArguments = function(a, b) {
<ide> log.push(a, b);
<ide> };
<add> PoolableClassWithMultiArguments.prototype.destructor = function() {};
<ide> PooledClass.addPoolingTo(
<ide> PoolableClassWithMultiArguments,
<ide> PooledClass.twoArgumentPooler
<ide> describe('Pooled class', function() {
<ide> var PoolableClassWithOneArgument = function(a) {
<ide> log.push(a);
<ide> };
<add> PoolableClassWithOneArgument.prototype.destructor = function() {};
<ide> PooledClass.addPoolingTo(
<ide> PoolableClassWithOneArgument
<ide> );
<ide> describe('Pooled class', function() {
<ide> var PoolableClassWithOneArgument = function(a) {
<ide> log.push(a);
<ide> };
<add> PoolableClassWithOneArgument.prototype.destructor = function() {};
<ide> PooledClass.addPoolingTo(
<ide> PoolableClassWithOneArgument
<ide> );
<ide> describe('Pooled class', function() {
<ide> it('should throw when the class releases an instance of a different type',
<ide> function() {
<ide> var RandomClass = function() {};
<add> RandomClass.prototype.destructor = function() {};
<ide> PooledClass.addPoolingTo(RandomClass);
<ide> var randomInstance = RandomClass.getPooled();
<ide> PoolableClass.getPooled();
<ide> describe('Pooled class', function() {
<ide> );
<ide> }
<ide> );
<add>
<add> it('should throw if no destructor is defined', function() {
<add> var ImmortalClass = function() {};
<add> PooledClass.addPoolingTo(ImmortalClass);
<add> var inst = ImmortalClass.getPooled();
<add> expect(function() {
<add> ImmortalClass.release(inst);
<add> }).toThrow();
<add> });
<ide> }); | 4 |
Mixed | Javascript | move dep0113 to end-of-life | b8018f407b2ae2daa70d41b2aa9dbbc5ca921b0f | <ide><path>doc/api/deprecations.md
<ide> accessed outside of Node.js core: `Socket.prototype._handle`,
<ide> ### DEP0113: Cipher.setAuthTag(), Decipher.getAuthTag()
<ide> <!-- YAML
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/26249
<add> description: End-of-Life.
<ide> - version: v11.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/22126
<ide> description: Runtime deprecation.
<ide> -->
<ide>
<del>Type: Runtime
<add>Type: End-of-Life
<ide>
<del>With the current crypto API, having `Cipher.setAuthTag()` and
<del>`Decipher.getAuthTag()` is not helpful and both functions will throw an error
<del>when called. They have never been documented and will be removed in a future
<del>release.
<add>`Cipher.setAuthTag()` and `Decipher.getAuthTag()` are no longer available. They
<add>were never documented and would throw when called.
<ide>
<ide> <a id="DEP0114"></a>
<ide> ### DEP0114: crypto._toBuf()
<ide><path>lib/internal/crypto/cipher.js
<ide> const {
<ide> const assert = require('internal/assert');
<ide> const LazyTransform = require('internal/streams/lazy_transform');
<ide>
<del>const { deprecate, normalizeEncoding } = require('internal/util');
<add>const { normalizeEncoding } = require('internal/util');
<ide>
<ide> // Lazy loaded for startup performance.
<ide> let StringDecoder;
<ide> function setAuthTag(tagbuf) {
<ide> return this;
<ide> }
<ide>
<del>Object.defineProperty(Cipher.prototype, 'setAuthTag', {
<del> get: deprecate(() => setAuthTag,
<del> 'Cipher.setAuthTag is deprecated and will be removed in a ' +
<del> 'future version of Node.js.',
<del> 'DEP0113')
<del>});
<del>
<ide> Cipher.prototype.setAAD = function setAAD(aadbuf, options) {
<ide> if (!isArrayBufferView(aadbuf)) {
<ide> throw new ERR_INVALID_ARG_TYPE('buffer',
<ide> function addCipherPrototypeFunctions(constructor) {
<ide> constructor.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
<ide> if (constructor === Cipheriv) {
<ide> constructor.prototype.getAuthTag = Cipher.prototype.getAuthTag;
<del> Object.defineProperty(constructor.prototype, 'setAuthTag', {
<del> get: deprecate(() => setAuthTag,
<del> 'Cipher.setAuthTag is deprecated and will be removed in ' +
<del> 'a future version of Node.js.',
<del> 'DEP0113')
<del> });
<ide> } else {
<ide> constructor.prototype.setAuthTag = setAuthTag;
<del> Object.defineProperty(constructor.prototype, 'getAuthTag', {
<del> get: deprecate(() => constructor.prototype.getAuthTag,
<del> 'Decipher.getAuthTag is deprecated and will be removed ' +
<del> 'in a future version of Node.js.',
<del> 'DEP0113')
<del> });
<ide> }
<ide> constructor.prototype.setAAD = Cipher.prototype.setAAD;
<ide> } | 2 |
Text | Text | translate 10.5-clone-with-props.md to japanese | 2a81f1229af9d4b4b5b444f88325bd8279471682 | <ide><path>docs/docs/10.5-clone-with-props.ja-JP.md
<add>---
<add>id: clone-with-props
<add>title: ReactElementsをクローンすること
<add>permalink: clone-with-props-ja-JP.html
<add>prev: test-utils-ja-JP.html
<add>next: create-fragment-ja-JP.html
<add>---
<add>
<add>> 注意:
<add>> `cloneWithProps` は使用不可になりました。[React.cloneElement](top-level-api-ja-JP.html#react.cloneelement)を代わりに使用してください。
<add>
<add>元のReact要素とは異なるプロパティを持った要素のコピーを作成したいと考える稀なケースがあるかと思います。1つの例としては、以下のように、 `this.props.children` に渡すように要素をクローンし、異なるプロパティを持つようそれらをレンダリングするものです。
<add>
<add>```js
<add>var _makeBlue = function(element) {
<add> return React.addons.cloneWithProps(element, {style: {color: 'blue'}});
<add>};
<add>
<add>var Blue = React.createClass({
<add> render: function() {
<add> var blueChildren = React.Children.map(this.props.children, _makeBlue);
<add> return <div>{blueChildren}</div>;
<add> }
<add>});
<add>
<add>React.render(
<add> <Blue>
<add> <p>This text is blue.</p>
<add> </Blue>,
<add> document.getElementById('container')
<add>);
<add>```
<add>
<add>`cloneWithProps` は `key` や `ref` をクローンされた要素に渡すことはありません。 `className` や `style` は自動的にマージされます。
<ide>\ No newline at end of file | 1 |
Ruby | Ruby | save ~9% of object allocations on heavy requests | b474d06d5ea646c8145b07c8acbf1181c9e0b2aa | <ide><path>activesupport/lib/active_support/per_thread_registry.rb
<ide> module ActiveSupport
<ide> #
<ide> # If the class has an initializer, it must accept no arguments.
<ide> module PerThreadRegistry
<add> def self.extended(object)
<add> object.instance_variable_set '@per_thread_registry_key', object.name.freeze
<add> end
<add>
<ide> def instance
<del> Thread.current[name] ||= new
<add> Thread.current[@per_thread_registry_key] ||= new
<ide> end
<ide>
<ide> protected
<del>
<ide> def method_missing(name, *args, &block) # :nodoc:
<ide> # Caches the method definition as a singleton method of the receiver.
<ide> define_singleton_method(name) do |*a, &b| | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.