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 safe rel to link | 2c3428a4fa762e7cdca8bb0995f509e33930b669 | <ide><path>packages/learn/src/introductions/coding-interview-prep/project-euler/index.md
<ide> superBlock: Coding Interview Prep
<ide> >
<ide> > Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
<ide> >
<del>>_from the Project Euler [homepage](https://projecteuler.net/)_
<add>>_from the Project Euler <a href='https://projecteuler.net/' rel='noopener noreferrer'>home page</a>_ | 1 |
Text | Text | add v3.20.4 to changelog.md | a497a8e7354c334509d0b0817b2bde0126deda3c | <ide><path>CHANGELOG.md
<ide> - [#18993](https://github.com/emberjs/ember.js/pull/18993) [DEPRECATION] Deprecate `getWithDefault` per [RFC #554](https://github.com/emberjs/rfcs/blob/master/text/0554-deprecate-getwithdefault.md).
<ide> - [#17571](https://github.com/emberjs/ember.js/pull/17571) [BUGFIX] Avoid tampering `queryParam` argument in RouterService#isActive
<ide>
<add>### v3.20.4 (August 11, 2020)
<add>
<add>- [#19047](https://github.com/emberjs/ember.js/pull/19047) Ensure `inject-babel-helpers` plugin can be parallelized
<add>- [#19089](https://github.com/emberjs/ember.js/pull/19089) Update rendering engine to improve immediate encoding performance
<add>- [#19082](https://github.com/emberjs/ember.js/pull/19082) Simplify mixin application
<add>- [#19088](https://github.com/emberjs/ember.js/pull/19088) Simplify factory instantiation from the container
<add>- [#19028](https://github.com/emberjs/ember.js/pull/19028) Ensure setter CP's with dependent keys on curly components can be two way bound
<add>- [#19077](https://github.com/emberjs/ember.js/pull/19077) Simplify `get` and improve `computed` caching scheme.
<add>- [#19065](https://github.com/emberjs/ember.js/pull/19065) / [#19072](https://github.com/emberjs/ember.js/pull/19072) - Updates GlimmerVM to improve internal destroyable system and improve tag / revision computation.
<add>- [#19081](https://github.com/emberjs/ember.js/pull/19081) Reduces template compilation size in production builds.
<add>
<ide> ### v3.20.3 (July 30, 2020)
<ide>
<ide> - [#19048](https://github.com/emberjs/ember.js/pull/19048) [BUGFIX] Update `router.js` to ensure `transition.abort` works for query param only transitions | 1 |
Javascript | Javascript | correct the number of expected tests | da148f158f40b474841ad7a60cc39c5868cf420c | <ide><path>test/unit/core.js
<ide> test("isFunction", function() {
<ide> });
<ide>
<ide> test( "isNumeric", function() {
<del> expect( 38 );
<add> expect( 37 );
<ide>
<ide> var t = jQuery.isNumeric,
<ide> Traditionalists = /** @constructor */ function(n) { | 1 |
PHP | PHP | fix tests parameter typehints | 83d806918d339a5e7e92580e7ebbb0b870323a25 | <ide><path>tests/TestCase/Error/ErrorHandlerTest.php
<ide> public function memoryLimitProvider()
<ide> * @dataProvider memoryLimitProvider
<ide> * @return void
<ide> */
<del> public function testIncreaseMemoryLimit($start, $adjust, $expected)
<add> public function testIncreaseMemoryLimit(string $start, int $adjust, string $expected)
<ide> {
<ide> $initial = ini_get('memory_limit');
<ide> $this->skipIf(strlen($initial) === 0, 'Cannot read memory limit, and cannot test increasing it.'); | 1 |
Java | Java | fix typos in mergedannotationscollectiontests | d85a6c0bea2b1f2a33809475df0674479ea7f424 | <ide><path>spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsCollectionTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> void createWhenAnnotationAggregateIndexIsNotZeroThrowsException() {
<ide> }
<ide>
<ide> @Test
<del> void interateIteratesInCorrectOrder() {
<add> void iterateIteratesInCorrectOrder() {
<ide> MergedAnnotations annotations = getDirectAndSimple();
<ide> List<Class<?>> types = new ArrayList<>();
<ide> for (MergedAnnotation<?> annotation : annotations) {
<ide> void isDirectlyPresentWhenNotPresentReturnsFalse() {
<ide>
<ide> @Test
<ide> void getReturnsAppropriateAnnotation() {
<del> MergedAnnotations annotations = getMutiRoute1();
<del> assertThat(annotations.get(MutiRouteTarget.class).getString(
<add> MergedAnnotations annotations = getMultiRoute1();
<add> assertThat(annotations.get(MultiRouteTarget.class).getString(
<ide> MergedAnnotation.VALUE)).isEqualTo("12");
<del> assertThat(annotations.get(MutiRouteTarget.class.getName()).getString(
<add> assertThat(annotations.get(MultiRouteTarget.class.getName()).getString(
<ide> MergedAnnotation.VALUE)).isEqualTo("12");
<ide> }
<ide>
<ide> void getWhenNotPresentReturnsMissing() {
<ide>
<ide> @Test
<ide> void getWithPredicateReturnsOnlyMatching() {
<del> MergedAnnotations annotations = getMutiRoute1();
<del> assertThat(annotations.get(MutiRouteTarget.class,
<add> MergedAnnotations annotations = getMultiRoute1();
<add> assertThat(annotations.get(MultiRouteTarget.class,
<ide> annotation -> annotation.getDistance() >= 3).getString(
<ide> MergedAnnotation.VALUE)).isEqualTo("111");
<ide> }
<ide>
<ide> @Test
<ide> void getWithSelectorReturnsSelected() {
<del> MergedAnnotations annotations = getMutiRoute1();
<del> MergedAnnotationSelector<MutiRouteTarget> deepest = (existing,
<add> MergedAnnotations annotations = getMultiRoute1();
<add> MergedAnnotationSelector<MultiRouteTarget> deepest = (existing,
<ide> candidate) -> candidate.getDistance() > existing.getDistance() ? candidate
<ide> : existing;
<del> assertThat(annotations.get(MutiRouteTarget.class, null, deepest).getString(
<add> assertThat(annotations.get(MultiRouteTarget.class, null, deepest).getString(
<ide> MergedAnnotation.VALUE)).isEqualTo("111");
<ide> }
<ide>
<ide> void streamStreamsInCorrectOrder() {
<ide>
<ide> @Test
<ide> void streamWithTypeStreamsInCorrectOrder() {
<del> MergedAnnotations annotations = getMutiRoute1();
<add> MergedAnnotations annotations = getMultiRoute1();
<ide> List<String> values = new ArrayList<>();
<del> annotations.stream(MutiRouteTarget.class).forEach(
<add> annotations.stream(MultiRouteTarget.class).forEach(
<ide> annotation -> values.add(annotation.getString(MergedAnnotation.VALUE)));
<ide> assertThat(values).containsExactly("12", "111");
<ide> }
<ide>
<ide> @Test
<del> void getMetaWhenRootHasAttributeValuesShouldAlaisAttributes() {
<del> MergedAnnotation<Alaised> root = MergedAnnotation.of(null, null, Alaised.class,
<add> void getMetaWhenRootHasAttributeValuesShouldAliasAttributes() {
<add> MergedAnnotation<Aliased> root = MergedAnnotation.of(null, null, Aliased.class,
<ide> Collections.singletonMap("testAlias", "test"));
<ide> MergedAnnotations annotations = MergedAnnotationsCollection.of(
<ide> Collections.singleton(root));
<del> MergedAnnotation<AlaisTarget> metaAnnotation = annotations.get(AlaisTarget.class);
<add> MergedAnnotation<AliasTarget> metaAnnotation = annotations.get(AliasTarget.class);
<ide> assertThat(metaAnnotation.getString("test")).isEqualTo("test");
<ide> }
<ide>
<ide> @Test
<del> void getMetaWhenRootHasNoAttributeValuesShouldAlaisAttributes() {
<del> MergedAnnotation<Alaised> root = MergedAnnotation.of(null, null, Alaised.class,
<add> void getMetaWhenRootHasNoAttributeValuesShouldAliasAttributes() {
<add> MergedAnnotation<Aliased> root = MergedAnnotation.of(null, null, Aliased.class,
<ide> Collections.emptyMap());
<ide> MergedAnnotations annotations = MergedAnnotationsCollection.of(
<ide> Collections.singleton(root));
<del> MergedAnnotation<AlaisTarget> metaAnnotation = annotations.get(AlaisTarget.class);
<add> MergedAnnotation<AliasTarget> metaAnnotation = annotations.get(AliasTarget.class);
<ide> assertThat(root.getString("testAlias")).isEqualTo("newdefault");
<ide> assertThat(metaAnnotation.getString("test")).isEqualTo("newdefault");
<ide> }
<ide> private MergedAnnotations getDirectAndSimple() {
<ide> return MergedAnnotationsCollection.of(list);
<ide> }
<ide>
<del> private MergedAnnotations getMutiRoute1() {
<add> private MergedAnnotations getMultiRoute1() {
<ide> List<MergedAnnotation<?>> list = new ArrayList<>();
<del> list.add(MergedAnnotation.of(null, null, MutiRoute1.class,
<add> list.add(MergedAnnotation.of(null, null, MultiRoute1.class,
<ide> Collections.emptyMap()));
<ide> return MergedAnnotationsCollection.of(list);
<ide> }
<ide> private MergedAnnotations getMutiRoute1() {
<ide> }
<ide>
<ide> @Retention(RetentionPolicy.RUNTIME)
<del> @interface MutiRouteTarget {
<add> @interface MultiRouteTarget {
<ide>
<ide> String value();
<ide>
<ide> }
<ide>
<del> @MutiRoute11
<del> @MutiRoute12
<add> @MultiRoute11
<add> @MultiRoute12
<ide> @Retention(RetentionPolicy.RUNTIME)
<del> @interface MutiRoute1 {
<add> @interface MultiRoute1 {
<ide>
<ide> }
<ide>
<del> @MutiRoute111
<add> @MultiRoute111
<ide> @Retention(RetentionPolicy.RUNTIME)
<del> @interface MutiRoute11 {
<add> @interface MultiRoute11 {
<ide>
<ide> }
<ide>
<del> @MutiRouteTarget("12")
<add> @MultiRouteTarget("12")
<ide> @Retention(RetentionPolicy.RUNTIME)
<del> @interface MutiRoute12 {
<add> @interface MultiRoute12 {
<ide>
<ide> }
<ide>
<del> @MutiRouteTarget("111")
<add> @MultiRouteTarget("111")
<ide> @Retention(RetentionPolicy.RUNTIME)
<del> @interface MutiRoute111 {
<add> @interface MultiRoute111 {
<ide>
<ide> }
<ide>
<ide> @Retention(RetentionPolicy.RUNTIME)
<del> @interface AlaisTarget {
<add> @interface AliasTarget {
<ide>
<ide> String test() default "default";
<ide>
<ide> }
<ide>
<ide> @Retention(RetentionPolicy.RUNTIME)
<del> @AlaisTarget
<del> @interface Alaised {
<add> @AliasTarget
<add> @interface Aliased {
<ide>
<del> @AliasFor(annotation = AlaisTarget.class, attribute = "test")
<add> @AliasFor(annotation = AliasTarget.class, attribute = "test")
<ide> String testAlias() default "newdefault";
<ide>
<ide> } | 1 |
Python | Python | add fp16 to transformer with benchmark tests. | b7e97bec293f668238aba8467286f3321b6ebd83 | <ide><path>official/resnet/resnet_run_loop.py
<ide> def define_resnet_flags(resnet_size_choices=None, dynamic_loss_scale=False,
<ide> datasets_num_private_threads=True,
<ide> datasets_num_parallel_batches=True,
<ide> dynamic_loss_scale=dynamic_loss_scale,
<del> fp16_implementation=fp16_implementation)
<add> fp16_implementation=fp16_implementation,
<add> loss_scale=True)
<ide> flags_core.define_image()
<ide> flags_core.define_benchmark()
<ide> flags.adopt_module_key_flags(flags_core)
<ide><path>official/transformer/transformer_estimator_benchmark.py
<ide> def __init__(self, output_dir=None, root_data_dir=None, **kwargs):
<ide> super(TransformerBaseEstimatorAccuracy, self).__init__(
<ide> output_dir=output_dir, flag_methods=flag_methods)
<ide>
<del> def benchmark_graph_1_gpu(self):
<del> """Benchmark graph mode 1 gpu.
<add> def benchmark_graph_2_gpu(self):
<add> """Benchmark graph mode 2 gpus.
<ide>
<ide> The paper uses 8 GPUs and a much larger effective batch size, this is will
<ide> not converge to the 27.3 BLEU (uncased) SOTA.
<ide> """
<ide> self._setup()
<del> FLAGS.num_gpus = 1
<add> FLAGS.num_gpus = 2
<ide> FLAGS.data_dir = self.train_data_dir
<ide> FLAGS.vocab_file = self.vocab_file
<ide> # Sets values directly to avoid validation check.
<ide> FLAGS['bleu_source'].value = self.bleu_source
<ide> FLAGS['bleu_ref'].value = self.bleu_ref
<ide> FLAGS.param_set = 'base'
<del> FLAGS.batch_size = 4096
<add> FLAGS.batch_size = 4096 * 2
<ide> FLAGS.train_steps = 100000
<ide> FLAGS.steps_between_evals = 5000
<del> FLAGS.model_dir = self._get_model_dir('benchmark_graph_1_gpu')
<add> FLAGS.model_dir = self._get_model_dir('benchmark_graph_2_gpu')
<ide> FLAGS.hooks = ['ExamplesPerSecondHook']
<del> self._run_and_report_benchmark()
<add> # These bleu scores are based on test runs after at this limited
<add> # number of steps and batch size after verifying SOTA at 8xV100s.
<add> self._run_and_report_benchmark(bleu_min=25.3, bleu_max=26)
<ide>
<del> def benchmark_graph_2_gpu(self):
<del> """Benchmark graph mode 2 gpus.
<add> def benchmark_graph_fp16_2_gpu(self):
<add> """Benchmark 2 gpu with fp16 mixed-precision.
<ide>
<del> The paper uses 8 GPUs and a much larger effective batch size, this is will
<del> not converge to the 27.3 BLEU (uncased) SOTA.
<add> The paper uses 8 GPUs and a much larger effective batch-size,
<add> this is unlikely to hit the target bleu score regardless of
<add> number of steps.
<ide> """
<ide> self._setup()
<ide> FLAGS.num_gpus = 2
<add> FLAGS.dtype = 'fp16'
<ide> FLAGS.data_dir = self.train_data_dir
<ide> FLAGS.vocab_file = self.vocab_file
<ide> # Sets values directly to avoid validation check.
<ide> def benchmark_graph_2_gpu(self):
<ide> FLAGS.batch_size = 4096 * 2
<ide> FLAGS.train_steps = 100000
<ide> FLAGS.steps_between_evals = 5000
<del> FLAGS.model_dir = self._get_model_dir('benchmark_graph_2_gpu')
<add> FLAGS.model_dir = self._get_model_dir('benchmark_graph_fp16_2_gpu')
<ide> FLAGS.hooks = ['ExamplesPerSecondHook']
<del> self._run_and_report_benchmark()
<add> # These bleu scores are based on test runs after at this limited
<add> # number of steps and batch size after verifying SOTA at 8xV100s.
<add> self._run_and_report_benchmark(bleu_min=25.3, bleu_max=26)
<ide>
<ide> def benchmark_graph_8_gpu(self):
<ide> """Benchmark graph mode 8 gpus.
<ide>
<del> SOTA is 27.3 BLEU (uncased).
<add> Best so far is 27.2 with 4048 * 8 at 75,000 steps.
<add> Other test: 2024 * 8 peaked at 26.66 at 100,000 steps.
<ide> """
<ide> self._setup()
<ide> FLAGS.num_gpus = 8
<ide> def benchmark_graph_8_gpu(self):
<ide> FLAGS['bleu_source'].value = self.bleu_source
<ide> FLAGS['bleu_ref'].value = self.bleu_ref
<ide> FLAGS.param_set = 'base'
<del> FLAGS.batch_size = 2048 * 8
<add> FLAGS.batch_size = 3072 * 8
<ide> FLAGS.train_steps = 100000
<ide> FLAGS.steps_between_evals = 5000
<ide> FLAGS.model_dir = self._get_model_dir('benchmark_graph_8_gpu')
<ide> FLAGS.hooks = ['ExamplesPerSecondHook']
<ide> self._run_and_report_benchmark()
<ide>
<del> def _run_and_report_benchmark(self):
<add> def benchmark_graph_fp16_8_gpu(self):
<add> """benchmark 8 gpus with fp16 mixed precision.
<add>
<add> SOTA is 27.3 BLEU (uncased).
<add> """
<add> self._setup()
<add> FLAGS.num_gpus = 8
<add> FLAGS.dtype = 'fp16'
<add> FLAGS.data_dir = self.train_data_dir
<add> FLAGS.vocab_file = self.vocab_file
<add> # Sets values directly to avoid validation check.
<add> FLAGS['bleu_source'].value = self.bleu_source
<add> FLAGS['bleu_ref'].value = self.bleu_ref
<add> FLAGS.param_set = 'base'
<add> FLAGS.batch_size = 3072 * 8
<add> FLAGS.train_steps = 100000
<add> FLAGS.steps_between_evals = 5000
<add> FLAGS.model_dir = self._get_model_dir('benchmark_graph_fp16_8_gpu')
<add> FLAGS.hooks = ['ExamplesPerSecondHook']
<add> self._run_and_report_benchmark()
<add>
<add> def _run_and_report_benchmark(self, bleu_min=27.3, bleu_max=28):
<add> """Run benchmark and report results.
<add>
<add> Args:
<add> bleu_min: minimum expected uncased bleu. default is SOTA.
<add> bleu_max: max expected uncased bleu. default is a high number.
<add> """
<ide> start_time_sec = time.time()
<ide> stats = transformer_main.run_transformer(flags.FLAGS)
<ide> wall_time_sec = time.time() - start_time_sec
<ide> self._report_benchmark(stats,
<ide> wall_time_sec,
<del> bleu_min=27.2,
<del> bleu_max=28)
<add> bleu_min=bleu_min,
<add> bleu_max=bleu_max)
<ide>
<ide>
<ide> class TransformerBaseEstimatorBenchmark(EstimatorBenchmark):
<ide> def benchmark_graph_1_gpu(self):
<ide> """Benchmark graph 1 gpu."""
<ide> self._setup()
<ide> FLAGS.num_gpus = 1
<del> FLAGS.batch_size = 2048
<add> FLAGS.batch_size = 4096
<ide> FLAGS.model_dir = self._get_model_dir('benchmark_graph_1_gpu')
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_graph_fp16_1_gpu(self):
<add> """Benchmark graph fp16 1 gpu."""
<add> self._setup()
<add> FLAGS.num_gpus = 1
<add> FLAGS.dtype = 'fp16'
<add> FLAGS.batch_size = 4096
<add> FLAGS.model_dir = self._get_model_dir('benchmark_graph_fp16_1_gpu')
<add> self._run_and_report_benchmark()
<add>
<ide> def benchmark_graph_2_gpu(self):
<ide> """Benchmark graph 2 gpus."""
<ide> self._setup()
<ide> FLAGS.num_gpus = 2
<del> FLAGS.batch_size = 2048 * 2
<add> FLAGS.batch_size = 4096 * 2
<ide> FLAGS.model_dir = self._get_model_dir('benchmark_graph_2_gpu')
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_graph_fp16_2_gpu(self):
<add> """Benchmark graph fp16 2 gpus."""
<add> self._setup()
<add> FLAGS.num_gpus = 2
<add> FLAGS.dtype = 'fp16'
<add> FLAGS.batch_size = 4096 * 2
<add> FLAGS.model_dir = self._get_model_dir('benchmark_graph_fp16_2_gpu')
<add> self._run_and_report_benchmark()
<add>
<ide> def benchmark_graph_4_gpu(self):
<ide> """Benchmark graph 4 gpus."""
<ide> self._setup()
<ide> FLAGS.num_gpus = 4
<del> FLAGS.batch_size = 2048 * 4
<add> FLAGS.batch_size = 4096 * 4
<ide> FLAGS.model_dir = self._get_model_dir('benchmark_graph_4_gpu')
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_graph_fp16_4_gpu(self):
<add> """Benchmark 4 graph fp16 gpus."""
<add> self._setup()
<add> FLAGS.num_gpus = 4
<add> FLAGS.dtype = 'fp16'
<add> FLAGS.batch_size = 4096 * 4
<add> FLAGS.model_dir = self._get_model_dir('benchmark_graph_fp16_4_gpu')
<add> self._run_and_report_benchmark()
<add>
<ide> def benchmark_graph_8_gpu(self):
<ide> """Benchmark graph 8 gpus."""
<ide> self._setup()
<ide> FLAGS.num_gpus = 8
<del> FLAGS.batch_size = 2048 * 8
<add> FLAGS.batch_size = 4096 * 8
<ide> FLAGS.model_dir = self._get_model_dir('benchmark_graph_8_gpu')
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_graph_fp16_8_gpu(self):
<add> """Benchmark graph fp16 8 gpus."""
<add> self._setup()
<add> FLAGS.num_gpus = 8
<add> FLAGS.dtype = 'fp16'
<add> FLAGS.batch_size = 4096 * 8
<add> FLAGS.model_dir = self._get_model_dir('benchmark_graph_fp16_8_gpu')
<add> self._run_and_report_benchmark()
<add>
<ide> def _run_and_report_benchmark(self):
<ide> start_time_sec = time.time()
<ide> stats = transformer_main.run_transformer(flags.FLAGS)
<ide><path>official/transformer/transformer_main.py
<ide> def get_train_op_and_metrics(loss, params):
<ide> if params["use_tpu"] and params["tpu"] != tpu_util.LOCAL:
<ide> optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
<ide>
<add> # Uses automatic mixed precision FP16 training if on GPU.
<add> if params["dtype"] == "fp16":
<add> optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite(
<add> optimizer)
<add>
<ide> # Calculate and apply gradients using LazyAdamOptimizer.
<ide> global_step = tf.train.get_global_step()
<ide> tvars = tf.trainable_variables()
<ide> def evaluate_and_log_bleu(estimator, bleu_source, bleu_ref, vocab_file):
<ide> uncased_score, cased_score = translate_and_compute_bleu(
<ide> estimator, subtokenizer, bleu_source, bleu_ref)
<ide>
<del> tf.logging.info("Bleu score (uncased): %d", uncased_score)
<del> tf.logging.info("Bleu score (cased): %d", cased_score)
<add> tf.logging.info("Bleu score (uncased): %f", uncased_score)
<add> tf.logging.info("Bleu score (cased): %f", cased_score)
<ide> return uncased_score, cased_score
<ide>
<ide>
<ide> def define_transformer_flags():
<ide> intra_op=False,
<ide> synthetic_data=True,
<ide> max_train_steps=False,
<del> dtype=False,
<add> dtype=True,
<ide> all_reduce_alg=True
<ide> )
<ide> flags_core.define_benchmark()
<ide><path>official/utils/flags/_performance.py
<ide>
<ide>
<ide> def get_tf_dtype(flags_obj):
<del> if getattr(flags_obj, 'fp16_implementation', None) == 'graph_rewrite':
<add> if getattr(flags_obj, "fp16_implementation", None) == "graph_rewrite":
<ide> # If the graph_rewrite is used, we build the graph with fp32, and let the
<ide> # graph rewrite change ops to fp16.
<ide> return tf.float32
<ide> def define_performance(num_parallel_calls=True, inter_op=True, intra_op=True,
<ide> tf_gpu_thread_mode=False,
<ide> datasets_num_private_threads=False,
<ide> datasets_num_parallel_batches=False,
<del> dynamic_loss_scale=False, fp16_implementation=False):
<add> dynamic_loss_scale=False, fp16_implementation=False,
<add> loss_scale=False):
<ide> """Register flags for specifying performance tuning arguments.
<ide>
<ide> Args:
<ide> def define_performance(num_parallel_calls=True, inter_op=True, intra_op=True,
<ide> dynamic_loss_scale: Allow the "loss_scale" flag to take on the value
<ide> "dynamic". Only valid if `dtype` is True.
<ide> fp16_implementation: Create fp16_implementation flag.
<add> loss_scale: Controls the loss scaling, normally for mixed-precision
<add> training. Can only be turned on if dtype is also True.
<ide>
<ide> Returns:
<ide> A list of flags for core.py to marks as key flags.
<ide> def define_performance(num_parallel_calls=True, inter_op=True, intra_op=True,
<ide> loss_scale_help_text = loss_scale_help_text.format(
<ide> "This must be an int/float", "")
<ide> loss_scale_validation_msg = "loss_scale should be a positive int/float."
<del> flags.DEFINE_string(
<del> name="loss_scale", short_name="ls", default=None,
<del> help=help_wrap(loss_scale_help_text))
<add> if loss_scale:
<add> flags.DEFINE_string(
<add> name="loss_scale", short_name="ls", default=None,
<add> help=help_wrap(loss_scale_help_text))
<ide>
<del> @flags.validator(flag_name="loss_scale", message=loss_scale_validation_msg)
<del> def _check_loss_scale(loss_scale): # pylint: disable=unused-variable
<del> """Validator to check the loss scale flag is valid"""
<del> if loss_scale is None:
<del> return True # null case is handled in get_loss_scale()
<add> @flags.validator(flag_name="loss_scale",
<add> message=loss_scale_validation_msg)
<add> def _check_loss_scale(loss_scale): # pylint: disable=unused-variable
<add> """Validator to check the loss scale flag is valid."""
<add> if loss_scale is None:
<add> return True # null case is handled in get_loss_scale()
<ide>
<del> if loss_scale == "dynamic" and dynamic_loss_scale:
<del> return True
<add> if loss_scale == "dynamic" and dynamic_loss_scale:
<add> return True
<ide>
<del> try:
<del> loss_scale = float(loss_scale)
<del> except ValueError:
<del> return False
<add> try:
<add> loss_scale = float(loss_scale)
<add> except ValueError:
<add> return False
<ide>
<del> return loss_scale > 0
<add> return loss_scale > 0
<ide>
<ide> if fp16_implementation:
<ide> # Currently, this flag is only defined for the estimator resnet model.
<ide> flags.DEFINE_enum(
<del> name="fp16_implementation", default='casting',
<del> enum_values=('casting', 'graph_rewrite'),
<add> name="fp16_implementation", default="casting",
<add> enum_values=("casting', 'graph_rewrite"),
<ide> help=help_wrap(
<ide> "When --dtype=fp16, how fp16 should be implemented. This has no "
<ide> "impact on correctness. 'casting' will cause manual tf.casts to "
<ide> "be inserted in the model. 'graph_rewrite' means "
<ide> "tf.train.experimental.enable_mixed_precision_graph_rewrite will "
<ide> "be used to automatically use fp16 without any manual casts."))
<ide>
<del> @flags.multi_flags_validator(['fp16_implementation', 'dtype',
<del> 'loss_scale'])
<add> @flags.multi_flags_validator(["fp16_implementation", "dtype",
<add> "loss_scale"])
<ide> def _check_fp16_implementation(flags_dict):
<ide> """Validator to check fp16_implementation flag is valid."""
<del> if (flags_dict['fp16_implementation'] == 'graph_rewrite' and
<del> flags_dict['dtype'] != 'fp16'):
<del> raise flags.ValidationError('--fp16_implementation should not be '
<del> 'specified unless --dtype=fp16')
<del> if (flags_dict['fp16_implementation'] != 'graph_rewrite' and
<del> flags_dict['loss_scale'] == 'dynamic'):
<del> raise flags.ValidationError('--loss_scale=dynamic is only supported '
<del> 'when '
<del> '--fp16_implementation=graph_rewrite')
<add> if (flags_dict["fp16_implementation"] == "graph_rewrite" and
<add> flags_dict["dtype"] != "fp16"):
<add> raise flags.ValidationError("--fp16_implementation should not be "
<add> "specified unless --dtype=fp16")
<add> if (flags_dict["fp16_implementation"] != "graph_rewrite" and
<add> flags_dict["loss_scale"] == "dynamic"):
<add> raise flags.ValidationError("--loss_scale=dynamic is only supported "
<add> "when "
<add> "--fp16_implementation=graph_rewrite")
<ide> return True
<ide>
<ide> if all_reduce_alg:
<ide><path>official/utils/flags/flags_test.py
<ide>
<ide> def define_flags():
<ide> flags_core.define_base(num_gpu=False)
<del> flags_core.define_performance(dynamic_loss_scale=True)
<add> flags_core.define_performance(dynamic_loss_scale=True, loss_scale=True)
<ide> flags_core.define_image()
<ide> flags_core.define_benchmark()
<ide> | 5 |
Go | Go | add proto validation at parse | 0633b12b286d763521124f6d144deade89a89bfc | <ide><path>nat/nat.go
<ide> package nat
<ide>
<ide> import (
<ide> "fmt"
<del> "github.com/dotcloud/docker/utils"
<ide> "strconv"
<ide> "strings"
<add>
<add> "github.com/dotcloud/docker/utils"
<ide> )
<ide>
<ide> const (
<ide> func SplitProtoPort(rawPort string) (string, string) {
<ide> return parts[1], parts[0]
<ide> }
<ide>
<add>func validateProto(proto string) bool {
<add> for _, availableProto := range []string{"tcp", "udp"} {
<add> if availableProto == proto {
<add> return true
<add> }
<add> }
<add> return false
<add>}
<add>
<ide> // We will receive port specs in the format of ip:public:private/proto and these need to be
<ide> // parsed in the internal types
<ide> func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, error) {
<ide> func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding,
<ide> if _, err := strconv.ParseUint(hostPort, 10, 16); hostPort != "" && err != nil {
<ide> return nil, nil, fmt.Errorf("Invalid hostPort: %s", hostPort)
<ide> }
<add> if !validateProto(proto) {
<add> return nil, nil, fmt.Errorf("Invalid proto: %s", proto)
<add> }
<ide>
<ide> port := NewPort(proto, containerPort)
<ide> if _, exists := exposedPorts[port]; !exists { | 1 |
Python | Python | simplify chained comparisons | ee1f0fa3e3c33205166d79c13e250db9d295570d | <ide><path>libcloud/common/aliyun.py
<ide> class AliyunXmlResponse(XmlResponse):
<ide> namespace = None
<ide>
<ide> def success(self):
<del> return self.status >= 200 and self.status < 300
<add> return 200 <= self.status < 300
<ide>
<ide> def parse_body(self):
<ide> """
<ide><path>libcloud/common/brightbox.py
<ide>
<ide> class BrightboxResponse(JsonResponse):
<ide> def success(self):
<del> return self.status >= httplib.OK and self.status < httplib.BAD_REQUEST
<add> return httplib.OK <= self.status < httplib.BAD_REQUEST
<ide>
<ide> def parse_body(self):
<ide> if self.headers['content-type'].split(';')[0] == 'application/json':
<ide><path>libcloud/common/openstack.py
<ide> class OpenStackResponse(Response):
<ide>
<ide> def success(self):
<ide> i = int(self.status)
<del> return i >= 200 and i <= 299
<add> return 200 <= i <= 299
<ide>
<ide> def has_content_type(self, content_type):
<ide> content_type_value = self.headers.get('content-type') or ''
<ide><path>libcloud/compute/drivers/cloudsigma.py
<ide> def success(self):
<ide> if self.status == httplib.UNAUTHORIZED:
<ide> raise InvalidCredsError()
<ide>
<del> return self.status >= 200 and self.status <= 299
<add> return 200 <= self.status <= 299
<ide>
<ide> def parse_body(self):
<ide> if not self.body:
<ide><path>libcloud/compute/drivers/elasticstack.py
<ide> def success(self):
<ide> if self.status == 401:
<ide> raise InvalidCredsError()
<ide>
<del> return self.status >= 200 and self.status <= 299
<add> return 200 <= self.status <= 299
<ide>
<ide> def parse_error(self):
<ide> error_header = self.headers.get('x-elastic-error', '')
<ide><path>libcloud/compute/drivers/opennebula.py
<ide> def success(self):
<ide> :return: True is success, else False.
<ide> """
<ide> i = int(self.status)
<del> return i >= 200 and i <= 299
<add> return 200 <= i <= 299
<ide>
<ide> def parse_error(self):
<ide> """
<ide><path>libcloud/dns/drivers/powerdns.py
<ide> class PowerDNSResponse(JsonResponse):
<ide>
<ide> def success(self):
<ide> i = int(self.status)
<del> return i >= 200 and i <= 299
<add> return 200 <= i <= 299
<ide>
<ide> def parse_error(self):
<ide> if self.status == httplib.UNAUTHORIZED:
<ide><path>libcloud/storage/drivers/cloudfiles.py
<ide> class CloudFilesResponse(Response):
<ide>
<ide> def success(self):
<ide> i = int(self.status)
<del> return i >= 200 and i <= 299 or i in self.valid_response_codes
<add> return 200 <= i <= 299 or i in self.valid_response_codes
<ide>
<ide> def parse_body(self):
<ide> if not self.body:
<ide><path>libcloud/storage/drivers/oss.py
<ide> class OSSResponse(XmlResponse):
<ide>
<ide> def success(self):
<ide> i = int(self.status)
<del> return i >= 200 and i <= 299 or i in self.valid_response_codes
<add> return 200 <= i <= 299 or i in self.valid_response_codes
<ide>
<ide> def parse_body(self):
<ide> """
<ide><path>libcloud/storage/drivers/s3.py
<ide> class S3Response(AWSBaseResponse):
<ide>
<ide> def success(self):
<ide> i = int(self.status)
<del> return i >= 200 and i <= 299 or i in self.valid_response_codes
<add> return 200 <= i <= 299 or i in self.valid_response_codes
<ide>
<ide> def parse_error(self):
<ide> if self.status in [httplib.UNAUTHORIZED, httplib.FORBIDDEN]:
<ide><path>libcloud/utils/py3.py
<ide> PY27 = False
<ide> PY3 = False
<ide>
<del>if sys.version_info >= (2, 0) and sys.version_info < (3, 0):
<add>if (2, 0) <= sys.version_info < (3, 0):
<ide> PY2 = True
<ide>
<del>if sys.version_info >= (2, 7) and sys.version_info < (2, 8):
<add>if (2, 7) <= sys.version_info < (2, 8):
<ide> PY27 = True
<ide>
<ide> if sys.version_info >= (3, 0): | 11 |
PHP | PHP | add tests for invalid connection config | 8d9eb78f4afb5aa1d25b67eac89c22e5ba27c9a0 | <ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function testConnect() {
<ide> $this->assertTrue($this->connection->isConnected());
<ide> }
<ide>
<add>/**
<add> * Tests creating a connection using no driver throws an exception
<add> *
<add> * @expectedException \Cake\Database\Exception\MissingDriverException
<add> * @expectedExceptionMessage Database driver "" could not be found.
<add> * @return void
<add> */
<add> public function testNoDriver() {
<add> $connection = new Connection([]);
<add> }
<add>
<add>/**
<add> * Tests creating a connection using an invalid driver throws an exception
<add> *
<add> * @expectedException \Cake\Database\Exception\MissingDriverException
<add> * @expectedExceptionMessage Database driver "" could not be found.
<add> * @return void
<add> */
<add> public function testEmptyDriver() {
<add> $connection = new Connection(['driver' => false]);
<add> }
<add>
<ide> /**
<ide> * Tests creating a connection using an invalid driver throws an exception
<ide> *
<ide> * @expectedException \Cake\Database\Exception\MissingDriverException
<del> * @expectedExceptionMessage Database driver \Foo\InvalidDriver could not be found.
<add> * @expectedExceptionMessage Database driver "\Foo\InvalidDriver" could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingDriver() { | 1 |
Ruby | Ruby | remove warning of circular require | 80b8df5f3d09205d8f239e9aefd5ed0e0ddfd4a5 | <ide><path>actionpack/lib/action_controller/metal/params_wrapper.rb
<ide> require 'active_support/core_ext/hash/except'
<ide> require 'active_support/core_ext/module/anonymous'
<ide> require 'active_support/core_ext/struct'
<del>require 'action_dispatch/http/mime_types'
<add>require 'action_dispatch/http/mime_type'
<ide>
<ide> module ActionController
<ide> # Wraps the parameters hash into a nested hash. This will allow clients to submit | 1 |
Python | Python | add cpu converters | ed80b6431d19726869673081a058687159f048ee | <ide><path>libcloud/utils/misc.py
<ide> def to_k8s_memory_size_str_from_n_bytes(n_bytes, unit=None):
<ide> return k8s_memory_size_str
<ide>
<ide>
<add>def to_cpu_str(n_cpus):
<add> """Convert number of cpus to cpu string
<add> (e.g. 0.5 -> '500m')
<add> """
<add> millicores = int(n_cpus * 1000)
<add> if millicores % 1 == 0:
<add> return f"{millicores}m"
<add> nanocores = int(n_cpus * 1000000000)
<add> return f"{nanocores}n"
<add>
<add>
<add>def to_n_cpus_from_cpu_str(cpu_str):
<add> """Convert cpu string to number of cpus
<add> (e.g. '500m' -> 0.5, '2000000000n' -> 2)
<add> """
<add> if cpu_str.endswith("n"):
<add> return int(cpu_str.strip("n")) / 1000000000
<add> elif cpu_str.endswith("u"):
<add> return int(cpu_str.strip("u")) / 1000000
<add> elif cpu_str.endswith("m"):
<add> return int(cpu_str.strip("m")) / 1000
<add> elif cpu_str.isnumeric():
<add> return int(cpu_str)
<add> else:
<add> return 0
<add>
<add>
<ide> # Error message which indicates a transient SSL error upon which request
<ide> # can be retried
<ide> TRANSIENT_SSL_ERROR = "The read operation timed out" | 1 |
PHP | PHP | fix bug in fluent class | e8e7db687c6e93cd53b8b12ce761e39e367b8ab1 | <ide><path>laravel/fluent.php
<ide> public function __isset($key)
<ide> */
<ide> public function __unset($key)
<ide> {
<del> return unset($this->attributes[$key]);
<add> unset($this->attributes[$key]);
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file | 1 |
Javascript | Javascript | make `isequal` its own module | 149c4f41ee5c0cfc9143b5bfcf966109ddab94f8 | <ide><path>packages/ember-runtime/lib/core.js
<ide> @module ember
<ide> @submodule ember-runtime
<ide> */
<del>
<del>/**
<del> Compares two objects, returning true if they are logically equal. This is
<del> a deeper comparison than a simple triple equal. For sets it will compare the
<del> internal objects. For any other object that implements `isEqual()` it will
<del> respect that method.
<del>
<del> ```javascript
<del> Ember.isEqual('hello', 'hello'); // true
<del> Ember.isEqual(1, 2); // false
<del> Ember.isEqual([4, 2], [4, 2]); // false
<del> ```
<del>
<del> @method isEqual
<del> @for Ember
<del> @param {Object} a first object to compare
<del> @param {Object} b second object to compare
<del> @return {Boolean}
<del> @public
<del>*/
<del>export function isEqual(a, b) {
<del> if (a && typeof a.isEqual === 'function') {
<del> return a.isEqual(b);
<del> }
<del>
<del> if (a instanceof Date && b instanceof Date) {
<del> return a.getTime() === b.getTime();
<del> }
<del>
<del> return a === b;
<del>}
<ide><path>packages/ember-runtime/lib/is-equal.js
<add>/**
<add> Compares two objects, returning true if they are logically equal. This is
<add> a deeper comparison than a simple triple equal. For sets it will compare the
<add> internal objects. For any other object that implements `isEqual()` it will
<add> respect that method.
<add>
<add> ```javascript
<add> Ember.isEqual('hello', 'hello'); // true
<add> Ember.isEqual(1, 2); // false
<add> Ember.isEqual([4, 2], [4, 2]); // false
<add> Ember.isEqual({ isEqual() { return true;} }, null) // true
<add> ```
<add>
<add> @method isEqual
<add> @for Ember
<add> @param {Object} a first object to compare
<add> @param {Object} b second object to compare
<add> @return {Boolean}
<add> @public
<add>*/
<add>export default function isEqual(a, b) {
<add> if (a && typeof a.isEqual === 'function') {
<add> return a.isEqual(b);
<add> }
<add>
<add> if (a instanceof Date && b instanceof Date) {
<add> return a.getTime() === b.getTime();
<add> }
<add>
<add> return a === b;
<add>}
<ide><path>packages/ember-runtime/lib/main.js
<ide>
<ide> // BEGIN IMPORTS
<ide> import Ember from 'ember-metal';
<del>import { isEqual } from 'ember-runtime/core';
<add>import isEqual from 'ember-runtime/is-equal';
<ide> import compare from 'ember-runtime/compare';
<ide> import copy from 'ember-runtime/copy';
<ide> import inject from 'ember-runtime/inject';
<ide><path>packages/ember-runtime/tests/core/isEqual_test.js
<del>import {isEqual} from 'ember-runtime/core';
<add>import isEqual from 'ember-runtime/is-equal';
<ide>
<ide> QUnit.module('isEqual');
<ide> | 4 |
PHP | PHP | add missing typehint | dcbdaff0d53626cd6aa0e182850e7d9844cc89da | <ide><path>src/Routing/RouteCollection.php
<ide> public function registerMiddleware($name, callable $middleware)
<ide> * @param array $middlewareNames Names of the middleware
<ide> * @return $this
<ide> */
<del> public function middlewareGroup($name, $middlewareNames)
<add> public function middlewareGroup($name, array $middlewareNames)
<ide> {
<ide> if ($this->hasMiddleware($name)) {
<ide> $message = "Cannot add middleware group '$name'. A middleware by this name has already been registered."; | 1 |
PHP | PHP | macth() | b82b72bc16a48c22cc3650adc326df4e4e018729 | <ide><path>src/Illuminate/Routing/Route.php
<ide> public function getMethods()
<ide> */
<ide> public function methods()
<ide> {
<add> if (in_array('GET', $this->methods) && ! in_array('HEAD', $this->methods))
<add> {
<add> $this->methods[] = 'HEAD';
<add> }
<add>
<ide> return $this->methods;
<ide> }
<ide>
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function __construct(Dispatcher $events, Container $container = null)
<ide> */
<ide> public function get($uri, $action)
<ide> {
<del> return $this->addRoute(array('GET', 'HEAD'), $uri, $action);
<add> return $this->addRoute('GET', $uri, $action);
<ide> }
<ide>
<ide> /**
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testOptionsResponsesAreGeneratedByDefault()
<ide> }
<ide>
<ide>
<add> public function testHeadDispatcher()
<add> {
<add> $router = $this->getRouter();
<add> $router->match(['GET', 'POST'], 'foo', function () { return 'bar'; });
<add>
<add> $response = $router->dispatch(Request::create('foo', 'OPTIONS'));
<add> $this->assertEquals(200, $response->getStatusCode());
<add> $this->assertEquals('GET,HEAD,POST', $response->headers->get('Allow'));
<add>
<add> $response = $router->dispatch(Request::create('foo', 'HEAD'));
<add> $this->assertEquals(200, $response->getStatusCode());
<add> $this->assertEquals('', $response->getContent());
<add>
<add> $router = $this->getRouter();
<add> $router->match(['GET'], 'foo', function () { return 'bar'; });
<add>
<add> $response = $router->dispatch(Request::create('foo', 'OPTIONS'));
<add> $this->assertEquals(200, $response->getStatusCode());
<add> $this->assertEquals('GET,HEAD', $response->headers->get('Allow'));
<add>
<add> $router = $this->getRouter();
<add> $router->match(['POST'], 'foo', function () { return 'bar'; });
<add>
<add> $response = $router->dispatch(Request::create('foo', 'OPTIONS'));
<add> $this->assertEquals(200, $response->getStatusCode());
<add> $this->assertEquals('POST', $response->headers->get('Allow'));
<add> }
<add>
<add>
<ide> public function testNonGreedyMatches()
<ide> {
<ide> $route = new Route('GET', 'images/{id}.{ext}', function() {}); | 3 |
Ruby | Ruby | accept parameters in methods delegated to tempfile | e9ba548baf74cc3a5ec65135dac385d81e14f06e | <ide><path>actionpack/lib/action_dispatch/http/upload.rb
<ide> def initialize(hash)
<ide> @headers = hash[:head]
<ide> end
<ide>
<del> def read(*args)
<del> @tempfile.read(*args)
<del> end
<del>
<ide> # Delegate these methods to the tempfile.
<del> [:open, :close, :path, :rewind, :size, :eof?].each do |method|
<del> class_eval "def #{method}; @tempfile.#{method}; end"
<add> [:read, :open, :close, :path, :rewind, :size, :eof?].each do |method|
<add> class_eval "def #{method}(*args); @tempfile.#{method}(*args); end"
<ide> end
<ide>
<ide> private
<ide><path>actionpack/test/dispatch/uploaded_file_test.rb
<ide> def test_delegates_close_to_tempfile
<ide> assert_equal 'thunderhorse', uf.close
<ide> end
<ide>
<add> def test_close_accepts_parameter
<add> tf = Class.new { def close(optional = false); "thunderhorse: #{optional}" end }
<add> uf = Http::UploadedFile.new(:tempfile => tf.new)
<add> assert_equal 'thunderhorse: true', uf.close(true)
<add> end
<add>
<ide> def test_delegates_to_tempfile
<ide> tf = Class.new { def read; 'thunderhorse' end }
<ide> uf = Http::UploadedFile.new(:tempfile => tf.new) | 2 |
Text | Text | fix slack invitation link | c2681859531977fb83fee782f8aec6b50196d644 | <ide><path>README.md
<ide> # Chart.js
<ide>
<del>[](https://travis-ci.org/chartjs/Chart.js) [](https://coveralls.io/github/chartjs/Chart.js?branch=master) [](https://codeclimate.com/github/chartjs/Chart.js) [](https://chart-js-automation.herokuapp.com/)
<add>[](https://travis-ci.org/chartjs/Chart.js) [](https://coveralls.io/github/chartjs/Chart.js?branch=master) [](https://codeclimate.com/github/chartjs/Chart.js) [](https://chartjs-slack.herokuapp.com/)
<ide>
<ide> *Simple HTML5 Charts using the canvas element* [chartjs.org](http://www.chartjs.org)
<ide>
<ide><path>docs/README.md
<ide> # Chart.js
<ide>
<del>[](https://chart-js-automation.herokuapp.com/)
<add>[](https://chartjs-slack.herokuapp.com/)
<ide>
<ide> ## Installation
<ide>
<ide><path>docs/developers/contributing.md
<ide> New contributions to the library are welcome, but we ask that you please follow
<ide>
<ide> # Joining the project
<ide>
<del> Active committers and contributors are invited to introduce yourself and request commit access to this project. We have a very active Slack community that you can join [here](https://chart-js-automation.herokuapp.com/). If you think you can help, we'd love to have you!
<add> Active committers and contributors are invited to introduce yourself and request commit access to this project. We have a very active Slack community that you can join [here](https://chartjs-slack.herokuapp.com/). If you think you can help, we'd love to have you!
<ide>
<ide> # Building and Testing
<ide> | 3 |
Ruby | Ruby | set source encoding | 2efdeb7a9517b677240e2c821c97941f6b905923 | <ide><path>actionpack/test/template/url_helper_test.rb
<add># encoding: utf-8
<ide> require 'abstract_unit'
<ide>
<ide> RequestMock = Struct.new("Request", :request_uri, :protocol, :host_with_port, :env) | 1 |
Python | Python | add cli option to manage html output | 78efbd1101df63030dc1b6edf5650c5b211602dd | <ide><path>glances/glances.py
<ide> from __future__ import generators
<ide>
<ide> __appname__ = 'glances'
<del>__version__ = "1.4b13"
<add>__version__ = "1.4b14"
<ide> __author__ = "Nicolas Hennion <nicolas@nicolargo.com>"
<ide> __licence__ = "LGPL"
<ide>
<ide> def __update__(self):
<ide> self.process_all.append(proc)
<ide> # Grab stats from process list
<ide> for proc in self.process_all[:]:
<del> if (proc.is_running()):
<add> try:
<add> if (not proc.is_running()):
<add> try:
<add> self.process_all.remove(proc)
<add> except:
<add> pass
<add> except psutil.error.NoSuchProcess:
<add> try:
<add> self.process_all.remove(proc)
<add> except:
<add> pass
<add> else:
<ide> # Global stats
<ide> try:
<ide> self.processcount[str(proc.status)] += 1
<ide> def __update__(self):
<ide> self.process.append(procstat)
<ide> except:
<ide> pass
<del> else:
<del> try:
<del> self.process_all.remove(proc)
<del> except:
<del> pass
<ide> # If it is the first grab then empty process list
<ide> if (self.process_first_grab):
<ide> self.process = []
<ide> def printSyntax():
<ide> printVersion()
<ide> print _("Usage: glances.py [-t|--time sec] [-h|--help] [-v|--version]")
<ide> print ""
<del> print _("\t-h:\tDisplay the syntax and exit")
<del> print _("\t-t sec:\tSet the refresh time in second default is 1")
<del> print _("\t-v:\tDisplay the version and exit")
<add> print _("\t-h:\t\tDisplay the syntax and exit")
<add> print _("\t-o output:\tGenerate output (available: html)")
<add> print _("\t-t sec:\t\tSet the refresh time in second default is 1")
<add> print _("\t-v:\t\tDisplay the version and exit")
<ide> print ""
<ide> print _("When Glances is running, you can press:")
<ide> print _("'a' to set the automatic mode. The processes are sorted automatically")
<ide> def printSyntax():
<ide>
<ide> def init():
<ide> global limits, logs, stats, screen, html
<add> global html_tag
<ide> global refresh_time
<ide>
<add> # Set default tags
<add> html_tag = False
<add>
<add> # Set the default refresh time
<ide> refresh_time = 1
<ide>
<ide> # Manage args
<ide> try:
<del> opts, args = getopt.getopt(sys.argv[1:], "ht:v", ["help", "time", "version"])
<add> opts, args = getopt.getopt(sys.argv[1:], "ho:t:v", ["help", "output", "time", "version"])
<ide> except getopt.GetoptError, err:
<ide> # Print help information and exit:
<ide> print str(err)
<ide> def init():
<ide> if opt in ("-v", "--version"):
<ide> printVersion()
<ide> sys.exit(0)
<add> elif opt in ("-o", "--output"):
<add> if arg == "html":
<add> if (jinja_tag):
<add> html_tag = True
<add> else:
<add> print _("Error: Need the Jinja library to export into HTML")
<add> sys.exit(2)
<add> else:
<add> print _("Error: Unknown output %s" % arg)
<add> sys.exit(2)
<ide> elif opt in ("-t", "--time"):
<ide> if int(arg) >= 1:
<ide> refresh_time = int(arg)
<ide> def init():
<ide> screen = glancesScreen(refresh_time)
<ide>
<ide> # Init HTML output
<del> html = glancesHtml(refresh_time)
<add> if (html_tag):
<add> html = glancesHtml(refresh_time)
<ide>
<ide>
<ide> def main():
<ide> def main():
<ide> screen.update(stats)
<ide>
<ide> # Update the HTML output
<del> html.update(stats)
<add> if (html_tag):
<add> html.update(stats)
<ide>
<ide>
<ide> def end(): | 1 |
Python | Python | add test to check comparison with nan | ad9a03084919c5be168327180bc6eb9ae186c2dc | <ide><path>numpy/core/tests/test_simd.py
<ide> def test_special_cases(self):
<ide> nnan = self.notnan(self.setall(self._nan()))
<ide> assert nnan == [0]*self.nlanes
<ide>
<add> import operator
<add>
<add> @pytest.mark.parametrize('py_comp,np_comp', [
<add> (operator.lt, "cmplt"),
<add> (operator.le, "cmple"),
<add> (operator.gt, "cmpgt"),
<add> (operator.ge, "cmpge"),
<add> (operator.eq, "cmpeq"),
<add> (operator.ne, "cmpneq")
<add> ])
<add> def test_comparison_with_nan(self, py_comp, np_comp):
<add> pinf, ninf, nan = self._pinfinity(), self._ninfinity(), self._nan()
<add> mask_true = self._true_mask()
<add>
<add> def to_bool(vector):
<add> return [lane == mask_true for lane in vector]
<add>
<add> intrin = getattr(self, np_comp)
<add> cmp_cases = ((0, nan), (nan, 0), (nan, nan), (pinf, nan), (ninf, nan))
<add> for case_operand1, case_operand2 in cmp_cases:
<add> data_a = [case_operand1]*self.nlanes
<add> data_b = [case_operand2]*self.nlanes
<add> vdata_a = self.setall(case_operand1)
<add> vdata_b = self.setall(case_operand2)
<add> vcmp = to_bool(intrin(vdata_a, vdata_b))
<add> data_cmp = [py_comp(a, b) for a, b in zip(data_a, data_b)]
<add> assert vcmp == data_cmp
<add>
<ide> class _SIMD_ALL(_Test_Utility):
<ide> """
<ide> To test all vector types at once | 1 |
Javascript | Javascript | replace hardgoto with api links | a7d595f349ff0bd9a41164a08ec4ad8cfed237e9 | <ide><path>client/src/client-only-routes/ShowProfileOrFourOhFour.js
<ide> import {
<ide> userByNameSelector,
<ide> userProfileFetchStateSelector,
<ide> fetchProfileForUser,
<del> usernameSelector,
<del> hardGoTo as navigate
<add> usernameSelector
<ide> } from '../redux';
<ide> import FourOhFourPage from '../components/FourOhFour';
<ide> import Profile from '../components/profile/Profile';
<ide> const propTypes = {
<ide> fetchProfileForUser: PropTypes.func.isRequired,
<ide> isSessionUser: PropTypes.bool,
<ide> maybeUser: PropTypes.string,
<del> navigate: PropTypes.func.isRequired,
<ide> requestedUser: PropTypes.shape({
<ide> username: PropTypes.string,
<ide> profileUI: PropTypes.object
<ide> const makeMapStateToProps = () => (state, props) => {
<ide> };
<ide>
<ide> const mapDispatchToProps = {
<del> fetchProfileForUser,
<del> navigate
<add> fetchProfileForUser
<ide> };
<ide>
<ide> class ShowProfileOrFourOhFour extends Component {
<ide> class ShowProfileOrFourOhFour extends Component {
<ide> return null;
<ide> }
<ide>
<del> const { isSessionUser, requestedUser, showLoading, navigate } = this.props;
<add> const { isSessionUser, requestedUser, showLoading } = this.props;
<ide> if (isEmpty(requestedUser)) {
<ide> if (showLoading) {
<ide> // We don't know if /:maybeUser is a user or not, we will show
<ide> class ShowProfileOrFourOhFour extends Component {
<ide>
<ide> // We have a response from the API, and we have some state in the
<ide> // store for /:maybeUser, we now handover rendering to the Profile component
<del> return (
<del> <Profile
<del> isSessionUser={isSessionUser}
<del> navigate={navigate}
<del> user={requestedUser}
<del> />
<del> );
<add> return <Profile isSessionUser={isSessionUser} user={requestedUser} />;
<ide> }
<ide> }
<ide>
<ide><path>client/src/client-only-routes/ShowSettings.js
<ide> const mapDispatchToProps = {
<ide> verifyCert
<ide> };
<ide>
<del>const createHandleSignoutClick = navigate => e => {
<del> e.preventDefault();
<del> return navigate(`${apiLocation}/signout`);
<del>};
<del>
<ide> export function ShowSettings(props) {
<ide> const {
<ide> createFlashMessage,
<ide> export function ShowSettings(props) {
<ide> bsSize='lg'
<ide> bsStyle='primary'
<ide> className='btn-invert'
<del> href={'/signout'}
<del> onClick={createHandleSignoutClick(navigate)}
<add> href={`${apiLocation}/signout`}
<ide> >
<ide> Sign me out of freeCodeCamp
<ide> </Button>
<ide><path>client/src/client-only-routes/ShowUser.js
<ide> import Helmet from 'react-helmet';
<ide> import Login from '../components/Header/components/Login';
<ide>
<ide> import {
<del> hardGoTo as navigate,
<ide> isSignedInSelector,
<ide> userFetchStateSelector,
<ide> userSelector,
<ide> import './showuser.css';
<ide> const propTypes = {
<ide> email: PropTypes.string,
<ide> isSignedIn: PropTypes.bool,
<del> navigate: PropTypes.func.isRequired,
<ide> reportUser: PropTypes.func.isRequired,
<ide> userFetchState: PropTypes.shape({
<ide> pending: PropTypes.bool,
<ide> const mapStateToProps = createSelector(
<ide> );
<ide>
<ide> const mapDispatchToProps = {
<del> navigate,
<ide> reportUser
<ide> };
<ide>
<ide><path>client/src/components/Donation/DonateForm.js
<ide> import {
<ide> ToggleButton,
<ide> ToggleButtonGroup
<ide> } from '@freecodecamp/react-bootstrap';
<del>// import { StripeProvider, Elements } from 'react-stripe-elements';
<ide> import ApplePay from './assets/ApplePay';
<ide> import GooglePay from './assets/GooglePay';
<ide> import acceptedCards from './assets/accepted-cards.png';
<ide> import {
<ide> } from '../../../../config/donation-settings';
<ide> import { deploymentEnv } from '../../../config/env.json';
<ide> import Spacer from '../helpers/Spacer';
<del>// import DonateFormChildViewForHOC from './DonateFormChildViewForHOC';
<ide> import PaypalButton from './PaypalButton';
<ide> import DonateCompletion from './DonateCompletion';
<del>import {
<del> isSignedInSelector,
<del> signInLoadingSelector,
<del> hardGoTo as navigate
<del>} from '../../redux';
<add>import { isSignedInSelector, signInLoadingSelector } from '../../redux';
<ide>
<ide> import './Donation.css';
<ide>
<ide> const propTypes = {
<ide> handleProcessing: PropTypes.func,
<ide> isDonating: PropTypes.bool,
<ide> isSignedIn: PropTypes.bool,
<del> navigate: PropTypes.func.isRequired,
<ide> showLoading: PropTypes.bool.isRequired,
<ide> stripe: PropTypes.shape({
<ide> createToken: PropTypes.func.isRequired,
<ide> const mapStateToProps = createSelector(
<ide> showLoading
<ide> })
<ide> );
<del>const mapDispatchToProps = {
<del> navigate
<del>};
<ide>
<ide> const initialState = {
<ide> donationState: {
<ide> class DonateForm extends Component {
<ide> DonateForm.displayName = 'DonateForm';
<ide> DonateForm.propTypes = propTypes;
<ide>
<del>export default connect(
<del> mapStateToProps,
<del> mapDispatchToProps
<del>)(DonateForm);
<add>export default connect(mapStateToProps)(DonateForm);
<ide><path>client/src/components/Header/components/Login.js
<ide> import React from 'react';
<ide> import PropTypes from 'prop-types';
<ide> import { connect } from 'react-redux';
<ide> import { createSelector } from 'reselect';
<del>import { navigate as gatsbyNavigate } from 'gatsby';
<ide> import { Button } from '@freecodecamp/react-bootstrap';
<ide>
<del>import { hardGoTo as navigate, isSignedInSelector } from '../../../redux';
<add>import { isSignedInSelector } from '../../../redux';
<ide> import { apiLocation } from '../../../../config/env.json';
<ide>
<ide> import { gtagReportConversion } from '../../../analytics/gtag';
<ide> const mapStateToProps = createSelector(
<ide> isSignedIn
<ide> })
<ide> );
<del>const mapDispatchToProps = {
<del> navigate
<del>};
<del>
<del>const createOnClick = (navigate, isSignedIn) => e => {
<del> e.preventDefault();
<del> gtagReportConversion();
<del> if (isSignedIn) {
<del> return gatsbyNavigate('/learn');
<del> }
<del> return navigate(`${apiLocation}/signin`);
<del>};
<ide>
<ide> function Login(props) {
<del> const { children, navigate, isSignedIn, ...restProps } = props;
<add> const { children, isSignedIn, ...restProps } = props;
<add> const href = isSignedIn ? '/learn' : `${apiLocation}/signin`;
<ide> return (
<ide> <Button
<ide> bsStyle='default'
<ide> className={(restProps.block ? 'btn-cta-big' : '') + ' signup-btn btn-cta'}
<del> href='/signin'
<del> onClick={createOnClick(navigate, isSignedIn)}
<add> href={href}
<add> onClick={() => gtagReportConversion()}
<ide> {...restProps}
<ide> >
<ide> {children || 'Sign In'}
<ide> function Login(props) {
<ide> Login.displayName = 'Login';
<ide> Login.propTypes = {
<ide> children: PropTypes.any,
<del> isSignedIn: PropTypes.bool,
<del> navigate: PropTypes.func.isRequired
<add> isSignedIn: PropTypes.bool
<ide> };
<ide>
<del>export default connect(
<del> mapStateToProps,
<del> mapDispatchToProps
<del>)(Login);
<add>export default connect(mapStateToProps)(Login);
<ide><path>client/src/components/helpers/CurrentChallengeLink.js
<ide> import React from 'react';
<ide> import PropTypes from 'prop-types';
<del>import { bindActionCreators } from 'redux';
<del>import { connect } from 'react-redux';
<ide>
<ide> import { apiLocation } from '../../../config/env.json';
<ide>
<del>import { hardGoTo } from '../../redux';
<del>
<ide> const currentChallengeApi = '/challenges/current-challenge';
<ide>
<ide> const propTypes = {
<ide> children: PropTypes.any,
<del> hardGoTo: PropTypes.func.isRequired,
<ide> isLargeBtn: PropTypes.bool
<ide> };
<ide>
<del>const mapStateToProps = () => ({});
<del>const mapDispatchToProps = dispatch =>
<del> bindActionCreators({ hardGoTo }, dispatch);
<del>
<del>const createClickHandler = hardGoTo => e => {
<del> e.preventDefault();
<del> return hardGoTo(`${apiLocation}${currentChallengeApi}`);
<del>};
<del>
<del>function CurrentChallengeLink({ children, hardGoTo, isLargeBtn }) {
<add>function CurrentChallengeLink({ children, isLargeBtn }) {
<ide> let classNames;
<ide> if (isLargeBtn) {
<ide> classNames = 'btn btn-lg btn-primary btn-block';
<ide> } else {
<ide> classNames = 'btn btn-cta-big btn-primary btn-block';
<ide> }
<ide> return (
<del> <a
<del> className={classNames}
<del> href={currentChallengeApi}
<del> onClick={createClickHandler(hardGoTo)}
<del> >
<add> <a className={classNames} href={`${apiLocation}${currentChallengeApi}`}>
<ide> {children}
<ide> </a>
<ide> );
<ide> function CurrentChallengeLink({ children, hardGoTo, isLargeBtn }) {
<ide> CurrentChallengeLink.displayName = 'CurrentChallengeLink';
<ide> CurrentChallengeLink.propTypes = propTypes;
<ide>
<del>export default connect(
<del> mapStateToProps,
<del> mapDispatchToProps
<del>)(CurrentChallengeLink);
<add>export default CurrentChallengeLink;
<ide><path>client/src/components/profile/Profile.js
<ide> import { apiLocation } from '../../../config/env.json';
<ide>
<ide> const propTypes = {
<ide> isSessionUser: PropTypes.bool,
<del> navigate: PropTypes.func.isRequired,
<ide> user: PropTypes.shape({
<ide> profileUI: PropTypes.shape({
<ide> isLocked: PropTypes.bool,
<ide> function renderProfile(user) {
<ide> );
<ide> }
<ide>
<del>function Profile({ user, isSessionUser, navigate }) {
<add>function Profile({ user, isSessionUser }) {
<ide> const {
<ide> profileUI: { isLocked = true },
<ide> username
<ide> } = user;
<ide>
<del> const createHandleSignoutClick = navigate => e => {
<del> e.preventDefault();
<del> return navigate(`${apiLocation}/signout`);
<del> };
<del>
<ide> return (
<ide> <Fragment>
<ide> <Helmet>
<ide> function Profile({ user, isSessionUser, navigate }) {
<ide> bsSize='lg'
<ide> bsStyle='primary'
<ide> className='btn-invert'
<del> href={'/signout'}
<del> onClick={createHandleSignoutClick(navigate)}
<add> href={`${apiLocation}/signout`}
<ide> >
<ide> Sign me out of freeCodeCamp
<ide> </Button>
<ide><path>client/src/components/settings/Certification.test.js
<ide> import '@testing-library/jest-dom/extend-expect';
<ide> import React from 'react';
<ide> import { render } from '@testing-library/react';
<add>import { Provider } from 'react-redux';
<add>import { createStore } from '../../redux/createStore';
<ide>
<ide> import { CertificationSettings } from './Certification';
<ide>
<add>function renderWithRedux(ui) {
<add> return render(<Provider store={createStore()}>{ui}</Provider>);
<add>}
<add>
<ide> describe('<certification />', () => {
<ide> // shallow rendering does not render children component
<ide> // form buttons are not included in shallow render
<ide> it('Should render show cert button for claimed legacy cert', () => {
<del> const { container } = render(
<add> const { container } = renderWithRedux(
<ide> <CertificationSettings {...defaultTestProps} />
<ide> );
<ide>
<ide> describe('<certification />', () => {
<ide> });
<ide>
<ide> it('Should link show cert button to the claimed legacy cert', () => {
<del> const { container } = render(
<add> const { container } = renderWithRedux(
<ide> <CertificationSettings {...defaultTestProps} />
<ide> );
<ide>
<ide> describe('<certification />', () => {
<ide>
<ide> // full forms with unclaimed certs should should not shallow render button
<ide> it('Should not render show cert button for unclaimed full form', () => {
<del> const { container } = render(
<add> const { container } = renderWithRedux(
<ide> <CertificationSettings {...defaultTestProps} />
<ide> );
<ide>
<ide> describe('<certification />', () => {
<ide>
<ide> // empty forms with unclaimed certs should should not shallow render button
<ide> it('Should not render show cert button for empty form', () => {
<del> const { container } = render(
<add> const { container } = renderWithRedux(
<ide> <CertificationSettings {...defaultTestProps} />
<ide> );
<ide>
<ide><path>client/src/pages/learn.js
<ide> import Intro from '../components/Intro';
<ide> import {
<ide> userFetchStateSelector,
<ide> isSignedInSelector,
<del> userSelector,
<del> hardGoTo as navigate
<add> userSelector
<ide> } from '../redux';
<ide> import {
<ide> ChallengeNode,
<ide> const propTypes = {
<ide> hash: PropTypes.string,
<ide> isSignedIn: PropTypes.bool,
<ide> location: PropTypes.object,
<del> navigate: PropTypes.func.isRequired,
<ide> state: PropTypes.object,
<ide> user: PropTypes.shape({
<ide> name: PropTypes.string,
<ide> const hashValueSelector = (state, hash) => {
<ide> else if (hash) return hash.substr(1);
<ide> else return null;
<ide> };
<del>const mapDispatchToProps = {
<del> navigate
<del>};
<ide>
<ide> export const LearnPage = ({
<ide> location: { hash = '', state = '' },
<ide> isSignedIn,
<del> navigate,
<ide> fetchState: { pending, complete },
<ide> user: { name = '', username = '', completedChallengeCount = 0 },
<ide> data: {
<ide> export const LearnPage = ({
<ide> completedChallengeCount={completedChallengeCount}
<ide> isSignedIn={isSignedIn}
<ide> name={name}
<del> navigate={navigate}
<ide> pending={pending}
<ide> slug={slug}
<ide> username={username}
<ide> export const LearnPage = ({
<ide> LearnPage.displayName = 'LearnPage';
<ide> LearnPage.propTypes = propTypes;
<ide>
<del>export default connect(
<del> mapStateToProps,
<del> mapDispatchToProps
<del>)(LearnPage);
<add>export default connect(mapStateToProps)(LearnPage);
<ide>
<ide> export const query = graphql`
<ide> query FirstChallenge { | 9 |
Python | Python | fix typos in the comments for manifest | b5bb3605066e06dd522ed0d32bfde9292d104110 | <ide><path>numpy/distutils/mingw32ccompiler.py
<ide> def build_import_library():
<ide> # raise DistutilsPlatformError, msg
<ide> return
<ide>
<add>#=====================================
<add># Dealing with Visual Studio MANIFESTS
<add>#=====================================
<add>
<ide> # Functions to deal with visual studio manifests. Manifest are a mechanism to
<ide> # enforce strong DLL versioning on windows, and has nothing to do with
<ide> # distutils MANIFEST. manifests are XML files with version info, and used by
<del># the OS loader; they are necessary when linking against a DLL no in the system
<del># path; in particular, python 2.6 is built against the MS runtime 9 (the one
<del># from VS 2008), which is not available on most windows systems; python 2.6
<del># installer does install it in the Win SxS (Side by side) directory, but this
<del># requires the manifest too. This is a big mess, thanks MS for a wonderful
<del># system.
<add># the OS loader; they are necessary when linking against a DLL not in the
<add># system path; in particular, official python 2.6 binary is built against the
<add># MS runtime 9 (the one from VS 2008), which is not available on most windows
<add># systems; python 2.6 installer does install it in the Win SxS (Side by side)
<add># directory, but this requires the manifest for this to work. This is a big
<add># mess, thanks MS for a wonderful system.
<ide>
<ide> # XXX: ideally, we should use exactly the same version as used by python, but I
<ide> # have no idea how to obtain the exact version from python. We could use the | 1 |
Javascript | Javascript | memorize lazy data on access | d9238f061d95eaef977d9771c82febd58d6cacd4 | <ide><path>lib/cache/FileCachePlugin.js
<ide>
<ide> "use strict";
<ide>
<del>const fs = require("fs");
<ide> const path = require("path");
<ide> const createHash = require("../util/createHash");
<ide> const makeSerializable = require("../util/makeSerializable");
<ide> class Pack {
<ide> this.invalid = false;
<ide> }
<ide>
<del> get(relativeFilename) {
<del> this.used.add(relativeFilename);
<del> return this.content.get(relativeFilename);
<add> get(identifier) {
<add> this.used.add(identifier);
<add> return this.content.get(identifier);
<ide> }
<ide>
<del> set(relativeFilename, data) {
<del> this.used.add(relativeFilename);
<add> set(identifier, data) {
<add> this.used.add(identifier);
<ide> this.invalid = true;
<del> return this.content.set(relativeFilename, data);
<add> return this.content.set(identifier, data);
<ide> }
<ide>
<ide> collectGarbage(maxAge) {
<ide> this._updateLastAccess();
<ide> const now = Date.now();
<del> for (const [relativeFilename, lastAccess] of this.lastAccess) {
<add> for (const [identifier, lastAccess] of this.lastAccess) {
<ide> if (now - lastAccess > maxAge) {
<del> this.lastAccess.delete(relativeFilename);
<del> this.content.delete(relativeFilename);
<add> this.lastAccess.delete(identifier);
<add> this.content.delete(identifier);
<ide> }
<ide> }
<ide> }
<ide>
<ide> _updateLastAccess() {
<ide> const now = Date.now();
<del> for (const relativeFilename of this.used) {
<del> this.lastAccess.set(relativeFilename, now);
<add> for (const identifier of this.used) {
<add> this.lastAccess.set(identifier, now);
<ide> }
<ide> this.used.clear();
<ide> }
<ide>
<ide> serialize({ write, snapshot, rollback }) {
<ide> this._updateLastAccess();
<ide> write(this.version);
<del> for (const [relativeFilename, data] of this.content) {
<add> for (const [identifier, data] of this.content) {
<ide> const s = snapshot();
<ide> try {
<del> write(relativeFilename);
<add> write(identifier);
<ide> write(data);
<ide> } catch (err) {
<ide> rollback(s);
<ide> class Pack {
<ide> deserialize({ read }) {
<ide> this.version = read();
<ide> this.content = new Map();
<del> let relativeFilename = read();
<del> while (relativeFilename !== null) {
<del> this.content.set(relativeFilename, read());
<del> relativeFilename = read();
<add> let identifier = read();
<add> while (identifier !== null) {
<add> this.content.set(identifier, read());
<add> identifier = read();
<ide> }
<ide> this.lastAccess = read();
<ide> }
<ide> }
<ide>
<ide> makeSerializable(Pack, "webpack/lib/cache/FileCachePlugin", "Pack");
<ide>
<del>const memorize = fn => {
<del> let result = undefined;
<del> return () => {
<del> if (result === undefined) result = fn();
<del> return result;
<del> };
<del>};
<del>
<ide> class FileCachePlugin {
<ide> /**
<ide> * @param {FileCacheOptions} options options
<ide> class FileCachePlugin {
<ide> }
<ide> });
<ide> };
<del> if (store === "instant" || store === "pack") {
<add> if (store === "instant") {
<ide> return promiseFactory();
<del> } else if (store === "idle") {
<add> } else if (store === "idle" || store === "pack") {
<ide> pendingPromiseFactories.set(identifier, promiseFactory);
<ide> return Promise.resolve();
<ide> } else if (store === "background") {
<ide> class FileCachePlugin {
<ide> return cacheEntryPromise.then(
<ide> cacheEntry => {
<ide> if (cacheEntry === undefined) return;
<del> if (typeof cacheEntry.data === "function")
<del> cacheEntry.data = memorize(cacheEntry.data);
<ide> this.memoryCache.set(identifier, cacheEntry);
<del> if (cacheEntry === undefined) return;
<ide> if (cacheEntry.identifier !== identifier) {
<ide> if (log >= 3) {
<ide> console.warn(
<ide> class FileCachePlugin {
<ide> }
<ide> );
<ide> const serializePack = () => {
<del> packPromise = packPromise.then(pack => {
<del> if (!pack.invalid) return pack;
<add> return packPromise.then(pack => {
<add> if (!pack.invalid) return;
<ide> if (log >= 3) {
<ide> console.warn(`Storing pack...`);
<ide> }
<ide> pack.collectGarbage(1000 * 60 * 60 * 24 * 2);
<add> // You might think this breaks all access to the existing pack
<add> // which are still referenced, but serializing the pack memorizes
<add> // all data in the pack and makes it no longer need the backing file
<add> // So it's safe to replace the pack file
<ide> return serializer
<del> .serializeToFile(pack, `${cacheDirectory}.pack~`)
<del> .then(
<del> result =>
<del> new Promise((resolve, reject) => {
<del> if (!result) {
<del> if (log >= 1) {
<del> console.warn(
<del> 'Caching failed for pack, because content is flagged as not serializable. Use store: "idle" instead.'
<del> );
<del> }
<del> return resolve();
<del> }
<del> fs.unlink(`${cacheDirectory}.pack`, err => {
<del> fs.rename(
<del> `${cacheDirectory}.pack~`,
<del> `${cacheDirectory}.pack`,
<del> err => {
<del> if (err) return reject(err);
<del> if (log >= 3) {
<del> console.warn(`Stored pack`);
<del> }
<del> resolve();
<del> }
<del> );
<del> });
<del> })
<del> )
<add> .serializeToFile(pack, `${cacheDirectory}.pack`)
<ide> .then(() => {
<del> return serializer.deserializeFromFile(`${cacheDirectory}.pack`);
<add> if (log >= 3) {
<add> console.warn(`Stored pack`);
<add> }
<ide> })
<ide> .catch(err => {
<ide> if (log >= 1) {
<ide> class FileCachePlugin {
<ide> return new Pack(version);
<ide> });
<ide> });
<del> return packPromise;
<ide> };
<ide> compiler.cache.hooks.shutdown.tapPromise("FileCachePlugin", () => {
<ide> isIdle = false;
<ide> class FileCachePlugin {
<ide> );
<ide> pendingPromiseFactories.clear();
<ide> if (currentIdlePromise !== undefined) promises.push(currentIdlePromise);
<del> const promise = Promise.all(promises);
<add> let promise = Promise.all(promises);
<ide> if (store === "pack") {
<del> return promise.then(serializePack);
<add> promise = promise.then(serializePack);
<ide> }
<ide> return promise;
<ide> });
<ide>
<ide> let currentIdlePromise;
<ide> let isIdle = false;
<ide> const processIdleTasks = () => {
<del> if (isIdle && pendingPromiseFactories.size > 0) {
<del> const promises = [];
<del> const maxTime = Date.now() + 100;
<del> let maxCount = 100;
<del> for (const [filename, factory] of pendingPromiseFactories) {
<del> pendingPromiseFactories.delete(filename);
<del> promises.push(factory());
<del> if (maxCount-- <= 0 || Date.now() > maxTime) break;
<add> if (isIdle) {
<add> if (pendingPromiseFactories.size > 0) {
<add> const promises = [];
<add> const maxTime = Date.now() + 100;
<add> let maxCount = 100;
<add> for (const [filename, factory] of pendingPromiseFactories) {
<add> pendingPromiseFactories.delete(filename);
<add> promises.push(factory());
<add> if (maxCount-- <= 0 || Date.now() > maxTime) break;
<add> }
<add> currentIdlePromise = Promise.all(promises).then(() => {
<add> currentIdlePromise = undefined;
<add> });
<add> currentIdlePromise.then(processIdleTasks);
<add> } else if (store === "pack") {
<add> currentIdlePromise = serializePack();
<ide> }
<del> currentIdlePromise = Promise.all(promises).then(() => {
<del> currentIdlePromise = undefined;
<del> });
<del> currentIdlePromise.then(processIdleTasks);
<ide> }
<ide> };
<ide> compiler.cache.hooks.beginIdle.tap("FileCachePlugin", () => {
<ide> isIdle = true;
<del> if (store === "pack") {
<del> pendingPromiseFactories.delete("pack");
<del> pendingPromiseFactories.set("pack", serializePack);
<del> }
<ide> Promise.resolve().then(processIdleTasks);
<ide> });
<ide> compiler.cache.hooks.endIdle.tap("FileCachePlugin", () => {
<ide><path>lib/serialization/BinaryMiddleware.js
<ide>
<ide> "use strict";
<ide>
<add>const memorize = require("../util/memorize");
<ide> const SerializerMiddleware = require("./SerializerMiddleware");
<ide>
<ide> /*
<ide> const identifyNumber = n => {
<ide>
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> _handleFunctionSerialization(fn, context) {
<del> return () => {
<add> return memorize(() => {
<ide> const r = fn();
<ide> if (r instanceof Promise)
<ide> return r.then(data => data && this.serialize(data, context));
<ide> if (r) return this.serialize(r, context);
<ide> return null;
<del> };
<add> });
<ide> }
<ide>
<ide> _handleFunctionDeserialization(fn, context) {
<del> return () => {
<add> return memorize(() => {
<ide> const r = fn();
<ide> if (r instanceof Promise)
<ide> return r.then(data => this.deserialize(data, context));
<ide> return this.deserialize(r, context);
<del> };
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>lib/serialization/FileMiddleware.js
<ide> const fs = require("fs");
<ide> const mkdirp = require("mkdirp");
<ide> const path = require("path");
<add>const Queue = require("../util/Queue");
<add>const memorize = require("../util/memorize");
<ide> const SerializerMiddleware = require("./SerializerMiddleware");
<ide>
<ide> class Section {
<ide> class Section {
<ide> }
<ide> }
<ide>
<del>const createPointer = (filename, offset, size) => {
<del> return () => {
<del> return new Promise((resolve, reject) => {
<del> // TODO handle concurrent access to file
<del> fs.open(filename, "r", (err, file) => {
<del> if (err) return reject(err);
<add>/**
<add> * @typedef {Object} FileJob
<add> * @property {boolean} write
<add> * @property {(fileHandle: number, callback: (err: Error?) => void) => void} fn
<add> * @property {(err: Error?) => void} errorHandler
<add> */
<ide>
<del> readSection(filename, file, offset, size, (readErr, parts) => {
<del> fs.close(file, err => {
<del> if (err) return reject(err);
<del> if (readErr) return reject(readErr);
<add>class FileManager {
<add> constructor() {
<add> /** @type {Map<string, Queue<FileJob>>} */
<add> this.jobs = new Map();
<add> this.processing = new Map();
<add> }
<ide>
<del> resolve(parts);
<del> });
<add> addJob(filename, write, fn, errorHandler) {
<add> let queue = this.jobs.get(filename);
<add> let start = false;
<add> if (queue === undefined) {
<add> queue = new Queue();
<add> this.jobs.set(filename, queue);
<add> start = true;
<add> }
<add> queue.enqueue({
<add> write,
<add> fn,
<add> errorHandler
<add> });
<add> if (start) {
<add> this._startProcessing(filename, queue);
<add> }
<add> }
<add>
<add> /**
<add> * @param {string} filename the filename
<add> * @param {Queue<FileJob>} queue the job queue
<add> * @returns {void}
<add> */
<add> _startProcessing(filename, queue) {
<add> let fileHandle;
<add> let write = false;
<add> /** @type {FileJob | undefined} */
<add> let currentJob = undefined;
<add> /**
<add> * Pull the next job from the queue, and process it
<add> * When queue empty and file open, close it
<add> * When queue (still) empty and file closed, exit processing
<add> * @returns {void}
<add> */
<add> const next = () => {
<add> if (queue.length === 0) {
<add> if (fileHandle !== undefined) {
<add> closeFile(next);
<add> } else {
<add> this.jobs.delete(filename);
<add> this.processing.delete(filename);
<add> }
<add> return;
<add> }
<add> currentJob = queue.dequeue();
<add> // If file is already open but in the wrong mode
<add> // close it and open it the other way
<add> if (fileHandle !== undefined && write !== currentJob.write) {
<add> closeFile(openFile);
<add> } else {
<add> openFile();
<add> }
<add> };
<add> /**
<add> * Close the file and continue with the passed next step
<add> * @param {function(): void} next next step
<add> * @returns {void}
<add> */
<add> const closeFile = next => {
<add> fs.close(fileHandle, err => {
<add> if (err) return handleError(err);
<add> fileHandle = undefined;
<add> next();
<add> });
<add> };
<add> /**
<add> * Open the file if needed and continue with job processing
<add> * @returns {void}
<add> */
<add> const openFile = () => {
<add> if (fileHandle === undefined) {
<add> write = currentJob.write;
<add> fs.open(filename, write ? "w" : "r", (err, file) => {
<add> if (err) return handleError(err);
<add> fileHandle = file;
<add> process();
<ide> });
<add> } else {
<add> process();
<add> }
<add> };
<add> /**
<add> * Process the job function and continue with the next job
<add> * @returns {void}
<add> */
<add> const process = () => {
<add> currentJob.fn(fileHandle, err => {
<add> if (err) return handleError(err);
<add> currentJob = undefined;
<add> next();
<ide> });
<add> };
<add> /**
<add> * Handle any error, continue with the next job
<add> * @param {Error} err occured error
<add> * @returns {void}
<add> */
<add> const handleError = err => {
<add> if (currentJob !== undefined) {
<add> currentJob.errorHandler(err);
<add> } else {
<add> console.error(`Error in FileManager: ${err.message}`);
<add> }
<add> next();
<add> };
<add> next();
<add> }
<add>}
<add>const fileManager = new FileManager();
<add>
<add>const createPointer = (filename, offset, size) => {
<add> return memorize(() => {
<add> return new Promise((resolve, reject) => {
<add> fileManager.addJob(
<add> filename,
<add> false,
<add> (file, callback) => {
<add> readSection(filename, file, offset, size, (err, parts) => {
<add> if (err) return callback(err);
<add> resolve(parts);
<add> callback();
<add> });
<add> },
<add> reject
<add> );
<ide> });
<del> };
<add> });
<ide> };
<ide>
<ide> const readSection = (filename, file, offset, size, callback) => {
<ide> class FileMiddleware extends SerializerMiddleware {
<ide> return new Promise((resolve, reject) => {
<ide> mkdirp(path.dirname(filename), err => {
<ide> if (err) return reject(err);
<del> fs.writeFile(filename, Buffer.concat(buffers), err => {
<del> if (err) return reject(err);
<del> resolve(true);
<add> fileManager.addJob(filename, true, (file, callback) => {
<add> fs.writeFile(file, Buffer.concat(buffers), err => {
<add> if (err) return callback(err);
<add> resolve(true);
<add> callback();
<add> });
<ide> });
<ide> });
<ide> });
<ide> class FileMiddleware extends SerializerMiddleware {
<ide> */
<ide> deserialize(data, { filename }) {
<ide> return new Promise((resolve, reject) => {
<del> fs.open(filename, "r", (err, file) => {
<del> if (err) return reject(err);
<add> fileManager.addJob(
<add> filename,
<add> false,
<add> (file, callback) => {
<add> const sizeBuf = Buffer.alloc(4);
<add> fs.read(file, sizeBuf, 0, 4, 0, err => {
<add> if (err) return callback(err);
<ide>
<del> const sizeBuf = Buffer.alloc(4);
<del> fs.read(file, sizeBuf, 0, 4, 0, err => {
<del> if (err) return reject(err);
<del>
<del> const rootSize = sizeBuf.readUInt32LE(0);
<add> const rootSize = sizeBuf.readUInt32LE(0);
<ide>
<del> readSection(filename, file, 4, rootSize, (readErr, parts) => {
<del> fs.close(file, err => {
<del> if (err) return reject(err);
<del> if (readErr) return reject(readErr);
<add> readSection(filename, file, 4, rootSize, (err, parts) => {
<add> if (err) return callback(err);
<ide>
<ide> resolve(parts);
<add> callback();
<ide> });
<ide> });
<del> });
<del> });
<add> },
<add> reject
<add> );
<ide> });
<ide> }
<ide> }
<ide><path>lib/serialization/ObjectMiddleware.js
<ide>
<ide> "use strict";
<ide>
<add>const memorize = require("../util/memorize");
<ide> const ErrorObjectSerializer = require("./ErrorObjectSerializer");
<ide> const MapObjectSerializer = require("./MapObjectSerializer");
<ide> const PlainObjectSerializer = require("./PlainObjectSerializer");
<ide> class ObjectMiddleware extends SerializerMiddleware {
<ide> }
<ide>
<ide> _handleFunctionSerialization(fn, context) {
<del> return () => {
<add> return memorize(() => {
<ide> const r = fn();
<ide>
<ide> if (r instanceof Promise)
<ide> return r.then(data => this.serialize([data], context));
<ide>
<ide> return this.serialize([r], context);
<del> };
<add> });
<ide> }
<ide>
<ide> _handleFunctionDeserialization(fn, context) {
<del> return () => {
<add> return memorize(() => {
<ide> const r = fn();
<ide>
<ide> if (r instanceof Promise)
<ide> return r.then(data => this.deserialize(data, context)[0]);
<ide>
<ide> return this.deserialize(r, context)[0];
<del> };
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>lib/util/memorize.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add>*/
<add>
<add>"use strict";
<add>
<add>const memorize = fn => {
<add> let memorized = false;
<add> let result = undefined;
<add> return () => {
<add> if (memorized) {
<add> return result;
<add> } else {
<add> result = fn();
<add> memorized = true;
<add> // Allow to clean up memory for fn
<add> // and all dependent resources
<add> fn = undefined;
<add> return result;
<add> }
<add> };
<add>};
<add>
<add>module.exports = memorize; | 5 |
Javascript | Javascript | construct new buffer from buffer tojson() output | 2cae44f16934836f0a66b2ea930a0604f505e571 | <ide><path>lib/buffer.js
<ide> function Buffer(subject, encoding) {
<ide> this.length = subject > 0 ? subject >>> 0 : 0;
<ide> else if (util.isString(subject))
<ide> this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8');
<del> else if (util.isObject(subject))
<add> else if (util.isObject(subject)) {
<add> if (subject.type === 'Buffer' && util.isArray(subject.data))
<add> subject = subject.data;
<add>
<ide> this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;
<del> else
<add> } else
<ide> throw new TypeError('must start with number, buffer, array or string');
<ide>
<ide> if (this.length > kMaxLength) {
<ide><path>test/simple/test-buffer.js
<ide> Buffer(Buffer(0), 0, 0);
<ide> }));
<ide> })();
<ide>
<add>// issue GH-7849
<add>(function() {
<add> var buf = new Buffer('test');
<add> var json = JSON.stringify(buf);
<add> var obj = JSON.parse(json);
<add> var copy = new Buffer(obj);
<add>
<add> assert(buf.equals(copy));
<add>})();
<add>
<ide> // issue GH-4331
<ide> assert.throws(function() {
<ide> new Buffer(0xFFFFFFFF); | 2 |
Javascript | Javascript | fix object comparisons in ie tests | b2ddd989b89acfeabcf92ffb2e180c04cd8d308b | <ide><path>packages/ember/tests/routing/basic_test.js
<ide> asyncTest("Events are triggered on the current state", function() {
<ide> events: {
<ide> showStuff: function(handler, obj) {
<ide> ok(handler instanceof App.HomeRoute, "the handler is an App.HomeRoute");
<del> deepEqual(obj, { name: "Tom Dale" }, "the context is correct");
<add> // Using Ember.copy removes any private Ember vars which older IE would be confused by
<add> deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct");
<ide> start();
<ide> }
<ide> }
<ide> asyncTest("Events are triggered on the current state", function() {
<ide> events: {
<ide> showStuff: function(handler, obj) {
<ide> ok(handler instanceof App.RootRoute, "the handler is an App.HomeRoute");
<del> deepEqual(obj, { name: "Tom Dale" }, "the context is correct");
<add> // Using Ember.copy removes any private Ember vars which older IE would be confused by
<add> deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct");
<ide> start();
<ide> }
<ide> } | 1 |
Javascript | Javascript | improve crypto coverage | 513d9bb8aa53feb6630ac56fc231e846d928804f | <ide><path>test/parallel/test-crypto-dh.js
<ide> let firstByte = ecdh1.getPublicKey('buffer', 'compressed')[0];
<ide> assert(firstByte === 2 || firstByte === 3);
<ide> firstByte = ecdh1.getPublicKey('buffer', 'hybrid')[0];
<ide> assert(firstByte === 6 || firstByte === 7);
<add>// format value should be string
<add>assert.throws(() => {
<add> ecdh1.getPublicKey('buffer', 10);
<add>}, /^TypeError: Bad format: 10$/);
<ide>
<ide> // ECDH should check that point is on curve
<ide> const ecdh3 = crypto.createECDH('secp256k1');
<ide> ecdh5.setPrivateKey(cafebabeKey, 'hex');
<ide> // Verify object state did not change.
<ide> assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey);
<ide> });
<add>
<add>// invalid test: curve argument is undefined
<add>assert.throws(() => {
<add> crypto.createECDH();
<add>}, /^TypeError: "curve" argument should be a string$/); | 1 |
Ruby | Ruby | fix to_rack for fully-scoped references | d0251c1abc3d63513c8b07647607e3a5654caedb | <ide><path>Library/Homebrew/formulary.rb
<ide> def self.from_contents(name, path, contents, spec = :stable)
<ide> end
<ide>
<ide> def self.to_rack(ref)
<del> # First, check whether the rack with the given name exists.
<add> # If using a fully-scoped reference, check if the formula can be resolved.
<add> factory(ref) if ref.include? "/"
<add>
<add> # Check whether the rack with the given name exists.
<ide> if (rack = HOMEBREW_CELLAR/File.basename(ref, ".rb")).directory?
<ide> return rack.resolved_path
<ide> end
<ide>
<del> # Second, use canonical name to locate rack.
<add> # Use canonical name to locate rack.
<ide> (HOMEBREW_CELLAR/canonical_name(ref)).resolved_path
<ide> end
<ide>
<ide><path>Library/Homebrew/test/test_formulary.rb
<ide> def test_factory_from_rack_and_from_keg
<ide> def test_load_from_contents
<ide> assert_kind_of Formula, Formulary.from_contents(@name, @path, @path.read)
<ide> end
<add>
<add> def test_to_rack
<add> assert_equal HOMEBREW_CELLAR/@name, Formulary.to_rack(@name)
<add> (HOMEBREW_CELLAR/@name).mkpath
<add> assert_equal HOMEBREW_CELLAR/@name, Formulary.to_rack(@name)
<add> assert_raises(TapFormulaUnavailableError) { Formulary.to_rack("a/b/#{@name}") }
<add> ensure
<add> FileUtils.rm_rf HOMEBREW_CELLAR/@name
<add> end
<ide> end
<ide>
<ide> class FormularyTapFactoryTest < Homebrew::TestCase | 2 |
Text | Text | remove unnecessary key attribute | 96cd8bd5bb09083226e787f249444164ed9d0654 | <ide><path>docs/tutorials/essentials/part-5-async-logic.md
<ide> import { selectAllPosts, fetchPosts } from './postsSlice'
<ide> // highlight-start
<ide> const PostExcerpt = ({ post }) => {
<ide> return (
<del> <article className="post-excerpt" key={post.id}>
<add> <article className="post-excerpt">
<ide> <h3>{post.title}</h3>
<ide> <div>
<ide> <PostAuthor userId={post.user} /> | 1 |
Go | Go | remove redundant pluginpermissiondenied | 7f0cf432e98e1a2e2860faa36ec8bdc55d219e12 | <ide><path>client/errors.go
<ide> func (e objectNotFoundError) Error() string {
<ide> return fmt.Sprintf("Error: No such %s: %s", e.object, e.id)
<ide> }
<ide>
<del>type pluginPermissionDenied struct {
<del> name string
<del>}
<del>
<del>func (e pluginPermissionDenied) Error() string {
<del> return "Permission denied while installing plugin " + e.name
<del>}
<del>
<ide> // NewVersionError returns an error if the APIVersion required
<ide> // if less than the current supported version
<ide> func (cli *Client) NewVersionError(APIrequired, feature string) error {
<ide><path>client/plugin_install.go
<ide> func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values,
<ide> return nil, err
<ide> }
<ide> if !accept {
<del> return nil, pluginPermissionDenied{options.RemoteRef}
<add> return nil, errors.Errorf("permission denied while installing plugin %s", options.RemoteRef)
<ide> }
<ide> }
<ide> return privileges, nil | 2 |
Go | Go | prevent multiple parallel systemdiskusage call | 5a9f2a3ce66d8b0954af965b0b8bf384df02c41a | <ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide>
<ide> seccompProfile []byte
<ide> seccompProfilePath string
<add>
<add> diskUsageRunning int32
<add> containersPruneRunning int32
<add> volumesPruneRunning int32
<add> imagesPruneRunning int32
<add> networksPruneRunning int32
<ide> }
<ide>
<ide> // HasExperimental returns whether the experimental features of the daemon are enabled or not
<ide><path>daemon/disk_usage.go
<ide> package daemon
<ide>
<ide> import (
<ide> "fmt"
<add> "sync/atomic"
<ide>
<ide> "golang.org/x/net/context"
<ide>
<ide> func (daemon *Daemon) getLayerRefs() map[layer.ChainID]int {
<ide>
<ide> // SystemDiskUsage returns information about the daemon data disk usage
<ide> func (daemon *Daemon) SystemDiskUsage(ctx context.Context) (*types.DiskUsage, error) {
<add> if !atomic.CompareAndSwapInt32(&daemon.diskUsageRunning, 0, 1) {
<add> return nil, fmt.Errorf("a disk usage operation is already running")
<add> }
<add> defer atomic.StoreInt32(&daemon.diskUsageRunning, 0)
<add>
<ide> // Retrieve container list
<ide> allContainers, err := daemon.Containers(&types.ContainerListOptions{
<ide> Size: true, | 2 |
Javascript | Javascript | adapt abort tests for new windows code | 82b44f465b830f2a131cd78e6dcb8cb261b17084 | <ide><path>test/abort/test-abort-uncaught-exception.js
<ide> function run(flags, argv2, signals) {
<ide> child.on('exit', common.mustCall(function(code, sig) {
<ide> if (common.isWindows) {
<ide> if (signals)
<del> assert.strictEqual(code, 0xC0000005);
<add> assert.strictEqual(code, 0x80000003);
<ide> else
<ide> assert.strictEqual(code, 1);
<ide> } else if (signals) {
<ide><path>test/abort/test-worker-abort-uncaught-exception.js
<ide> const child = spawn(process.execPath, [
<ide> ]);
<ide> child.on('exit', common.mustCall((code, sig) => {
<ide> if (common.isWindows) {
<del> assert.strictEqual(code, 0xC0000005);
<add> assert.strictEqual(code, 0x80000003);
<ide> } else {
<ide> assert(['SIGABRT', 'SIGTRAP', 'SIGILL'].includes(sig),
<ide> `Unexpected signal ${sig}`);
<ide><path>test/common/index.js
<ide> function nodeProcessAborted(exitCode, signal) {
<ide> const expectedSignals = ['SIGILL', 'SIGTRAP', 'SIGABRT'];
<ide>
<ide> // On Windows, 'aborts' are of 2 types, depending on the context:
<del> // (i) Forced access violation, if --abort-on-uncaught-exception is on
<del> // which corresponds to exit code 3221225477 (0xC0000005)
<add> // (i) Exception breakpoint, if --abort-on-uncaught-exception is on
<add> // which corresponds to exit code 2147483651 (0x80000003)
<ide> // (ii) Otherwise, _exit(134) which is called in place of abort() due to
<ide> // raising SIGABRT exiting with ambiguous exit code '3' by default
<ide> if (isWindows)
<del> expectedExitCodes = [0xC0000005, 134];
<add> expectedExitCodes = [0x80000003, 134];
<ide>
<ide> // When using --abort-on-uncaught-exception, V8 will use
<ide> // base::OS::Abort to terminate the process.
<ide><path>test/parallel/test-windows-failed-heap-allocation.js
<ide> const cmd = `"${process.execPath}" --max-old-space-size=3 "${__filename}"`;
<ide> exec(`${cmd} heapBomb`, { cwd: tmpdir.path }, common.mustCall((err) => {
<ide> const msg = `Wrong exit code of ${err.code}! Expected 134 for abort`;
<ide> // Note: common.nodeProcessAborted() is not asserted here because it
<del> // returns true on 134 as well as 0xC0000005 (V8's base::OS::Abort)
<add> // returns true on 134 as well as 0x80000003 (V8's base::OS::Abort)
<ide> assert.strictEqual(err.code, 134, msg);
<ide> })); | 4 |
Python | Python | remove redundant tests from test_multiarray.py | 33934d5751bb5acbd14da6a2dec9e3eeaaddb40f | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def test_3darray(self):
<ide> assert_equal(array[1, 2, 3], from_c)
<ide>
<ide>
<del>class PriorityNdarray():
<del> __array_priority__ = 1000
<del>
<del> def __init__(self, array):
<del> self.array = array
<del>
<del> def __lt__(self, array):
<del> if isinstance(array, PriorityNdarray):
<del> array = array.array
<del> return PriorityNdarray(self.array < array)
<del>
<del> def __gt__(self, array):
<del> if isinstance(array, PriorityNdarray):
<del> array = array.array
<del> return PriorityNdarray(self.array > array)
<del>
<del> def __le__(self, array):
<del> if isinstance(array, PriorityNdarray):
<del> array = array.array
<del> return PriorityNdarray(self.array <= array)
<del>
<del> def __ge__(self, array):
<del> if isinstance(array, PriorityNdarray):
<del> array = array.array
<del> return PriorityNdarray(self.array >= array)
<del>
<del> def __eq__(self, array):
<del> if isinstance(array, PriorityNdarray):
<del> array = array.array
<del> return PriorityNdarray(self.array == array)
<del>
<del> def __ne__(self, array):
<del> if isinstance(array, PriorityNdarray):
<del> array = array.array
<del> return PriorityNdarray(self.array != array)
<del>
<del>
<del>class TestArrayPriority(TestCase):
<del> def test_lt(self):
<del> l = np.asarray([0., -1., 1.], dtype=dtype)
<del> r = np.asarray([0., 1., -1.], dtype=dtype)
<del> lp = PriorityNdarray(l)
<del> rp = PriorityNdarray(r)
<del> res1 = l < r
<del> res2 = l < rp
<del> res3 = lp < r
<del> res4 = lp < rp
<del>
<del> assert_array_equal(res1, res2.array)
<del> assert_array_equal(res1, res3.array)
<del> assert_array_equal(res1, res4.array)
<del> assert_(isinstance(res1, np.ndarray))
<del> assert_(isinstance(res2, PriorityNdarray))
<del> assert_(isinstance(res3, PriorityNdarray))
<del> assert_(isinstance(res4, PriorityNdarray))
<del>
<del> def test_gt(self):
<del> l = np.asarray([0., -1., 1.], dtype=dtype)
<del> r = np.asarray([0., 1., -1.], dtype=dtype)
<del> lp = PriorityNdarray(l)
<del> rp = PriorityNdarray(r)
<del> res1 = l > r
<del> res2 = l > rp
<del> res3 = lp > r
<del> res4 = lp > rp
<del>
<del> assert_array_equal(res1, res2.array)
<del> assert_array_equal(res1, res3.array)
<del> assert_array_equal(res1, res4.array)
<del> assert_(isinstance(res1, np.ndarray))
<del> assert_(isinstance(res2, PriorityNdarray))
<del> assert_(isinstance(res3, PriorityNdarray))
<del> assert_(isinstance(res4, PriorityNdarray))
<del>
<del> def test_le(self):
<del> l = np.asarray([0., -1., 1.], dtype=dtype)
<del> r = np.asarray([0., 1., -1.], dtype=dtype)
<del> lp = PriorityNdarray(l)
<del> rp = PriorityNdarray(r)
<del> res1 = l <= r
<del> res2 = l <= rp
<del> res3 = lp <= r
<del> res4 = lp <= rp
<del>
<del> assert_array_equal(res1, res2.array)
<del> assert_array_equal(res1, res3.array)
<del> assert_array_equal(res1, res4.array)
<del> assert_(isinstance(res1, np.ndarray))
<del> assert_(isinstance(res2, PriorityNdarray))
<del> assert_(isinstance(res3, PriorityNdarray))
<del> assert_(isinstance(res4, PriorityNdarray))
<del>
<del> def test_ge(self):
<del> l = np.asarray([0., -1., 1.], dtype=dtype)
<del> r = np.asarray([0., 1., -1.], dtype=dtype)
<del> lp = PriorityNdarray(l)
<del> rp = PriorityNdarray(r)
<del> res1 = l >= r
<del> res2 = l >= rp
<del> res3 = lp >= r
<del> res4 = lp >= rp
<del>
<del> assert_array_equal(res1, res2.array)
<del> assert_array_equal(res1, res3.array)
<del> assert_array_equal(res1, res4.array)
<del> assert_(isinstance(res1, np.ndarray))
<del> assert_(isinstance(res2, PriorityNdarray))
<del> assert_(isinstance(res3, PriorityNdarray))
<del> assert_(isinstance(res4, PriorityNdarray))
<del>
<del> def test_eq(self):
<del> l = np.asarray([0., -1., 1.], dtype=dtype)
<del> r = np.asarray([0., 1., -1.], dtype=dtype)
<del> lp = PriorityNdarray(l)
<del> rp = PriorityNdarray(r)
<del> res1 = l == r
<del> res2 = l == rp
<del> res3 = lp == r
<del> res4 = lp == rp
<del>
<del> assert_array_equal(res1, res2.array)
<del> assert_array_equal(res1, res3.array)
<del> assert_array_equal(res1, res4.array)
<del> assert_(isinstance(res1, np.ndarray))
<del> assert_(isinstance(res2, PriorityNdarray))
<del> assert_(isinstance(res3, PriorityNdarray))
<del> assert_(isinstance(res4, PriorityNdarray))
<del>
<del> def test_ne(self):
<del> l = np.asarray([0., -1., 1.], dtype=dtype)
<del> r = np.asarray([0., 1., -1.], dtype=dtype)
<del> lp = PriorityNdarray(l)
<del> rp = PriorityNdarray(r)
<del> res1 = l != r
<del> res2 = l != rp
<del> res3 = lp != r
<del> res4 = lp != rp
<del>
<del> assert_array_equal(res1, res2.array)
<del> assert_array_equal(res1, res3.array)
<del> assert_array_equal(res1, res4.array)
<del> assert_(isinstance(res1, np.ndarray))
<del> assert_(isinstance(res2, PriorityNdarray))
<del> assert_(isinstance(res3, PriorityNdarray))
<del> assert_(isinstance(res4, PriorityNdarray))
<del>
<del>
<ide> class TestConversion(TestCase):
<ide> def test_array_scalar_relational_operation(self):
<ide> #All integer | 1 |
Text | Text | clarify `requiremanualdestroy` option | 79478113d4b405051a14678fdf2d5fd4b88b90f8 | <ide><path>doc/api/async_hooks.md
<ide> asyncResource.triggerAsyncId();
<ide> * `options` {Object}
<ide> * `triggerAsyncId` {number} The ID of the execution context that created this
<ide> async event. **Default:** `executionAsyncId()`.
<del> * `requireManualDestroy` {boolean} Disables automatic `emitDestroy` when the
<del> object is garbage collected. This usually does not need to be set (even if
<del> `emitDestroy` is called manually), unless the resource's `asyncId` is
<del> retrieved and the sensitive API's `emitDestroy` is called with it.
<add> * `requireManualDestroy` {boolean} If set to `true`, disables `emitDestroy`
<add> when the object is garbage collected. This usually does not need to be set
<add> (even if `emitDestroy` is called manually), unless the resource's `asyncId`
<add> is retrieved and the sensitive API's `emitDestroy` is called with it.
<ide> **Default:** `false`.
<ide>
<ide> Example usage: | 1 |
Python | Python | pass environment to cythonize script. closes #791 | 071d11cb35f276da4463978dfe6056765d106dbe | <ide><path>bin/cythonize.py
<ide> def process_pyx(fromfile, tofile):
<ide>
<ide> try:
<ide> try:
<del> r = subprocess.call(['cython'] + flags + ['-o', tofile, fromfile])
<add> r = subprocess.call(['cython'] + flags + ['-o', tofile, fromfile],
<add> shell=True, env=os.environ) # See Issue #791
<ide> if r != 0:
<ide> raise Exception('Cython failed')
<ide> except OSError: | 1 |
Go | Go | simplify codes on calculating shutdown timeout | de68ac8393d32d2c2028dd11c5816430ad0d8d8b | <ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) shutdownContainer(c *container.Container) error {
<ide> return nil
<ide> }
<ide>
<del>// ShutdownTimeout returns the shutdown timeout based on the max stopTimeout of the containers,
<del>// and is limited by daemon's ShutdownTimeout.
<add>// ShutdownTimeout returns the timeout (in seconds) before containers are forcibly
<add>// killed during shutdown. The default timeout can be configured both on the daemon
<add>// and per container, and the longest timeout will be used. A grace-period of
<add>// 5 seconds is added to the configured timeout.
<add>//
<add>// A negative (-1) timeout means "indefinitely", which means that containers
<add>// are not forcibly killed, and the daemon shuts down after all containers exit.
<ide> func (daemon *Daemon) ShutdownTimeout() int {
<del> // By default we use daemon's ShutdownTimeout.
<ide> shutdownTimeout := daemon.configStore.ShutdownTimeout
<add> if shutdownTimeout < 0 {
<add> return -1
<add> }
<add> if daemon.containers == nil {
<add> return shutdownTimeout
<add> }
<ide>
<ide> graceTimeout := 5
<del> if daemon.containers != nil {
<del> for _, c := range daemon.containers.List() {
<del> if shutdownTimeout >= 0 {
<del> stopTimeout := c.StopTimeout()
<del> if stopTimeout < 0 {
<del> shutdownTimeout = -1
<del> } else {
<del> if stopTimeout+graceTimeout > shutdownTimeout {
<del> shutdownTimeout = stopTimeout + graceTimeout
<del> }
<del> }
<del> }
<add> for _, c := range daemon.containers.List() {
<add> stopTimeout := c.StopTimeout()
<add> if stopTimeout < 0 {
<add> return -1
<add> }
<add> if stopTimeout+graceTimeout > shutdownTimeout {
<add> shutdownTimeout = stopTimeout + graceTimeout
<ide> }
<ide> }
<ide> return shutdownTimeout | 1 |
PHP | PHP | add closing ' mark | 3eeaaeb79a78c42e1aafcab5dc27e5d6f5fee10b | <ide><path>src/ORM/Table.php
<ide> public function newEntities(array $data, array $options = [])
<ide> *
<ide> * ```
<ide> * $article = $this->Articles->patchEntity($article, $this->request->data(), [
<del> * 'fieldList' => ['title', 'body', 'tags', 'comments],
<add> * 'fieldList' => ['title', 'body', 'tags', 'comments'],
<ide> * 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']]
<ide> * ]
<ide> * ); | 1 |
Javascript | Javascript | remove duplicate link | b6f4770d114c79c98e62107edc395e7682a00047 | <ide><path>website/docusaurus.config.js
<ide> module.exports = {
<ide> label: 'FAQ',
<ide> to: 'faq'
<ide> },
<del> {
<del> label: 'Tutorial',
<del> to: 'basics/basic-tutorial'
<del> },
<ide> {
<ide> label: 'API Reference',
<ide> to: 'api/api-reference' | 1 |
Python | Python | fix token order in xlnet preprocessing | 74c5035808de18b016c88b1f864d609bc684b367 | <ide><path>examples/run_squad.py
<ide> def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=Fal
<ide> max_seq_length=args.max_seq_length,
<ide> doc_stride=args.doc_stride,
<ide> max_query_length=args.max_query_length,
<del> is_training=not evaluate)
<add> is_training=not evaluate,
<add> cls_token_segment_id=2 if args.model_type in ['xlnet'] else 0,
<add> pad_token_segment_id=3 if args.model_type in ['xlnet'] else 0,
<add> cls_token_at_end=True if args.model_type in ['xlnet'] else False,
<add> sequence_a_is_doc=True if args.model_type in ['xlnet'] else False)
<ide> if args.local_rank in [-1, 0]:
<ide> logger.info("Saving features into cached file %s", cached_features_file)
<ide> torch.save(features, cached_features_file)
<ide><path>examples/utils_squad.py
<ide> def convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide> cls_token='[CLS]', sep_token='[SEP]', pad_token=0,
<ide> sequence_a_segment_id=0, sequence_b_segment_id=1,
<ide> cls_token_segment_id=0, pad_token_segment_id=0,
<del> mask_padding_with_zero=True):
<add> mask_padding_with_zero=True,
<add> sequence_a_is_doc=False):
<ide> """Loads a data file into a list of `InputBatch`s."""
<ide>
<ide> unique_id = 1000000000
<ide> def convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide> p_mask.append(0)
<ide> cls_index = 0
<ide>
<del> # Query
<del> for token in query_tokens:
<del> tokens.append(token)
<add> # XLNet: P SEP Q SEP CLS
<add> # Others: CLS Q SEP P SEP
<add> if not sequence_a_is_doc:
<add> # Query
<add> tokens += query_tokens
<add> segment_ids += [sequence_a_segment_id] * len(query_tokens)
<add> p_mask += [1] * len(query_tokens)
<add>
<add> # SEP token
<add> tokens.append(sep_token)
<ide> segment_ids.append(sequence_a_segment_id)
<ide> p_mask.append(1)
<ide>
<del> # SEP token
<del> tokens.append(sep_token)
<del> segment_ids.append(sequence_a_segment_id)
<del> p_mask.append(1)
<del>
<ide> # Paragraph
<ide> for i in range(doc_span.length):
<ide> split_token_index = doc_span.start + i
<ide> def convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide> split_token_index)
<ide> token_is_max_context[len(tokens)] = is_max_context
<ide> tokens.append(all_doc_tokens[split_token_index])
<del> segment_ids.append(sequence_b_segment_id)
<add> if not sequence_a_is_doc:
<add> segment_ids.append(sequence_b_segment_id)
<add> else:
<add> segment_ids.append(sequence_a_segment_id)
<ide> p_mask.append(0)
<ide> paragraph_len = doc_span.length
<ide>
<add> if sequence_a_is_doc:
<add> # SEP token
<add> tokens.append(sep_token)
<add> segment_ids.append(sequence_a_segment_id)
<add> p_mask.append(1)
<add>
<add> tokens += query_tokens
<add> segment_ids += [sequence_b_segment_id] * len(query_tokens)
<add> p_mask += [1] * len(query_tokens)
<add>
<ide> # SEP token
<ide> tokens.append(sep_token)
<ide> segment_ids.append(sequence_b_segment_id)
<ide> def convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide> end_position = 0
<ide> span_is_impossible = True
<ide> else:
<del> doc_offset = len(query_tokens) + 2
<add> if sequence_a_is_doc:
<add> doc_offset = 0
<add> else:
<add> doc_offset = len(query_tokens) + 2
<ide> start_position = tok_start_position - doc_start + doc_offset
<ide> end_position = tok_end_position - doc_start + doc_offset
<ide> | 2 |
Go | Go | fix couple of races with accessing maps | e6d87c0706d178407ffccaab5c3ffc13a9e7b02e | <ide><path>volume/store/store.go
<ide> func (s *VolumeStore) create(name, driverName string, opts, labels map[string]st
<ide> if err != nil {
<ide> return nil, err
<ide> }
<add> s.globalLock.Lock()
<ide> s.labels[name] = labels
<add> s.globalLock.Unlock()
<ide>
<ide> if s.db != nil {
<ide> metadata := &volumeMetadata{
<ide> func (s *VolumeStore) getVolume(name string) (volume.Volume, error) {
<ide> }
<ide>
<ide> logrus.Debugf("Getting volume reference for name: %s", name)
<del> if v, exists := s.names[name]; exists {
<add> s.globalLock.Lock()
<add> v, exists := s.names[name]
<add> s.globalLock.Unlock()
<add> if exists {
<ide> vd, err := volumedrivers.GetDriver(v.DriverName())
<ide> if err != nil {
<ide> return nil, err | 1 |
Ruby | Ruby | use .diff instead of .patch for github diffs | 7fe9413cf16d70e89fdb79228a297d98a2608625 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_patch(patch)
<ide> end
<ide> when %r[macports/trunk]
<ide> problem "MacPorts patches should specify a revision instead of trunk:\n#{patch.url}"
<add> when %r[^https?://github\.com/.*commit.*\.patch$]
<add> problem "GitHub appends a git version to patches; use .diff instead."
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | use indexof util for ie8 compatibility | b97f08383c881afc77525e0f318de6b5cfc0e219 | <ide><path>src/lib/duration/valid.js
<ide> import toInt from '../utils/to-int';
<add>import indexOf from '../utils/index-of';
<ide> import {Duration} from './constructor';
<ide> import {createDuration} from './create';
<ide>
<ide> var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
<ide>
<ide> export default function isDurationValid(m) {
<ide> for (var key in m) {
<del> if (!(ordering.indexOf(key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
<add> if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
<ide> return false;
<ide> }
<ide> } | 1 |
PHP | PHP | remove unexecutable line | 5c8ed0329317118a80b63b8c04fc7fc64555582d | <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function testAddInputTypeException()
<ide> {
<ide> $restore = error_reporting(E_ALL & ~E_USER_DEPRECATED);
<ide> $this->RequestHandler->addInputType('csv', ['I am not callable']);
<del> error_reporting($restore);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | fix reference to geolocationexample | a7e977c5ddf372b59ab4c77a0ced4fa2d67df604 | <ide><path>Examples/UIExplorer/GeoLocationExample.js
<ide> /**
<ide> * Copyright 2004-present Facebook. All Rights Reserved.
<ide> *
<del> * @providesModule GeolocationExample
<add> * @providesModule GeoLocationExample
<ide> */
<ide> /* eslint no-console: 0 */
<ide> 'use strict';
<ide><path>Examples/UIExplorer/UIExplorerList.js
<ide> var EXAMPLES = [
<ide> require('./ActivityIndicatorExample'),
<ide> require('./ScrollViewExample'),
<ide> require('./DatePickerExample'),
<del> require('./GeolocationExample'),
<add> require('./GeoLocationExample'),
<ide> require('./TabBarExample'),
<ide> require('./SwitchExample'),
<ide> require('./SliderExample'), | 2 |
Go | Go | delay port redirect until packet reaches container | 3c9d05fba58fb8ff688ba5a827abacc609c50e76 | <ide><path>libnetwork/service_linux.go
<ide> import (
<ide>
<ide> func init() {
<ide> reexec.Register("fwmarker", fwMarker)
<add> reexec.Register("redirecter", redirecter)
<ide> }
<ide>
<ide> func newService(name string, id string, ingressPorts []*PortConfig, aliases []string) *service {
<ide> func (sb *sandbox) populateLoadbalancers(ep *endpoint) {
<ide> n := ep.getNetwork()
<ide> eIP := ep.Iface().Address()
<ide>
<add> if n.ingress {
<add> if err := addRedirectRules(sb.Key(), eIP, ep.ingressPorts); err != nil {
<add> logrus.Errorf("Failed to add redirect rules for ep %s: %v", ep.Name(), err)
<add> }
<add> }
<add>
<ide> if sb.ingress {
<ide> // For the ingress sandbox if this is not gateway
<ide> // endpoint do nothing.
<ide> func (sb *sandbox) addLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*P
<ide> }
<ide>
<ide> logrus.Debugf("Creating service for vip %s fwMark %d ingressPorts %#v", vip, fwMark, ingressPorts)
<del> if err := invokeFWMarker(sb.Key(), vip, fwMark, ingressPorts, filteredPorts, eIP, false); err != nil {
<add> if err := invokeFWMarker(sb.Key(), vip, fwMark, ingressPorts, eIP, false); err != nil {
<ide> logrus.Errorf("Failed to add firewall mark rule in sbox %s: %v", sb.Key(), err)
<ide> return
<ide> }
<ide> func (sb *sandbox) rmLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*Po
<ide> }
<ide> }
<ide>
<del> if err := invokeFWMarker(sb.Key(), vip, fwMark, ingressPorts, filteredPorts, eIP, true); err != nil {
<add> if err := invokeFWMarker(sb.Key(), vip, fwMark, ingressPorts, eIP, true); err != nil {
<ide> logrus.Errorf("Failed to add firewall mark rule in sbox %s: %v", sb.Key(), err)
<ide> }
<ide> }
<ide> func readPortsFromFile(fileName string) ([]*PortConfig, error) {
<ide>
<ide> // Invoke fwmarker reexec routine to mark vip destined packets with
<ide> // the passed firewall mark.
<del>func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, filteredPorts []*PortConfig, eIP *net.IPNet, isDelete bool) error {
<del> var (
<del> ingressPortsFile string
<del> filteredPortsFile string
<del> )
<add>func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, eIP *net.IPNet, isDelete bool) error {
<add> var ingressPortsFile string
<ide>
<ide> if len(ingressPorts) != 0 {
<ide> var err error
<ide> ingressPortsFile, err = writePortsToFile(ingressPorts)
<ide> if err != nil {
<ide> return err
<ide> }
<del> }
<ide>
<del> if len(filteredPorts) != 0 {
<del> var err error
<del> filteredPortsFile, err = writePortsToFile(filteredPorts)
<del> if err != nil {
<del> return err
<del> }
<add> defer os.Remove(ingressPortsFile)
<ide> }
<ide>
<ide> addDelOpt := "-A"
<ide> func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*Port
<ide>
<ide> cmd := &exec.Cmd{
<ide> Path: reexec.Self(),
<del> Args: append([]string{"fwmarker"}, path, vip.String(), fmt.Sprintf("%d", fwMark), addDelOpt, ingressPortsFile, filteredPortsFile, eIP.String()),
<add> Args: append([]string{"fwmarker"}, path, vip.String(), fmt.Sprintf("%d", fwMark), addDelOpt, ingressPortsFile, eIP.String()),
<ide> Stdout: os.Stdout,
<ide> Stderr: os.Stderr,
<ide> }
<ide> func fwMarker() {
<ide> runtime.LockOSThread()
<ide> defer runtime.UnlockOSThread()
<ide>
<del> if len(os.Args) < 8 {
<add> if len(os.Args) < 7 {
<ide> logrus.Error("invalid number of arguments..")
<ide> os.Exit(1)
<ide> }
<ide>
<ide> var ingressPorts []*PortConfig
<del> var filteredPorts []*PortConfig
<ide> if os.Args[5] != "" {
<ide> var err error
<ide> ingressPorts, err = readPortsFromFile(os.Args[5])
<ide> func fwMarker() {
<ide> }
<ide> }
<ide>
<del> if os.Args[6] != "" {
<del> var err error
<del> filteredPorts, err = readPortsFromFile(os.Args[6])
<del> if err != nil {
<del> logrus.Errorf("Failed reading filtered ports file: %v", err)
<del> os.Exit(7)
<del> }
<del> }
<del>
<ide> vip := os.Args[2]
<ide> fwMark, err := strconv.ParseUint(os.Args[3], 10, 32)
<ide> if err != nil {
<ide> func fwMarker() {
<ide> addDelOpt := os.Args[4]
<ide>
<ide> rules := [][]string{}
<del> for _, iPort := range filteredPorts {
<del> rule := strings.Fields(fmt.Sprintf("-t nat %s PREROUTING -p %s --dport %d -j REDIRECT --to-port %d",
<del> addDelOpt, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, iPort.TargetPort))
<del> rules = append(rules, rule)
<del> }
<del>
<ide> for _, iPort := range ingressPorts {
<ide> rule := strings.Fields(fmt.Sprintf("-t mangle %s PREROUTING -p %s --dport %d -j MARK --set-mark %d",
<ide> addDelOpt, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, fwMark))
<ide> func fwMarker() {
<ide> }
<ide>
<ide> if addDelOpt == "-A" {
<del> eIP, subnet, err := net.ParseCIDR(os.Args[7])
<add> eIP, subnet, err := net.ParseCIDR(os.Args[6])
<ide> if err != nil {
<del> logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[7], err)
<add> logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[6], err)
<ide> os.Exit(9)
<ide> }
<ide>
<ide> func fwMarker() {
<ide> }
<ide> }
<ide> }
<add>
<add>func addRedirectRules(path string, eIP *net.IPNet, ingressPorts []*PortConfig) error {
<add> var ingressPortsFile string
<add>
<add> if len(ingressPorts) != 0 {
<add> var err error
<add> ingressPortsFile, err = writePortsToFile(ingressPorts)
<add> if err != nil {
<add> return err
<add> }
<add> defer os.Remove(ingressPortsFile)
<add> }
<add>
<add> cmd := &exec.Cmd{
<add> Path: reexec.Self(),
<add> Args: append([]string{"redirecter"}, path, eIP.String(), ingressPortsFile),
<add> Stdout: os.Stdout,
<add> Stderr: os.Stderr,
<add> }
<add>
<add> if err := cmd.Run(); err != nil {
<add> return fmt.Errorf("reexec failed: %v", err)
<add> }
<add>
<add> return nil
<add>}
<add>
<add>// Redirecter reexec function.
<add>func redirecter() {
<add> runtime.LockOSThread()
<add> defer runtime.UnlockOSThread()
<add>
<add> if len(os.Args) < 4 {
<add> logrus.Error("invalid number of arguments..")
<add> os.Exit(1)
<add> }
<add>
<add> var ingressPorts []*PortConfig
<add> if os.Args[3] != "" {
<add> var err error
<add> ingressPorts, err = readPortsFromFile(os.Args[3])
<add> if err != nil {
<add> logrus.Errorf("Failed reading ingress ports file: %v", err)
<add> os.Exit(2)
<add> }
<add> }
<add>
<add> eIP, _, err := net.ParseCIDR(os.Args[2])
<add> if err != nil {
<add> logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[2], err)
<add> os.Exit(3)
<add> }
<add>
<add> rules := [][]string{}
<add> for _, iPort := range ingressPorts {
<add> rule := strings.Fields(fmt.Sprintf("-t nat -A PREROUTING -d %s -p %s --dport %d -j REDIRECT --to-port %d",
<add> eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, iPort.TargetPort))
<add> rules = append(rules, rule)
<add> }
<add>
<add> ns, err := netns.GetFromPath(os.Args[1])
<add> if err != nil {
<add> logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
<add> os.Exit(4)
<add> }
<add> defer ns.Close()
<add>
<add> if err := netns.Set(ns); err != nil {
<add> logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err)
<add> os.Exit(5)
<add> }
<add>
<add> for _, rule := range rules {
<add> if err := iptables.RawCombinedOutputNative(rule...); err != nil {
<add> logrus.Errorf("setting up rule failed, %v: %v", rule, err)
<add> os.Exit(5)
<add> }
<add> }
<add>} | 1 |
Python | Python | add documentation to gcs_download_operator | 206681f7b2afd0944ef87b7c469c65cd0d81b71c | <ide><path>airflow/contrib/operators/gcs_download_operator.py
<ide> def __init__(
<ide> **kwargs):
<ide> """
<ide> Create a new GoogleCloudStorageDownloadOperator.
<add>
<add> :param bucket: The Google cloud storage bucket where the object is.
<add> :type bucket: string
<add> :param object: The name of the object to download in the Google cloud
<add> storage bucket.
<add> :type object: string
<add> :param filename: The file path on the local file system (where the
<add> operator is being executed) that the file should be downloaded to.
<add> :type filename: string
<add> :param google_cloud_storage_conn_id: The connection ID to use when
<add> connecting to Google cloud storage.
<add> :type google_cloud_storage_conn_id: string
<ide> """
<ide> super(GoogleCloudStorageDownloadOperator, self).__init__(*args, **kwargs)
<ide> self.bucket = bucket | 1 |
Python | Python | replace 'unique samples' with 'samples' | 2979250119547754c60cf5c2df1c60708a1bd2df | <ide><path>keras/engine/training.py
<ide> def fit(self,
<ide> before declaring one epoch finished and starting the
<ide> next epoch. When training with input tensors such as
<ide> TensorFlow data tensors, the default `None` is equal to
<del> the number of unique samples in your dataset divided by
<add> the number of samples in your dataset divided by
<ide> the batch size, or 1 if that cannot be determined.
<ide> validation_steps: Only relevant if `steps_per_epoch`
<ide> is specified. Total number of steps (batches of samples)
<ide> def evaluate(self, x=None, y=None,
<ide> steps: Integer or `None`.
<ide> Total number of steps (batches of samples)
<ide> before declaring the evaluation round finished.
<del> The default `None` is equal to the number of unique samples in
<add> The default `None` is equal to the number of samples in
<ide> your dataset divided by the batch size.
<ide>
<ide>
<ide> def fit_generator(self,
<ide> steps_per_epoch: Total number of steps (batches of samples)
<ide> to yield from `generator` before declaring one epoch
<ide> finished and starting the next epoch. It should typically
<del> be equal to the number of unique samples of your dataset
<add> be equal to the number of samples of your dataset
<ide> divided by the batch size. Not used if using `Sequence`.
<ide> epochs: Integer, total number of iterations on the data.
<ide> verbose: Verbosity mode, 0, 1, or 2.
<ide><path>keras/models.py
<ide> def fit(self,
<ide> before declaring one epoch finished and starting the
<ide> next epoch. When training with input tensors such as
<ide> TensorFlow data tensors, the default `None` is equal to
<del> the number of unique samples in your dataset divided by
<add> the number of samples in your dataset divided by
<ide> the batch size, or 1 if that cannot be determined.
<ide> validation_steps: Only relevant if `steps_per_epoch`
<ide> is specified. Total number of steps (batches of samples)
<ide> def fit_generator(self, generator,
<ide> steps_per_epoch: Total number of steps (batches of samples)
<ide> to yield from `generator` before declaring one epoch
<ide> finished and starting the next epoch. It should typically
<del> be equal to the number of unique samples of your dataset
<add> be equal to the number of samples of your dataset
<ide> divided by the batch size.
<ide> epochs: Integer, total number of iterations on the data.
<ide> Note that in conjunction with initial_epoch, the parameter
<ide> def fit_generator(self, generator,
<ide> is a generator.
<ide> Number of steps to yield from validation generator
<ide> at the end of every epoch. It should typically
<del> be equal to the number of unique samples of your
<add> be equal to the number of samples of your
<ide> validation dataset divided by the batch size.
<ide> class_weight: Dictionary mapping class indices to a weight
<ide> for the class. | 2 |
PHP | PHP | fix errored namespaces. | 5ea6689a39fc05376cd20832b531e9cb1d71096e | <ide><path>tests/Foundation/Http/KernelTest.php
<ide> <?php
<ide>
<del>namespace Illuminate\Tests\Foundation\Bootstrap\Http;
<add>namespace Illuminate\Tests\Foundation\Http;
<ide>
<ide> use Illuminate\Events\Dispatcher;
<ide> use Illuminate\Foundation\Application;
<ide><path>tests/Foundation/Http/Middleware/ConvertEmptyStringsToNullTest.php
<ide> <?php
<ide>
<del>namespace Illuminate\Tests\Foundation\Bootstrap\Http\Middleware;
<add>namespace Illuminate\Tests\Foundation\Http\Middleware;
<ide>
<ide> use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
<ide> use Illuminate\Http\Request;
<ide><path>tests/Foundation/Http/Middleware/TransformsRequestTest.php
<ide> <?php
<ide>
<del>namespace Illuminate\Tests\Foundation\Bootstrap\Http\Middleware;
<add>namespace Illuminate\Tests\Foundation\Http\Middleware;
<ide>
<ide> use Illuminate\Foundation\Http\Middleware\TransformsRequest;
<ide> use Illuminate\Http\Request;
<ide><path>tests/Foundation/Http/Middleware/TrimStringsTest.php
<ide> <?php
<ide>
<del>namespace Illuminate\Tests\Foundation\Bootstrap\Http\Middleware;
<add>namespace Illuminate\Tests\Foundation\Http\Middleware;
<ide>
<ide> use Illuminate\Foundation\Http\Middleware\TrimStrings;
<ide> use Illuminate\Http\Request;
<ide><path>tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php
<ide> <?php
<ide>
<del>namespace Illuminate\Tests\Foundation\Bootstrap\Testing\Concerns;
<add>namespace Illuminate\Tests\Foundation\Testing\Concerns;
<ide>
<ide> use Illuminate\Foundation\Mix;
<ide> use Orchestra\Testbench\TestCase;
<ide><path>tests/Foundation/Testing/Concerns/InteractsWithViewsTest.php
<ide> <?php
<ide>
<del>namespace Illuminate\Tests\Foundation\Bootstrap\Testing\Concerns;
<add>namespace Illuminate\Tests\Foundation\Testing\Concerns;
<ide>
<ide> use Illuminate\Foundation\Testing\Concerns\InteractsWithViews;
<ide> use Illuminate\View\Component;
<ide><path>tests/Foundation/Testing/Concerns/MakesHttpRequestsTest.php
<ide> <?php
<ide>
<del>namespace Illuminate\Tests\Foundation\Bootstrap\Testing\Concerns;
<add>namespace Illuminate\Tests\Foundation\Testing\Concerns;
<ide>
<ide> use Illuminate\Contracts\Routing\Registrar;
<ide> use Illuminate\Contracts\Routing\UrlGenerator;
<ide><path>tests/Foundation/Testing/WormholeTest.php
<ide> <?php
<ide>
<del>namespace Illuminate\Tests\Foundation\Bootstrap\Testing;
<add>namespace Illuminate\Tests\Foundation\Testing;
<ide>
<ide> use Carbon\CarbonImmutable;
<ide> use Illuminate\Foundation\Testing\Wormhole; | 8 |
Text | Text | fix typo by changing 'for' to 'from' | c8bc3c2943b86d26f10d66c97579ea6aa35bb897 | <ide><path>guides/source/layouts_and_rendering.md
<ide> Just like the `:status` option for `render`, `:status` for `redirect_to` accepts
<ide>
<ide> #### The Difference Between `render` and `redirect_to`
<ide>
<del>Sometimes inexperienced developers think of `redirect_to` as a sort of `goto` command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.
<add>Sometimes inexperienced developers think of `redirect_to` as a sort of `goto` command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request from the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.
<ide>
<ide> Consider these actions to see the difference:
<ide> | 1 |
Ruby | Ruby | make `parser#parse` return `args` | bf13db3367fc474d9f012984ddd482ae06a01ad8 | <ide><path>Library/Homebrew/cli/parser.rb
<ide> def parse(argv = @argv, allow_no_named_args: false)
<ide> Homebrew.args = @args
<ide>
<ide> @args_parsed = true
<del> @parser
<add> @args
<ide> end
<ide>
<ide> def global_option?(name, desc)
<ide><path>Library/Homebrew/dev-cmd/mirror.rb
<ide> def mirror_args
<ide> end
<ide>
<ide> def mirror
<del> mirror_args.parse
<add> args = mirror_args.parse
<ide>
<ide> bintray_org = args.bintray_org || "homebrew"
<ide> bintray_repo = args.bintray_repo || "mirror"
<ide><path>Library/Homebrew/dev-cmd/pr-upload.rb
<ide> def pr_upload_args
<ide> end
<ide>
<ide> def pr_upload
<del> pr_upload_args.parse
<add> args = pr_upload_args.parse
<ide>
<ide> bintray_org = args.bintray_org || "homebrew"
<ide> bintray = Bintray.new(org: bintray_org) | 3 |
Ruby | Ruby | kill legacy dispatcher | 0c3cde404ac45d59439c324a4a13ec239c582a5c | <ide><path>actionpack/lib/action_dispatch/railtie.rb
<ide> class Railtie < Rails::Railtie
<ide>
<ide> # Prepare dispatcher callbacks and run 'prepare' callbacks
<ide> initializer "action_dispatch.prepare_dispatcher" do |app|
<del> # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
<del> require 'rails/dispatcher'
<ide> ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
<ide> end
<ide> end
<ide><path>railties/lib/rails/dispatcher.rb
<del>#--
<del># Copyright (c) 2004-2010 David Heinemeier Hansson
<del>#
<del># Permission is hereby granted, free of charge, to any person obtaining
<del># a copy of this software and associated documentation files (the
<del># "Software"), to deal in the Software without restriction, including
<del># without limitation the rights to use, copy, modify, merge, publish,
<del># distribute, sublicense, and/or sell copies of the Software, and to
<del># permit persons to whom the Software is furnished to do so, subject to
<del># the following conditions:
<del>#
<del># The above copyright notice and this permission notice shall be
<del># included in all copies or substantial portions of the Software.
<del>#
<del># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
<del># EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<del># MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
<del># NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
<del># LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
<del># OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
<del># WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<del>#++
<del>require 'action_controller/deprecated/dispatcher'
<del>Dispatcher = ActionController::Dispatcher | 2 |
PHP | PHP | get basic html layout in place | 4e2698e05e3d9c92ef405bac93ba5fb7641b539a | <ide><path>src/Error/Debug/HtmlFormatter.php
<ide> */
<ide> class HtmlFormatter implements FormatterInterface
<ide> {
<add> /**
<add> * @var bool
<add> */
<add> protected static $outputHeader = false;
<add>
<ide> /**
<ide> * Random id so that HTML ids are not shared between dump outputs.
<ide> *
<ide> protected function style(string $style, string $text): string
<ide> );
<ide> }
<ide>
<add> /**
<add> * Generate the CSS and Javascript for dumps
<add> *
<add> * Only output once per process as we don't need it more than once.
<add> *
<add> * @return string
<add> */
<add> protected function dumpHeader(): string
<add> {
<add> ob_start();
<add> include __DIR__ . DIRECTORY_SEPARATOR . 'dumpHeader.php';
<add> return ob_get_clean();
<add> }
<add>
<ide> /**
<ide> * Convert a tree of NodeInterface objects into HTML
<ide> *
<ide> protected function style(string $style, string $text): string
<ide> public function dump(NodeInterface $node): string
<ide> {
<ide> $html = $this->export($node);
<add> $head = '';
<add> if (!static::$outputHeader) {
<add> static::$outputHeader = true;
<add> $head = $this->dumpHeader();
<add> }
<ide>
<del> return '<div class="cake-dbg">' . $html . '</div>';
<add> return $head . '<div class="cake-dbg">' . $html . '</div>';
<ide> }
<ide>
<ide> /**
<ide> protected function export(NodeInterface $var): string
<ide> */
<ide> protected function exportArray(ArrayNode $var): string
<ide> {
<del> $out = '<div class="cake-dbg-array">' . $this->style('punct', '[');
<add> $open = '<span class="cake-dbg-array">' .
<add> $this->style('punct', '[') .
<add> '<samp class="cake-dbg-array-items">';
<ide> $vars = [];
<ide>
<ide> $arrow = $this->style('punct', ' => ');
<ide> foreach ($var->getChildren() as $item) {
<ide> $val = $item->getValue();
<ide> $vars[] = '<span class="cake-dbg-array-item">' .
<ide> $this->export($item->getKey()) . $arrow . $this->export($val) .
<add> $this->style('punct', ',') .
<ide> '</span>';
<ide> }
<ide>
<del> $close = $this->style('punct', ']') . '</div>';
<del> if (count($vars)) {
<del> return $out . implode($this->style('punct', ','), $vars) . $close;
<del> }
<del>
<del> return $out . $close;
<add> $close = '</samp>' .
<add> $this->style('punct', ']') .
<add> '</span>';
<add> return $open . implode('', $vars) . $close;
<ide> }
<ide>
<ide> /**
<ide> protected function exportObject($var): string
<ide> {
<ide> $objectId = "cake-db-object-{$this->id}-{$var->getId()}";
<ide> $out = sprintf(
<del> '<div class="cake-dbg-object" id="%s">',
<add> '<span class="cake-dbg-object" id="%s">',
<ide> $objectId
<ide> );
<ide>
<ide> protected function exportObject($var): string
<ide> $this->style('number', (string)$var->getId())
<ide> );
<ide>
<del> return '<div class="cake-dbg-ref">' .
<add> return '<span class="cake-dbg-ref">' .
<ide> $this->style('punct', 'object(') .
<ide> $this->style('class', $var->getValue()) .
<del> $this->style('punct', ')') .
<add> $this->style('punct', ') ') .
<ide> $link .
<ide> $this->style('punct', ' {}') .
<del> '</div>';
<add> '</span>';
<ide> }
<ide>
<ide> $out .= $this->style('punct', 'object(') .
<ide> $this->style('class', $var->getValue()) .
<ide> $this->style('punct', ') id:') .
<ide> $this->style('number', (string)$var->getId()) .
<del> $this->style('punct', ' {');
<add> $this->style('punct', ' {') .
<add> '<samp class="cake-dbg-object-props">';
<ide>
<ide> $props = [];
<ide> foreach ($var->getChildren() as $property) {
<ide> protected function exportObject($var): string
<ide> }
<ide> }
<ide>
<del> $end = $this->style('punct', '}') . '</div>';
<add> $end = '</samp>' .
<add> $this->style('punct', '}') .
<add> '</span>';
<add>
<ide> if (count($props)) {
<del> return $out . implode("\n", $props) . $end;
<add> return $out . implode("", $props) . $end;
<ide> }
<ide>
<ide> return $out . $end;
<ide><path>src/Error/Debug/dumpHeader.php
<add><style type="text/css">
<add>.cake-dbg {
<add> font-family: monospace;
<add> --indent: 20px;
<add>}
<add>.cake-dbg-object {
<add> display: inline;
<add>}
<add>/*
<add>Array item container and each items are blocks so
<add>nesting works.
<add>*/
<add>.cake-dbg-object-props,
<add>.cake-dbg-array-items {
<add> display: block;
<add>}
<add>.cake-dbg-prop,
<add>.cake-dbg-array-item {
<add> display: block;
<add> padding-left: var(--indent);
<add>}
<add>
<add>/* Textual elements */
<add>.cake-dbg-punct {
<add>}
<add>.cake-dbg-string {
<add>}
<add>.cake-dbg-number {
<add> font-weight: bold;
<add>}
<add>.cake-dbg-const {
<add> font-weight: bold;
<add>}
<add></style>
<ide><path>src/Error/Debugger.php
<ide> public static function printVar($var, array $location = [], ?bool $showHtml = nu
<ide> $file = str_replace($search, '', $file);
<ide> }
<ide> $html = <<<HTML
<del><div class="cake-debug-output" style="direction:ltr">
<add><div class="cake-debug-output cake-debug" style="direction:ltr">
<ide> %s
<del><pre class="cake-debug">
<ide> %s
<del></pre>
<ide> </div>
<ide> HTML;
<ide> $text = <<<TEXT
<ide> public static function printVar($var, array $location = [], ?bool $showHtml = nu
<ide> $var = Debugger::exportVar($var, 25);
<ide> if ($showHtml) {
<ide> $template = $html;
<del> $var = h($var);
<ide> if ($file && $line) {
<ide> $lineInfo = sprintf('<span><strong>%s</strong> (line <strong>%s</strong>)</span>', $file, $line);
<ide> } | 3 |
Java | Java | fix crash when destroying catalyst | f1015664e92f02c33417a591a2438db7c0cd3811 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public List<ViewManager> createAllViewManagers(
<ide> }
<ide>
<ide> public @Nullable ViewManager createViewManager(String viewManagerName) {
<del> ReactApplicationContext context =
<del> Assertions.assertNotNull((ReactApplicationContext) getCurrentReactContext());
<add> ReactApplicationContext context;
<add> synchronized (mReactContextLock) {
<add> context = (ReactApplicationContext) getCurrentReactContext();
<add> if (context == null || !context.hasActiveCatalystInstance()) {
<add> return null;
<add> }
<add> }
<add>
<ide> synchronized (mPackages) {
<ide> for (ReactPackage reactPackage : mPackages) {
<ide> if (reactPackage instanceof ViewManagerOnDemandReactPackage) {
<ide> public List<ViewManager> createAllViewManagers(
<ide> return null;
<ide> }
<ide>
<del> public List<String> getViewManagerNames() {
<del> ReactApplicationContext context =
<del> Assertions.assertNotNull((ReactApplicationContext) getCurrentReactContext());
<add> public @Nullable List<String> getViewManagerNames() {
<add> ReactApplicationContext context;
<add> synchronized(mReactContextLock) {
<add> context = (ReactApplicationContext) getCurrentReactContext();
<add> if (context == null || !context.hasActiveCatalystInstance()) {
<add> return null;
<add> }
<add> }
<add>
<ide> synchronized (mPackages) {
<ide> Set<String> uniqueNames = new HashSet<>();
<ide> for (ReactPackage reactPackage : mPackages) {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ViewManagerOnDemandReactPackage.java
<ide> public interface ViewManagerOnDemandReactPackage {
<ide> *
<ide> * @param loadClasses defines if View Managers classes should be loaded or be avoided.
<ide> */
<del> List<String> getViewManagerNames(ReactApplicationContext reactContext, boolean loadClasses);
<add> @Nullable List<String> getViewManagerNames(ReactApplicationContext reactContext, boolean loadClasses);
<ide> /**
<ide> * Creates and returns a ViewManager with a specific name {@param viewManagerName}. It's up to an
<ide> * implementing package how to interpret the name. | 2 |
PHP | PHP | add test for scriptstart() default behavior | 6553c3f554505031c2f521f5e30dcbbfda988967 | <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testScriptBlock()
<ide> */
<ide> public function testScriptStartAndScriptEnd()
<ide> {
<del> $result = $this->Html->scriptStart(['safe' => true]);
<add> $result = $this->Html->scriptStart();
<ide> $this->assertNull($result);
<ide> echo 'this is some javascript';
<ide>
<ide> $result = $this->Html->scriptEnd();
<ide> $expected = [
<ide> '<script',
<del> $this->cDataStart,
<ide> 'this is some javascript',
<del> $this->cDataEnd,
<ide> '/script'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide> public function testScriptStartAndScriptEnd()
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<add> $result = $this->Html->scriptStart(['safe' => true]);
<add> $this->assertNull($result);
<add> echo 'this is some javascript';
<add>
<add> $result = $this->Html->scriptEnd();
<add> $expected = [
<add> '<script',
<add> $this->cDataStart,
<add> 'this is some javascript',
<add> $this->cDataEnd,
<add> '/script'
<add> ];
<add> $this->assertHtml($expected, $result);
<add>
<ide> $result = $this->Html->scriptStart(['safe' => true, 'type' => 'text/x-handlebars-template']);
<ide> $this->assertNull($result);
<ide> echo 'this is some template'; | 1 |
Java | Java | refine behavior on error after response committed | f05175586e32e660ff190311f0b102c2b3b3a398 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorHttpHandlerAdapter.java
<ide> public Mono<Void> apply(HttpServerRequest request, HttpServerResponse response)
<ide> }
<ide>
<ide> return this.httpHandler.handle(adaptedRequest, adaptedResponse)
<del> .onErrorResume(ex -> {
<del> logger.error("Could not complete request", ex);
<del> response.status(HttpResponseStatus.INTERNAL_SERVER_ERROR);
<del> return Mono.empty();
<del> })
<del> .doOnSuccess(aVoid -> logger.debug("Successfully completed request"));
<add> .doOnError(ex -> logger.error("Handling completed with error", ex))
<add> .doOnSuccess(aVoid -> logger.debug("Handling completed with success"));
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java
<ide>
<ide> import java.io.IOException;
<ide> import java.util.Collection;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<ide> import javax.servlet.AsyncContext;
<ide> import javax.servlet.AsyncEvent;
<ide> import javax.servlet.AsyncListener;
<add>import javax.servlet.DispatcherType;
<ide> import javax.servlet.Servlet;
<ide> import javax.servlet.ServletConfig;
<add>import javax.servlet.ServletException;
<ide> import javax.servlet.ServletRegistration;
<ide> import javax.servlet.ServletRequest;
<ide> import javax.servlet.ServletResponse;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.web.util.NestedServletException;
<ide>
<ide> /**
<ide> * Adapt {@link HttpHandler} to an {@link HttpServlet} using Servlet Async
<ide> public class ServletHttpHandlerAdapter implements Servlet {
<ide>
<ide> private static final Log logger = LogFactory.getLog(ServletHttpHandlerAdapter.class);
<ide>
<del>
<ide> private static final int DEFAULT_BUFFER_SIZE = 8192;
<ide>
<add> private static final String WRITE_ERROR_ATTRIBUTE_NAME = ServletHttpHandlerAdapter.class.getName() + ".ERROR";
<add>
<ide>
<ide> private final HttpHandler httpHandler;
<ide>
<ide> private String getServletPath(ServletConfig config) {
<ide>
<ide>
<ide> @Override
<del> public void service(ServletRequest request, ServletResponse response) throws IOException {
<add> public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
<add>
<add> if (DispatcherType.ASYNC.equals(request.getDispatcherType())) {
<add> Throwable ex = (Throwable) request.getAttribute(WRITE_ERROR_ATTRIBUTE_NAME);
<add> Assert.notNull(ex, "Unexpected async dispatch");
<add> throw new NestedServletException("Write publisher error", ex);
<add> }
<add>
<ide> // Start async before Read/WriteListener registration
<ide> AsyncContext asyncContext = request.startAsync();
<ide> asyncContext.setTimeout(-1);
<ide> public void service(ServletRequest request, ServletResponse response) throws IOE
<ide> httpResponse = new HttpHeadResponseDecorator(httpResponse);
<ide> }
<ide>
<del> asyncContext.addListener(ERROR_LISTENER);
<add> AtomicBoolean isCompleted = new AtomicBoolean();
<add> HandlerResultAsyncListener listener = new HandlerResultAsyncListener(isCompleted);
<add> asyncContext.addListener(listener);
<ide>
<del> HandlerResultSubscriber subscriber = new HandlerResultSubscriber(asyncContext);
<add> HandlerResultSubscriber subscriber = new HandlerResultSubscriber(asyncContext, isCompleted);
<ide> this.httpHandler.handle(httpRequest, httpResponse).subscribe(subscriber);
<ide> }
<ide>
<ide> public void destroy() {
<ide> * We cannot combine ERROR_LISTENER and HandlerResultSubscriber due to:
<ide> * https://issues.jboss.org/browse/WFLY-8515
<ide> */
<del> private static void runIfAsyncNotComplete(AsyncContext asyncContext, Runnable task) {
<add> private static void runIfAsyncNotComplete(AsyncContext asyncContext, AtomicBoolean isCompleted, Runnable task) {
<ide> try {
<del> if (asyncContext.getRequest().isAsyncStarted()) {
<add> if (asyncContext.getRequest().isAsyncStarted() && isCompleted.compareAndSet(false, true)) {
<ide> task.run();
<ide> }
<ide> }
<ide> private static void runIfAsyncNotComplete(AsyncContext asyncContext, Runnable ta
<ide> }
<ide>
<ide>
<del> private final static AsyncListener ERROR_LISTENER = new AsyncListener() {
<add> private static class HandlerResultAsyncListener implements AsyncListener {
<add>
<add> private final AtomicBoolean isCompleted;
<add>
<add>
<add> public HandlerResultAsyncListener(AtomicBoolean isCompleted) {
<add> this.isCompleted = isCompleted;
<add> }
<ide>
<ide> @Override
<ide> public void onTimeout(AsyncEvent event) {
<add> logger.debug("Timeout notification from Servlet container");
<ide> AsyncContext context = event.getAsyncContext();
<del> runIfAsyncNotComplete(context, context::complete);
<add> runIfAsyncNotComplete(context, this.isCompleted, context::complete);
<ide> }
<ide>
<ide> @Override
<ide> public void onError(AsyncEvent event) {
<add> logger.debug("Error notification from Servlet container");
<ide> AsyncContext context = event.getAsyncContext();
<del> runIfAsyncNotComplete(context, context::complete);
<add> runIfAsyncNotComplete(context, this.isCompleted, context::complete);
<ide> }
<ide>
<ide> @Override
<ide> private class HandlerResultSubscriber implements Subscriber<Void> {
<ide>
<ide> private final AsyncContext asyncContext;
<ide>
<del> public HandlerResultSubscriber(AsyncContext asyncContext) {
<add> private final AtomicBoolean isCompleted;
<add>
<add>
<add> public HandlerResultSubscriber(AsyncContext asyncContext, AtomicBoolean isCompleted) {
<ide> this.asyncContext = asyncContext;
<add> this.isCompleted = isCompleted;
<ide> }
<ide>
<ide> @Override
<ide> public void onNext(Void aVoid) {
<ide>
<ide> @Override
<ide> public void onError(Throwable ex) {
<del> runIfAsyncNotComplete(this.asyncContext, () -> {
<del> logger.error("Could not complete request", ex);
<del> HttpServletResponse response = (HttpServletResponse) this.asyncContext.getResponse();
<del> response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
<del> this.asyncContext.complete();
<add> logger.error("Handling completed with error", ex);
<add> runIfAsyncNotComplete(this.asyncContext, this.isCompleted, () -> {
<add> if (this.asyncContext.getResponse().isCommitted()) {
<add> logger.debug("Dispatching into container to raise error");
<add> this.asyncContext.getRequest().setAttribute(WRITE_ERROR_ATTRIBUTE_NAME, ex);
<add> this.asyncContext.dispatch();
<add> }
<add> else {
<add> try {
<add> logger.debug("Setting response status code to 500");
<add> this.asyncContext.getResponse().resetBuffer();
<add> ((HttpServletResponse) this.asyncContext.getResponse()).setStatus(500);
<add> }
<add> finally {
<add> this.asyncContext.complete();
<add> }
<add> }
<ide> });
<ide> }
<ide>
<ide> @Override
<ide> public void onComplete() {
<del> runIfAsyncNotComplete(this.asyncContext, () -> {
<del> logger.debug("Successfully completed request");
<del> this.asyncContext.complete();
<del> });
<add> logger.debug("Handling completed with success");
<add> runIfAsyncNotComplete(this.asyncContext, this.isCompleted, this.asyncContext::complete);
<ide> }
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowHttpHandlerAdapter.java
<ide>
<ide> package org.springframework.http.server.reactive;
<ide>
<add>import java.io.IOException;
<add>
<ide> import io.undertow.server.HttpServerExchange;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> public void onNext(Void aVoid) {
<ide>
<ide> @Override
<ide> public void onError(Throwable ex) {
<del> logger.error("Could not complete request", ex);
<del> if (!this.exchange.isResponseStarted() && this.exchange.getStatusCode() < 500) {
<add> logger.error("Handling completed with error", ex);
<add> if (this.exchange.isResponseStarted()) {
<add> try {
<add> logger.debug("Closing connection");
<add> this.exchange.getConnection().close();
<add> }
<add> catch (IOException e) {
<add> // Ignore
<add> }
<add> }
<add> else {
<add> logger.debug("Setting response status code to 500");
<ide> this.exchange.setStatusCode(500);
<add> this.exchange.endExchange();
<ide> }
<del> this.exchange.endExchange();
<ide> }
<ide>
<ide> @Override
<ide> public void onComplete() {
<del> logger.debug("Successfully completed request");
<add> logger.debug("Handling completed with success");
<ide> this.exchange.endExchange();
<ide> }
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/HttpWebHandlerAdapter.java
<ide> public LocaleContextResolver getLocaleContextResolver() {
<ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<ide> ServerWebExchange exchange = createExchange(request, response);
<ide> return getDelegate().handle(exchange)
<del> .onErrorResume(ex -> {
<del> handleFailure(response, ex);
<del> return Mono.empty();
<del> })
<add> .onErrorResume(ex -> handleFailure(response, ex))
<ide> .then(Mono.defer(response::setComplete));
<ide> }
<ide>
<ide> protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttp
<ide> getCodecConfigurer(), getLocaleContextResolver());
<ide> }
<ide>
<del> private void handleFailure(ServerHttpResponse response, Throwable ex) {
<del> boolean statusCodeChanged = response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
<add> private Mono<Void> handleFailure(ServerHttpResponse response, Throwable ex) {
<ide> if (isDisconnectedClientError(ex)) {
<ide> if (disconnectedClientLogger.isTraceEnabled()) {
<ide> disconnectedClientLogger.trace("Looks like the client has gone away", ex);
<ide> else if (disconnectedClientLogger.isDebugEnabled()) {
<ide> " (For a full stack trace, set the log category '" + DISCONNECTED_CLIENT_LOG_CATEGORY +
<ide> "' to TRACE level.)");
<ide> }
<add> return Mono.empty();
<ide> }
<del> else if (!statusCodeChanged) {
<del> logger.error("Unhandled failure: " + ex.getMessage() + ", " +
<del> "response already committed with status=" + response.getStatusCode());
<del> }
<del> else {
<add> if (response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR)) {
<ide> logger.error("Failed to handle request", ex);
<add> return Mono.empty();
<ide> }
<add> // After the response is committed, propagate errors to the server..
<add> HttpStatus status = response.getStatusCode();
<add> logger.error("Unhandled failure: " + ex.getMessage() + ", response already set (status=" + status + ")");
<add> return Mono.error(ex);
<ide> }
<ide>
<ide> private boolean isDisconnectedClientError(Throwable ex) {
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java
<ide>
<ide> import java.io.IOException;
<ide>
<add>import org.junit.Assume;
<ide> import org.junit.Test;
<ide> import org.reactivestreams.Publisher;
<add>import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.ResponseEntity;
<add>import org.springframework.http.server.reactive.bootstrap.ReactorHttpServer;
<ide> import org.springframework.web.bind.annotation.ExceptionHandler;
<ide> import org.springframework.web.bind.annotation.GetMapping;
<ide> import org.springframework.web.bind.annotation.RestController;
<ide> protected ApplicationContext initApplicationContext() {
<ide>
<ide>
<ide> @Test
<del> public void controllerThrowingException() throws Exception {
<del> String expected = "Recovered from error: State";
<del> assertEquals(expected, performGet("/thrown-exception", new HttpHeaders(), String.class).getBody());
<add> public void thrownException() throws Exception {
<add> doTest("/thrown-exception", "Recovered from error: State");
<ide> }
<ide>
<ide> @Test
<del> public void controllerThrowingExceptionWithCause() throws Exception {
<del> String expected = "Recovered from error: State";
<del> assertEquals(expected, performGet("/thrown-exception-with-cause", new HttpHeaders(), String.class).getBody());
<add> public void thrownExceptionWithCause() throws Exception {
<add> doTest("/thrown-exception-with-cause", "Recovered from error: State");
<ide> }
<ide>
<ide> @Test
<del> public void controllerThrowingExceptionWithCauseToHandle() throws Exception {
<del> String expected = "Recovered from error: IO";
<del> String url = "/thrown-exception-with-cause-to-handle";
<del> assertEquals(expected, performGet(url, new HttpHeaders(), String.class).getBody());
<add> public void thrownExceptionWithCauseToHandle() throws Exception {
<add> doTest("/thrown-exception-with-cause-to-handle", "Recovered from error: IO");
<ide> }
<ide>
<ide> @Test
<del> public void controllerReturnsMonoError() throws Exception {
<del> String expected = "Recovered from error: Argument";
<del> assertEquals(expected, performGet("/mono-error", new HttpHeaders(), String.class).getBody());
<add> public void errorBeforeFirstItem() throws Exception {
<add> doTest("/mono-error", "Recovered from error: Argument");
<add> }
<add>
<add> @Test // SPR-16051
<add> public void exceptionAfterSeveralItems() throws Exception {
<add>
<add> // TODO: uncomment and try after https://github.com/reactor/reactor-netty/issues/231
<add> Assume.assumeFalse(server instanceof ReactorHttpServer);
<add>
<add> try {
<add> performGet("/SPR-16051", new HttpHeaders(), String.class).getBody();
<add> fail();
<add> }
<add> catch (Throwable ex) {
<add> String message = ex.getMessage();
<add> assertNotNull(message);
<add> assertTrue("Actual: " + message, message.startsWith("Error while extracting response"));
<add> }
<add> }
<add>
<add> private void doTest(String url, String expected) throws Exception {
<add> assertEquals(expected, performGet(url, new HttpHeaders(), String.class).getBody());
<ide> }
<ide>
<ide>
<ide> public Publisher<String> handleWithError() {
<ide> return Mono.error(new IllegalArgumentException("Argument"));
<ide> }
<ide>
<add> @GetMapping("/SPR-16051")
<add> public Flux<String> errors() {
<add> return Flux.range(1, 10000)
<add> .map(i -> {
<add> if (i == 1000) {
<add> throw new RuntimeException("Random error");
<add> }
<add> return i + ". foo bar";
<add> });
<add> }
<add>
<add>
<ide> @ExceptionHandler
<ide> public Publisher<String> handleArgumentException(IOException ex) {
<ide> return Mono.just("Recovered from error: " + ex.getMessage());
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/socket/AbstractWebSocketIntegrationTests.java
<ide> import java.util.LinkedHashMap;
<ide> import java.util.Map;
<ide>
<del>import org.apache.tomcat.websocket.WsWebSocketContainer;
<ide> import org.apache.tomcat.websocket.server.WsContextListener;
<ide> import org.junit.After;
<ide> import org.junit.Before; | 6 |
Ruby | Ruby | remove unused revision default | 492ce9cc5e98ef9fa330abb93f4082cdb4d034bf | <ide><path>Library/Homebrew/bottles.rb
<ide> require 'extend/ARGV'
<ide> require 'bottle_version'
<ide>
<del>def bottle_filename f, options={:tag=>bottle_tag, :bottle_revision=>nil}
<add>def bottle_filename f, options={:tag=>bottle_tag}
<ide> name = f.name.downcase
<ide> version = f.stable.version
<ide> options[:revision] ||= f.bottle.revision.to_i if f.bottle | 1 |
Text | Text | fix s/rststream/close in example | 47a282293f62813a88b4c4ba18bc5e5246a6515c | <ide><path>doc/api/http2.md
<ide> const { NGHTTP2_CANCEL } = http2.constants;
<ide> const req = client.request({ ':path': '/' });
<ide>
<ide> // Cancel the stream if there's no activity after 5 seconds
<del>req.setTimeout(5000, () => req.rstStream(NGHTTP2_CANCEL));
<add>req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));
<ide> ```
<ide>
<ide> #### http2stream.state | 1 |
Javascript | Javascript | remove deprecation warnings in http module | a63fd0fe560055428bc2edb8ee7af2ffe61cd7bd | <ide><path>lib/http.js
<ide> IncomingMessage.prototype._parseQueryString = function () {
<ide> throw new Error("_parseQueryString is deprecated. Use require(\"querystring\") to parse query strings.\n");
<ide> };
<ide>
<del>var setBodyEncodingWarning;
<del>
<del>IncomingMessage.prototype.setBodyEncoding = function (enc) {
<del> // deprecation message
<del> if (!setBodyEncodingWarning) {
<del> setBodyEncodingWarning = "setBodyEncoding has been renamed to setEncoding, please update your code.";
<del> sys.error(setBodyEncodingWarning);
<del> }
<del>
<del> this.setEncoding(enc);
<del>};
<ide>
<ide> IncomingMessage.prototype.setEncoding = function (encoding) {
<ide> var StringDecoder = require("string_decoder").StringDecoder; // lazy load
<ide> OutgoingMessage.prototype.addTrailers = function (headers) {
<ide> };
<ide>
<ide>
<del>OutgoingMessage.prototype.finish = function () {
<del> throw new Error("finish() has been renamed to close().");
<del>};
<del>
<del>var closeWarning;
<del>
<del>OutgoingMessage.prototype.close = function (data, encoding) {
<del> if (!closeWarning) {
<del> closeWarning = "OutgoingMessage.prototype.close has been renamed to end()";
<del> sys.error(closeWarning);
<del> }
<del> return this.end(data, encoding);
<del>};
<del>
<ide> OutgoingMessage.prototype.end = function (data, encoding) {
<ide> var ret;
<ide>
<ide> ServerResponse.prototype.writeHead = function (statusCode) {
<ide> this._storeHeader(statusLine, headers);
<ide> };
<ide>
<del>// TODO Eventually remove
<del>var sendHeaderWarning, writeHeaderWarning;
<del>ServerResponse.prototype.sendHeader = function () {
<del> if (!sendHeaderWarning) {
<del> sendHeaderWarning = "sendHeader() has been renamed to writeHead()";
<del> sys.error(sendHeaderWarning);
<del> }
<del> this.writeHead.apply(this, arguments);
<del>};
<add>
<ide> ServerResponse.prototype.writeHeader = function () {
<del> if (!writeHeaderWarning) {
<del> writeHeaderWarning = "writeHeader() has been renamed to writeHead()";
<del> sys.error(writeHeaderWarning);
<del> }
<ide> this.writeHead.apply(this, arguments);
<ide> };
<ide>
<ide> ClientRequest.prototype.finish = function () {
<ide> );
<ide> };
<ide>
<del>var clientRequestCloseWarning;
<del>
<del>ClientRequest.prototype.close = function () {
<del> if (!clientRequestCloseWarning) {
<del> clientRequestCloseWarning = "Warning: ClientRequest.prototype.close has been renamed to end()";
<del> sys.error(clientRequestCloseWarning);
<del> }
<del> if (typeof arguments[0] == "function") {
<del> throw new Error( "ClientRequest.prototype.end does not take a callback. "
<del> + "Add a 'response' listener manually to the request object."
<del> );
<del> }
<del> return this.end();
<del>};
<ide>
<ide> ClientRequest.prototype.end = function () {
<ide> if (typeof arguments[0] == "function") { | 1 |
Ruby | Ruby | make valid_type? public | 5d528f835e871f5f9d4b68e8a81cfbe900b7e718 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def close
<ide> pool.checkin self
<ide> end
<ide>
<add> def valid_type?(type)
<add> true
<add> end
<add>
<ide> protected
<ide>
<ide> def log(sql, name = "SQL", binds = [])
<ide> def translate_exception(exception, message)
<ide> # override in derived class
<ide> ActiveRecord::StatementInvalid.new(message)
<ide> end
<del>
<del> def valid_types?(type)
<del> true
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def strict_mode?
<ide> @config.fetch(:strict, true)
<ide> end
<ide>
<add> def valid_type?(type)
<add> !native_database_types[type].nil?
<add> end
<add>
<ide> protected
<ide>
<ide> # MySQL is too stupid to create a temporary table for use subquery, so we have
<ide> def configure_connection
<ide> # ...and send them all in one query
<ide> execute("SET #{encoding} #{variable_assignments}", :skip_logging)
<ide> end
<del>
<del> def valid_type?(type)
<del> !native_database_types[type].nil?
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def use_insert_returning?
<ide> @use_insert_returning
<ide> end
<ide>
<add> def valid_type?(type)
<add> !native_database_types[type].nil?
<add> end
<add>
<ide> protected
<ide>
<ide> # Returns the version of the connected PostgreSQL server.
<ide> def extract_table_ref_from_insert_sql(sql)
<ide> def table_definition
<ide> TableDefinition.new(self)
<ide> end
<del>
<del> def valid_type?(type)
<del> !native_database_types[type].nil?
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def translate_exception(exception, message)
<ide> super
<ide> end
<ide> end
<del>
<del> def valid_type?(type)
<del> true
<del> end
<del>
<ide> end
<ide> end
<ide> end | 4 |
Text | Text | remove nbsp's across tables in the docs | 83ed1f391bc6551477b6c97d7ffec61ac2cf80b3 | <ide><path>website/docs/api/cli.md
<ide> $ python -m spacy project run [subcommand] [project_dir] [--force] [--dry]
<ide> | `subcommand` | Name of the command or workflow to run. ~~str (positional)~~ |
<ide> | `project_dir` | Path to project directory. Defaults to current working directory. ~~Path (positional)~~ |
<ide> | `--force`, `-F` | Force re-running steps, even if nothing changed. ~~bool (flag)~~ |
<del>| `--dry`, `-D` | Perform a dry run and don't execute scripts. ~~bool (flag)~~ |
<add>| `--dry`, `-D` | Perform a dry run and don't execute scripts. ~~bool (flag)~~ |
<ide> | `--help`, `-h` | Show help message and available arguments. ~~bool (flag)~~ |
<ide> | **EXECUTES** | The command defined in the `project.yml`. |
<ide>
<ide> For more examples, see the templates in our
<ide>
<ide> </Accordion>
<ide>
<del>| Name | Description |
<del>| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `project_dir` | Path to project directory. Defaults to current working directory. ~~Path (positional)~~ |
<del>| `--output`, `-o` | Path to output file or `-` for stdout (default). If a file is specified and it already exists and contains auto-generated docs, only the auto-generated docs section is replaced. ~~Path (positional)~~ |
<del>| `--no-emoji`, `-NE` | Don't use emoji in the titles. ~~bool (flag)~~ |
<del>| **CREATES** | The Markdown-formatted project documentation. |
<add>| Name | Description |
<add>| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `project_dir` | Path to project directory. Defaults to current working directory. ~~Path (positional)~~ |
<add>| `--output`, `-o` | Path to output file or `-` for stdout (default). If a file is specified and it already exists and contains auto-generated docs, only the auto-generated docs section is replaced. ~~Path (positional)~~ |
<add>| `--no-emoji`, `-NE` | Don't use emoji in the titles. ~~bool (flag)~~ |
<add>| **CREATES** | The Markdown-formatted project documentation. |
<ide>
<ide> ### project dvc {#project-dvc tag="command"}
<ide>
<ide> $ python -m spacy project dvc [project_dir] [workflow] [--force] [--verbose]
<ide> | `project_dir` | Path to project directory. Defaults to current working directory. ~~Path (positional)~~ |
<ide> | `workflow` | Name of workflow defined in `project.yml`. Defaults to first workflow if not set. ~~Optional[str] \(option)~~ |
<ide> | `--force`, `-F` | Force-updating config file. ~~bool (flag)~~ |
<del>| `--verbose`, `-V` | Print more output generated by DVC. ~~bool (flag)~~ |
<add>| `--verbose`, `-V` | Print more output generated by DVC. ~~bool (flag)~~ |
<ide> | `--help`, `-h` | Show help message and available arguments. ~~bool (flag)~~ |
<ide> | **CREATES** | A `dvc.yaml` file in the project directory, based on the steps defined in the given workflow. |
<ide>
<ide> $ python -m spacy huggingface-hub push [whl_path] [--org] [--msg] [--local-repo]
<ide> | `--org`, `-o` | Optional name of organization to which the pipeline should be uploaded. ~~str (option)~~ |
<ide> | `--msg`, `-m` | Commit message to use for update. Defaults to `"Update spaCy pipeline"`. ~~str (option)~~ |
<ide> | `--local-repo`, `-l` | Local path to the model repository (will be created if it doesn't exist). Defaults to `hub` in the current working directory. ~~Path (option)~~ |
<del>| `--verbose`, `-V` | Output additional info for debugging, e.g. the full generated hub metadata. ~~bool (flag)~~ |
<add>| `--verbose`, `-V` | Output additional info for debugging, e.g. the full generated hub metadata. ~~bool (flag)~~ |
<ide> | **UPLOADS** | The pipeline to the hub. |
<ide><path>website/docs/api/corpus.md
<ide> streaming.
<ide> > augmenter = null
<ide> > ```
<ide>
<del>| Name | Description |
<del>| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `path` | The directory or filename to read from. Expects data in spaCy's binary [`.spacy` format](/api/data-formats#binary-training). ~~Path~~ |
<del>| `gold_preproc` | Whether to set up the Example object with gold-standard sentences and tokens for the predictions. See [`Corpus`](/api/corpus#init) for details. ~~bool~~ |
<del>| `max_length` | Maximum document length. Longer documents will be split into sentences, if sentence boundaries are available. Defaults to `0` for no limit. ~~int~~ |
<del>| `limit` | Limit corpus to a subset of examples, e.g. for debugging. Defaults to `0` for no limit. ~~int~~ |
<del>| `augmenter` | Apply some simply data augmentation, where we replace tokens with variations. This is especially useful for punctuation and case replacement, to help generalize beyond corpora that don't have smart-quotes, or only have smart quotes, etc. Defaults to `None`. ~~Optional[Callable]~~ |
<add>| Name | Description |
<add>| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `path` | The directory or filename to read from. Expects data in spaCy's binary [`.spacy` format](/api/data-formats#binary-training). ~~Path~~ |
<add>| `gold_preproc` | Whether to set up the Example object with gold-standard sentences and tokens for the predictions. See [`Corpus`](/api/corpus#init) for details. ~~bool~~ |
<add>| `max_length` | Maximum document length. Longer documents will be split into sentences, if sentence boundaries are available. Defaults to `0` for no limit. ~~int~~ |
<add>| `limit` | Limit corpus to a subset of examples, e.g. for debugging. Defaults to `0` for no limit. ~~int~~ |
<add>| `augmenter` | Apply some simply data augmentation, where we replace tokens with variations. This is especially useful for punctuation and case replacement, to help generalize beyond corpora that don't have smart-quotes, or only have smart quotes, etc. Defaults to `None`. ~~Optional[Callable]~~ |
<ide>
<ide> ```python
<ide> %%GITHUB_SPACY/spacy/training/corpus.py
<ide> train/test skew.
<ide> > corpus = Corpus("./data", limit=10)
<ide> > ```
<ide>
<del>| Name | Description |
<del>| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `path` | The directory or filename to read from. ~~Union[str, Path]~~ |
<del>| _keyword-only_ | |
<del>| `gold_preproc` | Whether to set up the Example object with gold-standard sentences and tokens for the predictions. Defaults to `False`. ~~bool~~ |
<del>| `max_length` | Maximum document length. Longer documents will be split into sentences, if sentence boundaries are available. Defaults to `0` for no limit. ~~int~~ |
<del>| `limit` | Limit corpus to a subset of examples, e.g. for debugging. Defaults to `0` for no limit. ~~int~~ |
<del>| `augmenter` | Optional data augmentation callback. ~~Callable[[Language, Example], Iterable[Example]]~~ |
<del>| `shuffle` | Whether to shuffle the examples. Defaults to `False`. ~~bool~~ |
<add>| Name | Description |
<add>| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `path` | The directory or filename to read from. ~~Union[str, Path]~~ |
<add>| _keyword-only_ | |
<add>| `gold_preproc` | Whether to set up the Example object with gold-standard sentences and tokens for the predictions. Defaults to `False`. ~~bool~~ |
<add>| `max_length` | Maximum document length. Longer documents will be split into sentences, if sentence boundaries are available. Defaults to `0` for no limit. ~~int~~ |
<add>| `limit` | Limit corpus to a subset of examples, e.g. for debugging. Defaults to `0` for no limit. ~~int~~ |
<add>| `augmenter` | Optional data augmentation callback. ~~Callable[[Language, Example], Iterable[Example]]~~ |
<add>| `shuffle` | Whether to shuffle the examples. Defaults to `False`. ~~bool~~ |
<ide>
<ide> ## Corpus.\_\_call\_\_ {#call tag="method"}
<ide>
<ide><path>website/docs/api/language.md
<ide> instance and factory instance.
<ide> | `factory` | The name of the registered component factory. ~~str~~ |
<ide> | `default_config` | The default config, describing the default values of the factory arguments. ~~Dict[str, Any]~~ |
<ide> | `assigns` | `Doc` or `Token` attributes assigned by this component, e.g. `["token.ent_id"]`. Used for [pipe analysis](/usage/processing-pipelines#analysis). ~~Iterable[str]~~ |
<del>| `requires` | `Doc` or `Token` attributes required by this component, e.g. `["token.ent_id"]`. Used for [pipe analysis](/usage/processing-pipelines#analysis). ~~Iterable[str]~~ |
<del>| `retokenizes` | Whether the component changes tokenization. Used for [pipe analysis](/usage/processing-pipelines#analysis). ~~bool~~ |
<add>| `requires` | `Doc` or `Token` attributes required by this component, e.g. `["token.ent_id"]`. Used for [pipe analysis](/usage/processing-pipelines#analysis). ~~Iterable[str]~~ |
<add>| `retokenizes` | Whether the component changes tokenization. Used for [pipe analysis](/usage/processing-pipelines#analysis). ~~bool~~ |
<ide> | `default_score_weights` | The scores to report during training, and their default weight towards the final score used to select the best model. Weights should sum to `1.0` per component and will be combined and normalized for the whole pipeline. If a weight is set to `None`, the score will not be logged or weighted. ~~Dict[str, Optional[float]]~~ |
<ide> | `scores` | All scores set by the components if it's trainable, e.g. `["ents_f", "ents_r", "ents_p"]`. Based on the `default_score_weights` and used for [pipe analysis](/usage/processing-pipelines#analysis). ~~Iterable[str]~~ |
<ide><path>website/docs/api/matcher.md
<ide> pattern keys correspond to a number of
<ide> [`Token` attributes](/api/token#attributes). The supported attributes for
<ide> rule-based matching are:
<ide>
<del>| Attribute | Description |
<del>| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
<del>| `ORTH` | The exact verbatim text of a token. ~~str~~ |
<del>| `TEXT` <Tag variant="new">2.1</Tag> | The exact verbatim text of a token. ~~str~~ |
<del>| `NORM` | The normalized form of the token text. ~~str~~ |
<del>| `LOWER` | The lowercase form of the token text. ~~str~~ |
<del>| `LENGTH` | The length of the token text. ~~int~~ |
<del>| `IS_ALPHA`, `IS_ASCII`, `IS_DIGIT` | Token text consists of alphabetic characters, ASCII characters, digits. ~~bool~~ |
<del>| `IS_LOWER`, `IS_UPPER`, `IS_TITLE` | Token text is in lowercase, uppercase, titlecase. ~~bool~~ |
<del>| `IS_PUNCT`, `IS_SPACE`, `IS_STOP` | Token is punctuation, whitespace, stop word. ~~bool~~ |
<del>| `IS_SENT_START` | Token is start of sentence. ~~bool~~ |
<del>| `LIKE_NUM`, `LIKE_URL`, `LIKE_EMAIL` | Token text resembles a number, URL, email. ~~bool~~ |
<del>| `SPACY` | Token has a trailing space. ~~bool~~ |
<del>| `POS`, `TAG`, `MORPH`, `DEP`, `LEMMA`, `SHAPE` | The token's simple and extended part-of-speech tag, morphological analysis, dependency label, lemma, shape. ~~str~~ |
<del>| `ENT_TYPE` | The token's entity label. ~~str~~ |
<del>| `ENT_IOB` | The IOB part of the token's entity tag. ~~str~~ |
<del>| `ENT_ID` | The token's entity ID (`ent_id`). ~~str~~ |
<del>| `ENT_KB_ID` | The token's entity knowledge base ID (`ent_kb_id`). ~~str~~ |
<del>| `_` <Tag variant="new">2.1</Tag> | Properties in [custom extension attributes](/usage/processing-pipelines#custom-components-attributes). ~~Dict[str, Any]~~ |
<del>| `OP` | Operator or quantifier to determine how often to match a token pattern. ~~str~~ |
<add>| Attribute | Description |
<add>| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
<add>| `ORTH` | The exact verbatim text of a token. ~~str~~ |
<add>| `TEXT` <Tag variant="new">2.1</Tag> | The exact verbatim text of a token. ~~str~~ |
<add>| `NORM` | The normalized form of the token text. ~~str~~ |
<add>| `LOWER` | The lowercase form of the token text. ~~str~~ |
<add>| `LENGTH` | The length of the token text. ~~int~~ |
<add>| `IS_ALPHA`, `IS_ASCII`, `IS_DIGIT` | Token text consists of alphabetic characters, ASCII characters, digits. ~~bool~~ |
<add>| `IS_LOWER`, `IS_UPPER`, `IS_TITLE` | Token text is in lowercase, uppercase, titlecase. ~~bool~~ |
<add>| `IS_PUNCT`, `IS_SPACE`, `IS_STOP` | Token is punctuation, whitespace, stop word. ~~bool~~ |
<add>| `IS_SENT_START` | Token is start of sentence. ~~bool~~ |
<add>| `LIKE_NUM`, `LIKE_URL`, `LIKE_EMAIL` | Token text resembles a number, URL, email. ~~bool~~ |
<add>| `SPACY` | Token has a trailing space. ~~bool~~ |
<add>| `POS`, `TAG`, `MORPH`, `DEP`, `LEMMA`, `SHAPE` | The token's simple and extended part-of-speech tag, morphological analysis, dependency label, lemma, shape. ~~str~~ |
<add>| `ENT_TYPE` | The token's entity label. ~~str~~ |
<add>| `ENT_IOB` | The IOB part of the token's entity tag. ~~str~~ |
<add>| `ENT_ID` | The token's entity ID (`ent_id`). ~~str~~ |
<add>| `ENT_KB_ID` | The token's entity knowledge base ID (`ent_kb_id`). ~~str~~ |
<add>| `_` <Tag variant="new">2.1</Tag> | Properties in [custom extension attributes](/usage/processing-pipelines#custom-components-attributes). ~~Dict[str, Any]~~ |
<add>| `OP` | Operator or quantifier to determine how often to match a token pattern. ~~str~~ |
<ide>
<ide> Operators and quantifiers define **how often** a token pattern should be
<ide> matched:
<ide><path>website/docs/api/top-level.md
<ide> If a setting is not present in the options, the default value will be used.
<ide> | `template` <Tag variant="new">2.2</Tag> | Optional template to overwrite the HTML used to render entity spans. Should be a format string and can use `{bg}`, `{text}` and `{label}`. See [`templates.py`](%%GITHUB_SPACY/spacy/displacy/templates.py) for examples. ~~Optional[str]~~ |
<ide> | `kb_url_template` <Tag variant="new">3.2.1</Tag> | Optional template to construct the KB url for the entity to link to. Expects a python f-string format with single field to fill in. ~~Optional[str]~~ |
<ide>
<del>
<ide> #### Span Visualizer options {#displacy_options-span}
<ide>
<ide> > #### Example
<ide> If a setting is not present in the options, the default value will be used.
<ide> > displacy.serve(doc, style="span", options=options)
<ide> > ```
<ide>
<del>| Name | Description |
<del>|-----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
<del>| `spans_key` | Which spans key to render spans from. Default is `"sc"`. ~~str~~ |
<add>| Name | Description |
<add>| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `spans_key` | Which spans key to render spans from. Default is `"sc"`. ~~str~~ |
<ide> | `templates` | Dictionary containing the keys `"span"`, `"slice"`, and `"start"`. These dictate how the overall span, a span slice, and the starting token will be rendered. ~~Optional[Dict[str, str]~~ |
<del>| `kb_url_template` | Optional template to construct the KB url for the entity to link to. Expects a python f-string format with single field to fill in ~~Optional[str]~~ |
<del>| `colors` | Color overrides. Entity types should be mapped to color names or values. ~~Dict[str, str]~~ |
<del>
<add>| `kb_url_template` | Optional template to construct the KB url for the entity to link to. Expects a python f-string format with single field to fill in ~~Optional[str]~~ |
<add>| `colors` | Color overrides. Entity types should be mapped to color names or values. ~~Dict[str, str]~~ |
<ide>
<del>By default, displaCy comes with colors for all entity types used by [spaCy's
<del>trained pipelines](/models) for both entity and span visualizer. If you're
<del>using custom entity types, you can use the `colors` setting to add your own
<del>colors for them. Your application or pipeline package can also expose a
<del>[`spacy_displacy_colors` entry
<del>point](/usage/saving-loading#entry-points-displacy) to add custom labels and
<del>their colors automatically.
<add>By default, displaCy comes with colors for all entity types used by
<add>[spaCy's trained pipelines](/models) for both entity and span visualizer. If
<add>you're using custom entity types, you can use the `colors` setting to add your
<add>own colors for them. Your application or pipeline package can also expose a
<add>[`spacy_displacy_colors` entry point](/usage/saving-loading#entry-points-displacy)
<add>to add custom labels and their colors automatically.
<ide>
<ide> By default, displaCy links to `#` for entities without a `kb_id` set on their
<ide> span. If you wish to link an entity to their URL then consider using the
<ide> span. If you wish to link an entity to their URL then consider using the
<ide> should redirect you to their Wikidata page, in this case
<ide> `https://www.wikidata.org/wiki/Q95`.
<ide>
<del>
<ide> ## registry {#registry source="spacy/util.py" new="3"}
<ide>
<ide> spaCy's function registry extends
<ide> and the accuracy scores on the development set.
<ide> The built-in, default logger is the ConsoleLogger, which prints results to the
<ide> console in tabular format. The
<ide> [spacy-loggers](https://github.com/explosion/spacy-loggers) package, included as
<del>a dependency of spaCy, enables other loggers, such as one that
<del>sends results to a [Weights & Biases](https://www.wandb.com/) dashboard.
<add>a dependency of spaCy, enables other loggers, such as one that sends results to
<add>a [Weights & Biases](https://www.wandb.com/) dashboard.
<ide>
<ide> Instead of using one of the built-in loggers, you can
<ide> [implement your own](/usage/training#custom-logging).
<ide> the [`Corpus`](/api/corpus) class.
<ide> > limit = 0
<ide> > ```
<ide>
<del>| Name | Description |
<del>| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `path` | The directory or filename to read from. Expects data in spaCy's binary [`.spacy` format](/api/data-formats#binary-training). ~~Union[str, Path]~~ |
<del>| `gold_preproc` | Whether to set up the Example object with gold-standard sentences and tokens for the predictions. See [`Corpus`](/api/corpus#init) for details. ~~bool~~ |
<del>| `max_length` | Maximum document length. Longer documents will be split into sentences, if sentence boundaries are available. Defaults to `0` for no limit. ~~int~~ |
<del>| `limit` | Limit corpus to a subset of examples, e.g. for debugging. Defaults to `0` for no limit. ~~int~~ |
<del>| `augmenter` | Apply some simply data augmentation, where we replace tokens with variations. This is especially useful for punctuation and case replacement, to help generalize beyond corpora that don't have smart-quotes, or only have smart quotes, etc. Defaults to `None`. ~~Optional[Callable]~~ |
<del>| **CREATES** | The corpus reader. ~~Corpus~~ |
<add>| Name | Description |
<add>| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `path` | The directory or filename to read from. Expects data in spaCy's binary [`.spacy` format](/api/data-formats#binary-training). ~~Union[str, Path]~~ |
<add>| `gold_preproc` | Whether to set up the Example object with gold-standard sentences and tokens for the predictions. See [`Corpus`](/api/corpus#init) for details. ~~bool~~ |
<add>| `max_length` | Maximum document length. Longer documents will be split into sentences, if sentence boundaries are available. Defaults to `0` for no limit. ~~int~~ |
<add>| `limit` | Limit corpus to a subset of examples, e.g. for debugging. Defaults to `0` for no limit. ~~int~~ |
<add>| `augmenter` | Apply some simply data augmentation, where we replace tokens with variations. This is especially useful for punctuation and case replacement, to help generalize beyond corpora that don't have smart-quotes, or only have smart quotes, etc. Defaults to `None`. ~~Optional[Callable]~~ |
<add>| **CREATES** | The corpus reader. ~~Corpus~~ |
<ide>
<ide> #### spacy.JsonlCorpus.v1 {#jsonlcorpus tag="registered function"}
<ide>
<ide><path>website/docs/usage/linguistic-features.md
<ide> but do not change its part-of-speech. We say that a **lemma** (root form) is
<ide> **inflected** (modified/combined) with one or more **morphological features** to
<ide> create a surface form. Here are some examples:
<ide>
<del>| Context | Surface | Lemma | POS | Morphological Features |
<add>| Context | Surface | Lemma | POS | Morphological Features |
<ide> | ---------------------------------------- | ------- | ----- | ------ | ---------------------------------------- |
<ide> | I was reading the paper | reading | read | `VERB` | `VerbForm=Ger` |
<ide> | I don't watch the news, I read the paper | read | read | `VERB` | `VerbForm=Fin`, `Mood=Ind`, `Tense=Pres` |
<ide> for token in doc:
<ide> print(token.text, token.pos_, token.dep_, token.head.text)
<ide> ```
<ide>
<del>| Text | POS | Dep | Head text |
<add>| Text | POS | Dep | Head text |
<ide> | ----------------------------------- | ------ | ------- | --------- |
<ide> | Credit and mortgage account holders | `NOUN` | `nsubj` | submit |
<ide> | must | `VERB` | `aux` | submit |
<ide><path>website/docs/usage/rule-based-matching.md
<ide> The available token pattern keys correspond to a number of
<ide> [`Token` attributes](/api/token#attributes). The supported attributes for
<ide> rule-based matching are:
<ide>
<del>| Attribute | Description |
<del>| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `ORTH` | The exact verbatim text of a token. ~~str~~ |
<del>| `TEXT` <Tag variant="new">2.1</Tag> | The exact verbatim text of a token. ~~str~~ |
<del>| `NORM` | The normalized form of the token text. ~~str~~ |
<del>| `LOWER` | The lowercase form of the token text. ~~str~~ |
<del>| `LENGTH` | The length of the token text. ~~int~~ |
<del>| `IS_ALPHA`, `IS_ASCII`, `IS_DIGIT` | Token text consists of alphabetic characters, ASCII characters, digits. ~~bool~~ |
<del>| `IS_LOWER`, `IS_UPPER`, `IS_TITLE` | Token text is in lowercase, uppercase, titlecase. ~~bool~~ |
<del>| `IS_PUNCT`, `IS_SPACE`, `IS_STOP` | Token is punctuation, whitespace, stop word. ~~bool~~ |
<del>| `IS_SENT_START` | Token is start of sentence. ~~bool~~ |
<del>| `LIKE_NUM`, `LIKE_URL`, `LIKE_EMAIL` | Token text resembles a number, URL, email. ~~bool~~ |
<del>| `SPACY` | Token has a trailing space. ~~bool~~ |
<del>| `POS`, `TAG`, `MORPH`, `DEP`, `LEMMA`, `SHAPE` | The token's simple and extended part-of-speech tag, morphological analysis, dependency label, lemma, shape. Note that the values of these attributes are case-sensitive. For a list of available part-of-speech tags and dependency labels, see the [Annotation Specifications](/api/annotation). ~~str~~ |
<del>| `ENT_TYPE` | The token's entity label. ~~str~~ |
<del>| `_` <Tag variant="new">2.1</Tag> | Properties in [custom extension attributes](/usage/processing-pipelines#custom-components-attributes). ~~Dict[str, Any]~~ |
<del>| `OP` | [Operator or quantifier](#quantifiers) to determine how often to match a token pattern. ~~str~~ |
<add>| Attribute | Description |
<add>| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `ORTH` | The exact verbatim text of a token. ~~str~~ |
<add>| `TEXT` <Tag variant="new">2.1</Tag> | The exact verbatim text of a token. ~~str~~ |
<add>| `NORM` | The normalized form of the token text. ~~str~~ |
<add>| `LOWER` | The lowercase form of the token text. ~~str~~ |
<add>| `LENGTH` | The length of the token text. ~~int~~ |
<add>| `IS_ALPHA`, `IS_ASCII`, `IS_DIGIT` | Token text consists of alphabetic characters, ASCII characters, digits. ~~bool~~ |
<add>| `IS_LOWER`, `IS_UPPER`, `IS_TITLE` | Token text is in lowercase, uppercase, titlecase. ~~bool~~ |
<add>| `IS_PUNCT`, `IS_SPACE`, `IS_STOP` | Token is punctuation, whitespace, stop word. ~~bool~~ |
<add>| `IS_SENT_START` | Token is start of sentence. ~~bool~~ |
<add>| `LIKE_NUM`, `LIKE_URL`, `LIKE_EMAIL` | Token text resembles a number, URL, email. ~~bool~~ |
<add>| `SPACY` | Token has a trailing space. ~~bool~~ |
<add>| `POS`, `TAG`, `MORPH`, `DEP`, `LEMMA`, `SHAPE` | The token's simple and extended part-of-speech tag, morphological analysis, dependency label, lemma, shape. Note that the values of these attributes are case-sensitive. For a list of available part-of-speech tags and dependency labels, see the [Annotation Specifications](/api/annotation). ~~str~~ |
<add>| `ENT_TYPE` | The token's entity label. ~~str~~ |
<add>| `_` <Tag variant="new">2.1</Tag> | Properties in [custom extension attributes](/usage/processing-pipelines#custom-components-attributes). ~~Dict[str, Any]~~ |
<add>| `OP` | [Operator or quantifier](#quantifiers) to determine how often to match a token pattern. ~~str~~ |
<ide>
<ide> <Accordion title="Does it matter if the attribute names are uppercase or lowercase?">
<ide>
<ide><path>website/docs/usage/v3-1.md
<ide> your own.
<ide> > contributions for Catalan and to Kenneth Enevoldsen for Danish. For additional
<ide> > Danish pipelines, check out [DaCy](https://github.com/KennethEnevoldsen/DaCy).
<ide>
<del>| Package | Language | UPOS | Parser LAS | NER F |
<del>| ------------------------------------------------- | -------- | ---: | ---------: | -----: |
<del>| [`ca_core_news_sm`](/models/ca#ca_core_news_sm) | Catalan | 98.2 | 87.4 | 79.8 |
<del>| [`ca_core_news_md`](/models/ca#ca_core_news_md) | Catalan | 98.3 | 88.2 | 84.0 |
<del>| [`ca_core_news_lg`](/models/ca#ca_core_news_lg) | Catalan | 98.5 | 88.4 | 84.2 |
<del>| [`ca_core_news_trf`](/models/ca#ca_core_news_trf) | Catalan | 98.9 | 93.0 | 91.2 |
<del>| [`da_core_news_trf`](/models/da#da_core_news_trf) | Danish | 98.0 | 85.0 | 82.9 |
<add>| Package | Language | UPOS | Parser LAS | NER F |
<add>| ------------------------------------------------- | -------- | ---: | ---------: | ----: |
<add>| [`ca_core_news_sm`](/models/ca#ca_core_news_sm) | Catalan | 98.2 | 87.4 | 79.8 |
<add>| [`ca_core_news_md`](/models/ca#ca_core_news_md) | Catalan | 98.3 | 88.2 | 84.0 |
<add>| [`ca_core_news_lg`](/models/ca#ca_core_news_lg) | Catalan | 98.5 | 88.4 | 84.2 |
<add>| [`ca_core_news_trf`](/models/ca#ca_core_news_trf) | Catalan | 98.9 | 93.0 | 91.2 |
<add>| [`da_core_news_trf`](/models/da#da_core_news_trf) | Danish | 98.0 | 85.0 | 82.9 |
<ide>
<ide> ### Resizable text classification architectures {#resizable-textcat}
<ide>
<ide><path>website/docs/usage/v3.md
<ide> import Benchmarks from 'usage/\_benchmarks-models.md'
<ide> > corpus that had both syntactic and entity annotations, so the transformer
<ide> > models for those languages do not include NER.
<ide>
<del>| Package | Language | Transformer | Tagger | Parser | NER |
<add>| Package | Language | Transformer | Tagger | Parser | NER |
<ide> | ------------------------------------------------ | -------- | --------------------------------------------------------------------------------------------- | -----: | -----: | ---: |
<ide> | [`en_core_web_trf`](/models/en#en_core_web_trf) | English | [`roberta-base`](https://huggingface.co/roberta-base) | 97.8 | 95.2 | 89.9 |
<ide> | [`de_dep_news_trf`](/models/de#de_dep_news_trf) | German | [`bert-base-german-cased`](https://huggingface.co/bert-base-german-cased) | 99.0 | 95.8 | - |
<ide> attribute ruler before training using the `[initialize]` block of your config.
<ide>
<ide> ### Using Lexeme Tables
<ide>
<del>To use tables like `lexeme_prob` when training a model from scratch, you need
<del>to add an entry to the `initialize` block in your config. Here's what that
<del>looks like for the existing trained pipelines:
<add>To use tables like `lexeme_prob` when training a model from scratch, you need to
<add>add an entry to the `initialize` block in your config. Here's what that looks
<add>like for the existing trained pipelines:
<ide>
<ide> ```ini
<ide> [initialize.lookups] | 9 |
Ruby | Ruby | fix bulk change_table with change_null and default | fbb6511f399885035ad67e416dd8802b8b041b6d | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def bulk_change_table(table_name, operations)
<ide>
<ide> if respond_to?(method, true)
<ide> sqls, procs = Array(send(method, table, *arguments)).partition { |v| v.is_a?(String) }
<del> sql_fragments << sqls
<add> sql_fragments.concat(sqls)
<ide> non_combinable_operations.concat(procs)
<ide> else
<ide> execute "ALTER TABLE #{quote_table_name(table_name)} #{sql_fragments.join(", ")}" unless sql_fragments.empty?
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
<ide> def change_column_null(table_name, column_name, null, default = nil) # :nodoc:
<ide> column = column_for(table_name, column_name)
<ide> execute "UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote_default_expression(default, column)} WHERE #{quote_column_name(column_name)} IS NULL" if column
<ide> end
<del> execute "ALTER TABLE #{quote_table_name(table_name)} #{change_column_null_for_alter(table_name, column_name, null, default)}"
<add> execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL"
<ide> end
<ide>
<ide> # Adds comment for given table column or drops it if +comment+ is a +nil+
<ide> def change_column_default_for_alter(table_name, column_name, default_or_changes)
<ide> end
<ide>
<ide> def change_column_null_for_alter(table_name, column_name, null, default = nil)
<del> "ALTER COLUMN #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL"
<add> if default.nil?
<add> "ALTER COLUMN #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL"
<add> else
<add> Proc.new { change_column_null(table_name, column_name, null, default) }
<add> end
<ide> end
<ide>
<ide> def add_index_opclass(quoted_columns, **options)
<ide><path>activerecord/test/cases/migration_test.rb
<ide> def test_changing_columns
<ide> assert_equal "This is a comment", column(:birthdate).comment
<ide> end
<ide>
<add> def test_changing_column_null_with_default
<add> with_bulk_change_table do |t|
<add> t.string :name
<add> t.integer :age
<add> t.date :birthdate
<add> end
<add>
<add> assert_not column(:name).default
<add> assert_equal :date, column(:birthdate).type
<add>
<add> classname = ActiveRecord::Base.connection.class.name[/[^:]*$/]
<add> expected_query_count = {
<add> "Mysql2Adapter" => 7, # four queries to retrieve schema info, one for bulk change, one for UPDATE, one for NOT NULL
<add> "PostgreSQLAdapter" => 5, # two queries for columns, one for bulk change, one for UPDATE, one for NOT NULL
<add> }.fetch(classname) {
<add> raise "need an expected query count for #{classname}"
<add> }
<add>
<add> assert_queries(expected_query_count, ignore_none: true) do
<add> with_bulk_change_table do |t|
<add> t.change :name, :string, default: "NONAME"
<add> t.change :birthdate, :datetime
<add> t.change_null :age, false, 0
<add> end
<add> end
<add>
<add> assert_equal "NONAME", column(:name).default
<add> assert_equal :datetime, column(:birthdate).type
<add> assert_equal false, column(:age).null
<add> end
<add>
<ide> if supports_text_column_with_default?
<ide> def test_default_functions_on_columns
<ide> with_bulk_change_table do |t| | 3 |
PHP | PHP | allow returning array when routing mail | ab9686ae58f1e89bae4e31fcb70bacc0ab546eb6 | <ide><path>src/Illuminate/Notifications/Channels/MailChannel.php
<ide> public function send($notifiable, Notification $notification)
<ide> $message = $notification->toMail($notifiable);
<ide>
<ide> $this->mailer->send($message->view, $message->toArray(), function ($m) use ($notifiable, $notification, $message) {
<del> $m->to($notifiable->routeNotificationFor('mail'));
<add> $recipients = $notifiable->routeNotificationFor('mail');
<add>
<add> if (is_array($recipients)) {
<add> $m->bcc($recipients);
<add> } else {
<add> $m->to($recipients);
<add> }
<ide>
<ide> $m->subject($message->subject ?: Str::title(
<ide> Str::snake(class_basename($notification), ' ') | 1 |
Python | Python | fix infinite recursion in spacy.info | 07199c3e8b1f7f91c41e7d19f364c902d3e9590b | <ide><path>spacy/__init__.py
<ide> def load(name, **overrides):
<ide> overrides['path'] = model_path
<ide>
<ide> return cls(**overrides)
<del>
<del>
<del>def info(name, markdown):
<del> info(name, markdown) | 1 |
Python | Python | remove forgotten print | 2d1a9997d100f208207f70231890f1bfcf8e434b | <ide><path>libcloud/compute/drivers/packet.py
<ide> def list_images(self):
<ide>
<ide> def list_sizes(self):
<ide> data = self.connection.request('/plans').object['plans']
<del> print data
<ide> return [self._to_size(size) for size in data if
<ide> size.get('line') == 'baremetal']
<ide> | 1 |
Javascript | Javascript | add some basic examples | 89089f5546555d41fcc37c2640aa1edbcdf5e7ee | <ide><path>examples/basic-css/pages/index.js
<add>import React from 'react'
<add>import { css, StyleSheet } from 'next/css'
<add>
<add>export default () => (
<add> <div className={css(styles.main)}>
<add> <p>Hello World</p>
<add> </div>
<add>)
<add>
<add>const styles = StyleSheet.create({
<add> main: {
<add> font: '15px Helvetica, Arial, sans-serif',
<add> background: '#eee',
<add> padding: '100px',
<add> textAlign: 'center',
<add> transition: '100ms ease-in background',
<add> ':hover': {
<add> background: '#ccc'
<add> }
<add> }
<add>})
<ide><path>examples/head-elements/pages/index.js
<add>import React from 'react'
<add>import Head from 'next/head'
<add>
<add>export default () => (
<add> <div>
<add> <Head>
<add> <title>This page has a title 🤔</title>
<add> <meta charSet="utf-8" />
<add> <meta name="viewport" content="initial-scale=1.0, width=device-width" />
<add> </Head>
<add>
<add> <h1>This page has a title 🤔</h1>
<add> </div>
<add>)
<ide><path>examples/hello-world/pages/about.js
<add>import React from 'react'
<add>export default () => (
<add> <div>About us</div>
<add>)
<ide><path>examples/hello-world/pages/index.js
<add>import React from 'react'
<add>import Link from 'next/link'
<add>export default () => (
<add> <div>Hello World. <Link href="/about">About</Link></div>
<add>)
<ide><path>examples/nested-components/components/paragraph.js
<add>import React from 'react'
<add>import { css, StyleSheet } from 'next/css'
<add>
<add>export default ({ children }) => (
<add> <p className={css(styles.main)}>{children}</p>
<add>)
<add>
<add>const styles = StyleSheet.create({
<add> main: {
<add> font: '13px Helvetica, Arial',
<add> margin: '10px 0'
<add> }
<add>})
<ide><path>examples/nested-components/components/post.js
<add>import React from 'react'
<add>import { css, StyleSheet } from 'next/css'
<add>
<add>export default ({ title, children }) => (
<add> <div className={css(styles.main)}>
<add> <h1 className={css(styles.title)}>{ title }</h1>
<add> { children }
<add> </div>
<add>)
<add>
<add>const styles = StyleSheet.create({
<add> main: {
<add> font: '15px Helvetica, Arial',
<add> border: '1px solid #eee',
<add> padding: '0 10px'
<add> },
<add>
<add> title: {
<add> fontSize: '16px',
<add> fontWeight: 'bold',
<add> margin: '10px 0'
<add> }
<add>})
<ide><path>examples/nested-components/pages/index.js
<add>import React from 'react'
<add>import P from '../components/paragraph'
<add>import Post from '../components/post'
<add>import { css, StyleSheet } from 'next/css'
<add>
<add>export default () => (
<add> <div className={css(styles.main)}>
<add> <Post title="My first blog post">
<add> <P>Hello there</P>
<add> <P>This is an example of a componentized blog post</P>
<add> </Post>
<add>
<add> <Hr />
<add>
<add> <Post title="My second blog post">
<add> <P>Hello there</P>
<add> <P>This is another example.</P>
<add> <P>Wa-hoo!</P>
<add> </Post>
<add>
<add> <Hr />
<add>
<add> <Post title="The final blog post">
<add> <P>C'est fin</P>
<add> </Post>
<add> </div>
<add>)
<add>
<add>const Hr = () => <hr className={css(styles.hr)} />
<add>
<add>const styles = StyleSheet.create({
<add> main: {
<add> margin: 'auto',
<add> maxWidth: '420px',
<add> padding: '10px'
<add> },
<add>
<add> hr: {
<add> width: '100px',
<add> borderWidth: 0,
<add> margin: '20px auto',
<add> textAlign: 'center',
<add> ':before': {
<add> content: '"***"',
<add> color: '#ccc'
<add> }
<add> }
<add>}) | 7 |
Go | Go | suppress false positive for g404 (gosec) | 561a010161d20fa3367b6b7e9efefe04161c1291 | <ide><path>libnetwork/networkdb/cluster.go
<ide> func randomOffset(n int) int {
<ide> return 0
<ide> }
<ide>
<del> val, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
<add> val, err := rand.Int(rand.Reader, big.NewInt(int64(n))) // #nosec G404 -- False positive; see https://github.com/securego/gosec/issues/862
<ide> if err != nil {
<ide> logrus.Errorf("Failed to get a random offset: %v", err)
<ide> return 0 | 1 |
Text | Text | fix typos in render targets article | ea3e339568061152db716b14582be519988842c0 | <ide><path>threejs/lessons/threejs-rendertargets.md
<ide> After you render to it you can use that texture like any other texture.
<ide>
<ide> Let's make a simple example. We'll start with an example from [the article on responsiveness](threejs-responsive.html).
<ide>
<del>Rendering to a render target just almost exactly the same as normal rendering. First we create a `WebGLRenderTarget`.
<add>Rendering to a render target is almost exactly the same as normal rendering. First we create a `WebGLRenderTarget`.
<ide>
<ide> ```js
<ide> const rtWidth = 512;
<ide> function makeInstance(geometry, color, x) {
<ide> ];
<ide> ```
<ide>
<del>The `Scene` and `Camera` from previous article are still there. We'll use them to render to the canvas.
<add>The `Scene` and `Camera` from the previous article are still there. We'll use them to render to the canvas.
<ide> We just need to add stuff to render.
<ide>
<ide> Let's add a cube that uses the render target's texture.
<ide> Render target are used for all kinds of things. Shadows use a render target. [Pi
<ide>
<ide> A few notes about using `WebGLRenderTarget`.
<ide>
<del>* By default `WebGLRenderTarget` creates 2 textures. A color texture and a depth/stencil texture. If you don't need the depth or stencil textures you can request it not create them by passing in options. Example:
<add>* By default `WebGLRenderTarget` creates 2 textures. A color texture and a depth/stencil texture. If you don't need the depth or stencil textures you can request to not create them by passing in options. Example:
<ide>
<ide> const rt = new THREE.WebGLRenderTarget(width, height, {
<ide> depthBuffer: false,
<ide> A few notes about using `WebGLRenderTarget`.
<ide>
<ide> function render(time) {
<ide> time *= 0.001;
<del>
<add>
<ide> if (resizeRendererToDisplaySize(renderer)) {
<ide> const canvas = renderer.domElement;
<ide> camera.aspect = canvas.clientWidth / canvas.clientHeight; | 1 |
Ruby | Ruby | fix action mailer tests after old mapper removal | b7bfeaa9fc7eaf315ce8eaae129fd0d02c9d09d0 | <ide><path>actionmailer/test/url_test.rb
<ide> def teardown
<ide> def test_signed_up_with_url
<ide> UrlTestMailer.delivery_method = :test
<ide>
<del> assert_deprecated do
<del> AppRoutes.draw do |map|
<del> map.connect ':controller/:action/:id'
<del> map.welcome 'welcome', :controller=>"foo", :action=>"bar"
<del> end
<add> AppRoutes.draw do
<add> match ':controller(/:action(/:id))'
<add> match '/welcome' => "foo#bar", :as => "welcome"
<ide> end
<ide>
<ide> expected = new_mail | 1 |
Java | Java | fix handling of protected visibility | 9820e3341d8691eddcadc0adc33e2a90bde1b37e | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/InstanceSupplierCodeGenerator.java
<ide> private CodeBlock generateCodeForConstructor(RegisteredBean registeredBean,
<ide> .getUserClass(constructor.getDeclaringClass());
<ide> boolean dependsOnBean = ClassUtils.isInnerClass(declaringClass);
<ide> Visibility accessVisibility = getAccessVisibility(registeredBean, constructor);
<del> if (accessVisibility == Visibility.PUBLIC
<del> || accessVisibility == Visibility.PACKAGE_PRIVATE) {
<add> if (accessVisibility != Visibility.PRIVATE) {
<ide> return generateCodeForAccessibleConstructor(beanName, beanClass, constructor,
<ide> dependsOnBean, declaringClass);
<ide> }
<ide> private CodeBlock generateCodeForFactoryMethod(RegisteredBean registeredBean,
<ide> .getUserClass(factoryMethod.getDeclaringClass());
<ide> boolean dependsOnBean = !Modifier.isStatic(factoryMethod.getModifiers());
<ide> Visibility accessVisibility = getAccessVisibility(registeredBean, factoryMethod);
<del> if (accessVisibility == Visibility.PUBLIC
<del> || accessVisibility == Visibility.PACKAGE_PRIVATE) {
<add> if (accessVisibility != Visibility.PRIVATE) {
<ide> return generateCodeForAccessibleFactoryMethod(beanName, beanClass, factoryMethod,
<ide> declaringClass, dependsOnBean);
<ide> } | 1 |
Javascript | Javascript | add test for issue | c486d7a87f6015d7aac9ce59463f1a9927043ef8 | <ide><path>packages/ember-metal/tests/computed_test.js
<ide> import {
<ide> set,
<ide> isWatching,
<ide> addObserver,
<add> notifyPropertyChange,
<ide> } from '..';
<ide> import { meta as metaFor } from 'ember-meta';
<ide> import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
<ide> moduleFor(
<ide> assert.equal(count, 1, 'should have invoked computed property');
<ide> }
<ide>
<add> ['@test `notifyPropertyChange` works for a computed property not setup using Ember.defineProperty #GH16427'](
<add> assert
<add> ) {
<add> let obj = {
<add> a: 50,
<add> b: computed(function() {
<add> return this.a / 5;
<add> }),
<add> };
<add>
<add> expectDeprecation(function() {
<add> assert.equal(get(obj, 'b'), 10);
<add> });
<add>
<add> obj.a = 10;
<add> notifyPropertyChange(obj, 'b');
<add>
<add> assert.equal(get(obj, 'b'), 2);
<add> }
<add>
<ide> ['@test defining computed property should invoke property on get'](assert) {
<ide> let obj = {};
<ide> let count = 0; | 1 |
Ruby | Ruby | use string for arguments in server test | d0bb649cbf415093dd1cc3f08b7b746dab5ad32f | <ide><path>railties/test/commands/server_test.rb
<ide> def test_argument_precedence_over_environment_variable
<ide> end
<ide>
<ide> def test_records_user_supplied_options
<del> server_options = parse_arguments(["-p", 3001])
<add> server_options = parse_arguments(["-p", "3001"])
<ide> assert_equal [:Port], server_options[:user_supplied_options]
<ide>
<del> server_options = parse_arguments(["--port", 3001])
<add> server_options = parse_arguments(["--port", "3001"])
<ide> assert_equal [:Port], server_options[:user_supplied_options]
<ide>
<ide> server_options = parse_arguments(["-p3001", "-C", "--binding", "127.0.0.1"]) | 1 |
Javascript | Javascript | remove string literal arg from assertion | cc58e5546caa07b36c78f8826fd73493a82c397c | <ide><path>test/parallel/test-fs-readfile.js
<ide> for (const e of fileInfo) {
<ide> fs.readFile(e.name, common.mustCall((err, buf) => {
<ide> console.log(`Validating readFile on file ${e.name} of length ${e.len}`);
<ide> assert.ifError(err);
<del> assert.deepStrictEqual(buf, e.contents, 'Incorrect file contents');
<add> assert.deepStrictEqual(buf, e.contents);
<ide> }));
<ide> } | 1 |
Javascript | Javascript | change mergemap -> map in redux-observable example | bc185878e8afae7de6598b5b7538170756143ec1 | <ide><path>examples/with-redux-observable/redux/epics.js
<ide> import { interval } from 'rxjs/observable/interval'
<ide> import { of } from 'rxjs/observable/of'
<del>import { takeUntil, mergeMap, catchError } from 'rxjs/operators'
<add>import { takeUntil, mergeMap, catchError, map } from 'rxjs/operators'
<ide> import { combineEpics, ofType } from 'redux-observable'
<ide> import ajax from 'universal-rx-request' // because standard AjaxObservable only works in browser
<ide>
<ide> export const fetchUserEpic = (action$, store) =>
<ide> mergeMap(action => {
<ide> return interval(3000).pipe(
<ide> mergeMap(x =>
<del> of(
<del> actions.fetchCharacter({
<del> isServer: store.getState().isServer
<del> })
<del> )
<add> actions.fetchCharacter({
<add> isServer: store.getState().isServer
<add> })
<ide> ),
<ide> takeUntil(action$.ofType(types.STOP_FETCHING_CHARACTERS))
<ide> )
<ide> export const fetchCharacterEpic = (action$, store) =>
<ide> ajax({
<ide> url: `https://swapi.co/api/people/${store.getState().nextCharacterId}`
<ide> }).pipe(
<del> mergeMap(response =>
<del> of(
<del> actions.fetchCharacterSuccess(
<del> response.body,
<del> store.getState().isServer
<del> )
<add> map(response =>
<add> actions.fetchCharacterSuccess(
<add> response.body,
<add> store.getState().isServer
<ide> )
<ide> ),
<ide> catchError(error => | 1 |
Javascript | Javascript | add temporary build debugging | 86d45a5b9bd3c81b5b4f6ededebad065cb3f21d3 | <ide><path>src/package-transpilation-registry.js
<ide> class PackageTranspilationRegistry {
<ide> const packagePathWithSep = packagePath.endsWith(path.sep) ?
<ide> packagePath : packagePath + path.sep;
<ide> Object.keys(this.specByFilePath).forEach(filePath => {
<add> console.log('checking if ' + filePath + ' starts with ' + packagePathWithSep)
<ide> if (filePath.startsWith(packagePathWithSep)) {
<add> console.log(' >> REMOVING ' + filePath)
<ide> delete this.specByFilePath[filePath]
<ide> }
<ide> })
<ide> class PackageTranspilationRegistry {
<ide> getCachePath: (sourceCode, filePath) => {
<ide> const spec = this.getPackageTranspilerSpecForFilePath(filePath)
<ide> if (spec) {
<del> return this.getCachePath(sourceCode, filePath, spec)
<add> try {
<add> return this.getCachePath(sourceCode, filePath, spec)
<add> } catch (err) {
<add> console.log("ERROR!!!")
<add> console.log("The file being transpiled was " + filePath)
<add> console.log(spec)
<add> }
<ide> }
<ide>
<ide> return transpiler.getCachePath(sourceCode, filePath) | 1 |
Javascript | Javascript | add missing line break | 5be6f993aa64de4b7da4fd26dcd2cf5285bd6ed3 | <ide><path>src/ng/filter/filters.js
<ide> var ZERO_CHAR = '0';
<ide> <div ng-controller="ExampleController">
<ide> <input type="number" ng-model="amount" aria-label="amount"> <br>
<ide> default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
<del> custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
<add> custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
<ide> no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
<ide> </div>
<ide> </file> | 1 |
Java | Java | fix typo in defaultparthttpmessagereader | 3a35d79c72b1152313aec5d499f678fb57a96099 | <ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java
<ide> public void setStreaming(boolean streaming) {
<ide> * Defaults to UTF-8 as per RFC 7578.
<ide> * @param headersCharset the charset to use for decoding headers
<ide> * @since 5.3.6
<del> * @see <a href="https://tools.ietf.org/html/rfc7578#section-5.1">RFC-7578 Section 5.2</a>
<add> * @see <a href="https://tools.ietf.org/html/rfc7578#section-5.1">RFC-7578 Section 5.1</a>
<ide> */
<ide> public void setHeadersCharset(Charset headersCharset) {
<ide> Assert.notNull(headersCharset, "HeadersCharset must not be null"); | 1 |
Python | Python | use testcase instead of numpytestcase | 59e1ee936c730b19a4c4016172658695fb197ada | <ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_simple(self):
<ide> assert(all(unique(x) == [1+1j, 1+10j, 5+6j, 10]))
<ide>
<ide>
<del>class TestPiecewise(NumpyTestCase):
<add>class TestPiecewise(TestCase):
<ide> def check_simple(self):
<ide> # Condition is single bool list
<ide> x = piecewise([0, 0], [True, False], [1]) | 1 |
Text | Text | provide more context on techinical values | 6d3775e29117d8ddf6879ed124dea7839a613986 | <ide><path>doc/guides/technical-values.md
<ide> The project uses these technical values to establish priorities and guide
<ide> collaboration.
<ide>
<add>These are the shared values as of this writing and will
<add>evolve. We hope they are useful to people new
<add>to the project in order to better understand which contributions
<add>will be aligned with the current direction and as thinking
<add>points when trading off between conflicting goals.
<add>
<add>The factors influencing every discussion/decision are
<add>different and priority 1 does not always trump priority 2
<add>and so on.
<add>
<ide> ## Values and priority level
<ide>
<ide> * Priority 1 - Developer experience | 1 |
Text | Text | add overlay2 description to overlayfs-driver.md | 8625adbd67f08f2da7816d0ce9d2e9267f7a4f6b | <ide><path>docs/userguide/storagedriver/overlayfs-driver.md
<ide> using it in production Docker environments.
<ide> Docker's `overlay` storage driver leverages several OverlayFS features to build
<ide> and manage the on-disk structures of images and containers.
<ide>
<add>Since version 1.12, Docker also provides `overlay2` storage driver which is much
<add>more efficient than `overlay` in terms of inode utilization. The `overlay2`
<add>driver is only compatible with Linux kernel 4.0 and later.
<add>
<add>For comparison between `overlay` vs `overlay2`, please also refer to [Select a
<add>storage driver](selectadriver.md#overlay-vs-overlay2).
<add>
<ide> >**Note**: Since it was merged into the mainline kernel, the OverlayFS *kernel
<ide> >module* was renamed from "overlayfs" to "overlay". As a result you may see the
<ide> > two terms used interchangeably in some documentation. However, this document
<del>> uses "OverlayFS" to refer to the overall filesystem, and `overlay` to refer
<del>> to Docker's storage-driver.
<add>> uses "OverlayFS" to refer to the overall filesystem, and `overlay`/`overlay2`
<add>> to refer to Docker's storage-drivers.
<ide>
<del>## Image layering and sharing with OverlayFS
<add>## Image layering and sharing with OverlayFS (`overlay`)
<ide>
<ide> OverlayFS takes two directories on a single Linux host, layers one on top of
<ide> the other, and provides a single unified view. These directories are often
<ide> Notice how the image layer and container layer can contain the same files. When
<ide> obscure the existence of the same files in the image layer ("lowerdir"). The
<ide> container mount ("merged") presents the unified view.
<ide>
<del>OverlayFS only works with two layers. This means that multi-layered images
<del>cannot be implemented as multiple OverlayFS layers. Instead, each image layer
<del>is implemented as its own directory under `/var/lib/docker/overlay`.
<del>Hard links are then used as a space-efficient way to reference data shared with
<del> lower layers. As of Docker 1.10, image layer IDs no longer correspond to
<del>directory names in `/var/lib/docker/`
<add>The `overlay` driver only works with two layers. This means that multi-layered
<add>images cannot be implemented as multiple OverlayFS layers. Instead, each image
<add>layer is implemented as its own directory under `/var/lib/docker/overlay`. Hard
<add>links are then used as a space-efficient way to reference data shared with lower
<add>layers. As of Docker 1.10, image layer IDs no longer correspond to directory
<add>names in `/var/lib/docker/`
<ide>
<ide> To create a container, the `overlay` driver combines the directory representing
<ide> the image's top layer plus a new directory for the container. The image's top
<ide> layer is the "lowerdir" in the overlay and read-only. The new directory for the
<ide> container is the "upperdir" and is writable.
<ide>
<del>## Example: Image and container on-disk constructs
<add>### Example: Image and container on-disk constructs (`overlay`)
<ide>
<ide> The following `docker pull` command shows a Docker host with downloading a
<del>Docker image comprising four layers.
<add>Docker image comprising five layers.
<ide>
<ide> $ sudo docker pull ubuntu
<ide> Using default tag: latest
<ide> latest: Pulling from library/ubuntu
<del> 8387d9ff0016: Pull complete
<del> 3b52deaaf0ed: Pull complete
<del> 4bd501fad6de: Pull complete
<add>
<add> 5ba4f30e5bea: Pull complete
<add> 9d7d19c9dc56: Pull complete
<add> ac6ad7efd0f9: Pull complete
<add> e7491a747824: Pull complete
<ide> a3ed95caeb02: Pull complete
<del> Digest: sha256:457b05828bdb5dcc044d93d042863fba3f2158ae249a6db5ae3934307c757c54
<add> Digest: sha256:46fb5d001b88ad904c5c732b086b596b92cfb4a4840a3abd0e35dbb6870585e4
<ide> Status: Downloaded newer image for ubuntu:latest
<ide>
<ide> Each image layer has it's own directory under `/var/lib/docker/overlay/`. This
<ide> is where the contents of each image layer are stored.
<ide>
<del>The output of the command below shows the four directories that store the
<add>The output of the command below shows the five directories that store the
<ide> contents of each image layer just pulled. However, as can be seen, the image
<ide> layer IDs do not match the directory names in `/var/lib/docker/overlay`. This
<ide> is normal behavior in Docker 1.10 and later.
<ide>
<ide> $ ls -l /var/lib/docker/overlay/
<del> total 24
<del> drwx------ 3 root root 4096 Oct 28 11:02 1d073211c498fd5022699b46a936b4e4bdacb04f637ad64d3475f558783f5c3e
<del> drwx------ 3 root root 4096 Oct 28 11:02 5a4526e952f0aa24f3fcc1b6971f7744eb5465d572a48d47c492cb6bbf9cbcda
<del> drwx------ 5 root root 4096 Oct 28 11:06 99fcaefe76ef1aa4077b90a413af57fd17d19dce4e50d7964a273aae67055235
<del> drwx------ 3 root root 4096 Oct 28 11:01 c63fb41c2213f511f12f294dd729b9903a64d88f098c20d2350905ac1fdbcbba
<add> total 20
<add> drwx------ 3 root root 4096 Jun 20 16:11 38f3ed2eac129654acef11c32670b534670c3a06e483fce313d72e3e0a15baa8
<add> drwx------ 3 root root 4096 Jun 20 16:11 55f1e14c361b90570df46371b20ce6d480c434981cbda5fd68c6ff61aa0a5358
<add> drwx------ 3 root root 4096 Jun 20 16:11 824c8a961a4f5e8fe4f4243dab57c5be798e7fd195f6d88ab06aea92ba931654
<add> drwx------ 3 root root 4096 Jun 20 16:11 ad0fe55125ebf599da124da175174a4b8c1878afe6907bf7c78570341f308461
<add> drwx------ 3 root root 4096 Jun 20 16:11 edab9b5e5bf73f2997524eebeac1de4cf9c8b904fa8ad3ec43b3504196aa3801
<ide>
<ide> The image layer directories contain the files unique to that layer as well as
<ide> hard links to the data that is shared with lower layers. This allows for
<ide> efficient use of disk space.
<ide>
<add> $ ls -i /var/lib/docker/overlay/38f3ed2eac129654acef11c32670b534670c3a06e483fce313d72e3e0a15baa8/root/bin/ls
<add> 19793696 /var/lib/docker/overlay/38f3ed2eac129654acef11c32670b534670c3a06e483fce313d72e3e0a15baa8/root/bin/ls
<add> $ ls -i /var/lib/docker/overlay/55f1e14c361b90570df46371b20ce6d480c434981cbda5fd68c6ff61aa0a5358/root/bin/ls
<add> 19793696 /var/lib/docker/overlay/55f1e14c361b90570df46371b20ce6d480c434981cbda5fd68c6ff61aa0a5358/root/bin/ls
<add>
<ide> Containers also exist on-disk in the Docker host's filesystem under
<ide> `/var/lib/docker/overlay/`. If you inspect the directory relating to a running
<ide> container using the `ls -l` command, you find the following file and
<ide> directories.
<ide>
<ide> $ ls -l /var/lib/docker/overlay/<directory-of-running-container>
<ide> total 16
<del> -rw-r--r-- 1 root root 64 Oct 28 11:06 lower-id
<del> drwxr-xr-x 1 root root 4096 Oct 28 11:06 merged
<del> drwxr-xr-x 4 root root 4096 Oct 28 11:06 upper
<del> drwx------ 3 root root 4096 Oct 28 11:06 work
<add> -rw-r--r-- 1 root root 64 Jun 20 16:39 lower-id
<add> drwxr-xr-x 1 root root 4096 Jun 20 16:39 merged
<add> drwxr-xr-x 4 root root 4096 Jun 20 16:39 upper
<add> drwx------ 3 root root 4096 Jun 20 16:39 work
<ide>
<ide> These four filesystem objects are all artifacts of OverlayFS. The "lower-id"
<ide> file contains the ID of the top layer of the image the container is based on.
<ide> This is used by OverlayFS as the "lowerdir".
<ide>
<del> $ cat /var/lib/docker/overlay/73de7176c223a6c82fd46c48c5f152f2c8a7e49ecb795a7197c3bb795c4d879e/lower-id
<del> 1d073211c498fd5022699b46a936b4e4bdacb04f637ad64d3475f558783f5c3e
<add> $ cat /var/lib/docker/overlay/ec444863a55a9f1ca2df72223d459c5d940a721b2288ff86a3f27be28b53be6c/lower-id
<add> 55f1e14c361b90570df46371b20ce6d480c434981cbda5fd68c6ff61aa0a5358
<ide>
<ide> The "upper" directory is the containers read-write layer. Any changes made to
<ide> the container are written to this directory.
<ide> You can verify all of these constructs from the output of the `mount` command.
<ide> (Ellipses and line breaks are used in the output below to enhance readability.)
<ide>
<ide> $ mount | grep overlay
<del> overlay on /var/lib/docker/overlay/73de7176c223.../merged
<del> type overlay (rw,relatime,lowerdir=/var/lib/docker/overlay/1d073211c498.../root,
<del> upperdir=/var/lib/docker/overlay/73de7176c223.../upper,
<del> workdir=/var/lib/docker/overlay/73de7176c223.../work)
<add> overlay on /var/lib/docker/overlay/ec444863a55a.../merged
<add> type overlay (rw,relatime,lowerdir=/var/lib/docker/overlay/55f1e14c361b.../root,
<add> upperdir=/var/lib/docker/overlay/ec444863a55a.../upper,
<add> workdir=/var/lib/docker/overlay/ec444863a55a.../work)
<ide>
<ide> The output reflects that the overlay is mounted as read-write ("rw").
<ide>
<add>
<add>## Image layering and sharing with OverlayFS (`overlay2`)
<add>
<add>While the `overlay` driver only works with a single lower OverlayFS layer and
<add>hence requires hard links for implementation of multi-layered images, the
<add>`overlay2` driver natively supports multiple lower OverlayFS layers (up to 128).
<add>
<add>Hence the `overlay2` driver offers better performance for layer-related docker commands (e.g. `docker build` and `docker commit`), and consumes fewer inodes than the `overlay` driver.
<add>
<add>### Example: Image and container on-disk constructs (`overlay2`)
<add>
<add>After downloading a five-layer image using `docker pull ubuntu`, you can see
<add>six directories under `/var/lib/docker/overlay2`.
<add>
<add> $ ls -l /var/lib/docker/overlay2
<add> total 24
<add> drwx------ 5 root root 4096 Jun 20 07:36 223c2864175491657d238e2664251df13b63adb8d050924fd1bfcdb278b866f7
<add> drwx------ 3 root root 4096 Jun 20 07:36 3a36935c9df35472229c57f4a27105a136f5e4dbef0f87905b2e506e494e348b
<add> drwx------ 5 root root 4096 Jun 20 07:36 4e9fa83caff3e8f4cc83693fa407a4a9fac9573deaf481506c102d484dd1e6a1
<add> drwx------ 5 root root 4096 Jun 20 07:36 e8876a226237217ec61c4baf238a32992291d059fdac95ed6303bdff3f59cff5
<add> drwx------ 5 root root 4096 Jun 20 07:36 eca1e4e1694283e001f200a667bb3cb40853cf2d1b12c29feda7422fed78afed
<add> drwx------ 2 root root 4096 Jun 20 07:36 l
<add>
<add>The "l" directory contains shortened layer identifiers as symbolic links. These
<add>shortened identifiers are used for avoid hitting the page size limitation on
<add>mount arguments.
<add>
<add> $ ls -l /var/lib/docker/overlay2/l
<add> total 20
<add> lrwxrwxrwx 1 root root 72 Jun 20 07:36 6Y5IM2XC7TSNIJZZFLJCS6I4I4 -> ../3a36935c9df35472229c57f4a27105a136f5e4dbef0f87905b2e506e494e348b/diff
<add> lrwxrwxrwx 1 root root 72 Jun 20 07:36 B3WWEFKBG3PLLV737KZFIASSW7 -> ../4e9fa83caff3e8f4cc83693fa407a4a9fac9573deaf481506c102d484dd1e6a1/diff
<add> lrwxrwxrwx 1 root root 72 Jun 20 07:36 JEYMODZYFCZFYSDABYXD5MF6YO -> ../eca1e4e1694283e001f200a667bb3cb40853cf2d1b12c29feda7422fed78afed/diff
<add> lrwxrwxrwx 1 root root 72 Jun 20 07:36 NFYKDW6APBCCUCTOUSYDH4DXAT -> ../223c2864175491657d238e2664251df13b63adb8d050924fd1bfcdb278b866f7/diff
<add> lrwxrwxrwx 1 root root 72 Jun 20 07:36 UL2MW33MSE3Q5VYIKBRN4ZAGQP -> ../e8876a226237217ec61c4baf238a32992291d059fdac95ed6303bdff3f59cff5/diff
<add>
<add>The lowerest layer contains the "link" file which contains the name of the shortened
<add>identifier, and the "diff" directory which contains the contents.
<add>
<add> $ /var/lib/docker/overlay2/3a36935c9df35472229c57f4a27105a136f5e4dbef0f87905b2e506e494e348b/
<add> diff link
<add> $ cat /var/lib/docker/overlay2/3a36935c9df35472229c57f4a27105a136f5e4dbef0f87905b2e506e494e348b/link
<add> 6Y5IM2XC7TSNIJZZFLJCS6I4I4
<add> $ ls /var/lib/docker/overlay2/3a36935c9df35472229c57f4a27105a136f5e4dbef0f87905b2e506e494e348b/diff
<add> bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
<add>
<add>The second layer contains the "lower" file for denoting the layer composition,
<add>and the "diff" directory for the layer contents. It also contains the "merged" and
<add>the "work" directories.
<add>
<add> $ ls /var/lib/docker/overlay2/223c2864175491657d238e2664251df13b63adb8d050924fd1bfcdb278b866f7
<add> diff link lower merged work
<add> $ cat /var/lib/docker/overlay2/223c2864175491657d238e2664251df13b63adb8d050924fd1bfcdb278b866f7/lower
<add> l/6Y5IM2XC7TSNIJZZFLJCS6I4I4
<add> $ ls /var/lib/docker/overlay2/223c2864175491657d238e2664251df13b63adb8d050924fd1bfcdb278b866f7/diff/
<add> etc sbin usr var
<add>
<add>A directory for running container have similar files and directories as well.
<add>Note that the lower list is separated by ':', and ordered from highest layer to lower.
<add>
<add> $ ls -l /var/lib/docker/overlay/<directory-of-running-container>
<add> $ cat /var/lib/docker/overlay/<directory-of-running-container>/lower
<add> l/DJA75GUWHWG7EWICFYX54FIOVT:l/B3WWEFKBG3PLLV737KZFIASSW7:l/JEYMODZYFCZFYSDABYXD5MF6YO:l/UL2MW33MSE3Q5VYIKBRN4ZAGQP:l/NFYKDW6APBCCUCTOUSYDH4DXAT:l/6Y5IM2XC7TSNIJZZFLJCS6I4I4
<add>
<add>The result of `mount` is as follows:
<add>
<add> $ mount | grep overlay
<add> overlay on /var/lib/docker/overlay2/9186877cdf386d0a3b016149cf30c208f326dca307529e646afce5b3f83f5304/merged
<add> type overlay (rw,relatime,
<add> lowerdir=l/DJA75GUWHWG7EWICFYX54FIOVT:l/B3WWEFKBG3PLLV737KZFIASSW7:l/JEYMODZYFCZFYSDABYXD5MF6YO:l/UL2MW33MSE3Q5VYIKBRN4ZAGQP:l/NFYKDW6APBCCUCTOUSYDH4DXAT:l/6Y5IM2XC7TSNIJZZFLJCS6I4I4,
<add> upperdir=9186877cdf386d0a3b016149cf30c208f326dca307529e646afce5b3f83f5304/diff,
<add> workdir=9186877cdf386d0a3b016149cf30c208f326dca307529e646afce5b3f83f5304/work)
<add>
<ide> ## Container reads and writes with overlay
<ide>
<ide> Consider three scenarios where a container opens a file for read access with
<ide> Consider some scenarios where files in a container are modified.
<ide>
<ide> - **Writing to a file for the first time**. The first time a container writes
<ide> to an existing file, that file does not exist in the container ("upperdir").
<del>The `overlay` driver performs a *copy_up* operation to copy the file from the
<del>image ("lowerdir") to the container ("upperdir"). The container then writes the
<del> changes to the new copy of the file in the container layer.
<add>The `overlay`/`overlay2` driver performs a *copy_up* operation to copy the file
<add>from the image ("lowerdir") to the container ("upperdir"). The container then
<add>writes the changes to the new copy of the file in the container layer.
<ide>
<ide> However, OverlayFS works at the file level not the block level. This means
<ide> that all OverlayFS copy-up operations copy entire files, even if the file is
<ide> file in the image layer ("lowerdir") is not deleted. However, the whiteout file
<ide> created in the "upperdir". This has the same effect as a whiteout file and
<ide> effectively masks the existence of the directory in the image's "lowerdir".
<ide>
<del>## Configure Docker with the overlay storage driver
<add>## Configure Docker with the `overlay`/`overlay2` storage driver
<ide>
<del>To configure Docker to use the overlay storage driver your Docker host must be
<add>To configure Docker to use the `overlay` storage driver your Docker host must be
<ide> running version 3.18 of the Linux kernel (preferably newer) with the overlay
<del>kernel module loaded. OverlayFS can operate on top of most supported Linux
<del>filesystems. However, ext4 is currently recommended for use in production
<del>environments.
<add>kernel module loaded. For the `overlay2` driver, the version of your kernel must
<add>be 4.0 or newer. OverlayFS can operate on top of most supported Linux filesystems.
<add>However, ext4 is currently recommended for use in production environments.
<ide>
<ide> The following procedure shows you how to configure your Docker host to use
<ide> OverlayFS. The procedure assumes that the Docker daemon is in a stopped state.
<ide> OverlayFS. The procedure assumes that the Docker daemon is in a stopped state.
<ide> $ lsmod | grep overlay
<ide> overlay
<ide>
<del>3. Start the Docker daemon with the `overlay` storage driver.
<add>3. Start the Docker daemon with the `overlay`/`overlay2` storage driver.
<ide>
<ide> $ dockerd --storage-driver=overlay &
<ide> [1] 29403
<ide> OverlayFS. The procedure assumes that the Docker daemon is in a stopped state.
<ide> <output truncated>
<ide>
<ide> Alternatively, you can force the Docker daemon to automatically start with
<del> the `overlay` driver by editing the Docker config file and adding the
<del> `--storage-driver=overlay` flag to the `DOCKER_OPTS` line. Once this option
<add> the `overlay`/`overlay2` driver by editing the Docker config file and adding
<add> the `--storage-driver=overlay` flag to the `DOCKER_OPTS` line. Once this option
<ide> is set you can start the daemon using normal startup scripts without having
<ide> to manually pass in the `--storage-driver` flag.
<ide>
<del>4. Verify that the daemon is using the `overlay` storage driver
<add>4. Verify that the daemon is using the `overlay`/`overlay2` storage driver
<ide>
<ide> $ docker info
<ide> Containers: 0
<ide> OverlayFS. The procedure assumes that the Docker daemon is in a stopped state.
<ide> `extfs`. Multiple backing filesystems are supported but `extfs` (ext4) is
<ide> recommended for production use cases.
<ide>
<del>Your Docker host is now using the `overlay` storage driver. If you run the
<del>`mount` command, you'll find Docker has automatically created the `overlay`
<del>mount with the required "lowerdir", "upperdir", "merged" and "workdir"
<add>Your Docker host is now using the `overlay`/`overlay2` storage driver. If you
<add>run the `mount` command, you'll find Docker has automatically created the
<add>`overlay` mount with the required "lowerdir", "upperdir", "merged" and "workdir"
<ide> constructs.
<ide>
<ide> ## OverlayFS and Docker Performance
<ide>
<del>As a general rule, the `overlay` driver should be fast. Almost certainly faster
<del> than `aufs` and `devicemapper`. In certain circumstances it may also be faster
<del> than `btrfs`. That said, there are a few things to be aware of relative to the
<del> performance of Docker using the `overlay` storage driver.
<add>As a general rule, the `overlay`/`overlay2` drivers should be fast. Almost
<add>certainly faster than `aufs` and `devicemapper`. In certain circumstances it may
<add>also be faster than `btrfs`. That said, there are a few things to be aware of
<add>relative to the performance of Docker using the `overlay`/`overlay2` storage
<add>drivers.
<ide>
<del>- **Page Caching**. OverlayFS supports page cache sharing. This means multiple
<del>containers accessing the same file can share a single page cache entry (or
<del>entries). This makes the `overlay` driver efficient with memory and a good
<del>option for PaaS and other high density use cases.
<add>- **Page Caching**. OverlayFS supports page cache sharing. This means multiple
<add>containers accessing the same file can share a single page cache entry (or
<add>entries). This makes the `overlay`/`overlay2` drivers efficient with memory and
<add>a good option for PaaS and other high density use cases.
<ide>
<ide> - **copy_up**. As with AUFS, OverlayFS has to perform copy-up operations any
<ide> time a container writes to a file for the first time. This can insert latency
<ide> possible to incur far larger latencies if searching through many AUFS layers.
<ide> - **RPMs and Yum**. OverlayFS only implements a subset of the POSIX standards.
<ide> This can result in certain OverlayFS operations breaking POSIX standards. One
<ide> such operation is the *copy-up* operation. Therefore, using `yum` inside of a
<del>container on a Docker host using the `overlay` storage driver is unlikely to
<del>work without implementing workarounds.
<add>container on a Docker host using the `overlay`/`overlay2` storage drivers is
<add>unlikely to work without implementing workarounds.
<ide>
<ide> - **Inode limits**. Use of the `overlay` storage driver can cause excessive
<ide> inode consumption. This is especially so as the number of images and containers
<ide> on the Docker host grows. A Docker host with a large number of images and lots
<del> of started and stopped containers can quickly run out of inodes.
<add> of started and stopped containers can quickly run out of inodes. The `overlay2`
<add> does not have such an issue.
<ide>
<ide> Unfortunately you can only specify the number of inodes in a filesystem at the
<ide> time of creation. For this reason, you may wish to consider putting | 1 |
Text | Text | add ruyadorno to collaborators | d36e832a32dfb0c0c49bf9e3dee93ff231c97eb0 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Ron Korving** <ron@ronkorving.nl>
<ide> * [rubys](https://github.com/rubys) -
<ide> **Sam Ruby** <rubys@intertwingly.net>
<add>* [ruyadorno](https://github.com/ruyadorno) -
<add>**Ruy Adorno** <ruyadorno@github.com> (he/him)
<ide> * [rvagg](https://github.com/rvagg) -
<ide> **Rod Vagg** <rod@vagg.org>
<ide> * [ryzokuken](https://github.com/ryzokuken) - | 1 |
PHP | PHP | remove options key in paginatorhelper tests | 0d39f2d97e3ef74a8479dcedf736bbebdcfcf73b | <ide><path>Cake/Test/TestCase/View/Helper/PaginatorHelperTest.php
<ide> <?php
<ide> /**
<del> * PaginatorHelperTest file
<del> *
<ide> * PHP 5
<ide> *
<ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.View.Helper
<ide> * @since CakePHP(tm) v 1.2.0.4206
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide> /**
<ide> * PaginatorHelperTest class
<ide> *
<del> * @package Cake.Test.Case.View.Helper
<ide> */
<ide> class PaginatorHelperTest extends TestCase {
<ide>
<ide> public function setUp() {
<ide> $this->Paginator->request->addParams(array(
<ide> 'paging' => array(
<ide> 'Article' => array(
<del> 'page' => 2,
<add> 'page' => 1,
<ide> 'current' => 9,
<ide> 'count' => 62,
<ide> 'prevPage' => false,
<ide> 'nextPage' => true,
<ide> 'pageCount' => 7,
<ide> 'order' => null,
<ide> 'limit' => 20,
<del> 'options' => array(
<del> 'page' => 1,
<del> 'conditions' => array()
<del> ),
<ide> )
<ide> )
<ide> ));
<ide> public function testSortLinks() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => true,
<ide> 'pageCount' => 7,
<del> 'options' => array(
<del> 'page' => 1,
<del> 'order' => array('date' => 'asc'),
<del> 'conditions' => array()
<del> ),
<add> 'sort' => 'date',
<add> 'direction' => 'asc',
<add> 'page' => 1,
<ide> )
<ide> );
<ide>
<ide> public function testSortLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['sort'] = 'title';
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'title';
<ide> $result = $this->Paginator->sort('title', array('asc' => 'ascending', 'desc' => 'descending'));
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index/param?sort=title&direction=desc', 'class' => 'asc'),
<ide> public function testSortLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
<del> $this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'desc';
<ide> $result = $this->Paginator->sort('title');
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index/param?sort=title&direction=asc', 'class' => 'desc'),
<ide> public function testSortLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<del> $this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<ide> $result = $this->Paginator->sort('title');
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index/param?sort=title&direction=desc', 'class' => 'asc'),
<ide> public function testSortLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
<del> $this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'desc';
<ide> $result = $this->Paginator->sort('title', 'Title', array('direction' => 'desc'));
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index/param?sort=title&direction=asc', 'class' => 'desc'),
<ide> public function testSortLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
<del> $this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'desc';
<ide> $result = $this->Paginator->sort('title', 'Title', array('direction' => 'asc'));
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index/param?sort=title&direction=asc', 'class' => 'desc'),
<ide> public function testSortLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<del> $this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'asc';
<ide> $result = $this->Paginator->sort('title', 'Title', array('direction' => 'asc'));
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index/param?sort=title&direction=desc', 'class' => 'asc'),
<ide> public function testSortLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<del> $this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<add>
<ide> $result = $this->Paginator->sort('title', 'Title', array('direction' => 'desc'));
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index/param?sort=title&direction=desc', 'class' => 'asc'),
<ide> public function testSortLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<del> $this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<add>
<ide> $result = $this->Paginator->sort('title', 'Title', array('direction' => 'desc', 'class' => 'foo'));
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index/param?sort=title&direction=desc', 'class' => 'foo asc'),
<ide> public function testSortLinkWithVirtualField() {
<ide> array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'form' => array(), 'url' => array('url' => 'accounts/')),
<ide> array('base' => '', 'here' => '/accounts/', 'webroot' => '/')
<ide> ));
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('full_name' => 'asc');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'full_name';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<ide>
<ide> $result = $this->Paginator->sort('Article.full_name');
<ide> $expected = array(
<ide> public function testSortLinkWithVirtualField() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('full_name' => 'desc');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'full_name';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'desc';
<ide> $result = $this->Paginator->sort('Article.full_name');
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index?sort=Article.full_name&direction=asc', 'class' => 'desc'),
<ide> public function testSortLinksUsingDotNotation() {
<ide> array('base' => '', 'here' => '/accounts/', 'webroot' => '/')
<ide> ));
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'desc';
<ide> $result = $this->Paginator->sort('Article.title');
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index?sort=Article.title&direction=asc', 'class' => 'desc'),
<ide> public function testSortLinksUsingDotNotation() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'desc';
<ide> $result = $this->Paginator->sort('Article.title', 'Title');
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index?sort=Article.title&direction=asc', 'class' => 'desc'),
<ide> public function testSortLinksUsingDotNotation() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<ide> $result = $this->Paginator->sort('Article.title', 'Title');
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index?sort=Article.title&direction=desc', 'class' => 'asc'),
<ide> public function testSortLinksUsingDotNotation() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Account.title' => 'asc');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Account.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<ide> $result = $this->Paginator->sort('title');
<ide> $expected = array(
<ide> 'a' => array('href' => '/accounts/index?sort=title&direction=asc'),
<ide> public function testSortKeyFallbackToParams() {
<ide> public function testSortDir() {
<ide> $result = $this->Paginator->sortDir();
<ide> $expected = 'asc';
<del>
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'desc';
<ide> $result = $this->Paginator->sortDir();
<del> $expected = 'desc';
<del>
<del> $this->assertEquals($expected, $result);
<del>
<del> unset($this->Paginator->request->params['paging']['Article']['options']);
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<del> $result = $this->Paginator->sortDir();
<del> $expected = 'asc';
<del>
<del> $this->assertEquals($expected, $result);
<del>
<del> unset($this->Paginator->request->params['paging']['Article']['options']);
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('title' => 'desc');
<del> $result = $this->Paginator->sortDir();
<del> $expected = 'desc';
<del>
<del> $this->assertEquals($expected, $result);
<add> $this->assertEquals('desc', $result);
<ide>
<del> unset($this->Paginator->request->params['paging']['Article']['options']);
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('title' => 'asc');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<ide> $result = $this->Paginator->sortDir();
<del> $expected = 'asc';
<del>
<del> $this->assertEquals($expected, $result);
<add> $this->assertEquals('asc', $result);
<ide>
<del> unset($this->Paginator->request->params['paging']['Article']['options']);
<del> $this->Paginator->request->params['paging']['Article']['options']['direction'] = 'asc';
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'desc';
<ide> $result = $this->Paginator->sortDir();
<del> $expected = 'asc';
<del>
<del> $this->assertEquals($expected, $result);
<add> $this->assertEquals('desc', $result);
<ide>
<del> unset($this->Paginator->request->params['paging']['Article']['options']);
<del> $this->Paginator->request->params['paging']['Article']['options']['direction'] = 'desc';
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<ide> $result = $this->Paginator->sortDir();
<del> $expected = 'desc';
<del>
<del> $this->assertEquals($expected, $result);
<add> $this->assertEquals('asc', $result);
<ide>
<del> unset($this->Paginator->request->params['paging']['Article']['options']);
<add> unset($this->Paginator->request->params['paging']['Article']['direction']);
<ide> $result = $this->Paginator->sortDir('Article', array('direction' => 'asc'));
<del> $expected = 'asc';
<del>
<del> $this->assertEquals($expected, $result);
<add> $this->assertEquals('asc', $result);
<ide>
<ide> $result = $this->Paginator->sortDir('Article', array('direction' => 'desc'));
<del> $expected = 'desc';
<del>
<del> $this->assertEquals($expected, $result);
<add> $this->assertEquals('desc', $result);
<ide>
<ide> $result = $this->Paginator->sortDir('Article', array('direction' => 'asc'));
<del> $expected = 'asc';
<del>
<del> $this->assertEquals($expected, $result);
<add> $this->assertEquals('asc', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testSortDir() {
<ide> * @return void
<ide> */
<ide> public function testSortDirFallbackToParams() {
<del> $this->Paginator->request->params['paging']['Article']['order'] = array(
<del> 'Article.body' => 'ASC'
<del> );
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.body';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<add>
<ide> $result = $this->Paginator->sortDir();
<ide> $this->assertEquals('asc', $result);
<ide>
<ide> $result = $this->Paginator->sortDir('Article');
<ide> $this->assertEquals('asc', $result);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['order'] = array(
<del> 'Article.body' => 'DESC'
<del> );
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.body';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'DESC';
<add>
<ide> $result = $this->Paginator->sortDir();
<ide> $this->assertEquals('desc', $result);
<ide>
<ide> public function testUrlGeneration() {
<ide> $result = $this->Paginator->url();
<ide> $this->assertEquals('/index', $result);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['page'] = 2;
<add> $this->Paginator->request->params['paging']['Article']['page'] = 2;
<ide> $result = $this->Paginator->url();
<ide> $this->assertEquals('/index?page=2', $result);
<ide>
<del> $options = array('order' => array('Article' => 'desc'));
<add> $options = array('sort' => 'Article', 'direction' => 'desc');
<ide> $result = $this->Paginator->url($options);
<ide> $this->assertEquals('/index?page=2&sort=Article&direction=desc', $result);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['page'] = 3;
<del> $options = array('order' => array('Article.name' => 'desc'));
<add> $this->Paginator->request->params['paging']['Article']['page'] = 3;
<add> $options = array('sort' => 'Article.name', 'direction' => 'desc');
<ide> $result = $this->Paginator->url($options);
<ide> $this->assertEquals('/index?page=3&sort=Article.name&direction=desc', $result);
<ide> }
<ide> public function testUrlGenerationWithPrefixes() {
<ide> array('base' => '', 'here' => 'posts/index', 'webroot' => '/')
<ide> ));
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['page'] = 2;
<ide> $this->Paginator->request->params['paging']['Article']['page'] = 2;
<ide> $this->Paginator->request->params['paging']['Article']['prevPage'] = true;
<ide> $options = array('prefix' => 'members');
<ide> public function testUrlGenerationWithPrefixes() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $options = array('prefix' => 'members', 'controller' => 'posts', 'order' => array('name' => 'desc'));
<add> $options = array('prefix' => 'members', 'controller' => 'posts', 'sort' => 'name', 'direction' => 'desc');
<ide> $result = $this->Paginator->url($options);
<ide> $expected = '/members/posts/index?page=2&sort=name&direction=desc';
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $options = array('controller' => 'posts', 'order' => array('Article.name' => 'desc'));
<add> $options = array('controller' => 'posts', 'sort' => 'Article.name', 'direction' => 'desc');
<ide> $result = $this->Paginator->url($options);
<ide> $expected = '/posts/index?page=2&sort=Article.name&direction=desc';
<ide> $this->assertEquals($expected, $result);
<ide> public function testOptions() {
<ide> $this->Paginator->request->params = array();
<ide>
<ide> $options = array('paging' => array('Article' => array(
<del> 'order' => 'desc',
<add> 'direction' => 'desc',
<ide> 'sort' => 'title'
<ide> )));
<ide> $this->Paginator->options($options);
<ide>
<ide> $expected = array('Article' => array(
<del> 'order' => 'desc',
<add> 'direction' => 'desc',
<ide> 'sort' => 'title'
<ide> ));
<ide> $this->assertEquals($expected, $this->Paginator->request->params['paging']);
<ide> public function testOptions() {
<ide> $this->Paginator->request->params = array();
<ide>
<ide> $options = array('Article' => array(
<del> 'order' => 'desc',
<add> 'direction' => 'desc',
<ide> 'sort' => 'title'
<ide> ));
<ide> $this->Paginator->options($options);
<ide> $this->assertEquals($expected, $this->Paginator->request->params['paging']);
<ide>
<ide> $options = array('paging' => array('Article' => array(
<del> 'order' => 'desc',
<add> 'direction' => 'desc',
<ide> 'sort' => 'Article.title'
<ide> )));
<ide> $this->Paginator->options($options);
<ide>
<ide> $expected = array('Article' => array(
<del> 'order' => 'desc',
<add> 'direction' => 'desc',
<ide> 'sort' => 'Article.title'
<ide> ));
<ide> $this->assertEquals($expected, $this->Paginator->request->params['paging']);
<ide> public function testPassedArgsMergingWithUrlOptions() {
<ide> 'Article' => array(
<ide> 'page' => 1, 'current' => 3, 'count' => 13,
<ide> 'prevPage' => false, 'nextPage' => true, 'pageCount' => 8,
<del> 'options' => array(
<del> 'page' => 1,
<del> 'order' => array(),
<del> 'conditions' => array()
<del> ),
<add> 'sort' => null, 'direction' => null,
<ide> )
<ide> );
<ide>
<ide> public function testPagingLinks() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => true,
<ide> 'pageCount' => 5,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide> $result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled'));
<ide> public function testPagingLinks() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => true,
<ide> 'pageCount' => 5,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide>
<ide> public function testPagingLinks() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => true,
<ide> 'pageCount' => 5,
<del> 'options' => array(
<del> 'page' => 1,
<del> 'limit' => 3,
<del> 'order' => array('Client.name' => 'DESC'),
<del> ),
<add> 'sort' => 'Client.name',
<add> 'direction' => 'DESC',
<add> 'limit' => 3,
<ide> )
<ide> );
<ide>
<ide> public function testPagingLinks() {
<ide> 'prevPage' => true,
<ide> 'nextPage' => false,
<ide> 'pageCount' => 2,
<del> 'options' => array(
<del> 'page' => 2,
<del> 'limit' => 10,
<del> 'order' => array(),
<del> 'conditions' => array()
<del> ),
<add> 'limit' => 10,
<ide> )
<ide> );
<ide> $result = $this->Paginator->prev('Prev');
<ide> public function testPagingLinks() {
<ide> 'Client' => array(
<ide> 'page' => 2, 'current' => 1, 'count' => 13, 'prevPage' => true,
<ide> 'nextPage' => false, 'pageCount' => 2,
<del> 'defaults' => array(),
<del> 'options' => array(
<del> 'page' => 2, 'limit' => 10, 'order' => array(), 'conditions' => array()
<del> ),
<add> 'limit' => 10,
<ide> )
<ide> );
<ide> $this->Paginator->options(array('url' => array(12, 'page' => 3)));
<ide> public function testPagingLinksOptionsReplaceEmptyDisabledOptions() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => true,
<ide> 'pageCount' => 5,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide> $result = $this->Paginator->prev('<< Previous', array('escape' => false));
<ide> public function testPagingLinksNotDefaultModel() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => true,
<ide> 'pageCount' => 5,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> ),
<ide> 'Server' => array(
<ide> 'page' => 1,
<ide> public function testPagingLinksNotDefaultModel() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => false,
<ide> 'pageCount' => 5,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide> $result = $this->Paginator->next('Next', array('model' => 'Client'));
<ide> public function testGenericLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['page'] = 2;
<add> $this->Paginator->request->params['paging']['Article']['page'] = 2;
<ide> $result = $this->Paginator->link('Sort by title', array('sort' => 'title', 'direction' => 'desc'));
<ide> $expected = array(
<ide> 'a' => array('href' => '/index?page=2&sort=title&direction=desc'),
<ide> public function testGenericLinks() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['page'] = 4;
<add> $this->Paginator->request->params['paging']['Article']['page'] = 4;
<ide> $result = $this->Paginator->link('Sort by title on page 4', array('sort' => 'Article.title', 'direction' => 'desc'));
<ide> $expected = array(
<ide> 'a' => array('href' => '/index?page=4&sort=Article.title&direction=desc'),
<ide> public function testNumbers() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => 2,
<ide> 'pageCount' => 15,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide> $result = $this->Paginator->numbers();
<ide> public function testNumbers() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => 2,
<ide> 'pageCount' => 15,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide> $result = $this->Paginator->numbers();
<ide> public function testNumbers() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => 2,
<ide> 'pageCount' => 15,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide> $result = $this->Paginator->numbers();
<ide> public function testNumbers() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => 2,
<ide> 'pageCount' => 9,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide>
<ide> public function testNumbers() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => 2,
<ide> 'pageCount' => 15,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide>
<ide> public function testNumbers() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => 2,
<ide> 'pageCount' => 15,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide>
<ide> public function testNumbers() {
<ide> 'prevPage' => 1,
<ide> 'nextPage' => 1,
<ide> 'pageCount' => 42,
<del> 'options' => array(
<del> 'page' => 6,
<del> ),
<ide> )
<ide> );
<ide>
<ide> public function testNumbers() {
<ide> 'prevPage' => 1,
<ide> 'nextPage' => 1,
<ide> 'pageCount' => 42,
<del> 'options' => array(
<del> 'page' => 37,
<del> ),
<ide> )
<ide> );
<ide>
<ide> public function testNumbers() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => 2,
<ide> 'pageCount' => 3,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide> $options = array('modulus' => 10);
<ide> public function testNumbers() {
<ide> 'prevPage' => true,
<ide> 'nextPage' => true,
<ide> 'pageCount' => 4,
<del> 'options' => array(
<del> 'page' => 1,
<del> 'order' => array('Client.name' => 'DESC'),
<del> ),
<add> 'sort' => 'Client.name',
<add> 'direction' => 'DESC',
<ide> )
<ide> );
<ide> $result = $this->Paginator->numbers(array('class' => 'page-link'));
<ide> public function testNumbers() {
<ide> 'prevPage' => 1,
<ide> 'nextPage' => 1,
<ide> 'pageCount' => 4897,
<del> 'options' => array(
<del> 'page' => 4894,
<del> ),
<ide> )
<ide> );
<ide>
<ide> public function testNumbers() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => 3,
<ide> 'pageCount' => 3,
<del> 'options' => array(
<del> 'page' => 1,
<del> )
<ide> )
<ide> );
<ide>
<ide> public function testFirstEmpty() {
<ide> * @return void
<ide> */
<ide> public function testFirstFullBaseUrl() {
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'DESC');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'DESC';
<ide>
<ide> $this->Paginator->options(array('url' => array('_full' => true)));
<ide>
<ide> public function testLastOptions() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => 2,
<ide> 'pageCount' => 15,
<del> 'options' => array(
<del> 'page' => 1,
<del> 'order' => array('Client.name' => 'DESC'),
<del> ),
<add> 'sort' => 'Client.name',
<add> 'direction' => 'DESC',
<ide> )
<ide> );
<ide>
<ide> public function testCounter() {
<ide> 'nextPage' => true,
<ide> 'pageCount' => 5,
<ide> 'limit' => 3,
<del> 'options' => array(
<del> 'page' => 1,
<del> 'order' => array('Client.name' => 'DESC'),
<del> ),
<add> 'sort' => 'Client.name',
<add> 'order' => 'DESC',
<ide> )
<ide> );
<ide> $input = 'Page %page% of %pages%, showing %current% records out of %count% total, ';
<ide> public function testNextLinkUsingDotNotation() {
<ide> array('base' => '', 'here' => '/accounts/', 'webroot' => '/')
<ide> ));
<ide>
<del> $this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
<add> $this->Paginator->request->params['paging']['Article']['sort'] = 'Article.title';
<add> $this->Paginator->request->params['paging']['Article']['direction'] = 'asc';
<ide> $this->Paginator->request->params['paging']['Article']['page'] = 1;
<ide>
<ide> $test = array('url' => array(
<ide> public function testWithOnePage() {
<ide> 'prevPage' => false,
<ide> 'nextPage' => true,
<ide> 'pageCount' => 1,
<del> 'options' => array(
<del> 'page' => 1,
<del> ),
<ide> )
<ide> );
<ide> $this->assertFalse($this->Paginator->numbers());
<ide> public function testWithZeroPages() {
<ide> 'nextPage' => false,
<ide> 'pageCount' => 0,
<ide> 'limit' => 10,
<del> 'options' => array(
<del> 'page' => 0,
<del> 'conditions' => array()
<del> ),
<ide> )
<ide> );
<ide> | 1 |
PHP | PHP | fix filesystem prepend when file doesn't exist | c0efbe169bf9840e9629ae0351a2eff7b62a3feb | <ide><path>src/Illuminate/Filesystem/Filesystem.php
<ide> public function prepend($path, $data)
<ide> }
<ide> else
<ide> {
<del> return $this->put($data);
<add> return $this->put($path, $data);
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | keep the first string we fetch | d2d003e8f8051e4d1a941319829603c1c713aedf | <ide><path>activesupport/test/caching_test.rb
<ide> def test_local_cache_raw_values_with_marshal
<ide>
<ide> def test_read_should_return_a_different_object_id_each_time_it_is_called
<ide> @cache.write('foo', 'bar')
<del> assert_not_equal @cache.read('foo').object_id, @cache.read('foo').object_id
<ide> value = @cache.read('foo')
<add> assert_not_equal value.object_id, @cache.read('foo').object_id
<ide> value << 'bingo'
<ide> assert_not_equal value, @cache.read('foo')
<ide> end | 1 |
Text | Text | add net socket write signature | 8e305890c9eb4488c7daf4600eca016b814b39bf | <ide><path>doc/api/net.md
<ide> active socket in the event system. If the socket is already `unref`ed calling
<ide> added: v0.1.90
<ide> -->
<ide>
<add>* `data` {string|Buffer|Uint8Array}
<add>* `encoding` {string} Only used when data is `string`. **Default:** `utf8`.
<add>* `callback` {Function}
<ide> * Returns: {boolean}
<ide>
<ide> Sends data on the socket. The second parameter specifies the encoding in the
<ide> buffer. Returns `false` if all or part of the data was queued in user memory.
<ide> The optional `callback` parameter will be executed when the data is finally
<ide> written out - this may not be immediately.
<ide>
<add>See Writable stream [`write()`][stream_writable_write] method for more
<add>information.
<add>
<ide> ## net.connect()
<ide>
<ide> Aliases to
<ide> Returns `true` if input is a version 6 IP address, otherwise returns `false`.
<ide> [duplex stream]: stream.html#stream_class_stream_duplex
<ide> [half-closed]: https://tools.ietf.org/html/rfc1122
<ide> [socket(7)]: http://man7.org/linux/man-pages/man7/socket.7.html
<add>[stream_writable_write]: stream.html#stream_writable_write_chunk_encoding_callback
<ide> [unspecified IPv4 address]: https://en.wikipedia.org/wiki/0.0.0.0
<ide> [unspecified IPv6 address]: https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address | 1 |
Javascript | Javascript | give priority to initial window background | 82fbec0879b7955752d3769afd44c39898f26f32 | <ide><path>static/index.js
<ide>
<ide> var backgroundStylesheet = document.createElement('style')
<ide> backgroundStylesheet.type = 'text/css'
<del> backgroundStylesheet.innerText = 'html, body { background: ' + backgroundColor + '; }'
<add> backgroundStylesheet.innerText = 'html, body { background: ' + backgroundColor + ' !important; }'
<ide> document.head.appendChild(backgroundStylesheet)
<ide>
<ide> // Remove once the page loads | 1 |
Python | Python | fix lgtm.com error | 34efd6957e3ca3d9981042b0db21addf4f4884ef | <ide><path>numpy/linalg/lapack_lite/clapack_scrub.py
<ide> def OutOfHeader(line):
<ide> return lines.getValue()
<ide>
<ide> def removeSubroutinePrototypes(source):
<del> expression = re.compile(
<del> r'/\* Subroutine \*/^\s*(?:(?:inline|static)\s+){0,2}(?!else|typedef|return)\w+\s+\*?\s*(\w+)\s*\([^0]+\)\s*;?'
<del> )
<del> lines = LineQueue()
<del> for line in UStringIO(source):
<del> if not expression.match(line):
<del> lines.add(line)
<del>
<del> return lines.getValue()
<add> # This function has never worked as advertised by its name:
<add> # - "/* Subroutine */" declarations may span multiple lines and
<add> # cannot be matched by a line by line approach.
<add> # - The caret in the initial regex would prevent any match, even
<add> # of single line "/* Subroutine */" declarations.
<add> #
<add> # While we could "fix" this function to do what the name implies
<add> # it should do, we have no hint of what it should really do.
<add> #
<add> # Therefore we keep the existing (non-)functionaity, documenting
<add> # this function as doing nothing at all.
<add> return source
<ide>
<ide> def removeBuiltinFunctions(source):
<ide> lines = LineQueue() | 1 |
Python | Python | add more optional_next tests | 346b570fd3d59b3f2a9a436ecbceb6353956b544 | <ide><path>official/resnet/keras/keras_imagenet_benchmark.py
<ide> def benchmark_8_gpu_fp16_dynamic_tweaked(self):
<ide> FLAGS.data_delay_prefetch = True
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_xla_8_gpu_fp16_optional_next(self):
<add> """Test Keras model with XLA, 8 GPUs and fp16.
<add>
<add> This test also enables get_next_as_optional.
<add> """
<add> self._setup()
<add>
<add> FLAGS.num_gpus = 8
<add> FLAGS.dtype = 'fp16'
<add> FLAGS.enable_eager = True
<add> FLAGS.enable_xla = True
<add> FLAGS.distribution_strategy = 'default'
<add> FLAGS.model_dir = self._get_model_dir(
<add> 'benchmark_xla_8_gpu_fp16_optional_next')
<add> FLAGS.batch_size = 256 * 8 # 8 GPUs
<add> FLAGS.enable_get_next_as_optional = True
<add> self._run_and_report_benchmark()
<add>
<ide> def benchmark_xla_8_gpu_fp16(self):
<ide> """Test Keras model with XLA, 8 GPUs and fp16."""
<ide> self._setup()
<ide> def benchmark_xla_8_gpu_fp16_cloning_tweaked(self):
<ide> FLAGS.data_delay_prefetch = True
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_xla_8_gpu_fp16_cloning_tweaked_optional_next(self):
<add> """Test with manual config tuning, XLA, 8 GPUs, fp16, and cloning.
<add>
<add> This test also enables get_next_as_optional.
<add> """
<add> self._setup()
<add>
<add> FLAGS.num_gpus = 8
<add> FLAGS.dtype = 'fp16'
<add> FLAGS.enable_eager = True
<add> FLAGS.enable_xla = True
<add> FLAGS.distribution_strategy = 'default'
<add> FLAGS.clone_model_in_keras_dist_strat = True
<add> FLAGS.model_dir = self._get_model_dir(
<add> 'benchmark_xla_8_gpu_fp16_cloning_tweaked_optional_next')
<add> FLAGS.batch_size = 256 * 8
<add> FLAGS.use_tensor_lr = True
<add> # FLAGS.tf_gpu_thread_mode = 'gpu_private'
<add> FLAGS.data_delay_prefetch = True
<add> FLAGS.enable_get_next_as_optional = True
<add> self._run_and_report_benchmark()
<add>
<ide> def benchmark_xla_8_gpu_fp16_tweaked_delay_measure(self):
<ide> """Test with manual config tuning, XLA, 8 GPUs and fp16.
<ide> | 1 |
Javascript | Javascript | replace 'blacklist' with 'blocklist' | 36f0ad2f985c3289018f0fdaaddf309cc9458d9b | <ide><path>test/specs/helpers/parseHeaders.spec.js
<ide> describe('helpers::parseHeaders', function () {
<ide>
<ide> it('should handle duplicates', function() {
<ide> var parsed = parseHeaders(
<del> 'Age: age-a\n' + // age is in ignore duplicates blacklist
<add> 'Age: age-a\n' + // age is in ignore duplicates blocklist
<ide> 'Age: age-b\n' +
<ide> 'Foo: foo-a\n' +
<ide> 'Foo: foo-b\n' | 1 |
Python | Python | fix stray pos in language stubs | ad1c747c6b1ecb7dbc4bcbab10f69bfa5198099b | <ide><path>spacy/es/language_data.py
<ide> "vs.": [{"F": "vs."}],
<ide>
<ide> "''": [{"F": "''"}],
<del> "—": [{"F": "—", "L": "--", "pos": ":"}],
<add> "—": [{"F": "—", "L": "--", "pos": "$,"}],
<ide>
<ide> "a.m.": [{"F": "a.m."}],
<ide> "p.m.": [{"F": "p.m."}],
<ide><path>spacy/fr/language_data.py
<ide> "vs.": [{"F": "vs."}],
<ide>
<ide> "''": [{"F": "''"}],
<del> "—": [{"F": "—", "L": "--", "pos": ":"}],
<add> "—": [{"F": "—", "L": "--", "pos": "$,"}],
<ide>
<ide> "a.m.": [{"F": "a.m."}],
<ide> "p.m.": [{"F": "p.m."}],
<ide><path>spacy/it/language_data.py
<add># encoding: utf8
<add>from __future__ import unicode_literals
<add>import re
<add>
<add>
<add>STOP_WORDS = set()
<add>
<add>
<add>TOKENIZER_PREFIXES = map(re.escape, r'''
<add>,
<add>"
<add>(
<add>[
<add>{
<add>*
<add><
<add>>
<add>$
<add>£
<add>„
<add>“
<add>'
<add>``
<add>`
<add>#
<add>US$
<add>C$
<add>A$
<add>a-
<add>‘
<add>....
<add>...
<add>‚
<add>»
<add>_
<add>§
<add>'''.strip().split('\n'))
<add>
<add>
<add>TOKENIZER_SUFFIXES = r'''
<add>,
<add>\"
<add>\)
<add>\]
<add>\}
<add>\*
<add>\!
<add>\?
<add>%
<add>\$
<add>>
<add>:
<add>;
<add>'
<add>”
<add>“
<add>«
<add>_
<add>''
<add>'s
<add>'S
<add>’s
<add>’S
<add>’
<add>‘
<add>°
<add>€
<add>\.\.
<add>\.\.\.
<add>\.\.\.\.
<add>(?<=[a-zäöüßÖÄÜ)\]"'´«‘’%\)²“”])\.
<add>\-\-
<add>´
<add>(?<=[0-9])km²
<add>(?<=[0-9])m²
<add>(?<=[0-9])cm²
<add>(?<=[0-9])mm²
<add>(?<=[0-9])km³
<add>(?<=[0-9])m³
<add>(?<=[0-9])cm³
<add>(?<=[0-9])mm³
<add>(?<=[0-9])ha
<add>(?<=[0-9])km
<add>(?<=[0-9])m
<add>(?<=[0-9])cm
<add>(?<=[0-9])mm
<add>(?<=[0-9])µm
<add>(?<=[0-9])nm
<add>(?<=[0-9])yd
<add>(?<=[0-9])in
<add>(?<=[0-9])ft
<add>(?<=[0-9])kg
<add>(?<=[0-9])g
<add>(?<=[0-9])mg
<add>(?<=[0-9])µg
<add>(?<=[0-9])t
<add>(?<=[0-9])lb
<add>(?<=[0-9])oz
<add>(?<=[0-9])m/s
<add>(?<=[0-9])km/h
<add>(?<=[0-9])mph
<add>(?<=[0-9])°C
<add>(?<=[0-9])°K
<add>(?<=[0-9])°F
<add>(?<=[0-9])hPa
<add>(?<=[0-9])Pa
<add>(?<=[0-9])mbar
<add>(?<=[0-9])mb
<add>(?<=[0-9])T
<add>(?<=[0-9])G
<add>(?<=[0-9])M
<add>(?<=[0-9])K
<add>(?<=[0-9])kb
<add>'''.strip().split('\n')
<add>
<add>
<add>TOKENIZER_INFIXES = tuple()
<add>
<add>
<add>TOKENIZER_EXCEPTIONS = {
<add> "vs.": [{"F": "vs."}],
<add>
<add> "''": [{"F": "''"}],
<add> "—": [{"F": "—", "L": "--", "pos": "$,"}],
<add>
<add> "a.m.": [{"F": "a.m."}],
<add> "p.m.": [{"F": "p.m."}],
<add>
<add> "1a.m.": [{"F": "1"}, {"F": "a.m."}],
<add> "2a.m.": [{"F": "2"}, {"F": "a.m."}],
<add> "3a.m.": [{"F": "3"}, {"F": "a.m."}],
<add> "4a.m.": [{"F": "4"}, {"F": "a.m."}],
<add> "5a.m.": [{"F": "5"}, {"F": "a.m."}],
<add> "6a.m.": [{"F": "6"}, {"F": "a.m."}],
<add> "7a.m.": [{"F": "7"}, {"F": "a.m."}],
<add> "8a.m.": [{"F": "8"}, {"F": "a.m."}],
<add> "9a.m.": [{"F": "9"}, {"F": "a.m."}],
<add> "10a.m.": [{"F": "10"}, {"F": "a.m."}],
<add> "11a.m.": [{"F": "11"}, {"F": "a.m."}],
<add> "12a.m.": [{"F": "12"}, {"F": "a.m."}],
<add> "1am": [{"F": "1"}, {"F": "am", "L": "a.m."}],
<add> "2am": [{"F": "2"}, {"F": "am", "L": "a.m."}],
<add> "3am": [{"F": "3"}, {"F": "am", "L": "a.m."}],
<add> "4am": [{"F": "4"}, {"F": "am", "L": "a.m."}],
<add> "5am": [{"F": "5"}, {"F": "am", "L": "a.m."}],
<add> "6am": [{"F": "6"}, {"F": "am", "L": "a.m."}],
<add> "7am": [{"F": "7"}, {"F": "am", "L": "a.m."}],
<add> "8am": [{"F": "8"}, {"F": "am", "L": "a.m."}],
<add> "9am": [{"F": "9"}, {"F": "am", "L": "a.m."}],
<add> "10am": [{"F": "10"}, {"F": "am", "L": "a.m."}],
<add> "11am": [{"F": "11"}, {"F": "am", "L": "a.m."}],
<add> "12am": [{"F": "12"}, {"F": "am", "L": "a.m."}],
<add>
<add> "p.m.": [{"F": "p.m."}],
<add> "1p.m.": [{"F": "1"}, {"F": "p.m."}],
<add> "2p.m.": [{"F": "2"}, {"F": "p.m."}],
<add> "3p.m.": [{"F": "3"}, {"F": "p.m."}],
<add> "4p.m.": [{"F": "4"}, {"F": "p.m."}],
<add> "5p.m.": [{"F": "5"}, {"F": "p.m."}],
<add> "6p.m.": [{"F": "6"}, {"F": "p.m."}],
<add> "7p.m.": [{"F": "7"}, {"F": "p.m."}],
<add> "8p.m.": [{"F": "8"}, {"F": "p.m."}],
<add> "9p.m.": [{"F": "9"}, {"F": "p.m."}],
<add> "10p.m.": [{"F": "10"}, {"F": "p.m."}],
<add> "11p.m.": [{"F": "11"}, {"F": "p.m."}],
<add> "12p.m.": [{"F": "12"}, {"F": "p.m."}],
<add> "1pm": [{"F": "1"}, {"F": "pm", "L": "p.m."}],
<add> "2pm": [{"F": "2"}, {"F": "pm", "L": "p.m."}],
<add> "3pm": [{"F": "3"}, {"F": "pm", "L": "p.m."}],
<add> "4pm": [{"F": "4"}, {"F": "pm", "L": "p.m."}],
<add> "5pm": [{"F": "5"}, {"F": "pm", "L": "p.m."}],
<add> "6pm": [{"F": "6"}, {"F": "pm", "L": "p.m."}],
<add> "7pm": [{"F": "7"}, {"F": "pm", "L": "p.m."}],
<add> "8pm": [{"F": "8"}, {"F": "pm", "L": "p.m."}],
<add> "9pm": [{"F": "9"}, {"F": "pm", "L": "p.m."}],
<add> "10pm": [{"F": "10"}, {"F": "pm", "L": "p.m."}],
<add> "11pm": [{"F": "11"}, {"F": "pm", "L": "p.m."}],
<add> "12pm": [{"F": "12"}, {"F": "pm", "L": "p.m."}],
<add>
<add> "Ala.": [{"F": "Ala."}],
<add> "Ariz.": [{"F": "Ariz."}],
<add> "Ark.": [{"F": "Ark."}],
<add> "Calif.": [{"F": "Calif."}],
<add> "Colo.": [{"F": "Colo."}],
<add> "Conn.": [{"F": "Conn."}],
<add> "Del.": [{"F": "Del."}],
<add> "D.C.": [{"F": "D.C."}],
<add> "Fla.": [{"F": "Fla."}],
<add> "Ga.": [{"F": "Ga."}],
<add> "Ill.": [{"F": "Ill."}],
<add> "Ind.": [{"F": "Ind."}],
<add> "Kans.": [{"F": "Kans."}],
<add> "Kan.": [{"F": "Kan."}],
<add> "Ky.": [{"F": "Ky."}],
<add> "La.": [{"F": "La."}],
<add> "Md.": [{"F": "Md."}],
<add> "Mass.": [{"F": "Mass."}],
<add> "Mich.": [{"F": "Mich."}],
<add> "Minn.": [{"F": "Minn."}],
<add> "Miss.": [{"F": "Miss."}],
<add> "Mo.": [{"F": "Mo."}],
<add> "Mont.": [{"F": "Mont."}],
<add> "Nebr.": [{"F": "Nebr."}],
<add> "Neb.": [{"F": "Neb."}],
<add> "Nev.": [{"F": "Nev."}],
<add> "N.H.": [{"F": "N.H."}],
<add> "N.J.": [{"F": "N.J."}],
<add> "N.M.": [{"F": "N.M."}],
<add> "N.Y.": [{"F": "N.Y."}],
<add> "N.C.": [{"F": "N.C."}],
<add> "N.D.": [{"F": "N.D."}],
<add> "Okla.": [{"F": "Okla."}],
<add> "Ore.": [{"F": "Ore."}],
<add> "Pa.": [{"F": "Pa."}],
<add> "Tenn.": [{"F": "Tenn."}],
<add> "Va.": [{"F": "Va."}],
<add> "Wash.": [{"F": "Wash."}],
<add> "Wis.": [{"F": "Wis."}],
<add>
<add> ":)": [{"F": ":)"}],
<add> "<3": [{"F": "<3"}],
<add> ";)": [{"F": ";)"}],
<add> "(:": [{"F": "(:"}],
<add> ":(": [{"F": ":("}],
<add> "-_-": [{"F": "-_-"}],
<add> "=)": [{"F": "=)"}],
<add> ":/": [{"F": ":/"}],
<add> ":>": [{"F": ":>"}],
<add> ";-)": [{"F": ";-)"}],
<add> ":Y": [{"F": ":Y"}],
<add> ":P": [{"F": ":P"}],
<add> ":-P": [{"F": ":-P"}],
<add> ":3": [{"F": ":3"}],
<add> "=3": [{"F": "=3"}],
<add> "xD": [{"F": "xD"}],
<add> "^_^": [{"F": "^_^"}],
<add> "=]": [{"F": "=]"}],
<add> "=D": [{"F": "=D"}],
<add> "<333": [{"F": "<333"}],
<add> ":))": [{"F": ":))"}],
<add> ":0": [{"F": ":0"}],
<add> "-__-": [{"F": "-__-"}],
<add> "xDD": [{"F": "xDD"}],
<add> "o_o": [{"F": "o_o"}],
<add> "o_O": [{"F": "o_O"}],
<add> "V_V": [{"F": "V_V"}],
<add> "=[[": [{"F": "=[["}],
<add> "<33": [{"F": "<33"}],
<add> ";p": [{"F": ";p"}],
<add> ";D": [{"F": ";D"}],
<add> ";-p": [{"F": ";-p"}],
<add> ";(": [{"F": ";("}],
<add> ":p": [{"F": ":p"}],
<add> ":]": [{"F": ":]"}],
<add> ":O": [{"F": ":O"}],
<add> ":-/": [{"F": ":-/"}],
<add> ":-)": [{"F": ":-)"}],
<add> ":(((": [{"F": ":((("}],
<add> ":((": [{"F": ":(("}],
<add> ":')": [{"F": ":')"}],
<add> "(^_^)": [{"F": "(^_^)"}],
<add> "(=": [{"F": "(="}],
<add> "o.O": [{"F": "o.O"}],
<add> "\")": [{"F": "\")"}],
<add>
<add> "a.": [{"F": "a."}],
<add> "b.": [{"F": "b."}],
<add> "c.": [{"F": "c."}],
<add> "d.": [{"F": "d."}],
<add> "e.": [{"F": "e."}],
<add> "f.": [{"F": "f."}],
<add> "g.": [{"F": "g."}],
<add> "h.": [{"F": "h."}],
<add> "i.": [{"F": "i."}],
<add> "j.": [{"F": "j."}],
<add> "k.": [{"F": "k."}],
<add> "l.": [{"F": "l."}],
<add> "m.": [{"F": "m."}],
<add> "n.": [{"F": "n."}],
<add> "o.": [{"F": "o."}],
<add> "p.": [{"F": "p."}],
<add> "q.": [{"F": "q."}],
<add> "r.": [{"F": "r."}],
<add> "s.": [{"F": "s."}],
<add> "t.": [{"F": "t."}],
<add> "u.": [{"F": "u."}],
<add> "v.": [{"F": "v."}],
<add> "w.": [{"F": "w."}],
<add> "x.": [{"F": "x."}],
<add> "y.": [{"F": "y."}],
<add> "z.": [{"F": "z."}],
<add>}
<add>
<add>
<add>TAG_MAP = {
<add>"$(": {"pos": "PUNCT", "PunctType": "Brck"},
<add>"$,": {"pos": "PUNCT", "PunctType": "Comm"},
<add>"$.": {"pos": "PUNCT", "PunctType": "Peri"},
<add>"ADJA": {"pos": "ADJ"},
<add>"ADJD": {"pos": "ADJ", "Variant": "Short"},
<add>"ADV": {"pos": "ADV"},
<add>"APPO": {"pos": "ADP", "AdpType": "Post"},
<add>"APPR": {"pos": "ADP", "AdpType": "Prep"},
<add>"APPRART": {"pos": "ADP", "AdpType": "Prep", "PronType": "Art"},
<add>"APZR": {"pos": "ADP", "AdpType": "Circ"},
<add>"ART": {"pos": "DET", "PronType": "Art"},
<add>"CARD": {"pos": "NUM", "NumType": "Card"},
<add>"FM": {"pos": "X", "Foreign": "Yes"},
<add>"ITJ": {"pos": "INTJ"},
<add>"KOKOM": {"pos": "CONJ", "ConjType": "Comp"},
<add>"KON": {"pos": "CONJ"},
<add>"KOUI": {"pos": "SCONJ"},
<add>"KOUS": {"pos": "SCONJ"},
<add>"NE": {"pos": "PROPN"},
<add>"NNE": {"pos": "PROPN"},
<add>"NN": {"pos": "NOUN"},
<add>"PAV": {"pos": "ADV", "PronType": "Dem"},
<add>"PROAV": {"pos": "ADV", "PronType": "Dem"},
<add>"PDAT": {"pos": "DET", "PronType": "Dem"},
<add>"PDS": {"pos": "PRON", "PronType": "Dem"},
<add>"PIAT": {"pos": "DET", "PronType": "Ind,Neg,Tot"},
<add>"PIDAT": {"pos": "DET", "AdjType": "Pdt", "PronType": "Ind,Neg,Tot"},
<add>"PIS": {"pos": "PRON", "PronType": "Ind,Neg,Tot"},
<add>"PPER": {"pos": "PRON", "PronType": "Prs"},
<add>"PPOSAT": {"pos": "DET", "Poss": "Yes", "PronType": "Prs"},
<add>"PPOSS": {"pos": "PRON", "Poss": "Yes", "PronType": "Prs"},
<add>"PRELAT": {"pos": "DET", "PronType": "Rel"},
<add>"PRELS": {"pos": "PRON", "PronType": "Rel"},
<add>"PRF": {"pos": "PRON", "PronType": "Prs", "Reflex": "Yes"},
<add>"PTKA": {"pos": "PART"},
<add>"PTKANT": {"pos": "PART", "PartType": "Res"},
<add>"PTKNEG": {"pos": "PART", "Negative": "Neg"},
<add>"PTKVZ": {"pos": "PART", "PartType": "Vbp"},
<add>"PTKZU": {"pos": "PART", "PartType": "Inf"},
<add>"PWAT": {"pos": "DET", "PronType": "Int"},
<add>"PWAV": {"pos": "ADV", "PronType": "Int"},
<add>"PWS": {"pos": "PRON", "PronType": "Int"},
<add>"TRUNC": {"pos": "X", "Hyph": "Yes"},
<add>"VAFIN": {"pos": "AUX", "Mood": "Ind", "VerbForm": "Fin"},
<add>"VAIMP": {"pos": "AUX", "Mood": "Imp", "VerbForm": "Fin"},
<add>"VAINF": {"pos": "AUX", "VerbForm": "Inf"},
<add>"VAPP": {"pos": "AUX", "Aspect": "Perf", "VerbForm": "Part"},
<add>"VMFIN": {"pos": "VERB", "Mood": "Ind", "VerbForm": "Fin", "VerbType": "Mod"},
<add>"VMINF": {"pos": "VERB", "VerbForm": "Inf", "VerbType": "Mod"},
<add>"VMPP": {"pos": "VERB", "Aspect": "Perf", "VerbForm": "Part", "VerbType": "Mod"},
<add>"VVFIN": {"pos": "VERB", "Mood": "Ind", "VerbForm": "Fin"},
<add>"VVIMP": {"pos": "VERB", "Mood": "Imp", "VerbForm": "Fin"},
<add>"VVINF": {"pos": "VERB", "VerbForm": "Inf"},
<add>"VVIZU": {"pos": "VERB", "VerbForm": "Inf"},
<add>"VVPP": {"pos": "VERB", "Aspect": "Perf", "VerbForm": "Part"},
<add>"XY": {"pos": "X"},
<add>"SP": {"pos": "SPACE"}
<add>}
<ide><path>spacy/pt/language_data.py
<ide> "vs.": [{"F": "vs."}],
<ide>
<ide> "''": [{"F": "''"}],
<del> "—": [{"F": "—", "L": "--", "pos": ":"}],
<add> "—": [{"F": "—", "L": "--", "pos": "$,"}],
<ide>
<ide> "a.m.": [{"F": "a.m."}],
<ide> "p.m.": [{"F": "p.m."}], | 4 |
Python | Python | use the same pattern as everywhere else | 4621ad6f9d89637745f32e18e4e36f3f5212d4b9 | <ide><path>src/transformers/tokenization_transfo_xl.py
<ide>
<ide> import numpy as np
<ide>
<del>from .file_utils import cached_path
<add>from .file_utils import cached_path, is_torch_available
<ide> from .tokenization_utils import PreTrainedTokenizer
<ide>
<ide>
<del>try:
<add>if is_torch_available():
<ide> import torch
<del>except ImportError:
<del> pass
<ide>
<ide>
<ide> logger = logging.getLogger(__name__) | 1 |
PHP | PHP | add support for is() with multiple types | d4a3594e4f53eca1090eb8ab4f30e03304bb305e | <ide><path>lib/Cake/Network/CakeRequest.php
<ide> public function __isset($name) {
<ide> }
<ide>
<ide> /**
<del> * Check whether or not a Request is a certain type. Uses the built in detection rules
<del> * as well as additional rules defined with CakeRequest::addDetector(). Any detector can be called
<add> * Check whether or not a Request is a certain type.
<add> *
<add> * Uses the built in detection rules as well as additional rules
<add> * defined with CakeRequest::addDetector(). Any detector can be called
<ide> * as `is($type)` or `is$Type()`.
<ide> *
<del> * @param string $type The type of request you want to check.
<add> * @param string|array $type The type of request you want to check. If an array
<add> * this method will return true if the request matches any type.
<ide> * @return boolean Whether or not the request is the type you are checking.
<ide> */
<ide> public function is($type) {
<add> if (is_array($type)) {
<add> $result = array_map(array($this, 'is'), $type);
<add> return count(array_filter($result)) > 0;
<add> }
<ide> $type = strtolower($type);
<ide> if (!isset($this->_detectors[$type])) {
<ide> return false;
<ide><path>lib/Cake/Test/Case/Network/CakeRequestTest.php
<ide> public function testIsHttpMethods() {
<ide> $this->assertFalse($request->is('delete'));
<ide> }
<ide>
<add>/**
<add> * Test is() with multiple types.
<add> *
<add> * @return void
<add> */
<add> public function testIsMultiple() {
<add> $request = new CakeRequest('some/path');
<add>
<add> $_SERVER['REQUEST_METHOD'] = 'GET';
<add> $this->assertTrue($request->is(array('get', 'post')));
<add>
<add> $_SERVER['REQUEST_METHOD'] = 'POST';
<add> $this->assertTrue($request->is(array('get', 'post')));
<add>
<add> $_SERVER['REQUEST_METHOD'] = 'PUT';
<add> $this->assertFalse($request->is(array('get', 'post')));
<add> }
<add>
<ide> /**
<ide> * test the method() method.
<ide> * | 2 |
Text | Text | remove outdated reference to updating /etc/hosts | 171f5d84f908056353d5cd138d13de1636447d68 | <ide><path>docs/reference/run.md
<ide> If a container is connected to the default bridge network and `linked`
<ide> with other containers, then the container's `/etc/hosts` file is updated
<ide> with the linked container's name.
<ide>
<del>If the container is connected to user-defined network, the container's
<del>`/etc/hosts` file is updated with names of all other containers in that
<del>user-defined network.
<del>
<ide> > **Note** Since Docker may live update the container’s `/etc/hosts` file, there
<ide> may be situations when processes inside the container can end up reading an
<ide> empty or incomplete `/etc/hosts` file. In most cases, retrying the read again | 1 |
Javascript | Javascript | remove excessive instrumentation | 9d13b7cf3dff1bd3298bbbe48da01d94bd848f56 | <ide><path>packages/ember-handlebars/lib/helpers/binding.js
<ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer
<ide> fn = options.fn,
<ide> inverse = options.inverse,
<ide> view = data.view,
<del> instrumentName = view.instrumentName,
<ide> currentContext = this,
<ide> pathRoot, path, normalized,
<ide> observer;
<ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer
<ide>
<ide> template(context, { data: options.data });
<ide> } else {
<del> var bindView = Ember.instrument('bind-view.' + instrumentName,
<del> { object: view.toString() },
<del> function() {
<del> // Create the view that will wrap the output of this template/property
<del> // and add it to the nearest view's childViews array.
<del> // See the documentation of Ember._HandlebarsBoundView for more.
<del> var bindView = view.createChildView(Ember._HandlebarsBoundView, {
<del> preserveContext: preserveContext,
<del> shouldDisplayFunc: shouldDisplay,
<del> valueNormalizerFunc: valueNormalizer,
<del> displayTemplate: fn,
<del> inverseTemplate: inverse,
<del> path: path,
<del> pathRoot: pathRoot,
<del> previousContext: currentContext,
<del> isEscaped: !options.hash.unescaped,
<del> templateData: options.data
<del> });
<del>
<del> view.appendChild(bindView);
<del> return bindView;
<del> });
<add> // Create the view that will wrap the output of this template/property
<add> // and add it to the nearest view's childViews array.
<add> // See the documentation of Ember._HandlebarsBoundView for more.
<add> var bindView = view.createChildView(Ember._HandlebarsBoundView, {
<add> preserveContext: preserveContext,
<add> shouldDisplayFunc: shouldDisplay,
<add> valueNormalizerFunc: valueNormalizer,
<add> displayTemplate: fn,
<add> inverseTemplate: inverse,
<add> path: path,
<add> pathRoot: pathRoot,
<add> previousContext: currentContext,
<add> isEscaped: !options.hash.unescaped,
<add> templateData: options.data
<add> });
<add>
<add> view.appendChild(bindView);
<ide>
<ide> /** @private */
<ide> observer = function() {
<ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer
<ide> function simpleBind(property, options) {
<ide> var data = options.data,
<ide> view = data.view,
<del> instrumentName = view.instrumentName,
<ide> currentContext = this,
<ide> pathRoot, path, normalized,
<ide> observer;
<ide> function simpleBind(property, options) {
<ide> if (result === null || result === undefined) { result = ""; }
<ide> data.buffer.push(result);
<ide> } else {
<del> var bindView = Ember.instrument('simple-bind-view.' + instrumentName,
<del> { object: view.toString() },
<del> function() {
<del> var bindView = new Ember._SimpleHandlebarsView(
<del> path, pathRoot, !options.hash.unescaped, options.data
<del> );
<del>
<del> bindView._parentView = view;
<del> view.appendChild(bindView);
<del> return bindView;
<del> });
<add> var bindView = new Ember._SimpleHandlebarsView(
<add> path, pathRoot, !options.hash.unescaped, options.data
<add> );
<add>
<add> bindView._parentView = view;
<add> view.appendChild(bindView);
<ide>
<ide> observer = function() {
<ide> Ember.run.scheduleOnce('render', bindView, 'rerender');
<ide> EmberHandlebars.registerHelper('bindAttr', function(options) {
<ide>
<ide> Ember.assert("You must specify at least one hash argument to bindAttr", !!Ember.keys(attrs).length);
<ide>
<del> var view = options.data.view, instrumentName = view.instrumentName;
<add> var view = options.data.view;
<ide> var ret = [];
<ide> var ctx = this;
<ide>
<ide> EmberHandlebars.registerHelper('bindAttr', function(options) {
<ide> // Handle classes differently, as we can bind multiple classes
<ide> var classBindings = attrs['class'];
<ide> if (classBindings !== null && classBindings !== undefined) {
<del> var classResults = Ember.instrument('class-bindings.' + instrumentName,
<del> { object: view.toString() },
<del> function() {
<del> return EmberHandlebars.bindClasses(this, classBindings, view, dataId, options);
<del> }, this);
<add> var classResults = EmberHandlebars.bindClasses(this, classBindings, view, dataId, options);
<ide>
<ide> ret.push('class="' + Handlebars.Utils.escapeExpression(classResults.join(' ')) + '"');
<ide> delete attrs['class'];
<ide><path>packages/ember-handlebars/lib/helpers/collection.js
<ide> Ember.Handlebars.registerHelper('collection', function(path, options) {
<ide> var data = options.data;
<ide> var inverse = options.inverse;
<ide> var view = options.data.view;
<del> var instrumentName = view.instrumentName;
<ide>
<ide> // If passed a path string, convert that into an object.
<ide> // Otherwise, just default to the standard class.
<ide> Ember.Handlebars.registerHelper('collection', function(path, options) {
<ide>
<ide> var viewString = view.toString();
<ide>
<del> Ember.instrument('collection-setup.' + instrumentName,
<del> { object: viewString },
<del> function() {
<del> var viewOptions = Ember.Handlebars.ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this);
<del> viewOptions._anonymous = true;
<del> hash.itemViewClass = itemViewClass.extend(viewOptions);
<del> });
<add> var viewOptions = Ember.Handlebars.ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this);
<add> hash.itemViewClass = itemViewClass.extend(viewOptions);
<ide>
<del> return Ember.instrument('collection-view.' + instrumentName,
<del> { object: viewString },
<del> function() {
<del> return Ember.Handlebars.helpers.view.call(this, collectionClass, options);
<del> }, this);
<add> return Ember.Handlebars.helpers.view.call(this, collectionClass, options);
<ide> });
<ide>
<ide><path>packages/ember-handlebars/lib/views/handlebars_bound_view.js
<ide> SimpleHandlebarsView.prototype = {
<ide> return result;
<ide> },
<ide>
<del> renderToBuffer: function(parentBuffer) {
<del> var name = 'render-to-buffer.simpleHandlebars',
<del> details = { object: '<Ember._SimpleHandlebarsView>' };
<del>
<del> return Ember.instrument(name, details, function() {
<del> return this._renderToBuffer(parentBuffer);
<del> }, this);
<del> },
<del>
<del> _renderToBuffer: function(buffer) {
<add> renderToBuffer: function(buffer) {
<ide> var string = '';
<ide>
<ide> string += this.morph.startTag();
<ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.CoreView = Ember.Object.extend(Ember.Evented, {
<ide> be used.
<ide> */
<ide> renderToBuffer: function(parentBuffer, bufferOperation) {
<del> var name = 'render-to-buffer.' + this.instrumentName,
<add> var name = 'render.' + this.instrumentName,
<ide> details = {};
<ide>
<ide> this.instrumentDetails(details);
<ide> Ember.View = Ember.CoreView.extend(
<ide> Ember.assert('template must be a function. Did you mean to call Ember.Handlebars.compile("...") or specify templateName instead?', typeof template === 'function');
<ide> // The template should write directly to the render buffer instead
<ide> // of returning a string.
<del> Ember.instrument('template.' + this.instrumentName,
<del> { object: this.toString() },
<del> function() { output = template(context, { data: data }); });
<add> output = template(context, { data: data });
<ide>
<ide> // If the template returned a string instead of writing to the buffer,
<ide> // push the string onto the buffer. | 4 |
Java | Java | add contravariant for min and max | a884a67a7c2b4c4f51d21d6219db7a039fdb9f83 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public static Observable<Double> averageDoubles(Observable<Double> source) {
<ide> * if the source is empty
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229715(v=vs.103).aspx">MSDN: Observable.Min</a>
<ide> */
<del> public static <T extends Comparable<T>> Observable<T> min(Observable<T> source) {
<add> public static <T extends Comparable<? super T>> Observable<T> min(Observable<T> source) {
<ide> return OperationMinMax.min(source);
<ide> }
<ide>
<ide> public static <T extends Comparable<T>> Observable<T> min(Observable<T> source)
<ide> * if the source is empty
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229095(v=vs.103).aspx">MSDN: Observable.Min</a>
<ide> */
<del> public Observable<T> min(Comparator<T> comparator) {
<add> public Observable<T> min(Comparator<? super T> comparator) {
<ide> return OperationMinMax.min(this, comparator);
<ide> }
<ide>
<ide> public Observable<T> min(Comparator<T> comparator) {
<ide> * @return an observable emitting a List of the elements with the minimum key value.
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh228970(v=vs.103).aspx">MSDN: Observable.MinBy</a>
<ide> */
<del> public <R extends Comparable<R>> Observable<List<T>> minBy(Func1<T, R> selector) {
<add> public <R extends Comparable<? super R>> Observable<List<T>> minBy(Func1<T, R> selector) {
<ide> return OperationMinMax.minBy(this, selector);
<ide> }
<ide>
<ide> public <R extends Comparable<R>> Observable<List<T>> minBy(Func1<T, R> selector)
<ide> * @return an observable emitting a List of the elements with the minimum key value according to the specified comparator.
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh228970(v=vs.103).aspx">MSDN: Observable.MinBy</a>
<ide> */
<del> public <R> Observable<List<T>> minBy(Func1<T, R> selector, Comparator<R> comparator) {
<add> public <R> Observable<List<T>> minBy(Func1<T, R> selector, Comparator<? super R> comparator) {
<ide> return OperationMinMax.minBy(this, selector, comparator);
<ide> }
<ide>
<ide> public <R> Observable<List<T>> minBy(Func1<T, R> selector, Comparator<R> compara
<ide> * if the source is empty.
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211837(v=vs.103).aspx">MSDN: Observable.Max</a>
<ide> */
<del> public static <T extends Comparable<T>> Observable<T> max(Observable<T> source) {
<add> public static <T extends Comparable<? super T>> Observable<T> max(Observable<T> source) {
<ide> return OperationMinMax.max(source);
<ide> }
<ide>
<ide> public static <T extends Comparable<T>> Observable<T> max(Observable<T> source)
<ide> * if the source is empty.
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211635(v=vs.103).aspx">MSDN: Observable.Max</a>
<ide> */
<del> public Observable<T> max(Comparator<T> comparator) {
<add> public Observable<T> max(Comparator<? super T> comparator) {
<ide> return OperationMinMax.max(this, comparator);
<ide> }
<ide>
<ide> public Observable<T> max(Comparator<T> comparator) {
<ide> * @return an observable emitting a List of the elements with the maximum key value.
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229058(v=vs.103).aspx">MSDN: Observable.MaxBy</a>
<ide> */
<del> public <R extends Comparable<R>> Observable<List<T>> maxBy(Func1<T, R> selector) {
<add> public <R extends Comparable<? super R>> Observable<List<T>> maxBy(Func1<T, R> selector) {
<ide> return OperationMinMax.maxBy(this, selector);
<ide> }
<ide>
<ide> public <R extends Comparable<R>> Observable<List<T>> maxBy(Func1<T, R> selector)
<ide> * @return an observable emitting a List of the elements with the maximum key value according to the specified comparator.
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244330(v=vs.103).aspx">MSDN: Observable.MaxBy</a>
<ide> */
<del> public <R> Observable<List<T>> maxBy(Func1<T, R> selector, Comparator<R> comparator) {
<add> public <R> Observable<List<T>> maxBy(Func1<T, R> selector, Comparator<? super R> comparator) {
<ide> return OperationMinMax.maxBy(this, selector, comparator);
<ide> }
<ide>
<ide><path>rxjava-core/src/main/java/rx/operators/OperationMinMax.java
<ide> */
<ide> public class OperationMinMax {
<ide>
<del> public static <T extends Comparable<T>> Observable<T> min(
<add> public static <T extends Comparable<? super T>> Observable<T> min(
<ide> Observable<T> source) {
<ide> return minMax(source, -1L);
<ide> }
<ide>
<ide> public static <T> Observable<T> min(Observable<T> source,
<del> final Comparator<T> comparator) {
<add> final Comparator<? super T> comparator) {
<ide> return minMax(source, comparator, -1L);
<ide> }
<ide>
<del> public static <T, R extends Comparable<R>> Observable<List<T>> minBy(
<add> public static <T, R extends Comparable<? super R>> Observable<List<T>> minBy(
<ide> Observable<T> source, final Func1<T, R> selector) {
<ide> return minMaxBy(source, selector, -1L);
<ide> }
<ide>
<ide> public static <T, R> Observable<List<T>> minBy(Observable<T> source,
<del> final Func1<T, R> selector, final Comparator<R> comparator) {
<add> final Func1<T, R> selector, final Comparator<? super R> comparator) {
<ide> return minMaxBy(source, selector, comparator, -1L);
<ide> }
<ide>
<del> public static <T extends Comparable<T>> Observable<T> max(
<add> public static <T extends Comparable<? super T>> Observable<T> max(
<ide> Observable<T> source) {
<ide> return minMax(source, 1L);
<ide> }
<ide>
<ide> public static <T> Observable<T> max(Observable<T> source,
<del> final Comparator<T> comparator) {
<add> final Comparator<? super T> comparator) {
<ide> return minMax(source, comparator, 1L);
<ide> }
<ide>
<del> public static <T, R extends Comparable<R>> Observable<List<T>> maxBy(
<add> public static <T, R extends Comparable<? super R>> Observable<List<T>> maxBy(
<ide> Observable<T> source, final Func1<T, R> selector) {
<ide> return minMaxBy(source, selector, 1L);
<ide> }
<ide>
<ide> public static <T, R> Observable<List<T>> maxBy(Observable<T> source,
<del> final Func1<T, R> selector, final Comparator<R> comparator) {
<add> final Func1<T, R> selector, final Comparator<? super R> comparator) {
<ide> return minMaxBy(source, selector, comparator, 1L);
<ide> }
<ide>
<del> private static <T extends Comparable<T>> Observable<T> minMax(
<add> private static <T extends Comparable<? super T>> Observable<T> minMax(
<ide> Observable<T> source, final long flag) {
<ide> return source.reduce(new Func2<T, T, T>() {
<ide> @Override
<ide> public T call(T acc, T value) {
<ide> }
<ide>
<ide> private static <T> Observable<T> minMax(Observable<T> source,
<del> final Comparator<T> comparator, final long flag) {
<add> final Comparator<? super T> comparator, final long flag) {
<ide> return source.reduce(new Func2<T, T, T>() {
<ide> @Override
<ide> public T call(T acc, T value) {
<ide> public T call(T acc, T value) {
<ide> });
<ide> }
<ide>
<del> private static <T, R extends Comparable<R>> Observable<List<T>> minMaxBy(
<add> private static <T, R extends Comparable<? super R>> Observable<List<T>> minMaxBy(
<ide> Observable<T> source, final Func1<T, R> selector, final long flag) {
<ide> return source.reduce(new ArrayList<T>(),
<ide> new Func2<List<T>, T, List<T>>() {
<ide> public List<T> call(List<T> acc, T value) {
<ide> }
<ide>
<ide> private static <T, R> Observable<List<T>> minMaxBy(Observable<T> source,
<del> final Func1<T, R> selector, final Comparator<R> comparator,
<add> final Func1<T, R> selector, final Comparator<? super R> comparator,
<ide> final long flag) {
<ide> return source.reduce(new ArrayList<T>(),
<ide> new Func2<List<T>, T, List<T>>() { | 2 |
Python | Python | improve matcher tests re issue | 2d3ce89b78fab01608b389ecc07a6edda30609c5 | <ide><path>spacy/tests/matcher/test_matcher_logic.py
<ide> import pytest
<ide> import re
<ide> from spacy.matcher import Matcher
<del>from spacy.tokens import Doc
<add>from spacy.tokens import Doc, Span
<ide>
<ide>
<ide> pattern1 = [{"ORTH": "A", "OP": "1"}, {"ORTH": "A", "OP": "*"}]
<ide> def test_matcher_end_zero_plus(en_vocab):
<ide> assert len(matcher(nlp("a b c"))) == 2
<ide> assert len(matcher(nlp("a b b c"))) == 3
<ide> assert len(matcher(nlp("a b b"))) == 3
<add>
<add>
<add>def test_matcher_sets_return_correct_tokens(en_vocab):
<add> matcher = Matcher(en_vocab)
<add> patterns = [
<add> [{'LOWER': {'IN': ["zero"]}}],
<add> [{'LOWER': {'IN': ["one"]}}],
<add> [{'LOWER': {'IN': ["two"]}}],
<add> ]
<add> matcher.add('TEST', None, *patterns)
<add> doc = Doc(en_vocab, words="zero one two three".split())
<add> matches = matcher(doc)
<add> texts = [Span(doc, s, e, label=L).text for L, s, e in matches]
<add> assert texts == ['zero', 'one', 'two'] | 1 |
Python | Python | add description method in bigquerycursor class | 7d2c2ee879656faf47829d1ad89fc4441e19a66e | <ide><path>airflow/providers/google/cloud/hooks/bigquery.py
<ide> def __init__(
<ide> self.job_id = None # type: Optional[str]
<ide> self.buffer = [] # type: list
<ide> self.all_pages_loaded = False # type: bool
<add> self._description = [] # type: List
<ide>
<ide> @property
<del> def description(self) -> None:
<del> """The schema description method is not currently implemented"""
<del> raise NotImplementedError
<add> def description(self) -> List:
<add> """Return the cursor description"""
<add> return self._description
<add>
<add> @description.setter
<add> def description(self, value):
<add> self._description = value
<ide>
<ide> def close(self) -> None:
<ide> """By default, do nothing"""
<ide> def execute(self, operation: str, parameters: Optional[dict] = None) -> None:
<ide> self.flush_results()
<ide> self.job_id = self.hook.run_query(sql)
<ide>
<add> query_results = self._get_query_result()
<add> description = _format_schema_for_description(query_results["schema"])
<add> self.description = description
<add>
<ide> def executemany(self, operation: str, seq_of_parameters: list) -> None:
<ide> """
<ide> Execute a BigQuery query multiple times with different parameters.
<ide> def next(self) -> Union[List, None]:
<ide> if self.all_pages_loaded:
<ide> return None
<ide>
<del> query_results = (
<del> self.service.jobs()
<del> .getQueryResults(
<del> projectId=self.project_id,
<del> jobId=self.job_id,
<del> location=self.location,
<del> pageToken=self.page_token,
<del> )
<del> .execute(num_retries=self.num_retries)
<del> )
<del>
<add> query_results = self._get_query_result()
<ide> if 'rows' in query_results and query_results['rows']:
<ide> self.page_token = query_results.get('pageToken')
<ide> fields = query_results['schema']['fields']
<ide> def setinputsizes(self, sizes: Any) -> None:
<ide> def setoutputsize(self, size: Any, column: Any = None) -> None:
<ide> """Does nothing by default"""
<ide>
<add> def _get_query_result(self) -> Dict:
<add> """Get job query results like data, schema, job type..."""
<add> query_results = (
<add> self.service.jobs()
<add> .getQueryResults(
<add> projectId=self.project_id,
<add> jobId=self.job_id,
<add> location=self.location,
<add> pageToken=self.page_token,
<add> )
<add> .execute(num_retries=self.num_retries)
<add> )
<add>
<add> return query_results
<add>
<ide>
<ide> def _bind_parameters(operation: str, parameters: dict) -> str:
<ide> """Helper method that binds parameters to a SQL query"""
<ide> def _validate_src_fmt_configs(
<ide> raise ValueError(f"{k} is not a valid src_fmt_configs for type {source_format}.")
<ide>
<ide> return src_fmt_configs
<add>
<add>
<add>def _format_schema_for_description(schema: Dict) -> List:
<add> """
<add> Reformat the schema to match cursor description standard which is a tuple
<add> of 7 elemenbts (name, type, display_size, internal_size, precision, scale, null_ok)
<add> """
<add> description = []
<add> for field in schema["fields"]:
<add> field_description = (
<add> field["name"],
<add> field["type"],
<add> None,
<add> None,
<add> None,
<add> None,
<add> field["mode"] == "NULLABLE",
<add> )
<add> description.append(field_description)
<add> return description
<ide><path>tests/providers/google/cloud/hooks/test_bigquery.py
<ide> BigQueryHook,
<ide> _api_resource_configs_duplication_check,
<ide> _cleanse_time_partitioning,
<add> _format_schema_for_description,
<ide> _validate_src_fmt_configs,
<ide> _validate_value,
<ide> split_tablename,
<ide> def test_execute_many(self, mock_insert, _):
<ide> ]
<ide> )
<ide>
<add> def test_format_schema_for_description(self):
<add> test_query_result = {
<add> "schema": {
<add> "fields": [
<add> {"name": "field_1", "type": "STRING", "mode": "NULLABLE"},
<add> ]
<add> },
<add> }
<add> description = _format_schema_for_description(test_query_result["schema"])
<add> assert description == [('field_1', 'STRING', None, None, None, None, True)]
<add>
<ide> @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
<del> def test_description(self, mock_get_service):
<add> @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
<add> def test_description(self, mock_insert, mock_get_service):
<add> mock_get_query_results = mock_get_service.return_value.jobs.return_value.getQueryResults
<add> mock_execute = mock_get_query_results.return_value.execute
<add> mock_execute.return_value = {
<add> "schema": {
<add> "fields": [
<add> {"name": "ts", "type": "TIMESTAMP", "mode": "NULLABLE"},
<add> ]
<add> },
<add> }
<add>
<ide> bq_cursor = self.hook.get_cursor()
<del> with pytest.raises(NotImplementedError):
<del> bq_cursor.description
<add> bq_cursor.execute("SELECT CURRENT_TIMESTAMP() as ts")
<add> assert bq_cursor.description == [("ts", "TIMESTAMP", None, None, None, None, True)]
<ide>
<ide> @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
<ide> def test_close(self, mock_get_service): | 2 |
Javascript | Javascript | fix url in _http-benchmarkers.js | a3778cb9b1fcd91d06a449af5f6bd166f3d36bee | <ide><path>benchmark/_http-benchmarkers.js
<ide> const path = require('path');
<ide> const fs = require('fs');
<ide>
<ide> const requirementsURL =
<del> 'https://github.com/nodejs/node/blob/master/doc/guides/writing-and-running-benchmarks.md##http-benchmark-requirements';
<add> 'https://github.com/nodejs/node/blob/master/doc/guides/writing-and-running-benchmarks.md#http-benchmark-requirements';
<ide>
<ide> // The port used by servers and wrk
<ide> exports.PORT = process.env.PORT || 12346; | 1 |
Text | Text | fix examples in buffer.md to avoid confusion | 0d0028935b136d80bf137962159ddde74337edf5 | <ide><path>doc/api/buffer.md
<del># Buffer
<add># Buffer
<ide>
<ide> > Stability: 2 - Stable
<ide>
<ide> are unknown and *could contain sensitive data*. Use
<ide> Example:
<ide>
<ide> ```js
<del>const buf = new Buffer(5);
<add>const buf = new Buffer(10);
<ide>
<del>// Prints: (contents may vary): <Buffer 78 e0 82 02 01>
<add>// Prints: (contents may vary): <Buffer 48 21 4b 00 00 00 00 00 30 dd>
<ide> console.log(buf);
<ide>
<ide> buf.fill(0);
<ide>
<del>// Prints: <Buffer 00 00 00 00 00>
<add>// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
<ide> console.log(buf);
<ide> ```
<ide>
<ide> initialized*. The contents of the newly created `Buffer` are unknown and
<ide> Example:
<ide>
<ide> ```js
<del>const buf = Buffer.allocUnsafe(5);
<add>const buf = Buffer.allocUnsafe(10);
<ide>
<del>// Prints: (contents may vary): <Buffer 78 e0 82 02 01>
<add>// Prints: (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
<ide> console.log(buf);
<ide>
<ide> buf.fill(0);
<ide>
<del>// Prints: <Buffer 00 00 00 00 00>
<add>// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
<ide> console.log(buf);
<ide> ```
<ide> | 1 |
Javascript | Javascript | use different tmpdir | 8cd3a38fd4870faa4b86498230c4ff6526d270e5 | <ide><path>packager/blacklist.js
<ide> var path = require('path');
<ide> // Don't forget to everything listed here to `package.json`
<ide> // modulePathIgnorePatterns.
<ide> var sharedBlacklist = [
<del> /js\/tmp\/.*/,
<ide> /node_modules[/\\]react[/\\]dist[/\\].*/,
<ide> 'node_modules/react/lib/React.js',
<ide> 'node_modules/react/lib/ReactDOM.js', | 1 |
Javascript | Javascript | add guard to originalconsole | 54d331895c721fa85dc0ee237a3bbc04da3a324d | <ide><path>lib/internal/bootstrap_node.js
<ide> enumerable: true,
<ide> get: function() {
<ide> if (!console) {
<del> console = installInspectorConsole(originalConsole);
<add> console = originalConsole === undefined ?
<add> NativeModule.require('console') :
<add> installInspectorConsole(originalConsole);
<ide> }
<ide> return console;
<ide> } | 1 |
Python | Python | fix warning in ``test_get_sync_subtask_option``. | 69093e535b9f05b34af7b88eec3ce238ad202ed2 | <ide><path>t/unit/tasks/test_result.py
<ide> def add_pending_result(self, *args, **kwargs):
<ide> def wait_for_pending(self, *args, **kwargs):
<ide> return True
<ide>
<add> def remove_pending_result(self, *args, **kwargs):
<add> return True
<add>
<ide>
<ide> class test_AsyncResult:
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.