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
Ruby
Ruby
remove unused variable
584ebed482907abb3b18c65495cd62fe5f643a89
<ide><path>actionpack/lib/action_view/helpers/form_options_helper.rb <ide> def grouped_options_for_select(grouped_options, selected_key = nil, options = {} <ide> divider = options[:divider] <ide> else <ide> prompt = options <del> options = {} <ide> message = "Passing the prompt to grouped_options_for_select as an argument is deprecated. " \ <ide> "Please use an options hash like `{ prompt: #{prompt.inspect} }`." <ide> ActiveSupport::Deprecation.warn message
1
Python
Python
rewrite tensorflow train_step and test_step
349f1c85d35167c3a416a19ca869358c8e0e4b0c
<ide><path>src/transformers/modeling_tf_utils.py <ide> class TFPreTrainedModel(tf.keras.Model, TFModelUtilsMixin, TFGenerationMixin, Pu <ide> main_input_name = "input_ids" <ide> _auto_class = None <ide> _using_dummy_loss = None <add> _label_to_output_map = None <ide> <ide> # a list of re pattern of tensor names to ignore from the model when loading the model weights <ide> # (and avoid unnecessary warnings). <ide> def compile( <ide> function themselves. <ide> """ <ide> if loss == "passthrough": <del> if metrics is not None: <del> raise ValueError( <del> "Passing metrics as a dict is not supported when using the internal loss! " <del> "Please either compile the model with a loss, or remove the metrics argument. " <del> "Note that advanced metrics using the `KerasMetricCallback` can still be used with the internal " <del> "loss." <del> ) <ide> logger.warning( <ide> "No loss specified in compile() - the model's internal loss computation will be used as the " <ide> "loss. Don't panic - this is a common way to train TensorFlow models in Transformers! " <del> "To disable this behaviour, please pass a loss argument, or explicitly pass " <add> "To disable this behaviour please pass a loss argument, or explicitly pass " <ide> "`loss=None` if you do not want your model to compute a loss." <ide> ) <ide> loss = dummy_loss <ide> self._using_dummy_loss = True <ide> else: <ide> self._using_dummy_loss = False <ide> parent_args = list(inspect.signature(tf.keras.Model.compile).parameters.keys()) <add> # This argument got renamed, we need to support both versions <ide> if "steps_per_execution" in parent_args: <ide> super().compile( <ide> optimizer=optimizer, <ide> def compute_loss(self, *args, **kwargs): <ide> ) <ide> return self.hf_compute_loss(*args, **kwargs) <ide> <add> def get_label_to_output_name_mapping(self): <add> arg_names = list(dict(inspect.signature(self.call).parameters).keys()) <add> if self._label_to_output_map is not None: <add> return self._label_to_output_map <add> elif "start_positions" in arg_names: <add> return {"start_positions": "start_logits", "end_positions": "end_logits"} <add> elif "sentence_order_label" in arg_names: <add> return {"labels": "prediction_logits", "sentence_order_label": "sop_logits"} <add> elif "next_sentence_label" in arg_names: <add> return {"labels": "prediction_logits", "next_sentence_label": "seq_relationship_logits"} <add> elif "mc_labels" in arg_names: <add> return {"labels": "logits", "mc_labels": "mc_logits"} <add> else: <add> return dict() <add> <ide> def train_step(self, data): <ide> """ <del> A modification of Keras's default `train_step` that cleans up the printed metrics when we use a dummy loss. If <del> a user specifies a loss at model compile time, this function behaves as the original Keras `train_step`. <del> <del> When the model is compiled without specifying the loss, our overridden compile function can set a simple dummy <del> loss that just reads the loss output head of the model. When using this dummy loss, inputs can be passed either <del> as keys in the input dictionary, or as normal Keras labels. <add> A modification of Keras's default `train_step` that correctly handles matching outputs to labels for our models <add> and supports directly training on the loss output head. In addition, it ensures input keys are copied to the <add> labels where appropriate. It will also copy label keys into the input dict when using the dummy loss, to ensure <add> that they are available to the model during the forward pass. <ide> """ <ide> <del> # These are the only transformations `Model.fit` applies to user-input <del> # data when a `tf.data.Dataset` is provided. <add> # We hardcode the most common renamings; models with weirder names can set `self._label_to_output_map` <add> arg_names = list(dict(inspect.signature(self.call).parameters).keys()) <add> label_kwargs = find_labels(self.__class__) <add> label_to_output = self.get_label_to_output_name_mapping() <add> output_to_label = {val: key for key, val in label_to_output.items()} <ide> if not self._using_dummy_loss: <ide> data = data_adapter.expand_1d(data) <ide> x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data) <ide> <ide> # When using a dummy loss, we ensure that separate labels are copied to the correct model arguments, <ide> # if those keys are not already present in the input dict <ide> if self._using_dummy_loss and y is not None: <del> arg_names = list(dict(inspect.signature(self.call).parameters).keys()) <del> label_kwargs = find_labels(self.__class__) <add> <ide> # If y is a tensor and the model only has one label-like input, map y to that input <ide> if len(label_kwargs) == 1 and isinstance(y, tf.Tensor): <ide> if isinstance(x, tf.Tensor): <ide> def train_step(self, data): <ide> for key, val in y.items(): <ide> if key in arg_names and key not in x: <ide> x[key] = val <add> elif output_to_label.get(key, None) in arg_names and key not in x: <add> x[output_to_label[key]] = val <add> if y is None: <add> y = {key: val for key, val in x.items() if key in label_kwargs} <add> if not y and not self._using_dummy_loss: <add> raise ValueError("Could not find label column(s) in input dict and no separate labels were provided!") <add> <add> if isinstance(y, dict): <add> # Rename labels at this point to match output heads <add> y = {label_to_output.get(key, key): val for key, val in y.items()} <ide> <ide> # Run forward pass. <ide> with tf.GradientTape() as tape: <ide> y_pred = self(x, training=True) <ide> if self._using_dummy_loss: <ide> loss = self.compiled_loss(y_pred.loss, y_pred.loss, sample_weight, regularization_losses=self.losses) <ide> else: <add> loss = None <add> <add> # This next block matches outputs to label keys. Tensorflow's standard method for doing this <add> # can get very confused if any of the keys contain nested values (e.g. lists/tuples of Tensors) <add> if isinstance(y, dict) and len(y) == 1: <add> if list(y.keys())[0] in y_pred.keys(): <add> y_pred = y_pred[list(y.keys())[0]] <add> elif list(y_pred.keys())[0] == "loss": <add> y_pred = y_pred[1] <add> else: <add> y_pred = y_pred[0] <add> _, y = y.popitem() <add> elif isinstance(y, dict): <add> # If the labels are a dict, match keys from the output by name <add> y_pred = {key: val for key, val in y_pred.items() if key in y} <add> elif isinstance(y, tuple) or isinstance(y, list): <add> # If the labels are a tuple/list, match keys to the output by order, skipping the loss. <add> if list(y_pred.keys())[0] == "loss": <add> y_pred = y_pred.to_tuple()[1:] <add> else: <add> y_pred = y_pred.to_tuple() <add> y_pred = y_pred[: len(y)] # Remove unused fields in case those cause problems <add> else: <add> # If the labels are a single tensor, match them to the first non-loss tensor in the output <add> if list(y_pred.keys())[0] == "loss": <add> y_pred = y_pred[1] <add> else: <add> y_pred = y_pred[0] <add> <add> if loss is None: <ide> loss = self.compiled_loss(y, y_pred, sample_weight, regularization_losses=self.losses) <add> <ide> # Run backwards pass. <ide> self.optimizer.minimize(loss, self.trainable_variables, tape=tape) <ide> <del> # When using the dummy_loss we know metrics are not present, so we can skip a lot of this <del> if self._using_dummy_loss: <del> self.compiled_metrics.update_state(y_pred.loss, y_pred.loss, sample_weight) <del> else: <del> self.compiled_metrics.update_state(y, y_pred, sample_weight) <add> self.compiled_metrics.update_state(y, y_pred, sample_weight) <ide> # Collect metrics to return <ide> return_metrics = {} <ide> for metric in self.metrics: <ide> def train_step(self, data): <ide> return_metrics.update(result) <ide> else: <ide> return_metrics[metric.name] = result <del> # These next two lines are also not in the base method - they correct the displayed metrics <del> # when we're using a dummy loss, to avoid a bogus "loss_loss" value being shown. <del> if "loss" in return_metrics and "loss_loss" in return_metrics: <del> del return_metrics["loss_loss"] <ide> return return_metrics <ide> <ide> def test_step(self, data): <ide> """ <del> A modification of Keras's default `test_step` that cleans up the printed metrics when we use a dummy loss. If a <del> user specifies a loss at model compile time, this function behaves as the original Keras `test_step`. <del> <del> When the model is compiled without specifying the loss, our overridden compile function can set a simple dummy <del> loss that just reads the loss output head of the model. When using this dummy loss, inputs can be passed either <del> as keys in the input dictionary, or as normal Keras labels. <add> A modification of Keras's default `train_step` that correctly handles matching outputs to labels for our models <add> and supports directly training on the loss output head. In addition, it ensures input keys are copied to the <add> labels where appropriate. It will also copy label keys into the input dict when using the dummy loss, to ensure <add> that they are available to the model during the forward pass. <ide> """ <del> # These are the only transformations `Model.fit` applies to user-input <del> # data when a `tf.data.Dataset` is provided. <add> # We hardcode the most common renamings; models with weirder names can set `self._label_to_output_map` <add> arg_names = list(dict(inspect.signature(self.call).parameters).keys()) <add> label_kwargs = find_labels(self.__class__) <add> label_to_output = self.get_label_to_output_name_mapping() <add> output_to_label = {val: key for key, val in label_to_output.items()} <ide> if not self._using_dummy_loss: <ide> data = data_adapter.expand_1d(data) <ide> x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data) <ide> def test_step(self, data): <ide> # if those keys are not already present in the input dict <ide> if self._using_dummy_loss and y is not None: <ide> arg_names = list(dict(inspect.signature(self.call).parameters).keys()) <del> label_kwargs = find_labels(self.__class__) <ide> # If y is a tensor and the model only has one label-like input, map y to that input <ide> if len(label_kwargs) == 1 and isinstance(y, tf.Tensor): <ide> if isinstance(x, tf.Tensor): <ide> def test_step(self, data): <ide> for key, val in y.items(): <ide> if key in arg_names and key not in x: <ide> x[key] = val <add> elif output_to_label.get(key, None) in arg_names and key not in x: <add> x[output_to_label[key]] = val <add> if y is None: <add> y = {key: val for key, val in x.items() if key in label_kwargs} <add> if not y and not self._using_dummy_loss: <add> raise ValueError("Could not find label column(s) in input dict and no separate labels were provided!") <add> <add> if isinstance(y, dict): <add> # Rename labels at this point to match output heads <add> y = {label_to_output.get(key, key): val for key, val in y.items()} <ide> <ide> # Run forward pass. <ide> y_pred = self(x, training=False) <ide> if self._using_dummy_loss: <del> self.compiled_loss(y_pred.loss, y_pred.loss, sample_weight, regularization_losses=self.losses) <add> loss = self.compiled_loss(y_pred.loss, y_pred.loss, sample_weight, regularization_losses=self.losses) <ide> else: <del> self.compiled_loss(y, y_pred, sample_weight, regularization_losses=self.losses) <del> <del> # When using the dummy_loss we know metrics are not present, so we can skip a lot of this <del> if self._using_dummy_loss: <del> self.compiled_metrics.update_state(y_pred.loss, y_pred.loss, sample_weight) <add> loss = None <add> <add> # This next block matches outputs to label keys. Tensorflow's standard method for doing this <add> # can get very confused if any of the keys contain nested values (e.g. lists/tuples of Tensors) <add> if isinstance(y, dict) and len(y) == 1: <add> if list(y.keys())[0] in y_pred.keys(): <add> y_pred = y_pred[list(y.keys())[0]] <add> elif list(y_pred.keys())[0] == "loss": <add> y_pred = y_pred[1] <add> else: <add> y_pred = y_pred[0] <add> _, y = y.popitem() <add> elif isinstance(y, dict): <add> # If the labels are a dict, match keys from the output by name <add> y_pred = {key: val for key, val in y_pred.items() if key in y} <add> elif isinstance(y, tuple) or isinstance(y, list): <add> # If the labels are a tuple/list, match keys to the output by order, skipping the loss. <add> if list(y_pred.keys())[0] == "loss": <add> y_pred = y_pred.to_tuple()[1:] <add> else: <add> y_pred = y_pred.to_tuple() <add> y_pred = y_pred[: len(y)] # Remove unused fields in case those cause problems <ide> else: <del> self.compiled_metrics.update_state(y, y_pred, sample_weight) <add> # If the labels are a single tensor, match them to the first non-loss tensor in the output <add> if list(y_pred.keys())[0] == "loss": <add> y_pred = y_pred[1] <add> else: <add> y_pred = y_pred[0] <add> <add> if loss is None: <add> loss = self.compiled_loss(y, y_pred, sample_weight, regularization_losses=self.losses) <add> <add> self.compiled_metrics.update_state(y, y_pred, sample_weight) <ide> # Collect metrics to return <ide> return_metrics = {} <ide> for metric in self.metrics: <ide> def test_step(self, data): <ide> return_metrics.update(result) <ide> else: <ide> return_metrics[metric.name] = result <del> # These next two lines are also not in the base method - they correct the displayed metrics <del> # when we're using a dummy loss, to avoid a bogus "loss_loss" value being shown. <del> if "loss" in return_metrics and "loss_loss" in return_metrics: <del> del return_metrics["loss_loss"] <ide> return return_metrics <ide> <ide> def create_model_card( <ide><path>tests/test_modeling_tf_common.py <ide> def test_keras_fit(self): <ide> labels = {key: val for key, val in prepared_for_class.items() if key in label_names} <ide> inputs_minus_labels = {key: val for key, val in prepared_for_class.items() if key not in label_names} <ide> self.assertGreater(len(inputs_minus_labels), 0) <del> model.compile(optimizer=tf.keras.optimizers.SGD(0.0), run_eagerly=True) <add> accuracy_classes = [ <add> "ForPreTraining", <add> "ForCausalLM", <add> "ForMaskedLM", <add> "ForQuestionAnswering", <add> "ForMultipleChoice", <add> "ForSequenceClassification", <add> "ForTokenClassification", <add> "ForNextSentencePrediction", <add> "LMHeadModel", <add> ] <add> for accuracy_class in accuracy_classes: <add> if model.__class__.__name__.endswith(accuracy_class): <add> metrics = [tf.keras.metrics.SparseCategoricalAccuracy()] <add> break <add> else: <add> metrics = [] <add> <add> model.compile(optimizer=tf.keras.optimizers.SGD(0.0), run_eagerly=True, metrics=metrics) <ide> # Make sure the model fits without crashing regardless of where we pass the labels <ide> history1 = model.fit( <ide> prepared_for_class, <ide> def test_keras_fit(self): <ide> shuffle=False, <ide> ) <ide> val_loss1 = history1.history["val_loss"][0] <add> accuracy1 = {key: val[0] for key, val in history1.history.items() if key.endswith("accuracy")} <ide> history2 = model.fit( <ide> inputs_minus_labels, <ide> labels, <ide> def test_keras_fit(self): <ide> shuffle=False, <ide> ) <ide> val_loss2 = history2.history["val_loss"][0] <add> accuracy2 = {key: val[0] for key, val in history1.history.items() if key.endswith("accuracy")} <ide> self.assertTrue(np.allclose(val_loss1, val_loss2, atol=1e-2, rtol=1e-3)) <add> self.assertEqual(history1.history.keys(), history2.history.keys()) <add> for key in history1.history.keys(): <add> if not key.startswith("val_"): <add> self.assertTrue("val_" + key in history1.history.keys(), "Outputs differ in train/test step!") <add> if metrics: <add> self.assertTrue(len(accuracy1) == len(accuracy2) > 0, "Missing metrics!") <ide> <ide> def test_int64_inputs(self): <ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
2
Python
Python
fix a typo
77ce4470311e8f8094b8a06f21fded80dc5c57da
<ide><path>libcloud/compute/drivers/openstack.py <ide> def create_node(self, **kwargs): <ide> <ide> <ide> :keyword networks: The server is launched into a set of Networks. <del> :type networks: :class:`OpenStackNetwork` <add> :type networks: ``list`` of :class:`OpenStackNetwork` <ide> <ide> :keyword ex_disk_config: Name of the disk configuration. <ide> Can be either ``AUTO`` or ``MANUAL``.
1
Text
Text
add daeyeon to triagers
9fa110087b5bdc306955cbaa0e14ec6e1695238f
<ide><path>README.md <ide> maintaining the Node.js project. <ide> <ide> * [Ayase-252](https://github.com/Ayase-252) - <ide> **Qingyu Deng** <<i@ayase-lab.com>> <add>* [daeyeon](https://github.com/daeyeon) - <add> **Daeyeon Jeong** <<daeyeon.dev@gmail.com>> (he/him) <ide> * [F3n67u](https://github.com/F3n67u) - <ide> **Feng Yu** <<F3n67u@outlook.com>> (he/him) <ide> * [himadriganguly](https://github.com/himadriganguly) -
1
Python
Python
update lexeme ranks for loaded vectors
0e4b96c97e1959e7c78d0c35063ff021f2189f82
<ide><path>spacy/training/initialize.py <ide> def load_vectors_into_model( <ide> logger.warning(Warnings.W112.format(name=name)) <ide> <ide> nlp.vocab.vectors = vectors_nlp.vocab.vectors <add> for lex in nlp.vocab: <add> lex.rank = nlp.vocab.vectors.key2row.get(lex.orth, OOV_RANK) <ide> if add_strings: <ide> # I guess we should add the strings from the vectors_nlp model? <ide> # E.g. if someone does a similarity query, they might expect the strings.
1
Python
Python
improve docstrings for various modules
53796988929d7b5de98cd322fdea9e0a8edec0a1
<ide><path>airflow/operators/sql.py <ide> class SQLIntervalCheckOperator(BaseSQLOperator): <ide> :type table: str <ide> :param conn_id: the connection ID used to connect to the database. <ide> :type conn_id: str <del> :param database: name of database which overwrite the defined one in connection <del> :type database: str <add> :param database: name of database which will overwrite the defined one in connection <add> :type database: Optional[str] <ide> :param days_back: number of days between ds and the ds we want to check <ide> against. Defaults to 7 days <del> :type days_back: int <add> :type days_back: Optional[int] <add> :param date_filter_column: The column name for the dates to filter on. Defaults to 'ds' <add> :type date_filter_column: Optional[str] <ide> :param ratio_formula: which formula to use to compute the ratio between <ide> the two metrics. Assuming cur is the metric of today and ref is <ide> the metric to today - days_back. <ide> class SQLIntervalCheckOperator(BaseSQLOperator): <ide> :type ratio_formula: str <ide> :param ignore_zero: whether we should ignore zero metrics <ide> :type ignore_zero: bool <del> :param metrics_threshold: a dictionary of ratios indexed by metrics <del> :type metrics_threshold: dict <add> :param metrics_thresholds: a dictionary of ratios indexed by metrics <add> :type metrics_thresholds: dict <ide> """ <ide> <ide> __mapper_args__ = {"polymorphic_identity": "SQLIntervalCheckOperator"} <ide><path>airflow/providers/amazon/aws/hooks/datasync.py <ide> class AWSDataSyncHook(AwsBaseHook): <ide> :class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` <ide> :class:`~airflow.providers.amazon.aws.operators.datasync.AWSDataSyncOperator` <ide> <del> :param int wait_for_task_execution: Time to wait between two <del> consecutive calls to check TaskExecution status. <add> :param wait_interval_seconds: Time to wait between two <add> consecutive calls to check TaskExecution status. Defaults to 5 seconds. <add> :type wait_interval_seconds: Optional[int] <ide> :raises ValueError: If wait_interval_seconds is not between 0 and 15*60 seconds. <ide> """ <ide> <ide><path>airflow/providers/amazon/aws/operators/emr_create_job_flow.py <ide> class EmrCreateJobFlowOperator(BaseOperator): <ide> :param job_flow_overrides: boto3 style arguments or reference to an arguments file <ide> (must be '.json') to override emr_connection extra. (templated) <ide> :type job_flow_overrides: dict|str <add> :param region_name: Region named passed to EmrHook <add> :type region_name: Optional[str] <ide> """ <ide> <ide> template_fields = ['job_flow_overrides'] <ide><path>airflow/providers/google/ads/operators/ads.py <ide> class GoogleAdsListAccountsOperator(BaseOperator): <ide> not necessarily include all accounts within the account hierarchy; rather, it will only include <ide> accounts where your authenticated user has been added with admin or other rights in the account. <ide> <del> ..seealso:: <add> .. seealso:: <ide> https://developers.google.com/google-ads/api/reference/rpc <ide> <ide> <ide> class GoogleAdsListAccountsOperator(BaseOperator): <ide> :type gcp_conn_id: str <ide> :param google_ads_conn_id: Airflow Google Ads connection ID <ide> :type google_ads_conn_id: str <del> :param page_size: The number of results per API page request. Max 10,000 <del> :type page_size: int <ide> :param gzip: Option to compress local file or file data for upload <ide> :type gzip: bool <ide> :param impersonation_chain: Optional service account to impersonate using short-term
4
PHP
PHP
fix code style;
d410a6bf3f279b5e766d6d7c2a7bb49fb93c88d9
<ide><path>tests/Http/HttpRequestTest.php <ide> public function testMagicMethods() <ide> $this->assertEquals(empty($request->undefined), true); <ide> <ide> // Simulates Route parameters. <del> $request = Request::create('/example/bar', 'GET', [ 'xyz' => 'overwrited' ]); <add> $request = Request::create('/example/bar', 'GET', ['xyz' => 'overwrited']); <ide> $request->setRouteResolver(function () use ($request) { <ide> $route = new Route('GET', '/example/{foo}/{xyz?}/{undefined?}', []); <ide> $route->bind($request);
1
Ruby
Ruby
remove deprecated formatted named routes
bd729344a7ac747cccaeed983d435fc36c905683
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def #{selector}(*args) # <ide> url_for(#{hash_access_method}(opts)) # url_for(hash_for_users_url(opts)) <ide> # <ide> end # end <del> #Add an alias to support the now deprecated formatted_* URL. # #Add an alias to support the now deprecated formatted_* URL. <del> def formatted_#{selector}(*args) # def formatted_users_url(*args) <del> ActiveSupport::Deprecation.warn( # ActiveSupport::Deprecation.warn( <del> "formatted_#{selector}() has been deprecated. " + # "formatted_users_url() has been deprecated. " + <del> "Please pass format to the standard " + # "Please pass format to the standard " + <del> "#{selector} method instead.", caller) # "users_url method instead.", caller) <del> #{selector}(*args) # users_url(*args) <del> end # end <ide> protected :#{selector} # protected :users_url <ide> end_eval <ide> helpers << selector <ide><path>actionpack/test/controller/url_rewriter_test.rb <ide> def test_named_routes_with_nil_keys <ide> end <ide> end <ide> <del> def test_formatted_url_methods_are_deprecated <del> with_routing do |set| <del> set.draw do |map| <del> resources :posts <del> end <del> # We need to create a new class in order to install the new named route. <del> kls = Class.new { include ActionController::UrlWriter } <del> controller = kls.new <del> params = {:id => 1, :format => :xml} <del> assert_deprecated do <del> assert_equal("/posts/1.xml", controller.send(:formatted_post_path, params)) <del> end <del> assert_deprecated do <del> assert_equal("/posts/1.xml", controller.send(:formatted_post_path, 1, :xml)) <del> end <del> end <del> end <del> <ide> def test_multiple_includes_maintain_distinct_options <ide> first_class = Class.new { include ActionController::UrlWriter } <ide> second_class = Class.new { include ActionController::UrlWriter }
2
Text
Text
fix "introduction" link of readme.md
4222b0e2be92395b75f27bea97789a779a8cde05
<ide><path>README.md <ide> Redux co-maintainer [Mark Erikson](https://twitter.com/acemarke) has put togethe <ide> <ide> ## Documentation <ide> <del>- [Introduction](http://redux.js.org/introduction) <add>- [Introduction](http://redux.js.org/introduction/getting-started) <ide> - [Basics](http://redux.js.org/basics/basic-tutorial) <ide> - [Advanced](http://redux.js.org/advanced/advanced-tutorial) <ide> - [Recipes](http://redux.js.org/recipes/recipe-index)
1
Python
Python
remove unnecessary argument
f74a45c1fe54b4a63c17626baf5572377d179410
<ide><path>spacy/tests/serialize/test_serialize_tagger.py <ide> <ide> @pytest.fixture <ide> def taggers(en_vocab): <del> tagger1 = Tagger(en_vocab, True) <del> tagger2 = Tagger(en_vocab, True) <add> tagger1 = Tagger(en_vocab) <add> tagger2 = Tagger(en_vocab) <ide> tagger1.model = tagger1.Model(None, None) <ide> tagger2.model = tagger2.Model(None, None) <ide> return (tagger1, tagger2)
1
Ruby
Ruby
remove explicit tmpdir deletions
1aee7c6945c3cbbbbfa2830bb1cf6bf39d4702be
<ide><path>Library/Homebrew/test/audit_test.rb <ide> def setup <ide> @dir = mktmpdir <ide> end <ide> <del> def teardown <del> FileUtils.rm_rf @dir <del> super <del> end <del> <ide> def formula_text(name, body = nil, options = {}) <ide> path = Pathname.new "#{@dir}/#{name}.rb" <ide> path.open("w") do |f| <ide> def setup <ide> @dir = mktmpdir <ide> end <ide> <del> def teardown <del> FileUtils.rm_rf @dir <del> super <del> end <del> <ide> def formula_auditor(name, text, options = {}) <ide> path = Pathname.new "#{@dir}/#{name}.rb" <ide> path.open("w") do |f| <ide><path>Library/Homebrew/test/language_python_test.rb <ide> def setup <ide> @venv = Language::Python::Virtualenv::Virtualenv.new(@formula, @dir, "python") <ide> end <ide> <del> def teardown <del> FileUtils.rm_rf @dir <del> super <del> end <del> <ide> def test_virtualenv_creation <ide> @formula.expects(:resource).with("homebrew-virtualenv").returns( <ide> mock("resource", stage: true) <ide><path>Library/Homebrew/test/pathname_test.rb <ide> def setup <ide> @file = @src/"foo" <ide> @dir = @src/"bar" <ide> end <del> <del> def teardown <del> rmtree(@src) <del> rmtree(@dst) <del> super <del> end <ide> end <ide> <ide> class PathnameTests < Homebrew::TestCase <ide><path>Library/Homebrew/test/sandbox_test.rb <ide> def setup <ide> @file = @dir/"foo" <ide> end <ide> <del> def teardown <del> @dir.rmtree <del> super <del> end <del> <ide> def test_formula? <ide> f = formula { url "foo-1.0" } <ide> f2 = formula { url "bar-1.0" } <ide><path>Library/Homebrew/test/utils_test.rb <ide> def setup <ide> end <ide> <ide> def teardown <del> @dir.rmtree <ide> ENV.replace @env <ide> super <ide> end
5
Text
Text
use uuid method to define the uuid type [ci skip]
c0747e2f39a1c040c50e63fb41e23dfa6e30f2fc
<ide><path>guides/source/active_record_postgresql.md <ide> extension to use uuid. <ide> ```ruby <ide> # db/migrate/20131220144913_create_revisions.rb <ide> create_table :revisions do |t| <del> t.column :identifier, :uuid <add> t.uuid :identifier <ide> end <ide> <ide> # app/models/revision.rb
1
Text
Text
fix v8.6 changelog entry
f55005514c350bbcba77b9664140e1518d7586a7
<ide><path>doc/changelogs/CHANGELOG_V8.md <ide> * [[`9e8b1b3ec6`](https://github.com/nodejs/node/commit/9e8b1b3ec6)] - **util**: refactor inspect for performance and more (Ruben Bridgewater) [#14881](https://github.com/nodejs/node/pull/14881) <ide> * [[`539445890b`](https://github.com/nodejs/node/commit/539445890b)] - **util**: add fast internal array join method (Ruben Bridgewater) [#14881](https://github.com/nodejs/node/pull/14881) <ide> * [[`7d95dc385c`](https://github.com/nodejs/node/commit/7d95dc385c)] - **vm**: support parsing a script in a specific context (Timothy Gu) [#14888](https://github.com/nodejs/node/pull/14888) <del>james@ubuntu:~/node/main$ <ide> <ide> <a id="8.5.0"></a> <ide> ## 2017-09-12, Version 8.5.0 (Current), @MylesBorins
1
Ruby
Ruby
move #encode_with to relation
ef8cae60ee330f760e35f7c2ed9497b6918587f9
<ide><path>activerecord/lib/active_record/relation.rb <ide> def to_a <ide> @records <ide> end <ide> <add> # Serializes the relation objects Array. <add> def encode_with(coder) <add> coder.represent_seq(nil, to_a) <add> end <add> <ide> def as_json(options = nil) #:nodoc: <ide> to_a.as_json(options) <ide> end <ide><path>activerecord/lib/active_record/relation/delegation.rb <ide> def respond_to?(method, include_private = false) <ide> arel.respond_to?(method, include_private) <ide> end <ide> <del> def encode_with(coder) <del> coder.represent_seq(nil, to_a) <del> end <del> <ide> protected <ide> <ide> def array_delegable?(method)
2
Ruby
Ruby
fix wrong test description and failure message
2242317fddaec2d2cca5103b4f79f71d73d25b31
<ide><path>activemodel/test/cases/validations/validations_context_test.rb <ide> def validate(record) <ide> end <ide> end <ide> <del> test "with a class that adds errors on update and validating a new model with no arguments" do <add> test "with a class that adds errors on create and validating a new model with no arguments" do <ide> Topic.validates_with(ValidatorThatAddsErrors, :on => :create) <ide> topic = Topic.new <del> assert topic.valid?, "Validation doesn't run on create if 'on' is set to update" <add> assert topic.valid?, "Validation doesn't run on valid? if 'on' is set to create" <ide> end <ide> <ide> test "with a class that adds errors on update and validating a new model" do
1
Javascript
Javascript
add test for url
abb0bdd53fa6d831de43119fb1d5560afc495677
<ide><path>test/parallel/test-url-relative.js <ide> const assert = require('assert'); <ide> const inspect = require('util').inspect; <ide> const url = require('url'); <ide> <add>// when source is false <add>assert.strictEqual(url.resolveObject('', 'foo'), 'foo'); <add> <ide> /* <ide> [from, path, expected] <ide> */
1
Javascript
Javascript
support cyclic object references in error messages
fa12c3c86af7965d1b9d9a5dd3434755e9e04635
<ide><path>src/ng/directive/ngRepeat.js <ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { <ide> }); <ide> throw ngRepeatMinErr('dupes', <ide> "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}", <del> expression, trackById, toJson(value)); <add> expression, trackById, value); <ide> } else { <ide> // new never before seen block <ide> nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
1
Javascript
Javascript
fix description for `rewritelinks`
a4db4e618779609003abe3957749732d02782561
<ide><path>src/ng/location.js <ide> function $LocationProvider(){ <ide> * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are <ide> * true, and a base tag is not present, an error will be thrown when `$location` is injected. <ide> * See the {@link guide/$location $location guide for more information} <del> * - **rewriteLinks** - `{boolean}` - (default: `false`) When html5Mode is enabled, disables <del> * url rewriting for relative linksTurns off url rewriting for relative links. <add> * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled, <add> * enables/disables url rewriting for relative links. <ide> * <ide> * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter <ide> */
1
Text
Text
make minor improvements to fs.realpath() docs
89d211f54acea642cce65be731f4878555283ff0
<ide><path>doc/api/fs.md <ide> changes: <ide> Asynchronously computes the canonical pathname by resolving `.`, `..` and <ide> symbolic links. <ide> <del>Note that "canonical" does not mean "unique": hard links and bind mounts can <add>A canonical pathname is not necessarily unique. Hard links and bind mounts can <ide> expose a file system entity through many pathnames. <ide> <ide> This function behaves like realpath(3), with some exceptions: <ide> changes: <ide> * `encoding` {string} **Default:** `'utf8'` <ide> * Returns: {string|Buffer} <ide> <del>Synchronously computes the canonical pathname by resolving `.`, `..` and <del>symbolic links. <del> <del>Note that "canonical" does not mean "unique": hard links and bind mounts can <del>expose a file system entity through many pathnames. <del> <del>This function behaves like realpath(3), with some exceptions: <del> <del>1. No case conversion is performed on case-insensitive file systems. <del> <del>2. The maximum number of symbolic links is platform-independent and generally <del> (much) higher than what the native realpath(3) implementation supports. <del> <del>The optional `options` argument can be a string specifying an encoding, or an <del>object with an `encoding` property specifying the character encoding to use for <del>the returned value. If the `encoding` is set to `'buffer'`, the path returned <del>will be passed as a `Buffer` object. <del> <del>If `path` resolves to a socket or a pipe, the function will return a system <del>dependent name for that object. <add>Synchronous version of [`fs.realpath()`][]. Returns the resolved pathname. <ide> <ide> ## fs.realpathSync.native(path[, options]) <ide> <!-- YAML <ide> the file contents. <ide> [`fs.read()`]: #fs_fs_read_fd_buffer_offset_length_position_callback <ide> [`fs.readFile()`]: #fs_fs_readfile_path_options_callback <ide> [`fs.readFileSync()`]: #fs_fs_readfilesync_path_options <add>[`fs.realpath()`]: #fs_fs_realpath_path_options_callback <ide> [`fs.rmdir()`]: #fs_fs_rmdir_path_callback <ide> [`fs.stat()`]: #fs_fs_stat_path_callback <ide> [`fs.utimes()`]: #fs_fs_utimes_path_atime_mtime_callback
1
Python
Python
fix escape sequence
817b0db52132d3a1060e7876f1894554da783673
<ide><path>spacy/lang/lt/punctuation.py <ide> ) <ide> <ide> <del>_suffixes = ["\."] + list(TOKENIZER_SUFFIXES) <add>_suffixes = [r"\."] + list(TOKENIZER_SUFFIXES) <ide> <ide> <ide> TOKENIZER_INFIXES = _infixes
1
Mixed
Go
add new `hostconfig` field, `mounts`
fc7b904dced4d18d49c8a6c47ae3f415d16d0c43
<ide><path>container/container.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> containertypes "github.com/docker/docker/api/types/container" <add> mounttypes "github.com/docker/docker/api/types/mount" <ide> networktypes "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/daemon/exec" <ide> "github.com/docker/docker/daemon/logger" <ide> func (container *Container) ShouldRestart() bool { <ide> // AddMountPointWithVolume adds a new mount point configured with a volume to the container. <ide> func (container *Container) AddMountPointWithVolume(destination string, vol volume.Volume, rw bool) { <ide> container.MountPoints[destination] = &volume.MountPoint{ <add> Type: mounttypes.TypeVolume, <ide> Name: vol.Name(), <ide> Driver: vol.DriverName(), <ide> Destination: destination, <ide><path>daemon/create_unix.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> containertypes "github.com/docker/docker/api/types/container" <add> mounttypes "github.com/docker/docker/api/types/mount" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> func (daemon *Daemon) createContainerPlatformSpecificSettings(container *contain <ide> // this is only called when the container is created. <ide> func (daemon *Daemon) populateVolumes(c *container.Container) error { <ide> for _, mnt := range c.MountPoints { <del> if !mnt.CopyData || mnt.Volume == nil { <add> if mnt.Volume == nil { <add> continue <add> } <add> <add> if mnt.Type != mounttypes.TypeVolume || !mnt.CopyData { <ide> continue <ide> } <ide> <ide><path>daemon/create_windows.go <ide> func (daemon *Daemon) createContainerPlatformSpecificSettings(container *contain <ide> <ide> for spec := range config.Volumes { <ide> <del> mp, err := volume.ParseMountSpec(spec, hostConfig.VolumeDriver) <add> mp, err := volume.ParseMountRaw(spec, hostConfig.VolumeDriver) <ide> if err != nil { <ide> return fmt.Errorf("Unrecognised volume spec: %v", err) <ide> } <ide><path>daemon/inspect_unix.go <ide> func addMountPoints(container *container.Container) []types.MountPoint { <ide> mountPoints := make([]types.MountPoint, 0, len(container.MountPoints)) <ide> for _, m := range container.MountPoints { <ide> mountPoints = append(mountPoints, types.MountPoint{ <add> Type: m.Type, <ide> Name: m.Name, <ide> Source: m.Path(), <ide> Destination: m.Destination, <ide><path>daemon/inspect_windows.go <ide> func addMountPoints(container *container.Container) []types.MountPoint { <ide> mountPoints := make([]types.MountPoint, 0, len(container.MountPoints)) <ide> for _, m := range container.MountPoints { <ide> mountPoints = append(mountPoints, types.MountPoint{ <add> Type: m.Type, <ide> Name: m.Name, <ide> Source: m.Path(), <ide> Destination: m.Destination, <ide><path>daemon/mounts.go <ide> func (daemon *Daemon) removeMountPoints(container *container.Container, rm bool) <ide> if rm { <ide> // Do not remove named mountpoints <ide> // these are mountpoints specified like `docker run -v <name>:/foo` <del> if m.Named { <add> if m.Spec.Source != "" { <ide> continue <ide> } <ide> err := daemon.volumes.Remove(m.Volume) <ide><path>daemon/volumes.go <ide> import ( <ide> <ide> "github.com/docker/docker/api/types" <ide> containertypes "github.com/docker/docker/api/types/container" <add> mounttypes "github.com/docker/docker/api/types/mount" <ide> "github.com/docker/docker/container" <add> dockererrors "github.com/docker/docker/errors" <ide> "github.com/docker/docker/volume" <add> "github.com/opencontainers/runc/libcontainer/label" <ide> ) <ide> <ide> var ( <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> Driver: m.Driver, <ide> Destination: m.Destination, <ide> Propagation: m.Propagation, <del> Named: m.Named, <add> Spec: m.Spec, <add> CopyData: false, <ide> } <ide> <ide> if len(cp.Source) == 0 { <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> <ide> // 3. Read bind mounts <ide> for _, b := range hostConfig.Binds { <del> // #10618 <del> bind, err := volume.ParseMountSpec(b, hostConfig.VolumeDriver) <add> bind, err := volume.ParseMountRaw(b, hostConfig.VolumeDriver) <ide> if err != nil { <ide> return err <ide> } <ide> <add> // #10618 <ide> _, tmpfsExists := hostConfig.Tmpfs[bind.Destination] <ide> if binds[bind.Destination] || tmpfsExists { <ide> return fmt.Errorf("Duplicate mount point '%s'", bind.Destination) <ide> } <ide> <del> if len(bind.Name) > 0 { <add> if bind.Type == mounttypes.TypeVolume { <ide> // create the volume <ide> v, err := daemon.volumes.CreateWithRef(bind.Name, bind.Driver, container.ID, nil, nil) <ide> if err != nil { <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> bind.Source = v.Path() <ide> // bind.Name is an already existing volume, we need to use that here <ide> bind.Driver = v.DriverName() <del> bind.Named = true <del> if bind.Driver == "local" { <del> bind = setBindModeIfNull(bind) <add> if bind.Driver == volume.DefaultDriverName { <add> setBindModeIfNull(bind) <ide> } <ide> } <ide> <ide> binds[bind.Destination] = true <ide> mountPoints[bind.Destination] = bind <ide> } <ide> <add> for _, cfg := range hostConfig.Mounts { <add> mp, err := volume.ParseMountSpec(cfg) <add> if err != nil { <add> return dockererrors.NewBadRequestError(err) <add> } <add> <add> if binds[mp.Destination] { <add> return fmt.Errorf("Duplicate mount point '%s'", cfg.Target) <add> } <add> <add> if mp.Type == mounttypes.TypeVolume { <add> var v volume.Volume <add> if cfg.VolumeOptions != nil { <add> var driverOpts map[string]string <add> if cfg.VolumeOptions.DriverConfig != nil { <add> driverOpts = cfg.VolumeOptions.DriverConfig.Options <add> } <add> v, err = daemon.volumes.CreateWithRef(mp.Name, mp.Driver, container.ID, driverOpts, cfg.VolumeOptions.Labels) <add> } else { <add> v, err = daemon.volumes.CreateWithRef(mp.Name, mp.Driver, container.ID, nil, nil) <add> } <add> if err != nil { <add> return err <add> } <add> <add> if err := label.Relabel(mp.Source, container.MountLabel, false); err != nil { <add> return err <add> } <add> mp.Volume = v <add> mp.Name = v.Name() <add> mp.Driver = v.DriverName() <add> <add> // only use the cached path here since getting the path is not neccessary right now and calling `Path()` may be slow <add> if cv, ok := v.(interface { <add> CachedPath() string <add> }); ok { <add> mp.Source = cv.CachedPath() <add> } <add> } <add> <add> binds[mp.Destination] = true <add> mountPoints[mp.Destination] = mp <add> } <add> <ide> container.Lock() <ide> <ide> // 4. Cleanup old volumes that are about to be reassigned. <ide><path>daemon/volumes_unix.go <ide> func sortMounts(m []container.Mount) []container.Mount { <ide> // setBindModeIfNull is platform specific processing to ensure the <ide> // shared mode is set to 'z' if it is null. This is called in the case <ide> // of processing a named volume and not a typical bind. <del>func setBindModeIfNull(bind *volume.MountPoint) *volume.MountPoint { <add>func setBindModeIfNull(bind *volume.MountPoint) { <ide> if bind.Mode == "" { <ide> bind.Mode = "z" <ide> } <del> return bind <ide> } <ide> <ide> // migrateVolume links the contents of a volume created pre Docker 1.7 <ide><path>daemon/volumes_windows.go <ide> func (daemon *Daemon) setupMounts(c *container.Container) ([]container.Mount, er <ide> <ide> // setBindModeIfNull is platform specific processing which is a no-op on <ide> // Windows. <del>func setBindModeIfNull(bind *volume.MountPoint) *volume.MountPoint { <del> return bind <add>func setBindModeIfNull(bind *volume.MountPoint) { <add> return <ide> } <ide><path>docs/reference/api/docker_remote_api.md <ide> This section lists each version from latest to oldest. Each listing includes a <ide> * `DELETE /volumes/(name)` now accepts a `force` query parameter to force removal of volumes that were already removed out of band by the volume driver plugin. <ide> * `POST /containers/create/` and `POST /containers/(name)/update` now validates restart policies. <ide> * `POST /containers/create` now validates IPAMConfig in NetworkingConfig, and returns error for invalid IPv4 and IPv6 addresses (`--ip` and `--ip6` in `docker create/run`). <add>* `POST /containers/create` now takes a `Mounts` field in `HostConfig` which replaces `Binds` and `Volumes`. *note*: `Binds` and `Volumes` are still available but are exclusive with `Mounts` <ide> <ide> ### v1.24 API changes <ide> <ide><path>docs/reference/api/docker_remote_api_v1.24.md <ide> Create a container <ide> "StorageOpt": {}, <ide> "CgroupParent": "", <ide> "VolumeDriver": "", <del> "ShmSize": 67108864 <add> "ShmSize": 67108864, <add> "Mounts": [] <ide> }, <ide> "NetworkingConfig": { <ide> "EndpointsConfig": { <ide> Return low-level information on the container `id` <ide> "VolumesFrom": null, <ide> "Ulimits": [{}], <ide> "VolumeDriver": "", <del> "ShmSize": 67108864 <add> "ShmSize": 67108864, <add> "Mounts": [] <ide> }, <ide> "HostnamePath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname", <ide> "HostsPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts", <ide><path>docs/reference/api/docker_remote_api_v1.25.md <ide> Create a container <ide> - **CgroupParent** - Path to `cgroups` under which the container's `cgroup` is created. If the path is not absolute, the path is considered to be relative to the `cgroups` path of the init process. Cgroups are created if they do not already exist. <ide> - **VolumeDriver** - Driver that this container users to mount volumes. <ide> - **ShmSize** - Size of `/dev/shm` in bytes. The size must be greater than 0. If omitted the system uses 64MB. <add> - **Mounts** – Specification for mounts to be added to the container. <add> - **Target** – Container path. <add> - **Source** – Mount source (e.g. a volume name, a host path). <add> - **Type** – The mount type (`bind`, or `volume`). <add> Available types (for the `Type` field): <add> - **bind** - Mounts a file or directory from the host into the container. Must exist prior to creating the container. <add> - **volume** - Creates a volume with the given name and options (or uses a pre-existing volume with the same name and options). These are **not** removed when the container is removed. <add> - **ReadOnly** – A boolean indicating whether the mount should be read-only. <add> - **BindOptions** - Optional configuration for the `bind` type. <add> - **Propagation** – A propagation mode with the value `[r]private`, `[r]shared`, or `[r]slave`. <add> - **VolumeOptions** – Optional configuration for the `volume` type. <add> - **NoCopy** – A boolean indicating if volume should be <add> populated with the data from the target. (Default false) <add> - **Labels** – User-defined name and labels for the volume as key/value pairs: `{"name": "value"}` <add> - **DriverConfig** – Map of driver-specific options. <add> - **Name** - Name of the driver to use to create the volume. <add> - **Options** - key/value map of driver specific options. <add> <ide> <ide> **Query parameters**: <ide> <ide><path>integration-cli/docker_api_containers_test.go <ide> import ( <ide> "encoding/json" <ide> "fmt" <ide> "io" <add> "io/ioutil" <ide> "net/http" <ide> "net/http/httputil" <ide> "net/url" <ide> "os" <add> "path/filepath" <ide> "regexp" <ide> "strconv" <ide> "strings" <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <ide> containertypes "github.com/docker/docker/api/types/container" <add> mounttypes "github.com/docker/docker/api/types/mount" <ide> networktypes "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/pkg/integration" <ide> "github.com/docker/docker/pkg/integration/checker" <add> "github.com/docker/docker/pkg/ioutils" <add> "github.com/docker/docker/pkg/mount" <ide> "github.com/docker/docker/pkg/stringid" <add> "github.com/docker/docker/volume" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func (s *DockerSuite) TestContainerApiStatsWithNetworkDisabled(c *check.C) { <ide> c.Assert(dec.Decode(&s), checker.IsNil) <ide> } <ide> } <add> <add>func (s *DockerSuite) TestContainersApiCreateMountsValidation(c *check.C) { <add> type m mounttypes.Mount <add> type hc struct{ Mounts []m } <add> type cfg struct { <add> Image string <add> HostConfig hc <add> } <add> type testCase struct { <add> config cfg <add> status int <add> msg string <add> } <add> <add> prefix, slash := getPrefixAndSlashFromDaemonPlatform() <add> destPath := prefix + slash + "foo" <add> notExistPath := prefix + slash + "notexist" <add> <add> cases := []testCase{ <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "notreal", Target: destPath}}}}, http.StatusBadRequest, "mount type unknown"}, <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind"}}}}, http.StatusBadRequest, "Target must not be empty"}, <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind", Target: destPath}}}}, http.StatusBadRequest, "Source must not be empty"}, <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind", Source: notExistPath, Target: destPath}}}}, http.StatusBadRequest, "bind source path does not exist"}, <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "volume"}}}}, http.StatusBadRequest, "Target must not be empty"}, <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "volume", Source: "hello", Target: destPath}}}}, http.StatusCreated, ""}, <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "volume", Source: "hello2", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{DriverConfig: &mounttypes.Driver{Name: "local"}}}}}}, http.StatusCreated, ""}, <add> } <add> <add> if SameHostDaemon.Condition() { <add> tmpDir, err := ioutils.TempDir("", "test-mounts-api") <add> c.Assert(err, checker.IsNil) <add> defer os.RemoveAll(tmpDir) <add> cases = append(cases, []testCase{ <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind", Source: tmpDir, Target: destPath}}}}, http.StatusCreated, ""}, <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind", Source: tmpDir, Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{}}}}}, http.StatusBadRequest, "VolumeOptions must not be specified"}, <add> }...) <add> } <add> <add> if DaemonIsLinux.Condition() { <add> cases = append(cases, []testCase{ <add> {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "volume", Source: "hello3", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{DriverConfig: &mounttypes.Driver{Name: "local", Options: map[string]string{"o": "size=1"}}}}}}}, http.StatusCreated, ""}, <add> }...) <add> <add> } <add> <add> for i, x := range cases { <add> c.Logf("case %d", i) <add> status, b, err := sockRequest("POST", "/containers/create", x.config) <add> c.Assert(err, checker.IsNil) <add> c.Assert(status, checker.Equals, x.status, check.Commentf("%s\n%v", string(b), cases[i].config)) <add> if len(x.msg) > 0 { <add> c.Assert(string(b), checker.Contains, x.msg, check.Commentf("%v", cases[i].config)) <add> } <add> } <add>} <add> <add>func (s *DockerSuite) TestContainerApiCreateMountsBindRead(c *check.C) { <add> testRequires(c, NotUserNamespace, SameHostDaemon) <add> // also with data in the host side <add> prefix, slash := getPrefixAndSlashFromDaemonPlatform() <add> destPath := prefix + slash + "foo" <add> tmpDir, err := ioutil.TempDir("", "test-mounts-api-bind") <add> c.Assert(err, checker.IsNil) <add> defer os.RemoveAll(tmpDir) <add> err = ioutil.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 666) <add> c.Assert(err, checker.IsNil) <add> <add> data := map[string]interface{}{ <add> "Image": "busybox", <add> "Cmd": []string{"/bin/sh", "-c", "cat /foo/bar"}, <add> "HostConfig": map[string]interface{}{"Mounts": []map[string]interface{}{{"Type": "bind", "Source": tmpDir, "Target": destPath}}}, <add> } <add> status, resp, err := sockRequest("POST", "/containers/create?name=test", data) <add> c.Assert(err, checker.IsNil, check.Commentf(string(resp))) <add> c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(resp))) <add> <add> out, _ := dockerCmd(c, "start", "-a", "test") <add> c.Assert(out, checker.Equals, "hello") <add>} <add> <add>// Test Mounts comes out as expected for the MountPoint <add>func (s *DockerSuite) TestContainersApiCreateMountsCreate(c *check.C) { <add> prefix, slash := getPrefixAndSlashFromDaemonPlatform() <add> destPath := prefix + slash + "foo" <add> <add> var ( <add> err error <add> testImg string <add> ) <add> if daemonPlatform != "windows" { <add> testImg, err = buildImage("test-mount-config", ` <add> FROM busybox <add> RUN mkdir `+destPath+` && touch `+destPath+slash+`bar <add> CMD cat `+destPath+slash+`bar <add> `, true) <add> } else { <add> testImg = "busybox" <add> } <add> c.Assert(err, checker.IsNil) <add> <add> type testCase struct { <add> cfg mounttypes.Mount <add> expected types.MountPoint <add> } <add> <add> cases := []testCase{ <add> // use literal strings here for `Type` instead of the defined constants in the volume package to keep this honest <add> // Validation of the actual `Mount` struct is done in another test is not needed here <add> {mounttypes.Mount{Type: "volume", Target: destPath}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}}, <add> {mounttypes.Mount{Type: "volume", Target: destPath + slash}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}}, <add> {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test1"}, types.MountPoint{Type: "volume", Name: "test1", RW: true, Destination: destPath}}, <add> {mounttypes.Mount{Type: "volume", Target: destPath, ReadOnly: true, Source: "test2"}, types.MountPoint{Type: "volume", Name: "test2", RW: false, Destination: destPath}}, <add> {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test3", VolumeOptions: &mounttypes.VolumeOptions{DriverConfig: &mounttypes.Driver{Name: volume.DefaultDriverName}}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", Name: "test3", RW: true, Destination: destPath}}, <add> } <add> <add> if SameHostDaemon.Condition() { <add> // setup temp dir for testing binds <add> tmpDir1, err := ioutil.TempDir("", "test-mounts-api-1") <add> c.Assert(err, checker.IsNil) <add> defer os.RemoveAll(tmpDir1) <add> cases = append(cases, []testCase{ <add> {mounttypes.Mount{Type: "bind", Source: tmpDir1, Target: destPath}, types.MountPoint{Type: "bind", RW: true, Destination: destPath, Source: tmpDir1}}, <add> {mounttypes.Mount{Type: "bind", Source: tmpDir1, Target: destPath, ReadOnly: true}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir1}}, <add> }...) <add> <add> // for modes only supported on Linux <add> if DaemonIsLinux.Condition() { <add> tmpDir3, err := ioutils.TempDir("", "test-mounts-api-3") <add> c.Assert(err, checker.IsNil) <add> defer os.RemoveAll(tmpDir3) <add> <add> c.Assert(mount.Mount(tmpDir3, tmpDir3, "none", "bind,rw"), checker.IsNil) <add> c.Assert(mount.ForceMount("", tmpDir3, "none", "shared"), checker.IsNil) <add> <add> cases = append(cases, []testCase{ <add> {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath}, types.MountPoint{Type: "bind", RW: true, Destination: destPath, Source: tmpDir3}}, <add> {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3}}, <add> {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true, BindOptions: &mounttypes.BindOptions{Propagation: "shared"}}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3, Propagation: "shared"}}, <add> }...) <add> } <add> } <add> <add> if daemonPlatform != "windows" { // Windows does not support volume populate <add> cases = append(cases, []testCase{ <add> {mounttypes.Mount{Type: "volume", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}}, <add> {mounttypes.Mount{Type: "volume", Target: destPath + slash, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}}, <add> {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test4", VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Type: "volume", Name: "test4", RW: true, Destination: destPath}}, <add> {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test5", ReadOnly: true, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Type: "volume", Name: "test5", RW: false, Destination: destPath}}, <add> }...) <add> } <add> <add> type wrapper struct { <add> containertypes.Config <add> HostConfig containertypes.HostConfig <add> } <add> type createResp struct { <add> ID string `json:"Id"` <add> } <add> for i, x := range cases { <add> c.Logf("case %d - config: %v", i, x.cfg) <add> status, data, err := sockRequest("POST", "/containers/create", wrapper{containertypes.Config{Image: testImg}, containertypes.HostConfig{Mounts: []mounttypes.Mount{x.cfg}}}) <add> c.Assert(err, checker.IsNil, check.Commentf(string(data))) <add> c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(data))) <add> <add> var resp createResp <add> err = json.Unmarshal(data, &resp) <add> c.Assert(err, checker.IsNil, check.Commentf(string(data))) <add> id := resp.ID <add> <add> var mps []types.MountPoint <add> err = json.NewDecoder(strings.NewReader(inspectFieldJSON(c, id, "Mounts"))).Decode(&mps) <add> c.Assert(err, checker.IsNil) <add> c.Assert(mps, checker.HasLen, 1) <add> c.Assert(mps[0].Destination, checker.Equals, x.expected.Destination) <add> <add> if len(x.expected.Source) > 0 { <add> c.Assert(mps[0].Source, checker.Equals, x.expected.Source) <add> } <add> if len(x.expected.Name) > 0 { <add> c.Assert(mps[0].Name, checker.Equals, x.expected.Name) <add> } <add> if len(x.expected.Driver) > 0 { <add> c.Assert(mps[0].Driver, checker.Equals, x.expected.Driver) <add> } <add> c.Assert(mps[0].RW, checker.Equals, x.expected.RW) <add> c.Assert(mps[0].Type, checker.Equals, x.expected.Type) <add> c.Assert(mps[0].Mode, checker.Equals, x.expected.Mode) <add> if len(x.expected.Propagation) > 0 { <add> c.Assert(mps[0].Propagation, checker.Equals, x.expected.Propagation) <add> } <add> <add> out, _, err := dockerCmdWithError("start", "-a", id) <add> if (x.cfg.Type != "volume" || (x.cfg.VolumeOptions != nil && x.cfg.VolumeOptions.NoCopy)) && daemonPlatform != "windows" { <add> c.Assert(err, checker.NotNil, check.Commentf("%s\n%v", out, mps[0])) <add> } else { <add> c.Assert(err, checker.IsNil, check.Commentf("%s\n%v", out, mps[0])) <add> } <add> <add> dockerCmd(c, "rm", "-fv", id) <add> if x.cfg.Type == "volume" && len(x.cfg.Source) > 0 { <add> // This should still exist even though we removed the container <add> dockerCmd(c, "volume", "inspect", mps[0].Name) <add> } else { <add> // This should be removed automatically when we removed the container <add> out, _, err := dockerCmdWithError("volume", "inspect", mps[0].Name) <add> c.Assert(err, checker.NotNil, check.Commentf(out)) <add> } <add> } <add>} <ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunVolumesMountedAsSlave(c *check.C) { <ide> <ide> func (s *DockerSuite) TestRunNamedVolumesMountedAsShared(c *check.C) { <ide> testRequires(c, DaemonIsLinux, NotUserNamespace) <del> out, exitcode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile") <del> <del> if exitcode == 0 { <del> c.Fatalf("expected non-zero exit code; received %d", exitcode) <del> } <del> <del> if expected := "Invalid volume specification"; !strings.Contains(out, expected) { <del> c.Fatalf(`Expected %q in output; got: %s`, expected, out) <del> } <add> out, exitCode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile") <add> c.Assert(exitCode, checker.Not(checker.Equals), 0) <add> c.Assert(out, checker.Contains, "invalid mount config") <ide> } <ide> <ide> func (s *DockerSuite) TestRunNamedVolumeCopyImageData(c *check.C) { <ide><path>runconfig/config.go <ide> func DecodeContainerConfig(src io.Reader) (*container.Config, *container.HostCon <ide> // validateVolumesAndBindSettings validates each of the volumes and bind settings <ide> // passed by the caller to ensure they are valid. <ide> func validateVolumesAndBindSettings(c *container.Config, hc *container.HostConfig) error { <add> if len(hc.Mounts) > 0 { <add> if len(hc.Binds) > 0 { <add> return conflictError(fmt.Errorf("must not specify both Binds and Mounts")) <add> } <add> <add> if len(c.Volumes) > 0 { <add> return conflictError(fmt.Errorf("must not specify both Volumes and Mounts")) <add> } <add> <add> if len(hc.VolumeDriver) > 0 { <add> return conflictError(fmt.Errorf("must not specify both VolumeDriver and Mounts")) <add> } <add> } <ide> <ide> // Ensure all volumes and binds are valid. <ide> for spec := range c.Volumes { <del> if _, err := volume.ParseMountSpec(spec, hc.VolumeDriver); err != nil { <del> return fmt.Errorf("Invalid volume spec %q: %v", spec, err) <add> if _, err := volume.ParseMountRaw(spec, hc.VolumeDriver); err != nil { <add> return fmt.Errorf("invalid volume spec %q: %v", spec, err) <ide> } <ide> } <ide> for _, spec := range hc.Binds { <del> if _, err := volume.ParseMountSpec(spec, hc.VolumeDriver); err != nil { <del> return fmt.Errorf("Invalid bind mount spec %q: %v", spec, err) <add> if _, err := volume.ParseMountRaw(spec, hc.VolumeDriver); err != nil { <add> return fmt.Errorf("invalid bind mount spec %q: %v", spec, err) <ide> } <ide> } <ide> <ide><path>runconfig/errors.go <ide> package runconfig <ide> <ide> import ( <ide> "fmt" <add> <add> "github.com/docker/docker/errors" <ide> ) <ide> <ide> var ( <ide> var ( <ide> // ErrConflictUTSHostname conflict between the hostname and the UTS mode <ide> ErrConflictUTSHostname = fmt.Errorf("Conflicting options: hostname and the UTS mode") <ide> ) <add> <add>func conflictError(err error) error { <add> return errors.NewRequestConflictError(err) <add>} <ide><path>volume/validate.go <add>package volume <add> <add>import ( <add> "errors" <add> "fmt" <add> "os" <add> "path/filepath" <add> <add> "github.com/docker/docker/api/types/mount" <add>) <add> <add>var errBindNotExist = errors.New("bind source path does not exist") <add> <add>type validateOpts struct { <add> skipBindSourceCheck bool <add> skipAbsolutePathCheck bool <add>} <add> <add>func validateMountConfig(mnt *mount.Mount, options ...func(*validateOpts)) error { <add> opts := validateOpts{} <add> for _, o := range options { <add> o(&opts) <add> } <add> <add> if len(mnt.Target) == 0 { <add> return &errMountConfig{mnt, errMissingField("Target")} <add> } <add> <add> if err := validateNotRoot(mnt.Target); err != nil { <add> return &errMountConfig{mnt, err} <add> } <add> <add> if !opts.skipAbsolutePathCheck { <add> if err := validateAbsolute(mnt.Target); err != nil { <add> return &errMountConfig{mnt, err} <add> } <add> } <add> <add> switch mnt.Type { <add> case mount.TypeBind: <add> if len(mnt.Source) == 0 { <add> return &errMountConfig{mnt, errMissingField("Source")} <add> } <add> // Don't error out just because the propagation mode is not supported on the platform <add> if opts := mnt.BindOptions; opts != nil { <add> if len(opts.Propagation) > 0 && len(propagationModes) > 0 { <add> if _, ok := propagationModes[opts.Propagation]; !ok { <add> return &errMountConfig{mnt, fmt.Errorf("invalid propagation mode: %s", opts.Propagation)} <add> } <add> } <add> } <add> if mnt.VolumeOptions != nil { <add> return &errMountConfig{mnt, errExtraField("VolumeOptions")} <add> } <add> <add> if err := validateAbsolute(mnt.Source); err != nil { <add> return &errMountConfig{mnt, err} <add> } <add> <add> // Do not allow binding to non-existent path <add> if !opts.skipBindSourceCheck { <add> fi, err := os.Stat(mnt.Source) <add> if err != nil { <add> if !os.IsNotExist(err) { <add> return &errMountConfig{mnt, err} <add> } <add> return &errMountConfig{mnt, errBindNotExist} <add> } <add> if err := validateStat(fi); err != nil { <add> return &errMountConfig{mnt, err} <add> } <add> } <add> case mount.TypeVolume: <add> if mnt.BindOptions != nil { <add> return &errMountConfig{mnt, errExtraField("BindOptions")} <add> } <add> <add> if len(mnt.Source) == 0 && mnt.ReadOnly { <add> return &errMountConfig{mnt, fmt.Errorf("must not set ReadOnly mode when using anonymous volumes")} <add> } <add> <add> if len(mnt.Source) != 0 { <add> if valid, err := IsVolumeNameValid(mnt.Source); !valid { <add> if err == nil { <add> err = errors.New("invalid volume name") <add> } <add> return &errMountConfig{mnt, err} <add> } <add> } <add> default: <add> return &errMountConfig{mnt, errors.New("mount type unknown")} <add> } <add> return nil <add>} <add> <add>type errMountConfig struct { <add> mount *mount.Mount <add> err error <add>} <add> <add>func (e *errMountConfig) Error() string { <add> return fmt.Sprintf("invalid mount config for type %q: %v", e.mount.Type, e.err.Error()) <add>} <add> <add>func errExtraField(name string) error { <add> return fmt.Errorf("field %s must not be specified", name) <add>} <add>func errMissingField(name string) error { <add> return fmt.Errorf("field %s must not be empty", name) <add>} <add> <add>func validateAbsolute(p string) error { <add> p = convertSlash(p) <add> if filepath.IsAbs(p) { <add> return nil <add> } <add> return fmt.Errorf("invalid mount path: '%s' mount path must be absolute", p) <add>} <ide><path>volume/validate_test.go <add>package volume <add> <add>import ( <add> "errors" <add> "io/ioutil" <add> "os" <add> "strings" <add> "testing" <add> <add> "github.com/docker/docker/api/types/mount" <add>) <add> <add>func TestValidateMount(t *testing.T) { <add> testDir, err := ioutil.TempDir("", "test-validate-mount") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(testDir) <add> <add> cases := []struct { <add> input mount.Mount <add> expected error <add> }{ <add> {mount.Mount{Type: mount.TypeVolume}, errMissingField("Target")}, <add> {mount.Mount{Type: mount.TypeVolume, Target: testDestinationPath, Source: "hello"}, nil}, <add> {mount.Mount{Type: mount.TypeVolume, Target: testDestinationPath}, nil}, <add> {mount.Mount{Type: mount.TypeBind}, errMissingField("Target")}, <add> {mount.Mount{Type: mount.TypeBind, Target: testDestinationPath}, errMissingField("Source")}, <add> {mount.Mount{Type: mount.TypeBind, Target: testDestinationPath, Source: testSourcePath, VolumeOptions: &mount.VolumeOptions{}}, errExtraField("VolumeOptions")}, <add> {mount.Mount{Type: mount.TypeBind, Source: testSourcePath, Target: testDestinationPath}, errBindNotExist}, <add> {mount.Mount{Type: mount.TypeBind, Source: testDir, Target: testDestinationPath}, nil}, <add> {mount.Mount{Type: "invalid", Target: testDestinationPath}, errors.New("mount type unknown")}, <add> } <add> for i, x := range cases { <add> err := validateMountConfig(&x.input) <add> if err == nil && x.expected == nil { <add> continue <add> } <add> if (err == nil && x.expected != nil) || (x.expected == nil && err != nil) || !strings.Contains(err.Error(), x.expected.Error()) { <add> t.Fatalf("expected %q, got %q, case: %d", x.expected, err, i) <add> } <add> } <add>} <ide><path>volume/validate_test_unix.go <add>// +build !windows <add> <add>package volume <add> <add>var ( <add> testDestinationPath = "/foo" <add> testSourcePath = "/foo" <add>) <ide><path>volume/validate_test_windows.go <add>package volume <add> <add>var ( <add> testDestinationPath = `c:\foo` <add> testSourcePath = `c:\foo` <add>) <ide><path>volume/volume.go <ide> package volume <ide> import ( <ide> "fmt" <ide> "os" <add> "path/filepath" <ide> "strings" <ide> "syscall" <ide> <ide> type ScopedVolume interface { <ide> // specifies which volume is to be used and where inside a container it should <ide> // be mounted. <ide> type MountPoint struct { <del> Source string // Container host directory <del> Destination string // Inside the container <del> RW bool // True if writable <del> Name string // Name set by user <del> Driver string // Volume driver to use <del> Volume Volume `json:"-"` <add> Source string // Container host directory <add> Destination string // Inside the container <add> RW bool // True if writable <add> Name string // Name set by user <add> Driver string // Volume driver to use <add> Type mounttypes.Type `json:",omitempty"` // Type of mount to use, see `Type<foo>` definitions <add> Volume Volume `json:"-"` <ide> <ide> // Note Mode is not used on Windows <del> Mode string `json:"Relabel"` // Originally field was `Relabel`" <add> Mode string `json:"Relabel,omitempty"` // Originally field was `Relabel`" <ide> <ide> // Note Propagation is not used on Windows <del> Propagation mounttypes.Propagation // Mount propagation string <del> Named bool // specifies if the mountpoint was specified by name <add> Propagation mounttypes.Propagation `json:",omitempty"` // Mount propagation string <ide> <ide> // Specifies if data should be copied from the container before the first mount <ide> // Use a pointer here so we can tell if the user set this value explicitly <ide> // This allows us to error out when the user explicitly enabled copy but we can't copy due to the volume being populated <ide> CopyData bool `json:"-"` <ide> // ID is the opaque ID used to pass to the volume driver. <ide> // This should be set by calls to `Mount` and unset by calls to `Unmount` <del> ID string <add> ID string `json:",omitempty"` <add> Spec mounttypes.Mount <ide> } <ide> <ide> // Setup sets up a mount point by either mounting the volume if it is <ide> func (m *MountPoint) Setup(mountLabel string, rootUID, rootGID int) (string, err <ide> if len(m.Source) == 0 { <ide> return "", fmt.Errorf("Unable to setup mount point, neither source nor volume defined") <ide> } <del> // idtools.MkdirAllNewAs() produces an error if m.Source exists and is a file (not a directory) <del> // also, makes sure that if the directory is created, the correct remapped rootUID/rootGID will own it <del> if err := idtools.MkdirAllNewAs(m.Source, 0755, rootUID, rootGID); err != nil { <del> if perr, ok := err.(*os.PathError); ok { <del> if perr.Err != syscall.ENOTDIR { <del> return "", err <add> // system.MkdirAll() produces an error if m.Source exists and is a file (not a directory), <add> if m.Type == mounttypes.TypeBind { <add> // idtools.MkdirAllNewAs() produces an error if m.Source exists and is a file (not a directory) <add> // also, makes sure that if the directory is created, the correct remapped rootUID/rootGID will own it <add> if err := idtools.MkdirAllNewAs(m.Source, 0755, rootUID, rootGID); err != nil { <add> if perr, ok := err.(*os.PathError); ok { <add> if perr.Err != syscall.ENOTDIR { <add> return "", err <add> } <ide> } <ide> } <ide> } <ide> func (m *MountPoint) Path() string { <ide> return m.Source <ide> } <ide> <del>// Type returns the type of mount point <del>func (m *MountPoint) Type() string { <del> if m.Name != "" { <del> return "volume" <del> } <del> if m.Source != "" { <del> return "bind" <del> } <del> return "ephemeral" <del>} <del> <ide> // ParseVolumesFrom ensures that the supplied volumes-from is valid. <ide> func ParseVolumesFrom(spec string) (string, string, error) { <ide> if len(spec) == 0 { <ide> func ParseVolumesFrom(spec string) (string, string, error) { <ide> return id, mode, nil <ide> } <ide> <add>// ParseMountRaw parses a raw volume spec (e.g. `-v /foo:/bar:shared`) into a <add>// structured spec. Once the raw spec is parsed it relies on `ParseMountSpec` to <add>// validate the spec and create a MountPoint <add>func ParseMountRaw(raw, volumeDriver string) (*MountPoint, error) { <add> arr, err := splitRawSpec(convertSlash(raw)) <add> if err != nil { <add> return nil, err <add> } <add> <add> var spec mounttypes.Mount <add> var mode string <add> switch len(arr) { <add> case 1: <add> // Just a destination path in the container <add> spec.Target = arr[0] <add> case 2: <add> if ValidMountMode(arr[1]) { <add> // Destination + Mode is not a valid volume - volumes <add> // cannot include a mode. eg /foo:rw <add> return nil, errInvalidSpec(raw) <add> } <add> // Host Source Path or Name + Destination <add> spec.Source = arr[0] <add> spec.Target = arr[1] <add> case 3: <add> // HostSourcePath+DestinationPath+Mode <add> spec.Source = arr[0] <add> spec.Target = arr[1] <add> mode = arr[2] <add> default: <add> return nil, errInvalidSpec(raw) <add> } <add> <add> if !ValidMountMode(mode) { <add> return nil, errInvalidMode(mode) <add> } <add> <add> if filepath.IsAbs(spec.Source) { <add> spec.Type = mounttypes.TypeBind <add> } else { <add> spec.Type = mounttypes.TypeVolume <add> } <add> <add> spec.ReadOnly = !ReadWrite(mode) <add> <add> // cannot assume that if a volume driver is passed in that we should set it <add> if volumeDriver != "" && spec.Type == mounttypes.TypeVolume { <add> spec.VolumeOptions = &mounttypes.VolumeOptions{ <add> DriverConfig: &mounttypes.Driver{Name: volumeDriver}, <add> } <add> } <add> <add> if copyData, isSet := getCopyMode(mode); isSet { <add> if spec.VolumeOptions == nil { <add> spec.VolumeOptions = &mounttypes.VolumeOptions{} <add> } <add> spec.VolumeOptions.NoCopy = !copyData <add> } <add> if HasPropagation(mode) { <add> spec.BindOptions = &mounttypes.BindOptions{ <add> Propagation: GetPropagation(mode), <add> } <add> } <add> <add> mp, err := ParseMountSpec(spec, platformRawValidationOpts...) <add> if mp != nil { <add> mp.Mode = mode <add> } <add> if err != nil { <add> err = fmt.Errorf("%v: %v", errInvalidSpec(raw), err) <add> } <add> return mp, err <add>} <add> <add>// ParseMountSpec reads a mount config, validates it, and configures a mountpoint from it. <add>func ParseMountSpec(cfg mounttypes.Mount, options ...func(*validateOpts)) (*MountPoint, error) { <add> if err := validateMountConfig(&cfg, options...); err != nil { <add> return nil, err <add> } <add> mp := &MountPoint{ <add> RW: !cfg.ReadOnly, <add> Destination: clean(convertSlash(cfg.Target)), <add> Type: cfg.Type, <add> Spec: cfg, <add> } <add> <add> switch cfg.Type { <add> case mounttypes.TypeVolume: <add> if cfg.Source == "" { <add> mp.Name = stringid.GenerateNonCryptoID() <add> } else { <add> mp.Name = cfg.Source <add> } <add> mp.CopyData = DefaultCopyMode <add> <add> mp.Driver = DefaultDriverName <add> if cfg.VolumeOptions != nil { <add> if cfg.VolumeOptions.DriverConfig != nil { <add> mp.Driver = cfg.VolumeOptions.DriverConfig.Name <add> } <add> if cfg.VolumeOptions.NoCopy { <add> mp.CopyData = false <add> } <add> } <add> case mounttypes.TypeBind: <add> mp.Source = clean(convertSlash(cfg.Source)) <add> if cfg.BindOptions != nil { <add> if len(cfg.BindOptions.Propagation) > 0 { <add> mp.Propagation = cfg.BindOptions.Propagation <add> } <add> } <add> } <add> return mp, nil <add>} <add> <ide> func errInvalidMode(mode string) error { <ide> return fmt.Errorf("invalid mode: %v", mode) <ide> } <ide> <ide> func errInvalidSpec(spec string) error { <del> return fmt.Errorf("Invalid volume specification: '%s'", spec) <add> return fmt.Errorf("invalid volume specification: '%s'", spec) <ide> } <ide><path>volume/volume_copy.go <ide> package volume <ide> <ide> import "strings" <ide> <del>const ( <del> // DefaultCopyMode is the copy mode used by default for normal/named volumes <del> DefaultCopyMode = true <del>) <del> <ide> // {<copy mode>=isEnabled} <ide> var copyModes = map[string]bool{ <ide> "nocopy": false, <ide><path>volume/volume_copy_unix.go <add>// +build !windows <add> <add>package volume <add> <add>const ( <add> // DefaultCopyMode is the copy mode used by default for normal/named volumes <add> DefaultCopyMode = true <add>) <ide><path>volume/volume_copy_windows.go <add>package volume <add> <add>const ( <add> // DefaultCopyMode is the copy mode used by default for normal/named volumes <add> DefaultCopyMode = false <add>) <ide><path>volume/volume_propagation_linux.go <ide> import ( <ide> <ide> // DefaultPropagationMode defines what propagation mode should be used by <ide> // default if user has not specified one explicitly. <del>const DefaultPropagationMode mounttypes.Propagation = "rprivate" <del> <ide> // propagation modes <add>const DefaultPropagationMode = mounttypes.PropagationRPrivate <add> <ide> var propagationModes = map[mounttypes.Propagation]bool{ <ide> mounttypes.PropagationPrivate: true, <ide> mounttypes.PropagationRPrivate: true, <ide><path>volume/volume_propagation_linux_test.go <ide> import ( <ide> "testing" <ide> ) <ide> <del>func TestParseMountSpecPropagation(t *testing.T) { <add>func TestParseMountRawPropagation(t *testing.T) { <ide> var ( <ide> valid []string <ide> invalid map[string]string <ide> func TestParseMountSpecPropagation(t *testing.T) { <ide> "/hostPath:/containerPath:ro,Z,rprivate", <ide> } <ide> invalid = map[string]string{ <del> "/path:/path:ro,rshared,rslave": `invalid mode: ro,rshared,rslave`, <del> "/path:/path:ro,z,rshared,rslave": `invalid mode: ro,z,rshared,rslave`, <del> "/path:shared": "Invalid volume specification", <del> "/path:slave": "Invalid volume specification", <del> "/path:private": "Invalid volume specification", <del> "name:/absolute-path:shared": "Invalid volume specification", <del> "name:/absolute-path:rshared": "Invalid volume specification", <del> "name:/absolute-path:slave": "Invalid volume specification", <del> "name:/absolute-path:rslave": "Invalid volume specification", <del> "name:/absolute-path:private": "Invalid volume specification", <del> "name:/absolute-path:rprivate": "Invalid volume specification", <add> "/path:/path:ro,rshared,rslave": `invalid mode`, <add> "/path:/path:ro,z,rshared,rslave": `invalid mode`, <add> "/path:shared": "invalid volume specification", <add> "/path:slave": "invalid volume specification", <add> "/path:private": "invalid volume specification", <add> "name:/absolute-path:shared": "invalid volume specification", <add> "name:/absolute-path:rshared": "invalid volume specification", <add> "name:/absolute-path:slave": "invalid volume specification", <add> "name:/absolute-path:rslave": "invalid volume specification", <add> "name:/absolute-path:private": "invalid volume specification", <add> "name:/absolute-path:rprivate": "invalid volume specification", <ide> } <ide> <ide> for _, path := range valid { <del> if _, err := ParseMountSpec(path, "local"); err != nil { <del> t.Fatalf("ParseMountSpec(`%q`) should succeed: error %q", path, err) <add> if _, err := ParseMountRaw(path, "local"); err != nil { <add> t.Fatalf("ParseMountRaw(`%q`) should succeed: error %q", path, err) <ide> } <ide> } <ide> <ide> for path, expectedError := range invalid { <del> if _, err := ParseMountSpec(path, "local"); err == nil { <del> t.Fatalf("ParseMountSpec(`%q`) should have failed validation. Err %v", path, err) <add> if _, err := ParseMountRaw(path, "local"); err == nil { <add> t.Fatalf("ParseMountRaw(`%q`) should have failed validation. Err %v", path, err) <ide> } else { <ide> if !strings.Contains(err.Error(), expectedError) { <del> t.Fatalf("ParseMountSpec(`%q`) error should contain %q, got %v", path, expectedError, err.Error()) <add> t.Fatalf("ParseMountRaw(`%q`) error should contain %q, got %v", path, expectedError, err.Error()) <ide> } <ide> } <ide> } <ide><path>volume/volume_propagation_unsupported.go <ide> import mounttypes "github.com/docker/docker/api/types/mount" <ide> const DefaultPropagationMode mounttypes.Propagation = "" <ide> <ide> // propagation modes not supported on this platform. <del>var propagationModes = map[string]bool{} <add>var propagationModes = map[mounttypes.Propagation]bool{} <ide> <ide> // GetPropagation is not supported. Return empty string. <ide> func GetPropagation(mode string) mounttypes.Propagation { <ide><path>volume/volume_test.go <ide> package volume <ide> <ide> import ( <add> "io/ioutil" <add> "os" <ide> "runtime" <ide> "strings" <ide> "testing" <add> <add> "github.com/docker/docker/api/types/mount" <ide> ) <ide> <del>func TestParseMountSpec(t *testing.T) { <add>func TestParseMountRaw(t *testing.T) { <ide> var ( <ide> valid []string <ide> invalid map[string]string <ide> func TestParseMountSpec(t *testing.T) { <ide> `c:\Program Files (x86)`, // With capitals and brackets <ide> } <ide> invalid = map[string]string{ <del> ``: "Invalid volume specification: ", <del> `.`: "Invalid volume specification: ", <del> `..\`: "Invalid volume specification: ", <del> `c:\:..\`: "Invalid volume specification: ", <del> `c:\:d:\:xyzzy`: "Invalid volume specification: ", <del> `c:`: "cannot be c:", <del> `c:\`: `cannot be c:\`, <del> `c:\notexist:d:`: `The system cannot find the file specified`, <del> `c:\windows\system32\ntdll.dll:d:`: `Source 'c:\windows\system32\ntdll.dll' is not a directory`, <del> `name<:d:`: `Invalid volume specification`, <del> `name>:d:`: `Invalid volume specification`, <del> `name::d:`: `Invalid volume specification`, <del> `name":d:`: `Invalid volume specification`, <del> `name\:d:`: `Invalid volume specification`, <del> `name*:d:`: `Invalid volume specification`, <del> `name|:d:`: `Invalid volume specification`, <del> `name?:d:`: `Invalid volume specification`, <del> `name/:d:`: `Invalid volume specification`, <del> `d:\pathandmode:rw`: `Invalid volume specification`, <add> ``: "invalid volume specification: ", <add> `.`: "invalid volume specification: ", <add> `..\`: "invalid volume specification: ", <add> `c:\:..\`: "invalid volume specification: ", <add> `c:\:d:\:xyzzy`: "invalid volume specification: ", <add> `c:`: "cannot be `c:`", <add> `c:\`: "cannot be `c:`", <add> `c:\notexist:d:`: `source path does not exist`, <add> `c:\windows\system32\ntdll.dll:d:`: `source path must be a directory`, <add> `name<:d:`: `invalid volume specification`, <add> `name>:d:`: `invalid volume specification`, <add> `name::d:`: `invalid volume specification`, <add> `name":d:`: `invalid volume specification`, <add> `name\:d:`: `invalid volume specification`, <add> `name*:d:`: `invalid volume specification`, <add> `name|:d:`: `invalid volume specification`, <add> `name?:d:`: `invalid volume specification`, <add> `name/:d:`: `invalid volume specification`, <add> `d:\pathandmode:rw`: `invalid volume specification`, <ide> `con:d:`: `cannot be a reserved word for Windows filenames`, <ide> `PRN:d:`: `cannot be a reserved word for Windows filenames`, <ide> `aUx:d:`: `cannot be a reserved word for Windows filenames`, <ide> func TestParseMountSpec(t *testing.T) { <ide> "/rw:/ro", <ide> } <ide> invalid = map[string]string{ <del> "": "Invalid volume specification", <del> "./": "Invalid volume destination", <del> "../": "Invalid volume destination", <del> "/:../": "Invalid volume destination", <del> "/:path": "Invalid volume destination", <del> ":": "Invalid volume specification", <del> "/tmp:": "Invalid volume destination", <del> ":test": "Invalid volume specification", <del> ":/test": "Invalid volume specification", <del> "tmp:": "Invalid volume destination", <del> ":test:": "Invalid volume specification", <del> "::": "Invalid volume specification", <del> ":::": "Invalid volume specification", <del> "/tmp:::": "Invalid volume specification", <del> ":/tmp::": "Invalid volume specification", <del> "/path:rw": "Invalid volume specification", <del> "/path:ro": "Invalid volume specification", <del> "/rw:rw": "Invalid volume specification", <del> "path:ro": "Invalid volume specification", <del> "/path:/path:sw": `invalid mode: sw`, <del> "/path:/path:rwz": `invalid mode: rwz`, <add> "": "invalid volume specification", <add> "./": "mount path must be absolute", <add> "../": "mount path must be absolute", <add> "/:../": "mount path must be absolute", <add> "/:path": "mount path must be absolute", <add> ":": "invalid volume specification", <add> "/tmp:": "invalid volume specification", <add> ":test": "invalid volume specification", <add> ":/test": "invalid volume specification", <add> "tmp:": "invalid volume specification", <add> ":test:": "invalid volume specification", <add> "::": "invalid volume specification", <add> ":::": "invalid volume specification", <add> "/tmp:::": "invalid volume specification", <add> ":/tmp::": "invalid volume specification", <add> "/path:rw": "invalid volume specification", <add> "/path:ro": "invalid volume specification", <add> "/rw:rw": "invalid volume specification", <add> "path:ro": "invalid volume specification", <add> "/path:/path:sw": `invalid mode`, <add> "/path:/path:rwz": `invalid mode`, <ide> } <ide> } <ide> <ide> for _, path := range valid { <del> if _, err := ParseMountSpec(path, "local"); err != nil { <del> t.Fatalf("ParseMountSpec(`%q`) should succeed: error %q", path, err) <add> if _, err := ParseMountRaw(path, "local"); err != nil { <add> t.Fatalf("ParseMountRaw(`%q`) should succeed: error %q", path, err) <ide> } <ide> } <ide> <ide> for path, expectedError := range invalid { <del> if _, err := ParseMountSpec(path, "local"); err == nil { <del> t.Fatalf("ParseMountSpec(`%q`) should have failed validation. Err %v", path, err) <add> if mp, err := ParseMountRaw(path, "local"); err == nil { <add> t.Fatalf("ParseMountRaw(`%q`) should have failed validation. Err '%v' - MP: %v", path, err, mp) <ide> } else { <ide> if !strings.Contains(err.Error(), expectedError) { <del> t.Fatalf("ParseMountSpec(`%q`) error should contain %q, got %v", path, expectedError, err.Error()) <add> t.Fatalf("ParseMountRaw(`%q`) error should contain %q, got %v", path, expectedError, err.Error()) <ide> } <ide> } <ide> } <ide> } <ide> <del>// testParseMountSpec is a structure used by TestParseMountSpecSplit for <del>// specifying test cases for the ParseMountSpec() function. <del>type testParseMountSpec struct { <add>// testParseMountRaw is a structure used by TestParseMountRawSplit for <add>// specifying test cases for the ParseMountRaw() function. <add>type testParseMountRaw struct { <ide> bind string <ide> driver string <ide> expDest string <ide> type testParseMountSpec struct { <ide> fail bool <ide> } <ide> <del>func TestParseMountSpecSplit(t *testing.T) { <del> var cases []testParseMountSpec <add>func TestParseMountRawSplit(t *testing.T) { <add> var cases []testParseMountRaw <ide> if runtime.GOOS == "windows" { <del> cases = []testParseMountSpec{ <add> cases = []testParseMountRaw{ <ide> {`c:\:d:`, "local", `d:`, `c:\`, ``, "", true, false}, <ide> {`c:\:d:\`, "local", `d:\`, `c:\`, ``, "", true, false}, <ide> // TODO Windows post TP5 - Add readonly support {`c:\:d:\:ro`, "local", `d:\`, `c:\`, ``, "", false, false}, <ide> func TestParseMountSpecSplit(t *testing.T) { <ide> {`name:d::rw`, "local", `d:`, ``, `name`, "local", true, false}, <ide> {`name:d:`, "local", `d:`, ``, `name`, "local", true, false}, <ide> // TODO Windows post TP5 - Add readonly support {`name:d::ro`, "local", `d:`, ``, `name`, "local", false, false}, <del> {`name:c:`, "", ``, ``, ``, "", true, true}, <del> {`driver/name:c:`, "", ``, ``, ``, "", true, true}, <add> {`name:c:`, "", ``, ``, ``, DefaultDriverName, true, true}, <add> {`driver/name:c:`, "", ``, ``, ``, DefaultDriverName, true, true}, <ide> } <ide> } else { <del> cases = []testParseMountSpec{ <add> cases = []testParseMountRaw{ <ide> {"/tmp:/tmp1", "", "/tmp1", "/tmp", "", "", true, false}, <ide> {"/tmp:/tmp2:ro", "", "/tmp2", "/tmp", "", "", false, false}, <ide> {"/tmp:/tmp3:rw", "", "/tmp3", "/tmp", "", "", true, false}, <ide> {"/tmp:/tmp4:foo", "", "", "", "", "", false, true}, <del> {"name:/named1", "", "/named1", "", "name", "", true, false}, <add> {"name:/named1", "", "/named1", "", "name", DefaultDriverName, true, false}, <ide> {"name:/named2", "external", "/named2", "", "name", "external", true, false}, <ide> {"name:/named3:ro", "local", "/named3", "", "name", "local", false, false}, <del> {"local/name:/tmp:rw", "", "/tmp", "", "local/name", "", true, false}, <add> {"local/name:/tmp:rw", "", "/tmp", "", "local/name", DefaultDriverName, true, false}, <ide> {"/tmp:tmp", "", "", "", "", "", true, true}, <ide> } <ide> } <ide> <del> for _, c := range cases { <del> m, err := ParseMountSpec(c.bind, c.driver) <add> for i, c := range cases { <add> t.Logf("case %d", i) <add> m, err := ParseMountRaw(c.bind, c.driver) <ide> if c.fail { <ide> if err == nil { <ide> t.Fatalf("Expected error, was nil, for spec %s\n", c.bind) <ide> func TestParseMountSpecSplit(t *testing.T) { <ide> } <ide> <ide> if m == nil || err != nil { <del> t.Fatalf("ParseMountSpec failed for spec %s driver %s error %v\n", c.bind, c.driver, err.Error()) <add> t.Fatalf("ParseMountRaw failed for spec '%s', driver '%s', error '%v'", c.bind, c.driver, err.Error()) <ide> continue <ide> } <ide> <ide> if m.Destination != c.expDest { <del> t.Fatalf("Expected destination %s, was %s, for spec %s\n", c.expDest, m.Destination, c.bind) <add> t.Fatalf("Expected destination '%s, was %s', for spec '%s'", c.expDest, m.Destination, c.bind) <ide> } <ide> <ide> if m.Source != c.expSource { <del> t.Fatalf("Expected source %s, was %s, for spec %s\n", c.expSource, m.Source, c.bind) <add> t.Fatalf("Expected source '%s', was '%s', for spec '%s'", c.expSource, m.Source, c.bind) <ide> } <ide> <ide> if m.Name != c.expName { <del> t.Fatalf("Expected name %s, was %s for spec %s\n", c.expName, m.Name, c.bind) <add> t.Fatalf("Expected name '%s', was '%s' for spec '%s'", c.expName, m.Name, c.bind) <ide> } <ide> <del> if m.Driver != c.expDriver { <del> t.Fatalf("Expected driver %s, was %s, for spec %s\n", c.expDriver, m.Driver, c.bind) <add> if (m.Driver != c.expDriver) || (m.Driver == DefaultDriverName && c.expDriver == "") { <add> t.Fatalf("Expected driver '%s', was '%s', for spec '%s'", c.expDriver, m.Driver, c.bind) <ide> } <ide> <ide> if m.RW != c.expRW { <del> t.Fatalf("Expected RW %v, was %v for spec %s\n", c.expRW, m.RW, c.bind) <add> t.Fatalf("Expected RW '%v', was '%v' for spec '%s'", c.expRW, m.RW, c.bind) <add> } <add> } <add>} <add> <add>func TestParseMountSpec(t *testing.T) { <add> type c struct { <add> input mount.Mount <add> expected MountPoint <add> } <add> testDir, err := ioutil.TempDir("", "test-mount-config") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(testDir) <add> <add> cases := []c{ <add> {mount.Mount{Type: mount.TypeBind, Source: testDir, Target: testDestinationPath, ReadOnly: true}, MountPoint{Type: mount.TypeBind, Source: testDir, Destination: testDestinationPath}}, <add> {mount.Mount{Type: mount.TypeBind, Source: testDir, Target: testDestinationPath}, MountPoint{Type: mount.TypeBind, Source: testDir, Destination: testDestinationPath, RW: true}}, <add> {mount.Mount{Type: mount.TypeBind, Source: testDir + string(os.PathSeparator), Target: testDestinationPath, ReadOnly: true}, MountPoint{Type: mount.TypeBind, Source: testDir, Destination: testDestinationPath}}, <add> {mount.Mount{Type: mount.TypeBind, Source: testDir, Target: testDestinationPath + string(os.PathSeparator), ReadOnly: true}, MountPoint{Type: mount.TypeBind, Source: testDir, Destination: testDestinationPath}}, <add> {mount.Mount{Type: mount.TypeVolume, Target: testDestinationPath}, MountPoint{Type: mount.TypeVolume, Destination: testDestinationPath, RW: true, Driver: DefaultDriverName, CopyData: DefaultCopyMode}}, <add> {mount.Mount{Type: mount.TypeVolume, Target: testDestinationPath + string(os.PathSeparator)}, MountPoint{Type: mount.TypeVolume, Destination: testDestinationPath, RW: true, Driver: DefaultDriverName, CopyData: DefaultCopyMode}}, <add> } <add> <add> for i, c := range cases { <add> t.Logf("case %d", i) <add> mp, err := ParseMountSpec(c.input) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if c.expected.Type != mp.Type { <add> t.Fatalf("Expected mount types to match. Expected: '%s', Actual: '%s'", c.expected.Type, mp.Type) <add> } <add> if c.expected.Destination != mp.Destination { <add> t.Fatalf("Expected mount destination to match. Expected: '%s', Actual: '%s'", c.expected.Destination, mp.Destination) <add> } <add> if c.expected.Source != mp.Source { <add> t.Fatalf("Expected mount source to match. Expected: '%s', Actual: '%s'", c.expected.Source, mp.Source) <add> } <add> if c.expected.RW != mp.RW { <add> t.Fatalf("Expected mount writable to match. Expected: '%v', Actual: '%s'", c.expected.RW, mp.RW) <add> } <add> if c.expected.Propagation != mp.Propagation { <add> t.Fatalf("Expected mount propagation to match. Expected: '%v', Actual: '%s'", c.expected.Propagation, mp.Propagation) <add> } <add> if c.expected.Driver != mp.Driver { <add> t.Fatalf("Expected mount driver to match. Expected: '%v', Actual: '%s'", c.expected.Driver, mp.Driver) <add> } <add> if c.expected.CopyData != mp.CopyData { <add> t.Fatalf("Expected mount copy data to match. Expected: '%v', Actual: '%v'", c.expected.CopyData, mp.CopyData) <ide> } <ide> } <ide> } <ide><path>volume/volume_unix.go <ide> package volume <ide> <ide> import ( <ide> "fmt" <add> "os" <ide> "path/filepath" <ide> "strings" <ide> <ide> mounttypes "github.com/docker/docker/api/types/mount" <ide> ) <ide> <add>var platformRawValidationOpts = []func(o *validateOpts){ <add> // need to make sure to not error out if the bind source does not exist on unix <add> // this is supported for historical reasons, the path will be automatically <add> // created later. <add> func(o *validateOpts) { o.skipBindSourceCheck = true }, <add>} <add> <ide> // read-write modes <ide> var rwModes = map[string]bool{ <ide> "rw": true, <ide> func (m *MountPoint) HasResource(absolutePath string) bool { <ide> return err == nil && relPath != ".." && !strings.HasPrefix(relPath, fmt.Sprintf("..%c", filepath.Separator)) <ide> } <ide> <del>// ParseMountSpec validates the configuration of mount information is valid. <del>func ParseMountSpec(spec, volumeDriver string) (*MountPoint, error) { <del> spec = filepath.ToSlash(spec) <del> <del> mp := &MountPoint{ <del> RW: true, <del> Propagation: DefaultPropagationMode, <del> } <del> if strings.Count(spec, ":") > 2 { <del> return nil, errInvalidSpec(spec) <del> } <del> <del> arr := strings.SplitN(spec, ":", 3) <del> if arr[0] == "" { <del> return nil, errInvalidSpec(spec) <del> } <del> <del> switch len(arr) { <del> case 1: <del> // Just a destination path in the container <del> mp.Destination = filepath.Clean(arr[0]) <del> case 2: <del> if isValid := ValidMountMode(arr[1]); isValid { <del> // Destination + Mode is not a valid volume - volumes <del> // cannot include a mode. eg /foo:rw <del> return nil, errInvalidSpec(spec) <del> } <del> // Host Source Path or Name + Destination <del> mp.Source = arr[0] <del> mp.Destination = arr[1] <del> case 3: <del> // HostSourcePath+DestinationPath+Mode <del> mp.Source = arr[0] <del> mp.Destination = arr[1] <del> mp.Mode = arr[2] // Mode field is used by SELinux to decide whether to apply label <del> if !ValidMountMode(mp.Mode) { <del> return nil, errInvalidMode(mp.Mode) <del> } <del> mp.RW = ReadWrite(mp.Mode) <del> mp.Propagation = GetPropagation(mp.Mode) <del> default: <del> return nil, errInvalidSpec(spec) <del> } <del> <del> //validate the volumes destination path <del> mp.Destination = filepath.Clean(mp.Destination) <del> if !filepath.IsAbs(mp.Destination) { <del> return nil, fmt.Errorf("Invalid volume destination path: '%s' mount path must be absolute.", mp.Destination) <del> } <del> <del> // Destination cannot be "/" <del> if mp.Destination == "/" { <del> return nil, fmt.Errorf("Invalid specification: destination can't be '/' in '%s'", spec) <del> } <del> <del> name, source := ParseVolumeSource(mp.Source) <del> if len(source) == 0 { <del> mp.Source = "" // Clear it out as we previously assumed it was not a name <del> mp.Driver = volumeDriver <del> // Named volumes can't have propagation properties specified. <del> // Their defaults will be decided by docker. This is just a <del> // safeguard. Don't want to get into situations where named <del> // volumes were mounted as '[r]shared' inside container and <del> // container does further mounts under that volume and these <del> // mounts become visible on host and later original volume <del> // cleanup becomes an issue if container does not unmount <del> // submounts explicitly. <del> if HasPropagation(mp.Mode) { <del> return nil, errInvalidSpec(spec) <del> } <del> } else { <del> mp.Source = filepath.Clean(source) <del> } <del> <del> copyData, isSet := getCopyMode(mp.Mode) <del> // do not allow copy modes on binds <del> if len(name) == 0 && isSet { <del> return nil, errInvalidMode(mp.Mode) <del> } <del> <del> mp.CopyData = copyData <del> mp.Name = name <del> <del> return mp, nil <del>} <del> <del>// ParseVolumeSource parses the origin sources that's mounted into the container. <del>// It returns a name and a source. It looks to see if the spec passed in <del>// is an absolute file. If it is, it assumes the spec is a source. If not, <del>// it assumes the spec is a name. <del>func ParseVolumeSource(spec string) (string, string) { <del> if !filepath.IsAbs(spec) { <del> return spec, "" <del> } <del> return "", spec <del>} <del> <ide> // IsVolumeNameValid checks a volume name in a platform specific manner. <ide> func IsVolumeNameValid(name string) (bool, error) { <ide> return true, nil <ide> func IsVolumeNameValid(name string) (bool, error) { <ide> // ValidMountMode will make sure the mount mode is valid. <ide> // returns if it's a valid mount mode or not. <ide> func ValidMountMode(mode string) bool { <add> if mode == "" { <add> return true <add> } <add> <ide> rwModeCount := 0 <ide> labelModeCount := 0 <ide> propagationModeCount := 0 <ide> func ReadWrite(mode string) bool { <ide> return false <ide> } <ide> } <del> <ide> return true <ide> } <add> <add>func validateNotRoot(p string) error { <add> p = filepath.Clean(convertSlash(p)) <add> if p == "/" { <add> return fmt.Errorf("invalid specification: destination can't be '/'") <add> } <add> return nil <add>} <add> <add>func validateCopyMode(mode bool) error { <add> return nil <add>} <add> <add>func convertSlash(p string) string { <add> return filepath.ToSlash(p) <add>} <add> <add>func splitRawSpec(raw string) ([]string, error) { <add> if strings.Count(raw, ":") > 2 { <add> return nil, errInvalidSpec(raw) <add> } <add> <add> arr := strings.SplitN(raw, ":", 3) <add> if arr[0] == "" { <add> return nil, errInvalidSpec(raw) <add> } <add> return arr, nil <add>} <add> <add>func clean(p string) string { <add> return filepath.Clean(p) <add>} <add> <add>func validateStat(fi os.FileInfo) error { <add> return nil <add>} <ide><path>volume/volume_windows.go <ide> import ( <ide> "regexp" <ide> "strings" <ide> <del> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/system" <ide> ) <ide> <ide> var roModes = map[string]bool{ <ide> "ro": true, <ide> } <ide> <add>var platformRawValidationOpts = []func(*validateOpts){ <add> // filepath.IsAbs is weird on Windows: <add> // `c:` is not considered an absolute path <add> // `c:\` is considered an absolute path <add> // In any case, the regex matching below ensures absolute paths <add> // TODO: consider this a bug with filepath.IsAbs (?) <add> func(o *validateOpts) { o.skipAbsolutePathCheck = true }, <add>} <add> <ide> const ( <ide> // Spec should be in the format [source:]destination[:mode] <ide> // <ide> func (m *MountPoint) BackwardsCompatible() bool { <ide> return false <ide> } <ide> <del>// ParseMountSpec validates the configuration of mount information is valid. <del>func ParseMountSpec(spec string, volumeDriver string) (*MountPoint, error) { <del> var specExp = regexp.MustCompile(`^` + RXSource + RXDestination + RXMode + `$`) <del> <del> // Ensure in platform semantics for matching. The CLI will send in Unix semantics. <del> match := specExp.FindStringSubmatch(filepath.FromSlash(strings.ToLower(spec))) <add>func splitRawSpec(raw string) ([]string, error) { <add> specExp := regexp.MustCompile(`^` + RXSource + RXDestination + RXMode + `$`) <add> match := specExp.FindStringSubmatch(strings.ToLower(raw)) <ide> <ide> // Must have something back <ide> if len(match) == 0 { <del> return nil, errInvalidSpec(spec) <add> return nil, errInvalidSpec(raw) <ide> } <ide> <del> // Pull out the sub expressions from the named capture groups <add> var split []string <ide> matchgroups := make(map[string]string) <add> // Pull out the sub expressions from the named capture groups <ide> for i, name := range specExp.SubexpNames() { <ide> matchgroups[name] = strings.ToLower(match[i]) <ide> } <del> <del> mp := &MountPoint{ <del> Source: matchgroups["source"], <del> Destination: matchgroups["destination"], <del> RW: true, <del> } <del> if strings.ToLower(matchgroups["mode"]) == "ro" { <del> mp.RW = false <del> } <del> <del> // Volumes cannot include an explicitly supplied mode eg c:\path:rw <del> if mp.Source == "" && mp.Destination != "" && matchgroups["mode"] != "" { <del> return nil, errInvalidSpec(spec) <del> } <del> <del> // Note: No need to check if destination is absolute as it must be by <del> // definition of matching the regex. <del> <del> if filepath.VolumeName(mp.Destination) == mp.Destination { <del> // Ensure the destination path, if a drive letter, is not the c drive <del> if strings.ToLower(mp.Destination) == "c:" { <del> return nil, fmt.Errorf("Destination drive letter in '%s' cannot be c:", spec) <del> } <del> } else { <del> // So we know the destination is a path, not drive letter. Clean it up. <del> mp.Destination = filepath.Clean(mp.Destination) <del> // Ensure the destination path, if a path, is not the c root directory <del> if strings.ToLower(mp.Destination) == `c:\` { <del> return nil, fmt.Errorf(`Destination path in '%s' cannot be c:\`, spec) <add> if source, exists := matchgroups["source"]; exists { <add> if source != "" { <add> split = append(split, source) <ide> } <ide> } <del> <del> // See if the source is a name instead of a host directory <del> if len(mp.Source) > 0 { <del> validName, err := IsVolumeNameValid(mp.Source) <del> if err != nil { <del> return nil, err <del> } <del> if validName { <del> // OK, so the source is a name. <del> mp.Name = mp.Source <del> mp.Source = "" <del> <del> // Set the driver accordingly <del> mp.Driver = volumeDriver <del> if len(mp.Driver) == 0 { <del> mp.Driver = DefaultDriverName <del> } <del> } else { <del> // OK, so the source must be a host directory. Make sure it's clean. <del> mp.Source = filepath.Clean(mp.Source) <add> if destination, exists := matchgroups["destination"]; exists { <add> if destination != "" { <add> split = append(split, destination) <ide> } <ide> } <del> <del> // Ensure the host path source, if supplied, exists and is a directory <del> if len(mp.Source) > 0 { <del> var fi os.FileInfo <del> var err error <del> if fi, err = os.Stat(mp.Source); err != nil { <del> return nil, fmt.Errorf("Source directory '%s' could not be found: %s", mp.Source, err) <del> } <del> if !fi.IsDir() { <del> return nil, fmt.Errorf("Source '%s' is not a directory", mp.Source) <add> if mode, exists := matchgroups["mode"]; exists { <add> if mode != "" { <add> split = append(split, mode) <ide> } <ide> } <del> <ide> // Fix #26329. If the destination appears to be a file, and the source is null, <ide> // it may be because we've fallen through the possible naming regex and hit a <ide> // situation where the user intention was to map a file into a container through <ide> // a local volume, but this is not supported by the platform. <del> if len(mp.Source) == 0 && len(mp.Destination) > 0 { <del> var fi os.FileInfo <del> var err error <del> if fi, err = os.Stat(mp.Destination); err == nil { <del> validName, err := IsVolumeNameValid(mp.Destination) <del> if err != nil { <del> return nil, err <del> } <del> if !validName && !fi.IsDir() { <del> return nil, fmt.Errorf("file '%s' cannot be mapped. Only directories can be mapped on this platform", mp.Destination) <add> if matchgroups["source"] == "" && matchgroups["destination"] != "" { <add> validName, err := IsVolumeNameValid(matchgroups["destination"]) <add> if err != nil { <add> return nil, err <add> } <add> if !validName { <add> if fi, err := os.Stat(matchgroups["destination"]); err == nil { <add> if !fi.IsDir() { <add> return nil, fmt.Errorf("file '%s' cannot be mapped. Only directories can be mapped on this platform", matchgroups["destination"]) <add> } <ide> } <ide> } <ide> } <del> <del> logrus.Debugf("MP: Source '%s', Dest '%s', RW %t, Name '%s', Driver '%s'", mp.Source, mp.Destination, mp.RW, mp.Name, mp.Driver) <del> return mp, nil <add> return split, nil <ide> } <ide> <ide> // IsVolumeNameValid checks a volume name in a platform specific manner. <ide> func IsVolumeNameValid(name string) (bool, error) { <ide> } <ide> nameExp = regexp.MustCompile(`^` + RXReservedNames + `$`) <ide> if nameExp.MatchString(name) { <del> return false, fmt.Errorf("Volume name %q cannot be a reserved word for Windows filenames", name) <add> return false, fmt.Errorf("volume name %q cannot be a reserved word for Windows filenames", name) <ide> } <ide> return true, nil <ide> } <ide> <ide> // ValidMountMode will make sure the mount mode is valid. <ide> // returns if it's a valid mount mode or not. <ide> func ValidMountMode(mode string) bool { <add> if mode == "" { <add> return true <add> } <ide> return roModes[strings.ToLower(mode)] || rwModes[strings.ToLower(mode)] <ide> } <ide> <ide> // ReadWrite tells you if a mode string is a valid read-write mode or not. <ide> func ReadWrite(mode string) bool { <del> return rwModes[strings.ToLower(mode)] <add> return rwModes[strings.ToLower(mode)] || mode == "" <add>} <add> <add>func validateNotRoot(p string) error { <add> p = strings.ToLower(convertSlash(p)) <add> if p == "c:" || p == `c:\` { <add> return fmt.Errorf("destination path cannot be `c:` or `c:\\`: %v", p) <add> } <add> return nil <add>} <add> <add>func validateCopyMode(mode bool) error { <add> if mode { <add> return fmt.Errorf("Windows does not support copying image path content") <add> } <add> return nil <add>} <add> <add>func convertSlash(p string) string { <add> return filepath.FromSlash(p) <add>} <add> <add>func clean(p string) string { <add> if match, _ := regexp.MatchString("^[a-z]:$", p); match { <add> return p <add> } <add> return filepath.Clean(p) <add>} <add> <add>func validateStat(fi os.FileInfo) error { <add> if !fi.IsDir() { <add> return fmt.Errorf("source path must be a directory") <add> } <add> return nil <ide> }
30
Javascript
Javascript
improve the jsdocs for the `pdfobjects` class
bad15894fc0ceac0cd8823dd4b55689261d29ca1
<ide><path>src/display/api.js <ide> const DefaultStandardFontDataFactory = <ide> */ <ide> <ide> /** <del> * @type IPDFStreamFactory <add> * @type {IPDFStreamFactory} <ide> * @private <ide> */ <ide> let createPDFNetworkStream; <ide> class PDFPageProxy { <ide> this._transport = transport; <ide> this._stats = pdfBug ? new StatTimer() : null; <ide> this._pdfBug = pdfBug; <add> /** @type {PDFObjects} */ <ide> this.commonObjs = transport.commonObjs; <ide> this.objs = new PDFObjects(); <ide> <ide> class WorkerTransport { <ide> * A PDF document and page is built of many objects. E.g. there are objects for <ide> * fonts, images, rendering code, etc. These objects may get processed inside of <ide> * a worker. This class implements some basic methods to manage these objects. <del> * @ignore <ide> */ <ide> class PDFObjects { <ide> #objs = Object.create(null); <ide> <ide> /** <ide> * Ensures there is an object defined for `objId`. <add> * <add> * @param {string} objId <add> * @returns {Object} <ide> */ <ide> #ensureObj(objId) { <ide> const obj = this.#objs[objId]; <ide> class PDFObjects { <ide> * If called *with* a callback, the callback is called with the data of the <ide> * object once the object is resolved. That means, if you call this method <ide> * and the object is already resolved, the callback gets called right away. <add> * <add> * @param {string} objId <add> * @param {function} [callback] <add> * @returns {any} <ide> */ <ide> get(objId, callback = null) { <ide> // If there is a callback, then the get can be async and the object is <ide> class PDFObjects { <ide> return obj.data; <ide> } <ide> <add> /** <add> * @param {string} objId <add> * @returns {boolean} <add> */ <ide> has(objId) { <ide> const obj = this.#objs[objId]; <ide> return obj?.capability.settled || false; <ide> } <ide> <ide> /** <ide> * Resolves the object `objId` with optional `data`. <add> * <add> * @param {string} objId <add> * @param {any} [data] <ide> */ <ide> resolve(objId, data = null) { <ide> const obj = this.#ensureObj(objId);
1
Javascript
Javascript
fix incorrect comment example for userid
1bb4e87dd6a0b3a3a66b72faf5056d3f47caf52b
<ide><path>src/ngResource/resource.js <ide> function shallowClearAndCopy(src, dst) { <ide> * read, update, delete) on server-side data like this: <ide> * ```js <ide> * var User = $resource('/user/:userId', {userId:'@id'}); <del> * var user = User.get({userId:123}, function() { <add> * var user = User.get({id:123}, function() { <ide> * user.abc = true; <ide> * user.$save(); <ide> * });
1
Javascript
Javascript
add skipped test for compat mode attrs-proxy
36225a2df71bdfab5de9580a332963793a294ee1
<ide><path>packages/ember-views/tests/compat/attrs_proxy_test.js <add>import View from "ember-views/views/view"; <add>import { runAppend, runDestroy } from "ember-runtime/tests/utils"; <add>import compile from "ember-template-compiler/system/compile"; <add>import Registry from "container/registry"; <add> <add>var view, registry, container; <add> <add>QUnit.module("ember-views: attrs-proxy", { <add> setup() { <add> registry = new Registry(); <add> container = registry.container(); <add> }, <add> <add> teardown() { <add> runDestroy(view); <add> } <add>}); <add> <add>QUnit.skip('works with properties setup in root of view', function() { <add> registry.register('view:foo', View.extend({ <add> bar: 'qux', <add> <add> template: compile('{{bar}}') <add> })); <add> <add> view = View.extend({ <add> container: registry.container(), <add> template: compile('{{view "foo" bar="baz"}}') <add> }).create(); <add> <add> runAppend(view); <add> <add> equal(view.$().text(), 'baz', 'value specified in the template is used'); <add>});
1
PHP
PHP
fix error on php 5.4
201dae5d527ccd01b30b82d9c3793ebac9a425e9
<ide><path>src/Controller/Component/AuthComponent.php <ide> public function startup(Event $event) { <ide> return $this->_unauthenticated($controller); <ide> } <ide> <add> $authorize = $this->config('authorize'); <ide> if ($this->_isLoginAction($controller) || <del> empty($this->config('authorize')) || <add> empty($authorize) || <ide> $this->isAuthorized($this->user()) <ide> ) { <ide> return true;
1
Python
Python
enable pegasus fp16 by clamping large activations
9e80f972fb41b40c224c007ffd04a3c2744b83fe
<ide><path>src/transformers/modeling_bart.py <ide> def forward(self, x, encoder_padding_mask, output_attentions=False): <ide> x = residual + x <ide> if not self.normalize_before: <ide> x = self.final_layer_norm(x) <add> if torch.isinf(x).any() or torch.isnan(x).any(): <add> clamp_value = torch.finfo(x.dtype).max - 1000 <add> x = torch.clamp(x, min=-clamp_value, max=clamp_value) <ide> return x, attn_weights <ide> <ide> <ide><path>tests/test_modeling_pegasus.py <ide> def test_pegasus_xsum_summary(self): <ide> # Demonstrate fp16 issue, Contributions welcome! <ide> self.model.half() <ide> translated_tokens_fp16 = self.model.generate(**inputs, max_length=10) <del> decoded = self.tokenizer.batch_decode(translated_tokens_fp16, skip_special_tokens=True) <del> bad_fp16_result = ["unk_7unk_7unk_7unk_7unk_7unk_7unk_7", "unk_7unk_7unk_7unk_7unk_7unk_7unk_7"] <del> self.assertListEqual(decoded, bad_fp16_result) <add> decoded_fp16 = self.tokenizer.batch_decode(translated_tokens_fp16, skip_special_tokens=True) <add> assert decoded_fp16 == [ <add> "California's largest electricity provider has begun", <add> "N-Dubz have revealed they were", <add> ] <ide> <ide> <ide> class PegasusConfigTests(unittest.TestCase):
2
PHP
PHP
rewrote validation library
c3b8524e1b97bbe14e3b5130d3c9b5d75eea75d7
<ide><path>application/lang/en/validation.php <ide> <ide> return array( <ide> <del> /* <del> |-------------------------------------------------------------------------- <del> | General Validation Messages <del> |-------------------------------------------------------------------------- <del> */ <del> <del> "acceptance_of" => "The :attribute must be accepted.", <del> "confirmation_of" => "The :attribute confirmation does not match.", <del> "exclusion_of" => "The :attribute value is invalid.", <del> "format_of" => "The :attribute format is invalid.", <del> "inclusion_of" => "The :attribute value is invalid.", <del> "presence_of" => "The :attribute can't be empty.", <del> "uniqueness_of" => "The :attribute has already been taken.", <del> "with_callback" => "The :attribute is invalid.", <del> <del> /* <del> |-------------------------------------------------------------------------- <del> | Numericality_Of Validation Messages <del> |-------------------------------------------------------------------------- <del> */ <del> <del> "number_not_valid" => "The :attribute must be a number.", <del> "number_not_integer" => "The :attribute must be an integer.", <del> "number_wrong_size" => "The :attribute must be :size.", <del> "number_too_big" => "The :attribute must be no more than :max.", <del> "number_too_small" => "The :attribute must be at least :min.", <del> <del> /* <del> |-------------------------------------------------------------------------- <del> | Length_Of Validation Messages <del> |-------------------------------------------------------------------------- <del> */ <del> <del> "string_wrong_size" => "The :attribute must be :size characters.", <del> "string_too_big" => "The :attribute must be no more than :max characters.", <del> "string_too_small" => "The :attribute must be at least :min characters.", <del> <del> /* <del> |-------------------------------------------------------------------------- <del> | Upload_Of Validation Messages <del> |-------------------------------------------------------------------------- <del> */ <del> <del> "file_wrong_type" => "The :attribute must be a file of type: :types.", <del> "file_too_big" => "The :attribute exceeds size limit of :maxkb.", <add> "accepted" => "The :attribute must be accepted.", <add> "active_url" => "The :attribute does not exist.", <add> "alpha" => "The :attribute may only contain letters.", <add> "alpha_dash" => "The :attribute may only contain letters, numbers, dashes, and underscores.", <add> "alpha_num" => "The :attribute may only contain letters and numbers.", <add> "between" => "The :attribute must be between :min - :max.", <add> "confirmed" => "The :attribute confirmation does not match.", <add> "email" => "The :attribute format is invalid.", <add> "image" => "The :attribute must be an image.", <add> "in" => "The selected :attribute is invalid.", <add> "integer" => "The :attribute must be an integer.", <add> "max" => "The :attribute must be less than :max.", <add> "mimes" => "The :attribute must be a file of type: :values.", <add> "min" => "The :attribute must be at least :min.", <add> "not_in" => "The selected :attribute is invalid.", <add> "numeric" => "The :attribute must be a number.", <add> "required" => "The :attribute field is required.", <add> "size" => "The :attribute must be :size.", <add> "unique" => "The :attribute has already been taken.", <add> "url" => "The :attribute format is invalid.", <ide> <ide> ); <ide>\ No newline at end of file <ide><path>system/db/eloquent.php <ide> abstract class Eloquent { <ide> * @return void <ide> */ <ide> public function __construct($attributes = array()) <add> { <add> $this->fill($attributes); <add> } <add> <add> /** <add> * Set the attributes of the model using an array. <add> * <add> * @param array $attributes <add> * @return void <add> */ <add> public function fill($attributes) <ide> { <ide> foreach ($attributes as $key => $value) <ide> { <ide><path>system/input.php <ide> class Input { <ide> */ <ide> public static $input; <ide> <add> /** <add> * Get all of the input data for the request. <add> * <add> * This method returns a merged array containing Input::get and Input::file. <add> * <add> * @return array <add> */ <add> public static function all() <add> { <add> return array_merge(static::get(), static::file()); <add> } <add> <ide> /** <ide> * Determine if the input data contains an item. <ide> * <ide><path>system/lang.php <ide> public static function line($key) <ide> /** <ide> * Get the language line. <ide> * <add> * @param string $language <ide> * @param mixed $default <ide> * @return string <ide> */ <del> public function get($default = null) <add> public function get($language = null, $default = null) <ide> { <del> $language = Config::get('application.language'); <add> if (is_null($language)) <add> { <add> $language = Config::get('application.language'); <add> } <ide> <ide> list($file, $line) = $this->parse($this->key); <ide> <ide> $this->load($file, $language); <ide> <del> if ( ! array_key_exists($language.$file, static::$lines)) <add> if ( ! isset(static::$lines[$language.$file][$line])) <ide> { <del> $line = is_callable($default) ? call_user_func($default) : $default; <del> } <del> else <del> { <del> $line = Arr::get(static::$lines[$language.$file], $line, $default); <add> return is_callable($default) ? call_user_func($default) : $default; <ide> } <ide> <add> $line = static::$lines[$language.$file][$line]; <add> <ide> foreach ($this->replacements as $key => $value) <ide> { <ide> $line = str_replace(':'.$key, $value, $line); <ide><path>system/str.php <ide> public static function length($value) <ide> /** <ide> * Generate a random alpha or alpha-numeric string. <ide> * <del> * Supported types: 'alnum' and 'alpha'. <add> * Supported types: 'alpha_num' and 'alpha'. <ide> * <ide> * @param int $length <ide> * @param string $type <ide> * @return string <ide> */ <del> public static function random($length = 16, $type = 'alnum') <add> public static function random($length = 16, $type = 'alpha_num') <ide> { <ide> $value = ''; <ide> <ide> public static function random($length = 16, $type = 'alnum') <ide> * @param string $type <ide> * @return string <ide> */ <del> private static function pool($type = 'alnum') <add> private static function pool($type = 'alpha_num') <ide> { <ide> switch ($type) <ide> { <del> case 'alnum': <add> case 'alpha_num': <ide> return '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; <ide> <ide> default: <add><path>system/validation/errors.php <del><path>system/validation/error_collector.php <ide> <?php namespace System\Validation; <ide> <del>class Error_Collector { <add>class Errors { <ide> <ide> /** <ide> * All of the error messages. <ide> class Error_Collector { <ide> public $messages; <ide> <ide> /** <del> * Create a new Error Collector instance. <add> * Create a new Errors instance. <ide> * <ide> * @return void <ide> */ <ide> public function __construct($messages = array()) <ide> */ <ide> public function add($attribute, $message) <ide> { <del> // ------------------------------------------------------------- <ide> // Make sure the error message is not duplicated. <del> // <del> // For example, the Nullable rules can add a "required" message. <del> // If the same message has already been added we don't want to <del> // add it again. <del> // ------------------------------------------------------------- <ide> if ( ! array_key_exists($attribute, $this->messages) or ! is_array($this->messages[$attribute]) or ! in_array($message, $this->messages[$attribute])) <ide> { <ide> $this->messages[$attribute][] = $message; <ide> public function all($format = ':message') <ide> { <ide> $all = array(); <ide> <del> // --------------------------------------------------------- <del> // Add each error message to the array of messages. Each <del> // messages will have the specified format applied to it. <del> // --------------------------------------------------------- <ide> foreach ($this->messages as $messages) <ide> { <ide> $all = array_merge($all, $this->format($messages, $format)); <ide><path>system/validation/message.php <del><?php namespace System\Validation; <del> <del>use System\Str; <del>use System\Lang; <del> <del>class Message { <del> <del> /** <del> * Get the appropriate validation message for a rule attribute. <del> * <del> * @param Rule $rule <del> * @param string $attribute <del> * @return string <del> */ <del> public static function get($rule, $attribute) <del> { <del> if ($rule instanceof Rangable_Rule) <del> { <del> $message = static::get_rangable_message($rule); <del> } <del> elseif ($rule instanceof Rules\Upload_of) <del> { <del> $message = static::get_upload_of_message($rule); <del> } <del> else <del> { <del> $message = static::get_message($rule); <del> } <del> <del> return static::prepare($rule, $attribute, $message); <del> } <del> <del> /** <del> * Get the error message for a typical validation rule. <del> * <del> * @param Rule $rule <del> * @return string <del> */ <del> private static function get_message($rule) <del> { <del> // --------------------------------------------------------- <del> // The built-in error messages are stored in the language <del> // directory and are keyed by the class name of the rule <del> // they are associated with. <del> // --------------------------------------------------------- <del> if (is_null($rule->error)) <del> { <del> $class = explode('\\', get_class($rule)); <del> <del> $rule->error = strtolower(end($class)); <del> } <del> <del> return (is_null($rule->message)) ? Lang::line('validation.'.$rule->error)->get() : $rule->message; <del> } <del> <del> /** <del> * Get the error message for a Rangable rule. <del> * <del> * @param Rule $rule <del> * @return string <del> */ <del> private static function get_rangable_message($rule) <del> { <del> // --------------------------------------------------------- <del> // Rangable rules sometimes set a "presence_of" error. <del> // <del> // This occurs when an attribute is null and the option to <del> // allow null values has not been set. <del> // --------------------------------------------------------- <del> if ($rule->error == 'presence_of') <del> { <del> return static::get_message($rule); <del> } <del> <del> // --------------------------------------------------------- <del> // Slice "number_" or "string_" off of the error type. <del> // --------------------------------------------------------- <del> $error_type = substr($rule->error, 7); <del> <del> return (is_null($rule->$error_type)) ? Lang::line('validation.'.$rule->error)->get() : $rule->$error_type; <del> } <del> <del> /** <del> * Get the error message for an Upload_Of rule. <del> * <del> * @param Rule $rule <del> * @return string <del> */ <del> private static function get_upload_of_message($rule) <del> { <del> // --------------------------------------------------------- <del> // Upload_Of rules sometimes set a "presence_of" error. <del> // <del> // This occurs when the uploaded file didn't exist and the <del> // "not_required" method was not called. <del> // --------------------------------------------------------- <del> if ($rule->error == 'presence_of') <del> { <del> return static::get_message($rule); <del> } <del> <del> // --------------------------------------------------------- <del> // Slice "file_" off of the error type. <del> // --------------------------------------------------------- <del> $error_type = substr($rule->error, 5); <del> <del> return (is_null($rule->$error_type)) ? Lang::line('validation.'.$rule->error)->get() : $rule->$error_type; <del> } <del> <del> /** <del> * Prepare an error message for display. All place-holders will be replaced <del> * with their actual values. <del> * <del> * @param Rule $rule <del> * @param string $attribute <del> * @param string $message <del> * @return string <del> */ <del> private static function prepare($rule, $attribute, $message) <del> { <del> // --------------------------------------------------------- <del> // The rangable rule messages have three place-holders that <del> // must be replaced. <del> // <del> // :max = The maximum size of the attribute. <del> // :min = The minimum size of the attribute. <del> // :size = The exact size the attribute must be. <del> // --------------------------------------------------------- <del> if ($rule instanceof Rangable_Rule) <del> { <del> $message = str_replace(':max', $rule->maximum, $message); <del> $message = str_replace(':min', $rule->minimum, $message); <del> $message = str_replace(':size', $rule->size, $message); <del> } <del> // --------------------------------------------------------- <del> // The Upload_Of rule message have two place-holders taht <del> // must be replaced. <del> // <del> // :max = The maximum file size of the upload (kilobytes). <del> // :types = The allowed file types for the upload. <del> // --------------------------------------------------------- <del> elseif ($rule instanceof Rules\Upload_Of) <del> { <del> $message = str_replace(':max', $rule->maximum, $message); <del> <del> if (is_array($rule->types)) <del> { <del> $message = str_replace(':types', implode(', ', $rule->types), $message); <del> } <del> } <del> <del> return str_replace(':attribute', Lang::line('attributes.'.$attribute)->get(str_replace('_', ' ', $attribute)), $message); <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/nullable_rule.php <del><?php namespace System\Validation; <del> <del>use System\Str; <del> <del>abstract class Nullable_Rule extends Rule { <del> <del> /** <del> * Indicates an empty value should be considered valid. <del> * <del> * @var bool <del> */ <del> public $allow_empty = false; <del> <del> /** <del> * Indicates null should be considered valid. <del> * <del> * @var bool <del> */ <del> public $allow_null = false; <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * If this method returns a value, the child class will return it <del> * as the result of the validation. Otherwise, the child class will <del> * continue validating as normal. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return mixed <del> */ <del> public function check($attribute, $attributes) <del> { <del> // ------------------------------------------------------------- <del> // If the attribute doesn't exist, the child's validation <del> // check will be be halted, and a presence_of error will be <del> // raised if null is not allowed. <del> // ------------------------------------------------------------- <del> if ( ! array_key_exists($attribute, $attributes)) <del> { <del> if ( ! $this->allow_null) <del> { <del> $this->error = 'presence_of'; <del> } <del> <del> return is_null($this->error); <del> } <del> <del> // ------------------------------------------------------------- <del> // Make sure the attribute is not an empty string. An error <del> // will be raised if the attribute is empty and empty strings <del> // are not allowed, halting the child's validation. <del> // ------------------------------------------------------------- <del> elseif (Str::length((string) $attributes[$attribute]) == 0 and ! $this->allow_empty) <del> { <del> $this->error = 'presence_of'; <del> <del> return false; <del> } <del> } <del> <del> /** <del> * Allow a empty and null to be considered valid. <del> * <del> * @return Nullable_Rule <del> */ <del> public function not_required() <del> { <del> return $this->allow_empty()->allow_null(); <del> } <del> <del> /** <del> * Allow empty to be considered valid. <del> * <del> * @return Nullable_Rule <del> */ <del> public function allow_empty() <del> { <del> $this->allow_empty = true; <del> return $this; <del> } <del> <del> /** <del> * Allow null to be considered valid. <del> * <del> * @return Nullable_Rule <del> */ <del> public function allow_null() <del> { <del> $this->allow_null = true; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rangable_rule.php <del><?php namespace System\Validation; <del> <del>abstract class Rangable_Rule extends Nullable_Rule { <del> <del> /** <del> * The exact size the attribute must be. <del> * <del> * @var int <del> */ <del> public $size; <del> <del> /** <del> * The maximum size of the attribute. <del> * <del> * @var int <del> */ <del> public $maximum; <del> <del> /** <del> * The minimum size of the attribute. <del> * <del> * @var int <del> */ <del> public $minimum; <del> <del> /** <del> * The "wrong size" error message. <del> * <del> * @var string <del> */ <del> public $wrong_size; <del> <del> /** <del> * The "too big" error message. <del> * <del> * @var string <del> */ <del> public $too_big; <del> <del> /** <del> * The "too small" error message. <del> * <del> * @var string <del> */ <del> public $too_small; <del> <del> /** <del> * Set the exact size the attribute must be. <del> * <del> * @param int $size <del> * @return Rangable_Rule <del> */ <del> public function is($size) <del> { <del> $this->size = $size; <del> return $this; <del> } <del> <del> /** <del> * Set the minimum and maximum size of the attribute. <del> * <del> * @param int $minimum <del> * @param int $maximum <del> * @return Rangable_Rule <del> */ <del> public function between($minimum, $maximum) <del> { <del> $this->minimum = $minimum; <del> $this->maximum = $maximum; <del> <del> return $this; <del> } <del> <del> /** <del> * Set the minimum size the attribute. <del> * <del> * @param int $minimum <del> * @return Rangable_Rule <del> */ <del> public function minimum($minimum) <del> { <del> $this->minimum = $minimum; <del> return $this; <del> } <del> <del> /** <del> * Set the maximum size the attribute. <del> * <del> * @param int $maximum <del> * @return Rangable_Rule <del> */ <del> public function maximum($maximum) <del> { <del> $this->maximum = $maximum; <del> return $this; <del> } <del> <del> /** <del> * Set the validation error message. <del> * <del> * @param string $message <del> * @return Rangable_Rule <del> */ <del> public function message($message) <del> { <del> return $this->wrong_size($message)->too_big($message)->too_small($message); <del> } <del> <del> /** <del> * Set the "wrong size" error message. <del> * <del> * @param string $message <del> * @return Rangable_Rule <del> */ <del> public function wrong_size($message) <del> { <del> $this->wrong_size = $message; <del> return $this; <del> } <del> <del> /** <del> * Set the "too big" error message. <del> * <del> * @param string $message <del> * @return Rangable_Rule <del> */ <del> public function too_big($message) <del> { <del> $this->too_big = $message; <del> return $this; <del> } <del> <del> /** <del> * Set the "too small" error message. <del> * <del> * @param string $message <del> * @return Rangable_Rule <del> */ <del> public function too_small($message) <del> { <del> $this->too_small = $message; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rule.php <del><?php namespace System\Validation; <del> <del>use System\Lang; <del> <del>abstract class Rule { <del> <del> /** <del> * The attributes being validated by the rule. <del> * <del> * @var array <del> */ <del> public $attributes; <del> <del> /** <del> * The validation error message. <del> * <del> * @var string <del> */ <del> public $message; <del> <del> /** <del> * The error type. This is used for rules that have more than <del> * one type of error such as Size_Of and Upload_Of. <del> * <del> * @var string <del> */ <del> public $error; <del> <del> /** <del> * Create a new validation Rule instance. <del> * <del> * @param array $attributes <del> * @return void <del> */ <del> public function __construct($attributes) <del> { <del> $this->attributes = $attributes; <del> } <del> <del> /** <del> * Run the validation rule. <del> * <del> * @param array $attributes <del> * @param Error_Collector $errors <del> * @return void <del> */ <del> public function validate($attributes, $errors) <del> { <del> foreach ($this->attributes as $attribute) <del> { <del> $this->error = null; <del> <del> if ( ! $this->check($attribute, $attributes)) <del> { <del> $errors->add($attribute, Message::get($this, $attribute)); <del> } <del> } <del> } <del> <del> /** <del> * Set the validation error message. <del> * <del> * @param string $message <del> * @return Rule <del> */ <del> public function message($message) <del> { <del> $this->message = $message; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/acceptance_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\Input; <del>use System\Validation\Rule; <del> <del>class Acceptance_Of extends Rule { <del> <del> /** <del> * The value is that is considered accepted. <del> * <del> * @var string <del> */ <del> public $accepts = '1'; <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> return Input::has($attribute) and (string) Input::get($attribute) === $this->accepts; <del> } <del> <del> /** <del> * Set the accepted value. <del> * <del> * @param string $value <del> * @return Acceptance_Of <del> */ <del> public function accepts($value) <del> { <del> $this->accepts = $value; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/confirmation_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\Input; <del>use System\Validation\Rule; <del> <del>class Confirmation_Of extends Rule { <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> if ( ! array_key_exists($attribute, $attributes)) <del> { <del> return true; <del> } <del> <del> return Input::has($attribute.'_confirmation') and $attributes[$attribute] === Input::get($attribute.'_confirmation'); <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/exclusion_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\Validation\Nullable_Rule; <del> <del>class Exclusion_Of extends Nullable_Rule { <del> <del> /** <del> * The reserved values for the attribute. <del> * <del> * @var string <del> */ <del> public $reserved; <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> if ( ! is_null($nullable = parent::check($attribute, $attributes))) <del> { <del> return $nullable; <del> } <del> <del> return ! in_array($attributes[$attribute], $this->reserved); <del> } <del> <del> /** <del> * Set the reserved values for the attribute <del> * <del> * @param array $reserved <del> * @return Exclusion_Of <del> */ <del> public function from($reserved) <del> { <del> $this->reserved = $reserved; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/format_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\Validation\Nullable_Rule; <del> <del>class Format_Of extends Nullable_Rule { <del> <del> /** <del> * The regular expression that will be used to validate the attribute. <del> * <del> * @var string <del> */ <del> public $expression; <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> if ( ! is_null($nullable = parent::check($attribute, $attributes))) <del> { <del> return $nullable; <del> } <del> <del> return preg_match($this->expression, $attributes[$attribute]); <del> } <del> <del> /** <del> * Set the regular expression. <del> * <del> * @param string $expression <del> * @return Format_Of <del> */ <del> public function using($expression) <del> { <del> $this->expression = $expression; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/inclusion_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\Validation\Nullable_Rule; <del> <del>class Inclusion_Of extends Nullable_Rule { <del> <del> /** <del> * The accepted values for the attribute. <del> * <del> * @var string <del> */ <del> public $accepted; <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> if ( ! is_null($nullable = parent::check($attribute, $attributes))) <del> { <del> return $nullable; <del> } <del> <del> return in_array($attributes[$attribute], $this->accepted); <del> } <del> <del> /** <del> * Set the accepted values for the attribute. <del> * <del> * @param array $accepted <del> * @return Inclusion_Of <del> */ <del> public function in($accepted) <del> { <del> $this->accepted = $accepted; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/length_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\Str; <del>use System\Validation\Rangable_Rule; <del> <del>class Length_Of extends Rangable_Rule { <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> if ( ! is_null($nullable = parent::check($attribute, $attributes))) <del> { <del> return $nullable; <del> } <del> <del> $value = trim((string) $attributes[$attribute]); <del> <del> // --------------------------------------------------------- <del> // Validate the exact length of the attribute. <del> // --------------------------------------------------------- <del> if ( ! is_null($this->size) and Str::length($value) !== $this->size) <del> { <del> $this->error = 'string_wrong_size'; <del> } <del> // --------------------------------------------------------- <del> // Validate the maximum length of the attribute. <del> // --------------------------------------------------------- <del> elseif ( ! is_null($this->maximum) and Str::length($value) > $this->maximum) <del> { <del> $this->error = 'string_too_big'; <del> } <del> // --------------------------------------------------------- <del> // Validate the minimum length of the attribute. <del> // --------------------------------------------------------- <del> elseif ( ! is_null($this->minimum) and Str::length($value) < $this->minimum) <del> { <del> $this->error = 'string_too_small'; <del> } <del> <del> return is_null($this->error); <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/numericality_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\Validation\Rangable_Rule; <del> <del>class Numericality_Of extends Rangable_Rule { <del> <del> /** <del> * Indicates that the attribute must be an integer. <del> * <del> * @var bool <del> */ <del> public $only_integer = false; <del> <del> /** <del> * The "not valid" error message. <del> * <del> * @var string <del> */ <del> public $not_valid; <del> <del> /** <del> * The "not integer" error message. <del> * <del> * @var string <del> */ <del> public $not_integer; <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> if ( ! is_null($nullable = parent::check($attribute, $attributes))) <del> { <del> return $nullable; <del> } <del> <del> // --------------------------------------------------------- <del> // Validate the attribute is a number. <del> // --------------------------------------------------------- <del> if ( ! is_numeric($attributes[$attribute])) <del> { <del> $this->error = 'number_not_valid'; <del> } <del> // --------------------------------------------------------- <del> // Validate the attribute is an integer. <del> // --------------------------------------------------------- <del> elseif ($this->only_integer and filter_var($attributes[$attribute], FILTER_VALIDATE_INT) === false) <del> { <del> $this->error = 'number_not_integer'; <del> } <del> // --------------------------------------------------------- <del> // Validate the exact size of the attribute. <del> // --------------------------------------------------------- <del> elseif ( ! is_null($this->size) and $attributes[$attribute] != $this->size) <del> { <del> $this->error = 'number_wrong_size'; <del> } <del> // --------------------------------------------------------- <del> // Validate the maximum size of the attribute. <del> // --------------------------------------------------------- <del> elseif ( ! is_null($this->maximum) and $attributes[$attribute] > $this->maximum) <del> { <del> $this->error = 'number_too_big'; <del> } <del> // --------------------------------------------------------- <del> // Validate the minimum size of the attribute. <del> // --------------------------------------------------------- <del> elseif ( ! is_null($this->minimum) and $attributes[$attribute] < $this->minimum) <del> { <del> $this->error = 'number_too_small'; <del> } <del> <del> return is_null($this->error); <del> } <del> <del> /** <del> * Specify that the attribute must be an integer. <del> * <del> * @return Numericality_Of <del> */ <del> public function only_integer() <del> { <del> $this->only_integer = true; <del> return $this; <del> } <del> <del> /** <del> * Set the "not valid" error message. <del> * <del> * @param string $message <del> * @return Numericality_Of <del> */ <del> public function not_valid($message) <del> { <del> $this->not_valid = $message; <del> return $this; <del> } <del> <del> /** <del> * Set the "not integer" error message. <del> * <del> * @param string $message <del> * @return Numericality_Of <del> */ <del> public function not_integer($message) <del> { <del> $this->not_integer = $message; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/presence_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\Validation\Nullable_Rule; <del> <del>class Presence_Of extends Nullable_Rule { <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> if ( ! is_null($nullable = parent::check($attribute, $attributes))) <del> { <del> return $nullable; <del> } <del> <del> // --------------------------------------------------------- <del> // The Nullable_Rule check method essentially is a check for <del> // the presence of an attribute, so there is no further <del> // checking that needs to be done. <del> // --------------------------------------------------------- <del> return true; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/uniqueness_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\DB; <del>use System\Validation\Nullable_Rule; <del> <del>class Uniqueness_Of extends Nullable_Rule { <del> <del> /** <del> * The database table that should be checked. <del> * <del> * @var string <del> */ <del> public $table; <del> <del> /** <del> * The database column that should be checked. <del> * <del> * @var string <del> */ <del> public $column; <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> if ( ! is_null($nullable = parent::check($attribute, $attributes))) <del> { <del> return $nullable; <del> } <del> <del> if (is_null($this->column)) <del> { <del> $this->column = $attribute; <del> } <del> <del> return DB::table($this->table)->where($this->column, '=', $attributes[$attribute])->count() == 0; <del> } <del> <del> /** <del> * Set the database table and column. <del> * <del> * The attribute name will be used as the column name if no other <del> * column name is specified. <del> * <del> * @param string $table <del> * @param string $column <del> * @return Uniqueness_Of <del> */ <del> public function on($table, $column = null) <del> { <del> $this->table = $table; <del> $this->column = $column; <del> <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/upload_of.php <del><?php namespace System\Validation\Rules; <del> <del>use System\File; <del>use System\Input; <del>use System\Validation\Nullable_Rule; <del> <del>class Upload_Of extends Nullable_Rule { <del> <del> /** <del> * The acceptable file types. <del> * <del> * @var array <del> */ <del> public $types = array(); <del> <del> /** <del> * The maximum file size in bytes. <del> * <del> * @var int <del> */ <del> public $maximum; <del> <del> /** <del> * The "wrong type" error message. <del> * <del> * @var string <del> */ <del> public $wrong_type; <del> <del> /** <del> * The "too big" error message. <del> * <del> * @var string <del> */ <del> public $too_big; <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> // ----------------------------------------------------- <del> // Check the presence of the upload. If the upload does <del> // not exist and the upload is required, a presence_of <del> // error will be raised. <del> // <del> // Otherwise no error will be raised. <del> // ----------------------------------------------------- <del> if ( ! array_key_exists($attribute, Input::file())) <del> { <del> if ( ! $this->allow_null) <del> { <del> $this->error = 'presence_of'; <del> } <del> <del> return is_null($this->error); <del> } <del> <del> // ----------------------------------------------------- <del> // Uploaded files are stored in the $_FILES array, so <del> // we use that array instead of the $attributes. <del> // ----------------------------------------------------- <del> $file = Input::file($attribute); <del> <del> if ( ! is_null($this->maximum) and $file['size'] > $this->maximum * 1000) <del> { <del> $this->error = 'file_too_big'; <del> } <del> <del> // ----------------------------------------------------- <del> // The File::is method uses the Fileinfo PHP extension <del> // to determine the MIME type of the file. <del> // ----------------------------------------------------- <del> foreach ($this->types as $type) <del> { <del> if (File::is($type, $file['tmp_name'])) <del> { <del> break; <del> } <del> <del> $this->error = 'file_wrong_type'; <del> } <del> <del> return is_null($this->error); <del> } <del> <del> /** <del> * Set the acceptable file types. <del> * <del> * @return Upload_Of <del> */ <del> public function is() <del> { <del> $this->types = func_get_args(); <del> return $this; <del> } <del> <del> /** <del> * Require that the uploaded file is an image type. <del> * <del> * @return Upload_Of <del> */ <del> public function is_image() <del> { <del> $this->types = array_merge($this->types, array('jpg', 'gif', 'png', 'bmp')); <del> return $this; <del> } <del> <del> /** <del> * Set the maximum file size in kilobytes. <del> * <del> * @param int $maximum <del> * @return Upload_Of <del> */ <del> public function maximum($maximum) <del> { <del> $this->maximum = $maximum; <del> return $this; <del> } <del> <del> /** <del> * Set the validation error message. <del> * <del> * @param string $message <del> * @return Upload_Of <del> */ <del> public function message($message) <del> { <del> return $this->wrong_type($message)->too_big($message); <del> } <del> <del> /** <del> * Set the "wrong type" error message. <del> * <del> * @param string $message <del> * @return Upload_Of <del> */ <del> public function wrong_type($message) <del> { <del> $this->wrong_type = $message; <del> return $this; <del> } <del> <del> /** <del> * Set the "too big" error message. <del> * <del> * @param string $message <del> * @return Upload_Of <del> */ <del> public function too_big($message) <del> { <del> $this->too_big = $message; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validation/rules/with_callback.php <del><?php namespace System\Validation\Rules; <del> <del>use System\Validation\Nullable_Rule; <del> <del>class With_Callback extends Nullable_Rule { <del> <del> /** <del> * The callback that will be used to validate the attribute. <del> * <del> * @var function <del> */ <del> public $callback; <del> <del> /** <del> * Evaluate the validity of an attribute. <del> * <del> * @param string $attribute <del> * @param array $attributes <del> * @return bool <del> */ <del> public function check($attribute, $attributes) <del> { <del> if ( ! is_callable($this->callback)) <del> { <del> throw new \Exception("The validation callback for the [$attribute] attribute is not callable."); <del> } <del> <del> if ( ! is_null($nullable = parent::check($attribute, $attributes))) <del> { <del> return $nullable; <del> } <del> <del> return call_user_func($this->callback, $attributes[$attribute]); <del> } <del> <del> /** <del> * Set the validation callback. <del> * <del> * @param function $callback <del> * @return With_Callback <del> */ <del> public function using($callback) <del> { <del> $this->callback = $callback; <del> return $this; <del> } <del> <del>} <ide>\ No newline at end of file <ide><path>system/validator.php <ide> class Validator { <ide> <ide> /** <del> * The attributes being validated. <add> * The array being validated. <ide> * <ide> * @var array <ide> */ <ide> public $attributes; <ide> <ide> /** <del> * The validation error collector. <add> * The validation rules. <add> * <add> * @var array <add> */ <add> public $rules; <add> <add> /** <add> * The validation messages. <ide> * <del> * @var Error_Collector <add> * @var array <add> */ <add> public $messages; <add> <add> /** <add> * The post-validation error messages. <add> * <add> * @var array <ide> */ <ide> public $errors; <ide> <ide> /** <del> * The validation rules. <add> * The "size" related validation rules. <ide> * <ide> * @var array <ide> */ <del> public $rules = array(); <add> protected $size_rules = array('size', 'between', 'min', 'max'); <add> <add> /** <add> * Create a new validator instance. <add> * <add> * @param array $attributes <add> * @param array $rules <add> * @param array $messages <add> * @return void <add> */ <add> public function __construct($attributes, $rules, $messages = array()) <add> { <add> $this->attributes = $attributes; <add> $this->rules = $rules; <add> $this->messages = $messages; <add> } <add> <add> /** <add> * Validate the target array using the specified validation rules. <add> * <add> * @return bool <add> */ <add> public function invalid() <add> { <add> return ! $this->valid(); <add> } <add> <add> /** <add> * Validate the target array using the specified validation rules. <add> * <add> * @return bool <add> */ <add> public function valid() <add> { <add> $this->errors = new Validation\Errors; <add> <add> foreach ($this->rules as $attribute => $rules) <add> { <add> if (is_string($rules)) <add> { <add> $rules = explode('|', $rules); <add> } <add> <add> foreach ($rules as $rule) <add> { <add> $this->check($attribute, $rule); <add> } <add> } <add> <add> return count($this->errors->messages) == 0; <add> } <ide> <ide> /** <del> * Create a new Validator instance. <add> * Evaluate an attribute against a validation rule. <ide> * <del> * @param mixed $target <add> * @param string $attribute <add> * @param string $rule <ide> * @return void <ide> */ <del> public function __construct($target = null) <add> protected function check($attribute, $rule) <ide> { <del> $this->errors = new Validation\Error_Collector; <add> list($rule, $parameters) = $this->parse($rule); <ide> <del> if (is_null($target)) <add> if ( ! method_exists($this, $validator = 'validate_'.$rule)) <ide> { <del> $target = Input::get(); <add> throw new \Exception("Validation rule [$rule] doesn't exist."); <ide> } <ide> <del> // If the source is an Eloquent model, use the model's attributes as the validation attributes. <del> $this->attributes = ($target instanceof DB\Eloquent) ? $target->attributes : (array) $target; <add> // No validation will be run for attributes that do not exist unless the rule being validated <add> // is "required" or "accepted". No other rules have implicit "required" checks. <add> if ( ! array_key_exists($attribute, $this->attributes) and ! in_array($rule, array('required', 'accepted'))) <add> { <add> continue; <add> } <add> <add> if ( ! $this->$validator($attribute, $parameters)) <add> { <add> $this->errors->add($attribute, $this->format_message($this->get_message($attribute, $rule), $attribute, $rule, $parameters)); <add> } <add> } <add> <add> /** <add> * Validate that a required attribute exists in the attributes array. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_required($attribute) <add> { <add> return array_key_exists($attribute, $this->attributes) and trim($this->attributes[$attribute]) !== ''; <add> } <add> <add> /** <add> * Validate that an attribute has a matching confirmation attribute. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_confirmed($attribute) <add> { <add> return array_key_exists($attribute.'_confirmation', $this->attributes) and $this->attributes[$attribute] == $this->attributes[$attribute.'_confirmation']; <add> } <add> <add> /** <add> * Validate that an attribute was "accepted". <add> * <add> * This validation rule implies the attribute is "required". <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_accepted($attribute) <add> { <add> return static::validate_required($attribute) and ($this->attributes[$attribute] == 'yes' or $this->attributes[$attribute] == '1'); <add> } <add> <add> /** <add> * Validate that an attribute is numeric. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_numeric($attribute) <add> { <add> return is_numeric($this->attributes[$attribute]); <add> } <add> <add> /** <add> * Validate that an attribute is an integer. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_integer($attribute) <add> { <add> return filter_var($this->attributes[$attribute], FILTER_VALIDATE_INT) !== false; <add> } <add> <add> /** <add> * Validate the size of an attribute. <add> * <add> * @param string $attribute <add> * @param array $parameters <add> * @return bool <add> */ <add> protected function validate_size($attribute, $parameters) <add> { <add> return $this->get_size($attribute) == $parameters[0]; <add> } <add> <add> /** <add> * Validate the size of an attribute is between a set of values. <add> * <add> * @param string $attribute <add> * @param array $parameters <add> * @return bool <add> */ <add> protected function validate_between($attribute, $parameters) <add> { <add> return $this->get_size($attribute) >= $parameters[0] and $this->get_size($attribute) <= $parameters[1]; <ide> } <ide> <ide> /** <del> * Create a new Validator instance. <add> * Validate the size of an attribute is greater than a minimum value. <ide> * <del> * @param mixed $target <del> * @return Validator <add> * @param string $attribute <add> * @param array $parameters <add> * @return bool <ide> */ <del> public static function make($target = null) <add> protected function validate_min($attribute, $parameters) <ide> { <del> return new static($target); <add> return $this->get_size($attribute) >= $parameters[0]; <ide> } <ide> <ide> /** <del> * Determine if the attributes pass all of the validation rules. <add> * Validate the size of an attribute is less than a maximum value. <ide> * <add> * @param string $attribute <add> * @param array $parameters <ide> * @return bool <ide> */ <del> public function is_valid() <add> protected function validate_max($attribute, $parameters) <ide> { <del> $this->errors->messages = array(); <add> return $this->get_size($attribute) <= $parameters[0]; <add> } <ide> <del> foreach ($this->rules as $rule) <add> /** <add> * Get the size of an attribute. <add> * <add> * @param string $attribute <add> * @return mixed <add> */ <add> protected function get_size($attribute) <add> { <add> if ($this->has_numeric_rule($attribute)) <ide> { <del> $rule->validate($this->attributes, $this->errors); <add> return $this->attributes[$attribute]; <ide> } <ide> <del> return count($this->errors->messages) == 0; <add> return (array_key_exists($attribute, $_FILES)) ? $this->attributes[$attribute]['size'] / 1000 : Str::length(trim($this->attributes[$attribute])); <ide> } <ide> <ide> /** <del> * Magic Method for dynamically creating validation rules. <add> * Validate an attribute is contained within a list of values. <add> * <add> * @param string $attribute <add> * @param array $parameters <add> * @return bool <add> */ <add> protected function validate_in($attribute, $parameters) <add> { <add> return in_array($this->attributes[$attribute], $parameters); <add> } <add> <add> /** <add> * Validate an attribute is not contained within a list of values. <add> * <add> * @param string $attribute <add> * @param array $parameters <add> * @return bool <ide> */ <del> public function __call($method, $parameters) <add> protected function validate_not_in($attribute, $parameters) <ide> { <del> if (file_exists(SYS_PATH.'validation/rules/'.$method.EXT)) <add> return ! in_array($this->attributes[$attribute], $parameters); <add> } <add> <add> /** <add> * Validate the uniqueness of an attribute value on a given database table. <add> * <add> * @param string $attribute <add> * @param array $parameters <add> * @return bool <add> */ <add> protected function validate_unique($attribute, $parameters) <add> { <add> if ( ! isset($parameters[1])) <ide> { <del> $rule = '\\System\\Validation\\Rules\\'.$method; <add> $parameters[1] = $attribute; <add> } <add> <add> return DB::table($parameters[0])->where($parameters[1], '=', $this->attributes[$attribute])->count() == 0; <add> } <add> <add> /** <add> * Validate than an attribute is a valid e-mail address. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_email($attribute) <add> { <add> return filter_var($this->attributes[$attribute], FILTER_VALIDATE_EMAIL) !== false; <add> } <add> <add> /** <add> * Validate than an attribute is a valid URL. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_url($attribute) <add> { <add> return filter_var($this->attributes[$attribute], FILTER_VALIDATE_URL) !== false; <add> } <add> <add> /** <add> * Validate that an attribute is an active URL. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_active_url($attribute) <add> { <add> $url = str_replace(array('http://', 'https://', 'ftp://'), '', Str::lower($this->attributes[$attribute])); <add> <add> return checkdnsrr($url); <add> } <add> <add> /** <add> * Validate the MIME type of a file is an image MIME type. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_image($attribute) <add> { <add> return static::validate_mime($attribute, array('jpg', 'png', 'gif', 'bmp')); <add> } <ide> <del> return $this->rules[] = new $rule($parameters); <add> /** <add> * Validate than an attribute contains only alphabetic characters. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_alpha($attribute) <add> { <add> return preg_match('/^([a-z])+$/i', $this->attributes[$attribute]); <add> } <add> <add> /** <add> * Validate than an attribute contains only alpha-numeric characters. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_alpha_num($attribute) <add> { <add> return preg_match('/^([a-z0-9])+$/i', $this->attributes[$attribute]); <add> } <add> <add> /** <add> * Validate than an attribute contains only alpha-numeric characters, dashes, and underscores. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function validate_alpha_dash($attribute) <add> { <add> return preg_match('/^([-a-z0-9_-])+$/i', $this->attributes[$attribute]); <add> } <add> <add> /** <add> * Validate the MIME type of a file upload attribute is in a set of MIME types. <add> * <add> * @param string $attribute <add> * @param array $parameters <add> * @return bool <add> */ <add> protected function validate_mimes($attribute, $parameters) <add> { <add> foreach ($parameters as $extension) <add> { <add> if (File::is($extension, $this->attributes[$attribute]['tmp_name'])) <add> { <add> return true; <add> } <add> } <add> <add> return false; <add> } <add> <add> /** <add> * Get the proper error message for an attribute and rule. <add> * <add> * Developer specified attribute specific rules take first priority. <add> * Developer specified error rules take second priority. <add> * <add> * If the message has not been specified by the developer, the default will be used <add> * from the validation language file. <add> * <add> * @param string $attribute <add> * @param string $rule <add> * @return string <add> */ <add> protected function get_message($attribute, $rule) <add> { <add> if (array_key_exists($attribute.'_'.$rule, $this->messages)) <add> { <add> return $this->messages[$attribute.'_'.$rule]; <add> } <add> elseif (array_key_exists($rule, $this->messages)) <add> { <add> return $this->messages[$rule]; <ide> } <add> else <add> { <add> $message = Lang::line('validation.'.$rule)->get(); <add> <add> // For "size" rules that are validating strings or files, we need to adjust <add> // the default error message appropriately. <add> if (in_array($rule, $this->size_rules) and ! $this->has_numeric_rule($attribute)) <add> { <add> return (array_key_exists($attribute, $_FILES)) ? rtrim($message, '.').' kilobytes.' : rtrim($message, '.').' characters.'; <add> } <add> <add> return $message; <add> } <add> } <add> <add> /** <add> * Replace all error message place-holders with actual values. <add> * <add> * @param string $message <add> * @param string $attribute <add> * @param string $rule <add> * @param array $parameters <add> * @return string <add> */ <add> protected function format_message($message, $attribute, $rule, $parameters) <add> { <add> $display = Lang::line('attributes.'.$attribute)->get(null, function() use ($attribute) { return str_replace('_', ' ', $attribute); }); <add> <add> $message = str_replace(':attribute', $display, $message); <add> <add> if (in_array($rule, $this->size_rules)) <add> { <add> $max = ($rule == 'between') ? $parameters[1] : $parameters[0]; <add> <add> $message = str_replace(':size', $parameters[0], str_replace(':min', $parameters[0], str_replace(':max', $max, $message))); <add> } <add> elseif (in_array($rule, array('in', 'not_in', 'mimes'))) <add> { <add> $message = str_replace(':values', implode(', ', $parameters), $message); <add> } <add> <add> return $message; <add> } <add> <add> /** <add> * Determine if an attribute has either a "numeric" or "integer" rule. <add> * <add> * @param string $attribute <add> * @return bool <add> */ <add> protected function has_numeric_rule($attribute) <add> { <add> return $this->has_rule($attribute, array('numeric', 'integer')); <add> } <add> <add> /** <add> * Determine if an attribute has a rule assigned to it. <add> * <add> * @param string $attribute <add> * @param array $rules <add> * @return bool <add> */ <add> protected function has_rule($attribute, $rules) <add> { <add> foreach ($this->rules[$attribute] as $rule) <add> { <add> list($rule, $parameters) = $this->parse($rule); <add> <add> if (in_array($rule, $rules)) <add> { <add> return true; <add> } <add> } <add> <add> return false; <add> } <add> <add> /** <add> * Extrac the rule name and parameters from a rule. <add> * <add> * @param string $rule <add> * @return array <add> */ <add> protected function parse($rule) <add> { <add> $parameters = (($colon = strpos($rule, ':')) !== false) ? explode(',', substr($rule, $colon + 1)) : array(); <ide> <del> throw new \Exception("Method [$method] does not exist on Validator class."); <add> return array(is_numeric($colon) ? substr($rule, 0, $colon) : $rule, $parameters); <ide> } <ide> <ide> } <ide>\ No newline at end of file
22
Javascript
Javascript
improve readability of net benchmarks
f955c734bac29a5df3d8ebf45944abfeed5e929b
<ide><path>benchmark/net/net-c2s.js <ide> Writer.prototype.emit = function() {}; <ide> Writer.prototype.prependListener = function() {}; <ide> <ide> <add>function flow() { <add> var dest = this.dest; <add> var res = dest.write(chunk, encoding); <add> if (!res) <add> dest.once('drain', this.flow); <add> else <add> process.nextTick(this.flow); <add>} <add> <ide> function Reader() { <del> this.flow = this.flow.bind(this); <add> this.flow = flow.bind(this); <ide> this.readable = true; <ide> } <ide> <ide> Reader.prototype.pipe = function(dest) { <ide> return dest; <ide> }; <ide> <del>Reader.prototype.flow = function() { <del> var dest = this.dest; <del> var res = dest.write(chunk, encoding); <del> if (!res) <del> dest.once('drain', this.flow); <del> else <del> process.nextTick(this.flow); <del>}; <del> <ide> <ide> function server() { <ide> var reader = new Reader(); <ide><path>benchmark/net/net-pipe.js <ide> Writer.prototype.emit = function() {}; <ide> Writer.prototype.prependListener = function() {}; <ide> <ide> <add>function flow() { <add> var dest = this.dest; <add> var res = dest.write(chunk, encoding); <add> if (!res) <add> dest.once('drain', this.flow); <add> else <add> process.nextTick(this.flow); <add>} <add> <ide> function Reader() { <del> this.flow = this.flow.bind(this); <add> this.flow = flow.bind(this); <ide> this.readable = true; <ide> } <ide> <ide> Reader.prototype.pipe = function(dest) { <ide> return dest; <ide> }; <ide> <del>Reader.prototype.flow = function() { <del> var dest = this.dest; <del> var res = dest.write(chunk, encoding); <del> if (!res) <del> dest.once('drain', this.flow); <del> else <del> process.nextTick(this.flow); <del>}; <del> <ide> <ide> function server() { <ide> var reader = new Reader(); <ide><path>benchmark/net/net-s2c.js <ide> Writer.prototype.emit = function() {}; <ide> Writer.prototype.prependListener = function() {}; <ide> <ide> <add>function flow() { <add> var dest = this.dest; <add> var res = dest.write(chunk, encoding); <add> if (!res) <add> dest.once('drain', this.flow); <add> else <add> process.nextTick(this.flow); <add>} <add> <ide> function Reader() { <del> this.flow = this.flow.bind(this); <add> this.flow = flow.bind(this); <ide> this.readable = true; <ide> } <ide> <ide> Reader.prototype.pipe = function(dest) { <ide> return dest; <ide> }; <ide> <del>Reader.prototype.flow = function() { <del> var dest = this.dest; <del> var res = dest.write(chunk, encoding); <del> if (!res) <del> dest.once('drain', this.flow); <del> else <del> process.nextTick(this.flow); <del>}; <del> <ide> <ide> function server() { <ide> var reader = new Reader();
3
Python
Python
fix a typo in django/db/transaction.py
cd7afcdcac69cc4e6f762188262957bceb4760e0
<ide><path>django/db/transaction.py <ide> class Atomic(ContextDecorator): <ide> connection. None denotes the absence of a savepoint. <ide> <ide> This allows reentrancy even if the same AtomicWrapper is reused. For <del> example, it's possible to define `oa = @atomic('other')` and use `@oa` or <add> example, it's possible to define `oa = atomic('other')` and use `@oa` or <ide> `with oa:` multiple times. <ide> <ide> Since database connections are thread-local, this is thread-safe.
1
Python
Python
update the typing tests for `np.core.multiarray`
fc66b9e3e30b02939c6a4c97e77c0b55188210ca
<ide><path>numpy/typing/tests/data/fail/constants.py <ide> np.ALLOW_THREADS = np.ALLOW_THREADS # E: Cannot assign to final <ide> np.little_endian = np.little_endian # E: Cannot assign to final <ide> np.UFUNC_PYVALS_NAME = np.UFUNC_PYVALS_NAME # E: Cannot assign to final <add>np.CLIP = 2 # E: Incompatible types <ide><path>numpy/typing/tests/data/reveal/array_constructors.py <del>from typing import List, Any <add>from typing import List, Any, TypeVar <add>from pathlib import Path <add> <ide> import numpy as np <ide> import numpy.typing as npt <ide> <del>class SubClass(np.ndarray): ... <add>_SCT = TypeVar("_SCT", bound=np.generic, covariant=True) <add> <add>class SubClass(np.ndarray[Any, np.dtype[_SCT]]): ... <ide> <ide> i8: np.int64 <ide> <ide> A: npt.NDArray[np.float64] <del>B: SubClass <add>B: SubClass[np.float64] <ide> C: List[int] <ide> <del>def func(i: int, j: int, **kwargs: Any) -> SubClass: ... <add>def func(i: int, j: int, **kwargs: Any) -> SubClass[np.float64]: ... <ide> <ide> reveal_type(np.empty_like(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <add>reveal_type(np.empty_like(B)) # E: SubClass[{float64}] <ide> reveal_type(np.empty_like([1, 1.0])) # E: numpy.ndarray[Any, numpy.dtype[Any]] <ide> reveal_type(np.empty_like(A, dtype=np.int64)) # E: numpy.ndarray[Any, numpy.dtype[{int64}]] <ide> reveal_type(np.empty_like(A, dtype='c16')) # E: numpy.ndarray[Any, numpy.dtype[Any]] <ide> <ide> reveal_type(np.array(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <add>reveal_type(np.array(B)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <add>reveal_type(np.array(B, subok=True)) # E: SubClass[{float64}] <ide> reveal_type(np.array([1, 1.0])) # E: numpy.ndarray[Any, numpy.dtype[Any]] <ide> reveal_type(np.array(A, dtype=np.int64)) # E: numpy.ndarray[Any, numpy.dtype[{int64}]] <ide> reveal_type(np.array(A, dtype='c16')) # E: numpy.ndarray[Any, numpy.dtype[Any]] <ide> def func(i: int, j: int, **kwargs: Any) -> SubClass: ... <ide> reveal_type(np.concatenate(A, dtype='c16')) # E: numpy.ndarray[Any, numpy.dtype[Any]] <ide> reveal_type(np.concatenate([1, 1.0], out=A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <ide> <del>reveal_type(np.asarray(A)) # E: numpy.ndarray[Any, Any] <del>reveal_type(np.asarray(B)) # E: numpy.ndarray[Any, Any] <del>reveal_type(np.asarray(C)) # E: numpy.ndarray[Any, Any] <add>reveal_type(np.asarray(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <add>reveal_type(np.asarray(B)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <add>reveal_type(np.asarray([1, 1.0])) # E: numpy.ndarray[Any, numpy.dtype[Any]] <add>reveal_type(np.asarray(A, dtype=np.int64)) # E: numpy.ndarray[Any, numpy.dtype[{int64}]] <add>reveal_type(np.asarray(A, dtype='c16')) # E: numpy.ndarray[Any, numpy.dtype[Any]] <ide> <ide> reveal_type(np.asanyarray(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <del>reveal_type(np.asanyarray(B)) # E: SubClass <del>reveal_type(np.asanyarray(B, dtype=int)) # E: numpy.ndarray[Any, Any] <del>reveal_type(np.asanyarray(C)) # E: numpy.ndarray[Any, Any] <del> <del>reveal_type(np.ascontiguousarray(A)) # E: numpy.ndarray[Any, Any] <del>reveal_type(np.ascontiguousarray(B)) # E: numpy.ndarray[Any, Any] <del>reveal_type(np.ascontiguousarray(C)) # E: numpy.ndarray[Any, Any] <del> <del>reveal_type(np.asfortranarray(A)) # E: numpy.ndarray[Any, Any] <del>reveal_type(np.asfortranarray(B)) # E: numpy.ndarray[Any, Any] <del>reveal_type(np.asfortranarray(C)) # E: numpy.ndarray[Any, Any] <add>reveal_type(np.asanyarray(B)) # E: SubClass[{float64}] <add>reveal_type(np.asanyarray([1, 1.0])) # E: numpy.ndarray[Any, numpy.dtype[Any]] <add>reveal_type(np.asanyarray(A, dtype=np.int64)) # E: numpy.ndarray[Any, numpy.dtype[{int64}]] <add>reveal_type(np.asanyarray(A, dtype='c16')) # E: numpy.ndarray[Any, numpy.dtype[Any]] <add> <add>reveal_type(np.ascontiguousarray(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <add>reveal_type(np.ascontiguousarray(B)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <add>reveal_type(np.ascontiguousarray([1, 1.0])) # E: numpy.ndarray[Any, numpy.dtype[Any]] <add>reveal_type(np.ascontiguousarray(A, dtype=np.int64)) # E: numpy.ndarray[Any, numpy.dtype[{int64}]] <add>reveal_type(np.ascontiguousarray(A, dtype='c16')) # E: numpy.ndarray[Any, numpy.dtype[Any]] <add> <add>reveal_type(np.asfortranarray(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <add>reveal_type(np.asfortranarray(B)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <add>reveal_type(np.asfortranarray([1, 1.0])) # E: numpy.ndarray[Any, numpy.dtype[Any]] <add>reveal_type(np.asfortranarray(A, dtype=np.int64)) # E: numpy.ndarray[Any, numpy.dtype[{int64}]] <add>reveal_type(np.asfortranarray(A, dtype='c16')) # E: numpy.ndarray[Any, numpy.dtype[Any]] <ide> <ide> reveal_type(np.require(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <del>reveal_type(np.require(B)) # E: SubClass <del>reveal_type(np.require(B, requirements=None)) # E: SubClass <add>reveal_type(np.require(B)) # E: SubClass[{float64}] <add>reveal_type(np.require(B, requirements=None)) # E: SubClass[{float64}] <ide> reveal_type(np.require(B, dtype=int)) # E: numpy.ndarray[Any, Any] <ide> reveal_type(np.require(B, requirements="E")) # E: numpy.ndarray[Any, Any] <ide> reveal_type(np.require(B, requirements=["ENSUREARRAY"])) # E: numpy.ndarray[Any, Any] <ide> reveal_type(np.require(B, requirements={"F", "E"})) # E: numpy.ndarray[Any, Any] <del>reveal_type(np.require(B, requirements=["C", "OWNDATA"])) # E: SubClass <del>reveal_type(np.require(B, requirements="W")) # E: SubClass <del>reveal_type(np.require(B, requirements="A")) # E: SubClass <add>reveal_type(np.require(B, requirements=["C", "OWNDATA"])) # E: SubClass[{float64}] <add>reveal_type(np.require(B, requirements="W")) # E: SubClass[{float64}] <add>reveal_type(np.require(B, requirements="A")) # E: SubClass[{float64}] <ide> reveal_type(np.require(C)) # E: numpy.ndarray[Any, Any] <ide> <ide> reveal_type(np.linspace(0, 10)) # E: numpy.ndarray[Any, Any] <ide> def func(i: int, j: int, **kwargs: Any) -> SubClass: ... <ide> <ide> reveal_type(np.full_like(A, i8)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]] <ide> reveal_type(np.full_like(C, i8)) # E: numpy.ndarray[Any, Any] <del>reveal_type(np.full_like(B, i8)) # E: SubClass <add>reveal_type(np.full_like(B, i8)) # E: SubClass[{float64}] <ide> reveal_type(np.full_like(B, i8, dtype=np.int64)) # E: numpy.ndarray[Any, Any] <ide> <ide> reveal_type(np.ones(1)) # E: numpy.ndarray[Any, Any] <ide> def func(i: int, j: int, **kwargs: Any) -> SubClass: ... <ide> reveal_type(np.indices([1, 2, 3])) # E: numpy.ndarray[Any, Any] <ide> reveal_type(np.indices([1, 2, 3], sparse=True)) # E: tuple[numpy.ndarray[Any, Any]] <ide> <del>reveal_type(np.fromfunction(func, (3, 5))) # E: SubClass <add>reveal_type(np.fromfunction(func, (3, 5))) # E: SubClass[{float64}] <ide> <ide> reveal_type(np.identity(10)) # E: numpy.ndarray[Any, Any] <ide> <ide><path>numpy/typing/tests/data/reveal/constants.py <ide> reveal_type(np.pi) # E: float <ide> <ide> reveal_type(np.ALLOW_THREADS) # E: int <del>reveal_type(np.BUFSIZE) # E: int <del>reveal_type(np.CLIP) # E: int <add>reveal_type(np.BUFSIZE) # E: Literal[8192] <add>reveal_type(np.CLIP) # E: Literal[0] <ide> reveal_type(np.ERR_CALL) # E: int <ide> reveal_type(np.ERR_DEFAULT) # E: int <ide> reveal_type(np.ERR_IGNORE) # E: int <ide> reveal_type(np.FPE_INVALID) # E: int <ide> reveal_type(np.FPE_OVERFLOW) # E: int <ide> reveal_type(np.FPE_UNDERFLOW) # E: int <del>reveal_type(np.MAXDIMS) # E: int <del>reveal_type(np.MAY_SHARE_BOUNDS) # E: int <del>reveal_type(np.MAY_SHARE_EXACT) # E: int <del>reveal_type(np.RAISE) # E: int <add>reveal_type(np.MAXDIMS) # E: Literal[32] <add>reveal_type(np.MAY_SHARE_BOUNDS) # E: Literal[0] <add>reveal_type(np.MAY_SHARE_EXACT) # E: Literal[-1] <add>reveal_type(np.RAISE) # E: Literal[2] <ide> reveal_type(np.SHIFT_DIVIDEBYZERO) # E: int <ide> reveal_type(np.SHIFT_INVALID) # E: int <ide> reveal_type(np.SHIFT_OVERFLOW) # E: int <ide> reveal_type(np.SHIFT_UNDERFLOW) # E: int <ide> reveal_type(np.UFUNC_BUFSIZE_DEFAULT) # E: int <del>reveal_type(np.WRAP) # E: int <del>reveal_type(np.tracemalloc_domain) # E: int <add>reveal_type(np.WRAP) # E: Literal[1] <add>reveal_type(np.tracemalloc_domain) # E: Literal[389047] <ide> <ide> reveal_type(np.little_endian) # E: bool <ide> reveal_type(np.True_) # E: numpy.bool_
3
Text
Text
add one more bullet point
856370f522d8d81e3e6c22b59c697b5aa06cb3b2
<ide><path>docs/upgrading/upgrading-your-ui-theme.md <ide> Text editor content is now rendered in the shadow DOM, which shields it from bei <ide> * Gutter decorations <ide> * Line decorations <ide> * Scrollbar styling <add>* Anything targeting a child selector of `.editor` <ide> <ide> During a transition phase, it will be possible to enable or disable the text editor's shadow DOM in the settings, so themes will need to be compatible with both approaches. <ide>
1
Ruby
Ruby
fix hashwithindifferentaccess.[] method
2ee28b2bf8414cad3655dbe685ff0d27051395cd
<ide><path>activesupport/lib/active_support/hash_with_indifferent_access.rb <ide> def self.new_from_hash_copying_default(hash) <ide> end <ide> end <ide> <add> def self.[](*args) <add> new.merge(Hash[*args]) <add> end <add> <ide> alias_method :regular_writer, :[]= unless method_defined?(:regular_writer) <ide> alias_method :regular_update, :update unless method_defined?(:regular_update) <ide> <ide><path>activesupport/test/core_ext/hash_ext_test.rb <ide> def test_store_on_indifferent_access <ide> assert_equal expected, hash <ide> end <ide> <add> def test_constructor_on_indifferent_access <add> hash = HashWithIndifferentAccess[:foo, 1] <add> assert_equal 1, hash[:foo] <add> assert_equal 1, hash['foo'] <add> hash[:foo] = 3 <add> assert_equal 3, hash[:foo] <add> assert_equal 3, hash['foo'] <add> end <add> <ide> def test_reverse_merge <ide> defaults = { :a => "x", :b => "y", :c => 10 }.freeze <ide> options = { :a => 1, :b => 2 }
2
PHP
PHP
remove extra method call
c764f76e5b1f2b99f34384039e123eff0bf8627a
<ide><path>laravel/blade.php <ide> public static function sharpen() <ide> */ <ide> public static function expired($view, $path) <ide> { <del> $compiled = static::compiled($path); <del> <ide> return filemtime($path) > filemtime(static::compiled($path)); <ide> } <ide>
1
Python
Python
fix mixed precision in tf models
3f290e6c8403c6a2cf80dce068869793bde49540
<ide><path>src/transformers/activations_tf.py <ide> import math <ide> <ide> import tensorflow as tf <add>from packaging import version <ide> <ide> <del>def gelu(x): <add>def _gelu(x): <ide> """ <ide> Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when <ide> initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): <ide> 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see <ide> https://arxiv.org/abs/1606.08415 <ide> """ <ide> x = tf.convert_to_tensor(x) <del> cdf = 0.5 * (1.0 + tf.math.erf(x / tf.math.sqrt(2.0))) <add> cdf = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0), x.dtype))) <ide> <ide> return x * cdf <ide> <ide> <del>def gelu_new(x): <add>def _gelu_new(x): <ide> """ <ide> Gaussian Error Linear Unit. This is a smoother version of the GELU. Original paper: https://arxiv.org/abs/1606.0841 <ide> <ide> def mish(x): <ide> <ide> def gelu_fast(x): <ide> x = tf.convert_to_tensor(x) <del> coeff1 = tf.cast(7978845608, x.dtype) <add> coeff1 = tf.cast(0.7978845608, x.dtype) <ide> coeff2 = tf.cast(0.044715, x.dtype) <ide> <ide> return 0.5 * x * (1.0 + tf.tanh(x * coeff2 * (1.0 + coeff1 * x * x))) <ide> <ide> <add>if version.parse(tf.version.VERSION) >= version.parse("2.4"): <add> <add> def approximate_gelu_wrap(x): <add> return tf.keras.activations.gelu(x, approximate=True) <add> <add> gelu = tf.keras.activations.gelu <add> gelu_new = approximate_gelu_wrap <add>else: <add> gelu = _gelu <add> gelu_new = _gelu_new <add> <add> <ide> ACT2FN = { <del> "gelu": tf.keras.layers.Activation(gelu), <add> "gelu": gelu, <ide> "relu": tf.keras.activations.relu, <ide> "swish": tf.keras.activations.swish, <ide> "silu": tf.keras.activations.swish, <del> "gelu_new": tf.keras.layers.Activation(gelu_new), <del> "mish": tf.keras.layers.Activation(mish), <add> "gelu_new": gelu_new, <add> "mish": mish, <ide> "tanh": tf.keras.activations.tanh, <del> "gelu_fast": tf.keras.layers.Activation(gelu_fast), <add> "gelu_fast": gelu_fast, <ide> } <ide> <ide> <ide><path>src/transformers/models/albert/modeling_tf_albert.py <ide> def set_bias(self, value): <ide> <ide> def call(self, hidden_states): <ide> hidden_states = self.dense(inputs=hidden_states) <del> hidden_states = self.activation(inputs=hidden_states) <add> hidden_states = self.activation(hidden_states) <ide> hidden_states = self.LayerNorm(inputs=hidden_states) <ide> seq_length = shape_list(tensor=hidden_states)[1] <ide> hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.embedding_size]) <ide><path>src/transformers/models/bert/modeling_tf_bert.py <ide> def __init__(self, config, **kwargs): <ide> <ide> def call(self, hidden_states): <ide> hidden_states = self.dense(inputs=hidden_states) <del> hidden_states = self.intermediate_act_fn(inputs=hidden_states) <add> hidden_states = self.intermediate_act_fn(hidden_states) <ide> <ide> return hidden_states <ide> <ide><path>src/transformers/models/electra/modeling_tf_electra.py <ide> def __init__(self, config, **kwargs): <ide> <ide> def call(self, hidden_states): <ide> hidden_states = self.dense(inputs=hidden_states) <del> hidden_states = self.intermediate_act_fn(inputs=hidden_states) <add> hidden_states = self.intermediate_act_fn(hidden_states) <ide> <ide> return hidden_states <ide> <ide><path>src/transformers/models/longformer/modeling_tf_longformer.py <ide> def __init__(self, config, **kwargs): <ide> <ide> def call(self, hidden_states): <ide> hidden_states = self.dense(inputs=hidden_states) <del> hidden_states = self.intermediate_act_fn(inputs=hidden_states) <add> hidden_states = self.intermediate_act_fn(hidden_states) <ide> <ide> return hidden_states <ide> <ide><path>src/transformers/models/mpnet/modeling_tf_mpnet.py <ide> def __init__(self, config, **kwargs): <ide> <ide> def call(self, hidden_states): <ide> hidden_states = self.dense(inputs=hidden_states) <del> hidden_states = self.intermediate_act_fn(inputs=hidden_states) <add> hidden_states = self.intermediate_act_fn(hidden_states) <ide> <ide> return hidden_states <ide> <ide><path>src/transformers/models/roberta/modeling_tf_roberta.py <ide> def __init__(self, config, **kwargs): <ide> <ide> def call(self, hidden_states): <ide> hidden_states = self.dense(inputs=hidden_states) <del> hidden_states = self.intermediate_act_fn(inputs=hidden_states) <add> hidden_states = self.intermediate_act_fn(hidden_states) <ide> <ide> return hidden_states <ide> <ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py <ide> def __init__(self, config, **kwargs): <ide> <ide> def call(self, hidden_states): <ide> hidden_states = self.dense(inputs=hidden_states) <del> hidden_states = self.intermediate_act_fn(inputs=hidden_states) <add> hidden_states = self.intermediate_act_fn(hidden_states) <ide> <ide> return hidden_states <ide>
8
Python
Python
remove useless imports
56db3ddf4e77a9c2184bf9580a67bcb2dd8ca4d7
<ide><path>tests/test_deprecations.py <ide> # -*- coding: utf-8 -*- <ide> """ <ide> tests.deprecations <del> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <add> ~~~~~~~~~~~~~~~~~~ <ide> <ide> Tests deprecation support. Not used currently. <ide> <ide> :copyright: (c) 2014 by Armin Ronacher. <ide> :license: BSD, see LICENSE for more details. <ide> """ <del> <del>import flask <del>import unittest <del>from tests import catch_warnings
1
Text
Text
refine rntester documentation to disable fabric
ad14eb4bd324f69d3a8619f536c208acfb878d14
<ide><path>packages/rn-tester/README.md <ide> If you are testing non-fabric component, modify [the fabric_enabled flag in RNTe <ide> fabric_enabled = false <ide> ``` <ide> <add>Also, if you previously built RNTester with fabric enabled, you might need to clean up the build files and Pods. <add>```sh <add># Clean the generated files and folders to clean install RNTester <add>cd packages/rn-tester/ <add>rm -rf build/generated/ios <add>rm -rf Pods <add>rm Podfile.lock <add>``` <add> <add>If you are still having a problem after doing the clean up (which can happen if you have built RNTester with older React Native versions where files were generated inside the react-native folder.), the best way might be to clean-install react-native (e.g. remove node_modules and yarn install). <add> <ide> Both macOS and Xcode are required. <ide> - `cd packages/rn-tester` <ide> - Install [Bundler](https://bundler.io/): `gem install bundler`. We use bundler to install the right version of [CocoaPods](https://cocoapods.org/) locally.
1
Python
Python
disallow verbose=1 with parameterserverstrategy
366d4ac23bae7dc327e94366d33c2dee507c59b7
<ide><path>keras/distribute/dataset_creator_model_fit_ps_only_test.py <ide> def testModelFitTensorBoardEpochLevel(self, strategy, use_dataset_creator): <ide> files = tf.compat.v1.gfile.ListDirectory(log_dir) <ide> self.assertGreaterEqual(len(files), 1) <ide> <del> def testModelFitVerbose1(self, strategy, use_dataset_creator): <del> with self.assertRaisesRegex(ValueError, <del> "`verbose=1` is not allowed with " <del> "`ParameterServerStrategy` for performance " <del> "reasons. Received: `verbose`=1"): <del> self._model_fit( <del> strategy, use_dataset_creator=use_dataset_creator, <del> verbose=1) <del> <ide> def testModelEvaluateErrorOnBatchLevelCallbacks(self, strategy, <ide> use_dataset_creator): <ide> <ide><path>keras/distribute/dataset_creator_model_fit_test_base.py <ide> def _model_fit(self, <ide> with_normalization_layer=False, <ide> callbacks=None, <ide> use_lookup_layer=False, <del> use_dataset_creator=True, <del> verbose="auto"): <add> use_dataset_creator=True): <ide> if callbacks is None: <ide> callbacks = [] <ide> <ide> def _model_fit(self, <ide> steps_per_epoch=steps_per_epoch, <ide> callbacks=callbacks, <ide> validation_data=validation_data, <del> validation_steps=steps_per_epoch, <del> verbose=verbose) <add> validation_steps=steps_per_epoch) <ide> return model <ide> <ide> def _model_evaluate(self, <ide><path>keras/engine/training.py <ide> def fit(self, <ide> verbose = 2 # Default to epoch-level logging for PSStrategy. <ide> else: <ide> verbose = 1 # Default to batch-level logging otherwise. <del> elif verbose == 1 and self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access <del> raise ValueError( <del> '`verbose=1` is not allowed with `ParameterServerStrategy` for ' <del> f'performance reasons. Received: `verbose`={verbose}') <ide> <ide> if validation_split: <ide> # Create the validation data using the training data. Only supported for
3
PHP
PHP
reset array keys for restoration
851b6719603437acec47f6c2959f70d11a9be9af
<ide><path>src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php <ide> public function newQueryForRestoration($ids) <ide> */ <ide> protected function newQueryForCollectionRestoration(array $ids) <ide> { <add> $ids = array_values($ids); <add> <ide> if (! Str::contains($ids[0], ':')) { <ide> return parent::newQueryForRestoration($ids); <ide> } <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphPivot.php <ide> public function newQueryForRestoration($ids) <ide> */ <ide> protected function newQueryForCollectionRestoration(array $ids) <ide> { <add> $ids = array_values($ids); <add> <ide> if (! Str::contains($ids[0], ':')) { <ide> return parent::newQueryForRestoration($ids); <ide> }
2
Mixed
Go
add format to secret ls
e281fe9c3a0034e119e7718a142133e86f38a4f2
<ide><path>cli/command/formatter/secret.go <add>package formatter <add> <add>import ( <add> "fmt" <add> "strings" <add> "time" <add> <add> "github.com/docker/docker/api/types/swarm" <add> units "github.com/docker/go-units" <add>) <add> <add>const ( <add> defaultSecretTableFormat = "table {{.ID}}\t{{.Name}}\t{{.CreatedAt}}\t{{.UpdatedAt}}" <add> secretIDHeader = "ID" <add> secretNameHeader = "NAME" <add> secretCreatedHeader = "CREATED" <add> secretUpdatedHeader = "UPDATED" <add>) <add> <add>// NewSecretFormat returns a Format for rendering using a network Context <add>func NewSecretFormat(source string, quiet bool) Format { <add> switch source { <add> case TableFormatKey: <add> if quiet { <add> return defaultQuietFormat <add> } <add> return defaultSecretTableFormat <add> } <add> return Format(source) <add>} <add> <add>// SecretWrite writes the context <add>func SecretWrite(ctx Context, secrets []swarm.Secret) error { <add> render := func(format func(subContext subContext) error) error { <add> for _, secret := range secrets { <add> secretCtx := &secretContext{s: secret} <add> if err := format(secretCtx); err != nil { <add> return err <add> } <add> } <add> return nil <add> } <add> return ctx.Write(newSecretContext(), render) <add>} <add> <add>func newSecretContext() *secretContext { <add> sCtx := &secretContext{} <add> <add> sCtx.header = map[string]string{ <add> "ID": secretIDHeader, <add> "Name": nameHeader, <add> "CreatedAt": secretCreatedHeader, <add> "UpdatedAt": secretUpdatedHeader, <add> "Labels": labelsHeader, <add> } <add> return sCtx <add>} <add> <add>type secretContext struct { <add> HeaderContext <add> s swarm.Secret <add>} <add> <add>func (c *secretContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(c) <add>} <add> <add>func (c *secretContext) ID() string { <add> return c.s.ID <add>} <add> <add>func (c *secretContext) Name() string { <add> return c.s.Spec.Annotations.Name <add>} <add> <add>func (c *secretContext) CreatedAt() string { <add> return units.HumanDuration(time.Now().UTC().Sub(c.s.Meta.CreatedAt)) + " ago" <add>} <add> <add>func (c *secretContext) UpdatedAt() string { <add> return units.HumanDuration(time.Now().UTC().Sub(c.s.Meta.UpdatedAt)) + " ago" <add>} <add> <add>func (c *secretContext) Labels() string { <add> mapLabels := c.s.Spec.Annotations.Labels <add> if mapLabels == nil { <add> return "" <add> } <add> var joinLabels []string <add> for k, v := range mapLabels { <add> joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v)) <add> } <add> return strings.Join(joinLabels, ",") <add>} <add> <add>func (c *secretContext) Label(name string) string { <add> if c.s.Spec.Annotations.Labels == nil { <add> return "" <add> } <add> return c.s.Spec.Annotations.Labels[name] <add>} <ide><path>cli/command/formatter/secret_test.go <add>package formatter <add> <add>import ( <add> "bytes" <add> "testing" <add> "time" <add> <add> "github.com/docker/docker/api/types/swarm" <add> "github.com/docker/docker/pkg/testutil/assert" <add>) <add> <add>func TestSecretContextFormatWrite(t *testing.T) { <add> // Check default output format (verbose and non-verbose mode) for table headers <add> cases := []struct { <add> context Context <add> expected string <add> }{ <add> // Errors <add> { <add> Context{Format: "{{InvalidFunction}}"}, <add> `Template parsing error: template: :1: function "InvalidFunction" not defined <add>`, <add> }, <add> { <add> Context{Format: "{{nil}}"}, <add> `Template parsing error: template: :1:2: executing "" at <nil>: nil is not a command <add>`, <add> }, <add> // Table format <add> {Context{Format: NewSecretFormat("table", false)}, <add> `ID NAME CREATED UPDATED <add>1 passwords Less than a second ago Less than a second ago <add>2 id_rsa Less than a second ago Less than a second ago <add>`}, <add> {Context{Format: NewSecretFormat("table {{.Name}}", true)}, <add> `NAME <add>passwords <add>id_rsa <add>`}, <add> {Context{Format: NewSecretFormat("{{.ID}}-{{.Name}}", false)}, <add> `1-passwords <add>2-id_rsa <add>`}, <add> } <add> <add> secrets := []swarm.Secret{ <add> {ID: "1", <add> Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()}, <add> Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "passwords"}}}, <add> {ID: "2", <add> Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()}, <add> Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "id_rsa"}}}, <add> } <add> for _, testcase := range cases { <add> out := bytes.NewBufferString("") <add> testcase.context.Output = out <add> if err := SecretWrite(testcase.context, secrets); err != nil { <add> assert.Error(t, err, testcase.expected) <add> } else { <add> assert.Equal(t, out.String(), testcase.expected) <add> } <add> } <add>} <ide><path>cli/command/secret/ls.go <ide> package secret <ide> <ide> import ( <del> "fmt" <del> "text/tabwriter" <del> "time" <del> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/cli" <ide> "github.com/docker/docker/cli/command" <del> "github.com/docker/go-units" <add> "github.com/docker/docker/cli/command/formatter" <ide> "github.com/spf13/cobra" <ide> "golang.org/x/net/context" <ide> ) <ide> <ide> type listOptions struct { <del> quiet bool <add> quiet bool <add> format string <ide> } <ide> <ide> func newSecretListCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> func newSecretListCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> <ide> flags := cmd.Flags() <ide> flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs") <add> flags.StringVarP(&opts.format, "format", "", "", "Pretty-print secrets using a Go template") <ide> <ide> return cmd <ide> } <ide> func runSecretList(dockerCli *command.DockerCli, opts listOptions) error { <ide> if err != nil { <ide> return err <ide> } <del> <del> w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0) <del> if opts.quiet { <del> for _, s := range secrets { <del> fmt.Fprintf(w, "%s\n", s.ID) <del> } <del> } else { <del> fmt.Fprintf(w, "ID\tNAME\tCREATED\tUPDATED") <del> fmt.Fprintf(w, "\n") <del> <del> for _, s := range secrets { <del> created := units.HumanDuration(time.Now().UTC().Sub(s.Meta.CreatedAt)) + " ago" <del> updated := units.HumanDuration(time.Now().UTC().Sub(s.Meta.UpdatedAt)) + " ago" <del> <del> fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", s.ID, s.Spec.Annotations.Name, created, updated) <add> format := opts.format <add> if len(format) == 0 { <add> if len(dockerCli.ConfigFile().SecretFormat) > 0 && !opts.quiet { <add> format = dockerCli.ConfigFile().SecretFormat <add> } else { <add> format = formatter.TableFormatKey <ide> } <ide> } <del> <del> w.Flush() <del> <del> return nil <add> secretCtx := formatter.Context{ <add> Output: dockerCli.Out(), <add> Format: formatter.NewSecretFormat(format, opts.quiet), <add> } <add> return formatter.SecretWrite(secretCtx, secrets) <ide> } <ide><path>cli/config/configfile/file.go <ide> type ConfigFile struct { <ide> ServiceInspectFormat string `json:"serviceInspectFormat,omitempty"` <ide> ServicesFormat string `json:"servicesFormat,omitempty"` <ide> TasksFormat string `json:"tasksFormat,omitempty"` <add> SecretFormat string `json:"secretFormat,omitempty"` <ide> } <ide> <ide> // LegacyLoadFromReader reads the non-nested configuration data given and sets up the <ide><path>docs/reference/commandline/cli.md <ide> property is not set, the client falls back to the default table <ide> format. For a list of supported formatting directives, see <ide> [**Formatting** section in the `docker stats` documentation](stats.md) <ide> <add>The property `secretFormat` specifies the default format for `docker <add>secret ls` output. When the `--format` flag is not provided with the <add>`docker secret ls` command, Docker's client uses this property. If this <add>property is not set, the client falls back to the default table <add>format. For a list of supported formatting directives, see <add>[**Formatting** section in the `docker secret ls` documentation](secret_ls.md) <add> <add> <ide> The property `credsStore` specifies an external binary to serve as the default <ide> credential store. When this property is set, `docker login` will attempt to <ide> store credentials in the binary specified by `docker-credential-<value>` which <ide> Following is a sample `config.json` file: <ide> "pluginsFormat": "table {{.ID}}\t{{.Name}}\t{{.Enabled}}", <ide> "statsFormat": "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}", <ide> "servicesFormat": "table {{.ID}}\t{{.Name}}\t{{.Mode}}", <add> "secretFormat": "table {{.ID}}\t{{.Name}}\t{{.CreatedAt}}\t{{.UpdatedAt}}", <ide> "serviceInspectFormat": "pretty", <ide> "detachKeys": "ctrl-e,e", <ide> "credsStore": "secretservice", <ide><path>docs/reference/commandline/secret_ls.md <ide> Aliases: <ide> <ide> Options: <ide> -q, --quiet Only display IDs <add> -format string Pretty-print secrets using a Go template <ide> ``` <ide> <ide> ## Description <ide> ID NAME CREATED <ide> mhv17xfe3gh6xc4rij5orpfds secret.json 2016-10-27 23:25:43.909181089 +0000 UTC 2016-10-27 23:25:43.909181089 +0000 UTC <ide> ``` <ide> <add>### Format the output <add> <add>The formatting option (`--format`) pretty prints secrets output <add>using a Go template. <add> <add>Valid placeholders for the Go template are listed below: <add> <add>| Placeholder | Description | <add>| ------------ | ------------------------------------------------------------------------------------ | <add>| `.ID` | Secret ID | <add>| `.Name` | Secret name | <add>| `.CreatedAt` | Time when the secret was created | <add>| `.UpdatedAt` | Time when the secret was updated | <add>| `.Labels` | All labels assigned to the secret | <add>| `.Label` | Value of a specific label for this secret. For example `{{.Label "secret.ssh.key"}}` | <add> <add>When using the `--format` option, the `secret ls` command will either <add>output the data exactly as the template declares or, when using the <add>`table` directive, will include column headers as well. <add> <add>The following example uses a template without headers and outputs the <add>`ID` and `Name` entries separated by a colon for all images: <add> <add>```bash <add>$ docker secret ls --format "{{.ID}}: {{.Name}}" <add> <add>77af4d6b9913: secret-1 <add>b6fa739cedf5: secret-2 <add>78a85c484f71: secret-3 <add>``` <add> <add>To list all secrets with their name and created date in a table format you <add>can use: <add> <add>```bash <add>$ docker secret ls --format "table {{.ID}}\t{{.Name}}\t{{.CreatedAt}}" <add> <add>ID NAME CREATED <add>77af4d6b9913 secret-1 5 minutes ago <add>b6fa739cedf5 secret-2 3 hours ago <add>78a85c484f71 secret-3 10 days ago <add>``` <add> <ide> ## Related commands <ide> <ide> * [secret create](secret_create.md)
6
Javascript
Javascript
use random port in test webserver
ff8c3342076546b772c0936b215e726f590716bc
<ide><path>test/test.js <ide> function parseOptions() { <ide> .example('$0 --b=firefox -t=issue5567 -t=issue5909', <ide> 'Run the reftest identified by issue5567 and issue5909 in Firefox.') <ide> .describe('port', 'The port the HTTP server should listen on.') <del> .default('port', 8000) <add> .default('port', 0) <ide> .describe('unitTest', 'Run the unit tests.') <ide> .describe('fontTest', 'Run the font tests.') <ide> .describe('noDownload', 'Skips test PDFs downloading.') <ide><path>test/webserver.js <ide> var defaultMimeType = 'application/octet-stream'; <ide> function WebServer() { <ide> this.root = '.'; <ide> this.host = 'localhost'; <del> this.port = 8000; <add> this.port = 0; <ide> this.server = null; <ide> this.verbose = false; <ide> this.cacheExpirationTime = 0; <ide> function WebServer() { <ide> } <ide> WebServer.prototype = { <ide> start: function (callback) { <add> this._ensureNonZeroPort(); <ide> this.server = http.createServer(this._handler.bind(this)); <ide> this.server.listen(this.port, this.host, callback); <ide> console.log( <ide> WebServer.prototype = { <ide> this.server.close(callback); <ide> this.server = null; <ide> }, <add> _ensureNonZeroPort: function () { <add> if (!this.port) { <add> // If port is 0, a random port will be chosen instead. Do not set a host <add> // name to make sure that the port is synchronously set by .listen(). <add> var server = http.createServer().listen(0); <add> var address = server.address(); <add> // .address().port being available synchronously is merely an <add> // implementation detail. So we are defensive here and fall back to some <add> // fixed port when the address is not available yet. <add> this.port = address ? address.port : 8000; <add> server.close(); <add> } <add> }, <ide> _handler: function (req, res) { <ide> var url = req.url; <ide> var urlParts = /([^?]*)((?:\?(.*))?)/.exec(url);
2
Ruby
Ruby
make use of tap to return a previously used var
ef5ae60a07c7d45855a9a2a4b695f153ef9faa79
<ide><path>activerecord/lib/active_record/associations/association_collection.rb <ide> def load_target <ide> @target = find_target.map do |f| <ide> i = @target.index(f) <ide> if i <del> t = @target.delete_at(i) <del> keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names) <del> t.attributes = f.attributes.except(*keys) <del> t <add> @target.delete_at(i).tap do |t| <add> keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names) <add> t.attributes = f.attributes.except(*keys) <add> end <ide> else <ide> f <ide> end
1
Java
Java
add jmh benchmark for replaysubject
329a0936d48bdbfd194ea48055e11718c65d9da6
<ide><path>rxjava-core/src/perf/java/rx/jmh/Baseline.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <ide> package rx.jmh; <ide> <ide> import org.openjdk.jmh.annotations.GenerateMicroBenchmark; <ide><path>rxjava-core/src/perf/java/rx/operators/OperatorMapPerf.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <ide> package rx.operators; <ide> <ide> import java.util.concurrent.CountDownLatch; <ide><path>rxjava-core/src/perf/java/rx/operators/OperatorSerializePerf.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <ide> package rx.operators; <ide> <ide> import java.util.concurrent.CountDownLatch; <ide><path>rxjava-core/src/perf/java/rx/subjects/ReplaySubjectPerf.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package rx.subjects; <add> <add>import org.openjdk.jmh.annotations.GenerateMicroBenchmark; <add>import org.openjdk.jmh.annotations.Param; <add>import org.openjdk.jmh.annotations.Scope; <add>import org.openjdk.jmh.annotations.State; <add>import org.openjdk.jmh.logic.BlackHole; <add>import rx.Observer; <add> <add>import java.util.concurrent.CountDownLatch; <add>import java.util.concurrent.atomic.AtomicLong; <add> <add>/** <add> * Benchmarks the {@link ReplaySubject}. <add> */ <add>public class ReplaySubjectPerf { <add> <add> @State(Scope.Thread) <add> public static class Input { <add> @Param({ "1", "512", "1024", "1048576" }) <add> public int nextRuns; <add> } <add> <add> @GenerateMicroBenchmark <add> public void subscribeBeforeEvents(final Input input, final BlackHole bh) throws Exception { <add> ReplaySubject<Object> subject = ReplaySubject.create(); <add> final CountDownLatch latch = new CountDownLatch(1); <add> final AtomicLong sum = new AtomicLong(); <add> <add> subject.subscribe(new Observer<Object>() { <add> @Override <add> public void onCompleted() { <add> latch.countDown(); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> } <add> <add> @Override <add> public void onNext(Object o) { <add> sum.incrementAndGet(); <add> } <add> }); <add> for (int i = 0; i < input.nextRuns; i++) { <add> subject.onNext("Response"); <add> } <add> subject.onCompleted(); <add> latch.await(); <add> bh.consume(sum); <add> } <add> <add> @GenerateMicroBenchmark <add> public void subscribeAfterEvents(final Input input, final BlackHole bh) throws Exception { <add> ReplaySubject<Object> subject = ReplaySubject.create(); <add> final CountDownLatch latch = new CountDownLatch(1); <add> final AtomicLong sum = new AtomicLong(); <add> <add> for (int i = 0; i < input.nextRuns; i++) { <add> subject.onNext("Response"); <add> } <add> subject.onCompleted(); <add> <add> subject.subscribe(new Observer<Object>() { <add> @Override <add> public void onCompleted() { <add> latch.countDown(); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> } <add> <add> @Override <add> public void onNext(Object o) { <add> sum.incrementAndGet(); <add> } <add> }); <add> latch.await(); <add> bh.consume(sum); <add> } <add> <add>}
4
Ruby
Ruby
fix syntax error in rdocs.
2aedb202c1c06011b5cb1715a6c76bf0104b287f
<ide><path>activesupport/lib/active_support/testing/assertions.rb <ide> def assert_blank(object, message=nil) <ide> <ide> # Test if an expression is not blank. Passes if object.present? is true. <ide> # <del> # assert_present {:data => 'x' } # => true <add> # assert_present({:data => 'x' }) # => true <ide> def assert_present(object, message=nil) <ide> message ||= "#{object.inspect} is blank" <ide> assert object.present?, message
1
PHP
PHP
fix cs errors
df20ef9809c3301972c3ecb2acf5edd22379cf49
<ide><path>tests/TestCase/Console/Command/Task/ViewTaskTest.php <ide> public function initialize(array $config) { <ide> 'foreignKey' => 'article_id' <ide> ]); <ide> } <add> <ide> } <ide> <ide> /** <ide> class ViewTaskArticlesTable extends Table { <ide> public function intialize(array $config) { <ide> $this->table('articles'); <ide> } <add> <ide> } <ide> <ide> /**
1
PHP
PHP
fix default values in postgres
a6eff184e7eca1f8d03162e6a9bc7f9202d8539c
<ide><path>src/Database/Schema/PostgresSchema.php <ide> public function convertColumnDescription(Table $table, $row) { <ide> $row['default'] = 0; <ide> } <ide> } <del> <ide> $field += [ <add> 'default' => $this->_defaultValue($row['default']), <ide> 'null' => $row['null'] === 'YES' ? true : false, <del> 'default' => $row['default'], <ide> 'comment' => $row['comment'] <ide> ]; <ide> $field['length'] = $row['char_length'] ?: $field['length']; <ide> $table->addColumn($row['name'], $field); <ide> } <ide> <add>/** <add> * Manipulate the default value. <add> * <add> * Postgres includes sequence data and casting information in default values. <add> * We need to remove those. <add> * <add> * @param string $default The default value. <add> * @return string <add> */ <add> protected function _defaultValue($default) { <add> if (is_numeric($default) || $default === null) { <add> return $default; <add> } <add> // Sequences <add> if (strpos($default, 'nextval') === 0) { <add> return null; <add> } <add> <add> // Remove quotes and postgres casts <add> return preg_replace( <add> "/^'(.*)'(?:::.*)$/", <add> "$1", <add> $default <add> ); <add> } <add> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide> public function convertIndexDescription(Table $table, $row) { <ide> $columnDef = $table->column($columns[0]); <ide> if ( <ide> count($columns) === 1 && <del> in_array($columnDef['type'], ['integer', 'biginteger']) <add> in_array($columnDef['type'], ['integer', 'biginteger']) && <add> $type === Table::CONSTRAINT_PRIMARY <ide> ) { <ide> $columnDef['autoIncrement'] = true; <ide> $table->addColumn($columns[0], $columnDef); <ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php <ide> protected function _createTables($connection) { <ide> $table = <<<SQL <ide> CREATE TABLE schema_authors ( <ide> id SERIAL, <del>name VARCHAR(50), <add>name VARCHAR(50) DEFAULT 'bob', <ide> bio DATE, <del>position INT, <add>position INT DEFAULT 1, <ide> created TIMESTAMP, <ide> PRIMARY KEY (id), <ide> CONSTRAINT "unique_position" UNIQUE ("position") <ide> public function testDescribeTable() { <ide> } <ide> } <ide> <add>/** <add> * Test describing a table containing defaults with Postgres <add> * <add> * @return void <add> */ <add> public function testDescribeTableWithDefaults() { <add> $connection = ConnectionManager::get('test'); <add> $this->_createTables($connection); <add> <add> $schema = new SchemaCollection($connection); <add> $result = $schema->describe('schema_authors'); <add> $expected = [ <add> 'id' => [ <add> 'type' => 'integer', <add> 'null' => false, <add> 'default' => null, <add> 'length' => 10, <add> 'precision' => null, <add> 'unsigned' => null, <add> 'comment' => null, <add> 'autoIncrement' => true, <add> ], <add> 'name' => [ <add> 'type' => 'string', <add> 'null' => true, <add> 'default' => 'bob', <add> 'length' => 50, <add> 'precision' => null, <add> 'comment' => null, <add> 'fixed' => null, <add> ], <add> 'bio' => [ <add> 'type' => 'date', <add> 'null' => true, <add> 'default' => null, <add> 'length' => null, <add> 'precision' => null, <add> 'comment' => null, <add> ], <add> 'position' => [ <add> 'type' => 'integer', <add> 'null' => true, <add> 'default' => '1', <add> 'length' => 10, <add> 'precision' => null, <add> 'comment' => null, <add> 'unsigned' => null, <add> 'autoIncrement' => null, <add> ], <add> 'created' => [ <add> 'type' => 'timestamp', <add> 'null' => true, <add> 'default' => null, <add> 'length' => null, <add> 'precision' => null, <add> 'comment' => null, <add> ], <add> ]; <add> $this->assertEquals(['id'], $result->primaryKey()); <add> foreach ($expected as $field => $definition) { <add> $this->assertEquals($definition, $result->column($field), "Mismatch in $field column"); <add> } <add> } <add> <ide> /** <ide> * Test describing a table with containing keywords <ide> *
2
Ruby
Ruby
add #first! and #last! to models & relations
5214e73850916de3c9127d35a4ecee0424d364a3
<ide><path>activerecord/lib/active_record/relation/finder_methods.rb <ide> def first(*args) <ide> end <ide> end <ide> <add> # Same as #first! but raises RecordNotFound if no record is returned <add> def first!(*args) <add> self.first(*args) or raise RecordNotFound <add> end <add> <ide> # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the <ide> # same arguments to this method as you can to <tt>find(:last)</tt>. <ide> def last(*args) <ide> def last(*args) <ide> end <ide> end <ide> <add> # Same as #last! but raises RecordNotFound if no record is returned <add> def last!(*args) <add> self.last(*args) or raise RecordNotFound <add> end <add> <ide> # A convenience wrapper for <tt>find(:all, *args)</tt>. You can pass in all the <ide> # same arguments to this method as you can to <tt>find(:all)</tt>. <ide> def all(*args) <ide><path>activerecord/test/cases/finder_test.rb <ide> def test_first_failing <ide> assert_nil Topic.where("title = 'The Second Topic of the day!'").first <ide> end <ide> <add> def test_first_bang_present <add> assert_nothing_raised do <add> assert_equal topics(:second), Topic.where("title = 'The Second Topic of the day'").first! <add> end <add> end <add> <add> def test_first_bang_missing <add> assert_raises ActiveRecord::RecordNotFound do <add> Topic.where("title = 'This title does not exist'").first! <add> end <add> end <add> <add> def test_last_bang_present <add> assert_nothing_raised do <add> assert_equal topics(:second), Topic.where("title = 'The Second Topic of the day'").last! <add> end <add> end <add> <add> def test_last_bang_missing <add> assert_raises ActiveRecord::RecordNotFound do <add> Topic.where("title = 'This title does not exist'").last! <add> end <add> end <add> <ide> def test_unexisting_record_exception_handling <ide> assert_raise(ActiveRecord::RecordNotFound) { <ide> Topic.find(1).parent
2
Javascript
Javascript
fix refresh inside callback
4306300b5ea8d8c4ff3daf64c7ed5fd64055ec2f
<ide><path>lib/internal/timers.js <ide> function getTimerCallbacks(runNextTicks) { <ide> if (start === undefined) <ide> start = getLibuvNow(); <ide> insert(timer, timer[kRefed], start); <del> } else { <add> } else if (!timer._idleNext && !timer._idlePrev) { <ide> if (timer[kRefed]) <ide> refCount--; <ide> timer[kRefed] = null; <ide><path>test/parallel/test-timers-refresh-in-callback.js <add>'use strict'; <add> <add>const common = require('../common'); <add> <add>// This test checks whether a refresh called inside the callback will keep <add>// the event loop alive to run the timer again. <add> <add>let didCall = false; <add>const timer = setTimeout(common.mustCall(() => { <add> if (!didCall) { <add> didCall = true; <add> timer.refresh(); <add> } <add>}, 2), 1);
2
Javascript
Javascript
add semicolon after chunk size
19839f8d984caee8ed064d0c15afa5cc89e47ede
<ide><path>test/parallel/test-http-chunked-smuggling.js <ide> function start() { <ide> 'Host: localhost:8080\r\n' + <ide> 'Transfer-Encoding: chunked\r\n' + <ide> '\r\n' + <del> '2 \n' + <add> '2;\n' + <ide> 'xx\r\n' + <ide> '4c\r\n' + <ide> '0\r\n' +
1
PHP
PHP
update docblock to match expectations
ac700f0ef4e684b07a00d4626c847007fa3da471
<ide><path>src/Illuminate/Queue/Failed/DatabaseFailedJobProvider.php <ide> public function all() <ide> * Get a single failed job. <ide> * <ide> * @param mixed $id <del> * @return array <add> * @return object|null <ide> */ <ide> public function find($id) <ide> { <ide><path>src/Illuminate/Queue/Failed/FailedJobProviderInterface.php <ide> public function all(); <ide> * Get a single failed job. <ide> * <ide> * @param mixed $id <del> * @return array <add> * @return object|null <ide> */ <ide> public function find($id); <ide> <ide><path>src/Illuminate/Queue/Failed/NullFailedJobProvider.php <ide> public function all() <ide> * Get a single failed job. <ide> * <ide> * @param mixed $id <del> * @return array <add> * @return object|null <ide> */ <ide> public function find($id) <ide> {
3
Text
Text
use sentence-case in quic.md headers
2c3092088679b355804416eb8afcf6a667a0df40
<ide><path>doc/api/quic.md <ide> socket.on('session', (session) => { <ide> <ide> ``` <ide> <del>## QUIC Basics <add>## QUIC basics <ide> <ide> QUIC is a UDP-based network transport protocol that includes built-in security <ide> via TLS 1.3, flow control, error correction, connection migration, <ide> Unlike the `net.Socket` and `tls.TLSSocket`, a `QuicSocket` instance cannot be <ide> directly used by user code at the JavaScript level to send or receive data over <ide> the network. <ide> <del>### Client and Server QuicSessions <add>### Client and server QuicSessions <ide> <ide> A `QuicSession` represents a logical connection between two QUIC endpoints (a <ide> client and a server). In the JavaScript API, each is represented by the <ide> session.on('stream', (stream) => { <ide> }); <ide> ``` <ide> <del>#### QuicStream Headers <add>#### QuicStream headers <ide> <ide> Some QUIC application protocols (like HTTP/3) make use of headers. <ide> <ide> also use explicit scope in addresses, so only packets sent to a multicast <ide> address without specifying an explicit scope are affected by the most recent <ide> successful use of this call. <ide> <del>##### Examples: IPv6 Outgoing Multicast Interface <add>##### Examples: IPv6 outgoing multicast interface <ide> <!-- YAML <ide> added: REPLACEME <ide> --> <ide> socket.on('ready', () => { <ide> }); <ide> ``` <ide> <del>##### Example: IPv4 Outgoing Multicast Interface <add>##### Example: IPv4 outgoing multicast interface <ide> <!-- YAML <ide> added: REPLACEME <ide> --> <ide> socket.on('ready', () => { <ide> }); <ide> ``` <ide> <del>##### Call Results <add>##### Call results <ide> <ide> A call on a socket that is not ready to send or no longer open may throw a <ide> Not running Error. <ide> added: REPLACEME <ide> <ide> Set to `true` if the `QuicStream` is unidirectional. <ide> <del>## Additional Notes <add>## Additional notes <ide> <del>### Custom DNS Lookup Functions <add>### Custom DNS lookup functions <ide> <ide> By default, the QUIC implementation uses the `dns` module's <ide> [promisified version of `lookup()`][] to resolve domains names
1
Ruby
Ruby
expose request method to reset the csrf token
b925880914fa3dca8c9cd0f8e88fb18fc8ec180b
<ide><path>actionpack/lib/action_dispatch/http/request.rb <ide> def body_stream # :nodoc: <ide> <ide> def reset_session <ide> session.destroy <del> controller_instance.reset_csrf_token(self) if controller_instance.respond_to?(:reset_csrf_token) <add> reset_csrf_token <ide> end <ide> <ide> def session=(session) # :nodoc: <ide> def inspect # :nodoc: <ide> "#<#{self.class.name} #{method} #{original_url.dump} for #{remote_ip}>" <ide> end <ide> <add> def reset_csrf_token <add> controller_instance.reset_csrf_token(self) if controller_instance.respond_to?(:reset_csrf_token) <add> end <add> <ide> def commit_csrf_token <ide> controller_instance.commit_csrf_token(self) if controller_instance.respond_to?(:commit_csrf_token) <ide> end
1
Ruby
Ruby
make tests for `person` pass
6198978fa23e7acc22bc0196db9315a60bea52d0
<ide><path>test/models/person.rb <ide> <ide> class Person <ide> include ActiveModel::GlobalIdentification <del> <add> <ide> attr_reader :id <del> <add> <ide> def self.find(id) <ide> new(id) <ide> end <del> <add> <ide> def initialize(id) <ide> @id = id <ide> end <del> <add> <ide> def ==(other_person) <del> other_person.is_a?(Person) && id == other_person.id <add> other_person.is_a?(Person) && id.to_s == other_person.id.to_s <ide> end <ide> end
1
Text
Text
update translation radix-sort
a5ab6f2d5ff5e044b2d7a1dbcebb41a3715aec15
<ide><path>guide/portuguese/algorithms/sorting-algorithms/radix-sort/index.md <ide> Agora, o array se torna: 10,11,17,21,123,34,44,654 Finalmente, classificamos de <ide> A matriz torna-se: 10,11,17,21,34,44,123,654 que é classificada. É assim que nosso algoritmo funciona. <ide> <ide> Uma implementação em C: <add>```c <add>void countsort(int arr[],int n,int place){ <add> int i,freq[range]={0}; // range for integers is 10 as digits range from 0-9 <add> int output[n]; <add> <add> for(i=0;i<n;i++) <add> freq[(arr[i]/place)%range]++; <add> <add> for(i=1;i<range;i++) <add> freq[i]+=freq[i-1]; <add> <add> for(i=n-1;i>=0;i--){ <add> output[freq[(arr[i]/place)%range]-1]=arr[i]; <add> freq[(arr[i]/place)%range]--; <add> } <add> <add> for(i=0;i<n;i++) <add> arr[i]=output[i]; <add>} <add> <add>void radixsort(ll arr[],int n,int maxx){ // maxx is the maximum element in the array <add> int mul=1; <add> while(maxx){ <add> countsort(arr,n,mul); <add> mul*=10; <add> maxx/=10; <add> } <add>} <ide> ``` <del>void countsort(int arr[],int n,int place){ <del> <del> int i,freq[range]={0}; //range for integers is 10 as digits range from 0-9 <del> <del> int output[n]; <del> <del> for(i=0;i<n;i++) <del> <del> freq[(arr[i]/place)%range]++; <del> <del> for(i=1;i<range;i++) <del> <del> freq[i]+=freq[i-1]; <del> <del> for(i=n-1;i>=0;i--){ <del> <del> output[freq[(arr[i]/place)%range]-1]=arr[i]; <del> <del> freq[(arr[i]/place)%range]--; <del> <del> } <del> <del> for(i=0;i<n;i++) <del> <del> arr[i]=output[i]; <del> <del> } <del> <del> void radixsort(ll arr[],int n,int maxx){ //maxx is the maximum element in the array <del> <del> int mul=1; <del> <del> while(maxx){ <del> <del> countsort(arr,n,mul); <del> <del> mul*=10; <del> <del> maxx/=10; <del> <del> } <del> <del> } <add> <add>Uma implementação em Python : <add> <add>```py <add>def counting_sort(arr, max_value, get_index): <add> counts = [0] * max_value <add> <add> # Counting - O(n) <add> for a in arr:s <add> counts[get_index(a)] += 1 <add> <add> # Accumulating - O(k) <add> for i, c in enumerate(counts): <add> if i == 0: <add> continue <add> else: <add> counts[i] += counts[i-1] <add> <add> # Calculating start index - O(k) <add> for i, c in enumerate(counts[:-1]): <add> if i == 0: <add> counts[i] = 0 <add> counts[i+1] = c <add> <add> ret = [None] * len(arr) <add> # Sorting - O(n) <add> for a in arr: <add> index = counts[get_index(a)] <add> ret[index] = a <add> counts[get_index(a)] += 1 <add> <add> return ret <ide> ``` <ide> <ide> ### Mais Informações: <ide> <ide> * [Wikipedia](https://en.wikipedia.org/wiki/Radix_sort) <ide> <del>* [GeeksForGeeks](http://www.geeksforgeeks.org/radix-sort/) <ide>\ No newline at end of file <add>* [GeeksForGeeks](http://www.geeksforgeeks.org/radix-sort/)
1
Javascript
Javascript
use isarray() to determine array type
a01ce6b81c197b0a4a1057981e8e9c1b74f37587
<ide><path>src/ng/filter/filter.js <ide> function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatc <ide> <ide> if ((expectedType === 'string') && (expected.charAt(0) === '!')) { <ide> return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp); <del> } else if (actualType === 'array') { <add> } else if (isArray(actual)) { <ide> // In case `actual` is an array, consider it a match <ide> // if ANY of it's items matches `expected` <ide> return actual.some(function(item) { <ide><path>test/ng/filter/filterSpec.js <ide> describe('Filter: filter', function() { <ide> ); <ide> <ide> <add> it('should match items with array properties containing one or more matching items', function() { <add> var items, expr; <add> <add> items = [ <add> {tags: ['web', 'html', 'css', 'js']}, <add> {tags: ['hybrid', 'html', 'css', 'js', 'ios', 'android']}, <add> {tags: ['mobile', 'ios', 'android']} <add> ]; <add> expr = {tags: 'html'}; <add> expect(filter(items, expr).length).toBe(2); <add> expect(filter(items, expr)).toEqual([items[0], items[1]]); <add> <add> items = [ <add> {nums: [1, 345, 12]}, <add> {nums: [0, 46, 78]}, <add> {nums: [123, 4, 67]} <add> ]; <add> expr = {nums: 12}; <add> expect(filter(items, expr).length).toBe(2); <add> expect(filter(items, expr)).toEqual([items[0], items[2]]); <add> <add> items = [ <add> {customers: [{name: 'John'}, {name: 'Elena'}, {name: 'Bill'}]}, <add> {customers: [{name: 'Sam'}, {name: 'Klara'}, {name: 'Bill'}]}, <add> {customers: [{name: 'Molli'}, {name: 'Elena'}, {name: 'Lora'}]} <add> ]; <add> expr = {customers: {name: 'Bill'}}; <add> expect(filter(items, expr).length).toBe(2); <add> expect(filter(items, expr)).toEqual([items[0], items[1]]); <add> } <add> ); <add> <add> <ide> it('should take object as predicate', function() { <ide> var items = [{first: 'misko', last: 'hevery'}, <ide> {first: 'adam', last: 'abrons'}];
2
Java
Java
update stomp message frames with messageid
e7dde941b7d9af04bb4a8dd5d68e9ccf4ad92b6e
<ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/PubSubHeaders.java <ide> package org.springframework.web.messaging; <ide> <ide> import java.util.Arrays; <add>import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> public PubSubHeaders(MessageHeaders messageHeaders, boolean readOnly) { <ide> <ide> this.messageHeaders = readOnly ? messageHeaders : new HashMap<String, Object>(messageHeaders); <ide> this.rawHeaders = this.messageHeaders.containsKey(RAW_HEADERS) ? <del> (Map<String, String>) messageHeaders.get(RAW_HEADERS) : new HashMap<String, String>(); <add> (Map<String, String>) messageHeaders.get(RAW_HEADERS) : Collections.<String, String>emptyMap(); <ide> <ide> if (this.messageHeaders.get(MESSAGE_TYPE) == null) { <ide> this.messageHeaders.put(MESSAGE_TYPE, MessageType.MESSAGE); <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/AbstractMessageService.java <ide> public void accept(Message<?> message) { <ide> logger.trace("Processing notification: " + message); <ide> } <ide> <del> MessageType messageType = (MessageType) message.getHeaders().get("messageType"); <add> PubSubHeaders headers = new PubSubHeaders(message.getHeaders(), true); <add> MessageType messageType = headers.getMessageType(); <ide> if (messageType == null || messageType.equals(MessageType.OTHER)) { <ide> processOther(message); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/StompHeaders.java <ide> public void updateRawHeaders() { <ide> if (subscriptionId != null) { <ide> getRawHeaders().put(SUBSCRIPTION, subscriptionId); <ide> } <add> if (StompCommand.MESSAGE.equals(getStompCommand()) && (getMessageId() == null)) { <add> getRawHeaders().put(MESSAGE_ID, getMessageHeaders().get(ID).toString()); <add> } <ide> } <ide> <ide> }
3
Python
Python
fix typo in multiarray sources
7f5efe309720501fbfa2cca886e47cb97e72f35b
<ide><path>numpy/core/setup.py <ide> def generate_umath_c(ext,build_dir): <ide> join('src', 'multiarray', 'common.c'), <ide> join('src', 'multiarray', 'usertypes.c'), <ide> join('src', 'multiarray', 'scalarapi.c'), <del> join('src', 'multiarray', 'refecount.c'), <add> join('src', 'multiarray', 'refcount.c'), <ide> join('src', 'multiarray', 'arraytypes.c.src'), <ide> join('src', 'multiarray', 'scalartypes.c.src')] <ide>
1
Ruby
Ruby
make these methods on env
3977beb8ed091606ff025c918368a2f94863da84
<ide><path>Library/Homebrew/extend/ENV.rb <ide> def setup_build_environment <ide> self['CMAKE_PREFIX_PATH'] = "#{HOMEBREW_PREFIX}" <ide> end <ide> <del> if MACOS_VERSION >= 10.6 and (self['HOMEBREW_USE_CLANG'] or ARGV.include? '--use-clang') <add> if MACOS_VERSION >= 10.6 and self.use_clang? <ide> self['CC'] = "#{MacOS.xcode_prefix}/usr/bin/clang" <ide> self['CXX'] = "#{MacOS.xcode_prefix}/usr/bin/clang++" <ide> cflags = ['-O3'] # -O4 makes the linker fail on some formulae <del> elsif MACOS_VERSION >= 10.6 and (self['HOMEBREW_USE_LLVM'] or ARGV.include? '--use-llvm') <add> elsif MACOS_VERSION >= 10.6 and self.use_llvm? <ide> self['CC'] = "#{MacOS.xcode_prefix}/usr/bin/llvm-gcc" <ide> self['CXX'] = "#{MacOS.xcode_prefix}/usr/bin/llvm-g++" <ide> cflags = ['-O4'] # link time optimisation baby! <del> elsif MACOS_VERSION >= 10.6 and (self['HOMEBREW_USE_GCC'] or ARGV.include? '--use-gcc') <add> elsif MACOS_VERSION >= 10.6 and self.use_gcc? <ide> self['CC'] = "#{MacOS.xcode_prefix}/usr/bin/gcc" <ide> self['CXX'] = "#{MacOS.xcode_prefix}/usr/bin/g++" <ide> cflags = ['-O3'] <ide> def remove_from_cflags f <ide> remove 'CFLAGS', f <ide> remove 'CXXFLAGS', f <ide> end <add> <add> def use_clang? <add> self['HOMEBREW_USE_CLANG'] or ARGV.include? '--use-clang' <add> end <add> def use_gcc? <add> self['HOMEBREW_USE_GCC'] or ARGV.include? '--use-gcc' <add> end <add> def use_llvm? <add> self['HOMEBREW_USE_LLVM'] or ARGV.include? '--use-llvm' <add> end <ide> end
1
Javascript
Javascript
prevent missing charcode to block the rendering
0ea9411f69fea09f3d9dc1f45202b00a1cd6f342
<ide><path>fonts.js <ide> var Font = (function Font() { <ide> // loop should never end on the last byte <ide> for (var i = 0; i < length; i++) { <ide> var charcode = int16([chars.charCodeAt(i++), chars.charCodeAt(i)]); <del> var unicode = encoding[charcode].unicode; <add> var unicode = encoding[charcode]; <add> if ('undefined' == typeof(unicode)) { <add> warn('Unencoded charcode ' + charcode); <add> unicode = charcode; <add> } else { <add> unicode = unicode.unicode; <add> } <ide> str += String.fromCharCode(unicode); <ide> } <ide> } <ide> else { <ide> for (var i = 0; i < chars.length; ++i) { <ide> var charcode = chars.charCodeAt(i); <del> var unicode = encoding[charcode].unicode; <add> var unicode = encoding[charcode]; <ide> if ('undefined' == typeof(unicode)) { <ide> warn('Unencoded charcode ' + charcode); <ide> unicode = charcode; <add> } else { <add> unicode = unicode.unicode; <ide> } <ide> <ide> // Handle surrogate pairs
1
Text
Text
avoid memory leak warning in async_hooks example
3518919cb7a8fca324f67c3fa3c61f1d820f61b2
<ide><path>doc/api/async_hooks.md <ide> class WorkerPool extends EventEmitter { <ide> this.numThreads = numThreads; <ide> this.workers = []; <ide> this.freeWorkers = []; <add> this.tasks = []; <ide> <ide> for (let i = 0; i < numThreads; i++) <ide> this.addNewWorker(); <add> <add> // Any time the kWorkerFreedEvent is emitted, dispatch <add> // the next task pending in the queue, if any. <add> this.on(kWorkerFreedEvent, () => { <add> if (this.tasks.length > 0) { <add> const { task, callback } = this.tasks.shift(); <add> this.runTask(task, callback); <add> } <add> }); <ide> } <ide> <ide> addNewWorker() { <ide> class WorkerPool extends EventEmitter { <ide> runTask(task, callback) { <ide> if (this.freeWorkers.length === 0) { <ide> // No free threads, wait until a worker thread becomes free. <del> this.once(kWorkerFreedEvent, () => this.runTask(task, callback)); <add> this.tasks.push({ task, callback }); <ide> return; <ide> } <ide>
1
Ruby
Ruby
use sort_by in prettylisting
6a1ad36fbd99b75f67cbc234cb887218b2d9d8cc
<ide><path>Library/Homebrew/cmd/list.rb <ide> def list_pinned <ide> <ide> class PrettyListing <ide> def initialize path <del> Pathname.new(path).children.sort{ |a,b| a.to_s.downcase <=> b.to_s.downcase }.each do |pn| <add> Pathname.new(path).children.sort_by { |p| p.to_s.downcase }.each do |pn| <ide> case pn.basename.to_s <ide> when 'bin', 'sbin' <ide> pn.find { |pnn| puts pnn unless pnn.directory? }
1
Ruby
Ruby
use 1.9 compat syntax. fixes homebrew/homebrew
492748bc0b2776ff4f14017fd482961feadd3034
<ide><path>Library/Homebrew/formula.rb <ide> class SoftwareSpecification <ide> attr_reader :url, :specs, :using <ide> <ide> VCS_SYMBOLS = { <del> :bzr, BazaarDownloadStrategy, <del> :curl, CurlDownloadStrategy, <del> :cvs, CVSDownloadStrategy, <del> :git, GitDownloadStrategy, <del> :hg, MercurialDownloadStrategy, <del> :nounzip, NoUnzipCurlDownloadStrategy, <del> :post, CurlPostDownloadStrategy, <del> :svn, SubversionDownloadStrategy, <add> :bzr => BazaarDownloadStrategy, <add> :curl => CurlDownloadStrategy, <add> :cvs => CVSDownloadStrategy, <add> :git => GitDownloadStrategy, <add> :hg => MercurialDownloadStrategy, <add> :nounzip => NoUnzipCurlDownloadStrategy, <add> :post => CurlPostDownloadStrategy, <add> :svn => SubversionDownloadStrategy, <ide> } <ide> <ide> def initialize url, specs=nil
1
Python
Python
fix handling of non-empty ndarrays
c01165f43068fea96722c172eb23efed4ca99763
<ide><path>numpy/lib/index_tricks.py <ide> def ix_(*args): <ide> out = [] <ide> nd = len(args) <ide> for k, new in enumerate(args): <del> # Explicitly type empty sequences to avoid float default <del> new = asarray(new, dtype=None if new else _nx.intp) <del> if (new.ndim != 1): <add> new = asarray(new) <add> if new.ndim != 1: <ide> raise ValueError("Cross index must be 1 dimensional") <add> if new.size == 0: <add> # Explicitly type empty arrays to avoid float default <add> new = new.astype(_nx.intp) <ide> if issubdtype(new.dtype, _nx.bool_): <ide> new, = new.nonzero() <ide> new.shape = (1,)*k + (new.size,) + (1,)*(nd-k-1) <ide><path>numpy/lib/tests/test_index_tricks.py <ide> def test_simple_1(self): <ide> <ide> class TestIx_(TestCase): <ide> def test_regression_1(self): <del> # Empty inputs create ouputs of indexing type, gh-5804 <del> a, = np.ix_(range(0, 0)) <del> assert_equal(a.dtype, np.intp) <add> # Test empty inputs create ouputs of indexing type, gh-5804 <add> # Test both lists and arrays <add> for func in (range, np.arange): <add> a, = np.ix_(func(0)) <add> assert_equal(a.dtype, np.intp) <ide> <ide> def test_shape_and_dtype(self): <ide> sizes = (4, 5, 3, 2) <del> arrays = np.ix_(*[range(sz) for sz in sizes]) <del> for k, (a, sz) in enumerate(zip(arrays, sizes)): <del> assert_equal(a.shape[k], sz) <del> assert_(all(sh == 1 for j, sh in enumerate(a.shape) if j != k)) <del> assert_(np.issubdtype(a.dtype, int)) <add> # Test both lists and arrays <add> for func in (range, np.arange): <add> arrays = np.ix_(*[func(sz) for sz in sizes]) <add> for k, (a, sz) in enumerate(zip(arrays, sizes)): <add> assert_equal(a.shape[k], sz) <add> assert_(all(sh == 1 for j, sh in enumerate(a.shape) if j != k)) <add> assert_(np.issubdtype(a.dtype, int)) <ide> <ide> def test_bool(self): <ide> bool_a = [True, False, True, True]
2
Go
Go
remove lxcconf in daemon_test.go and fix a typo
00d00b429ff6f5cecf6789d6b6773b8e979ad0ae
<ide><path>daemon/daemon_test.go <ide> func TestLoadWithVolume(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> hostConfig := `{"Binds":[],"ContainerIDFile":"","LxcConf":[],"Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", <add> hostConfig := `{"Binds":[],"ContainerIDFile":"","Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", <ide> "Privileged":false,"PortBindings":{},"Links":null,"PublishAllPorts":false,"Dns":null,"DnsOptions":null,"DnsSearch":null,"ExtraHosts":null,"VolumesFrom":null, <ide> "Devices":[],"NetworkMode":"bridge","IpcMode":"","PidMode":"","CapAdd":null,"CapDrop":null,"RestartPolicy":{"Name":"no","MaximumRetryCount":0}, <ide> "SecurityOpt":null,"ReadonlyRootfs":false,"Ulimits":null,"LogConfig":{"Type":"","Config":null},"CgroupParent":""}` <ide> func TestLoadWithBindMount(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> hostConfig := `{"Binds":["/vol1:/vol1"],"ContainerIDFile":"","LxcConf":[],"Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", <add> hostConfig := `{"Binds":["/vol1:/vol1"],"ContainerIDFile":"","Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", <ide> "Privileged":false,"PortBindings":{},"Links":null,"PublishAllPorts":false,"Dns":null,"DnsOptions":null,"DnsSearch":null,"ExtraHosts":null,"VolumesFrom":null, <ide> "Devices":[],"NetworkMode":"bridge","IpcMode":"","PidMode":"","CapAdd":null,"CapDrop":null,"RestartPolicy":{"Name":"no","MaximumRetryCount":0}, <ide> "SecurityOpt":null,"ReadonlyRootfs":false,"Ulimits":null,"LogConfig":{"Type":"","Config":null},"CgroupParent":""}` <ide> func TestLoadWithVolume17RC(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> hostConfig := `{"Binds":[],"ContainerIDFile":"","LxcConf":[],"Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", <add> hostConfig := `{"Binds":[],"ContainerIDFile":"","Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", <ide> "Privileged":false,"PortBindings":{},"Links":null,"PublishAllPorts":false,"Dns":null,"DnsOptions":null,"DnsSearch":null,"ExtraHosts":null,"VolumesFrom":null, <ide> "Devices":[],"NetworkMode":"bridge","IpcMode":"","PidMode":"","CapAdd":null,"CapDrop":null,"RestartPolicy":{"Name":"no","MaximumRetryCount":0}, <ide> "SecurityOpt":null,"ReadonlyRootfs":false,"Ulimits":null,"LogConfig":{"Type":"","Config":null},"CgroupParent":""}` <ide> func TestRemoveLocalVolumesFollowingSymlinks(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> hostConfig := `{"Binds":[],"ContainerIDFile":"","LxcConf":[],"Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", <add> hostConfig := `{"Binds":[],"ContainerIDFile":"","Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", <ide> "Privileged":false,"PortBindings":{},"Links":null,"PublishAllPorts":false,"Dns":null,"DnsOptions":null,"DnsSearch":null,"ExtraHosts":null,"VolumesFrom":null, <ide> "Devices":[],"NetworkMode":"bridge","IpcMode":"","PidMode":"","CapAdd":null,"CapDrop":null,"RestartPolicy":{"Name":"no","MaximumRetryCount":0}, <ide> "SecurityOpt":null,"ReadonlyRootfs":false,"Ulimits":null,"LogConfig":{"Type":"","Config":null},"CgroupParent":""}` <ide><path>daemon/execdriver/driver.go <ide> import ( <ide> ) <ide> <ide> // Context is a generic key value pair that allows <del>// arbatrary data to be sent <add>// arbitrary data to be sent <ide> type Context map[string]string <ide> <ide> // Define error messages
2
Text
Text
remove extra space from manpage
20d05297c3089fb6c214a94e26814417b533d0f0
<ide><path>docs/Manpage.md <ide> to send a notification when the autoupdate process has finished successfully. <ide> <br>Output this tool's current version. <ide> <ide> * `--upgrade`: <del> Automatically upgrade your installed formulae. If the Caskroom exists locally Casks will be upgraded as well. Must be passed with `start`. <add> Automatically upgrade your installed formulae. If the Caskroom exists locally Casks will be upgraded as well. Must be passed with `start`. <ide> * `--cleanup`: <ide> Automatically clean brew's cache and logs. Must be passed with `start`. <ide> * `--enable-notification`:
1
Python
Python
add basic japanese support
c8f83aeb873c2d3beff22cbe0f967b6d56b6793e
<ide><path>setup.py <ide> 'spacy.fi', <ide> 'spacy.bn', <ide> 'spacy.he', <del> 'spacy.nb', <add> 'spacy.nb', <add> 'spacy.ja', <ide> 'spacy.en.lemmatizer', <ide> 'spacy.cli.converters', <ide> 'spacy.language_data', <ide><path>spacy/__init__.py <ide> from .deprecated import resolve_model_name <ide> from .cli.info import info <ide> <del>from . import en, de, zh, es, it, hu, fr, pt, nl, sv, fi, bn, he, nb <add>from . import en, de, zh, es, it, hu, fr, pt, nl, sv, fi, bn, he, nb, ja <ide> <ide> <ide> _languages = (en.English, de.German, es.Spanish, pt.Portuguese, fr.French, <ide> it.Italian, hu.Hungarian, zh.Chinese, nl.Dutch, sv.Swedish, <del> fi.Finnish, bn.Bengali, he.Hebrew, nb.Norwegian) <add> fi.Finnish, bn.Bengali, he.Hebrew, nb.Norwegian, ja.Japanese) <ide> <ide> <ide> for _lang in _languages: <ide><path>spacy/ja/__init__.py <add># encoding: utf8 <add>from __future__ import unicode_literals, print_function <add> <add>from os import path <add> <add>from ..language import Language <add>from ..attrs import LANG <add>from ..tokens import Doc <add> <add>from .language_data import * <add> <add> <add>class Japanese(Language): <add> lang = 'ja' <add> <add> def make_doc(self, text): <add> from janome.tokenizer import Tokenizer <add> words = [x.surface for x in Tokenizer().tokenize(text)] <add> return Doc(self.vocab, words=words, spaces=[False]*len(words)) <ide><path>spacy/ja/language_data.py <add># encoding: utf8 <add>from __future__ import unicode_literals <add> <add> <add># import base language data <add>from .. import language_data as base <add> <add> <add># import util functions <add>from ..language_data import update_exc, strings_to_exc <add> <add> <add># import language-specific data from files <add>from .tag_map import TAG_MAP <add>from .stop_words import STOP_WORDS <add> <add> <add>TAG_MAP = dict(TAG_MAP) <add>STOP_WORDS = set(STOP_WORDS) <add> <add> <add># export <add>__all__ = ["TAG_MAP", "STOP_WORDS"] <ide>\ No newline at end of file <ide><path>spacy/ja/stop_words.py <add># encoding: utf8 <add>from __future__ import unicode_literals <add> <add> <add># stop words as whitespace-separated list <add>STOP_WORDS = set(""" <add>。 <add>、 <add>""".split()) <ide>\ No newline at end of file <ide><path>spacy/ja/tag_map.py <add># encoding: utf8 <add>from __future__ import unicode_literals <add> <add>from ..symbols import * <add> <add> <add>TAG_MAP = { <add> "ADV": {POS: ADV}, <add> "NOUN": {POS: NOUN}, <add> "ADP": {POS: ADP}, <add> "PRON": {POS: PRON}, <add> "SCONJ": {POS: SCONJ}, <add> "PROPN": {POS: PROPN}, <add> "DET": {POS: DET}, <add> "SYM": {POS: SYM}, <add> "INTJ": {POS: INTJ}, <add> "PUNCT": {POS: PUNCT}, <add> "NUM": {POS: NUM}, <add> "AUX": {POS: AUX}, <add> "X": {POS: X}, <add> "CONJ": {POS: CONJ}, <add> "ADJ": {POS: ADJ}, <add> "VERB": {POS: VERB} <add>} <ide>\ No newline at end of file
6
Go
Go
remove unused istransporturl()
074bc1c3ab6c6d506200a002b6e8809e4cf3ce38
<ide><path>pkg/urlutil/urlutil.go <ide> // Package urlutil provides helper function to check urls kind. <del>// It supports http urls, git urls and transport url (tcp://, …) <add>// It supports http and git urls. <ide> package urlutil // import "github.com/docker/docker/pkg/urlutil" <ide> <ide> import ( <ide> var ( <ide> // <ide> // Going forward, no additional prefixes should be added, and users should <ide> // be encouraged to use explicit URLs (https://github.com/user/repo.git) instead. <del> "git": {"git://", "github.com/", "git@"}, <del> "transport": {"tcp://", "tcp+tls://", "udp://", "unix://", "unixgram://"}, <add> "git": {"git://", "github.com/", "git@"}, <ide> } <ide> urlPathWithFragmentSuffix = regexp.MustCompile(".git(?:#.+)?$") <ide> ) <ide> func IsGitURL(str string) bool { <ide> return checkURL(str, "git") <ide> } <ide> <del>// IsTransportURL returns true if the provided str is a transport (tcp, tcp+tls, udp, unix) URL. <del>func IsTransportURL(str string) bool { <del> return checkURL(str, "transport") <del>} <del> <ide> func checkURL(str, kind string) bool { <ide> for _, prefix := range validPrefixes[kind] { <ide> if strings.HasPrefix(str, prefix) { <ide><path>pkg/urlutil/urlutil_test.go <ide> var ( <ide> invalidGitUrls = []string{ <ide> "http://github.com/docker/docker.git:#branch", <ide> } <del> transportUrls = []string{ <del> "tcp://example.com", <del> "tcp+tls://example.com", <del> "udp://example.com", <del> "unix:///example", <del> "unixgram:///example", <del> } <ide> ) <ide> <ide> func TestIsGIT(t *testing.T) { <ide> func TestIsGIT(t *testing.T) { <ide> } <ide> } <ide> } <del> <del>func TestIsTransport(t *testing.T) { <del> for _, url := range transportUrls { <del> if !IsTransportURL(url) { <del> t.Fatalf("%q should be detected as valid Transport url", url) <del> } <del> } <del>}
2
Go
Go
fix a typo
2c6fbd864ae089e9cb544666949b8b2d897b3b23
<ide><path>daemon/logger/loggerutils/logfile.go <ide> func watchFile(name string) (filenotify.FileWatcher, error) { <ide> <ide> logger := logrus.WithFields(logrus.Fields{ <ide> "module": "logger", <del> "fille": name, <add> "file": name, <ide> }) <ide> <ide> if err := fileWatcher.Add(name); err != nil {
1
PHP
PHP
use a better assert
fad9410ac23c9d1bc186ce94462e9aa641d7499b
<ide><path>tests/TestCase/Log/LogTest.php <ide> public function testLogFileWriting() { <ide> } <ide> $result = Log::write(LOG_WARNING, 'Test warning'); <ide> $this->assertTrue($result); <del> $this->assertTrue(file_exists(LOGS . 'error.log')); <add> $this->assertFileExists(LOGS . 'error.log'); <ide> unlink(LOGS . 'error.log'); <ide> <ide> Log::write(LOG_WARNING, 'Test warning 1'); <ide> public function testSelectiveLoggingByLevel() { <ide> $testMessage = 'selective logging'; <ide> Log::write(LOG_WARNING, $testMessage); <ide> <del> $this->assertTrue(file_exists(LOGS . 'eggs.log')); <del> $this->assertFalse(file_exists(LOGS . 'spam.log')); <add> $this->assertFileExists(LOGS . 'eggs.log'); <add> $this->assertFileNotExists(LOGS . 'spam.log'); <ide> <ide> Log::write(LOG_DEBUG, $testMessage); <del> $this->assertTrue(file_exists(LOGS . 'spam.log')); <add> $this->assertFileExists(LOGS . 'spam.log'); <ide> <ide> $contents = file_get_contents(LOGS . 'spam.log'); <ide> $this->assertContains('Debug: ' . $testMessage, $contents); <ide> public function testScopedLogging() { <ide> )); <ide> <ide> Log::write('info', 'info message', 'transactions'); <del> $this->assertFalse(file_exists(LOGS . 'error.log')); <del> $this->assertTrue(file_exists(LOGS . 'shops.log')); <del> $this->assertTrue(file_exists(LOGS . 'debug.log')); <add> $this->assertFileNotExists(LOGS . 'error.log'); <add> $this->assertFileExists(LOGS . 'shops.log'); <add> $this->assertFileExists(LOGS . 'debug.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::write('warning', 'warning message', 'orders'); <del> $this->assertTrue(file_exists(LOGS . 'error.log')); <del> $this->assertTrue(file_exists(LOGS . 'shops.log')); <del> $this->assertFalse(file_exists(LOGS . 'debug.log')); <add> $this->assertFileExists(LOGS . 'error.log'); <add> $this->assertFileExists(LOGS . 'shops.log'); <add> $this->assertFileNotExists(LOGS . 'debug.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::write('error', 'error message', 'orders'); <del> $this->assertTrue(file_exists(LOGS . 'error.log')); <del> $this->assertFalse(file_exists(LOGS . 'debug.log')); <del> $this->assertFalse(file_exists(LOGS . 'shops.log')); <add> $this->assertFileExists(LOGS . 'error.log'); <add> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertFileNotExists(LOGS . 'shops.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> public function testConvenienceScopedLogging() { <ide> )); <ide> <ide> Log::info('info message', 'transactions'); <del> $this->assertFalse(file_exists(LOGS . 'error.log')); <del> $this->assertTrue(file_exists(LOGS . 'shops.log')); <del> $this->assertTrue(file_exists(LOGS . 'debug.log')); <add> $this->assertFileNotExists(LOGS . 'error.log'); <add> $this->assertFileExists(LOGS . 'shops.log'); <add> $this->assertFileExists(LOGS . 'debug.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::error('error message', 'orders'); <del> $this->assertTrue(file_exists(LOGS . 'error.log')); <del> $this->assertFalse(file_exists(LOGS . 'debug.log')); <del> $this->assertFalse(file_exists(LOGS . 'shops.log')); <add> $this->assertFileExists(LOGS . 'error.log'); <add> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertFileNotExists(LOGS . 'shops.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::warning('warning message', 'orders'); <del> $this->assertTrue(file_exists(LOGS . 'error.log')); <del> $this->assertTrue(file_exists(LOGS . 'shops.log')); <del> $this->assertFalse(file_exists(LOGS . 'debug.log')); <add> $this->assertFileExists(LOGS . 'error.log'); <add> $this->assertFileExists(LOGS . 'shops.log'); <add> $this->assertFileNotExists(LOGS . 'debug.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> public function testScopedLoggingExclusive() { <ide> )); <ide> <ide> Log::write('info', 'transactions message', 'transactions'); <del> $this->assertFalse(file_exists(LOGS . 'eggs.log')); <del> $this->assertTrue(file_exists(LOGS . 'shops.log')); <add> $this->assertFileNotExists(LOGS . 'eggs.log'); <add> $this->assertFileExists(LOGS . 'shops.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::write('info', 'eggs message', 'eggs'); <del> $this->assertTrue(file_exists(LOGS . 'eggs.log')); <del> $this->assertFalse(file_exists(LOGS . 'shops.log')); <add> $this->assertFileExists(LOGS . 'eggs.log'); <add> $this->assertFileNotExists(LOGS . 'shops.log'); <ide> } <ide> <ide> /** <ide> public function testConvenienceMethods() { <ide> Log::emergency($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <ide> $this->assertRegExp('/(Emergency|Critical): ' . $testMessage . '/', $contents); <del> $this->assertFalse(file_exists(LOGS . 'debug.log')); <add> $this->assertFileNotExists(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'alert message'; <ide> Log::alert($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <ide> $this->assertRegExp('/(Alert|Critical): ' . $testMessage . '/', $contents); <del> $this->assertFalse(file_exists(LOGS . 'debug.log')); <add> $this->assertFileNotExists(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'critical message'; <ide> Log::critical($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <ide> $this->assertContains('Critical: ' . $testMessage, $contents); <del> $this->assertFalse(file_exists(LOGS . 'debug.log')); <add> $this->assertFileNotExists(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'error message'; <ide> Log::error($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <ide> $this->assertContains('Error: ' . $testMessage, $contents); <del> $this->assertFalse(file_exists(LOGS . 'debug.log')); <add> $this->assertFileNotExists(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'warning message'; <ide> Log::warning($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <ide> $this->assertContains('Warning: ' . $testMessage, $contents); <del> $this->assertFalse(file_exists(LOGS . 'debug.log')); <add> $this->assertFileNotExists(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'notice message'; <ide> Log::notice($testMessage); <ide> $contents = file_get_contents(LOGS . 'debug.log'); <ide> $this->assertRegExp('/(Notice|Debug): ' . $testMessage . '/', $contents); <del> $this->assertFalse(file_exists(LOGS . 'error.log')); <add> $this->assertFileNotExists(LOGS . 'error.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'info message'; <ide> Log::info($testMessage); <ide> $contents = file_get_contents(LOGS . 'debug.log'); <ide> $this->assertRegExp('/(Info|Debug): ' . $testMessage . '/', $contents); <del> $this->assertFalse(file_exists(LOGS . 'error.log')); <add> $this->assertFileNotExists(LOGS . 'error.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'debug message'; <ide> Log::debug($testMessage); <ide> $contents = file_get_contents(LOGS . 'debug.log'); <ide> $this->assertContains('Debug: ' . $testMessage, $contents); <del> $this->assertFalse(file_exists(LOGS . 'error.log')); <add> $this->assertFileNotExists(LOGS . 'error.log'); <ide> $this->_deleteLogs(); <ide> } <ide>
1
Ruby
Ruby
fix external perl checker
d84b1711d052cc1ed5f3b818532fe629d04acbf4
<ide><path>Library/Homebrew/formula_installer.rb <ide> def check_external_deps f <ide> raise pyerr(dep) unless quiet_system "/usr/bin/env", "python", "-c", "import #{dep}" <ide> end <ide> f.external_deps[:perl].each do |dep| <del> raise plerr(dep) unless quiet_system "/usr/bin/env", "perl", "-e", "use '#{dep}'" <add> raise plerr(dep) unless quiet_system "/usr/bin/env", "perl", "-e", "use #{dep}" <ide> end <ide> f.external_deps[:ruby].each do |dep| <ide> raise rberr(dep) unless quiet_system "/usr/bin/env", "ruby", "-rubygems", "-e", "require '#{dep}'"
1
Ruby
Ruby
stringify param values in controller tests
9277e72a3ca1009f135b1eb194ff6f3c96a55c1b
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def xml_http_request(request_method, action, parameters = nil, session = nil, fl <ide> end <ide> alias xhr :xml_http_request <ide> <add> def stringify_values(hash_or_array_or_value) <add> case hash_or_array_or_value <add> when Hash <add> hash_or_array_or_value.each do |key, value| <add> hash_or_array_or_value[key] = stringify_values(value) <add> end <add> when Array <add> hash_or_array_or_value.map {|i| stringify_values(i)} <add> when Numeric, Symbol <add> hash_or_array_or_value.to_s <add> else <add> hash_or_array_or_value <add> end <add> end <add> <ide> def process(action, parameters = nil, session = nil, flash = nil, http_method = 'GET') <add> # Ensure that numbers and symbols passed as params are converted to <add> # strings, as is the case when engaging rack. <add> stringify_values(parameters) <add> <ide> # Sanity check for required instance variables so we can give an <ide> # understandable error message. <ide> %w(@routes @controller @request @response).each do |iv_name| <ide><path>actionpack/test/controller/test_test.rb <ide> def test_params_passing <ide> ) <ide> end <ide> <add> def test_params_passing_with_fixnums <add> get :test_params, :page => {:name => "Page name", :month => 4, :year => 2004, :day => 6} <add> parsed_params = eval(@response.body) <add> assert_equal( <add> {'controller' => 'test_test/test', 'action' => 'test_params', <add> 'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}}, <add> parsed_params <add> ) <add> end <add> <ide> def test_params_passing_with_frozen_values <ide> assert_nothing_raised do <ide> get :test_params, :frozen => 'icy'.freeze, :frozens => ['icy'.freeze].freeze
2
Ruby
Ruby
allow mounting engines at '/'
22b11a41cc764bc0f7b0c0f518a5289230428597
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def url_for(options) <ide> end <ide> <ide> script_name = options.delete(:script_name) <del> path = (script_name.blank? ? _generate_prefix(options) : script_name).to_s <add> path = (script_name.blank? ? _generate_prefix(options) : script_name.chomp('/')).to_s <ide> <ide> path_options = options.except(*RESERVED_OPTIONS) <ide> path_options = yield(path_options) if block_given? <ide><path>actionpack/test/dispatch/prefix_generation_test.rb <ide> require 'abstract_unit' <add>require 'rack/test' <ide> <ide> module TestGenerationPrefix <add> class Post <add> extend ActiveModel::Naming <add> <add> def to_param <add> "1" <add> end <add> <add> def self.model_name <add> klass = "Post" <add> def klass.name; self end <add> <add> ActiveModel::Name.new(klass) <add> end <add> end <add> <ide> class WithMountedEngine < ActionDispatch::IntegrationTest <del> require 'rack/test' <ide> include Rack::Test::Methods <ide> <ide> class BlogEngine <ide> def self.call(env) <ide> # force draw <ide> RailsApplication.routes <ide> <del> class Post <del> extend ActiveModel::Naming <del> <del> def to_param <del> "1" <del> end <del> <del> def self.model_name <del> klass = "Post" <del> def klass.name; self end <del> <del> ActiveModel::Name.new(klass) <del> end <del> end <del> <ide> class ::InsideEngineGeneratingController < ActionController::Base <ide> include BlogEngine.routes.url_helpers <ide> include RailsApplication.routes.mounted_helpers <ide> def setup <ide> assert_equal "http://www.example.com/awesome/blog/posts/1", path <ide> end <ide> end <add> <add> class EngineMountedAtRoot < ActionDispatch::IntegrationTest <add> include Rack::Test::Methods <add> <add> class BlogEngine <add> def self.routes <add> @routes ||= begin <add> routes = ActionDispatch::Routing::RouteSet.new <add> routes.draw do <add> match "/posts/:id", :to => "posts#show", :as => :post <add> end <add> <add> routes <add> end <add> end <add> <add> def self.call(env) <add> env['action_dispatch.routes'] = routes <add> routes.call(env) <add> end <add> end <add> <add> class RailsApplication <add> def self.routes <add> @routes ||= begin <add> routes = ActionDispatch::Routing::RouteSet.new <add> routes.draw do <add> mount BlogEngine => "/" <add> end <add> <add> routes <add> end <add> end <add> <add> def self.call(env) <add> env['action_dispatch.routes'] = routes <add> routes.call(env) <add> end <add> end <add> <add> # force draw <add> RailsApplication.routes <add> <add> class ::PostsController < ActionController::Base <add> include BlogEngine.routes.url_helpers <add> include RailsApplication.routes.mounted_helpers <add> <add> def show <add> render :text => post_path(:id => params[:id]) <add> end <add> end <add> <add> def app <add> RailsApplication <add> end <add> <add> test "generating path inside engine" do <add> get "/posts/1" <add> assert_equal "/posts/1", last_response.body <add> end <add> end <ide> end
2
Go
Go
add logdrivers to /info
17abacb8946ed89496fcbf07a0288fafe24cb7b0
<ide><path>api/types/types.go <ide> type PluginsInfo struct { <ide> Network []string <ide> // List of Authorization plugins registered <ide> Authorization []string <add> // List of Log plugins registered <add> Log []string <ide> } <ide> <ide> // ExecStartCheck is a temp struct used by execStart <ide><path>cli/command/system/info.go <ide> func prettyPrintInfo(dockerCli *command.DockerCli, info types.Info) error { <ide> fmt.Fprintf(dockerCli.Out(), "\n") <ide> } <ide> <add> fmt.Fprintf(dockerCli.Out(), " Log:") <add> fmt.Fprintf(dockerCli.Out(), " %s", strings.Join(info.Plugins.Log, " ")) <add> fmt.Fprintf(dockerCli.Out(), "\n") <add> <ide> fmt.Fprintf(dockerCli.Out(), "Swarm: %v\n", info.Swarm.LocalNodeState) <ide> if info.Swarm.LocalNodeState != swarm.LocalNodeStateInactive && info.Swarm.LocalNodeState != swarm.LocalNodeStateLocked { <ide> fmt.Fprintf(dockerCli.Out(), " NodeID: %s\n", info.Swarm.NodeID) <ide><path>daemon/cluster/executor/container/executor.go <ide> func (e *executor) Describe(ctx context.Context) (*api.NodeDescription, error) { <ide> // the plugin list by default. <ide> addPlugins("Network", append([]string{"overlay"}, info.Plugins.Network...)) <ide> addPlugins("Authorization", info.Plugins.Authorization) <add> addPlugins("Log", info.Plugins.Log) <ide> <ide> // add v2 plugins <ide> v2Plugins, err := e.backend.PluginManager().List(filters.NewArgs()) <ide> func (e *executor) Describe(ctx context.Context) (*api.NodeDescription, error) { <ide> continue <ide> } <ide> plgnTyp := typ.Capability <del> if typ.Capability == "volumedriver" { <add> switch typ.Capability { <add> case "volumedriver": <ide> plgnTyp = "Volume" <del> } else if typ.Capability == "networkdriver" { <add> case "networkdriver": <ide> plgnTyp = "Network" <add> case "logdriver": <add> plgnTyp = "Log" <ide> } <add> <ide> plugins[api.PluginDescription{ <ide> Type: plgnTyp, <ide> Name: plgn.Name, <ide><path>daemon/info.go <ide> import ( <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/cli/debug" <ide> "github.com/docker/docker/container" <add> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/dockerversion" <ide> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/parsers/kernel" <ide> func (daemon *Daemon) showPluginsInfo() types.PluginsInfo { <ide> pluginsInfo.Volume = volumedrivers.GetDriverList() <ide> pluginsInfo.Network = daemon.GetNetworkDriverList() <ide> pluginsInfo.Authorization = daemon.configStore.GetAuthorizationPlugins() <add> pluginsInfo.Log = logger.ListDrivers() <ide> <ide> return pluginsInfo <ide> } <ide><path>daemon/logger/factory.go <ide> package logger <ide> <ide> import ( <ide> "fmt" <add> "sort" <ide> "sync" <ide> <ide> containertypes "github.com/docker/docker/api/types/container" <ide> type logdriverFactory struct { <ide> m sync.Mutex <ide> } <ide> <add>func (lf *logdriverFactory) list() []string { <add> ls := make([]string, 0, len(lf.registry)) <add> lf.m.Lock() <add> for name := range lf.registry { <add> ls = append(ls, name) <add> } <add> lf.m.Unlock() <add> sort.Strings(ls) <add> return ls <add>} <add> <add>// ListDrivers gets the list of registered log driver names <add>func ListDrivers() []string { <add> return factory.list() <add>} <add> <ide> func (lf *logdriverFactory) register(name string, c Creator) error { <ide> if lf.driverRegistered(name) { <ide> return fmt.Errorf("logger: log driver named '%s' is already registered", name) <ide><path>integration-cli/docker_cli_plugins_logdriver_test.go <ide> package main <ide> <ide> import ( <add> "encoding/json" <add> "net/http" <ide> "strings" <ide> <add> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/integration-cli/checker" <add> "github.com/docker/docker/integration-cli/request" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func (s *DockerSuite) TestPluginLogDriver(c *check.C) { <ide> dockerCmd(c, "plugin", "disable", pluginName) <ide> dockerCmd(c, "plugin", "rm", pluginName) <ide> } <add> <add>// Make sure log drivers are listed in info, and v2 plugins are not. <add>func (s *DockerSuite) TestPluginLogDriverInfoList(c *check.C) { <add> testRequires(c, IsAmd64, DaemonIsLinux) <add> pluginName := "cpuguy83/docker-logdriver-test" <add> <add> dockerCmd(c, "plugin", "install", pluginName) <add> status, body, err := request.SockRequest("GET", "/info", nil, daemonHost()) <add> c.Assert(status, checker.Equals, http.StatusOK) <add> c.Assert(err, checker.IsNil) <add> <add> var info types.Info <add> err = json.Unmarshal(body, &info) <add> c.Assert(err, checker.IsNil) <add> drivers := strings.Join(info.Plugins.Log, " ") <add> c.Assert(drivers, checker.Contains, "json-file") <add> c.Assert(drivers, checker.Not(checker.Contains), pluginName) <add>}
6
Ruby
Ruby
use utils link_path_manpages
03352805c66c8f545fad59f7007f615a55d3e37b
<ide><path>Library/Homebrew/tap.rb <ide> def install(options = {}) <ide> end <ide> <ide> def link_manpages <del> return unless (path/"man").exist? <del> conflicts = [] <del> (path/"man").find do |src| <del> next if src.directory? <del> dst = HOMEBREW_PREFIX/"share"/src.relative_path_from(path) <del> next if dst.symlink? && src == dst.resolved_path <del> if dst.exist? <del> conflicts << dst <del> next <del> end <del> dst.make_relative_symlink(src) <del> end <del> unless conflicts.empty? <del> onoe <<-EOS.undent <del> Could not link #{name} manpages to: <del> #{conflicts.join("\n")} <del> <del> Please delete these files and run `brew tap --repair`. <del> EOS <del> end <add> link_path_manpages(path, "brew tap --repair") <ide> end <ide> <ide> # uninstall this {Tap}.
1
Javascript
Javascript
add a `pixelpositionformouseevent` method
e1ae3749c01240ef0668da63d78c796b6af22b89
<ide><path>src/text-editor-component.js <ide> class TextEditorComponent { <ide> if (scrolled) this.updateSync() <ide> } <ide> <del> screenPositionForMouseEvent ({clientX, clientY}) { <add> screenPositionForMouseEvent (event) { <add> return this.screenPositionForPixelPosition(this.pixelPositionForMouseEvent(event)) <add> } <add> <add> pixelPositionForMouseEvent ({clientX, clientY}) { <ide> const scrollContainerRect = this.refs.scrollContainer.getBoundingClientRect() <ide> clientX = Math.min(scrollContainerRect.right, Math.max(scrollContainerRect.left, clientX)) <ide> clientY = Math.min(scrollContainerRect.bottom, Math.max(scrollContainerRect.top, clientY)) <ide> const linesRect = this.refs.lineTiles.getBoundingClientRect() <del> return this.screenPositionForPixelPosition({ <add> return { <ide> top: clientY - linesRect.top, <ide> left: clientX - linesRect.left <del> }) <add> } <ide> } <ide> <ide> didUpdateSelections () {
1
Go
Go
fix race in `testapiswarmrestartcluster`
fdcde8bb65acf2c459e93678bf2659139ef5e918
<ide><path>integration-cli/docker_api_swarm_test.go <ide> func setGlobalMode(s *swarm.Service) { <ide> <ide> func checkClusterHealth(c *check.C, cl []*SwarmDaemon, managerCount, workerCount int) { <ide> var totalMCount, totalWCount int <add> <ide> for _, d := range cl { <del> info, err := d.info() <del> c.Assert(err, check.IsNil) <add> var ( <add> info swarm.Info <add> err error <add> ) <add> <add> // check info in a waitAndAssert, because if the cluster doesn't have a leader, `info` will return an error <add> checkInfo := func(c *check.C) (interface{}, check.CommentInterface) { <add> info, err = d.info() <add> return err, check.Commentf("cluster not ready in time") <add> } <add> waitAndAssert(c, defaultReconciliationTimeout, checkInfo, checker.IsNil) <ide> if !info.ControlAvailable { <ide> totalWCount++ <ide> continue <ide> } <add> <ide> var leaderFound bool <ide> totalMCount++ <ide> var mCount, wCount int <add> <ide> for _, n := range d.listNodes(c) { <del> c.Assert(n.Status.State, checker.Equals, swarm.NodeStateReady, check.Commentf("state of node %s, reported by %s", n.ID, d.Info.NodeID)) <del> c.Assert(n.Spec.Availability, checker.Equals, swarm.NodeAvailabilityActive, check.Commentf("availability of node %s, reported by %s", n.ID, d.Info.NodeID)) <add> waitReady := func(c *check.C) (interface{}, check.CommentInterface) { <add> if n.Status.State == swarm.NodeStateReady { <add> return true, nil <add> } <add> nn := d.getNode(c, n.ID) <add> n = *nn <add> return n.Status.State == swarm.NodeStateReady, check.Commentf("state of node %s, reported by %s", n.ID, d.Info.NodeID) <add> } <add> waitAndAssert(c, defaultReconciliationTimeout, waitReady, checker.True) <add> <add> waitActive := func(c *check.C) (interface{}, check.CommentInterface) { <add> if n.Spec.Availability == swarm.NodeAvailabilityActive { <add> return true, nil <add> } <add> nn := d.getNode(c, n.ID) <add> n = *nn <add> return n.Spec.Availability == swarm.NodeAvailabilityActive, check.Commentf("availability of node %s, reported by %s", n.ID, d.Info.NodeID) <add> } <add> waitAndAssert(c, defaultReconciliationTimeout, waitActive, checker.True) <add> <ide> if n.Spec.Role == swarm.NodeRoleManager { <ide> c.Assert(n.ManagerStatus, checker.NotNil, check.Commentf("manager status of node %s (manager), reported by %s", n.ID, d.Info.NodeID)) <ide> if n.ManagerStatus.Leader {
1
Javascript
Javascript
add typings for various library template plugins
ed9d0246d5186333435a225f473474352b9b406c
<ide><path>lib/AmdMainTemplatePlugin.js <ide> const { ConcatSource } = require("webpack-sources"); <ide> const Template = require("./Template"); <ide> <add>/** @typedef {import("./Compilation")} Compilation */ <add> <ide> class AmdMainTemplatePlugin { <add> /** <add> * @param {string} name the library name <add> */ <ide> constructor(name) { <add> /** @type {string} */ <ide> this.name = name; <ide> } <ide> <add> /** <add> * @param {Compilation} compilation the compilation instance <add> * @returns {void} <add> */ <ide> apply(compilation) { <ide> const { mainTemplate, chunkTemplate } = compilation; <ide> <ide><path>lib/ExportPropertyMainTemplatePlugin.js <ide> <ide> const { ConcatSource } = require("webpack-sources"); <ide> <add>/** @typedef {import("./Compilation")} Compilation */ <add> <add>/** <add> * @param {string[]} accessor the accessor to convert to path <add> * @returns {string} the path <add> */ <ide> const accessorToObjectAccess = accessor => { <ide> return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); <ide> }; <ide> <ide> class ExportPropertyMainTemplatePlugin { <add> /** <add> * @param {string|string[]} property the name of the property to export <add> */ <ide> constructor(property) { <ide> this.property = property; <ide> } <ide> <add> /** <add> * @param {Compilation} compilation the compilation instance <add> * @returns {void} <add> */ <ide> apply(compilation) { <ide> const { mainTemplate, chunkTemplate } = compilation; <ide> <ide><path>lib/LibraryTemplatePlugin.js <ide> <ide> const SetVarMainTemplatePlugin = require("./SetVarMainTemplatePlugin"); <ide> <add>/** @typedef {import("./Compiler")} Compiler */ <add> <add>/** <add> * @param {string[]} accessor the accessor to convert to path <add> * @returns {string} the path <add> */ <ide> const accessorToObjectAccess = accessor => { <del> return accessor <del> .map(a => { <del> return `[${JSON.stringify(a)}]`; <del> }) <del> .join(""); <add> return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); <ide> }; <ide> <del>const accessorAccess = (base, accessor, joinWith) => { <del> accessor = [].concat(accessor); <del> return accessor <del> .map((a, idx) => { <del> a = base <del> ? base + accessorToObjectAccess(accessor.slice(0, idx + 1)) <del> : accessor[0] + accessorToObjectAccess(accessor.slice(1, idx + 1)); <del> if (idx === accessor.length - 1) return a; <add>/** <add> * @param {string=} base the path prefix <add> * @param {string|string[]} accessor the accessor <add> * @param {string=} joinWith the element separator <add> * @returns {string} the path <add> */ <add>const accessorAccess = (base, accessor, joinWith = "; ") => { <add> const accessors = Array.isArray(accessor) ? accessor : [accessor]; <add> return accessors <add> .map((_, idx) => { <add> const a = base <add> ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) <add> : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); <add> if (idx === accessors.length - 1) return a; <ide> if (idx === 0 && typeof base === "undefined") <ide> return `${a} = typeof ${a} === "object" ? ${a} : {}`; <ide> return `${a} = ${a} || {}`; <ide> }) <del> .join(joinWith || "; "); <add> .join(joinWith); <ide> }; <ide> <ide> class LibraryTemplatePlugin { <add> /** <add> * @param {string} name name of library <add> * @param {string} target type of library <add> * @param {boolean} umdNamedDefine setting this to true will name the UMD module <add> * @param {string|TODO} auxiliaryComment comment in the UMD wrapper <add> * @param {string|string[]} exportProperty which export should be exposed as library <add> */ <ide> constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { <ide> this.name = name; <ide> this.target = target; <ide> class LibraryTemplatePlugin { <ide> this.exportProperty = exportProperty; <ide> } <ide> <add> /** <add> * @param {Compiler} compiler the compiler instance <add> * @returns {void} <add> */ <ide> apply(compiler) { <ide> compiler.hooks.thisCompilation.tap("LibraryTemplatePlugin", compilation => { <ide> if (this.exportProperty) { <del> var ExportPropertyMainTemplatePlugin = require("./ExportPropertyMainTemplatePlugin"); <add> const ExportPropertyMainTemplatePlugin = require("./ExportPropertyMainTemplatePlugin"); <ide> new ExportPropertyMainTemplatePlugin(this.exportProperty).apply( <ide> compilation <ide> ); <ide> } <ide> switch (this.target) { <ide> case "var": <ide> new SetVarMainTemplatePlugin( <del> `var ${accessorAccess(false, this.name)}` <add> `var ${accessorAccess(undefined, this.name)}`, <add> false <ide> ).apply(compilation); <ide> break; <ide> case "assign": <ide> new SetVarMainTemplatePlugin( <del> accessorAccess(undefined, this.name) <add> accessorAccess(undefined, this.name), <add> false <ide> ).apply(compilation); <ide> break; <ide> case "this": <ide> case "self": <ide> case "window": <del> if (this.name) <add> if (this.name) { <ide> new SetVarMainTemplatePlugin( <del> accessorAccess(this.target, this.name) <add> accessorAccess(this.target, this.name), <add> false <ide> ).apply(compilation); <del> else <add> } else { <ide> new SetVarMainTemplatePlugin(this.target, true).apply(compilation); <add> } <ide> break; <ide> case "global": <del> if (this.name) <add> if (this.name) { <ide> new SetVarMainTemplatePlugin( <ide> accessorAccess( <ide> compilation.runtimeTemplate.outputOptions.globalObject, <ide> this.name <del> ) <add> ), <add> false <ide> ).apply(compilation); <del> else <add> } else { <ide> new SetVarMainTemplatePlugin( <ide> compilation.runtimeTemplate.outputOptions.globalObject, <ide> true <ide> ).apply(compilation); <add> } <ide> break; <ide> case "commonjs": <del> if (this.name) <add> if (this.name) { <ide> new SetVarMainTemplatePlugin( <del> accessorAccess("exports", this.name) <add> accessorAccess("exports", this.name), <add> false <ide> ).apply(compilation); <del> else new SetVarMainTemplatePlugin("exports", true).apply(compilation); <add> } else { <add> new SetVarMainTemplatePlugin("exports", true).apply(compilation); <add> } <ide> break; <ide> case "commonjs2": <ide> case "commonjs-module": <del> new SetVarMainTemplatePlugin("module.exports").apply(compilation); <add> new SetVarMainTemplatePlugin("module.exports", false).apply( <add> compilation <add> ); <ide> break; <del> case "amd": <del> var AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin"); <add> case "amd": { <add> const AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin"); <ide> new AmdMainTemplatePlugin(this.name).apply(compilation); <ide> break; <add> } <ide> case "umd": <del> case "umd2": <del> var UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin"); <add> case "umd2": { <add> const UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin"); <ide> new UmdMainTemplatePlugin(this.name, { <ide> optionalAmdExternalAsGlobal: this.target === "umd2", <ide> namedDefine: this.umdNamedDefine, <ide> auxiliaryComment: this.auxiliaryComment <ide> }).apply(compilation); <ide> break; <del> case "jsonp": <del> var JsonpExportMainTemplatePlugin = require("./web/JsonpExportMainTemplatePlugin"); <add> } <add> case "jsonp": { <add> const JsonpExportMainTemplatePlugin = require("./web/JsonpExportMainTemplatePlugin"); <ide> new JsonpExportMainTemplatePlugin(this.name).apply(compilation); <ide> break; <add> } <ide> default: <ide> throw new Error(`${this.target} is not a valid Library target`); <ide> } <ide><path>lib/SetVarMainTemplatePlugin.js <ide> <ide> const { ConcatSource } = require("webpack-sources"); <ide> <add>/** @typedef {import("./Compilation")} Compilation */ <add> <ide> class SetVarMainTemplatePlugin { <add> /** <add> * @param {string} varExpression the accessor where the library is exported <add> * @param {boolean} copyObject specify copying the exports <add> */ <ide> constructor(varExpression, copyObject) { <add> /** @type {string} */ <ide> this.varExpression = varExpression; <add> /** @type {boolean} */ <ide> this.copyObject = copyObject; <ide> } <ide> <add> /** <add> * @param {Compilation} compilation the compilation instance <add> * @returns {void} <add> */ <ide> apply(compilation) { <ide> const { mainTemplate, chunkTemplate } = compilation; <ide> <ide><path>lib/UmdMainTemplatePlugin.js <ide> const { ConcatSource, OriginalSource } = require("webpack-sources"); <ide> const Template = require("./Template"); <ide> <del>function accessorToObjectAccess(accessor) { <add>/** @typedef {import("./Compilation")} Compilation */ <add> <add>/** <add> * @param {string[]} accessor the accessor to convert to path <add> * @returns {string} the path <add> */ <add>const accessorToObjectAccess = accessor => { <ide> return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); <del>} <add>}; <ide> <del>function accessorAccess(base, accessor) { <del> accessor = [].concat(accessor); <del> return accessor <del> .map((a, idx) => { <del> a = base + accessorToObjectAccess(accessor.slice(0, idx + 1)); <del> if (idx === accessor.length - 1) return a; <add>/** <add> * @param {string=} base the path prefix <add> * @param {string|string[]} accessor the accessor <add> * @param {string=} joinWith the element separator <add> * @returns {string} the path <add> */ <add>const accessorAccess = (base, accessor, joinWith = "; ") => { <add> const accessors = Array.isArray(accessor) ? accessor : [accessor]; <add> return accessors <add> .map((_, idx) => { <add> const a = base <add> ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) <add> : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); <add> if (idx === accessors.length - 1) return a; <add> if (idx === 0 && typeof base === "undefined") <add> return `${a} = typeof ${a} === "object" ? ${a} : {}`; <ide> return `${a} = ${a} || {}`; <ide> }) <del> .join(", "); <del>} <add> .join(joinWith); <add>}; <add> <add>/** <add> * @typedef {string | string[] | {[k: string]: string | string[]}} UmdMainTemplatePluginName <add> * @typedef {{optionalAmdExternalAsGlobal: boolean, namedDefine: boolean, auxiliaryComment: TODO}} UmdMainTemplatePluginOption <add> */ <ide> <ide> class UmdMainTemplatePlugin { <add> /** <add> * @param {UmdMainTemplatePluginName} name the name of the UMD library <add> * @param {UmdMainTemplatePluginOption} options the plugin option <add> */ <ide> constructor(name, options) { <ide> if (typeof name === "object" && !Array.isArray(name)) { <ide> this.name = name.root || name.amd || name.commonjs; <ide> class UmdMainTemplatePlugin { <ide> this.auxiliaryComment = options.auxiliaryComment; <ide> } <ide> <add> /** <add> * @param {Compilation} compilation the compilation instance <add> * @returns {void} <add> */ <ide> apply(compilation) { <ide> const { mainTemplate, chunkTemplate, runtimeTemplate } = compilation; <ide>
5
Go
Go
fix testbuildwithtabs for go 1.4
a31c14cadca4052a0a141347b322d825f56b814b
<ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildWithTabs(t *testing.T) { <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> expected := "[\"/bin/sh\",\"-c\",\"echo\\u0009one\\u0009\\u0009two\"]" <add> expected := `["/bin/sh","-c","echo\tone\t\ttwo"]` <ide> if res != expected { <ide> t.Fatalf("Missing tabs.\nGot:%s\nExp:%s", res, expected) <ide> }
1
Text
Text
add a condition for garbage collection eligibility
6d115ae515bd2b6aaf144b4f3c5545b35d769af6
<ide><path>guide/english/java/garbage-collection/index.md <ide> Java relieves the programmer from memory management task and itself reclaims the <ide> n = null; //the Integer object is no longer accessible <ide> ``` <ide> * Cyclic dependencies are not counted as reference so if Object X has reference of Object Y and Object Y has reference of Object X and they don’t have any other live reference then both Objects X and Y will be eligible for Garbage Collection. <add>* An object is also eligible for garbage collection when its reference variable is re-assigned and that object no longer has any other reference to it. Look at the code snippet below: <add>```java <add>Integer i1 = new Integer(10); //new Integer object created <add>Integer i2 = new Integer(20); //Another new Integer object created <add>i1 = i2;//i1 now references to i2 (re-assigned), therefore 10 (object in the heap) becomes eligible for garbage collection since it no longer has any other reference to it <add>``` <ide> <ide> ## How to manually make an object eligible for Garbage Collection? <ide> * Even though it is not the task of the programmer to destroy the objects, it is a good programming practice to make an object unreachable(thus eligible for GC) after it is used.
1
Javascript
Javascript
add benchmark script for resourceusage
56b25e7a6f741c8181c55f3d40d0cab6ffa1eb4d
<ide><path>benchmark/process/resourceUsage.js <add>'use strict'; <add> <add>const common = require('../common.js'); <add>const bench = common.createBenchmark(main, { <add> n: [1e5] <add>}); <add> <add>function main({ n }) { <add> bench.start(); <add> for (let i = 0; i < n; i++) { <add> process.resourceUsage(); <add> } <add> bench.end(n); <add>}
1
PHP
PHP
remove useless imports
252c2cc648035a16e545147542d5b62ef58ca6f4
<ide><path>tests/Filesystem/FilesystemTest.php <ide> use Illuminate\Filesystem\Filesystem; <ide> use Illuminate\Filesystem\FilesystemManager; <ide> use Illuminate\Foundation\Application; <del>use League\Flysystem\Adapter\Ftp; <ide> use Mockery as m; <ide> use PHPUnit\Framework\TestCase; <ide> use SplFileInfo; <ide><path>tests/Http/HttpClientTest.php <ide> namespace Illuminate\Tests\Http; <ide> <ide> use Illuminate\Http\Client\Factory; <del>use Illuminate\Http\Client\PendingRequest; <ide> use Illuminate\Http\Client\Request; <ide> use Illuminate\Support\Str; <ide> use OutOfBoundsException;
2
Python
Python
add sol3 for project_euler problem_03
ad2db80f8aeba7fe407eccd69327cfb3bdfaacd2
<ide><path>project_euler/problem_03/sol3.py <add>""" <add>Problem: <add>The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor <add>of a given number N? <add> <add>e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. <add>""" <add> <add> <add>def solution(n: int) -> int: <add> """Returns the largest prime factor of a given number n. <add> <add> >>> solution(13195) <add> 29 <add> >>> solution(10) <add> 5 <add> >>> solution(17) <add> 17 <add> >>> solution(3.4) <add> 3 <add> >>> solution(0) <add> Traceback (most recent call last): <add> ... <add> ValueError: Parameter n must be greater or equal to one. <add> >>> solution(-17) <add> Traceback (most recent call last): <add> ... <add> ValueError: Parameter n must be greater or equal to one. <add> >>> solution([]) <add> Traceback (most recent call last): <add> ... <add> TypeError: Parameter n must be int or passive of cast to int. <add> >>> solution("asd") <add> Traceback (most recent call last): <add> ... <add> TypeError: Parameter n must be int or passive of cast to int. <add> """ <add> try: <add> n = int(n) <add> except (TypeError, ValueError): <add> raise TypeError("Parameter n must be int or passive of cast to int.") <add> if n <= 0: <add> raise ValueError("Parameter n must be greater or equal to one.") <add> i = 2 <add> ans = 0 <add> if n == 2: <add> return 2 <add> while n > 2: <add> while n % i != 0: <add> i += 1 <add> ans = i <add> while n % i == 0: <add> n = n / i <add> i += 1 <add> <add> return int(ans) <add> <add> <add>if __name__ == "__main__": <add> # print(solution(int(input().strip()))) <add> import doctest <add> <add> doctest.testmod()
1
Text
Text
add article for javascript string.search()
306c53187f2b86cb19ff6a037bac4e0e629e5b4c
<ide><path>guide/english/javascript/standard-objects/string/string-prototype-search/index.md <ide> title: String.prototype.search <ide> --- <ide> ## String.prototype.search <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/string/string-prototype-search/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>The `search()` method searches for a match between a regular expression and the given String object. If a match is found, `search()` returns the index of the first match; if not found, `search()` returns -1. <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add>**Syntax** <add>```javascript <add>str.search(regexp) // regexp is a RegExp object <add>``` <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <del> <del>#### More Information: <del><!-- Please add any articles you think might be helpful to read before writing the article --> <add>**Example** <add>```js <add>var x = "Hello World"; <add>var pattern1 = /[A-H][a-e]/; // first character between 'A' and 'H', second between 'a' and 'e' <add>var pattern2 = "world"; // the string 'world' <add>console.log(x.search(pattern1)); // 0 <add>console.log(x.search(pattern2)); // -1 <add>console.log(x.search("o")); // 4 <add>``` <ide> <add>*Note*: `search()` implicitly converts a string argument to a RegExp object; in the example above, the string `world` in `pattern2` is converted to the regular expression `world` (and similarly for the string `o`). <ide> <add>#### More Information: <add>- [String.prototype.search() on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search)
1
Javascript
Javascript
fix touchablehighlight w/o `onlongpress`
bdf3c7911007f547101d753903da11ea4ee095f9
<ide><path>Libraries/Components/Touchable/TouchableBounce.js <ide> class TouchableBounce extends React.Component<Props, State> { <ide> this.props.onFocus(event); <ide> } <ide> }, <del> onLongPress: event => { <del> if (this.props.onLongPress != null) { <del> this.props.onLongPress(event); <del> } <del> }, <add> onLongPress: this.props.onLongPress, <ide> onPress: event => { <ide> const {onPressAnimationComplete, onPressWithCompletion} = this.props; <ide> const releaseBounciness = this.props.releaseBounciness ?? 10; <ide><path>Libraries/Components/Touchable/TouchableHighlight.js <ide> class TouchableHighlight extends React.Component<Props, State> { <ide> this.props.onFocus(event); <ide> } <ide> }, <del> onLongPress: event => { <del> if (this.props.onLongPress != null) { <del> this.props.onLongPress(event); <del> } <del> }, <add> onLongPress: this.props.onLongPress, <ide> onPress: event => { <ide> if (this._hideTimeout != null) { <ide> clearTimeout(this._hideTimeout);
2
Mixed
Javascript
remove setupbabel call from main entry point
17e0478cf4157e2067baf7437e3a81756744221a
<ide><path>local-cli/dependencies/dependencies.js <ide> */ <ide> 'use strict'; <ide> <del>const ReactPackager = require('../../packager/react-packager'); <add>require('../../setupBabel')(); <add>const ReactPackager = require('../../packager'); <ide> <ide> const denodeify = require('denodeify'); <ide> const fs = require('fs'); <ide><path>local-cli/server/runServer.js <ide> <ide> 'use strict'; <ide> <add>require('../../setupBabel')(); <ide> const InspectorProxy = require('./util/inspectorProxy.js'); <del>const ReactPackager = require('../../packager/react-packager'); <add>const ReactPackager = require('../../packager'); <ide> <ide> const attachHMRServer = require('./util/attachHMRServer'); <ide> const connect = require('connect'); <ide><path>packager/README.md <ide> The packager is made of two things: <ide> ReactPackager is how you mainly interact with the API. <ide> <ide> ```js <del>var ReactPackager = require('./react-packager'); <add>var ReactPackager = require('path/to/packager/'); <ide> ``` <ide> <ide> ### ReactPackager.buildBundle(serverOptions, bundleOptions) <ide><path>packager/index.js <ide> <ide> 'use strict'; <ide> <del>require('../setupBabel')(); <del>module.exports = require('./react-packager'); <add>const Logger = require('./src/Logger'); <add> <add>const debug = require('debug'); <add>const invariant = require('fbjs/lib/invariant'); <add> <add>import type {PostProcessModules, PostMinifyProcess} from './src/Bundler'; <add>import type Server from './src/Server'; <add>import type {GlobalTransformCache} from './src/lib/GlobalTransformCache'; <add>import type {Reporter} from './src/lib/reporting'; <add>import type {HasteImpl} from './src/node-haste/Module'; <add> <add>exports.createServer = createServer; <add>exports.Logger = Logger; <add> <add>type Options = { <add> hasteImpl?: HasteImpl, <add> globalTransformCache: ?GlobalTransformCache, <add> nonPersistent?: boolean, <add> postProcessModules?: PostProcessModules, <add> postMinifyProcess?: PostMinifyProcess, <add> projectRoots: $ReadOnlyArray<string>, <add> reporter?: Reporter, <add> +sourceExts: ?Array<string>, <add> +transformModulePath: string, <add> watch?: boolean, <add>}; <add> <add>type StrictOptions = {...Options, reporter: Reporter}; <add> <add>type PublicBundleOptions = { <add> +dev?: boolean, <add> +entryFile: string, <add> +generateSourceMaps?: boolean, <add> +inlineSourceMap?: boolean, <add> +minify?: boolean, <add> +platform?: string, <add> +runModule?: boolean, <add> +sourceMapUrl?: string, <add>}; <add> <add>/** <add> * This is a public API, so we don't trust the value and purposefully downgrade <add> * it as `mixed`. Because it understands `invariant`, Flow ensure that we <add> * refine these values completely. <add> */ <add>function assertPublicBundleOptions(bo: mixed): PublicBundleOptions { <add> invariant(typeof bo === 'object' && bo != null, 'bundle options must be an object'); <add> invariant(bo.dev === undefined || typeof bo.dev === 'boolean', 'bundle options field `dev` must be a boolean'); <add> const {entryFile} = bo; <add> invariant(typeof entryFile === 'string', 'bundle options must contain a string field `entryFile`'); <add> invariant(bo.generateSourceMaps === undefined || typeof bo.generateSourceMaps === 'boolean', 'bundle options field `generateSourceMaps` must be a boolean'); <add> invariant(bo.inlineSourceMap === undefined || typeof bo.inlineSourceMap === 'boolean', 'bundle options field `inlineSourceMap` must be a boolean'); <add> invariant(bo.minify === undefined || typeof bo.minify === 'boolean', 'bundle options field `minify` must be a boolean'); <add> invariant(bo.platform === undefined || typeof bo.platform === 'string', 'bundle options field `platform` must be a string'); <add> invariant(bo.runModule === undefined || typeof bo.runModule === 'boolean', 'bundle options field `runModule` must be a boolean'); <add> invariant(bo.sourceMapUrl === undefined || typeof bo.sourceMapUrl === 'string', 'bundle options field `sourceMapUrl` must be a boolean'); <add> return {entryFile, ...bo}; <add>} <add> <add>exports.buildBundle = function(options: Options, bundleOptions: PublicBundleOptions) { <add> var server = createNonPersistentServer(options); <add> const ServerClass = require('./src/Server'); <add> return server.buildBundle({ <add> ...ServerClass.DEFAULT_BUNDLE_OPTIONS, <add> ...assertPublicBundleOptions(bundleOptions), <add> }).then(p => { <add> server.end(); <add> return p; <add> }); <add>}; <add> <add>exports.getOrderedDependencyPaths = function(options: Options, depOptions: { <add> +entryFile: string, <add> +dev: boolean, <add> +platform: string, <add>}) { <add> var server = createNonPersistentServer(options); <add> return server.getOrderedDependencyPaths(depOptions) <add> .then(function(paths) { <add> server.end(); <add> return paths; <add> }); <add>}; <add> <add>function enableDebug() { <add> // react-packager logs debug messages using the 'debug' npm package, and uses <add> // the following prefix throughout. <add> // To enable debugging, we need to set our pattern or append it to any <add> // existing pre-configured pattern to avoid disabling logging for <add> // other packages <add> var debugPattern = 'RNP:*'; <add> var existingPattern = debug.load(); <add> if (existingPattern) { <add> debugPattern += ',' + existingPattern; <add> } <add> debug.enable(debugPattern); <add>} <add> <add>function createServer(options: StrictOptions): Server { <add> // the debug module is configured globally, we need to enable debugging <add> // *before* requiring any packages that use `debug` for logging <add> if (options.verbose) { <add> enableDebug(); <add> } <add> <add> // Some callsites may not be Flowified yet. <add> invariant(options.reporter != null, 'createServer() requires reporter'); <add> const serverOptions = Object.assign({}, options); <add> delete serverOptions.verbose; <add> const ServerClass = require('./src/Server'); <add> return new ServerClass(serverOptions); <add>} <add> <add>function createNonPersistentServer(options: Options): Server { <add> const serverOptions = { <add> // It's unsound to set-up the reporter here, <add> // but this allows backward compatibility. <add> reporter: options.reporter == null <add> ? require('./src/lib/reporting').nullReporter <add> : options.reporter, <add> ...options, <add> watch: !options.nonPersistent, <add> }; <add> return createServer(serverOptions); <add>} <ide><path>packager/react-packager.js <del>/** <del> * Copyright (c) 2015-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> * <del> * @flow <del> */ <del> <del>'use strict'; <del> <del>const Logger = require('./src/Logger'); <del> <del>const debug = require('debug'); <del>const invariant = require('fbjs/lib/invariant'); <del> <del>import type {PostProcessModules, PostMinifyProcess} from './src/Bundler'; <del>import type Server from './src/Server'; <del>import type {GlobalTransformCache} from './src/lib/GlobalTransformCache'; <del>import type {Reporter} from './src/lib/reporting'; <del>import type {HasteImpl} from './src/node-haste/Module'; <del> <del>exports.createServer = createServer; <del>exports.Logger = Logger; <del> <del>type Options = { <del> hasteImpl?: HasteImpl, <del> globalTransformCache: ?GlobalTransformCache, <del> nonPersistent?: boolean, <del> postProcessModules?: PostProcessModules, <del> postMinifyProcess?: PostMinifyProcess, <del> projectRoots: $ReadOnlyArray<string>, <del> reporter?: Reporter, <del> +sourceExts: ?Array<string>, <del> +transformModulePath: string, <del> watch?: boolean, <del>}; <del> <del>type StrictOptions = {...Options, reporter: Reporter}; <del> <del>type PublicBundleOptions = { <del> +dev?: boolean, <del> +entryFile: string, <del> +generateSourceMaps?: boolean, <del> +inlineSourceMap?: boolean, <del> +minify?: boolean, <del> +platform?: string, <del> +runModule?: boolean, <del> +sourceMapUrl?: string, <del>}; <del> <del>/** <del> * This is a public API, so we don't trust the value and purposefully downgrade <del> * it as `mixed`. Because it understands `invariant`, Flow ensure that we <del> * refine these values completely. <del> */ <del>function assertPublicBundleOptions(bo: mixed): PublicBundleOptions { <del> invariant(typeof bo === 'object' && bo != null, 'bundle options must be an object'); <del> invariant(bo.dev === undefined || typeof bo.dev === 'boolean', 'bundle options field `dev` must be a boolean'); <del> const {entryFile} = bo; <del> invariant(typeof entryFile === 'string', 'bundle options must contain a string field `entryFile`'); <del> invariant(bo.generateSourceMaps === undefined || typeof bo.generateSourceMaps === 'boolean', 'bundle options field `generateSourceMaps` must be a boolean'); <del> invariant(bo.inlineSourceMap === undefined || typeof bo.inlineSourceMap === 'boolean', 'bundle options field `inlineSourceMap` must be a boolean'); <del> invariant(bo.minify === undefined || typeof bo.minify === 'boolean', 'bundle options field `minify` must be a boolean'); <del> invariant(bo.platform === undefined || typeof bo.platform === 'string', 'bundle options field `platform` must be a string'); <del> invariant(bo.runModule === undefined || typeof bo.runModule === 'boolean', 'bundle options field `runModule` must be a boolean'); <del> invariant(bo.sourceMapUrl === undefined || typeof bo.sourceMapUrl === 'string', 'bundle options field `sourceMapUrl` must be a boolean'); <del> return {entryFile, ...bo}; <del>} <del> <del>exports.buildBundle = function(options: Options, bundleOptions: PublicBundleOptions) { <del> var server = createNonPersistentServer(options); <del> const ServerClass = require('./src/Server'); <del> return server.buildBundle({ <del> ...ServerClass.DEFAULT_BUNDLE_OPTIONS, <del> ...assertPublicBundleOptions(bundleOptions), <del> }).then(p => { <del> server.end(); <del> return p; <del> }); <del>}; <del> <del>exports.getOrderedDependencyPaths = function(options: Options, depOptions: { <del> +entryFile: string, <del> +dev: boolean, <del> +platform: string, <del>}) { <del> var server = createNonPersistentServer(options); <del> return server.getOrderedDependencyPaths(depOptions) <del> .then(function(paths) { <del> server.end(); <del> return paths; <del> }); <del>}; <del> <del>function enableDebug() { <del> // react-packager logs debug messages using the 'debug' npm package, and uses <del> // the following prefix throughout. <del> // To enable debugging, we need to set our pattern or append it to any <del> // existing pre-configured pattern to avoid disabling logging for <del> // other packages <del> var debugPattern = 'RNP:*'; <del> var existingPattern = debug.load(); <del> if (existingPattern) { <del> debugPattern += ',' + existingPattern; <del> } <del> debug.enable(debugPattern); <del>} <del> <del>function createServer(options: StrictOptions): Server { <del> // the debug module is configured globally, we need to enable debugging <del> // *before* requiring any packages that use `debug` for logging <del> if (options.verbose) { <del> enableDebug(); <del> } <del> <del> // Some callsites may not be Flowified yet. <del> invariant(options.reporter != null, 'createServer() requires reporter'); <del> const serverOptions = Object.assign({}, options); <del> delete serverOptions.verbose; <del> const ServerClass = require('./src/Server'); <del> return new ServerClass(serverOptions); <del>} <del> <del>function createNonPersistentServer(options: Options): Server { <del> const serverOptions = { <del> // It's unsound to set-up the reporter here, <del> // but this allows backward compatibility. <del> reporter: options.reporter == null <del> ? require('./src/lib/reporting').nullReporter <del> : options.reporter, <del> ...options, <del> watch: !options.nonPersistent, <del> }; <del> return createServer(serverOptions); <del>} <ide><path>setupBabel.js <ide> const escapeRegExp = require('lodash/escapeRegExp'); <ide> const path = require('path'); <ide> <ide> const BABEL_ENABLED_PATHS = [ <del> 'packager/react-packager.js', <add> 'packager/index.js', <ide> 'packager/src', <ide> 'packager/transformer.js', <ide> 'local-cli',
6
Text
Text
add heterogeneous enum, and description
2023d2bab5911e487d1281a81ab07eebddbbb0ba
<ide><path>client/src/guide/english/typescript/enums/index.md <ide> enum StringBasedEnum { <ide> Programming = "is fun", <ide> Pizza = "is good" <ide> } <add> <add>// Heterogeneous based enum <add>enum HeterogeneousBasedEnum { <add> Day = 2, <add> Pizza = "is good" <add>} <add> <add> <ide> ``` <add> <add>Like Constants Enums are ready only. its imperative to understand that the benefit of using an Enum vs a Constant is it allow developers to organize collections of related values.
1
Go
Go
add mechanism to skip tests
bc37c036b568f9ae27a7aa457ec73d0c5c6a61cf
<ide><path>integration-cli/docker_cli_links_test.go <ide> func TestLinksEtcHostsRegularFile(t *testing.T) { <ide> } <ide> <ide> func TestLinksEtcHostsContentMatch(t *testing.T) { <add> testRequires(t, SameHostDaemon) <add> <ide> runCmd := exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hosts") <ide> out, _, _, err := runCommandWithStdoutStderr(runCmd) <ide> if err != nil { <ide> func TestLinksPingLinkedContainersAfterRename(t *testing.T) { <ide> } <ide> <ide> func TestLinksIpTablesRulesWhenLinkAndUnlink(t *testing.T) { <add> testRequires(t, SameHostDaemon) <add> <ide> dockerCmd(t, "run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "sleep", "10") <ide> dockerCmd(t, "run", "-d", "--name", "parent", "--link", "child:http", "busybox", "sleep", "10") <ide> <ide> func TestLinksNotStartedParentNotFail(t *testing.T) { <ide> } <ide> <ide> func TestLinksHostsFilesInject(t *testing.T) { <add> testRequires(t, SameHostDaemon) <add> <ide> defer deleteAllContainers() <ide> <ide> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-itd", "--name", "one", "busybox", "top")) <ide> func TestLinksNetworkHostContainer(t *testing.T) { <ide> } <ide> <ide> func TestLinksUpdateOnRestart(t *testing.T) { <add> testRequires(t, SameHostDaemon) <add> <ide> defer deleteAllContainers() <ide> <ide> if out, err := exec.Command(dockerBinary, "run", "-d", "--name", "one", "busybox", "top").CombinedOutput(); err != nil { <ide><path>integration-cli/docker_cli_nat_test.go <ide> import ( <ide> ) <ide> <ide> func TestNetworkNat(t *testing.T) { <add> testRequires(t, SameHostDaemon) <add> <ide> iface, err := net.InterfaceByName("eth0") <ide> if err != nil { <ide> t.Skipf("Test not running with `make test`. Interface eth0 not found: %s", err) <ide><path>integration-cli/docker_test_vars_cli.go <add>// +build !daemon <add> <add>package main <add> <add>const ( <add> // tests should not assume daemon runs on the same machine as CLI <add> isLocalDaemon = false <add>) <ide><path>integration-cli/docker_test_vars_daemon.go <add>// +build daemon <add> <add>package main <add> <add>const ( <add> // tests can assume daemon runs on the same machine as CLI <add> isLocalDaemon = true <add>) <ide><path>integration-cli/requirements.go <add>package main <add> <add>import ( <add> "testing" <add>) <add> <add>type TestCondition func() bool <add> <add>type TestRequirement struct { <add> Condition TestCondition <add> SkipMessage string <add>} <add> <add>// List test requirements <add>var ( <add> SameHostDaemon = TestRequirement{ <add> func() bool { return isLocalDaemon }, <add> "Test requires docker daemon to runs on the same machine as CLI", <add> } <add>) <add> <add>// testRequires checks if the environment satisfies the requirements <add>// for the test to run or skips the tests. <add>func testRequires(t *testing.T, requirements ...TestRequirement) { <add> for _, r := range requirements { <add> if !r.Condition() { <add> t.Skip(r.SkipMessage) <add> } <add> } <add>}
5
Javascript
Javascript
remove unused file from chromium extension
fa965269ea98e32b2c9497cf185f85a3a32f0c88
<ide><path>extensions/chromium/patch-worker.js <del>/* <del>Copyright 2013 Rob Wu <gwnRob@gmail.com> <del>Licensed under the Apache License, Version 2.0 (the "License"); <del>you may not use this file except in compliance with the License. <del>You may obtain a copy of the License at <del> <del> http://www.apache.org/licenses/LICENSE-2.0 <del> <del>Unless required by applicable law or agreed to in writing, software <del>distributed under the License is distributed on an "AS IS" BASIS, <del>WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del>See the License for the specific language governing permissions and <del>limitations under the License. <del>*/ <del>// Target: Chrome 20+ <del> <del>// W3-compliant Worker proxy. <del>// This module replaces the global Worker object. <del>// When invoked, the default Worker object is called. <del>// If this call fails with SECURITY_ERR, the script is fetched <del>// using async XHR, and transparently proxies all calls and <del>// setters/getters to the new Worker object. <del>// Note: This script does not magically circumvent the Same origin policy. <del> <del>(function() { <del> 'use strict'; <del> var Worker_ = window.Worker; <del> var URL = window.URL || window.webkitURL; <del> // Create dummy worker for the following purposes: <del> // 1. Don't override the global Worker object if the fallback isn't <del> // going to work (future API changes?) <del> // 2. Use it to trigger early validation of postMessage calls <del> // Note: Blob constructor is supported since Chrome 20, but since <del> // some of the used Chrome APIs are only supported as of Chrome 20, <del> // I don't bother adding a BlobBuilder fallback. <del> var dummyWorker = new Worker_( <del> URL.createObjectURL(new Blob([], {type: 'text/javascript'}))); <del> window.Worker = function Worker(scriptURL) { <del> if (arguments.length === 0) { <del> throw new TypeError('Not enough arguments'); <del> } <del> try { <del> return new Worker_(scriptURL); <del> } catch (e) { <del> if (e.code === 18/*DOMException.SECURITY_ERR*/) { <del> return new WorkerXHR(scriptURL); <del> } else { <del> throw e; <del> } <del> } <del> }; <del> // Bind events and replay queued messages <del> function bindWorker(worker, workerURL) { <del> if (worker._terminated) { <del> return; <del> } <del> worker.Worker = new Worker_(workerURL); <del> worker.Worker.onerror = worker._onerror; <del> worker.Worker.onmessage = worker._onmessage; <del> var o; <del> while ( (o = worker._replayQueue.shift()) ) { <del> worker.Worker[o.method].apply(worker.Worker, o.arguments); <del> } <del> while ( (o = worker._messageQueue.shift()) ) { <del> worker.Worker.postMessage.apply(worker.Worker, o); <del> } <del> } <del> function WorkerXHR(scriptURL) { <del> var worker = this; <del> var x = new XMLHttpRequest(); <del> x.responseType = 'blob'; <del> x.onload = function() { <del> // http://stackoverflow.com/a/10372280/938089 <del> var workerURL = URL.createObjectURL(x.response); <del> bindWorker(worker, workerURL); <del> }; <del> x.open('GET', scriptURL); <del> x.send(); <del> worker._replayQueue = []; <del> worker._messageQueue = []; <del> } <del> WorkerXHR.prototype = { <del> constructor: Worker_, <del> terminate: function() { <del> if (!this._terminated) { <del> this._terminated = true; <del> if (this.Worker) <del> this.Worker.terminate(); <del> } <del> }, <del> postMessage: function(message, transfer) { <del> if (!(this instanceof WorkerXHR)) <del> throw new TypeError('Illegal invocation'); <del> if (this.Worker) { <del> this.Worker.postMessage.apply(this.Worker, arguments); <del> } else { <del> // Trigger validation: <del> dummyWorker.postMessage(message); <del> // Alright, push the valid message to the queue. <del> this._messageQueue.push(arguments); <del> } <del> } <del> }; <del> // Implement the EventTarget interface <del> [ <del> 'addEventListener', <del> 'removeEventListener', <del> 'dispatchEvent' <del> ].forEach(function(method) { <del> WorkerXHR.prototype[method] = function() { <del> if (!(this instanceof WorkerXHR)) { <del> throw new TypeError('Illegal invocation'); <del> } <del> if (this.Worker) { <del> this.Worker[method].apply(this.Worker, arguments); <del> } else { <del> this._replayQueue.push({method: method, arguments: arguments}); <del> } <del> }; <del> }); <del> Object.defineProperties(WorkerXHR.prototype, { <del> onmessage: { <del> get: function() {return this._onmessage || null;}, <del> set: function(func) { <del> this._onmessage = typeof func === 'function' ? func : null; <del> } <del> }, <del> onerror: { <del> get: function() {return this._onerror || null;}, <del> set: function(func) { <del> this._onerror = typeof func === 'function' ? func : null; <del> } <del> } <del> }); <del>})();
1
Javascript
Javascript
remove focused test
e82ee6ca377a9081f1a3ffa0f042d8a28a92c62d
<ide><path>spec/squirrel-update-spec.js <ide> const createFakeApp = function() { <ide> <ide> const AtomTestAppName = 'Atom Testing' <ide> <del>fdescribe("Windows Squirrel Update", function() { <add>describe("Windows Squirrel Update", function() { <ide> let tempHomeDirectory = null; <ide> <ide> beforeEach(function() {
1
Java
Java
add defaultusewrapper support to jackson builder
7b861c9a8aeda83ef6844633901d6f00ea28c4c0
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java <ide> import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; <ide> import com.fasterxml.jackson.databind.module.SimpleModule; <ide> import com.fasterxml.jackson.databind.ser.FilterProvider; <add>import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; <add>import com.fasterxml.jackson.dataformat.xml.XmlFactory; <ide> import com.fasterxml.jackson.dataformat.xml.XmlMapper; <ide> <ide> import org.springframework.beans.BeanUtils; <ide> public class Jackson2ObjectMapperBuilder { <ide> <ide> private ApplicationContext applicationContext; <ide> <add> private Boolean defaultUseWrapper; <add> <ide> <ide> /** <ide> * If set to {@code true}, an {@link XmlMapper} will be created using its <ide> public Jackson2ObjectMapperBuilder indentOutput(boolean indentOutput) { <ide> return this; <ide> } <ide> <add> /** <add> * Define if a wrapper will be used for indexed (List, array) properties or not by <add> * default (only applies to {@link XmlMapper}). <add> * @since 4.3 <add> */ <add> public Jackson2ObjectMapperBuilder defaultUseWrapper(boolean defaultUseWrapper) { <add> this.defaultUseWrapper = defaultUseWrapper; <add> return this; <add> } <add> <ide> /** <ide> * Specify features to enable. <ide> * @see com.fasterxml.jackson.core.JsonParser.Feature <ide> public Jackson2ObjectMapperBuilder applicationContext(ApplicationContext applica <ide> public <T extends ObjectMapper> T build() { <ide> ObjectMapper mapper; <ide> if (this.createXmlMapper) { <del> mapper = new XmlObjectMapperInitializer().create(); <add> mapper = (this.defaultUseWrapper == null ? new XmlObjectMapperInitializer().create() <add> : new XmlObjectMapperInitializer().create(this.defaultUseWrapper)); <ide> } <ide> else { <ide> mapper = new ObjectMapper(); <ide> public static Jackson2ObjectMapperBuilder xml() { <ide> private static class XmlObjectMapperInitializer { <ide> <ide> public ObjectMapper create() { <add> return new XmlMapper(xmlInputFactory()); <add> } <add> <add> public ObjectMapper create(boolean defaultUseWrapper) { <add> JacksonXmlModule module = new JacksonXmlModule(); <add> module.setDefaultUseWrapper(defaultUseWrapper); <add> return new XmlMapper(new XmlFactory(xmlInputFactory()), module); <add> } <add> <add> private static final XMLInputFactory xmlInputFactory() { <ide> XMLInputFactory inputFactory = XMLInputFactory.newInstance(); <ide> inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); <ide> inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); <ide> inputFactory.setXMLResolver(NO_OP_XML_RESOLVER); <del> return new XmlMapper(inputFactory); <add> return inputFactory; <ide> } <ide> <ide> private static final XMLResolver NO_OP_XML_RESOLVER = new XMLResolver() { <ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.java <ide> public void setIndentOutput(boolean indentOutput) { <ide> this.builder.indentOutput(indentOutput); <ide> } <ide> <add> /** <add> * Define if a wrapper will be used for indexed (List, array) properties or not by <add> * default (only applies to {@link XmlMapper}). <add> * @since 4.3 <add> */ <add> public void setDefaultUseWrapper(boolean defaultUseWrapper) { <add> this.builder.defaultUseWrapper(defaultUseWrapper); <add> } <add> <ide> /** <ide> * Specify features to enable. <ide> * @see com.fasterxml.jackson.core.JsonParser.Feature <ide><path>spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java <ide> import java.nio.file.Paths; <ide> import java.text.SimpleDateFormat; <ide> import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.Date; <ide> import java.util.HashMap; <add>import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.Optional; <ide> public void createXmlMapper() { <ide> assertTrue(xmlObjectMapper.getClass().isAssignableFrom(XmlMapper.class)); <ide> } <ide> <add> @Test // SPR-13975 <add> public void defaultUseWrapper() throws JsonProcessingException { <add> ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().defaultUseWrapper(false).build(); <add> assertNotNull(objectMapper); <add> assertEquals(XmlMapper.class, objectMapper.getClass()); <add> ListContainer<String> container = new ListContainer<>(Arrays.asList("foo", "bar")); <add> String output = objectMapper.writeValueAsString(container); <add> assertThat(output, containsString("<list>foo</list><list>bar</list></ListContainer>")); <add> } <add> <ide> <ide> public static class CustomIntegerModule extends Module { <ide> <ide> public void setProperty2(String property2) { <ide> } <ide> } <ide> <add> public static class ListContainer<T> { <add> <add> private List<T> list; <add> <add> public ListContainer() { <add> } <add> <add> public ListContainer(List<T> list) { <add> this.list = list; <add> } <add> <add> public List<T> getList() { <add> return list; <add> } <add> <add> public void setList(List<T> list) { <add> this.list = list; <add> } <add> } <add> <ide> }
3
Javascript
Javascript
add proper es6 symbol polyfill
049eff1482884be0c4e74080c2c18acb9447f2d5
<ide><path>dist/Immutable.js <ide> $traceurRuntime.createClass = createClass; <ide> $traceurRuntime.superCall = superCall; <ide> $traceurRuntime.defaultSuperCall = defaultSuperCall; <ide> "use strict"; <add>var SHIFT = 5; <add>var SIZE = 1 << SHIFT; <add>var MASK = SIZE - 1; <add>var NOT_SET = {}; <add>var CHANGE_LENGTH = {value: false}; <add>var DID_ALTER = {value: false}; <add>function MakeRef(ref) { <add> ref.value = false; <add> return ref; <add>} <add>function SetRef(ref) { <add> ref && (ref.value = true); <add>} <add>function OwnerID() {} <add>function arrCopy(arr) { <add> var len = arr.length; <add> var newArr = new Array(len); <add> for (var ii = 0; ii < len; ii++) { <add> newArr[ii] = arr[ii]; <add> } <add> return newArr; <add>} <add>var ITER_RESULT = { <add> value: undefined, <add> done: false <add>}; <add>function iteratorValue(value) { <add> ITER_RESULT.value = value; <add> ITER_RESULT.done = false; <add> return ITER_RESULT; <add>} <add>function iteratorDone() { <add> ITER_RESULT.value = undefined; <add> ITER_RESULT.done = true; <add> return ITER_RESULT; <add>} <add>function invariant(condition, error) { <add> if (!condition) <add> throw new Error(error); <add>} <add>if (typeof Symbol === 'undefined') { <add> Symbol = {}; <add>} <add>if (!Symbol.iterator) { <add> Symbol.iterator = '@@iterator'; <add>} <ide> var Sequence = function Sequence(value) { <ide> return $Sequence.from(arguments.length === 1 ? value : Array.prototype.slice.call(arguments)); <ide> }; <ide> var SequenceIterator = function SequenceIterator() {}; <ide> return '[Iterator]'; <ide> }}, {}); <ide> var SequenceIteratorPrototype = SequenceIterator.prototype; <add>SequenceIteratorPrototype[Symbol.iterator] = returnThis; <ide> SequenceIteratorPrototype.inspect = SequenceIteratorPrototype.toSource = function() { <ide> return this.toString(); <ide> }; <ide> function iteratorMapper(iter, fn) { <ide> }); <ide> return newIter; <ide> } <del>var SHIFT = 5; <del>var SIZE = 1 << SHIFT; <del>var MASK = SIZE - 1; <del>var NOT_SET = {}; <del>var CHANGE_LENGTH = {value: false}; <del>var DID_ALTER = {value: false}; <del>function MakeRef(ref) { <del> ref.value = false; <del> return ref; <del>} <del>function SetRef(ref) { <del> ref && (ref.value = true); <del>} <del>function OwnerID() {} <del>function arrCopy(arr) { <del> var len = arr.length; <del> var newArr = new Array(len); <del> for (var ii = 0; ii < len; ii++) { <del> newArr[ii] = arr[ii]; <del> } <del> return newArr; <del>} <del>var ITER_RESULT = { <del> value: undefined, <del> done: false <del>}; <del>function iteratorValue(value) { <del> ITER_RESULT.value = value; <del> ITER_RESULT.done = false; <del> return ITER_RESULT; <del>} <del>function iteratorDone() { <del> ITER_RESULT.value = undefined; <del> ITER_RESULT.done = true; <del> return ITER_RESULT; <del>} <ide> var Cursor = function Cursor(rootData, keyPath, onChange, value) { <ide> value = value ? value : rootData.getIn(keyPath); <ide> this.length = value instanceof Sequence ? value.length : null; <ide> function is(first, second) { <ide> } <ide> return false; <ide> } <del>function invariant(condition, error) { <del> if (!condition) <del> throw new Error(error); <del>} <ide> var Map = function Map(sequence) { <ide> var map = $Map.empty(); <ide> return sequence ? sequence.constructor === $Map ? sequence : map.merge(sequence) : map; <ide> var $Map = Map; <ide> return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); <ide> }}, Sequence); <ide> var MapPrototype = Map.prototype; <del>MapPrototype['@@iterator'] = function() { <add>MapPrototype[Symbol.iterator] = function() { <ide> return this.entries(); <ide> }; <ide> Map.from = Map; <ide> var $Vector = Vector; <ide> } <ide> }, IndexedSequence); <ide> var VectorPrototype = Vector.prototype; <del>VectorPrototype['@@iterator'] = VectorPrototype.values; <add>VectorPrototype[Symbol.iterator] = VectorPrototype.values; <ide> VectorPrototype.update = MapPrototype.update; <ide> VectorPrototype.updateIn = MapPrototype.updateIn; <ide> VectorPrototype.cursor = MapPrototype.cursor; <ide> var $Set = Set; <ide> } <ide> }, Sequence); <ide> var SetPrototype = Set.prototype; <del>SetPrototype['@@iterator'] = SetPrototype.keys = SetPrototype.values; <add>SetPrototype[Symbol.iterator] = SetPrototype.keys = SetPrototype.values; <ide> SetPrototype.contains = SetPrototype.has; <ide> SetPrototype.mergeDeep = SetPrototype.merge = SetPrototype.union; <ide> SetPrototype.mergeDeepWith = SetPrototype.mergeWith = function(merger) { <ide> var $Record = Record; <ide> }, {}, Sequence); <ide> var RecordPrototype = Record.prototype; <ide> RecordPrototype.__deepEqual = MapPrototype.__deepEqual; <del>RecordPrototype['iterator']; <add>RecordPrototype[Symbol.iterator] = MapPrototype[Symbol.iterator]; <ide> RecordPrototype.merge = MapPrototype.merge; <ide> RecordPrototype.mergeWith = MapPrototype.mergeWith; <ide> RecordPrototype.mergeDeep = MapPrototype.mergeDeep; <ide><path>dist/Immutable.min.js <ide> * LICENSE file in the root directory of this source tree. An additional grant <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> */ <del>function t(){function t(t,e,n,r){var i;if(r){var u=r.prototype;i=ve.create(u)}else i=t.prototype;return ve.keys(e).forEach(function(t){i[t]=e[t]}),ve.keys(n).forEach(function(e){t[e]=n[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,n,r){return ve.getPrototypeOf(e)[n].apply(t,r)}function n(t,n,r){e(t,n,"constructor",r)}function r(){return Object.create(ye)}function i(t){var e=Object.create(Ie);return e.__reversedIndices=t?t.__reversedIndices:!1,e}function u(t,e,n,r){var i=t.get?t.get(e[r],Ce):Ce;return i===Ce?n:++r===e.length?i:u(i,e,n,r)}function s(t,e,n){return(0===t||null!=n&&-n>=t)&&(null==e||null!=n&&e>=n)}function a(t,e){return 0>t?Math.max(0,e+t):e?Math.min(e,t):t}function o(t,e){return null==t?e:0>t?Math.max(0,e+t):e?Math.min(e,t):t}function h(t){return t}function c(t,e){return[e,t]}function f(){return!0}function l(){return this}function _(t){return(t||0)+1}function g(t,e,n,r,i){var u=t.__makeSequence();return u.__iterateUncached=function(u,s,a){var o=0,h=t.__iterate(function(t,i,s){if(e.call(n,t,i,s)){if(u(t,r?i:o,s)===!1)return!1;o++}},s,a);return i?h:o},u}function v(t){return function(){return!t.apply(this,arguments)}}function p(t){return"string"==typeof t?JSON.stringify(t):t}function m(t,e){for(var n="";e;)1&e&&(n+=t),(e>>=1)&&(t+=t);return n}function d(t,e){return t>e?1:e>t?-1:0}function y(t){x(1/0!==t,"Cannot perform this action with an infinite sequence.")}function w(t,e){var n=new be;return n.next=function(){var n=t.next();return n.done?n:(n.value=e(n.value),n)},n}function S(t){return t.value=!1,t}function I(t){t&&(t.value=!0)}function k(){}function D(t){for(var e=t.length,n=Array(e),r=0;e>r;r++)n[r]=t[r];return n}function b(t){return je.value=t,je.done=!1,je}function M(){return je.value=void 0,je.done=!0,je}function q(t,e,n){return n instanceof me?O(t,e,n):n}function O(t,e,n){return new Ue(t._rootData,t._keyPath.concat(e),t._onChange,n)}function A(t,e,n){var r=t._rootData.updateIn(t._keyPath,n?We.empty():void 0,e),i=t._keyPath||[];return t._onChange&&t._onChange.call(void 0,r,t._rootData,n?i.concat(n):i),new Ue(r,t._keyPath,t._onChange) <del>}function C(t,e){return t instanceof Ue&&(t=t.deref()),e instanceof Ue&&(e=e.deref()),t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t instanceof me?t.equals(e):!1}function x(t,e){if(!t)throw Error(e)}function E(t,e){return b(0===t||1===t?e[t]:e)}function j(t,e){return{node:t,index:0,__prev:e}}function U(t,e,n){var r=Object.create(Re);return r.length=t,r._root=e,r.__ownerID=n,r.__altered=!1,r}function W(t,e,n){var r=S(xe),i=S(Ee),u=P(t._root,t.__ownerID,0,T(e),e,n,r,i);if(!i.value)return t;var s=t.length+(r.value?n===Ce?-1:1:0);return t.__ownerID?(t.length=s,t._root=u,t.__altered=!0,t):u?U(s,u):We.empty()}function P(t,e,n,r,i,u,s,a){return t?t.update(e,n,r,i,u,s,a):u===Ce?t:(I(a),I(s),new Ne(e,r,[i,u]))}function R(t){return t.constructor===Ne||t.constructor===Ve}function z(t,e,n,r,i){if(t.hash===r)return new Ve(e,r,[t.entry,i]);var u,s=t.hash>>>n&Ae,a=r>>>n&Ae,o=s===a?[z(t,e,n+qe,r,i)]:(u=new Ne(e,r,i),a>s?[t,u]:[u,t]);return new ze(e,1<<s|1<<a,o)}function J(t,e,n,r){for(var i=0,u=0,s=Array(n),a=0,o=1,h=e.length;h>a;a++,o<<=1){var c=e[a];null!=c&&a!==r&&(i|=o,s[u++]=c)}return new ze(t,i,s)}function B(t,e,n,r,i){for(var u=0,s=Array(Oe),a=0;0!==n;a++,n>>>=1)s[a]=1&n?e[u++]:null;return s[r]=i,new Be(t,u+1,s)}function L(t,e,n){for(var r=[],i=0;n.length>i;i++){var u=n[i];u&&r.push(Array.isArray(u)?me(u).fromEntrySeq():me(u))}return K(t,e,r)}function V(t){return function(e,n){return e&&e.mergeDeepWith?e.mergeDeepWith(t,n):t?t(e,n):n}}function K(t,e,n){return 0===n.length?t:t.withMutations(function(t){for(var r=e?function(n,r){var i=t.get(r,Ce);t.set(r,i===Ce?n:e(i,n))}:function(e,n){t.set(n,e)},i=0;n.length>i;i++)n[i].forEach(r)})}function N(t,e,n,r,i){var u=e.length;if(i===u)return r(t);x(t.set,"updateIn with invalid keyPath");var s=i===u-1?n:We.empty(),a=e[i],o=t.get(a,s),h=N(o,e,n,r,i+1);return h===o?t:t.set(a,h)}function F(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function G(t,e,n,r){var i=r?t:D(t);return i[e]=n,i}function H(t,e,n,r){var i=t.length+1;if(r&&e+1===i)return t[e]=n,t; <del>for(var u=Array(i),s=0,a=0;i>a;a++)a===e?(u[a]=n,s=-1):u[a]=t[a+s];return u}function Q(t,e,n){var r=t.length-1;if(n&&e===r)return t.pop(),t;for(var i=Array(r),u=0,s=0;r>s;s++)s===e&&(u=1),i[s]=t[s+u];return i}function T(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t&Qe;t=""+t,e="string"}if("string"===e)return t.length>Te?X(t):Y(t);if(t.hashCode&&"function"==typeof t.hashCode)return t.hashCode();throw Error("Unable to hash: "+t)}function X(t){var e=Ze[t];return null==e&&(e=Y(t),Ye===Xe&&(Ye=0,Ze={}),Ye++,Ze[t]=e),e}function Y(t){for(var e=0,n=0;t.length>n;n++)e=31*e+t.charCodeAt(n)&Qe;return e}function Z(t,e,n,r,i,u){if(t){var s,a=t.array,o=a.length-1;if(0===e)for(s=0;o>=s;s++){var h=u?o-s:s;if(a.hasOwnProperty(h)){var c=h+n;if(c>=0&&r>c&&i(a[h],c)===!1)return!1}}else{var f=1<<e,l=e-qe;for(s=0;o>=s;s++){var _=u?o-s:s,g=n+_*f;if(r>g&&g+f>0){var v=a[_];if(v&&!Z(v,l,g,r,i,u))return!1}}}}return!0}function $(t,e,n,r,i){return{array:t,level:e,offset:n,max:r,index:0,__prev:i}}function te(t,e,n,r,i,u){var s=Object.create(rn);return s.length=e-t,s._origin=t,s._size=e,s._level=n,s._root=r,s._tail=i,s.__ownerID=u,s.__altered=!1,s}function ee(t,e,n){if(e>=t.length)return n===Ce?t:t.withMutations(function(t){ue(t,0,e+1).set(e,n)});e=ae(e,t._origin);var r=t._tail,i=t._root,u=S(Ee);return e>=oe(t._size)?r=ne(r,t.__ownerID,0,e,n,u):i=ne(i,t.__ownerID,t._level,e,n,u),u.value?t.__ownerID?(t._root=i,t._tail=r,t.__altered=!0,t):te(t._origin,t._size,t._level,i,r):t}function ne(t,e,n,r,i,u){var s,a=i===Ce,o=r>>>n&Ae,h=t&&t.array.length>o&&t.array.hasOwnProperty(o);if(a&&!h)return t;if(n>0){var c=t&&t.array[o],f=ne(c,e,n-qe,r,i,u);return f===c?t:(s=re(t,e),s.array[o]=f,s)}return!a&&h&&t.array[o]===i?t:(I(u),s=re(t,e),a?delete s.array[o]:s.array[o]=i,s)}function re(t,e){return e&&t&&e===t.ownerID?t:new un(t?t.array.slice():[],e)}function ie(t,e){if(e>=oe(t._size))return t._tail;if(1<<t._level+qe>e){for(var n=t._root,r=t._level;n&&r>0;)n=n.array[e>>>r&Ae],r-=qe;return n}}function ue(t,e,n){var r=t.__ownerID||new k,i=t._origin,u=t._size,s=i+e,a=null==n?u:0>n?u+n:i+n; <del>if(s===i&&a===u)return t;if(s>=a)return t.clear();for(var o=t._level,h=t._root,c=0;0>s+c;)h=new un(h&&h.array.length?[null,h]:[],r),o+=qe,c+=1<<o;c&&(s+=c,i+=c,a+=c,u+=c);for(var f=oe(u),l=oe(a);l>=1<<o+qe;)h=new un(h&&h.array.length?[h]:[],r),o+=qe;var _=t._tail,g=f>l?ie(t,a-1):l>f?new un([],r):_;if(_&&l>f&&u>s&&_.array.length){h=re(h,r);for(var v=h,p=o;p>qe;p-=qe){var m=f>>>p&Ae;v=v.array[m]=re(v.array[m],r)}v.array[f>>>qe&Ae]=_}if(u>a&&(g=g&&g.removeAfter(r,0,a)),s>=l)s-=l,a-=l,o=qe,h=null,g=g&&g.removeBefore(r,0,s);else if(s>i||f>l){var d,y;c=0;do d=s>>>o&Ae,y=l-1>>>o&Ae,d===y&&(d&&(c+=(1<<o)*d),o-=qe,h=h&&h.array[d]);while(h&&d===y);h&&s>i&&(h=h&&h.removeBefore(r,o,s-c)),h&&f>l&&(h=h&&h.removeAfter(r,o,l-c)),c&&(s-=c,a-=c)}return t.__ownerID?(t.length=a-s,t._origin=s,t._size=a,t._level=o,t._root=h,t._tail=g,t.__altered=!0,t):te(s,a,o,h,g)}function se(t,e,n){for(var r=[],i=0;n.length>i;i++){var u=n[i];u&&r.push(me(u))}var s=Math.max.apply(null,r.map(function(t){return t.length||0}));return s>t.length&&(t=t.setLength(s)),K(t,e,r)}function ae(t,e){return x(t>=0,"Index out of bounds"),t+e}function oe(t){return Oe>t?0:t-1>>>qe<<qe}function he(t,e){var n=Object.create(fn);return n.length=t?t.length:0,n._map=t,n.__ownerID=e,n}function ce(t,e,n){var r=Object.create(_n.prototype);return r.length=t?t.length:0,r._map=t,r._vector=e,r.__ownerID=n,r}function fe(t,e,n){var r=Object.create(Object.getPrototypeOf(t));return r._map=e,r.__ownerID=n,r}function le(t,e){return e?_e(e,t,"",{"":t}):ge(t)}function _e(t,e,n,r){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(r,n,me(e).map(function(n,r){return _e(t,n,r,e)})):e}function ge(t){if(t){if(Array.isArray(t))return me(t).map(ge).toVector();if(t.constructor===Object)return me(t).map(ge).toMap()}return t}var ve=Object,pe={};pe.createClass=t,pe.superCall=e,pe.defaultSuperCall=n;var me=function(t){return de.from(1===arguments.length?t:Array.prototype.slice.call(arguments))},de=me;pe.createClass(me,{toString:function(){return this.__toString("Seq {","}")},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e <del>},__toStringMapper:function(t,e){return e+": "+p(t)},toJS:function(){return this.map(function(t){return t instanceof de?t.toJS():t}).__toJS()},toArray:function(){y(this.length);var t=Array(this.length||0);return this.valueSeq().forEach(function(e,n){t[n]=e}),t},toObject:function(){y(this.length);var t={};return this.forEach(function(e,n){t[n]=e}),t},toVector:function(){return y(this.length),en.from(this)},toMap:function(){return y(this.length),We.from(this)},toOrderedMap:function(){return y(this.length),_n.from(this)},toSet:function(){return y(this.length),hn.from(this)},equals:function(t){if(this===t)return!0;if(!(t instanceof de))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1;if(0===this.length&&0===t.length)return!0}return this.__deepEquals(t)},__deepEquals:function(t){var e=this.cacheResult().entrySeq().toArray(),n=0;return t.every(function(t,r){var i=e[n++];return C(r,i[0])&&C(t,i[1])})},join:function(t){t=t||",";var e="",n=!0;return this.forEach(function(r){n?(n=!1,e+=r):e+=t+r}),e},count:function(t,e){return t?this.filter(t,e).count():(null==this.length&&(this.length=this.forEach(f)),this.length)},countBy:function(t){var e=this;return _n.empty().withMutations(function(n){e.forEach(function(e,r,i){n.update(t(e,r,i),_)})})},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t.map(function(t){return de(t)})),r=this.__makeSequence();return r.length=n.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),r.__iterateUncached=function(t,e){for(var r,i=0,u=n.length-1,s=0;u>=s&&!r;s++){var a=n[e?u-s:s];i+=a.__iterate(function(e,n,i){return t(e,n,i)===!1?(r=!0,!1):void 0},e)}return i},r},reverse:function(){var t=this,e=t.__makeSequence();return e.length=t.length,e.__iterateUncached=function(e,n){return t.__iterate(e,!n)},e.reverse=function(){return t},e},keySeq:function(){return this.flip().valueSeq()},valueSeq:function(){var t=this,e=i(t);return e.length=t.length,e.valueSeq=l,e.__iterateUncached=function(e,n,r){if(r&&null==this.length)return this.cacheResult().__iterate(e,n,r); <del>var i,u=0;return r?(u=this.length-1,i=function(t,n,r){return e(t,u--,r)!==!1}):i=function(t,n,r){return e(t,u++,r)!==!1},t.__iterate(i,n),r?this.length:u},e},entrySeq:function(){var t=this;if(t._cache)return de(t._cache);var e=t.map(c).valueSeq();return e.fromEntries=function(){return t},e},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},reduce:function(t,e,n){var r=e;return this.forEach(function(e,i,u){r=t.call(n,r,e,i,u)}),r},reduceRight:function(t,e,n){return this.reverse(!0).reduce(t,e,n)},every:function(t,e){var n=!0;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?void 0:(n=!1,!1)}),n},some:function(t,e){return!this.every(v(t),e)},first:function(){return this.find(f)},last:function(){return this.findLast(f)},rest:function(){return this.slice(1)},butLast:function(){return this.slice(0,-1)},has:function(t){return this.get(t,Ce)!==Ce},get:function(t,e){return this.find(function(e,n){return C(n,t)},null,e)},getIn:function(t,e){return t&&0!==t.length?u(this,t,e,0):this},contains:function(t){return this.find(function(e){return C(e,t)},null,Ce)!==Ce},find:function(t,e,n){var r=n;return this.forEach(function(n,i,u){return t.call(e,n,i,u)?(r=n,!1):void 0}),r},findKey:function(t,e){var n;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?(n=i,!1):void 0}),n},findLast:function(t,e,n){return this.reverse(!0).find(t,e,n)},findLastKey:function(t,e){return this.reverse(!0).findKey(t,e)},flip:function(){var t=this,e=r();return e.length=t.length,e.flip=function(){return t},e.__iterateUncached=function(e,n){return t.__iterate(function(t,n,r){return e(n,t,r)!==!1},n)},e},map:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){return n.__iterate(function(n,i,u){return r(t.call(e,n,i,u),i,u)!==!1},i)},r},mapKeys:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){return n.__iterate(function(n,i,u){return r(n,t.call(e,i,n,u),u)!==!1},i)},r},filter:function(t,e){return g(this,t,e,!0,!1)},slice:function(t,e){if(s(t,e,this.length))return this; <del>var n=a(t,this.length),r=o(e,this.length);if(n!==n||r!==r)return this.entrySeq().slice(t,e).fromEntrySeq();var i=0===n?this:this.skip(n);return null==r||r===this.length?i:i.take(r-n)},take:function(t){var e=0,n=this.takeWhile(function(){return e++<t});return n.length=this.length&&Math.min(this.length,t),n},takeLast:function(t,e){return this.reverse(e).take(t).reverse(e)},takeWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,u){if(i)return this.cacheResult().__iterate(r,i,u);var s=0;return n.__iterate(function(n,i,u){return t.call(e,n,i,u)&&r(n,i,u)!==!1?void s++:!1},i,u),s},r},takeUntil:function(t,e,n){return this.takeWhile(v(t),e,n)},skip:function(t,e){if(0===t)return this;var n=0,r=this.skipWhile(function(){return n++<t},null,e);return r.length=this.length&&Math.max(0,this.length-t),r},skipLast:function(t,e){return this.reverse(e).skip(t).reverse(e)},skipWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,u){if(i)return this.cacheResult().__iterate(r,i,u);var s=!0,a=0;return n.__iterate(function(n,i,u){if(!s||!(s=t.call(e,n,i,u))){if(r(n,i,u)===!1)return!1;a++}},i,u),a},r},skipUntil:function(t,e,n){return this.skipWhile(v(t),e,n)},groupBy:function(t){var e=this,n=_n.empty().withMutations(function(n){e.forEach(function(e,r,i){var u=t(e,r,i),s=n.get(u,Ce);s===Ce&&(s=[],n.set(u,s)),s.push([r,e])})});return n.map(function(t){return de(t).fromEntrySeq()})},sort:function(t,e){return this.sortBy(h,t,e)},sortBy:function(t,e){e=e||d;var n=this;return de(this.entrySeq().entrySeq().toArray().sort(function(r,i){return e(t(r[1][1],r[1][0],n),t(i[1][1],i[1][0],n))||r[0]-i[0]})).fromEntrySeq().valueSeq().fromEntrySeq()},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(y(this.length),this._cache=this.entrySeq().toArray(),null==this.length&&(this.length=this._cache.length)),this},__iterate:function(t,e,n){if(!this._cache)return this.__iterateUncached(t,e,n);var r=this.length-1,i=this._cache,u=this;if(e)for(var s=i.length-1;s>=0;s--){var a=i[s]; <del>if(t(a[1],n?a[0]:r-a[0],u)===!1)break}else i.every(n?function(e){return t(e[1],r-e[0],u)!==!1}:function(e){return t(e[1],e[0],u)!==!1});return this.length},__makeSequence:function(){return r()}},{from:function(t){if(t instanceof de)return t;if(!Array.isArray(t)){if(t&&t.constructor===Object)return new ke(t);t=[t]}return new De(t)}});var ye=me.prototype;ye.toJSON=ye.toJS,ye.__toJS=ye.toObject,ye.inspect=ye.toSource=function(){return""+this};var we=function(){pe.defaultSuperCall(this,Se.prototype,arguments)},Se=we;pe.createClass(we,{toString:function(){return this.__toString("Seq [","]")},toArray:function(){y(this.length);var t=Array(this.length||0);return t.length=this.forEach(function(e,n){t[n]=e}),t},fromEntrySeq:function(){var t=this,e=r();return e.length=t.length,e.entrySeq=function(){return t},e.__iterateUncached=function(e,n,r){return t.__iterate(function(t,n,r){return e(t[1],t[0],r)},n,r)},e},join:function(t){t=t||",";var e="",n=0;return this.forEach(function(r,i){var u=i-n;n=i,e+=(1===u?t:m(t,u))+r}),this.length&&this.length-1>n&&(e+=m(t,this.length-1-n)),e},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t).map(function(t){return me(t)}),r=this.__makeSequence();return r.length=n.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),r.__iterateUncached=function(t,e,r){if(r&&!this.length)return this.cacheResult().__iterate(t,e,r);for(var i,u=0,s=r&&this.length-1,a=n.length-1,o=0;a>=o&&!i;o++){var h=n[e?a-o:o];h instanceof Se||(h=h.valueSeq()),u+=h.__iterate(function(e,n,a){return n+=u,t(e,r?s-n:n,a)===!1?(i=!0,!1):void 0},e)}return u},r},reverse:function(t){var e=this,n=e.__makeSequence();return n.length=e.length,n.__reversedIndices=!!(t^e.__reversedIndices),n.__iterateUncached=function(n,r,i){return e.__iterate(n,!r,i^t)},n.reverse=function(n){return t===n?e:Ie.reverse.call(this,n)},n},valueSeq:function(){var t=pe.superCall(this,Se.prototype,"valueSeq",[]);return t.length=void 0,t},filter:function(t,e,n){var r=g(this,t,e,n,n);return n&&(r.length=this.length),r <del>},indexOf:function(t){return this.findIndex(function(e){return C(e,t)})},lastIndexOf:function(t){return this.reverse(!0).indexOf(t)},findIndex:function(t,e){var n=this.findKey(t,e);return null==n?-1:n},findLastIndex:function(t,e){return this.reverse(!0).findIndex(t,e)},slice:function(t,e,n){var r=this;if(s(t,e,r.length))return r;var i=r.__makeSequence(),u=a(t,r.length),h=o(e,r.length);return i.length=r.length&&(n?r.length:h-u),i.__reversedIndices=r.__reversedIndices,i.__iterateUncached=function(i,s,c){if(s)return this.cacheResult().__iterate(i,s,c);var f=this.__reversedIndices^c;if(u!==u||h!==h||f&&null==r.length){var l=r.count();u=a(t,l),h=o(e,l)}var _=f?r.length-h:u,g=f?r.length-u:h,v=r.__iterate(function(t,e,r){return f?null!=g&&e>=g||e>=_&&i(t,n?e:e-_,r)!==!1:_>e||(null==g||g>e)&&i(t,n?e:e-_,r)!==!1},s,c);return null!=this.length?this.length:n?v:Math.max(0,v-_)},i},splice:function(t,e){for(var n=[],r=2;arguments.length>r;r++)n[r-2]=arguments[r];return 0===e&&0===n.length?this:this.slice(0,t).concat(n,this.slice(t+e))},takeWhile:function(t,e,n){var r=this,i=r.__makeSequence();return i.__iterateUncached=function(u,s,a){if(s)return this.cacheResult().__iterate(u,s,a);var o=0,h=!0,c=r.__iterate(function(n,r,i){return t.call(e,n,r,i)&&u(n,r,i)!==!1?void(o=r):(h=!1,!1)},s,a);return n?i.length:h?c:o+1},n&&(i.length=this.length),i},skipWhile:function(t,e,n){var r=this,i=r.__makeSequence();return n&&(i.length=this.length),i.__iterateUncached=function(i,u,s){if(u)return this.cacheResult().__iterate(i,u,s);var a=r.__reversedIndices^s,o=!0,h=0,c=r.__iterate(function(r,u,a){return o&&(o=t.call(e,r,u,a),o||(h=u)),o||i(r,s||n?u:u-h,a)!==!1},u,s);return n?c:a?h+1:c-h},i},groupBy:function(t,e,n){var r=this,i=_n.empty().withMutations(function(e){r.forEach(function(i,u,s){var a=t(i,u,s),o=e.get(a,Ce);o===Ce&&(o=Array(n?r.length:0),e.set(a,o)),n?o[u]=i:o.push(i)})});return i.map(function(t){return me(t)})},sortBy:function(t,e,n){var r=pe.superCall(this,Se.prototype,"sortBy",[t,e]);return n||(r=r.valueSeq()),r.length=this.length,r <del>},__makeSequence:function(){return i(this)}},{},me);var Ie=we.prototype;Ie.__toJS=Ie.toArray,Ie.__toStringMapper=p;var ke=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};pe.createClass(ke,{toObject:function(){return this._object},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var n=this._object,r=this._keys,i=r.length-1,u=0;i>=u;u++){var s=e?i-u:u;if(t(n[r[s]],r[s],n)===!1)break}return u}},{},me);var De=function(t){this._array=t,this.length=t.length};pe.createClass(De,{toArray:function(){return this._array},__iterate:function(t,e,n){var r=this._array,i=r.length-1,u=-1;if(e){for(var s=i;s>=0;s--){if(r.hasOwnProperty(s)&&t(r[s],n?s:i-s,r)===!1)return u+1;u=s}return r.length}var a=r.every(function(e,s){return t(e,n?i-s:s,r)===!1?!1:(u=s,!0)});return a?r.length:u+1}},{},we),De.prototype.get=ke.prototype.get,De.prototype.has=ke.prototype.has;var be=function(){};pe.createClass(be,{toString:function(){return"[Iterator]"}},{});var Me=be.prototype;Me.inspect=Me.toSource=function(){return""+this};var qe=5,Oe=1<<qe,Ae=Oe-1,Ce={},xe={value:!1},Ee={value:!1},je={value:void 0,done:!1},Ue=function(t,e,n,r){r=r?r:t.getIn(e),this.length=r instanceof me?r.length:null,this._rootData=t,this._keyPath=e,this._onChange=n};pe.createClass(Ue,{deref:function(t){return this._rootData.getIn(this._keyPath,t)},get:function(t,e){if(Array.isArray(t)&&0===t.length)return this;var n=this._rootData.getIn(this._keyPath.concat(t),Ce);return n===Ce?e:q(this,t,n)},set:function(t,e){return A(this,function(n){return n.set(t,e)},t)},"delete":function(t){return A(this,function(e){return e.delete(t)},t)},clear:function(){return A(this,function(t){return t.clear()})},update:function(t,e,n){return 1===arguments.length?A(this,t):A(this,function(r){return r.update(t,e,n)},t)},cursor:function(t){return Array.isArray(t)&&0===t.length?this:O(this,t)},__iterate:function(t,e,n){var r=this,i=r.deref();return i&&i.__iterate?i.__iterate(function(e,n,i){return t(q(r,n,e),n,i) <del>},e,n):0}},{},me),Ue.prototype.getIn=Ue.prototype.get;var We=function(t){var e=Pe.empty();return t?t.constructor===Pe?t:e.merge(t):e},Pe=We;pe.createClass(We,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,T(t),t,e):e},set:function(t,e){return W(this,t,e)},"delete":function(t){return W(this,t,Ce)},update:function(t,e,n){return 1===arguments.length?this.updateIn([],null,t):this.updateIn([t],e,n)},updateIn:function(t,e,n){var r;return n||(r=[e,n],n=r[0],e=r[1],r),N(this,t,e,n,0)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._root=null,this.__altered=!0,this):Pe.empty()},merge:function(){return L(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return L(this,t,e)},mergeDeep:function(){return L(this,V(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return L(this,V(t),e)},cursor:function(t,e){return e||"function"!=typeof t?0===arguments.length?t=[]:Array.isArray(t)||(t=[t]):(e=t,t=[]),new Ue(this,t,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new k)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},keys:function(){return new Ge(this,0)},values:function(){return new Ge(this,1)},entries:function(){return new Ge(this,2)},__iterate:function(t,e){var n=this;if(!n._root)return 0;var r=0;return this._root.iterate(function(e){return t(e[1],e[0],n)===!1?!1:void r++},e),r},__deepEqual:function(t){var e=this;return t.every(function(t,n){return C(e.get(n,Ce),t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?U(this.length,this._root,t):(this.__ownerID=t,this.__altered=!1,this)}},{empty:function(){return He||(He=U(0))}},me);var Re=We.prototype;Re["@@iterator"]=function(){return this.entries()},We.from=We;var ze=function(t,e,n){this.ownerID=t,this.bitmap=e,this.nodes=n <del>},Je=ze;pe.createClass(ze,{get:function(t,e,n,r){var i=1<<(e>>>t&Ae),u=this.bitmap;return 0===(u&i)?r:this.nodes[F(u&i-1)].get(t+qe,e,n,r)},update:function(t,e,n,r,i,u,s){var a=n>>>e&Ae,o=1<<a,h=this.bitmap,c=0!==(h&o);if(!c&&i===Ce)return this;var f=F(h&o-1),l=this.nodes,_=c?l[f]:null,g=P(_,t,e+qe,n,r,i,u,s);if(g===_)return this;if(!c&&g&&l.length>=$e)return B(t,l,h,a,g);if(c&&!g&&2===l.length&&R(l[1^f]))return l[1^f];if(c&&g&&1===l.length&&R(g))return g;var v=t&&t===this.ownerID,p=c?g?h:h^o:h|o,m=c?g?G(l,f,g,v):Q(l,f,v):H(l,f,g,v);return v?(this.bitmap=p,this.nodes=m,this):new Je(t,p,m)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++)if(n[e?i-r:r].iterate(t,e)===!1)return!1}},{});var Be=function(t,e,n){this.ownerID=t,this.count=e,this.nodes=n},Le=Be;pe.createClass(Be,{get:function(t,e,n,r){var i=e>>>t&Ae,u=this.nodes[i];return u?u.get(t+qe,e,n,r):r},update:function(t,e,n,r,i,u,s){var a=n>>>e&Ae,o=i===Ce,h=this.nodes,c=h[a];if(o&&!c)return this;var f=P(c,t,e+qe,n,r,i,u,s);if(f===c)return this;var l=this.count;if(c){if(!f&&(l--,tn>l))return J(t,h,l,a)}else l++;var _=t&&t===this.ownerID,g=G(h,a,f,_);return _?(this.count=l,this.nodes=g,this):new Le(t,l,g)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++){var u=n[e?i-r:r];if(u&&u.iterate(t,e)===!1)return!1}}},{});var Ve=function(t,e,n){this.ownerID=t,this.hash=e,this.entries=n},Ke=Ve;pe.createClass(Ve,{get:function(t,e,n,r){for(var i=this.entries,u=0,s=i.length;s>u;u++)if(C(n,i[u][0]))return i[u][1];return r},update:function(t,e,n,r,i,u,s){var a=i===Ce;if(n!==this.hash)return a?this:(I(s),I(u),z(this,t,e,n,[r,i]));for(var o=this.entries,h=0,c=o.length;c>h&&!C(r,o[h][0]);h++);var f=c>h;if(a&&!f)return this;if(I(s),(a||!f)&&I(u),a&&2===c)return new Ne(t,this.hash,o[1^h]);var l=t&&t===this.ownerID,_=l?o:D(o);return f?a?h===c-1?_.pop():_[h]=_.pop():_[h]=[r,i]:_.push([r,i]),l?(this.entries=_,this):new Ke(t,this.hash,_)},iterate:function(t,e){for(var n=this.entries,r=0,i=n.length-1;i>=r;r++)if(t(n[e?i-r:r])===!1)return!1}},{});var Ne=function(t,e,n){this.ownerID=t,this.hash=e,this.entry=n <del>},Fe=Ne;pe.createClass(Ne,{get:function(t,e,n,r){return C(n,this.entry[0])?this.entry[1]:r},update:function(t,e,n,r,i,u,s){var a=i===Ce,o=C(r,this.entry[0]);return(o?i===this.entry[1]:a)?this:(I(s),a?(I(u),null):o?t&&t===this.ownerID?(this.entry[1]=i,this):new Fe(t,n,[r,i]):(I(u),z(this,t,e,n,[r,i])))},iterate:function(t){return t(this.entry)}},{});var Ge=function(t,e){this._type=e,this._stack=t._root&&j(t._root)};pe.createClass(Ge,{next:function(){for(var t=this._type,e=this._stack;e;){var n=e.node,r=e.index++;if(n.entry){if(0===r)return E(t,n.entry)}else if(n.entries){if(n.entries.length>r)return E(t,n.entries[r])}else if(n.nodes.length>r){var i=n.nodes[r];if(i){if(i.entry)return E(t,i.entry);e=this._stack=j(i,e)}continue}e=this._stack=this._stack.__prev}return M()}},{},be);var He,Qe=2147483647,Te=16,Xe=255,Ye=0,Ze={},$e=Oe/2,tn=Oe/4,en=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return nn.from(t)},nn=en;pe.createClass(en,{toString:function(){return this.__toString("Vector [","]")},get:function(t,e){if(t=ae(t,this._origin),t>=this._size)return e;var n=ie(this,t),r=t&Ae;return n&&(void 0===e||n.array.hasOwnProperty(r))?n.array[r]:e},first:function(){return this.get(0)},last:function(){return this.get(this.length?this.length-1:0)},set:function(t,e){return ee(this,t,e)},"delete":function(t){return ee(this,t,Ce)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=this._origin=this._size=0,this._level=qe,this._root=this._tail=null,this.__altered=!0,this):nn.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(n){ue(n,0,e+t.length);for(var r=0;t.length>r;r++)n.set(e+r,t[r])})},pop:function(){return ue(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){ue(e,-t.length);for(var n=0;t.length>n;n++)e.set(n,t[n])})},shift:function(){return ue(this,1)},merge:function(){return se(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return se(this,t,e)},mergeDeep:function(){return se(this,V(null),arguments) <del>},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return se(this,V(t),e)},setLength:function(t){return ue(this,0,t)},slice:function(t,e,n){var r=pe.superCall(this,nn.prototype,"slice",[t,e,n]);if(!n&&r!==this){var i=this,u=i.length;r.toVector=function(){return ue(i,0>t?Math.max(0,u+t):u?Math.min(u,t):t,null==e?u:0>e?Math.max(0,u+e):u?Math.min(u,e):e)}}return r},keys:function(t){return new an(this,0,t)},values:function(t){return new an(this,1,t)},entries:function(t){return new an(this,2,t)},__iterate:function(t,e,n){var r=this,i=0,u=r.length-1;n^=e;var s,a=function(e,s){return t(e,n?u-s:s,r)===!1?!1:(i=s,!0)},o=oe(this._size);return s=e?Z(this._tail,0,o-this._origin,this._size-this._origin,a,e)&&Z(this._root,this._level,-this._origin,o-this._origin,a,e):Z(this._root,this._level,-this._origin,o-this._origin,a,e)&&Z(this._tail,0,o-this._origin,this._size-this._origin,a,e),(s?u:e?u-i:i)+1},__deepEquals:function(t){var e=this.entries(!0);return t.every(function(t,n){var r=e.next().value;return r&&r[0]===n&&C(r[1],t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?te(this._origin,this._size,this._level,this._root,this._tail,t):(this.__ownerID=t,this)}},{empty:function(){return on||(on=te(0,0,qe))},from:function(t){if(!t||0===t.length)return nn.empty();if(t.constructor===nn)return t;var e=Array.isArray(t);return t.length>0&&Oe>t.length?te(0,t.length,qe,null,new un(e?D(t):me(t).toArray())):(e||(t=me(t),t instanceof we||(t=t.valueSeq())),nn.empty().merge(t))}},we);var rn=en.prototype;rn["@@iterator"]=rn.values,rn.update=Re.update,rn.updateIn=Re.updateIn,rn.cursor=Re.cursor,rn.withMutations=Re.withMutations,rn.asMutable=Re.asMutable,rn.asImmutable=Re.asImmutable,rn.wasAltered=Re.wasAltered;var un=function(t,e){this.array=t,this.ownerID=e},sn=un;pe.createClass(un,{removeBefore:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n>>>e&Ae;if(r>=this.array.length)return new sn([],t);var i,u=0===r;if(e>0){var s=this.array[r];if(i=s&&s.removeBefore(t,e-qe,n),i===s&&u)return this <del>}if(u&&!i)return this;var a=re(this,t);if(!u)for(var o=0;r>o;o++)delete a.array[o];return i&&(a.array[r]=i),a},removeAfter:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n-1>>>e&Ae;if(r>=this.array.length)return this;var i,u=r===this.array.length-1;if(e>0){var s=this.array[r];if(i=s&&s.removeAfter(t,e-qe,n),i===s&&u)return this}if(u&&!i)return this;var a=re(this,t);return u||(a.array.length=r+1),i&&(a.array[r]=i),a}},{});var an=function(t,e,n){var r=oe(t._size);this._type=e,this._sparse=n,this._stack=$(t._root&&t._root.array,t._level,-t._origin,r-t._origin,$(t._tail&&t._tail.array,0,r-t._origin,t._size-t._origin))};pe.createClass(an,{next:function(){for(var t=this._type,e=this._sparse,n=this._stack;n;){var r=n.array,i=n.index++,u=1<<n.level,s=n.offset+i*u;if(Oe>i&&s>-u&&n.max>s){var a=r&&r[i];if(0===n.level){if(!e||a||r&&r.length>i&&r.hasOwnProperty(i))return b(0===t?s:1===t?a:[s,a])}else(!e||a)&&(this._stack=n=$(a&&a.array,n.level-qe,s,n.max,n))}else n=this._stack=this._stack.__prev}return M()}},{},be);var on,hn=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return cn.from(t)},cn=hn;pe.createClass(hn,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map.has(t)},get:function(t,e){return this.has(t)?t:e},add:function(t){var e=this._map.set(t,null);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:he(e)},"delete":function(t){var e=this._map.delete(t);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:0===e.length?cn.empty():he(e)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this):cn.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var n=0;t.length>n;n++)me(t[n]).forEach(function(t){return e.add(t)})})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return me(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.every(function(t){return t.contains(n) <del>})||e.delete(n)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return me(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.some(function(t){return t.contains(n)})&&e.delete(n)})})},isSubset:function(t){return t=me(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=me(t),t.every(function(t){return e.contains(t)})},wasAltered:function(){return this._map.wasAltered()},values:function(){return this._map.keys()},entries:function(){return w(this.values(),function(t){return[t,t]})},__iterate:function(t,e){var n=this;return this._map.__iterate(function(e,r){return t(r,r,n)},e)},__deepEquals:function(t){return this._map.equals(t._map)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?he(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return ln||(ln=he(We.empty()))},from:function(t){var e=cn.empty();return t?t.constructor===cn?t:e.union(t):e},fromKeys:function(t){return cn.from(me(t).flip())}},me);var fn=hn.prototype;fn["@@iterator"]=fn.keys=fn.values,fn.contains=fn.has,fn.mergeDeep=fn.merge=fn.union,fn.mergeDeepWith=fn.mergeWith=function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return this.merge.apply(this,t)},fn.withMutations=Re.withMutations,fn.asMutable=Re.asMutable,fn.asImmutable=Re.asImmutable,fn.__toJS=Ie.__toJS,fn.__toStringMapper=Ie.__toStringMapper;var ln,_n=function(t){var e=gn.empty();return t?t.constructor===gn?t:e.merge(t):e},gn=_n;pe.createClass(_n,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){var n=this._map.get(t);return null!=n?this._vector.get(n)[1]:e},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this._vector.clear(),this):gn.empty()},set:function(t,e){var n=this._map.get(t),r=null!=n,i=r?this._map:this._map.set(t,this._vector.length),u=r?this._vector.set(n,[t,e]):this._vector.push([t,e]); <del>return this.__ownerID?(this.length=i.length,this._map=i,this._vector=u,this):u===this._vector?this:ce(i,u)},"delete":function(t){var e=this._map.get(t);if(null==e)return this;var n=this._map.delete(t),r=this._vector.delete(e);return this.__ownerID?(this.length=n.length,this._map=n,this._vector=r,this):0===n.length?gn.empty():ce(n,r)},wasAltered:function(){return this._map.wasAltered()||this._vector.wasAltered()},keys:function(){return w(this.entries(),function(t){return t[0]})},values:function(){return w(this.entries(),function(t){return t[1]})},entries:function(){return this._vector.values(!0)},__iterate:function(t,e){return this._vector.fromEntrySeq().__iterate(t,e)},__deepEqual:function(t){var e=this.entries();return t.every(function(t,n){var r=e.next().value;return r&&C(r[0],n)&&C(r[1],t)})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),n=this._vector.__ensureOwner(t);return t?ce(e,n,t):(this.__ownerID=t,this._map=e,this._vector=n,this)}},{empty:function(){return vn||(vn=ce(We.empty(),en.empty()))}},We),_n.from=_n;var vn,pn=function(t,e){var n=function(t){this._map=We(t)};t=me(t);var r=n.prototype=Object.create(dn);r.constructor=n,r._name=e,r._defaultValues=t;var i=Object.keys(t);return n.prototype.length=i.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(n.prototype,e,{get:function(){return this.get(e)},set:function(t){x(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}),n},mn=pn;pe.createClass(pn,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;Object.getPrototypeOf(this).constructor;return mn._empty||(mn._empty=fe(this,We.empty()))},set:function(t,e){if(null==t||!this.has(t))return this;var n=this._map.set(t,e);return this.__ownerID||n===this._map?this:fe(this,n)},"delete":function(t){if(null==t||!this.has(t))return this; <del>var e=this._map.delete(t);return this.__ownerID||e===this._map?this:fe(this,e)},keys:function(){return this._map.keys()},values:function(){return this._map.values()},entries:function(){return this._map.entries()},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var n=this;return this._defaultValues.map(function(t,e){return n.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?fe(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},me);var dn=pn.prototype;dn.__deepEqual=Re.__deepEqual,dn["iterator"],dn.merge=Re.merge,dn.mergeWith=Re.mergeWith,dn.mergeDeep=Re.mergeDeep,dn.mergeDeepWith=Re.mergeDeepWith,dn.update=Re.update,dn.updateIn=Re.updateIn,dn.cursor=Re.cursor,dn.withMutations=Re.withMutations,dn.asMutable=Re.asMutable,dn.asImmutable=Re.asImmutable;var yn=function(t,e,n){return this instanceof wn?(x(0!==n,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&In?In:(n=null==n?1:Math.abs(n),t>e&&(n=-n),this._start=t,this._end=e,this._step=n,void(this.length=Math.max(0,Math.ceil((e-t)/n-1)+1)))):new wn(t,e,n)},wn=yn;pe.createClass(yn,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return x(t>=0,"Index out of bounds"),this.length>t},get:function(t,e){return x(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._start+t*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e,n){return s(t,e,this.length)?this:n?pe.superCall(this,wn.prototype,"slice",[t,e,n]):(t=a(t,this.length),e=o(e,this.length),t>=e?In:new wn(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var n=e/this._step;if(n>=0&&this.length>n)return n}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,t)},skip:function(t,e){return e?pe.superCall(this,wn.prototype,"skip",[t]):this.slice(t) <del>},__iterate:function(t,e,n){for(var r=e^n,i=this.length-1,u=this._step,s=e?this._start+i*u:this._start,a=0;i>=a&&t(s,r?i-a:a,this)!==!1;a++)s+=e?-u:u;return r?this.length:a},__deepEquals:function(t){return this._start===t._start&&this._end===t._end&&this._step===t._step}},{},we);var Sn=yn.prototype;Sn.__toJS=Sn.toArray,Sn.first=rn.first,Sn.last=rn.last;var In=yn(0,0),kn=function(t,e){return 0===e&&Mn?Mn:this instanceof Dn?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new Dn(t,e)},Dn=kn;pe.createClass(kn,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return x(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._value:e},first:function(){return this._value},contains:function(t){return C(this._value,t)},slice:function(t,e,n){if(n)return pe.superCall(this,Dn.prototype,"slice",[t,e,n]);var r=this.length;return t=0>t?Math.max(0,r+t):Math.min(r,t),e=null==e?r:e>0?Math.min(r,e):Math.max(0,r+e),e>t?new Dn(this._value,e-t):Mn},reverse:function(t){return t?pe.superCall(this,Dn.prototype,"reverse",[t]):this},indexOf:function(t){return C(this._value,t)?0:-1},lastIndexOf:function(t){return C(this._value,t)?this.length:-1},__iterate:function(t,e,n){var r=e^n;x(!r||1/0>this.length,"Cannot access end of infinite range.");for(var i=this.length-1,u=0;i>=u&&t(this._value,r?i-u:u,this)!==!1;u++);return r?this.length:u},__deepEquals:function(t){return C(this._value,t._value)}},{},we);var bn=kn.prototype;bn.last=bn.first,bn.has=Sn.has,bn.take=Sn.take,bn.skip=Sn.skip,bn.__toJS=Sn.__toJS;var Mn=new kn(void 0,0),qn={Sequence:me,Map:We,Vector:en,Set:hn,OrderedMap:_n,Record:pn,Range:yn,Repeat:kn,is:C,fromJS:le};return qn}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t(); <ide>\ No newline at end of file <add>function t(){function t(t,e,n,r){var i;if(r){var u=r.prototype;i=ve.create(u)}else i=t.prototype;return ve.keys(e).forEach(function(t){i[t]=e[t]}),ve.keys(n).forEach(function(e){t[e]=n[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,n,r){return ve.getPrototypeOf(e)[n].apply(t,r)}function n(t,n,r){e(t,n,"constructor",r)}function r(t){return t.value=!1,t}function i(t){t&&(t.value=!0)}function u(){}function s(t){for(var e=t.length,n=Array(e),r=0;e>r;r++)n[r]=t[r];return n}function a(t){return be.value=t,be.done=!1,be}function o(){return be.value=void 0,be.done=!0,be}function h(t,e){if(!t)throw Error(e)}function c(){return Object.create(Me)}function f(t){var e=Object.create(Ae);return e.__reversedIndices=t?t.__reversedIndices:!1,e}function l(t,e,n,r){var i=t.get?t.get(e[r],we):we;return i===we?n:++r===e.length?i:l(i,e,n,r)}function _(t,e,n){return(0===t||null!=n&&-n>=t)&&(null==e||null!=n&&e>=n)}function g(t,e){return 0>t?Math.max(0,e+t):e?Math.min(e,t):t}function v(t,e){return null==t?e:0>t?Math.max(0,e+t):e?Math.min(e,t):t}function p(t){return t}function m(t,e){return[e,t]}function y(){return!0}function d(){return this}function w(t){return(t||0)+1}function S(t,e,n,r,i){var u=t.__makeSequence();return u.__iterateUncached=function(u,s,a){var o=0,h=t.__iterate(function(t,i,s){if(e.call(n,t,i,s)){if(u(t,r?i:o,s)===!1)return!1;o++}},s,a);return i?h:o},u}function I(t){return function(){return!t.apply(this,arguments)}}function b(t){return"string"==typeof t?JSON.stringify(t):t}function k(t,e){for(var n="";e;)1&e&&(n+=t),(e>>=1)&&(t+=t);return n}function D(t,e){return t>e?1:e>t?-1:0}function M(t){h(1/0!==t,"Cannot perform this action with an infinite sequence.")}function q(t,e){var n=new Ee;return n.next=function(){var n=t.next();return n.done?n:(n.value=e(n.value),n)},n}function O(t,e,n){return n instanceof ke?A(t,e,n):n}function A(t,e,n){return new Ue(t._rootData,t._keyPath.concat(e),t._onChange,n)}function C(t,e,n){var r=t._rootData.updateIn(t._keyPath,n?We.empty():void 0,e),i=t._keyPath||[];return t._onChange&&t._onChange.call(void 0,r,t._rootData,n?i.concat(n):i),new Ue(r,t._keyPath,t._onChange) <add>}function x(t,e){return t instanceof Ue&&(t=t.deref()),e instanceof Ue&&(e=e.deref()),t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t instanceof ke?t.equals(e):!1}function E(t,e){return a(0===t||1===t?e[t]:e)}function j(t,e){return{node:t,index:0,__prev:e}}function U(t,e,n){var r=Object.create(Re);return r.length=t,r._root=e,r.__ownerID=n,r.__altered=!1,r}function W(t,e,n){var i=r(Se),u=r(Ie),s=P(t._root,t.__ownerID,0,T(e),e,n,i,u);if(!u.value)return t;var a=t.length+(i.value?n===we?-1:1:0);return t.__ownerID?(t.length=a,t._root=s,t.__altered=!0,t):s?U(a,s):We.empty()}function P(t,e,n,r,u,s,a,o){return t?t.update(e,n,r,u,s,a,o):s===we?t:(i(o),i(a),new Ne(e,r,[u,s]))}function R(t){return t.constructor===Ne||t.constructor===Ve}function z(t,e,n,r,i){if(t.hash===r)return new Ve(e,r,[t.entry,i]);var u,s=t.hash>>>n&de,a=r>>>n&de,o=s===a?[z(t,e,n+me,r,i)]:(u=new Ne(e,r,i),a>s?[t,u]:[u,t]);return new ze(e,1<<s|1<<a,o)}function J(t,e,n,r){for(var i=0,u=0,s=Array(n),a=0,o=1,h=e.length;h>a;a++,o<<=1){var c=e[a];null!=c&&a!==r&&(i|=o,s[u++]=c)}return new ze(t,i,s)}function B(t,e,n,r,i){for(var u=0,s=Array(ye),a=0;0!==n;a++,n>>>=1)s[a]=1&n?e[u++]:null;return s[r]=i,new Be(t,u+1,s)}function L(t,e,n){for(var r=[],i=0;n.length>i;i++){var u=n[i];u&&r.push(Array.isArray(u)?ke(u).fromEntrySeq():ke(u))}return K(t,e,r)}function V(t){return function(e,n){return e&&e.mergeDeepWith?e.mergeDeepWith(t,n):t?t(e,n):n}}function K(t,e,n){return 0===n.length?t:t.withMutations(function(t){for(var r=e?function(n,r){var i=t.get(r,we);t.set(r,i===we?n:e(i,n))}:function(e,n){t.set(n,e)},i=0;n.length>i;i++)n[i].forEach(r)})}function N(t,e,n,r,i){var u=e.length;if(i===u)return r(t);h(t.set,"updateIn with invalid keyPath");var s=i===u-1?n:We.empty(),a=e[i],o=t.get(a,s),c=N(o,e,n,r,i+1);return c===o?t:t.set(a,c)}function F(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function G(t,e,n,r){var i=r?t:s(t);return i[e]=n,i}function H(t,e,n,r){var i=t.length+1;if(r&&e+1===i)return t[e]=n,t;for(var u=Array(i),s=0,a=0;i>a;a++)a===e?(u[a]=n,s=-1):u[a]=t[a+s]; <add>return u}function Q(t,e,n){var r=t.length-1;if(n&&e===r)return t.pop(),t;for(var i=Array(r),u=0,s=0;r>s;s++)s===e&&(u=1),i[s]=t[s+u];return i}function T(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t&Qe;t=""+t,e="string"}if("string"===e)return t.length>Te?X(t):Y(t);if(t.hashCode&&"function"==typeof t.hashCode)return t.hashCode();throw Error("Unable to hash: "+t)}function X(t){var e=Ze[t];return null==e&&(e=Y(t),Ye===Xe&&(Ye=0,Ze={}),Ye++,Ze[t]=e),e}function Y(t){for(var e=0,n=0;t.length>n;n++)e=31*e+t.charCodeAt(n)&Qe;return e}function Z(t,e,n,r,i,u){if(t){var s,a=t.array,o=a.length-1;if(0===e)for(s=0;o>=s;s++){var h=u?o-s:s;if(a.hasOwnProperty(h)){var c=h+n;if(c>=0&&r>c&&i(a[h],c)===!1)return!1}}else{var f=1<<e,l=e-me;for(s=0;o>=s;s++){var _=u?o-s:s,g=n+_*f;if(r>g&&g+f>0){var v=a[_];if(v&&!Z(v,l,g,r,i,u))return!1}}}}return!0}function $(t,e,n,r,i){return{array:t,level:e,offset:n,max:r,index:0,__prev:i}}function te(t,e,n,r,i,u){var s=Object.create(rn);return s.length=e-t,s._origin=t,s._size=e,s._level=n,s._root=r,s._tail=i,s.__ownerID=u,s.__altered=!1,s}function ee(t,e,n){if(e>=t.length)return n===we?t:t.withMutations(function(t){ue(t,0,e+1).set(e,n)});e=ae(e,t._origin);var i=t._tail,u=t._root,s=r(Ie);return e>=oe(t._size)?i=ne(i,t.__ownerID,0,e,n,s):u=ne(u,t.__ownerID,t._level,e,n,s),s.value?t.__ownerID?(t._root=u,t._tail=i,t.__altered=!0,t):te(t._origin,t._size,t._level,u,i):t}function ne(t,e,n,r,u,s){var a,o=u===we,h=r>>>n&de,c=t&&t.array.length>h&&t.array.hasOwnProperty(h);if(o&&!c)return t;if(n>0){var f=t&&t.array[h],l=ne(f,e,n-me,r,u,s);return l===f?t:(a=re(t,e),a.array[h]=l,a)}return!o&&c&&t.array[h]===u?t:(i(s),a=re(t,e),o?delete a.array[h]:a.array[h]=u,a)}function re(t,e){return e&&t&&e===t.ownerID?t:new un(t?t.array.slice():[],e)}function ie(t,e){if(e>=oe(t._size))return t._tail;if(1<<t._level+me>e){for(var n=t._root,r=t._level;n&&r>0;)n=n.array[e>>>r&de],r-=me;return n}}function ue(t,e,n){var r=t.__ownerID||new u,i=t._origin,s=t._size,a=i+e,o=null==n?s:0>n?s+n:i+n; <add>if(a===i&&o===s)return t;if(a>=o)return t.clear();for(var h=t._level,c=t._root,f=0;0>a+f;)c=new un(c&&c.array.length?[null,c]:[],r),h+=me,f+=1<<h;f&&(a+=f,i+=f,o+=f,s+=f);for(var l=oe(s),_=oe(o);_>=1<<h+me;)c=new un(c&&c.array.length?[c]:[],r),h+=me;var g=t._tail,v=l>_?ie(t,o-1):_>l?new un([],r):g;if(g&&_>l&&s>a&&g.array.length){c=re(c,r);for(var p=c,m=h;m>me;m-=me){var y=l>>>m&de;p=p.array[y]=re(p.array[y],r)}p.array[l>>>me&de]=g}if(s>o&&(v=v&&v.removeAfter(r,0,o)),a>=_)a-=_,o-=_,h=me,c=null,v=v&&v.removeBefore(r,0,a);else if(a>i||l>_){var d,w;f=0;do d=a>>>h&de,w=_-1>>>h&de,d===w&&(d&&(f+=(1<<h)*d),h-=me,c=c&&c.array[d]);while(c&&d===w);c&&a>i&&(c=c&&c.removeBefore(r,h,a-f)),c&&l>_&&(c=c&&c.removeAfter(r,h,_-f)),f&&(a-=f,o-=f)}return t.__ownerID?(t.length=o-a,t._origin=a,t._size=o,t._level=h,t._root=c,t._tail=v,t.__altered=!0,t):te(a,o,h,c,v)}function se(t,e,n){for(var r=[],i=0;n.length>i;i++){var u=n[i];u&&r.push(ke(u))}var s=Math.max.apply(null,r.map(function(t){return t.length||0}));return s>t.length&&(t=t.setLength(s)),K(t,e,r)}function ae(t,e){return h(t>=0,"Index out of bounds"),t+e}function oe(t){return ye>t?0:t-1>>>me<<me}function he(t,e){var n=Object.create(fn);return n.length=t?t.length:0,n._map=t,n.__ownerID=e,n}function ce(t,e,n){var r=Object.create(_n.prototype);return r.length=t?t.length:0,r._map=t,r._vector=e,r.__ownerID=n,r}function fe(t,e,n){var r=Object.create(Object.getPrototypeOf(t));return r._map=e,r.__ownerID=n,r}function le(t,e){return e?_e(e,t,"",{"":t}):ge(t)}function _e(t,e,n,r){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(r,n,ke(e).map(function(n,r){return _e(t,n,r,e)})):e}function ge(t){if(t){if(Array.isArray(t))return ke(t).map(ge).toVector();if(t.constructor===Object)return ke(t).map(ge).toMap()}return t}var ve=Object,pe={};pe.createClass=t,pe.superCall=e,pe.defaultSuperCall=n;var me=5,ye=1<<me,de=ye-1,we={},Se={value:!1},Ie={value:!1},be={value:void 0,done:!1};"undefined"==typeof Symbol&&(Symbol={}),Symbol.iterator||(Symbol.iterator="@@iterator");var ke=function(t){return De.from(1===arguments.length?t:Array.prototype.slice.call(arguments)) <add>},De=ke;pe.createClass(ke,{toString:function(){return this.__toString("Seq {","}")},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e},__toStringMapper:function(t,e){return e+": "+b(t)},toJS:function(){return this.map(function(t){return t instanceof De?t.toJS():t}).__toJS()},toArray:function(){M(this.length);var t=Array(this.length||0);return this.valueSeq().forEach(function(e,n){t[n]=e}),t},toObject:function(){M(this.length);var t={};return this.forEach(function(e,n){t[n]=e}),t},toVector:function(){return M(this.length),en.from(this)},toMap:function(){return M(this.length),We.from(this)},toOrderedMap:function(){return M(this.length),_n.from(this)},toSet:function(){return M(this.length),hn.from(this)},equals:function(t){if(this===t)return!0;if(!(t instanceof De))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1;if(0===this.length&&0===t.length)return!0}return this.__deepEquals(t)},__deepEquals:function(t){var e=this.cacheResult().entrySeq().toArray(),n=0;return t.every(function(t,r){var i=e[n++];return x(r,i[0])&&x(t,i[1])})},join:function(t){t=t||",";var e="",n=!0;return this.forEach(function(r){n?(n=!1,e+=r):e+=t+r}),e},count:function(t,e){return t?this.filter(t,e).count():(null==this.length&&(this.length=this.forEach(y)),this.length)},countBy:function(t){var e=this;return _n.empty().withMutations(function(n){e.forEach(function(e,r,i){n.update(t(e,r,i),w)})})},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t.map(function(t){return De(t)})),r=this.__makeSequence();return r.length=n.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),r.__iterateUncached=function(t,e){for(var r,i=0,u=n.length-1,s=0;u>=s&&!r;s++){var a=n[e?u-s:s];i+=a.__iterate(function(e,n,i){return t(e,n,i)===!1?(r=!0,!1):void 0},e)}return i},r},reverse:function(){var t=this,e=t.__makeSequence();return e.length=t.length,e.__iterateUncached=function(e,n){return t.__iterate(e,!n)},e.reverse=function(){return t <add>},e},keySeq:function(){return this.flip().valueSeq()},valueSeq:function(){var t=this,e=f(t);return e.length=t.length,e.valueSeq=d,e.__iterateUncached=function(e,n,r){if(r&&null==this.length)return this.cacheResult().__iterate(e,n,r);var i,u=0;return r?(u=this.length-1,i=function(t,n,r){return e(t,u--,r)!==!1}):i=function(t,n,r){return e(t,u++,r)!==!1},t.__iterate(i,n),r?this.length:u},e},entrySeq:function(){var t=this;if(t._cache)return De(t._cache);var e=t.map(m).valueSeq();return e.fromEntries=function(){return t},e},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},reduce:function(t,e,n){var r=e;return this.forEach(function(e,i,u){r=t.call(n,r,e,i,u)}),r},reduceRight:function(t,e,n){return this.reverse(!0).reduce(t,e,n)},every:function(t,e){var n=!0;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?void 0:(n=!1,!1)}),n},some:function(t,e){return!this.every(I(t),e)},first:function(){return this.find(y)},last:function(){return this.findLast(y)},rest:function(){return this.slice(1)},butLast:function(){return this.slice(0,-1)},has:function(t){return this.get(t,we)!==we},get:function(t,e){return this.find(function(e,n){return x(n,t)},null,e)},getIn:function(t,e){return t&&0!==t.length?l(this,t,e,0):this},contains:function(t){return this.find(function(e){return x(e,t)},null,we)!==we},find:function(t,e,n){var r=n;return this.forEach(function(n,i,u){return t.call(e,n,i,u)?(r=n,!1):void 0}),r},findKey:function(t,e){var n;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?(n=i,!1):void 0}),n},findLast:function(t,e,n){return this.reverse(!0).find(t,e,n)},findLastKey:function(t,e){return this.reverse(!0).findKey(t,e)},flip:function(){var t=this,e=c();return e.length=t.length,e.flip=function(){return t},e.__iterateUncached=function(e,n){return t.__iterate(function(t,n,r){return e(n,t,r)!==!1},n)},e},map:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){return n.__iterate(function(n,i,u){return r(t.call(e,n,i,u),i,u)!==!1},i)},r},mapKeys:function(t,e){var n=this,r=n.__makeSequence(); <add>return r.length=n.length,r.__iterateUncached=function(r,i){return n.__iterate(function(n,i,u){return r(n,t.call(e,i,n,u),u)!==!1},i)},r},filter:function(t,e){return S(this,t,e,!0,!1)},slice:function(t,e){if(_(t,e,this.length))return this;var n=g(t,this.length),r=v(e,this.length);if(n!==n||r!==r)return this.entrySeq().slice(t,e).fromEntrySeq();var i=0===n?this:this.skip(n);return null==r||r===this.length?i:i.take(r-n)},take:function(t){var e=0,n=this.takeWhile(function(){return e++<t});return n.length=this.length&&Math.min(this.length,t),n},takeLast:function(t,e){return this.reverse(e).take(t).reverse(e)},takeWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,u){if(i)return this.cacheResult().__iterate(r,i,u);var s=0;return n.__iterate(function(n,i,u){return t.call(e,n,i,u)&&r(n,i,u)!==!1?void s++:!1},i,u),s},r},takeUntil:function(t,e,n){return this.takeWhile(I(t),e,n)},skip:function(t,e){if(0===t)return this;var n=0,r=this.skipWhile(function(){return n++<t},null,e);return r.length=this.length&&Math.max(0,this.length-t),r},skipLast:function(t,e){return this.reverse(e).skip(t).reverse(e)},skipWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,u){if(i)return this.cacheResult().__iterate(r,i,u);var s=!0,a=0;return n.__iterate(function(n,i,u){if(!s||!(s=t.call(e,n,i,u))){if(r(n,i,u)===!1)return!1;a++}},i,u),a},r},skipUntil:function(t,e,n){return this.skipWhile(I(t),e,n)},groupBy:function(t){var e=this,n=_n.empty().withMutations(function(n){e.forEach(function(e,r,i){var u=t(e,r,i),s=n.get(u,we);s===we&&(s=[],n.set(u,s)),s.push([r,e])})});return n.map(function(t){return De(t).fromEntrySeq()})},sort:function(t,e){return this.sortBy(p,t,e)},sortBy:function(t,e){e=e||D;var n=this;return De(this.entrySeq().entrySeq().toArray().sort(function(r,i){return e(t(r[1][1],r[1][0],n),t(i[1][1],i[1][0],n))||r[0]-i[0]})).fromEntrySeq().valueSeq().fromEntrySeq()},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(M(this.length),this._cache=this.entrySeq().toArray(),null==this.length&&(this.length=this._cache.length)),this <add>},__iterate:function(t,e,n){if(!this._cache)return this.__iterateUncached(t,e,n);var r=this.length-1,i=this._cache,u=this;if(e)for(var s=i.length-1;s>=0;s--){var a=i[s];if(t(a[1],n?a[0]:r-a[0],u)===!1)break}else i.every(n?function(e){return t(e[1],r-e[0],u)!==!1}:function(e){return t(e[1],e[0],u)!==!1});return this.length},__makeSequence:function(){return c()}},{from:function(t){if(t instanceof De)return t;if(!Array.isArray(t)){if(t&&t.constructor===Object)return new Ce(t);t=[t]}return new xe(t)}});var Me=ke.prototype;Me.toJSON=Me.toJS,Me.__toJS=Me.toObject,Me.inspect=Me.toSource=function(){return""+this};var qe=function(){pe.defaultSuperCall(this,Oe.prototype,arguments)},Oe=qe;pe.createClass(qe,{toString:function(){return this.__toString("Seq [","]")},toArray:function(){M(this.length);var t=Array(this.length||0);return t.length=this.forEach(function(e,n){t[n]=e}),t},fromEntrySeq:function(){var t=this,e=c();return e.length=t.length,e.entrySeq=function(){return t},e.__iterateUncached=function(e,n,r){return t.__iterate(function(t,n,r){return e(t[1],t[0],r)},n,r)},e},join:function(t){t=t||",";var e="",n=0;return this.forEach(function(r,i){var u=i-n;n=i,e+=(1===u?t:k(t,u))+r}),this.length&&this.length-1>n&&(e+=k(t,this.length-1-n)),e},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t).map(function(t){return ke(t)}),r=this.__makeSequence();return r.length=n.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),r.__iterateUncached=function(t,e,r){if(r&&!this.length)return this.cacheResult().__iterate(t,e,r);for(var i,u=0,s=r&&this.length-1,a=n.length-1,o=0;a>=o&&!i;o++){var h=n[e?a-o:o];h instanceof Oe||(h=h.valueSeq()),u+=h.__iterate(function(e,n,a){return n+=u,t(e,r?s-n:n,a)===!1?(i=!0,!1):void 0},e)}return u},r},reverse:function(t){var e=this,n=e.__makeSequence();return n.length=e.length,n.__reversedIndices=!!(t^e.__reversedIndices),n.__iterateUncached=function(n,r,i){return e.__iterate(n,!r,i^t)},n.reverse=function(n){return t===n?e:Ae.reverse.call(this,n) <add>},n},valueSeq:function(){var t=pe.superCall(this,Oe.prototype,"valueSeq",[]);return t.length=void 0,t},filter:function(t,e,n){var r=S(this,t,e,n,n);return n&&(r.length=this.length),r},indexOf:function(t){return this.findIndex(function(e){return x(e,t)})},lastIndexOf:function(t){return this.reverse(!0).indexOf(t)},findIndex:function(t,e){var n=this.findKey(t,e);return null==n?-1:n},findLastIndex:function(t,e){return this.reverse(!0).findIndex(t,e)},slice:function(t,e,n){var r=this;if(_(t,e,r.length))return r;var i=r.__makeSequence(),u=g(t,r.length),s=v(e,r.length);return i.length=r.length&&(n?r.length:s-u),i.__reversedIndices=r.__reversedIndices,i.__iterateUncached=function(i,a,o){if(a)return this.cacheResult().__iterate(i,a,o);var h=this.__reversedIndices^o;if(u!==u||s!==s||h&&null==r.length){var c=r.count();u=g(t,c),s=v(e,c)}var f=h?r.length-s:u,l=h?r.length-u:s,_=r.__iterate(function(t,e,r){return h?null!=l&&e>=l||e>=f&&i(t,n?e:e-f,r)!==!1:f>e||(null==l||l>e)&&i(t,n?e:e-f,r)!==!1},a,o);return null!=this.length?this.length:n?_:Math.max(0,_-f)},i},splice:function(t,e){for(var n=[],r=2;arguments.length>r;r++)n[r-2]=arguments[r];return 0===e&&0===n.length?this:this.slice(0,t).concat(n,this.slice(t+e))},takeWhile:function(t,e,n){var r=this,i=r.__makeSequence();return i.__iterateUncached=function(u,s,a){if(s)return this.cacheResult().__iterate(u,s,a);var o=0,h=!0,c=r.__iterate(function(n,r,i){return t.call(e,n,r,i)&&u(n,r,i)!==!1?void(o=r):(h=!1,!1)},s,a);return n?i.length:h?c:o+1},n&&(i.length=this.length),i},skipWhile:function(t,e,n){var r=this,i=r.__makeSequence();return n&&(i.length=this.length),i.__iterateUncached=function(i,u,s){if(u)return this.cacheResult().__iterate(i,u,s);var a=r.__reversedIndices^s,o=!0,h=0,c=r.__iterate(function(r,u,a){return o&&(o=t.call(e,r,u,a),o||(h=u)),o||i(r,s||n?u:u-h,a)!==!1},u,s);return n?c:a?h+1:c-h},i},groupBy:function(t,e,n){var r=this,i=_n.empty().withMutations(function(e){r.forEach(function(i,u,s){var a=t(i,u,s),o=e.get(a,we);o===we&&(o=Array(n?r.length:0),e.set(a,o)),n?o[u]=i:o.push(i) <add>})});return i.map(function(t){return ke(t)})},sortBy:function(t,e,n){var r=pe.superCall(this,Oe.prototype,"sortBy",[t,e]);return n||(r=r.valueSeq()),r.length=this.length,r},__makeSequence:function(){return f(this)}},{},ke);var Ae=qe.prototype;Ae.__toJS=Ae.toArray,Ae.__toStringMapper=b;var Ce=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};pe.createClass(Ce,{toObject:function(){return this._object},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var n=this._object,r=this._keys,i=r.length-1,u=0;i>=u;u++){var s=e?i-u:u;if(t(n[r[s]],r[s],n)===!1)break}return u}},{},ke);var xe=function(t){this._array=t,this.length=t.length};pe.createClass(xe,{toArray:function(){return this._array},__iterate:function(t,e,n){var r=this._array,i=r.length-1,u=-1;if(e){for(var s=i;s>=0;s--){if(r.hasOwnProperty(s)&&t(r[s],n?s:i-s,r)===!1)return u+1;u=s}return r.length}var a=r.every(function(e,s){return t(e,n?i-s:s,r)===!1?!1:(u=s,!0)});return a?r.length:u+1}},{},qe),xe.prototype.get=Ce.prototype.get,xe.prototype.has=Ce.prototype.has;var Ee=function(){};pe.createClass(Ee,{toString:function(){return"[Iterator]"}},{});var je=Ee.prototype;je[Symbol.iterator]=d,je.inspect=je.toSource=function(){return""+this};var Ue=function(t,e,n,r){r=r?r:t.getIn(e),this.length=r instanceof ke?r.length:null,this._rootData=t,this._keyPath=e,this._onChange=n};pe.createClass(Ue,{deref:function(t){return this._rootData.getIn(this._keyPath,t)},get:function(t,e){if(Array.isArray(t)&&0===t.length)return this;var n=this._rootData.getIn(this._keyPath.concat(t),we);return n===we?e:O(this,t,n)},set:function(t,e){return C(this,function(n){return n.set(t,e)},t)},"delete":function(t){return C(this,function(e){return e.delete(t)},t)},clear:function(){return C(this,function(t){return t.clear()})},update:function(t,e,n){return 1===arguments.length?C(this,t):C(this,function(r){return r.update(t,e,n)},t)},cursor:function(t){return Array.isArray(t)&&0===t.length?this:A(this,t) <add>},__iterate:function(t,e,n){var r=this,i=r.deref();return i&&i.__iterate?i.__iterate(function(e,n,i){return t(O(r,n,e),n,i)},e,n):0}},{},ke),Ue.prototype.getIn=Ue.prototype.get;var We=function(t){var e=Pe.empty();return t?t.constructor===Pe?t:e.merge(t):e},Pe=We;pe.createClass(We,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,T(t),t,e):e},set:function(t,e){return W(this,t,e)},"delete":function(t){return W(this,t,we)},update:function(t,e,n){return 1===arguments.length?this.updateIn([],null,t):this.updateIn([t],e,n)},updateIn:function(t,e,n){var r;return n||(r=[e,n],n=r[0],e=r[1],r),N(this,t,e,n,0)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._root=null,this.__altered=!0,this):Pe.empty()},merge:function(){return L(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return L(this,t,e)},mergeDeep:function(){return L(this,V(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return L(this,V(t),e)},cursor:function(t,e){return e||"function"!=typeof t?0===arguments.length?t=[]:Array.isArray(t)||(t=[t]):(e=t,t=[]),new Ue(this,t,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new u)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},keys:function(){return new Ge(this,0)},values:function(){return new Ge(this,1)},entries:function(){return new Ge(this,2)},__iterate:function(t,e){var n=this;if(!n._root)return 0;var r=0;return this._root.iterate(function(e){return t(e[1],e[0],n)===!1?!1:void r++},e),r},__deepEqual:function(t){var e=this;return t.every(function(t,n){return x(e.get(n,we),t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?U(this.length,this._root,t):(this.__ownerID=t,this.__altered=!1,this)}},{empty:function(){return He||(He=U(0)) <add>}},ke);var Re=We.prototype;Re[Symbol.iterator]=function(){return this.entries()},We.from=We;var ze=function(t,e,n){this.ownerID=t,this.bitmap=e,this.nodes=n},Je=ze;pe.createClass(ze,{get:function(t,e,n,r){var i=1<<(e>>>t&de),u=this.bitmap;return 0===(u&i)?r:this.nodes[F(u&i-1)].get(t+me,e,n,r)},update:function(t,e,n,r,i,u,s){var a=n>>>e&de,o=1<<a,h=this.bitmap,c=0!==(h&o);if(!c&&i===we)return this;var f=F(h&o-1),l=this.nodes,_=c?l[f]:null,g=P(_,t,e+me,n,r,i,u,s);if(g===_)return this;if(!c&&g&&l.length>=$e)return B(t,l,h,a,g);if(c&&!g&&2===l.length&&R(l[1^f]))return l[1^f];if(c&&g&&1===l.length&&R(g))return g;var v=t&&t===this.ownerID,p=c?g?h:h^o:h|o,m=c?g?G(l,f,g,v):Q(l,f,v):H(l,f,g,v);return v?(this.bitmap=p,this.nodes=m,this):new Je(t,p,m)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++)if(n[e?i-r:r].iterate(t,e)===!1)return!1}},{});var Be=function(t,e,n){this.ownerID=t,this.count=e,this.nodes=n},Le=Be;pe.createClass(Be,{get:function(t,e,n,r){var i=e>>>t&de,u=this.nodes[i];return u?u.get(t+me,e,n,r):r},update:function(t,e,n,r,i,u,s){var a=n>>>e&de,o=i===we,h=this.nodes,c=h[a];if(o&&!c)return this;var f=P(c,t,e+me,n,r,i,u,s);if(f===c)return this;var l=this.count;if(c){if(!f&&(l--,tn>l))return J(t,h,l,a)}else l++;var _=t&&t===this.ownerID,g=G(h,a,f,_);return _?(this.count=l,this.nodes=g,this):new Le(t,l,g)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++){var u=n[e?i-r:r];if(u&&u.iterate(t,e)===!1)return!1}}},{});var Ve=function(t,e,n){this.ownerID=t,this.hash=e,this.entries=n},Ke=Ve;pe.createClass(Ve,{get:function(t,e,n,r){for(var i=this.entries,u=0,s=i.length;s>u;u++)if(x(n,i[u][0]))return i[u][1];return r},update:function(t,e,n,r,u,a,o){var h=u===we;if(n!==this.hash)return h?this:(i(o),i(a),z(this,t,e,n,[r,u]));for(var c=this.entries,f=0,l=c.length;l>f&&!x(r,c[f][0]);f++);var _=l>f;if(h&&!_)return this;if(i(o),(h||!_)&&i(a),h&&2===l)return new Ne(t,this.hash,c[1^f]);var g=t&&t===this.ownerID,v=g?c:s(c);return _?h?f===l-1?v.pop():v[f]=v.pop():v[f]=[r,u]:v.push([r,u]),g?(this.entries=v,this):new Ke(t,this.hash,v) <add>},iterate:function(t,e){for(var n=this.entries,r=0,i=n.length-1;i>=r;r++)if(t(n[e?i-r:r])===!1)return!1}},{});var Ne=function(t,e,n){this.ownerID=t,this.hash=e,this.entry=n},Fe=Ne;pe.createClass(Ne,{get:function(t,e,n,r){return x(n,this.entry[0])?this.entry[1]:r},update:function(t,e,n,r,u,s,a){var o=u===we,h=x(r,this.entry[0]);return(h?u===this.entry[1]:o)?this:(i(a),o?(i(s),null):h?t&&t===this.ownerID?(this.entry[1]=u,this):new Fe(t,n,[r,u]):(i(s),z(this,t,e,n,[r,u])))},iterate:function(t){return t(this.entry)}},{});var Ge=function(t,e){this._type=e,this._stack=t._root&&j(t._root)};pe.createClass(Ge,{next:function(){for(var t=this._type,e=this._stack;e;){var n=e.node,r=e.index++;if(n.entry){if(0===r)return E(t,n.entry)}else if(n.entries){if(n.entries.length>r)return E(t,n.entries[r])}else if(n.nodes.length>r){var i=n.nodes[r];if(i){if(i.entry)return E(t,i.entry);e=this._stack=j(i,e)}continue}e=this._stack=this._stack.__prev}return o()}},{},Ee);var He,Qe=2147483647,Te=16,Xe=255,Ye=0,Ze={},$e=ye/2,tn=ye/4,en=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return nn.from(t)},nn=en;pe.createClass(en,{toString:function(){return this.__toString("Vector [","]")},get:function(t,e){if(t=ae(t,this._origin),t>=this._size)return e;var n=ie(this,t),r=t&de;return n&&(void 0===e||n.array.hasOwnProperty(r))?n.array[r]:e},first:function(){return this.get(0)},last:function(){return this.get(this.length?this.length-1:0)},set:function(t,e){return ee(this,t,e)},"delete":function(t){return ee(this,t,we)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=this._origin=this._size=0,this._level=me,this._root=this._tail=null,this.__altered=!0,this):nn.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(n){ue(n,0,e+t.length);for(var r=0;t.length>r;r++)n.set(e+r,t[r])})},pop:function(){return ue(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){ue(e,-t.length);for(var n=0;t.length>n;n++)e.set(n,t[n])})},shift:function(){return ue(this,1) <add>},merge:function(){return se(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return se(this,t,e)},mergeDeep:function(){return se(this,V(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return se(this,V(t),e)},setLength:function(t){return ue(this,0,t)},slice:function(t,e,n){var r=pe.superCall(this,nn.prototype,"slice",[t,e,n]);if(!n&&r!==this){var i=this,u=i.length;r.toVector=function(){return ue(i,0>t?Math.max(0,u+t):u?Math.min(u,t):t,null==e?u:0>e?Math.max(0,u+e):u?Math.min(u,e):e)}}return r},keys:function(t){return new an(this,0,t)},values:function(t){return new an(this,1,t)},entries:function(t){return new an(this,2,t)},__iterate:function(t,e,n){var r=this,i=0,u=r.length-1;n^=e;var s,a=function(e,s){return t(e,n?u-s:s,r)===!1?!1:(i=s,!0)},o=oe(this._size);return s=e?Z(this._tail,0,o-this._origin,this._size-this._origin,a,e)&&Z(this._root,this._level,-this._origin,o-this._origin,a,e):Z(this._root,this._level,-this._origin,o-this._origin,a,e)&&Z(this._tail,0,o-this._origin,this._size-this._origin,a,e),(s?u:e?u-i:i)+1},__deepEquals:function(t){var e=this.entries(!0);return t.every(function(t,n){var r=e.next().value;return r&&r[0]===n&&x(r[1],t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?te(this._origin,this._size,this._level,this._root,this._tail,t):(this.__ownerID=t,this)}},{empty:function(){return on||(on=te(0,0,me))},from:function(t){if(!t||0===t.length)return nn.empty();if(t.constructor===nn)return t;var e=Array.isArray(t);return t.length>0&&ye>t.length?te(0,t.length,me,null,new un(e?s(t):ke(t).toArray())):(e||(t=ke(t),t instanceof qe||(t=t.valueSeq())),nn.empty().merge(t))}},qe);var rn=en.prototype;rn[Symbol.iterator]=rn.values,rn.update=Re.update,rn.updateIn=Re.updateIn,rn.cursor=Re.cursor,rn.withMutations=Re.withMutations,rn.asMutable=Re.asMutable,rn.asImmutable=Re.asImmutable,rn.wasAltered=Re.wasAltered;var un=function(t,e){this.array=t,this.ownerID=e},sn=un;pe.createClass(un,{removeBefore:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this; <add>var r=n>>>e&de;if(r>=this.array.length)return new sn([],t);var i,u=0===r;if(e>0){var s=this.array[r];if(i=s&&s.removeBefore(t,e-me,n),i===s&&u)return this}if(u&&!i)return this;var a=re(this,t);if(!u)for(var o=0;r>o;o++)delete a.array[o];return i&&(a.array[r]=i),a},removeAfter:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n-1>>>e&de;if(r>=this.array.length)return this;var i,u=r===this.array.length-1;if(e>0){var s=this.array[r];if(i=s&&s.removeAfter(t,e-me,n),i===s&&u)return this}if(u&&!i)return this;var a=re(this,t);return u||(a.array.length=r+1),i&&(a.array[r]=i),a}},{});var an=function(t,e,n){var r=oe(t._size);this._type=e,this._sparse=n,this._stack=$(t._root&&t._root.array,t._level,-t._origin,r-t._origin,$(t._tail&&t._tail.array,0,r-t._origin,t._size-t._origin))};pe.createClass(an,{next:function(){for(var t=this._type,e=this._sparse,n=this._stack;n;){var r=n.array,i=n.index++,u=1<<n.level,s=n.offset+i*u;if(ye>i&&s>-u&&n.max>s){var h=r&&r[i];if(0===n.level){if(!e||h||r&&r.length>i&&r.hasOwnProperty(i))return a(0===t?s:1===t?h:[s,h])}else(!e||h)&&(this._stack=n=$(h&&h.array,n.level-me,s,n.max,n))}else n=this._stack=this._stack.__prev}return o()}},{},Ee);var on,hn=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return cn.from(t)},cn=hn;pe.createClass(hn,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map.has(t)},get:function(t,e){return this.has(t)?t:e},add:function(t){var e=this._map.set(t,null);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:he(e)},"delete":function(t){var e=this._map.delete(t);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:0===e.length?cn.empty():he(e)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this):cn.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var n=0;t.length>n;n++)ke(t[n]).forEach(function(t){return e.add(t)})})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e]; <add>if(0===t.length)return this;t=t.map(function(t){return ke(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.every(function(t){return t.contains(n)})||e.delete(n)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ke(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.some(function(t){return t.contains(n)})&&e.delete(n)})})},isSubset:function(t){return t=ke(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=ke(t),t.every(function(t){return e.contains(t)})},wasAltered:function(){return this._map.wasAltered()},values:function(){return this._map.keys()},entries:function(){return q(this.values(),function(t){return[t,t]})},__iterate:function(t,e){var n=this;return this._map.__iterate(function(e,r){return t(r,r,n)},e)},__deepEquals:function(t){return this._map.equals(t._map)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?he(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return ln||(ln=he(We.empty()))},from:function(t){var e=cn.empty();return t?t.constructor===cn?t:e.union(t):e},fromKeys:function(t){return cn.from(ke(t).flip())}},ke);var fn=hn.prototype;fn[Symbol.iterator]=fn.keys=fn.values,fn.contains=fn.has,fn.mergeDeep=fn.merge=fn.union,fn.mergeDeepWith=fn.mergeWith=function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return this.merge.apply(this,t)},fn.withMutations=Re.withMutations,fn.asMutable=Re.asMutable,fn.asImmutable=Re.asImmutable,fn.__toJS=Ae.__toJS,fn.__toStringMapper=Ae.__toStringMapper;var ln,_n=function(t){var e=gn.empty();return t?t.constructor===gn?t:e.merge(t):e},gn=_n;pe.createClass(_n,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){var n=this._map.get(t);return null!=n?this._vector.get(n)[1]:e},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this._vector.clear(),this):gn.empty() <add>},set:function(t,e){var n=this._map.get(t),r=null!=n,i=r?this._map:this._map.set(t,this._vector.length),u=r?this._vector.set(n,[t,e]):this._vector.push([t,e]);return this.__ownerID?(this.length=i.length,this._map=i,this._vector=u,this):u===this._vector?this:ce(i,u)},"delete":function(t){var e=this._map.get(t);if(null==e)return this;var n=this._map.delete(t),r=this._vector.delete(e);return this.__ownerID?(this.length=n.length,this._map=n,this._vector=r,this):0===n.length?gn.empty():ce(n,r)},wasAltered:function(){return this._map.wasAltered()||this._vector.wasAltered()},keys:function(){return q(this.entries(),function(t){return t[0]})},values:function(){return q(this.entries(),function(t){return t[1]})},entries:function(){return this._vector.values(!0)},__iterate:function(t,e){return this._vector.fromEntrySeq().__iterate(t,e)},__deepEqual:function(t){var e=this.entries();return t.every(function(t,n){var r=e.next().value;return r&&x(r[0],n)&&x(r[1],t)})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),n=this._vector.__ensureOwner(t);return t?ce(e,n,t):(this.__ownerID=t,this._map=e,this._vector=n,this)}},{empty:function(){return vn||(vn=ce(We.empty(),en.empty()))}},We),_n.from=_n;var vn,pn=function(t,e){var n=function(t){this._map=We(t)};t=ke(t);var r=n.prototype=Object.create(yn);r.constructor=n,r._name=e,r._defaultValues=t;var i=Object.keys(t);return n.prototype.length=i.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(n.prototype,e,{get:function(){return this.get(e)},set:function(t){h(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}),n},mn=pn;pe.createClass(pn,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;Object.getPrototypeOf(this).constructor;return mn._empty||(mn._empty=fe(this,We.empty())) <add>},set:function(t,e){if(null==t||!this.has(t))return this;var n=this._map.set(t,e);return this.__ownerID||n===this._map?this:fe(this,n)},"delete":function(t){if(null==t||!this.has(t))return this;var e=this._map.delete(t);return this.__ownerID||e===this._map?this:fe(this,e)},keys:function(){return this._map.keys()},values:function(){return this._map.values()},entries:function(){return this._map.entries()},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var n=this;return this._defaultValues.map(function(t,e){return n.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?fe(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},ke);var yn=pn.prototype;yn.__deepEqual=Re.__deepEqual,yn[Symbol.iterator]=Re[Symbol.iterator],yn.merge=Re.merge,yn.mergeWith=Re.mergeWith,yn.mergeDeep=Re.mergeDeep,yn.mergeDeepWith=Re.mergeDeepWith,yn.update=Re.update,yn.updateIn=Re.updateIn,yn.cursor=Re.cursor,yn.withMutations=Re.withMutations,yn.asMutable=Re.asMutable,yn.asImmutable=Re.asImmutable;var dn=function(t,e,n){return this instanceof wn?(h(0!==n,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&In?In:(n=null==n?1:Math.abs(n),t>e&&(n=-n),this._start=t,this._end=e,this._step=n,void(this.length=Math.max(0,Math.ceil((e-t)/n-1)+1)))):new wn(t,e,n)},wn=dn;pe.createClass(dn,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return h(t>=0,"Index out of bounds"),this.length>t},get:function(t,e){return h(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._start+t*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e,n){return _(t,e,this.length)?this:n?pe.superCall(this,wn.prototype,"slice",[t,e,n]):(t=g(t,this.length),e=v(e,this.length),t>=e?In:new wn(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start; <add>if(e%this._step===0){var n=e/this._step;if(n>=0&&this.length>n)return n}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,t)},skip:function(t,e){return e?pe.superCall(this,wn.prototype,"skip",[t]):this.slice(t)},__iterate:function(t,e,n){for(var r=e^n,i=this.length-1,u=this._step,s=e?this._start+i*u:this._start,a=0;i>=a&&t(s,r?i-a:a,this)!==!1;a++)s+=e?-u:u;return r?this.length:a},__deepEquals:function(t){return this._start===t._start&&this._end===t._end&&this._step===t._step}},{},qe);var Sn=dn.prototype;Sn.__toJS=Sn.toArray,Sn.first=rn.first,Sn.last=rn.last;var In=dn(0,0),bn=function(t,e){return 0===e&&Mn?Mn:this instanceof kn?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new kn(t,e)},kn=bn;pe.createClass(bn,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return h(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._value:e},first:function(){return this._value},contains:function(t){return x(this._value,t)},slice:function(t,e,n){if(n)return pe.superCall(this,kn.prototype,"slice",[t,e,n]);var r=this.length;return t=0>t?Math.max(0,r+t):Math.min(r,t),e=null==e?r:e>0?Math.min(r,e):Math.max(0,r+e),e>t?new kn(this._value,e-t):Mn},reverse:function(t){return t?pe.superCall(this,kn.prototype,"reverse",[t]):this},indexOf:function(t){return x(this._value,t)?0:-1},lastIndexOf:function(t){return x(this._value,t)?this.length:-1},__iterate:function(t,e,n){var r=e^n;h(!r||1/0>this.length,"Cannot access end of infinite range.");for(var i=this.length-1,u=0;i>=u&&t(this._value,r?i-u:u,this)!==!1;u++);return r?this.length:u},__deepEquals:function(t){return x(this._value,t._value)}},{},qe);var Dn=bn.prototype;Dn.last=Dn.first,Dn.has=Sn.has,Dn.take=Sn.take,Dn.skip=Sn.skip,Dn.__toJS=Sn.__toJS;var Mn=new bn(void 0,0),qn={Sequence:ke,Map:We,Vector:en,Set:hn,OrderedMap:_n,Record:pn,Range:dn,Repeat:bn,is:x,fromJS:le};return qn}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t(); <ide><path>src/Map.js <ide> import "is" <ide> import "invariant" <ide> import "Cursor" <ide> import "TrieUtils" <add>import "Symbol" <ide> /* global Sequence, SequenceIterator, is, invariant, Cursor, <ide> SHIFT, SIZE, MASK, NOT_SET, CHANGE_LENGTH, DID_ALTER, OwnerID, <del> MakeRef, SetRef, arrCopy, iteratorValue, iteratorDone */ <add> MakeRef, SetRef, arrCopy, iteratorValue, iteratorDone, Symbol */ <ide> /* exported Map, MapPrototype */ <ide> <ide> <ide> class Map extends Sequence { <ide> } <ide> <ide> var MapPrototype = Map.prototype; <del>MapPrototype['@@iterator'] = function() { return this.entries() }; <add>MapPrototype[Symbol.iterator] = function() { return this.entries() }; <ide> <ide> Map.from = Map; <ide> <ide><path>src/Record.js <ide> import "Sequence" <ide> import "Map" <ide> import "invariant" <del>/* global Sequence, Map, MapPrototype, invariant */ <add>import "Symbol" <add>/* global Sequence, Map, MapPrototype, invariant, Symbol */ <ide> /* exported Record */ <ide> <ide> <ide> class Record extends Sequence { <ide> <ide> var RecordPrototype = Record.prototype; <ide> RecordPrototype.__deepEqual = MapPrototype.__deepEqual; <del>RecordPrototype['iterator']; <add>RecordPrototype[Symbol.iterator] = MapPrototype[Symbol.iterator]; <ide> RecordPrototype.merge = MapPrototype.merge; <ide> RecordPrototype.mergeWith = MapPrototype.mergeWith; <ide> RecordPrototype.mergeDeep = MapPrototype.mergeDeep; <ide><path>src/Sequence.js <ide> */ <ide> <ide> /* Sequence has implicit lazy dependencies */ <del>/* global is, Map, OrderedMap, Vector, Set, NOT_SET, invariant */ <add>import "TrieUtils" <add>import "invariant" <add>import "Symbol" <add>/* global is, Map, OrderedMap, Vector, Set, NOT_SET, invariant, Symbol */ <ide> /* exported Sequence, IndexedSequence, SequenceIterator, iteratorMapper */ <ide> <ide> <ide> class SequenceIterator { <ide> } <ide> <ide> var SequenceIteratorPrototype = SequenceIterator.prototype; <add>SequenceIteratorPrototype[Symbol.iterator] = returnThis; <ide> SequenceIteratorPrototype.inspect = <ide> SequenceIteratorPrototype.toSource = function () { return this.toString(); } <ide> <ide><path>src/Set.js <ide> <ide> import "Sequence" <ide> import "Map" <add>import "Symbol" <ide> /* global Sequence, IndexedSequencePrototype, iteratorMapper, <del> Map, MapPrototype */ <add> Map, MapPrototype, Symbol */ <ide> /* exported Set */ <ide> <ide> <ide> class Set extends Sequence { <ide> } <ide> <ide> var SetPrototype = Set.prototype; <del>SetPrototype['@@iterator'] = SetPrototype.keys = SetPrototype.values; <add>SetPrototype[Symbol.iterator] = SetPrototype.keys = SetPrototype.values; <ide> SetPrototype.contains = SetPrototype.has; <ide> SetPrototype.mergeDeep = SetPrototype.merge = SetPrototype.union; <ide> SetPrototype.mergeDeepWith = SetPrototype.mergeWith = function(merger, ...seqs) { <ide><path>src/Symbol.js <add>/* global Symbol */ <add> <add>if (typeof Symbol === 'undefined') { <add> Symbol = {}; // jshint ignore: line <add>} <add> <add>if (!Symbol.iterator) { <add> Symbol.iterator = '@@iterator'; <add>} <ide><path>src/Vector.js <ide> import "is" <ide> import "invariant" <ide> import "Map" <ide> import "TrieUtils" <add>import "Symbol" <ide> /* global Sequence, IndexedSequence, SequenceIterator, is, invariant, <ide> MapPrototype, mergeIntoCollectionWith, deepMerger, <ide> SHIFT, SIZE, MASK, NOT_SET, DID_ALTER, OwnerID, MakeRef, SetRef, <del> arrCopy, iteratorValue, iteratorDone */ <add> arrCopy, iteratorValue, iteratorDone, Symbol */ <ide> /* exported Vector, VectorPrototype */ <ide> <ide> <ide> class Vector extends IndexedSequence { <ide> } <ide> <ide> var VectorPrototype = Vector.prototype; <del>VectorPrototype['@@iterator'] = VectorPrototype.values; <add>VectorPrototype[Symbol.iterator] = VectorPrototype.values; <ide> VectorPrototype.update = MapPrototype.update; <ide> VectorPrototype.updateIn = MapPrototype.updateIn; <ide> VectorPrototype.cursor = MapPrototype.cursor;
8
PHP
PHP
remove additional is_callable checks
4dc98d47f5b85be3f4a01bb4580f7e6947d0e8d0
<ide><path>src/Controller/Controller.php <ide> use Cake\Utility\MergeVariablesTrait; <ide> use Cake\View\ViewVarsTrait; <ide> use LogicException; <del>use ReflectionClass; <add>use ReflectionMethod; <ide> use ReflectionException; <ide> <ide> /** <ide> public function invokeAction() { <ide> )); <ide> } <ide> $callable = [$this, $request->params['action']]; <del> if (!is_callable($callable)) { <del> throw new MissingActionException(array( <del> 'controller' => $this->name . "Controller", <del> 'action' => $request->params['action'], <del> 'prefix' => isset($request->params['prefix']) ? $request->params['prefix'] : '', <del> 'plugin' => $request->params['plugin'], <del> )); <del> } <ide> return call_user_func_array($callable, $request->params['pass']); <ide> } <ide> <ide> public function paginate($object = null) { <ide> * and allows all public methods on all subclasses of this class. <ide> * <ide> * @param string $action The action to check. <del> * @return boolean Whether or not the method is accesible from a URL. <add> * @return bool Whether or not the method is accesible from a URL. <ide> */ <ide> public function isAction($action) { <del> $reflection = new ReflectionClass($this); <ide> try { <del> $method = $reflection->getMethod($action); <add> $method = new ReflectionMethod($this, $action); <ide> } catch (\ReflectionException $e) { <ide> return false; <ide> }
1
Javascript
Javascript
use a dispatch table for performance
6735b578886df38b80d489fa38b17835c366490e
<ide><path>lib/serialization/BinaryMiddleware.js <ide> const SerializerMiddleware = require("./SerializerMiddleware"); <ide> /** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ <ide> /** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ <ide> <add>/* eslint-disable no-loop-func */ <add> <ide> /* <ide> Format: <ide> <ide> class BinaryMiddleware extends SerializerMiddleware { <ide> n--; <ide> } <ide> }; <del> <del> /** @type {DeserializedType} */ <del> const result = []; <del> while (currentBuffer !== null) { <del> if (typeof currentBuffer === "function") { <del> result.push( <del> SerializerMiddleware.deserializeLazy(currentBuffer, data => <del> this._deserialize(data, context) <del> ) <del> ); <del> currentDataItem++; <del> currentBuffer = <del> currentDataItem < data.length ? data[currentDataItem] : null; <del> currentIsBuffer = Buffer.isBuffer(currentBuffer); <del> continue; <del> } <del> const header = readU8(); <add> const dispatchTable = Array.from({ length: 256 }).map((_, header) => { <ide> switch (header) { <del> case LAZY_HEADER: { <del> const count = readU32(); <del> const start = result.length - count; <del> const data = /** @type {SerializedType} */ (result.slice(start)); <del> result.length = start; <del> result.push( <del> SerializerMiddleware.createLazy( <del> memorize(() => this._deserialize(data, context)), <del> this, <del> undefined, <del> data <del> ) <del> ); <del> break; <del> } <del> case BUFFER_HEADER: { <del> const len = readU32(); <del> result.push(read(len)); <del> break; <del> } <add> case LAZY_HEADER: <add> return () => { <add> const count = readU32(); <add> const start = result.length - count; <add> const data = /** @type {SerializedType} */ (result.slice(start)); <add> result.length = start; <add> result.push( <add> SerializerMiddleware.createLazy( <add> memorize(() => this._deserialize(data, context)), <add> this, <add> undefined, <add> data <add> ) <add> ); <add> }; <add> case BUFFER_HEADER: <add> return () => { <add> const len = readU32(); <add> result.push(read(len)); <add> }; <ide> case TRUE_HEADER: <del> result.push(true); <del> break; <add> return () => result.push(true); <ide> case FALSE_HEADER: <del> result.push(false); <del> break; <add> return () => result.push(false); <ide> case NULL3_HEADER: <del> result.push(null); <del> // falls through <add> return () => result.push(null, null, null); <ide> case NULL2_HEADER: <del> result.push(null); <del> // falls through <add> return () => result.push(null, null); <ide> case NULL_HEADER: <del> result.push(null); <del> break; <add> return () => result.push(null); <ide> case NULL_AND_TRUE_HEADER: <del> result.push(null); <del> result.push(true); <del> break; <add> return () => result.push(null, true); <ide> case NULL_AND_FALSE_HEADER: <del> result.push(null); <del> result.push(false); <del> break; <add> return () => result.push(null, false); <ide> case NULL_AND_I8_HEADER: <del> result.push(null); <del> if (currentBuffer) { <del> result.push(currentBuffer.readInt8(currentPosition)); <del> currentPosition += I8_SIZE; <del> checkOverflow(); <del> } else { <del> result.push(read(I8_SIZE).readInt8(0)); <del> } <del> break; <add> return () => { <add> if (currentBuffer) { <add> result.push( <add> null, <add> /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) <add> ); <add> currentPosition += I8_SIZE; <add> checkOverflow(); <add> } else { <add> result.push(null, read(I8_SIZE).readInt8(0)); <add> } <add> }; <ide> case NULL_AND_I32_HEADER: <del> result.push(null); <del> if (isInCurrentBuffer(I32_SIZE)) { <del> result.push(currentBuffer.readInt32LE(currentPosition)); <del> currentPosition += I32_SIZE; <del> checkOverflow(); <del> } else { <del> result.push(read(I32_SIZE).readInt32LE(0)); <del> } <del> break; <del> case NULLS8_HEADER: { <del> const len = readU8() + 4; <del> for (let i = 0; i < len; i++) { <add> return () => { <ide> result.push(null); <del> } <del> break; <del> } <del> case NULLS32_HEADER: { <del> const len = readU32() + 260; <del> for (let i = 0; i < len; i++) { <del> result.push(null); <del> } <del> break; <del> } <del> case BOOLEANS_HEADER: { <del> const innerHeader = readU8(); <del> if ((innerHeader & 0xf0) === 0) { <del> readBits(innerHeader, 3); <del> } else if ((innerHeader & 0xe0) === 0) { <del> readBits(innerHeader, 4); <del> } else if ((innerHeader & 0xc0) === 0) { <del> readBits(innerHeader, 5); <del> } else if ((innerHeader & 0x80) === 0) { <del> readBits(innerHeader, 6); <del> } else if (innerHeader !== 0xff) { <del> let count = (innerHeader & 0x7f) + 7; <del> while (count > 8) { <del> readBits(readU8(), 8); <del> count -= 8; <add> if (isInCurrentBuffer(I32_SIZE)) { <add> result.push( <add> /** @type {Buffer} */ (currentBuffer).readInt32LE( <add> currentPosition <add> ) <add> ); <add> currentPosition += I32_SIZE; <add> checkOverflow(); <add> } else { <add> result.push(read(I32_SIZE).readInt32LE(0)); <ide> } <del> readBits(readU8(), count); <del> } else { <del> let count = readU32(); <del> while (count > 8) { <del> readBits(readU8(), 8); <del> count -= 8; <add> }; <add> case NULLS8_HEADER: <add> return () => { <add> const len = readU8() + 4; <add> for (let i = 0; i < len; i++) { <add> result.push(null); <ide> } <del> readBits(readU8(), count); <del> } <del> break; <del> } <del> case STRING_HEADER: { <del> const len = readU32(); <del> if (isInCurrentBuffer(len)) { <del> result.push( <del> currentBuffer.toString( <del> undefined, <del> currentPosition, <del> currentPosition + len <del> ) <del> ); <del> currentPosition += len; <del> checkOverflow(); <del> } else { <del> const buf = read(len); <del> result.push(buf.toString()); <del> } <del> break; <del> } <del> default: <del> if (header <= 10) { <del> result.push(header); <del> } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) { <del> const len = header & SHORT_STRING_LENGTH_MASK; <del> if (len === 0) { <del> result.push(""); <del> } else if (isInCurrentBuffer(len)) { <add> }; <add> case NULLS32_HEADER: <add> return () => { <add> const len = readU32() + 260; <add> for (let i = 0; i < len; i++) { <add> result.push(null); <add> } <add> }; <add> case BOOLEANS_HEADER: <add> return () => { <add> const innerHeader = readU8(); <add> if ((innerHeader & 0xf0) === 0) { <add> readBits(innerHeader, 3); <add> } else if ((innerHeader & 0xe0) === 0) { <add> readBits(innerHeader, 4); <add> } else if ((innerHeader & 0xc0) === 0) { <add> readBits(innerHeader, 5); <add> } else if ((innerHeader & 0x80) === 0) { <add> readBits(innerHeader, 6); <add> } else if (innerHeader !== 0xff) { <add> let count = (innerHeader & 0x7f) + 7; <add> while (count > 8) { <add> readBits(readU8(), 8); <add> count -= 8; <add> } <add> readBits(readU8(), count); <add> } else { <add> let count = readU32(); <add> while (count > 8) { <add> readBits(readU8(), 8); <add> count -= 8; <add> } <add> readBits(readU8(), count); <add> } <add> }; <add> case STRING_HEADER: <add> return () => { <add> const len = readU32(); <add> if (isInCurrentBuffer(len)) { <ide> result.push( <ide> currentBuffer.toString( <del> "latin1", <add> undefined, <ide> currentPosition, <ide> currentPosition + len <ide> ) <ide> ); <ide> currentPosition += len; <ide> checkOverflow(); <ide> } else { <del> const buf = read(len); <del> result.push(buf.toString("latin1")); <add> result.push(read(len).toString()); <ide> } <del> } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) { <del> const len = (header & NUMBERS_COUNT_MASK) + 1; <del> const need = F64_SIZE * len; <del> if (isInCurrentBuffer(need)) { <del> for (let i = 0; i < len; i++) { <del> result.push(currentBuffer.readDoubleLE(currentPosition)); <del> currentPosition += F64_SIZE; <del> } <add> }; <add> case SHORT_STRING_HEADER: <add> return () => result.push(""); <add> case SHORT_STRING_HEADER | 1: <add> return () => { <add> if (currentBuffer) { <add> result.push( <add> currentBuffer.toString( <add> "latin1", <add> currentPosition, <add> currentPosition + 1 <add> ) <add> ); <add> currentPosition++; <ide> checkOverflow(); <ide> } else { <del> const buf = read(need); <del> for (let i = 0; i < len; i++) { <del> result.push(buf.readDoubleLE(i * F64_SIZE)); <del> } <add> result.push(read(1).toString("latin1")); <ide> } <del> } else if ((header & NUMBERS_HEADER_MASK) === I32_HEADER) { <del> const len = (header & NUMBERS_COUNT_MASK) + 1; <del> const need = I32_SIZE * len; <del> if (isInCurrentBuffer(need)) { <del> for (let i = 0; i < len; i++) { <del> result.push(currentBuffer.readInt32LE(currentPosition)); <del> currentPosition += I32_SIZE; <del> } <add> }; <add> case I8_HEADER: <add> return () => { <add> if (currentBuffer) { <add> result.push( <add> /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) <add> ); <add> currentPosition++; <ide> checkOverflow(); <ide> } else { <del> const buf = read(need); <del> for (let i = 0; i < len; i++) { <del> result.push(buf.readInt32LE(i * I32_SIZE)); <del> } <add> result.push(read(1).readInt8(0)); <ide> } <del> } else if ((header & NUMBERS_HEADER_MASK) === I8_HEADER) { <add> }; <add> default: <add> if (header <= 10) { <add> return () => result.push(header); <add> } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) { <add> const len = header & SHORT_STRING_LENGTH_MASK; <add> return () => { <add> if (isInCurrentBuffer(len)) { <add> result.push( <add> currentBuffer.toString( <add> "latin1", <add> currentPosition, <add> currentPosition + len <add> ) <add> ); <add> currentPosition += len; <add> checkOverflow(); <add> } else { <add> result.push(read(len).toString("latin1")); <add> } <add> }; <add> } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) { <ide> const len = (header & NUMBERS_COUNT_MASK) + 1; <del> const need = I8_SIZE * len; <del> if (isInCurrentBuffer(need)) { <del> for (let i = 0; i < len; i++) { <del> result.push(currentBuffer.readInt8(currentPosition)); <del> currentPosition += I8_SIZE; <add> return () => { <add> const need = F64_SIZE * len; <add> if (isInCurrentBuffer(need)) { <add> for (let i = 0; i < len; i++) { <add> result.push( <add> /** @type {Buffer} */ (currentBuffer).readDoubleLE( <add> currentPosition <add> ) <add> ); <add> currentPosition += F64_SIZE; <add> } <add> checkOverflow(); <add> } else { <add> const buf = read(need); <add> for (let i = 0; i < len; i++) { <add> result.push(buf.readDoubleLE(i * F64_SIZE)); <add> } <ide> } <del> checkOverflow(); <del> } else { <del> const buf = read(need); <del> for (let i = 0; i < len; i++) { <del> result.push(buf.readInt8(i * I8_SIZE)); <add> }; <add> } else if ((header & NUMBERS_HEADER_MASK) === I32_HEADER) { <add> const len = (header & NUMBERS_COUNT_MASK) + 1; <add> return () => { <add> const need = I32_SIZE * len; <add> if (isInCurrentBuffer(need)) { <add> for (let i = 0; i < len; i++) { <add> result.push( <add> /** @type {Buffer} */ (currentBuffer).readInt32LE( <add> currentPosition <add> ) <add> ); <add> currentPosition += I32_SIZE; <add> } <add> checkOverflow(); <add> } else { <add> const buf = read(need); <add> for (let i = 0; i < len; i++) { <add> result.push(buf.readInt32LE(i * I32_SIZE)); <add> } <ide> } <del> } <add> }; <add> } else if ((header & NUMBERS_HEADER_MASK) === I8_HEADER) { <add> const len = (header & NUMBERS_COUNT_MASK) + 1; <add> return () => { <add> const need = I8_SIZE * len; <add> if (isInCurrentBuffer(need)) { <add> for (let i = 0; i < len; i++) { <add> result.push( <add> /** @type {Buffer} */ (currentBuffer).readInt8( <add> currentPosition <add> ) <add> ); <add> currentPosition += I8_SIZE; <add> } <add> checkOverflow(); <add> } else { <add> const buf = read(need); <add> for (let i = 0; i < len; i++) { <add> result.push(buf.readInt8(i * I8_SIZE)); <add> } <add> } <add> }; <ide> } else { <del> throw new Error(`Unexpected header byte 0x${header.toString(16)}`); <add> return () => { <add> throw new Error( <add> `Unexpected header byte 0x${header.toString(16)}` <add> ); <add> }; <ide> } <del> break; <ide> } <add> }); <add> <add> /** @type {DeserializedType} */ <add> const result = []; <add> while (currentBuffer !== null) { <add> if (typeof currentBuffer === "function") { <add> result.push( <add> SerializerMiddleware.deserializeLazy(currentBuffer, data => <add> this._deserialize(data, context) <add> ) <add> ); <add> currentDataItem++; <add> currentBuffer = <add> currentDataItem < data.length ? data[currentDataItem] : null; <add> currentIsBuffer = Buffer.isBuffer(currentBuffer); <add> continue; <add> } <add> const header = readU8(); <add> dispatchTable[header](); <ide> } <ide> return result; <ide> }
1
Text
Text
create security.md for github security policy page
0a9842a705b1574b2553dea409bec0c6b05e9c9f
<ide><path>SECURITY.md <add># Reporting security issues <add> <add>The Moby maintainers take security seriously. If you discover a security issue, please bring it to their attention right away! <add> <add>### Reporting a Vulnerability <add> <add>Please **DO NOT** file a public issue, instead send your report privately to security@docker.com. <add> <add>Security reports are greatly appreciated and we will publicly thank you for it. We also like to send gifts—if you're into schwag, make sure to let us know. We currently do not offer a paid security bounty program, but are not ruling it out in the future.
1
Python
Python
use sha-256 instead of sha-1
dda61caf191ee69da9d944039cbb07fad5705a02
<ide><path>tools/cythonize.py <ide> def process_tempita_pxd(fromfile, tofile): <ide> # Hash db <ide> # <ide> def load_hashes(filename): <del> # Return { filename : (sha1 of input, sha1 of output) } <add> # Return { filename : (sha256 of input, sha256 of output) } <ide> if os.path.isfile(filename): <ide> hashes = {} <ide> with open(filename, 'r') as f: <ide> def save_hashes(hash_db, filename): <ide> for key, value in sorted(hash_db.items()): <ide> f.write("%s %s %s\n" % (key, value[0], value[1])) <ide> <del>def sha1_of_file(filename): <del> h = hashlib.sha1() <add>def sha256_of_file(filename): <add> h = hashlib.sha256() <ide> with open(filename, "rb") as f: <ide> h.update(f.read()) <ide> return h.hexdigest() <ide> def normpath(path): <ide> return path <ide> <ide> def get_hash(frompath, topath): <del> from_hash = sha1_of_file(frompath) <del> to_hash = sha1_of_file(topath) if os.path.exists(topath) else None <add> from_hash = sha256_of_file(frompath) <add> to_hash = sha256_of_file(topath) if os.path.exists(topath) else None <ide> return (from_hash, to_hash) <ide> <ide> def process(path, fromfile, tofile, processor_function, hash_db):
1
Java
Java
fix exception in jetty10requestupgradestrategy
7067461d711f9b830386761494fa0fdee02a025d
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/upgrade/Jetty10RequestUpgradeStrategy.java <ide> /* <del> * Copyright 2002-2021 the original author or authors. <add> * Copyright 2002-2022 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public WebSocketCreatorInterceptor( <ide> public Object invoke(@NonNull MethodInvocation invocation) { <ide> if (this.protocol != null) { <ide> ReflectionUtils.invokeMethod( <del> setAcceptedSubProtocol, invocation.getArguments()[2], this.protocol); <add> setAcceptedSubProtocol, invocation.getArguments()[1], this.protocol); <ide> } <ide> return this.adapter; <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/jetty/Jetty10RequestUpgradeStrategy.java <ide> /* <del> * Copyright 2002-2021 the original author or authors. <add> * Copyright 2002-2022 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public WebSocketCreatorInterceptor( <ide> public Object invoke(@NonNull MethodInvocation invocation) { <ide> if (this.protocol != null) { <ide> ReflectionUtils.invokeMethod( <del> setAcceptedSubProtocol, invocation.getArguments()[2], this.protocol); <add> setAcceptedSubProtocol, invocation.getArguments()[1], this.protocol); <ide> } <ide> return this.adapter; <ide> }
2
Ruby
Ruby
make arel nodes more invertable
3ebcbe4015e1035214d140144415f77e59ff2389
<ide><path>activerecord/lib/arel/nodes/binary.rb <ide> def fetch_attribute <ide> end <ide> <ide> class Between < Binary; include FetchAttribute; end <del> class NotIn < Binary; include FetchAttribute; end <del> class GreaterThan < Binary; include FetchAttribute; end <del> class GreaterThanOrEqual < Binary; include FetchAttribute; end <del> class NotEqual < Binary; include FetchAttribute; end <del> class LessThan < Binary; include FetchAttribute; end <del> class LessThanOrEqual < Binary; include FetchAttribute; end <add> <add> class GreaterThan < Binary <add> include FetchAttribute <add> <add> def invert <add> Arel::Nodes::LessThanOrEqual.new(left, right) <add> end <add> end <add> <add> class GreaterThanOrEqual < Binary <add> include FetchAttribute <add> <add> def invert <add> Arel::Nodes::LessThan.new(left, right) <add> end <add> end <add> <add> class LessThan < Binary <add> include FetchAttribute <add> <add> def invert <add> Arel::Nodes::GreaterThanOrEqual.new(left, right) <add> end <add> end <add> <add> class LessThanOrEqual < Binary <add> include FetchAttribute <add> <add> def invert <add> Arel::Nodes::GreaterThan.new(left, right) <add> end <add> end <add> <add> class NotEqual < Binary <add> include FetchAttribute <add> <add> def invert <add> Arel::Nodes::Equality.new(left, right) <add> end <add> end <add> <add> class NotIn < Binary <add> include FetchAttribute <add> <add> def invert <add> Arel::Nodes::In.new(left, right) <add> end <add> end <ide> <ide> class Or < Binary <ide> def fetch_attribute(&block) <ide><path>activerecord/test/cases/relation/merging_test.rb <ide> def test_merge_not_in_clause <ide> assert_equal [david], Author.where(id: mary).merge(non_mary_and_bob, rewhere: true) <ide> end <ide> <add> def test_merge_not_range_clause <add> david, mary, bob = authors(:david, :mary, :bob) <add> <add> less_than_bob = Author.where.not(id: bob.id..Float::INFINITY).order(:id) <add> <add> assert_equal [david, mary], less_than_bob <add> <add> assert_deprecated do <add> assert_equal [david], Author.where(id: david).merge(less_than_bob) <add> end <add> assert_equal [david, mary], Author.where(id: david).merge(less_than_bob, rewhere: true) <add> <add> assert_deprecated do <add> assert_equal [mary], Author.where(id: mary).merge(less_than_bob) <add> end <add> assert_equal [david, mary], Author.where(id: mary).merge(less_than_bob, rewhere: true) <add> end <add> <ide> def test_merge_doesnt_duplicate_same_clauses <ide> david, mary, bob = authors(:david, :mary, :bob) <ide> <ide><path>activerecord/test/cases/relation/where_clause_test.rb <ide> class WhereClauseTest < ActiveRecord::TestCase <ide> test "invert replaces each part of the predicate with its inverse" do <ide> original = WhereClause.new([ <ide> table["id"].in([1, 2, 3]), <add> table["id"].not_in([1, 2, 3]), <ide> table["id"].eq(1), <add> table["id"].not_eq(2), <add> table["id"].gt(1), <add> table["id"].gteq(2), <add> table["id"].lt(1), <add> table["id"].lteq(2), <ide> table["id"].is_not_distinct_from(1), <ide> table["id"].is_distinct_from(2), <ide> "sql literal" <ide> ]) <ide> expected = WhereClause.new([ <ide> table["id"].not_in([1, 2, 3]), <add> table["id"].in([1, 2, 3]), <ide> table["id"].not_eq(1), <add> table["id"].eq(2), <add> table["id"].lteq(1), <add> table["id"].lt(2), <add> table["id"].gteq(1), <add> table["id"].gt(2), <ide> table["id"].is_distinct_from(1), <ide> table["id"].is_not_distinct_from(2), <ide> Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new("sql literal"))
3
Javascript
Javascript
prevent unhandledpromiserejection if shell errors
a59f53a603306777fc6f949d84ce85f09bba4e4c
<ide><path>packages/react-dom/src/server/ReactDOMFizzServerBrowser.js <ide> function renderToReadableStream( <ide> resolve(stream); <ide> } <ide> function onShellError(error: mixed) { <add> // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`. <add> // However, `allReady` will be rejected by `onFatalError` as well. <add> // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`. <add> allReady.catch(() => {}); <ide> reject(error); <ide> } <ide> const request = createRequest(
1
Mixed
Text
add a new option dm.min_free_space
2e222f69b3486cf20039525a882ae4153b52f92c
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> var ( <ide> // We retry device removal so many a times that even error messages <ide> // will fill up console during normal operation. So only log Fatal <ide> // messages by default. <del> logLevel = devicemapper.LogLevelFatal <del> driverDeferredRemovalSupport = false <del> enableDeferredRemoval = false <del> enableDeferredDeletion = false <del> userBaseSize = false <add> logLevel = devicemapper.LogLevelFatal <add> driverDeferredRemovalSupport = false <add> enableDeferredRemoval = false <add> enableDeferredDeletion = false <add> userBaseSize = false <add> defaultMinFreeSpacePercent uint32 = 10 <ide> ) <ide> <ide> const deviceSetMetaFile string = "deviceset-metadata" <ide> type DeviceSet struct { <ide> deletionWorkerTicker *time.Ticker <ide> uidMaps []idtools.IDMap <ide> gidMaps []idtools.IDMap <add> minFreeSpacePercent uint32 //min free space percentage in thinpool <ide> } <ide> <ide> // DiskUsage contains information about disk usage and is used when reporting Status of a device. <ide> func (devices *DeviceSet) getNextFreeDeviceID() (int, error) { <ide> return 0, fmt.Errorf("devmapper: Unable to find a free device ID") <ide> } <ide> <add>func (devices *DeviceSet) poolHasFreeSpace() error { <add> if devices.minFreeSpacePercent == 0 { <add> return nil <add> } <add> <add> _, _, dataUsed, dataTotal, metadataUsed, metadataTotal, err := devices.poolStatus() <add> if err != nil { <add> return err <add> } <add> <add> minFreeData := (dataTotal * uint64(devices.minFreeSpacePercent)) / 100 <add> if minFreeData < 1 { <add> minFreeData = 1 <add> } <add> dataFree := dataTotal - dataUsed <add> if dataFree < minFreeData { <add> return fmt.Errorf("devmapper: Thin Pool has %v free data blocks which is less than minimum required %v free data blocks. Create more free space in thin pool or use dm.min_free_space option to change behavior", (dataTotal - dataUsed), minFreeData) <add> } <add> <add> minFreeMetadata := (metadataTotal * uint64(devices.minFreeSpacePercent)) / 100 <add> if minFreeMetadata < 1 { <add> minFreeData = 1 <add> } <add> <add> metadataFree := metadataTotal - metadataUsed <add> if metadataFree < minFreeMetadata { <add> return fmt.Errorf("devmapper: Thin Pool has %v free metadata blocks which is less than minimum required %v free metadata blocks. Create more free metadata space in thin pool or use dm.min_free_space option to change behavior", (metadataTotal - metadataUsed), minFreeMetadata) <add> } <add> <add> return nil <add>} <add> <ide> func (devices *DeviceSet) createRegisterDevice(hash string) (*devInfo, error) { <ide> devices.Lock() <ide> defer devices.Unlock() <ide> func (devices *DeviceSet) createRegisterDevice(hash string) (*devInfo, error) { <ide> } <ide> <ide> func (devices *DeviceSet) createRegisterSnapDevice(hash string, baseInfo *devInfo) error { <add> if err := devices.poolHasFreeSpace(); err != nil { <add> return err <add> } <add> <ide> deviceID, err := devices.getNextFreeDeviceID() <ide> if err != nil { <ide> return err <ide> func NewDeviceSet(root string, doInit bool, options []string, uidMaps, gidMaps [ <ide> deletionWorkerTicker: time.NewTicker(time.Second * 30), <ide> uidMaps: uidMaps, <ide> gidMaps: gidMaps, <add> minFreeSpacePercent: defaultMinFreeSpacePercent, <ide> } <ide> <ide> foundBlkDiscard := false <ide> func NewDeviceSet(root string, doInit bool, options []string, uidMaps, gidMaps [ <ide> return nil, err <ide> } <ide> <add> case "dm.min_free_space": <add> if !strings.HasSuffix(val, "%") { <add> return nil, fmt.Errorf("devmapper: Option dm.min_free_space requires %% suffix") <add> } <add> <add> valstring := strings.TrimSuffix(val, "%") <add> minFreeSpacePercent, err := strconv.ParseUint(valstring, 10, 32) <add> if err != nil { <add> return nil, err <add> } <add> <add> if minFreeSpacePercent >= 100 { <add> return nil, fmt.Errorf("devmapper: Invalid value %v for option dm.min_free_space", val) <add> } <add> <add> devices.minFreeSpacePercent = uint32(minFreeSpacePercent) <ide> default: <ide> return nil, fmt.Errorf("devmapper: Unknown option %s\n", key) <ide> } <ide><path>docs/reference/commandline/daemon.md <ide> options for `zfs` start with `zfs`. <ide> when unintentional leaking of mount point happens across multiple mount <ide> namespaces. <ide> <add>* `dm.min_free_space` <add> <add> Specifies the min free space percent in thin pool require for new device <add> creation to succeed. This check applies to both free data space as well <add> as free metadata space. Valid values are from 0% - 99%. Value 0% disables <add> free space checking logic. If user does not specify a value for this optoin, <add> then default value for this option is 10%. <add> <add> Whenever a new thin pool device is created (during docker pull or <add> during container creation), docker will check minimum free space is <add> available as specified by this parameter. If that is not the case, then <add> device creation will fail and docker operation will fail. <add> <add> One will have to create more free space in thin pool to recover from the <add> error. Either delete some of the images and containers from thin pool and <add> create free space or add more storage to thin pool. <add> <add> For lvm thin pool, one can add more storage to volume group container thin <add> pool and that should automatically resolve it. If loop devices are being <add> used, then stop docker, grow the size of loop files and restart docker and <add> that should resolve the issue. <add> <add> Example use: <add> <add> $ docker daemon --storage-opt dm.min_free_space_percent=10% <add> <ide> Currently supported options of `zfs`: <ide> <ide> * `zfs.fsname` <ide><path>man/docker-daemon.8.md <ide> By default docker will pick up the zfs filesystem where docker graph <ide> <ide> Example use: `docker daemon -s zfs --storage-opt zfs.fsname=zroot/docker` <ide> <add>#### dm.min_free_space <add> <add>Specifies the min free space percent in thin pool require for new device <add>creation to succeed. This check applies to both free data space as well <add>as free metadata space. Valid values are from 0% - 99%. Value 0% disables <add>free space checking logic. If user does not specify a value for this optoin, <add>then default value for this option is 10%. <add> <add>Whenever a new thin pool device is created (during docker pull or <add>during container creation), docker will check minimum free space is <add>available as specified by this parameter. If that is not the case, then <add>device creation will fail and docker operation will fail. <add> <add>One will have to create more free space in thin pool to recover from the <add>error. Either delete some of the images and containers from thin pool and <add>create free space or add more storage to thin pool. <add> <add>For lvm thin pool, one can add more storage to volume group container thin <add>pool and that should automatically resolve it. If loop devices are being <add>used, then stop docker, grow the size of loop files and restart docker and <add>that should resolve the issue. <add> <add>Example use: `docker daemon --storage-opt dm.min_free_space_percent=10%` <add> <ide> # CLUSTER STORE OPTIONS <ide> <ide> The daemon uses libkv to advertise
3
Javascript
Javascript
use pre-bundled elements inspector
9a93a3cba47722a590a8912a5ace1c479eb4178a
<ide><path>Libraries/Devtools/setupDevtools.js <ide> function setupDevtools() { <ide> var messageListeners = []; <ide> var closeListeners = []; <del> var ws = new window.WebSocket('ws://localhost:8081/devtools'); <add> var ws = new window.WebSocket('ws://localhost:8097/devtools'); <ide> // this is accessed by the eval'd backend code <ide> var FOR_BACKEND = { // eslint-disable-line no-unused-vars <ide> resolveRNStyle: require('flattenStyle'), <ide> function setupDevtools() { <ide> }, <ide> }; <ide> ws.onclose = () => { <del> console.warn('devtools socket closed'); <add> setTimeout(setupDevtools, 200); <ide> closeListeners.forEach(fn => fn()); <ide> }; <ide> ws.onerror = error => { <del> console.warn('devtools socket errored', error); <add> setTimeout(setupDevtools, 200); <ide> closeListeners.forEach(fn => fn()); <ide> }; <ide> ws.onopen = function () { <ide> function setupDevtools() { <ide> // FOR_BACKEND is used by the eval'd code <ide> eval(text); // eslint-disable-line no-eval <ide> } catch (e) { <del> console.error('Failed to eval' + e.message); <add> console.error('Failed to eval: ' + e.message); <ide> return; <ide> } <ide> window.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
1
Javascript
Javascript
remove tracking of app height
d86eba998b73d349b18545c28d938d1281b9af31
<ide><path>common/app/redux/index.js <ide> import { createSelector } from 'reselect'; <ide> import fetchUserEpic from './fetch-user-epic.js'; <ide> import updateMyCurrentChallengeEpic from './update-my-challenge-epic.js'; <ide> import fetchChallengesEpic from './fetch-challenges-epic.js'; <del>import navSizeEpic from './nav-size-epic.js'; <ide> <ide> import { createFilesMetaCreator } from '../files'; <ide> import { updateThemeMetacreator, entitiesSelector } from '../entities'; <ide> import { themes, invertTheme } from '../../utils/themes.js'; <ide> export const epics = [ <ide> fetchUserEpic, <ide> fetchChallengesEpic, <del> updateMyCurrentChallengeEpic, <del> navSizeEpic <add> updateMyCurrentChallengeEpic <ide> ]; <ide> <ide> export const types = createTypes([ <ide><path>common/app/redux/nav-size-epic.js <del>import { ofType } from 'redux-epic'; <del> <del>import { types } from './'; <del> <del>import { updateNavHeight } from '../Panes/redux'; <del> <del>export default function navSizeEpic(actions, _, { document }) { <del> return actions::ofType(types.appMounted) <del> .map(() => { <del> const navbar = document.getElementById('navbar'); <del> return updateNavHeight(navbar.clientHeight || 50); <del> }); <del>}
2