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 |
|---|---|---|---|---|---|
Javascript | Javascript | allow missing source in sourcemap #954 | 348c38b3f971b28254411cbda946a35283657fa8 | <ide><path>lib/ModuleFilenameHelpers.js
<ide> function asRegExp(test) {
<ide> }
<ide>
<ide> ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFilenameTemplate, requestShortener) {
<add> if(!module) module = "";
<ide> if(typeof module === "string") {
<ide> var shortIdentifier = requestShortener.shorten(module);
<ide> var identifier = shortIdentifier;
<ide><path>lib/SourceMapDevToolPlugin.js
<ide> SourceMapDevToolPlugin.prototype.apply = function(compiler) {
<ide> }, function(ai, bi) {
<ide> var a = allModules[ai];
<ide> var b = allModules[bi];
<del> a = typeof a === "string" ? a : a.identifier();
<del> b = typeof b === "string" ? b : b.identifier();
<add> a = !a ? "" : typeof a === "string" ? a : a.identifier();
<add> b = !b ? "" : typeof b === "string" ? b : b.identifier();
<ide> return a.length - b.length;
<ide> });
<ide> allModuleFilenames = ModuleFilenameHelpers.replaceDuplicates(allModuleFilenames, function(filename, i, n) { | 2 |
Mixed | Text | add tag support to journald logging driver, closes | 5a3351883b254d3690e9dcc5b89293bcee474493 | <ide><path>daemon/logger/journald/journald.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/coreos/go-systemd/journal"
<ide> "github.com/docker/docker/daemon/logger"
<add> "github.com/docker/docker/daemon/logger/loggerutils"
<ide> )
<ide>
<ide> const name = "journald"
<ide> func New(ctx logger.Context) (logger.Logger, error) {
<ide> name = name[1:]
<ide> }
<ide>
<add> // parse log tag
<add> tag, err := loggerutils.ParseLogTag(ctx, "")
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<ide> vars := map[string]string{
<ide> "CONTAINER_ID": ctx.ContainerID[:12],
<ide> "CONTAINER_ID_FULL": ctx.ContainerID,
<ide> "CONTAINER_NAME": name,
<add> "CONTAINER_TAG": tag,
<ide> }
<ide> extraAttrs := ctx.ExtraAttributes(strings.ToTitle)
<ide> for k, v := range extraAttrs {
<ide> func validateLogOpt(cfg map[string]string) error {
<ide> switch key {
<ide> case "labels":
<ide> case "env":
<add> case "tag":
<ide> default:
<ide> return fmt.Errorf("unknown log opt '%s' for journald log driver", key)
<ide> }
<ide><path>docs/admin/logging/journald.md
<ide> driver stores the following metadata in the journal with each message:
<ide> | `CONTAINER_ID` | The container ID truncated to 12 characters. |
<ide> | `CONTAINER_ID_FULL` | The full 64-character container ID. |
<ide> | `CONTAINER_NAME` | The container name at the time it was started. If you use `docker rename` to rename a container, the new name is not reflected in the journal entries. |
<add>| `CONTAINER_TAG` | The container tag ([log tag option documentation](log_tags.md)). |
<ide>
<ide> ## Usage
<ide>
<ide> You can set the logging driver for a specific container by using the
<ide> Users can use the `--log-opt NAME=VALUE` flag to specify additional
<ide> journald logging driver options.
<ide>
<add>### tag
<add>
<add>Specify template to set `CONTAINER_TAG` value in journald logs. Refer to
<add>[log tag option documentation](log_tags.md) for customizing the log tag format.
<add>
<ide> ### labels and env
<ide>
<ide> The `labels` and `env` options each take a comma-separated list of keys. If there is collision between `label` and `env` keys, the value of the `env` takes precedence. Both options add additional metadata in the journal with each message.
<ide><path>docs/admin/logging/log_tags.md
<ide> aliases = ["/engine/reference/logging/log_tags/"]
<ide> title = "Log tags for logging driver"
<ide> description = "Describes how to format tags for."
<del>keywords = ["docker, logging, driver, syslog, Fluentd, gelf"]
<add>keywords = ["docker, logging, driver, syslog, Fluentd, gelf, journald"]
<ide> [menu.main]
<ide> parent = "smn_logging"
<ide> weight = 1 | 3 |
Ruby | Ruby | improve host checks to instead check domains | 38ae98cbcd2690142506aa86b34a769175e53c41 | <ide><path>Library/Homebrew/livecheck/livecheck.rb
<ide> def checkable_urls(formula_or_cask)
<ide> sig { params(url: String).returns(String) }
<ide> def preprocess_url(url)
<ide> begin
<del> uri = URI.parse url
<del> rescue URI::InvalidURIError
<add> uri = Addressable::URI.parse url
<add> rescue Addressable::URI::InvalidURIError
<ide> return url
<ide> end
<ide>
<ide> host = uri.host
<add> domain = uri.domain
<ide> path = uri.path
<ide> return url if host.nil? || path.nil?
<ide>
<del> host = "github.com" if host == "github.s3.amazonaws.com"
<add> domain = host = "github.com" if host == "github.s3.amazonaws.com"
<ide> path = path.delete_prefix("/").delete_suffix(".git")
<ide> scheme = uri.scheme
<ide>
<del> if host.end_with?("github.com")
<add> if domain == "github.com"
<ide> return url if path.match? %r{/releases/latest/?$}
<ide>
<ide> owner, repo = path.delete_prefix("downloads/").split("/")
<ide> url = "#{scheme}://#{host}/#{owner}/#{repo}.git"
<del> elsif host.end_with?(*GITEA_INSTANCES)
<add> elsif GITEA_INSTANCES.include?(domain)
<ide> return url if path.match? %r{/releases/latest/?$}
<ide>
<ide> owner, repo = path.split("/")
<ide> url = "#{scheme}://#{host}/#{owner}/#{repo}.git"
<del> elsif host.end_with?(*GOGS_INSTANCES)
<add> elsif GOGS_INSTANCES.include?(domain)
<ide> owner, repo = path.split("/")
<ide> url = "#{scheme}://#{host}/#{owner}/#{repo}.git"
<ide> # sourcehut
<del> elsif host.end_with?("git.sr.ht")
<add> elsif host == "git.sr.ht"
<ide> owner, repo = path.split("/")
<ide> url = "#{scheme}://#{host}/#{owner}/#{repo}"
<ide> # GitLab (gitlab.com or self-hosted) | 1 |
Text | Text | add changes for 1.6.7 | 07e475137ec39604bca4a8be07a1a605a4fd6e7d | <ide><path>CHANGELOG.md
<add><a name="1.6.7"></a>
<add># 1.6.7 imperial-backstroke (2017-11-24)
<add>
<add>
<add>## Bug Fixes
<add>- **$compile:** sanitize special chars in directive name
<add> ([c4003f](https://github.com/angular/angular.js/commit/c4003fd03489f876b646f06838f4edb576bacf6f),
<add> [#16314](https://github.com/angular/angular.js/issues/16314),
<add> [#16278](https://github.com/angular/angular.js/issues/16278))
<add>- **$location:** do not decode forward slashes in the path in HTML5 mode
<add> ([e06ebf](https://github.com/angular/angular.js/commit/e06ebfdbb558544602fe9da4d7d98045a965f468),
<add> [#16312](https://github.com/angular/angular.js/issues/16312))
<add>- **sanitizeUri:** sanitize URIs that contain IDEOGRAPHIC SPACE chars
<add> ([ddeb1d](https://github.com/angular/angular.js/commit/ddeb1df15a23de93eb95dbe202e83e93673e1c4e),
<add> [#16288](https://github.com/angular/angular.js/issues/16288))
<add>- **$rootScope:** fix potential memory leak when removing scope listeners
<add> ([358a69](https://github.com/angular/angular.js/commit/358a69fa8b89b251ee44e523458d6c7f40b92b2d),
<add> [#16135](https://github.com/angular/angular.js/issues/16135),
<add> [#16161](https://github.com/angular/angular.js/issues/16161))
<add>- **http:** do not allow encoded callback params in jsonp requests
<add> ([569e90](https://github.com/angular/angular.js/commit/569e906a5818271416ad0b749be2f58dc34938bd))
<add>- **ngMock:** pass unexpected request failures in `$httpBackend` to the error handler
<add> ([1555a4](https://github.com/angular/angular.js/commit/1555a4911ad5360c145c0ddc8ec6c4bf9a381c13),
<add> [#16150](https://github.com/angular/angular.js/issues/16150),
<add> [#15855](https://github.com/angular/angular.js/issues/15855))
<add>- **ngAnimate:** don't close transitions when child transitions close
<add> ([1391e9](https://github.com/angular/angular.js/commit/1391e99c7f73795180b792af21ad4402f96e225d),
<add> [#16210](https://github.com/angular/angular.js/issues/16210))
<add>- **ngMock.browserTrigger:** add 'bubbles' to Transition/Animation Event
<add> ([7a5f06](https://github.com/angular/angular.js/commit/7a5f06d55d123a39bb7b030667fb1ab672939598))
<add>
<add>
<add>## New Features
<add>- **$sanitize, $compileProvider, linky:** add support for the "sftp" protocol in links
<add> ([a675ea](https://github.com/angular/angular.js/commit/a675ea034366fbb0fcf0d73fed65216aa99bce11),
<add> [#16102](https://github.com/angular/angular.js/issues/16102))
<add>- **ngModel.NgModelController:** expose $processModelValue to run model -> view pipeline
<add> ([145194](https://github.com/angular/angular.js/commit/14519488ce9218aa891d34e89fc3271fd4ed0f04),
<add> [#3407](https://github.com/angular/angular.js/issues/3407),
<add> [#10764](https://github.com/angular/angular.js/issues/10764),
<add> [#16237](https://github.com/angular/angular.js/issues/16237))
<add>- **$injector:** ability to load new modules after bootstrapping
<add> ([6e78fe](https://github.com/angular/angular.js/commit/6e78fee73258bb0ae36414f9db2e8734273e481b))
<add>
<add>
<add>## Performance Improvements
<add>- **jqLite:**
<add> - avoid setting class attribute when not changed
<add> ([9c95f6](https://github.com/angular/angular.js/commit/9c95f6d5e00ee7e054aabb3e363f5bfb3b7b4103))
<add> - avoid repeated add/removeAttribute in jqLiteRemoveClass
<add> ([cab9eb](https://github.com/angular/angular.js/commit/cab9ebfd5a02e897f802bf6321b8471e4843c5d3),
<add> [#16078](https://github.com/angular/angular.js/issues/16078),
<add> [#16131](https://github.com/angular/angular.js/issues/16131))
<add>
<add>
<ide> <a name="1.6.6"></a>
<ide> # 1.6.6 interdimensional-cable (2017-08-18)
<ide> | 1 |
Python | Python | mark the failing tests as xfail | 659732ade7a506bded4347a5828b9fc95377669f | <ide><path>numpy/linalg/tests/test_linalg.py
<ide> def test_types(self, dtype):
<ide> x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
<ide> assert_equal(linalg.solve(x, x).dtype, dtype)
<ide>
<add> @pytest.mark.xfail(sys.platform == 'cygwin',
<add> reason="Consistently fails on CI.")
<add> def test_sq_cases(self):
<add> super().test_sq_cases()
<add>
<ide> def test_0_size(self):
<ide> class ArraySubclass(np.ndarray):
<ide> pass
<ide> def test_types(self, dtype):
<ide> x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
<ide> assert_equal(linalg.inv(x).dtype, dtype)
<ide>
<add> @pytest.mark.xfail(sys.platform == 'cygwin',
<add> reason="Consistently fails on CI.")
<add> def test_sq_cases(self):
<add> super().test_sq_cases()
<add>
<ide> def test_0_size(self):
<ide> # Check that all kinds of 0-sized arrays work
<ide> class ArraySubclass(np.ndarray):
<ide> def test_stacked_inputs(self, outer_size, size, dt):
<ide> class TestCholesky:
<ide> # TODO: are there no other tests for cholesky?
<ide>
<del> def test_basic_property(self):
<add> @pytest.mark.xfail(sys.platform == 'cygwin',
<add> reason="Consistently fails in CI")
<add> @pytest.mark.parametrize('shape', [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)])
<add> @pytest.mark.parametrize('dtype', (np.float32, np.float64, np.complex64, np.complex128))
<add> def test_basic_property(self, shape, dtype):
<ide> # Check A = L L^H
<del> shapes = [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
<del> dtypes = (np.float32, np.float64, np.complex64, np.complex128)
<del>
<del> for shape, dtype in itertools.product(shapes, dtypes):
<del> np.random.seed(1)
<del> a = np.random.randn(*shape)
<del> if np.issubdtype(dtype, np.complexfloating):
<del> a = a + 1j*np.random.randn(*shape)
<add> np.random.seed(1)
<add> a = np.random.randn(*shape)
<add> if np.issubdtype(dtype, np.complexfloating):
<add> a = a + 1j*np.random.randn(*shape)
<ide>
<del> t = list(range(len(shape)))
<del> t[-2:] = -1, -2
<add> t = list(range(len(shape)))
<add> t[-2:] = -1, -2
<ide>
<del> a = np.matmul(a.transpose(t).conj(), a)
<del> a = np.asarray(a, dtype=dtype)
<add> a = np.matmul(a.transpose(t).conj(), a)
<add> a = np.asarray(a, dtype=dtype)
<ide>
<del> c = np.linalg.cholesky(a)
<add> c = np.linalg.cholesky(a)
<ide>
<del> b = np.matmul(c, c.transpose(t).conj())
<del> assert_allclose(b, a,
<del> err_msg=f'{shape} {dtype}\n{a}\n{c}',
<del> atol=500 * a.shape[0] * np.finfo(dtype).eps)
<add> b = np.matmul(c, c.transpose(t).conj())
<add> assert_allclose(b, a,
<add> err_msg=f'{shape} {dtype}\n{a}\n{c}',
<add> atol=500 * a.shape[0] * np.finfo(dtype).eps)
<ide>
<ide> def test_0_size(self):
<ide> class ArraySubclass(np.ndarray):
<ide> def test_non_square_handling(self, a, axes):
<ide> b = np.ones(a.shape[:2])
<ide> linalg.tensorsolve(a, b, axes=axes)
<ide>
<add> @pytest.mark.xfail(sys.platform == 'cygwin',
<add> reason="Consistently fails on CI")
<ide> @pytest.mark.parametrize("shape",
<ide> [(2, 3, 6), (3, 4, 4, 3), (0, 3, 3, 0)],
<ide> ) | 1 |
Javascript | Javascript | remove dependency to util | 7977aeb21def68c6a20534bc3eeee76192e1d20e | <ide><path>src/locale/el.js
<ide> //! author : Aggelos Karalias : https://github.com/mehiel
<ide>
<ide> import moment from '../moment';
<del>import isFunction from '../lib/utils/is-function';
<add>
<add>function isFunction(input) {
<add> return (
<add> (typeof Function !== 'undefined' && input instanceof Function) ||
<add> Object.prototype.toString.call(input) === '[object Function]'
<add> );
<add>}
<ide>
<ide> export default moment.defineLocale('el', {
<ide> monthsNominativeEl: 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split( | 1 |
Javascript | Javascript | fix missing readmes on core package detail pages | 138966224a0314b388c6ef624dcb6343b60a1535 | <ide><path>script/lib/include-path-in-packaged-app.js
<ide> const EXCLUDE_REGEXPS_SOURCES = [
<ide> // Ignore node_module files we won't need at runtime
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + '_*te?sts?_*' + escapeRegExp(path.sep),
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'examples?' + escapeRegExp(path.sep),
<del> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.md$',
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.d\\.ts$',
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.js\\.map$',
<ide> '.*' + escapeRegExp(path.sep) + 'test.*\\.html$' | 1 |
Ruby | Ruby | allow multiple macos requirements | 9eac310468b60a4ab4ef02aeda9e513337bbb198 | <ide><path>Library/Homebrew/requirement.rb
<ide> def ==(other)
<ide> alias eql? ==
<ide>
<ide> def hash
<del> [name, tags].hash
<add> [self.class, name, tags].hash
<ide> end
<ide>
<ide> sig { returns(String) }
<ide><path>Library/Homebrew/requirements/macos_requirement.rb
<ide> def message(type: :formula)
<ide> end
<ide> end
<ide>
<add> def ==(other)
<add> super(other) && comparator == other.comparator && version == other.version
<add> end
<add> alias eql? ==
<add>
<add> def hash
<add> [super, comparator, version].hash
<add> end
<add>
<ide> sig { returns(String) }
<ide> def inspect
<ide> "#<#{self.class.name}: version#{@comparator}#{@version.to_s.inspect} #{tags.inspect}>" | 2 |
Python | Python | freeze flaxwav2vec2 feature encoder | 3c4fbc616f74120c3900d07c772b7d2d9c7a53dd | <ide><path>src/transformers/models/wav2vec2/modeling_flax_wav2vec2.py
<ide> class FlaxWav2Vec2FeatureEncoder(nn.Module):
<ide> def setup(self):
<ide> self.conv_layers = FlaxConvLayersCollection(self.config, dtype=self.dtype)
<ide>
<del> def __call__(self, input_values):
<add> def __call__(self, input_values, freeze_feature_encoder=False):
<ide> hidden_states = input_values[:, :, None]
<ide> hidden_states = self.conv_layers(hidden_states)
<add> if freeze_feature_encoder:
<add> hidden_states = jax.lax.stop_gradient(hidden_states)
<ide> return hidden_states
<ide>
<ide>
<ide> def __call__(
<ide> train: bool = False,
<ide> output_attentions: Optional[bool] = None,
<ide> output_hidden_states: Optional[bool] = None,
<add> freeze_feature_encoder: bool = False,
<ide> return_dict: Optional[bool] = None,
<ide> ):
<ide> output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
<ide> def __call__(
<ide> not train,
<ide> output_attentions,
<ide> output_hidden_states,
<add> freeze_feature_encoder,
<ide> return_dict,
<ide> rngs=rngs,
<ide> )
<ide> def __call__(
<ide> deterministic=True,
<ide> output_attentions=None,
<ide> output_hidden_states=None,
<add> freeze_feature_encoder=False,
<ide> return_dict=None,
<ide> ):
<del> extract_features = self.feature_extractor(input_values)
<add> extract_features = self.feature_extractor(input_values, freeze_feature_encoder=freeze_feature_encoder)
<ide>
<ide> # make sure that no loss is computed on padded inputs
<ide> if attention_mask is not None:
<ide> def __call__(
<ide> deterministic=True,
<ide> output_attentions=None,
<ide> output_hidden_states=None,
<add> freeze_feature_encoder=False,
<ide> return_dict=None,
<ide> ):
<ide> outputs = self.wav2vec2(
<ide> def __call__(
<ide> deterministic=deterministic,
<ide> output_attentions=output_attentions,
<ide> output_hidden_states=output_hidden_states,
<add> freeze_feature_encoder=freeze_feature_encoder,
<ide> return_dict=return_dict,
<ide> )
<ide>
<ide> def __call__(
<ide> deterministic: bool = True,
<ide> output_attentions=None,
<ide> output_hidden_states=None,
<add> freeze_feature_enocder=False,
<ide> return_dict=None,
<ide> ):
<ide> r"""
<ide> def __call__(
<ide> output_hidden_states=output_hidden_states,
<ide> mask_time_indices=mask_time_indices,
<ide> deterministic=deterministic,
<add> freeze_feature_encoder=freeze_feature_enocder,
<ide> return_dict=return_dict,
<ide> )
<ide>
<ide> def __call__(
<ide> train: bool = False,
<ide> output_attentions: Optional[bool] = None,
<ide> output_hidden_states: Optional[bool] = None,
<add> freeze_feature_encoder: bool = False,
<ide> return_dict: Optional[bool] = None,
<ide> ):
<ide> output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
<ide> def __call__(
<ide> not train,
<ide> output_attentions,
<ide> output_hidden_states,
<add> freeze_feature_encoder,
<ide> return_dict,
<ide> rngs=rngs,
<ide> )
<ide><path>tests/wav2vec2/test_modeling_flax_wav2vec2.py
<ide> def model_jitted(input_values, attention_mask=None, **kwargs):
<ide>
<ide> self.assertEqual(jitted_output.shape, output.shape)
<ide>
<add> def test_freeze_feature_encoder(self):
<add> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<add>
<add> input_values = inputs_dict["input_values"]
<add> attention_mask = inputs_dict["attention_mask"]
<add>
<add> model = FlaxWav2Vec2ForPreTraining(config)
<add>
<add> outputs = model(
<add> input_values,
<add> attention_mask=attention_mask,
<add> freeze_feature_encoder=False,
<add> )
<add>
<add> outputs_frozen = model(
<add> input_values,
<add> attention_mask=attention_mask,
<add> freeze_feature_encoder=True,
<add> )
<add>
<add> # dummy loss function
<add> def compute_loss(projected_states, projected_quantized_states, epsilon=1e-8):
<add> # compute cosine similarity of projected and projected_quantized states
<add> cosine_sim = optax.cosine_similarity(projected_states, projected_quantized_states, epsilon=epsilon)
<add> loss = cosine_sim.sum()
<add> return loss
<add>
<add> # transform the loss function to get the gradients
<add> grad_fn = jax.value_and_grad(compute_loss)
<add>
<add> # compute loss and gradients for unfrozen model
<add> loss, grads = grad_fn(outputs.projected_states, outputs.projected_quantized_states)
<add>
<add> # compare to loss and gradients for frozen model
<add> loss_frozen, grads_frozen = grad_fn(outputs_frozen.projected_states, outputs_frozen.projected_quantized_states)
<add>
<add> self.assertLessEqual(np.abs(loss - loss_frozen), 1e-5)
<add> self.assertEqual(grads.shape, grads_frozen.shape)
<add> max_diff = np.amax(np.abs(grads - grads_frozen))
<add> self.assertLessEqual(max_diff, 1e-5)
<add>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<ide> for model_class_name in self.all_model_classes: | 2 |
Python | Python | move db call out of __init__ | 4bec1cc489f5d19daf7450c75c3e8057c9709dbd | <ide><path>airflow/providers/microsoft/azure/hooks/azure_fileshare.py
<ide> class AzureFileShareHook(BaseHook):
<ide>
<ide> def __init__(self, wasb_conn_id='wasb_default'):
<ide> self.conn_id = wasb_conn_id
<del> self.connection = self.get_conn()
<add> self._conn = None
<ide>
<ide> def get_conn(self):
<ide> """Return the FileService object."""
<del> conn = self.get_connection(self.conn_id)
<del> service_options = conn.extra_dejson
<del> return FileService(account_name=conn.login,
<del> account_key=conn.password, **service_options)
<add> if not self._conn:
<add> conn = self.get_connection(self.conn_id)
<add> service_options = conn.extra_dejson
<add> self._conn = FileService(account_name=conn.login,
<add> account_key=conn.password, **service_options)
<add> return self._conn
<ide>
<ide> def check_for_directory(self, share_name, directory_name, **kwargs):
<ide> """
<ide> def check_for_directory(self, share_name, directory_name, **kwargs):
<ide> :return: True if the file exists, False otherwise.
<ide> :rtype: bool
<ide> """
<del> return self.connection.exists(share_name, directory_name,
<add> return self.get_conn().exists(share_name, directory_name,
<ide> **kwargs)
<ide>
<ide> def check_for_file(self, share_name, directory_name, file_name, **kwargs):
<ide> def check_for_file(self, share_name, directory_name, file_name, **kwargs):
<ide> :return: True if the file exists, False otherwise.
<ide> :rtype: bool
<ide> """
<del> return self.connection.exists(share_name, directory_name,
<add> return self.get_conn().exists(share_name, directory_name,
<ide> file_name, **kwargs)
<ide>
<ide> def list_directories_and_files(self, share_name, directory_name=None, **kwargs):
<ide> def list_directories_and_files(self, share_name, directory_name=None, **kwargs):
<ide> :return: A list of files and directories
<ide> :rtype: list
<ide> """
<del> return self.connection.list_directories_and_files(share_name,
<add> return self.get_conn().list_directories_and_files(share_name,
<ide> directory_name,
<ide> **kwargs)
<ide>
<ide> def create_directory(self, share_name, directory_name, **kwargs):
<ide> :return: A list of files and directories
<ide> :rtype: list
<ide> """
<del> return self.connection.create_directory(share_name, directory_name, **kwargs)
<add> return self.get_conn().create_directory(share_name, directory_name, **kwargs)
<ide>
<ide> def get_file(self, file_path, share_name, directory_name, file_name, **kwargs):
<ide> """
<ide> def get_file(self, file_path, share_name, directory_name, file_name, **kwargs):
<ide> `FileService.get_file_to_path()` takes.
<ide> :type kwargs: object
<ide> """
<del> self.connection.get_file_to_path(share_name, directory_name,
<add> self.get_conn().get_file_to_path(share_name, directory_name,
<ide> file_name, file_path, **kwargs)
<ide>
<ide> def get_file_to_stream(self, stream, share_name, directory_name, file_name, **kwargs):
<ide> def get_file_to_stream(self, stream, share_name, directory_name, file_name, **kw
<ide> `FileService.get_file_to_stream()` takes.
<ide> :type kwargs: object
<ide> """
<del> self.connection.get_file_to_stream(share_name, directory_name,
<add> self.get_conn().get_file_to_stream(share_name, directory_name,
<ide> file_name, stream, **kwargs)
<ide>
<ide> def load_file(self, file_path, share_name, directory_name, file_name, **kwargs):
<ide> def load_file(self, file_path, share_name, directory_name, file_name, **kwargs):
<ide> `FileService.create_file_from_path()` takes.
<ide> :type kwargs: object
<ide> """
<del> self.connection.create_file_from_path(share_name, directory_name,
<add> self.get_conn().create_file_from_path(share_name, directory_name,
<ide> file_name, file_path, **kwargs)
<ide>
<ide> def load_string(self, string_data, share_name, directory_name, file_name, **kwargs):
<ide> def load_string(self, string_data, share_name, directory_name, file_name, **kwar
<ide> `FileService.create_file_from_text()` takes.
<ide> :type kwargs: object
<ide> """
<del> self.connection.create_file_from_text(share_name, directory_name,
<add> self.get_conn().create_file_from_text(share_name, directory_name,
<ide> file_name, string_data, **kwargs)
<ide>
<ide> def load_stream(self, stream, share_name, directory_name, file_name, count, **kwargs):
<ide> def load_stream(self, stream, share_name, directory_name, file_name, count, **kw
<ide> `FileService.create_file_from_stream()` takes.
<ide> :type kwargs: object
<ide> """
<del> self.connection.create_file_from_stream(share_name, directory_name,
<add> self.get_conn().create_file_from_stream(share_name, directory_name,
<ide> file_name, stream, count, **kwargs)
<ide><path>tests/providers/microsoft/azure/hooks/test_azure_fileshare.py
<ide> def setUp(self):
<ide> )
<ide> )
<ide>
<del> def test_key(self):
<add> def test_key_and_connection(self):
<ide> from azure.storage.file import FileService
<ide> hook = AzureFileShareHook(wasb_conn_id='wasb_test_key')
<ide> self.assertEqual(hook.conn_id, 'wasb_test_key')
<del> self.assertIsInstance(hook.connection, FileService)
<add> self.assertIsNone(hook._conn)
<add> self.assertIsInstance(hook.get_conn(), FileService)
<ide>
<ide> def test_sas_token(self):
<ide> from azure.storage.file import FileService
<ide> hook = AzureFileShareHook(wasb_conn_id='wasb_test_sas_token')
<ide> self.assertEqual(hook.conn_id, 'wasb_test_sas_token')
<del> self.assertIsInstance(hook.connection, FileService)
<add> self.assertIsInstance(hook.get_conn(), FileService)
<ide>
<ide> @mock.patch('airflow.providers.microsoft.azure.hooks.azure_fileshare.FileService',
<ide> autospec=True) | 2 |
PHP | PHP | fix variable potentially being undefined | 1ca0760a6678875e0711ef7f3e0c5eb88f431f4f | <ide><path>src/Command/HelpCommand.php
<ide> protected function asText($io, $commands): void
<ide> continue;
<ide> }
<ide> $namespace = str_replace('\\', '/', $matches[1]);
<del> if ($namespace === $appNamespace) {
<del> $prefix = 'App';
<del> } elseif ($namespace === 'Cake') {
<add> $prefix = 'App';
<add> if ($namespace === 'Cake') {
<ide> $prefix = 'CakePHP';
<ide> } elseif (in_array($namespace, $plugins)) {
<ide> $prefix = $namespace; | 1 |
Go | Go | avoid trivial uses of sprintf | cc0b7e6aadaafb6dbb2f2590e4bf12b844d8b8b0 | <ide><path>libnetwork/drivers/bridge/bridge_test.go
<ide> func verifyV4INCEntries(networks map[string]*bridgeNetwork, numEntries int, t *t
<ide> if x == y {
<ide> continue
<ide> }
<del> re := regexp.MustCompile(fmt.Sprintf("%s %s", x.config.BridgeName, y.config.BridgeName))
<add> re := regexp.MustCompile(x.config.BridgeName + " " + y.config.BridgeName)
<ide> matches := re.FindAllString(string(out[:]), -1)
<ide> if len(matches) != 1 {
<ide> t.Fatalf("Cannot find expected inter-network isolation rules in IP Tables:\n%s", string(out[:]))
<ide><path>libnetwork/drivers/ipvlan/ipvlan_setup.go
<ide> func delDummyLink(linkName string) error {
<ide>
<ide> // getDummyName returns the name of a dummy parent with truncated net ID and driver prefix
<ide> func getDummyName(netID string) string {
<del> return fmt.Sprintf("%s%s", dummyPrefix, netID)
<add> return dummyPrefix + netID
<ide> }
<ide><path>libnetwork/drivers/macvlan/macvlan_setup.go
<ide> func delDummyLink(linkName string) error {
<ide>
<ide> // getDummyName returns the name of a dummy parent with truncated net ID and driver prefix
<ide> func getDummyName(netID string) string {
<del> return fmt.Sprintf("%s%s", dummyPrefix, netID)
<add> return dummyPrefix + netID
<ide> }
<ide><path>libnetwork/drivers/overlay/ov_network.go
<ide> func (n *network) restoreSubnetSandbox(s *subnet, brName, vxlanName string) erro
<ide> brIfaceOption := make([]osl.IfaceOption, 2)
<ide> brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Address(s.gwIP))
<ide> brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Bridge(true))
<del> Ifaces[fmt.Sprintf("%s+%s", brName, "br")] = brIfaceOption
<add> Ifaces[brName+"+br"] = brIfaceOption
<ide>
<ide> err := sbox.Restore(Ifaces, nil, nil, nil)
<ide> if err != nil {
<ide> func (n *network) restoreSubnetSandbox(s *subnet, brName, vxlanName string) erro
<ide> Ifaces = make(map[string][]osl.IfaceOption)
<ide> vxlanIfaceOption := make([]osl.IfaceOption, 1)
<ide> vxlanIfaceOption = append(vxlanIfaceOption, sbox.InterfaceOptions().Master(brName))
<del> Ifaces[fmt.Sprintf("%s+%s", vxlanName, "vxlan")] = vxlanIfaceOption
<add> Ifaces[vxlanName+"+vxlan"] = vxlanIfaceOption
<ide> err = sbox.Restore(Ifaces, nil, nil, nil)
<ide> if err != nil {
<ide> return err
<ide><path>libnetwork/drivers/overlay/overlay.go
<ide> func (d *driver) restoreEndpoints() error {
<ide> Ifaces := make(map[string][]osl.IfaceOption)
<ide> vethIfaceOption := make([]osl.IfaceOption, 1)
<ide> vethIfaceOption = append(vethIfaceOption, n.sbox.InterfaceOptions().Master(s.brName))
<del> Ifaces[fmt.Sprintf("%s+%s", "veth", "veth")] = vethIfaceOption
<add> Ifaces["veth+veth"] = vethIfaceOption
<ide>
<ide> err := n.sbox.Restore(Ifaces, nil, nil, nil)
<ide> if err != nil {
<ide> func (d *driver) nodeJoin(advertiseAddress, bindAddress string, self bool) {
<ide> // If there is no cluster store there is no need to start serf.
<ide> if d.store != nil {
<ide> if err := validateSelf(advertiseAddress); err != nil {
<del> logrus.Warnf("%s", err.Error())
<add> logrus.Warn(err.Error())
<ide> }
<ide> err := d.serfInit()
<ide> if err != nil {
<ide><path>libnetwork/drivers/solaris/overlay/ov_network.go
<ide> func (n *network) restoreSubnetSandbox(s *subnet, brName, vxlanName string) erro
<ide> brIfaceOption := make([]osl.IfaceOption, 2)
<ide> brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Address(s.gwIP))
<ide> brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Bridge(true))
<del> Ifaces[fmt.Sprintf("%s+%s", brName, "br")] = brIfaceOption
<add> Ifaces[brName+"+br"] = brIfaceOption
<ide>
<ide> err := sbox.Restore(Ifaces, nil, nil, nil)
<ide> if err != nil {
<ide> func (n *network) restoreSubnetSandbox(s *subnet, brName, vxlanName string) erro
<ide> Ifaces = make(map[string][]osl.IfaceOption)
<ide> vxlanIfaceOption := make([]osl.IfaceOption, 1)
<ide> vxlanIfaceOption = append(vxlanIfaceOption, sbox.InterfaceOptions().Master(brName))
<del> Ifaces[fmt.Sprintf("%s+%s", vxlanName, "vxlan")] = vxlanIfaceOption
<add> Ifaces[vxlanName+"+vxlan"] = vxlanIfaceOption
<ide> err = sbox.Restore(Ifaces, nil, nil, nil)
<ide> if err != nil {
<ide> return err
<ide><path>libnetwork/drivers/solaris/overlay/overlay.go
<ide> func (d *driver) restoreEndpoints() error {
<ide> Ifaces := make(map[string][]osl.IfaceOption)
<ide> vethIfaceOption := make([]osl.IfaceOption, 1)
<ide> vethIfaceOption = append(vethIfaceOption, n.sbox.InterfaceOptions().Master(s.brName))
<del> Ifaces[fmt.Sprintf("%s+%s", "veth", "veth")] = vethIfaceOption
<add> Ifaces["veth+veth"] = vethIfaceOption
<ide>
<ide> err := n.sbox.Restore(Ifaces, nil, nil, nil)
<ide> if err != nil {
<ide> func (d *driver) nodeJoin(advertiseAddress, bindAddress string, self bool) {
<ide> // If there is no cluster store there is no need to start serf.
<ide> if d.store != nil {
<ide> if err := validateSelf(advertiseAddress); err != nil {
<del> logrus.Warnf("%s", err.Error())
<add> logrus.Warn(err.Error())
<ide> }
<ide> err := d.serfInit()
<ide> if err != nil {
<ide><path>libnetwork/ipam/allocator.go
<ide> func (a *Allocator) DumpDatabase() string {
<ide> s = fmt.Sprintf("\n\n%s Config", as)
<ide> aSpace.Lock()
<ide> for k, config := range aSpace.subnets {
<del> s = fmt.Sprintf("%s%s", s, fmt.Sprintf("\n%v: %v", k, config))
<add> s += fmt.Sprintf("\n%v: %v", k, config)
<ide> if config.Range == nil {
<ide> a.retrieveBitmask(k, config.Pool)
<ide> }
<ide> func (a *Allocator) DumpDatabase() string {
<ide>
<ide> s = fmt.Sprintf("%s\n\nBitmasks", s)
<ide> for k, bm := range a.addresses {
<del> s = fmt.Sprintf("%s%s", s, fmt.Sprintf("\n%s: %s", k, bm))
<add> s += fmt.Sprintf("\n%s: %s", k, bm)
<ide> }
<ide>
<ide> return s
<ide><path>libnetwork/types/types.go
<ide> func (p *PortBinding) GetCopy() PortBinding {
<ide> func (p *PortBinding) String() string {
<ide> ret := fmt.Sprintf("%s/", p.Proto)
<ide> if p.IP != nil {
<del> ret = fmt.Sprintf("%s%s", ret, p.IP.String())
<add> ret += p.IP.String()
<ide> }
<ide> ret = fmt.Sprintf("%s:%d/", ret, p.Port)
<ide> if p.HostIP != nil {
<del> ret = fmt.Sprintf("%s%s", ret, p.HostIP.String())
<add> ret += p.HostIP.String()
<ide> }
<ide> ret = fmt.Sprintf("%s:%d", ret, p.HostPort)
<ide> return ret | 9 |
Java | Java | fix todo in reactorhttpserver | 3eb2432ced0cba56ddb8fefac6da88f173a98703 | <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/ReactorHttpServer.java
<ide>
<ide> package org.springframework.http.server.reactive.bootstrap;
<ide>
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<ide> import reactor.core.Loopback;
<ide> import reactor.ipc.netty.NettyContext;
<ide>
<ide> public class ReactorHttpServer extends HttpServerSupport implements HttpServer,
<ide>
<ide> private reactor.ipc.netty.http.server.HttpServer reactorServer;
<ide>
<del> private NettyContext running;
<add> private AtomicReference<NettyContext> nettyContext = new AtomicReference<>();
<ide>
<ide>
<ide> @Override
<ide> public void afterPropertiesSet() throws Exception {
<ide> Assert.notNull(getHttpHandler());
<ide> this.reactorHandler = new ReactorHttpHandlerAdapter(getHttpHandler());
<ide> }
<del> this.reactorServer = reactor.ipc.netty.http.server.HttpServer.create(getHost(),
<del> getPort());
<add> this.reactorServer = reactor.ipc.netty.http.server.HttpServer
<add> .create(getHost(), getPort());
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public boolean isRunning() {
<del> NettyContext running = this.running;
<del> return running != null && running.channel()
<del> .isActive();
<add> NettyContext context = this.nettyContext.get();
<add> return (context != null && context.channel().isActive());
<ide> }
<ide>
<ide> @Override
<ide> public Object connectedInput() {
<del> return reactorServer;
<add> return this.reactorServer;
<ide> }
<ide>
<ide> @Override
<ide> public Object connectedOutput() {
<del> return reactorServer;
<add> return this.reactorServer;
<ide> }
<ide>
<ide> @Override
<ide> public void start() {
<del> // TODO: should be made thread-safe (compareAndSet..)
<del> if (this.running == null) {
<del> this.running = this.reactorServer.newHandler(reactorHandler).block();
<add> if (this.nettyContext.get() == null) {
<add> this.nettyContext.set(this.reactorServer.newHandler(reactorHandler).block());
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void stop() {
<del> NettyContext running = this.running;
<del> if (running != null) {
<del> this.running = null;
<del> running.dispose();
<add> NettyContext context = this.nettyContext.getAndSet(null);
<add> if (context != null) {
<add> context.dispose();
<ide> }
<ide> }
<ide> } | 1 |
Python | Python | add stop words | a8d84188f018ce84e91ce14e7be9b06952c59497 | <ide><path>spacy/lang/am/stop_words.py
<del># Stop words
<add># Stop words by Teshome Kassie http://etd.aau.edu.et/bitstream/handle/123456789/3315/Teshome%20Kassie.pdf?sequence=1&isAllowed=y
<add># Stop words by Tihitina Petros http://etd.aau.edu.et/bitstream/handle/123456789/3384/Tihitina%20Petros.pdf?sequence=1&isAllowed=y
<add>
<ide> STOP_WORDS = set(
<ide> """
<ide> ግን አንቺ አንተ እናንተ ያንተ ያንቺ የናንተ ራስህን ራስሽን ራሳችሁን
<add>ሁሉ ኋላ በሰሞኑ አሉ በኋላ ሁኔታ በኩል አስታውቀዋል ሆነ በውስጥ
<add>አስታውሰዋል ሆኑ ባጣም እስካሁን ሆኖም በተለይ አሳሰበ ሁል በተመለከተ
<add>አሳስበዋል ላይ በተመሳሳይ አስፈላጊ ሌላ የተለያየ አስገነዘቡ ሌሎች የተለያዩ
<add>አስገንዝበዋል ልዩ ተባለ አብራርተዋል መሆኑ ተገለጸ አስረድተዋል ተገልጿል
<add>ማለቱ ተጨማሪ እባክህ የሚገኝ ተከናወነ እባክሽ ማድረግ ችግር አንጻር ማን
<add>ትናንት እስኪደርስ ነበረች እንኳ ሰሞኑን ነበሩ እንኳን ሲሆን ነበር እዚሁ ሲል
<add>ነው እንደገለጹት አለ ና እንደተናገሩት ቢሆን ነገር እንዳስረዱት ብለዋል ነገሮች
<add>እንደገና ብዙ ናት ወቅት ቦታ ናቸው እንዲሁም በርካታ አሁን እንጂ እስከ
<add>ማለት የሚሆኑት ስለማናቸውም ውስጥ ይሆናሉ ሲባል ከሆነው ስለዚሁ ከአንድ
<add>ያልሆነ ሳለ የነበረውን ከአንዳንድ በማናቸውም በሙሉ የሆነው ያሉ በእነዚሁ
<add>ወር መሆናቸው ከሌሎች በዋና አንዲት ወይም
<add>በላይ እንደ በማቀድ ለሌሎች በሆኑ ቢሆንም ጊዜና ይሆኑበታል በሆነ አንዱ
<add>ለዚህ ለሆነው ለነዚህ ከዚህ የሌላውን ሶስተኛ አንዳንድ ለማንኛውም የሆነ ከሁለት
<add>የነገሩ ሰኣት አንደኛ እንዲሆን እንደነዚህ ማንኛውም ካልሆነ የሆኑት ጋር ቢያንስ
<add>ይህንንም እነደሆነ እነዚህን ይኸው የማናቸውም
<add>በሙሉም ይህችው በተለይም አንዱን የሚችለውን በነዚህ ከእነዚህ በሌላ
<add>የዚሁ ከእነዚሁ ለዚሁ በሚገባ ለእያንዳንዱ የአንቀጹ ወደ ይህም ስለሆነ ወይ
<add>ማናቸውንም ተብሎ እነዚህ መሆናቸውን የሆነችን ከአስር ሳይሆን ከዚያ የለውም
<add>የማይበልጥ እንደሆነና እንዲሆኑ በሚችሉ ብቻ ብሎ ከሌላ የሌላቸውን
<add>ለሆነ በሌሎች ሁለቱንም በቀር ይህ በታች አንደሆነ በነሱ
<add>ይህን የሌላ እንዲህ ከሆነ ያላቸው በነዚሁ በሚል የዚህ ይህንኑ
<add>በእንደዚህ ቁጥር ማናቸውም ሆነው ባሉ በዚህ በስተቀር ሲሆንና
<add>በዚህም መሆን ምንጊዜም እነዚህም በዚህና ያለ ስም
<add>ሲኖር ከዚህም መሆኑን በሁኔታው የማያንስ እነዚህኑ ማንም ከነዚሁ
<add>ያላቸውን እጅግ ሲሆኑ ለሆኑ ሊሆን ለማናቸውም
<ide> """.split()
<del>)
<add>)
<ide>\ No newline at end of file | 1 |
PHP | PHP | remove multiple method call | 25b486aaff659a7c981306140ed8e6b3a5b6f6ad | <ide><path>src/Datasource/EntityTrait.php
<ide> public function set($property, $value = null, $options = []) {
<ide>
<ide> if (!isset($this->_original[$p]) &&
<ide> isset($this->_properties[$p]) &&
<del> $this->_properties[$p] !== $value
<del> ) {
<add> $this->_properties[$p] !== $value
<add> ) {
<ide> $this->_original[$p] = $this->_properties[$p];
<ide> }
<ide>
<ide> public function extract(array $properties, $onlyDirty = false) {
<ide> public function extractOriginal(array $properties) {
<ide> $result = [];
<ide> foreach ($properties as $property) {
<del> if ($this->getOriginal($property) !== null &&
<del> $this->getOriginal($property) !== $this->get($property)
<del> ) {
<del> $result[$property] = $this->getOriginal($property);
<add> $original = $this->getOriginal($property);
<add> if ($original !== null && $original !== $this->get($property)) {
<add> $result[$property] = $original;
<ide> }
<ide> }
<ide> return $result; | 1 |
Go | Go | fix error handling | f41e0cf0485eac21d65c1af19a732b350292d200 | <ide><path>commands.go
<ide> func (cli *DockerCli) CmdRmi(args ...string) error {
<ide>
<ide> var encounteredError error
<ide> for _, name := range cmd.Args() {
<del> stream, _, err := cli.call("DELETE", "/images/"+name, nil, false)
<add> body, _, err := readBody(cli.call("DELETE", "/images/"+name, nil, false))
<ide> if err != nil {
<ide> fmt.Fprintf(cli.err, "%s\n", err)
<ide> encounteredError = fmt.Errorf("Error: failed to remove one or more images")
<ide> } else {
<ide> outs := engine.NewTable("Created", 0)
<del> if _, err := outs.ReadListFrom(stream); err != nil {
<add> if _, err := outs.ReadListFrom(body); err != nil {
<ide> fmt.Fprintf(cli.err, "%s\n", err)
<ide> encounteredError = fmt.Errorf("Error: failed to remove one or more images")
<ide> continue
<ide> func (cli *DockerCli) CmdHistory(args ...string) error {
<ide> return nil
<ide> }
<ide>
<del> stream, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, false)
<del> if stream != nil {
<del> defer stream.Close()
<del> }
<add> body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, false))
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> outs := engine.NewTable("Created", 0)
<del> if _, err := outs.ReadListFrom(stream); err != nil {
<add> if _, err := outs.ReadListFrom(body); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdImages(args ...string) error {
<ide> filter := cmd.Arg(0)
<ide>
<ide> if *flViz || *flTree {
<del> stream, _, err := cli.call("GET", "/images/json?all=1", nil, false)
<del> if stream != nil {
<del> defer stream.Close()
<del> }
<add> body, _, err := readBody(cli.call("GET", "/images/json?all=1", nil, false))
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> outs := engine.NewTable("Created", 0)
<del> if _, err := outs.ReadListFrom(stream); err != nil {
<add> if _, err := outs.ReadListFrom(body); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdImages(args ...string) error {
<ide> v.Set("all", "1")
<ide> }
<ide>
<del> stream, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil, false)
<del> if stream != nil {
<del> defer stream.Close()
<del> }
<add> body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
<add>
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> outs := engine.NewTable("Created", 0)
<del> if _, err := outs.ReadListFrom(stream); err != nil {
<add> if _, err := outs.ReadListFrom(body); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdDiff(args ...string) error {
<ide> return nil
<ide> }
<ide>
<del> stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, false)
<del> if stream != nil {
<del> defer stream.Close()
<del> }
<add> body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, false))
<add>
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> outs := engine.NewTable("", 0)
<del> if _, err := outs.ReadListFrom(stream); err != nil {
<add> if _, err := outs.ReadListFrom(body); err != nil {
<ide> return err
<ide> }
<ide> for _, change := range outs.Data {
<ide> func (cli *DockerCli) CmdSearch(args ...string) error {
<ide>
<ide> v := url.Values{}
<ide> v.Set("term", cmd.Arg(0))
<del> stream, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil, true)
<del> if stream != nil {
<del> defer stream.Close()
<del> }
<add>
<add> body, _, err := readBody(cli.call("GET", "/images/search?"+v.Encode(), nil, false))
<add>
<ide> if err != nil {
<ide> return err
<ide> }
<ide> outs := engine.NewTable("star_count", 0)
<del> if _, err := outs.ReadListFrom(stream); err != nil {
<add> if _, err := outs.ReadListFrom(body); err != nil {
<ide> return err
<ide> }
<ide> w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
<ide><path>engine/env.go
<ide> import (
<ide> "encoding/json"
<ide> "fmt"
<ide> "io"
<del> "io/ioutil"
<ide> "sort"
<ide> "strconv"
<ide> "strings"
<ide> func (t *Table) WriteTo(dst io.Writer) (n int64, err error) {
<ide> return n, nil
<ide> }
<ide>
<del>func (t *Table) ReadListFrom(src io.Reader) (n int64, err error) {
<add>func (t *Table) ReadListFrom(src []byte) (n int64, err error) {
<ide> var array []interface{}
<ide>
<del> content, err := ioutil.ReadAll(src)
<del> if err != nil {
<del> return -1, err
<del> }
<del>
<del> if err := json.Unmarshal(content, &array); err != nil {
<add> if err := json.Unmarshal(src, &array); err != nil {
<ide> return -1, err
<ide> }
<ide>
<ide> func (t *Table) ReadListFrom(src io.Reader) (n int64, err error) {
<ide> }
<ide> }
<ide>
<del> return int64(len(content)), nil
<add> return int64(len(src)), nil
<ide> }
<ide>
<ide> func (t *Table) ReadFrom(src io.Reader) (n int64, err error) {
<ide><path>engine/streams.go
<ide> import (
<ide> "container/ring"
<ide> "fmt"
<ide> "io"
<add> "io/ioutil"
<ide> "sync"
<ide> )
<ide>
<ide> func (o *Output) AddListTable() (dst *Table, err error) {
<ide> o.tasks.Add(1)
<ide> go func() {
<ide> defer o.tasks.Done()
<del> if _, err := dst.ReadListFrom(src); err != nil {
<add> content, err := ioutil.ReadAll(src)
<add> if err != nil {
<add> return
<add> }
<add> if _, err := dst.ReadListFrom(content); err != nil {
<ide> return
<ide> }
<ide> }()
<ide><path>integration/api_test.go
<ide> func TestGetImagesJSON(t *testing.T) {
<ide> assertHttpNotError(r, t)
<ide>
<ide> images := engine.NewTable("Created", 0)
<del> if _, err := images.ReadListFrom(r.Body); err != nil {
<add> if _, err := images.ReadListFrom(r.Body.Bytes()); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestGetImagesJSON(t *testing.T) {
<ide> assertHttpNotError(r2, t)
<ide>
<ide> images2 := engine.NewTable("ID", 0)
<del> if _, err := images2.ReadListFrom(r2.Body); err != nil {
<add> if _, err := images2.ReadListFrom(r2.Body.Bytes()); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestGetImagesJSON(t *testing.T) {
<ide> assertHttpNotError(r3, t)
<ide>
<ide> images3 := engine.NewTable("ID", 0)
<del> if _, err := images3.ReadListFrom(r3.Body); err != nil {
<add> if _, err := images3.ReadListFrom(r3.Body.Bytes()); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestGetImagesHistory(t *testing.T) {
<ide> assertHttpNotError(r, t)
<ide>
<ide> outs := engine.NewTable("Created", 0)
<del> if _, err := outs.ReadListFrom(r.Body); err != nil {
<add> if _, err := outs.ReadListFrom(r.Body.Bytes()); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> if len(outs.Data) != 1 {
<ide> func TestGetContainersChanges(t *testing.T) {
<ide> }
<ide> assertHttpNotError(r, t)
<ide> outs := engine.NewTable("", 0)
<del> if _, err := outs.ReadListFrom(r.Body); err != nil {
<add> if _, err := outs.ReadListFrom(r.Body.Bytes()); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> | 4 |
Python | Python | correct an issue in last commit for | 0e9e5e9512a36f9c410ff398c068d3e85ff06e2c | <ide><path>glances/__init__.py
<ide> # Global name
<ide> # Version should start and end with a numerical char
<ide> # See https://packaging.python.org/specifications/core-metadata/#version
<del>__version__ = '3.2.0b1'
<add>__version__ = '3.2.0b2'
<ide> __author__ = 'Nicolas Hennion <nicolas@nicolargo.com>'
<ide> __license__ = 'LGPLv3'
<ide>
<ide><path>glances/cpu_percent.py
<ide> def get_info(self):
<ide> cpu_freq = psutil.cpu_freq()
<ide> if hasattr(cpu_freq, 'current'):
<ide> self.cpu_info['cpu_hz_current'] = cpu_freq.current
<del> if hasattr(cpu_freq, 'cpu_hz'):
<add> else:
<add> self.cpu_info['cpu_hz_current'] = None
<add> if hasattr(cpu_freq, 'max'):
<ide> self.cpu_info['cpu_hz'] = cpu_freq.max
<add> else:
<add> self.cpu_info['cpu_hz'] = None
<ide> # Reset timer for cache
<ide> self.timer_cpu_info.reset(duration=self.cached_timer_cpu_info)
<ide> return self.cpu_info
<ide><path>glances/plugins/glances_quicklook.py
<ide> def update(self):
<ide> stats['swap'] = None
<ide>
<ide> # Get additional information
<del> stats['cpu_name'] = cpu_percent.get_info()['cpu_name']
<del> stats['cpu_hz_current'] = self._mhz_to_hz(cpu_percent.get_info()['cpu_hz_current'])
<del> stats['cpu_hz'] = self._mhz_to_hz(cpu_percent.get_info()['cpu_hz'])
<add> cpu_info = cpu_percent.get_info()
<add> stats['cpu_name'] = cpu_info['cpu_name']
<add> stats['cpu_hz_current'] = self._mhz_to_hz(cpu_info['cpu_hz_current']) if cpu_info['cpu_hz_current'] is not None else None
<add> stats['cpu_hz'] = self._mhz_to_hz(cpu_info['cpu_hz']) if cpu_info['cpu_hz'] is not None else None
<ide>
<ide> elif self.input_method == 'snmp':
<ide> # Not available
<ide> def msg_curse(self, args=None, max_width=10):
<ide>
<ide> # Build the string message
<ide> if 'cpu_name' in self.stats and 'cpu_hz_current' in self.stats and 'cpu_hz' in self.stats:
<del> msg_name = '{} - '.format(self.stats['cpu_name'])
<del> msg_freq = '{:.2f}/{:.2f}GHz'.format(self._hz_to_ghz(self.stats['cpu_hz_current']),
<del> self._hz_to_ghz(self.stats['cpu_hz']))
<add> msg_name = self.stats['cpu_name']
<add> if self.stats['cpu_hz_current'] and self.stats['cpu_hz']:
<add> msg_freq = ' - {:.2f}/{:.2f}GHz'.format(self._hz_to_ghz(self.stats['cpu_hz_current']),
<add> self._hz_to_ghz(self.stats['cpu_hz']))
<add> else:
<add> msg_freq = ''
<ide> if len(msg_name + msg_freq) - 6 <= max_width:
<ide> ret.append(self.curse_add_line(msg_name))
<ide> ret.append(self.curse_add_line(msg_freq)) | 3 |
PHP | PHP | fix boundmethod dockblock | 838a47599dd7fb0597656cf71ce4e18c7d9051b0 | <ide><path>src/Illuminate/Container/BoundMethod.php
<ide> class BoundMethod
<ide> * @param array $parameters
<ide> * @param string|null $defaultMethod
<ide> * @return mixed
<add> *
<add> * @throws \ReflectionException
<add> * @throws \InvalidArgumentException
<ide> */
<ide> public static function call($container, $callback, array $parameters = [], $defaultMethod = null)
<ide> {
<ide> protected static function normalizeMethod($callback)
<ide> * @param callable|string $callback
<ide> * @param array $parameters
<ide> * @return array
<add> *
<add> * @throws \ReflectionException
<ide> */
<ide> protected static function getMethodDependencies($container, $callback, array $parameters = [])
<ide> { | 1 |
Javascript | Javascript | revert part of d39268920 | ea1ec29ba67c837c82c74357e313bd4505b81eb8 | <ide><path>Libraries/StyleSheet/StyleSheetTypes.js
<ide> export type ____FontWeight_Internal =
<ide> | 'condensedBold'
<ide> | 'condensed'
<ide> | 'heavy'
<del> | 'black';
<add> | 'black'
<add> | 'Ultralight'
<add> | 'Thin'
<add> | 'Light'
<add> | 'Normal'
<add> | 'Medium'
<add> | 'Semibold'
<add> | 'Bold'
<add> | 'Condensed'
<add> | 'CondensedBold'
<add> | 'Heavy'
<add> | 'Black';
<ide>
<ide> export type ____FontVariantArray_Internal = $ReadOnlyArray<
<ide> | 'small-caps' | 1 |
Javascript | Javascript | fix stale getstate on hot reloading (#90) | 4acf88a0354a8a04364826ca76a0777bb6b58a32 | <ide><path>src/createDispatcher.js
<ide> export default function createDispatcher(store, middlewares = []) {
<ide> return state;
<ide> }
<ide>
<del> if (typeof middlewares === 'function') {
<del> middlewares = middlewares(getState);
<del> }
<add> const finalMiddlewares = typeof middlewares === 'function' ?
<add> middlewares(getState) :
<add> middlewares;
<ide>
<del> return composeMiddleware(...middlewares, dispatch);
<add> return composeMiddleware(...finalMiddlewares, dispatch);
<ide> };
<ide> } | 1 |
PHP | PHP | add strict_types to testsuite package | c38740b479e446f1a497b7af0d9d9274ddd20031 | <ide><path>src/TestSuite/ConsoleIntegrationTestCase.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/ConsoleIntegrationTestTrait.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/EmailTrait.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/IntegrationTestCase.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/LegacyCommandRunner.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/LegacyShellDispatcher.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> protected function _createShell($className, $shortName)
<ide> {
<ide> list($plugin) = pluginSplit($shortName);
<ide> $instance = new $className($this->_io);
<del> $instance->plugin = trim($plugin, '.');
<add> if ($plugin) {
<add> $instance->plugin = trim($plugin, '.');
<add> }
<ide>
<ide> return $instance;
<ide> }
<ide><path>src/TestSuite/MiddlewareDispatcher.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/StringCompareTrait.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/TestCase.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function assertHtml($expected, $string, $fullDebug = false)
<ide> $explanations = [];
<ide> $i = 1;
<ide> foreach ($attributes as $attr => $val) {
<del> if (is_numeric($attr) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) {
<add> if (is_numeric($attr) && preg_match('/^preg\:\/(.+)\/$/i', (string)$val, $matches)) {
<ide> $attrs[] = $matches[1];
<ide> $explanations[] = sprintf('Regex "%s" matches', $matches[1]);
<ide> continue;
<ide> }
<add> $val = (string)$val;
<ide>
<ide> $quotes = '["\']';
<ide> if (is_numeric($attr)) {
<ide><path>src/TestSuite/TestEmailTransport.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/TestSuite.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * A class to contain test cases and run them with shared fixtures
<ide> *
<ide><path>tests/TestCase/TestSuite/AssertHtmlTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> namespace Cake\Test\Fixture;
<ide>
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/TestSuite/ConsoleIntegrationTestTraitTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>tests/TestCase/TestSuite/EmailTraitTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function testGetCookiesHttpServer()
<ide> public function testPostDataHttpServer()
<ide> {
<ide> $this->post('/request_action/post_pass', ['title' => 'value']);
<del> $data = json_decode($this->_response->getBody());
<add> $data = json_decode('' . $this->_response->getBody());
<ide> $this->assertEquals('value', $data->title);
<ide> $this->assertHeader('X-Middleware', 'true');
<ide> }
<ide><path>tests/TestCase/TestSuite/TestCaseTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/TestSuite/TestEmailTransportTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/TestSuite/TestFixtureTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/TestSuite/TestSuiteTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) | 21 |
Go | Go | protect entire environment when testing | 063c89c71fd1fbeb7ef7c46f43ee805b620e7136 | <ide><path>integration-cli/check_test.go
<ide> func TestMain(m *testing.M) {
<ide> func Test(t *testing.T) {
<ide> cli.SetTestEnvironment(testEnv)
<ide> fakestorage.SetTestEnvironment(&testEnv.Execution)
<del> ienv.ProtectImages(t, &testEnv.Execution)
<add> ienv.ProtectAll(t, &testEnv.Execution)
<ide> check.TestingT(t)
<ide> }
<ide>
<ide><path>integration/container/main_test.go
<ide> func TestMain(m *testing.M) {
<ide> }
<ide>
<ide> func setupTest(t *testing.T) func() {
<del> environment.ProtectImages(t, testEnv)
<add> environment.ProtectAll(t, testEnv)
<ide> return func() { testEnv.Clean(t) }
<ide> }
<ide><path>integration/service/main_test.go
<ide> func TestMain(m *testing.M) {
<ide> }
<ide>
<ide> func setupTest(t *testing.T) func() {
<del> environment.ProtectImages(t, testEnv)
<add> environment.ProtectAll(t, testEnv)
<ide> return func() { testEnv.Clean(t) }
<ide> } | 3 |
Python | Python | add benchmark for creating new arrays | 145d10cd37fe61c5dcdf1d5841b7d23b09751038 | <ide><path>benchmarks/creating.py
<add>import timeit
<add>N = [1000,100]
<add>t1 = timeit.Timer('a=N.zeros(shape,type)','import numpy as N; shape=%s;type=float'%N)
<add>t2 = timeit.Timer('a=N.zeros(shape,type)','import Numeric as N; shape=%s;type=N.Float'%N)
<add>t3 = timeit.Timer('a=N.zeros(shape,type)',"import numarray as N; shape=%s;type=N.Float"%N)
<add>print "shape = ", N
<add>print "NumPy: ", t1.repeat(3,100)
<add>print "Numeric: ", t2.repeat(3,100)
<add>print "Numarray: ", t3.repeat(3,100) | 1 |
Mixed | Javascript | use camelcase and declare must_use_attribute | bfcd4cac48a294da32a0bda0a82055c640aebac9 | <ide><path>docs/docs/ref-04-tags-and-attributes.md
<ide> accept accessKey action allowFullScreen allowTransparency alt async
<ide> autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked
<ide> className colSpan cols content contentEditable contextMenu controls data
<ide> dateTime defer dir disabled draggable encType form formNoValidate frameBorder
<del>height hidden href htmlFor httpEquiv icon id itemprop itemscope itemtype
<add>height hidden href htmlFor httpEquiv icon id itemProp itemScope itemType
<ide> label lang list loop max maxLength method min multiple name noValidate
<ide> pattern placeholder poster preload radioGroup readOnly rel required role
<ide> rowSpan rows sandbox scope scrollLeft scrollTop seamless selected size span
<ide><path>src/browser/ui/dom/HTMLDOMPropertyConfig.js
<ide> var HTMLDOMPropertyConfig = {
<ide> autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
<ide> autoCorrect: null, // Supported in Mobile Safari for keyboard hints
<ide> property: null, // Supports OG in meta tags
<del> itemscope: HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
<del> itemtype: null, // Microdata: http://schema.org/docs/gs.html
<del> itemprop: null // Microdata: http://schema.org/docs/gs.html
<add> itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
<add> itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
<add> itemProp: MUST_USE_ATTRIBUTE // Microdata: http://schema.org/docs/gs.html
<ide> },
<ide> DOMAttributeNames: {
<ide> className: 'class', | 2 |
Text | Text | remove advice on bad python linking | 116075dda9c6c8bffe06e16646ed9eb4d0ae7f8e | <ide><path>share/doc/homebrew/Common-Issues.md
<ide> $ git clean -n # if this doesn't list anything that you want to keep, then
<ide> $ git clean -f # this will remove untracked files
<ide> ```
<ide>
<del>### Python: `Segmentation fault: 11` on `import <some_python_module>`
<del>
<del>A `Segmentation fault: 11` is in many cases due to a different Python
<del>executable used for building the software vs. the python you use to import the
<del>module. This can even happen when both python executables are the same version
<del>(e.g. 2.7.2). The explanation is that Python packages with C extensions (those
<del>that have `.so` files) are compiled against a certain python binary/library that
<del>may have been built with a different arch (e.g. Apple's python is still not a
<del>pure 64-bit build). Other things can go wrong, too. Welcome to the dirty
<del>underworld of C.
<del>
<del>To solve this, you should remove the problematic formula with those python
<del>bindings and all of its dependencies.
<del>
<del> - `brew rm $(brew deps --installed <problematic_formula>)`
<del> - `brew rm <problematic_formula>`
<del> - Also check the `$(brew --prefix)/lib/python2.7/site-packages` directory and
<del> delete all remains of the corresponding python modules if they were not
<del> cleanly removed by the previous steps.
<del> - Check that `which python` points to the python you want. Perhaps now is the
<del> time to `brew install python`.
<del> - Then reinstall `brew install <problematic_formula>`
<del> - Now start `python` and try to `import` the module installed by the
<del> \<problematic_formula\>
<del>
<del>You can basically use any Python (2.x) for the bindings homebrew provides, but
<del>you can't mix. Homebrew formulae use a brewed Python if available or, if not
<del>so, they use whatever `python` is in your `PATH`.
<del>
<del>### Python: `Fatal Python error: PyThreadState_Get: no current thread`
<del>
<del>```
<del>Fatal Python error: PyThreadState_Get: no current thread
<del>Abort trap: 6
<del>```
<del>
<del>This happens for `boost-python`, `pygtk`, `pygobject`, and related modules,
<del>for the same reason as described above. To solve this, follow the steps above.
<del>
<del>If `boost` is your problem, note that Boost.Python is now provided by the
<del>`boost-python` formula. Removing any existing `boost` and `boost-python`,
<del>running `brew update`, and installing them anew should fix things.
<del>
<ide> ### Python: easy-install.pth cannot be linked
<ide> ```
<ide> Warning: Could not link <formulaname>. Unlinking... | 1 |
Mixed | Ruby | add insert_all to activerecord models | 91ed21b304c468db8ce9fd830312c151432935d0 | <ide><path>activerecord/CHANGELOG.md
<add>* Add `insert_all`/`insert_all!`/`upsert_all` methods to `ActiveRecord::Persistence`,
<add> allowing bulk inserts akin to the bulk updates provided by `update_all` and
<add> bulk deletes by `delete_all`.
<add>
<add> Supports skipping or upserting duplicates through the `ON CONFLICT` syntax
<add> for Postgres (9.5+) and Sqlite (3.24+) and `ON DUPLICATE KEY UPDATE` syntax
<add> for MySQL.
<add>
<add> *Bob Lail*
<add>
<ide> * Add `rails db:seed:replant` that truncates tables of each database
<ide> for current environment and loads the seeds.
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
<ide> def sanitize_limit(limit)
<ide> end
<ide> end
<ide>
<add> # Fixture value is quoted by Arel, however scalar values
<add> # are not quotable. In this case we want to convert
<add> # the column value to YAML.
<add> def with_yaml_fallback(value) # :nodoc:
<add> if value.is_a?(Hash) || value.is_a?(Array)
<add> YAML.dump(value)
<add> else
<add> value
<add> end
<add> end
<add>
<ide> private
<ide> def default_insert_value(column)
<ide> Arel.sql("DEFAULT")
<ide> def arel_from_relation(relation)
<ide> relation
<ide> end
<ide> end
<del>
<del> # Fixture value is quoted by Arel, however scalar values
<del> # are not quotable. In this case we want to convert
<del> # the column value to YAML.
<del> def with_yaml_fallback(value)
<del> if value.is_a?(Hash) || value.is_a?(Array)
<del> YAML.dump(value)
<del> else
<del> value
<del> end
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def supports_lazy_transactions?
<ide> false
<ide> end
<ide>
<add> def supports_insert_returning?
<add> false
<add> end
<add>
<add> def supports_insert_on_duplicate_skip?
<add> false
<add> end
<add>
<add> def supports_insert_on_duplicate_update?
<add> false
<add> end
<add>
<add> def supports_insert_conflict_target?
<add> false
<add> end
<add>
<ide> # This is meant to be implemented by the adapters that support extensions
<ide> def disable_extension(name)
<ide> end
<ide> def default_index_type?(index) # :nodoc:
<ide> index.using.nil?
<ide> end
<ide>
<add> # Called by ActiveRecord::InsertAll,
<add> # Passed an instance of ActiveRecord::InsertAll::Builder,
<add> # This method implements standard bulk inserts for all databases, but
<add> # should be overridden by adapters to implement common features with
<add> # non-standard syntax like handling duplicates or returning values.
<add> def build_insert_sql(insert) # :nodoc:
<add> if insert.skip_duplicates? || insert.update_duplicates?
<add> raise NotImplementedError, "#{self.class} should define `build_insert_sql` to implement adapter-specific logic for handling duplicates during INSERT"
<add> end
<add>
<add> "INSERT #{insert.into} #{insert.values_list}"
<add> end
<add>
<ide> private
<ide> def check_version
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def supports_advisory_locks?
<ide> true
<ide> end
<ide>
<add> def supports_insert_on_duplicate_skip?
<add> true
<add> end
<add>
<add> def supports_insert_on_duplicate_update?
<add> true
<add> end
<add>
<ide> def get_advisory_lock(lock_name, timeout = 0) # :nodoc:
<ide> query_value("SELECT GET_LOCK(#{quote(lock_name.to_s)}, #{timeout})") == 1
<ide> end
<ide> def insert_fixtures_set(fixture_set, tables_to_delete = [])
<ide> end
<ide> end
<ide>
<add> def build_insert_sql(insert) # :nodoc:
<add> sql = +"INSERT #{insert.into} #{insert.values_list}"
<add>
<add> if insert.skip_duplicates?
<add> any_column = quote_column_name(insert.model.columns.first.name)
<add> sql << " ON DUPLICATE KEY UPDATE #{any_column}=#{any_column}"
<add> elsif insert.update_duplicates?
<add> sql << " ON DUPLICATE KEY UPDATE "
<add> sql << insert.updatable_columns.map { |column| "#{column}=VALUES(#{column})" }.join(",")
<add> end
<add>
<add> sql
<add> end
<add>
<ide> private
<ide> def check_version
<ide> if version < "5.5.8"
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def supports_savepoints?
<ide> true
<ide> end
<ide>
<add> def supports_insert_returning?
<add> true
<add> end
<add>
<add> def supports_insert_on_conflict?
<add> postgresql_version >= 90500
<add> end
<add> alias supports_insert_on_duplicate_skip? supports_insert_on_conflict?
<add> alias supports_insert_on_duplicate_update? supports_insert_on_conflict?
<add> alias supports_insert_conflict_target? supports_insert_on_conflict?
<add>
<ide> def index_algorithms
<ide> { concurrently: "CONCURRENTLY" }
<ide> end
<ide> def default_index_type?(index) # :nodoc:
<ide> index.using == :btree || super
<ide> end
<ide>
<add> def build_insert_sql(insert) # :nodoc:
<add> sql = +"INSERT #{insert.into} #{insert.values_list}"
<add>
<add> if insert.skip_duplicates?
<add> sql << " ON CONFLICT #{insert.conflict_target} DO NOTHING"
<add> elsif insert.update_duplicates?
<add> sql << " ON CONFLICT #{insert.conflict_target} DO UPDATE SET "
<add> sql << insert.updatable_columns.map { |column| "#{column}=excluded.#{column}" }.join(",")
<add> end
<add>
<add> sql << " RETURNING #{insert.returning}" if insert.returning
<add> sql
<add> end
<add>
<ide> private
<ide> def check_version
<ide> if postgresql_version < 90300
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def supports_json?
<ide> true
<ide> end
<ide>
<add> def supports_insert_on_conflict?
<add> sqlite_version >= "3.24.0"
<add> end
<add> alias supports_insert_on_duplicate_skip? supports_insert_on_conflict?
<add> alias supports_insert_on_duplicate_update? supports_insert_on_conflict?
<add> alias supports_insert_conflict_target? supports_insert_on_conflict?
<add>
<ide> def active?
<ide> @active
<ide> end
<ide> def insert_fixtures_set(fixture_set, tables_to_delete = [])
<ide> end
<ide> end
<ide>
<add> def build_insert_sql(insert) # :nodoc:
<add> sql = +"INSERT #{insert.into} #{insert.values_list}"
<add>
<add> if insert.skip_duplicates?
<add> sql << " ON CONFLICT #{insert.conflict_target} DO NOTHING"
<add> elsif insert.update_duplicates?
<add> sql << " ON CONFLICT #{insert.conflict_target} DO UPDATE SET "
<add> sql << insert.updatable_columns.map { |column| "#{column}=excluded.#{column}" }.join(",")
<add> end
<add>
<add> sql
<add> end
<add>
<ide> private
<ide> # See https://www.sqlite.org/limits.html,
<ide> # the default value is 999 when not configured.
<ide><path>activerecord/lib/active_record/insert_all.rb
<add># frozen_string_literal: true
<add>
<add>module ActiveRecord
<add> class InsertAll
<add> attr_reader :model, :connection, :inserts, :on_duplicate, :returning, :unique_by
<add>
<add> def initialize(model, inserts, on_duplicate:, returning: nil, unique_by: nil)
<add> @model, @connection, @inserts, @on_duplicate, @returning, @unique_by = model, model.connection, inserts, on_duplicate, returning, unique_by
<add> @returning = (connection.supports_insert_returning? ? primary_keys : false) if @returning.nil?
<add> @returning = false if @returning == []
<add> @on_duplicate = :skip if @on_duplicate == :update && updatable_columns.empty?
<add>
<add> ensure_valid_options_for_connection!
<add> end
<add>
<add> def execute
<add> if inserts.present?
<add> connection.exec_query to_sql, "Bulk Insert"
<add> else
<add> ActiveRecord::Result.new([], [])
<add> end
<add> end
<add>
<add> def keys
<add> inserts.present? ? inserts.first.keys.map(&:to_s) : []
<add> end
<add>
<add> def updatable_columns
<add> keys - readonly_columns - unique_by_columns
<add> end
<add>
<add> def skip_duplicates?
<add> on_duplicate == :skip
<add> end
<add>
<add> def update_duplicates?
<add> on_duplicate == :update
<add> end
<add>
<add> private
<add> def ensure_valid_options_for_connection!
<add> if returning && !connection.supports_insert_returning?
<add> raise ArgumentError, "#{connection.class} does not support :returning"
<add> end
<add>
<add> unless %i{ raise skip update }.member?(on_duplicate)
<add> raise NotImplementedError, "#{on_duplicate.inspect} is an unknown value for :on_duplicate. Valid values are :raise, :skip, and :update"
<add> end
<add>
<add> if on_duplicate == :skip && !connection.supports_insert_on_duplicate_skip?
<add> raise ArgumentError, "#{connection.class} does not support skipping duplicates"
<add> end
<add>
<add> if on_duplicate == :update && !connection.supports_insert_on_duplicate_update?
<add> raise ArgumentError, "#{connection.class} does not support upsert"
<add> end
<add>
<add> if unique_by && !connection.supports_insert_conflict_target?
<add> raise ArgumentError, "#{connection.class} does not support :unique_by"
<add> end
<add> end
<add>
<add> def to_sql
<add> connection.build_insert_sql(ActiveRecord::InsertAll::Builder.new(self))
<add> end
<add>
<add> def readonly_columns
<add> primary_keys + model.readonly_attributes.to_a
<add> end
<add>
<add> def unique_by_columns
<add> unique_by ? unique_by.fetch(:columns).map(&:to_s) : []
<add> end
<add>
<add> def primary_keys
<add> Array.wrap(model.primary_key)
<add> end
<add>
<add>
<add> class Builder
<add> attr_reader :model
<add>
<add> delegate :skip_duplicates?, :update_duplicates?, to: :insert_all
<add>
<add> def initialize(insert_all)
<add> @insert_all, @model, @connection = insert_all, insert_all.model, insert_all.connection
<add> end
<add>
<add> def into
<add> "INTO #{model.quoted_table_name}(#{columns_list})"
<add> end
<add>
<add> def values_list
<add> columns = connection.schema_cache.columns_hash(model.table_name)
<add> keys = insert_all.keys.to_set
<add> types = keys.map { |key| [ key, connection.lookup_cast_type_from_column(columns[key]) ] }.to_h
<add>
<add> values_list = insert_all.inserts.map do |attributes|
<add> attributes = attributes.stringify_keys
<add>
<add> unless attributes.keys.to_set == keys
<add> raise ArgumentError, "All objects being inserted must have the same keys"
<add> end
<add>
<add> keys.map do |key|
<add> bind = Relation::QueryAttribute.new(key, attributes[key], types[key])
<add> connection.with_yaml_fallback(bind.value_for_database)
<add> end
<add> end
<add>
<add> Arel::InsertManager.new.create_values_list(values_list).to_sql
<add> end
<add>
<add> def returning
<add> quote_columns(insert_all.returning).join(",") if insert_all.returning
<add> end
<add>
<add> def conflict_target
<add> return unless conflict_columns
<add> sql = +"(#{quote_columns(conflict_columns).join(',')})"
<add> sql << " WHERE #{where}" if where
<add> sql
<add> end
<add>
<add> def updatable_columns
<add> quote_columns(insert_all.updatable_columns)
<add> end
<add>
<add> private
<add> attr_reader :connection, :insert_all
<add>
<add> def columns_list
<add> quote_columns(insert_all.keys).join(",")
<add> end
<add>
<add> def quote_columns(columns)
<add> columns.map(&connection.method(:quote_column_name))
<add> end
<add>
<add> def conflict_columns
<add> @conflict_columns ||= begin
<add> conflict_columns = insert_all.unique_by.fetch(:columns) if insert_all.unique_by
<add> conflict_columns ||= Array.wrap(model.primary_key) if update_duplicates?
<add> conflict_columns
<add> end
<add> end
<add>
<add> def where
<add> insert_all.unique_by && insert_all.unique_by[:where]
<add> end
<add> end
<add> end
<add>end
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "active_record/insert_all"
<add>
<ide> module ActiveRecord
<ide> # = Active Record \Persistence
<ide> module Persistence
<ide> def create!(attributes = nil, &block)
<ide> end
<ide> end
<ide>
<add> # Inserts a single record into the databases. This method constructs a single SQL INSERT
<add> # statement and sends it straight to the database. It does not instantiate the involved
<add> # models and it does not trigger Active Record callbacks or validations. However, values
<add> # passed to #insert will still go through Active Record's normal type casting and
<add> # serialization.
<add> #
<add> # See <tt>ActiveRecord::Persistence#insert_all</tt> for documentation.
<add> def insert(attributes, returning: nil, unique_by: nil)
<add> insert_all([ attributes ], returning: returning, unique_by: unique_by)
<add> end
<add>
<add> # Inserts multiple records into the database. This method constructs a single SQL INSERT
<add> # statement and sends it straight to the database. It does not instantiate the involved
<add> # models and it does not trigger Active Record callbacks or validations. However, values
<add> # passed to #insert_all will still go through Active Record's normal type casting and
<add> # serialization.
<add> #
<add> # The +attributes+ parameter is an Array of Hashes. These Hashes describe the
<add> # attributes on the objects that are to be created. All of the Hashes must have
<add> # same keys.
<add> #
<add> # Records that would violate a unique constraint on the table are skipped.
<add> #
<add> # Returns an <tt>ActiveRecord::Result</tt>. The contents of the result depend on the
<add> # value of <tt>:returning</tt> (see below).
<add> #
<add> # ==== Options
<add> #
<add> # [:returning]
<add> # (Postgres-only) An array of attributes that should be returned for all successfully
<add> # inserted records. For databases that support <tt>INSERT ... RETURNING</tt>, this will default
<add> # to returning the primary keys of the successfully inserted records. Pass
<add> # <tt>returning: %w[ id name ]</tt> to return the id and name of every successfully inserted
<add> # record or pass <tt>returning: false</tt> to omit the clause.
<add> #
<add> # [:unique_by]
<add> # (Postgres and SQLite only) In a table with more than one unique constaint or index,
<add> # new records may considered duplicates according to different criteria. By default,
<add> # new rows will be skipped if they violate _any_ unique constraint/index. By defining
<add> # <tt>:unique_by</tt>, you can skip rows that would create duplicates according to the given
<add> # constraint but raise <tt>ActiveRecord::RecordNotUnique</tt> if rows violate other constraints.
<add> #
<add> # (For example, maybe you assume a client will try to import the same ISBNs more than
<add> # once and want to silently ignore the duplicate records, but you don't except any of
<add> # your code to attempt to create two rows with the same primary key and would appreciate
<add> # an exception report in that scenario.)
<add> #
<add> # Indexes can be identified by an array of columns:
<add> #
<add> # unique_by: { columns: %w[ isbn ] }
<add> #
<add> # Partial indexes can be identified by an array of columns and a <tt>:where</tt> condition:
<add> #
<add> # unique_by: { columns: %w[ isbn ], where: "published_on IS NOT NULL" }
<add> #
<add> # ==== Example
<add> #
<add> # # Insert multiple records and skip duplicates
<add> # # ('Eloquent Ruby' will be skipped because its id is duplicate)
<add> # Book.insert_all([
<add> # { id: 1, title: 'Rework', author: 'David' },
<add> # { id: 1, title: 'Eloquent Ruby', author: 'Russ' }
<add> # ])
<add> #
<add> def insert_all(attributes, returning: nil, unique_by: nil)
<add> InsertAll.new(self, attributes, on_duplicate: :skip, returning: returning, unique_by: unique_by).execute
<add> end
<add>
<add> # Inserts a single record into the databases. This method constructs a single SQL INSERT
<add> # statement and sends it straight to the database. It does not instantiate the involved
<add> # models and it does not trigger Active Record callbacks or validations. However, values
<add> # passed to #insert! will still go through Active Record's normal type casting and
<add> # serialization.
<add> #
<add> # See <tt>ActiveRecord::Persistence#insert_all!</tt> for documentation.
<add> def insert!(attributes, returning: nil)
<add> insert_all!([ attributes ], returning: returning)
<add> end
<add>
<add> # Inserts multiple records into the database. This method constructs a single SQL INSERT
<add> # statement and sends it straight to the database. It does not instantiate the involved
<add> # models and it does not trigger Active Record callbacks or validations. However, values
<add> # passed to #insert_all! will still go through Active Record's normal type casting and
<add> # serialization.
<add> #
<add> # The +attributes+ parameter is an Array of Hashes. These Hashes describe the
<add> # attributes on the objects that are to be created. All of the Hashes must have
<add> # same keys.
<add> #
<add> # #insert_all! will raise <tt>ActiveRecord::RecordNotUnique</tt> if any of the records being
<add> # inserts would violate a unique constraint on the table. In that case, no records
<add> # would be inserted.
<add> #
<add> # To skip duplicate records, see <tt>ActiveRecord::Persistence#insert_all</tt>.
<add> # To replace them, see <tt>ActiveRecord::Persistence#upsert_all</tt>.
<add> #
<add> # Returns an <tt>ActiveRecord::Result</tt>. The contents of the result depend on the
<add> # value of <tt>:returning</tt> (see below).
<add> #
<add> # ==== Options
<add> #
<add> # [:returning]
<add> # (Postgres-only) An array of attributes that should be returned for all successfully
<add> # inserted records. For databases that support <tt>INSERT ... RETURNING</tt>, this will default
<add> # to returning the primary keys of the successfully inserted records. Pass
<add> # <tt>returning: %w[ id name ]</tt> to return the id and name of every successfully inserted
<add> # record or pass <tt>returning: false</tt> to omit the clause.
<add> #
<add> # ==== Examples
<add> #
<add> # # Insert multiple records
<add> # Book.insert_all!([
<add> # { title: 'Rework', author: 'David' },
<add> # { title: 'Eloquent Ruby', author: 'Russ' }
<add> # ])
<add> #
<add> # # raises ActiveRecord::RecordNotUnique beacuse 'Eloquent Ruby'
<add> # # does not have a unique ID
<add> # Book.insert_all!([
<add> # { id: 1, title: 'Rework', author: 'David' },
<add> # { id: 1, title: 'Eloquent Ruby', author: 'Russ' }
<add> # ])
<add> #
<add> def insert_all!(attributes, returning: nil)
<add> InsertAll.new(self, attributes, on_duplicate: :raise, returning: returning).execute
<add> end
<add>
<add> # Upserts (inserts-or-creates) a single record into the databases. This method constructs
<add> # a single SQL INSERT statement and sends it straight to the database. It does not
<add> # instantiate the involved models and it does not trigger Active Record callbacks or
<add> # validations. However, values passed to #upsert will still go through Active Record's
<add> # normal type casting and serialization.
<add> #
<add> # See <tt>ActiveRecord::Persistence#upsert_all</tt> for documentation.
<add> def upsert(attributes, returning: nil, unique_by: nil)
<add> upsert_all([ attributes ], returning: returning, unique_by: unique_by)
<add> end
<add>
<add> # Upserts (creates-or-updates) multiple records into the database. This method constructs
<add> # a single SQL INSERT statement and sends it straight to the database. It does not
<add> # instantiate the involved models and it does not trigger Active Record callbacks or
<add> # validations. However, values passed to #upsert_all will still go through Active Record's
<add> # normal type casting and serialization.
<add> #
<add> # The +attributes+ parameter is an Array of Hashes. These Hashes describe the
<add> # attributes on the objects that are to be created. All of the Hashes must have
<add> # same keys.
<add> #
<add> # Returns an <tt>ActiveRecord::Result</tt>. The contents of the result depend on the
<add> # value of <tt>:returning</tt> (see below).
<add> #
<add> # ==== Options
<add> #
<add> # [:returning]
<add> # (Postgres-only) An array of attributes that should be returned for all successfully
<add> # inserted records. For databases that support <tt>INSERT ... RETURNING</tt>, this will default
<add> # to returning the primary keys of the successfully inserted records. Pass
<add> # <tt>returning: %w[ id name ]</tt> to return the id and name of every successfully inserted
<add> # record or pass <tt>returning: false</tt> to omit the clause.
<add> #
<add> # [:unique_by]
<add> # (Postgres and SQLite only) In a table with more than one unique constaint or index,
<add> # new records may considered duplicates according to different criteria. For MySQL,
<add> # an upsert will take place if a new record violates _any_ unique constraint. For
<add> # Postgres and SQLite, new rows will replace existing rows when the new row has the
<add> # same primary key as the existing row. By defining <tt>:unique_by</tt>, you can supply
<add> # a different key for matching new records to existing ones than the primary key.
<add> #
<add> # (For example, if you have a unique index on the ISBN column and use that as
<add> # the <tt>:unique_by</tt>, a new record with the same ISBN as an existing record
<add> # will replace the existing record but a new record with the same primary key
<add> # as an existing record will raise <tt>ActiveRecord::RecordNotUnique</tt>.)
<add> #
<add> # Indexes can be identified by an array of columns:
<add> #
<add> # unique_by: { columns: %w[ isbn ] }
<add> #
<add> # Partial indexes can be identified by an array of columns and a <tt>:where</tt> condition:
<add> #
<add> # unique_by: { columns: %w[ isbn ], where: "published_on IS NOT NULL" }
<add> #
<add> # ==== Examples
<add> #
<add> # # Insert multiple records, performing an upsert when records have duplicate ISBNs
<add> # # ('Eloquent Ruby' will overwrite 'Rework' because its ISBN is duplicate)
<add> # Book.upsert_all([
<add> # { title: 'Rework', author: 'David', isbn: '1' },
<add> # { title: 'Eloquent Ruby', author: 'Russ', isbn: '1' }
<add> # ],
<add> # unique_by: { columns: %w[ isbn ] })
<add> #
<add> def upsert_all(attributes, returning: nil, unique_by: nil)
<add> InsertAll.new(self, attributes, on_duplicate: :update, returning: returning, unique_by: unique_by).execute
<add> end
<add>
<ide> # Given an attributes hash, +instantiate+ returns a new instance of
<ide> # the appropriate class. Accepts only keys as strings.
<ide> #
<ide><path>activerecord/test/cases/helper.rb
<ide> def supports_default_expression?
<ide> end
<ide> end
<ide>
<del>def supports_savepoints?
<del> ActiveRecord::Base.connection.supports_savepoints?
<add>%w[
<add> supports_savepoints?
<add> supports_partial_index?
<add> supports_insert_returning?
<add> supports_insert_on_duplicate_skip?
<add> supports_insert_on_duplicate_update?
<add> supports_insert_conflict_target?
<add>].each do |method_name|
<add> define_method method_name do
<add> ActiveRecord::Base.connection.public_send(method_name)
<add> end
<ide> end
<ide>
<ide> def with_env_tz(new_tz = "US/Eastern")
<ide><path>activerecord/test/cases/insert_all_test.rb
<add># frozen_string_literal: true
<add>
<add>require "cases/helper"
<add>require "models/book"
<add>
<add>class ReadonlyNameBook < Book
<add> attr_readonly :name
<add>end
<add>
<add>class PersistenceTest < ActiveRecord::TestCase
<add> fixtures :books
<add>
<add> def test_insert
<add> assert_difference "Book.count", +1 do
<add> Book.insert! name: "Rework", author_id: 1
<add> end
<add> end
<add>
<add> def test_insert_all
<add> assert_difference "Book.count", +10 do
<add> Book.insert_all! [
<add> { name: "Rework", author_id: 1 },
<add> { name: "Patterns of Enterprise Application Architecture", author_id: 1 },
<add> { name: "Design of Everyday Things", author_id: 1 },
<add> { name: "Practical Object-Oriented Design in Ruby", author_id: 1 },
<add> { name: "Clean Code", author_id: 1 },
<add> { name: "Ruby Under a Microscope", author_id: 1 },
<add> { name: "The Principles of Product Development Flow", author_id: 1 },
<add> { name: "Peopleware", author_id: 1 },
<add> { name: "About Face", author_id: 1 },
<add> { name: "Eloquent Ruby", author_id: 1 },
<add> ]
<add> end
<add> end
<add>
<add> def test_insert_all_should_handle_empty_arrays
<add> assert_no_difference "Book.count" do
<add> Book.insert_all! []
<add> end
<add> end
<add>
<add> def test_insert_all_raises_on_duplicate_records
<add> assert_raise ActiveRecord::RecordNotUnique do
<add> Book.insert_all! [
<add> { name: "Rework", author_id: 1 },
<add> { name: "Patterns of Enterprise Application Architecture", author_id: 1 },
<add> { name: "Agile Web Development with Rails", author_id: 1 },
<add> ]
<add> end
<add> end
<add>
<add> def test_insert_all_returns_ActiveRecord_Result
<add> result = Book.insert_all! [{ name: "Rework", author_id: 1 }]
<add> assert_kind_of ActiveRecord::Result, result
<add> end
<add>
<add> def test_insert_all_returns_primary_key_if_returning_is_supported
<add> skip unless supports_insert_returning?
<add> result = Book.insert_all! [{ name: "Rework", author_id: 1 }]
<add> assert_equal %w[ id ], result.columns
<add> end
<add>
<add> def test_insert_all_returns_nothing_if_returning_is_empty
<add> skip unless supports_insert_returning?
<add> result = Book.insert_all! [{ name: "Rework", author_id: 1 }], returning: []
<add> assert_equal [], result.columns
<add> end
<add>
<add> def test_insert_all_returns_nothing_if_returning_is_false
<add> skip unless supports_insert_returning?
<add> result = Book.insert_all! [{ name: "Rework", author_id: 1 }], returning: false
<add> assert_equal [], result.columns
<add> end
<add>
<add> def test_insert_all_returns_requested_fields
<add> skip unless supports_insert_returning?
<add> result = Book.insert_all! [{ name: "Rework", author_id: 1 }], returning: [:id, :name]
<add> assert_equal %w[ Rework ], result.pluck("name")
<add> end
<add>
<add> def test_insert_all_can_skip_duplicate_records
<add> skip unless supports_insert_on_duplicate_skip?
<add> assert_no_difference "Book.count" do
<add> Book.insert_all [{ id: 1, name: "Agile Web Development with Rails" }]
<add> end
<add> end
<add>
<add> def test_insert_all_will_raise_if_duplicates_are_skipped_only_for_a_certain_conflict_target
<add> skip unless supports_insert_on_duplicate_skip? && supports_insert_conflict_target?
<add> assert_raise ActiveRecord::RecordNotUnique do
<add> Book.insert_all [{ id: 1, name: "Agile Web Development with Rails" }],
<add> unique_by: { columns: %i{author_id name} }
<add> end
<add> end
<add>
<add> def test_upsert_all_updates_existing_records
<add> skip unless supports_insert_on_duplicate_update?
<add> new_name = "Agile Web Development with Rails, 4th Edition"
<add> Book.upsert_all [{ id: 1, name: new_name }]
<add> assert_equal new_name, Book.find(1).name
<add> end
<add>
<add> def test_upsert_all_does_not_update_readonly_attributes
<add> skip unless supports_insert_on_duplicate_update?
<add> new_name = "Agile Web Development with Rails, 4th Edition"
<add> ReadonlyNameBook.upsert_all [{ id: 1, name: new_name }]
<add> assert_not_equal new_name, Book.find(1).name
<add> end
<add>
<add> def test_upsert_all_does_not_update_primary_keys
<add> skip unless supports_insert_on_duplicate_update? && supports_insert_conflict_target?
<add> Book.upsert_all [{ id: 101, name: "Perelandra", author_id: 7 }]
<add> Book.upsert_all [{ id: 103, name: "Perelandra", author_id: 7, isbn: "1974522598" }],
<add> unique_by: { columns: %i{author_id name} }
<add> book = Book.find_by(name: "Perelandra")
<add> assert_equal 101, book.id, "Should not have updated the ID"
<add> assert_equal "1974522598", book.isbn, "Should have updated the isbn"
<add> end
<add>
<add> def test_upsert_all_does_not_perform_an_upsert_if_a_partial_index_doesnt_apply
<add> skip unless supports_insert_on_duplicate_update? && supports_insert_conflict_target? && supports_partial_index?
<add> Book.upsert_all [{ name: "Out of the Silent Planet", author_id: 7, isbn: "1974522598", published_on: Date.new(1938, 4, 1) }]
<add> Book.upsert_all [{ name: "Perelandra", author_id: 7, isbn: "1974522598" }],
<add> unique_by: { columns: %w[ isbn ], where: "published_on IS NOT NULL" }
<add> assert_equal ["Out of the Silent Planet", "Perelandra"], Book.where(isbn: "1974522598").order(:name).pluck(:name)
<add> end
<add>end
<ide><path>activerecord/test/cases/instrumentation_test.rb
<ide> def test_payload_name_on_update
<ide> assert_equal "Book Update", event.payload[:name]
<ide> end
<ide> end
<del> book = Book.create(name: "test book")
<del> book.update_attribute(:name, "new name")
<add> book = Book.create(name: "test book", format: "paperback")
<add> book.update_attribute(:format, "ebook")
<ide> ensure
<ide> ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber
<ide> end
<ide> def test_payload_name_on_update_all
<ide> assert_equal "Book Update All", event.payload[:name]
<ide> end
<ide> end
<del> Book.create(name: "test book")
<del> Book.update_all(name: "new name")
<add> Book.create(name: "test book", format: "paperback")
<add> Book.update_all(format: "ebook")
<ide> ensure
<ide> ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber
<ide> end
<ide><path>activerecord/test/schema/schema.rb
<ide> t.column :font_size, :integer, **default_zero
<ide> t.column :difficulty, :integer, **default_zero
<ide> t.column :cover, :string, default: "hard"
<add> t.string :isbn
<add> t.datetime :published_on
<add> t.index [:author_id, :name], unique: true
<add> t.index :isbn, where: "published_on IS NOT NULL", unique: true
<ide> end
<ide>
<ide> create_table :booleans, force: true do |t| | 12 |
Javascript | Javascript | use $viewvalue instead of $modelvalue | f7174169f4f710d605f6a67f39f90a67a07d4cab | <ide><path>src/ng/directive/select.js
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> function getSelectedSet() {
<ide> var selectedSet = false;
<ide> if (multiple) {
<del> var modelValue = ctrl.$modelValue;
<del> if (trackFn && isArray(modelValue)) {
<add> var viewValue = ctrl.$viewValue;
<add> if (trackFn && isArray(viewValue)) {
<ide> selectedSet = new HashMap([]);
<ide> var locals = {};
<del> for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
<del> locals[valueName] = modelValue[trackIndex];
<del> selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
<add> for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {
<add> locals[valueName] = viewValue[trackIndex];
<add> selectedSet.put(trackFn(scope, locals), viewValue[trackIndex]);
<ide> }
<ide> } else {
<del> selectedSet = new HashMap(modelValue);
<add> selectedSet = new HashMap(viewValue);
<ide> }
<ide> }
<ide> return selectedSet;
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> optionGroup,
<ide> option,
<ide> existingParent, existingOptions, existingOption,
<del> modelValue = ctrl.$modelValue,
<add> viewValue = ctrl.$viewValue,
<ide> values = valuesFn(scope) || [],
<ide> keys = keyName ? sortedKeys(values) : values,
<ide> key,
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> } else {
<ide> if (trackFn) {
<ide> var modelCast = {};
<del> modelCast[valueName] = modelValue;
<add> modelCast[valueName] = viewValue;
<ide> selected = trackFn(scope, modelCast) === trackFn(scope, locals);
<ide> } else {
<del> selected = modelValue === valueFn(scope, locals);
<add> selected = viewValue === valueFn(scope, locals);
<ide> }
<ide> selectedSet = selectedSet || selected; // see if at least one item is selected
<ide> }
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> });
<ide> }
<ide> if (!multiple) {
<del> if (nullOption || modelValue === null) {
<add> if (nullOption || viewValue === null) {
<ide> // insert null option if we have a placeholder, or the model is null
<ide> optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
<ide> } else if (!selectedSet) {
<ide><path>test/ng/directive/selectSpec.js
<ide> describe('select', function() {
<ide> expect(scope.value).toBe(false);
<ide> });
<ide> });
<add>
<add> describe('ngModelCtrl', function() {
<add> it('should prefix the model value with the word "the" using $parsers', function() {
<add> createSelect({
<add> 'name': 'select',
<add> 'ng-model': 'value',
<add> 'ng-options': 'item for item in [\'first\', \'second\', \'third\', \'fourth\']',
<add> });
<add>
<add> scope.form.select.$parsers.push(function(value) {
<add> return 'the ' + value;
<add> });
<add>
<add> element.val('2');
<add> browserTrigger(element, 'change');
<add> expect(scope.value).toBe('the third');
<add> expect(element.val()).toBe('2');
<add> });
<add>
<add> it('should prefix the view value with the word "the" using $formatters', function() {
<add> createSelect({
<add> 'name': 'select',
<add> 'ng-model': 'value',
<add> 'ng-options': 'item for item in [\'the first\', \'the second\', \'the third\', \'the fourth\']',
<add> });
<add>
<add> scope.form.select.$formatters.push(function(value) {
<add> return 'the ' + value;
<add> });
<add>
<add> scope.$apply(function() {
<add> scope.value = 'third';
<add> });
<add> expect(element.val()).toBe('2');
<add> });
<add>
<add> it('should fail validation when $validators fail', function() {
<add> createSelect({
<add> 'name': 'select',
<add> 'ng-model': 'value',
<add> 'ng-options': 'item for item in [\'first\', \'second\', \'third\', \'fourth\']',
<add> });
<add>
<add> scope.form.select.$validators.fail = function() {
<add> return false;
<add> };
<add>
<add> element.val('2');
<add> browserTrigger(element, 'change');
<add> expect(element).toBeInvalid();
<add> expect(scope.value).toBeUndefined();
<add> expect(element.val()).toBe('2');
<add> });
<add>
<add> it('should pass validation when $validators pass', function() {
<add> createSelect({
<add> 'name': 'select',
<add> 'ng-model': 'value',
<add> 'ng-options': 'item for item in [\'first\', \'second\', \'third\', \'fourth\']',
<add> });
<add>
<add> scope.form.select.$validators.pass = function() {
<add> return true;
<add> };
<add>
<add> element.val('2');
<add> browserTrigger(element, 'change');
<add> expect(element).toBeValid();
<add> expect(scope.value).toBe('third');
<add> expect(element.val()).toBe('2');
<add> });
<add>
<add> it('should fail validation when $asyncValidators fail', inject(function($q, $rootScope) {
<add> var defer;
<add> createSelect({
<add> 'name': 'select',
<add> 'ng-model': 'value',
<add> 'ng-options': 'item for item in [\'first\', \'second\', \'third\', \'fourth\']',
<add> });
<add>
<add> scope.form.select.$asyncValidators.async = function() {
<add> defer = $q.defer();
<add> return defer.promise;
<add> };
<add>
<add> element.val('2');
<add> browserTrigger(element, 'change');
<add> expect(scope.form.select.$pending).toBeDefined();
<add> expect(scope.value).toBeUndefined();
<add> expect(element.val()).toBe('2');
<add>
<add> defer.reject();
<add> $rootScope.$digest();
<add> expect(scope.form.select.$pending).toBeUndefined();
<add> expect(scope.value).toBeUndefined();
<add> expect(element.val()).toBe('2');
<add> }));
<add>
<add> it('should pass validation when $asyncValidators pass', inject(function($q, $rootScope) {
<add> var defer;
<add> createSelect({
<add> 'name': 'select',
<add> 'ng-model': 'value',
<add> 'ng-options': 'item for item in [\'first\', \'second\', \'third\', \'fourth\']',
<add> });
<add>
<add> scope.form.select.$asyncValidators.async = function() {
<add> defer = $q.defer();
<add> return defer.promise;
<add> };
<add>
<add> element.val('2');
<add> browserTrigger(element, 'change');
<add> expect(scope.form.select.$pending).toBeDefined();
<add> expect(scope.value).toBeUndefined();
<add> expect(element.val()).toBe('2');
<add>
<add> defer.resolve();
<add> $rootScope.$digest();
<add> expect(scope.form.select.$pending).toBeUndefined();
<add> expect(scope.value).toBe('third');
<add> expect(element.val()).toBe('2');
<add> }));
<add> });
<ide> });
<ide>
<ide> | 2 |
Text | Text | replace unnecessary template literals | dddab5d4b1af7c6837d32a410bc5e1e44fcf15c1 | <ide><path>docs/recipes/WritingTests.md
<ide> const create = () => {
<ide> We test that our middleware is calling the `getState`, `dispatch`, and `next` functions at the right time.
<ide>
<ide> ```js
<del>it(`passes through non-function action`, () => {
<add>it('passes through non-function action', () => {
<ide> const { next, invoke } = create()
<ide> const action = {type: 'TEST'}
<ide> invoke(action) | 1 |
Ruby | Ruby | use --verify when querying head | 10f8443f8ae9f008c2bc45b0e80bcbb2f6419806 | <ide><path>Library/Homebrew/cmd/update.rb
<ide> def report
<ide> private
<ide>
<ide> def read_current_revision
<del> `git rev-parse HEAD`.chomp
<add> `git rev-parse -q --verify HEAD`.chomp
<ide> end
<ide>
<ide> def `(cmd) | 1 |
Python | Python | fix a typo in an error message | 9d5d0ec2264c86a19714cf185a5a183df14cbb94 | <ide><path>numpy/_array_api/_elementwise_functions.py
<ide> def bitwise_and(x1: Array, x2: Array, /) -> Array:
<ide> See its docstring for more information.
<ide> """
<ide> if x1.dtype not in _integer_or_boolean_dtypes or x2.dtype not in _integer_or_boolean_dtypes:
<del> raise TypeError('Only integer_or_boolean dtypes are allowed in bitwise_and')
<add> raise TypeError('Only integer or boolean dtypes are allowed in bitwise_and')
<ide> x1, x2 = Array._normalize_two_args(x1, x2)
<ide> return Array._new(np.bitwise_and(x1._array, x2._array))
<ide> | 1 |
PHP | PHP | add an environment method to app | 33f6acba80dd743e173e52d1b0e1116c6700b4d3 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function startExceptionHandling()
<ide> $provider->startHandling($this);
<ide> }
<ide>
<add> /**
<add> * Get the current application environment.
<add> *
<add> * @return string
<add> */
<add> public function environment()
<add> {
<add> return $this['env'];
<add> }
<add>
<ide> /**
<ide> * Detect the application's current environment.
<ide> *
<ide> public function detectEnvironment($environments)
<ide> {
<ide> $base = $this['request']->getHost();
<ide>
<del> // First we will check to see if we have any command-line arguments and if
<del> // if we do we will set this environment based on those arguments as we
<del> // need to set it before each configurations are actually loaded out.
<ide> $arguments = $this['request']->server->get('argv');
<ide>
<ide> if ($this->runningInConsole()) | 1 |
Ruby | Ruby | convert license array to hash | 6eb07d70f04d67345934764bb4316c8af43d5cb1 | <ide><path>Library/Homebrew/formula.rb
<ide> def method_added(method)
<ide> # <pre>license all_of: ["MIT", "GPL-2.0-only"]</pre>
<ide> # <pre>license "GPL-2.0-only" => { with: "LLVM-exception" }</pre>
<ide> # <pre>license :public_domain</pre>
<del> attr_rw :license
<add> def license(args = nil)
<add> if args.nil?
<add> @licenses
<add> else
<add> args = { any_of: args } if args.is_a? Array
<add> @licenses = args
<add> end
<add> end
<ide>
<ide> # @!attribute [w] homepage
<ide> # The homepage for the software. Used by users to get more information
<ide><path>Library/Homebrew/test/utils/spdx_spec.rb
<ide> expect(described_class.license_expression_to_string(any_of: ["MIT", "EPL-1.0+"])).to eq "MIT or EPL-1.0+"
<ide> end
<ide>
<del> it "treats array as any_of:" do
<del> expect(described_class.license_expression_to_string(["MIT", "EPL-1.0+"])).to eq "MIT or EPL-1.0+"
<del> end
<del>
<ide> it "returns license and exception" do
<ide> license_expression = { "MIT" => { with: "LLVM-exception" } }
<ide> expect(described_class.license_expression_to_string(license_expression)).to eq "MIT with LLVM-exception"
<ide> }
<ide> }
<ide> let(:any_of_license) { { any_of: ["MIT", "0BSD"] } }
<del> let(:license_array) { ["MIT", "0BSD"] }
<ide> let(:all_of_license) { { all_of: ["MIT", "0BSD"] } }
<ide> let(:nested_licenses) {
<ide> {
<ide> expect(described_class.licenses_forbid_installation?(any_of_license, multiple_forbidden)).to eq true
<ide> end
<ide>
<del> it "allows installation when one of the array licenses is allowed" do
<del> expect(described_class.licenses_forbid_installation?(license_array, mit_forbidden)).to eq false
<del> end
<del>
<del> it "forbids installation when none of the array licenses are allowed" do
<del> expect(described_class.licenses_forbid_installation?(license_array, multiple_forbidden)).to eq true
<del> end
<del>
<ide> it "forbids installation when one of the all_of licenses is allowed" do
<ide> expect(described_class.licenses_forbid_installation?(all_of_license, mit_forbidden)).to eq true
<ide> end
<ide><path>Library/Homebrew/utils/spdx.rb
<ide> def license_expression_to_string(license_expression, bracket: false, hash_type:
<ide> license_expression
<ide> when :public_domain
<ide> "Public Domain"
<del> when Hash, Array
<del> license_expression = { any_of: license_expression } if license_expression.is_a? Array
<add> when Hash
<ide> expressions = []
<ide>
<ide> if license_expression.keys.length == 1
<ide> def licenses_forbid_installation?(license_expression, forbidden_licenses)
<ide> case license_expression
<ide> when String, Symbol
<ide> forbidden_licenses_include? license_expression.to_s, forbidden_licenses
<del> when Hash, Array
<del> license_expression = { any_of: license_expression } if license_expression.is_a? Array
<add> when Hash
<ide> key = license_expression.keys.first
<ide> case key
<ide> when :any_of | 3 |
Mixed | Javascript | return this from getconnections() | 37fdfce93e333fbceb12576031602df641c058c8 | <ide><path>doc/api/net.md
<ide> connections use asynchronous `server.getConnections` instead.
<ide> added: v0.9.7
<ide> -->
<ide>
<add>* Returns {net.Server}
<add>
<ide> Asynchronously get the number of concurrent connections on the server. Works
<ide> when sockets were sent to forks.
<ide>
<ide><path>lib/net.js
<ide> Server.prototype.getConnections = function(cb) {
<ide> }
<ide>
<ide> if (!this._usingSlaves) {
<del> return end(null, this._connections);
<add> end(null, this._connections);
<add> return this;
<ide> }
<ide>
<ide> // Poll slaves
<ide> Server.prototype.getConnections = function(cb) {
<ide> for (var n = 0; n < this._slaves.length; n++) {
<ide> this._slaves[n].getConnections(oncount);
<ide> }
<add>
<add> return this;
<ide> };
<ide>
<ide>
<ide><path>test/parallel/test-net-pingpong.js
<ide> function pingPongTest(port, host) {
<ide>
<ide> function onSocket(socket) {
<ide> assert.strictEqual(socket.server, server);
<del> server.getConnections(common.mustCall(function(err, connections) {
<del> assert.ifError(err);
<del> assert.strictEqual(connections, 1);
<del> }));
<add> assert.strictEqual(
<add> server,
<add> server.getConnections(common.mustCall(function(err, connections) {
<add> assert.ifError(err);
<add> assert.strictEqual(connections, 1);
<add> }))
<add> );
<ide>
<ide> socket.setNoDelay();
<ide> socket.timeout = 0; | 3 |
Javascript | Javascript | use the es6 export syntax | 3ca4448afc784bc3ab5fc94692613e67fa22891e | <ide><path>src/git-repository-async.js
<ide> const indexStatusFlags = Git.Status.STATUS.INDEX_NEW | Git.Status.STATUS.INDEX_M
<ide> // Just using this for _.isEqual and _.object, we should impl our own here
<ide> import _ from 'underscore-plus'
<ide>
<del>module.exports = class GitRepositoryAsync {
<add>export default class GitRepositoryAsync {
<ide> static open (path, options = {}) {
<ide> // QUESTION: Should this wrap Git.Repository and reject with a nicer message?
<ide> return new GitRepositoryAsync(path, options) | 1 |
PHP | PHP | add type hinting to test suite package | 1cb5d9b44fa957998ee398b9366341b4874b8d9f | <ide><path>src/Console/ShellDispatcher.php
<ide> protected function _shellExists(string $shell): ?string
<ide> * @param string $shortName The plugin-prefixed shell name
<ide> * @return \Cake\Console\Shell A shell instance.
<ide> */
<del> protected function _createShell($className, $shortName)
<add> protected function _createShell(string $className, string $shortName): Shell
<ide> {
<ide> list($plugin) = pluginSplit($shortName);
<ide> $instance = new $className();
<ide><path>src/TestSuite/ConsoleIntegrationTestTrait.php
<ide> trait ConsoleIntegrationTestTrait
<ide> * @param array $input Input values to pass to an interactive shell
<ide> * @return void
<ide> */
<del> public function exec($command, array $input = [])
<add> public function exec(string $command, array $input = []): void
<ide> {
<ide> $runner = $this->makeRunner();
<ide>
<ide> public function exec($command, array $input = [])
<ide> *
<ide> * @return void
<ide> */
<del> public function tearDown()
<add> public function tearDown(): void
<ide> {
<ide> parent::tearDown();
<ide>
<ide> public function tearDown()
<ide> *
<ide> * @return void
<ide> */
<del> public function useCommandRunner()
<add> public function useCommandRunner(): void
<ide> {
<ide> $this->useCommandRunner = true;
<ide> }
<ide> public function useCommandRunner()
<ide> * @param string $message Failure message
<ide> * @return void
<ide> */
<del> public function assertExitCode($expected, $message = '')
<add> public function assertExitCode(int $expected, string $message = ''): void
<ide> {
<ide> $this->assertThat($expected, new ExitCode($this->exitCode), $message);
<ide> }
<ide> public function assertExitCode($expected, $message = '')
<ide> * @param string $message The message to output when the assertion fails.
<ide> * @return void
<ide> */
<del> public function assertOutputEmpty($message = '')
<add> public function assertOutputEmpty(string $message = ''): void
<ide> {
<ide> $this->assertThat(null, new ContentsEmpty($this->out->messages(), 'output'), $message);
<ide> }
<ide> public function assertOutputEmpty($message = '')
<ide> * @param string $message Failure message
<ide> * @return void
<ide> */
<del> public function assertOutputContains($expected, $message = '')
<add> public function assertOutputContains(string $expected, string $message = ''): void
<ide> {
<ide> $this->assertThat($expected, new ContentsContain($this->out->messages(), 'output'), $message);
<ide> }
<ide> public function assertOutputContains($expected, $message = '')
<ide> * @param string $message Failure message
<ide> * @return void
<ide> */
<del> public function assertOutputNotContains($expected, $message = '')
<add> public function assertOutputNotContains(string $expected, string $message = ''): void
<ide> {
<ide> $this->assertThat($expected, new ContentsNotContain($this->out->messages(), 'output'), $message);
<ide> }
<ide> public function assertOutputNotContains($expected, $message = '')
<ide> * @param string $message Failure message
<ide> * @return void
<ide> */
<del> public function assertOutputRegExp($pattern, $message = '')
<add> public function assertOutputRegExp(string $pattern, string $message = ''): void
<ide> {
<ide> $this->assertThat($pattern, new ContentsRegExp($this->out->messages(), 'output'), $message);
<ide> }
<ide> public function assertOutputRegExp($pattern, $message = '')
<ide> * @param string $message Failure message.
<ide> * @return void
<ide> */
<del> protected function assertOutputContainsRow(array $row, $message = '')
<add> protected function assertOutputContainsRow(array $row, string $message = ''): void
<ide> {
<ide> $this->assertThat($row, new ContentsContainRow($this->out->messages(), 'output'), $message);
<ide> }
<ide> protected function assertOutputContainsRow(array $row, $message = '')
<ide> * @param string $message Failure message
<ide> * @return void
<ide> */
<del> public function assertErrorContains($expected, $message = '')
<add> public function assertErrorContains(string $expected, string $message = ''): void
<ide> {
<ide> $this->assertThat($expected, new ContentsContain($this->err->messages(), 'error output'), $message);
<ide> }
<ide> public function assertErrorContains($expected, $message = '')
<ide> * @param string $message Failure message
<ide> * @return void
<ide> */
<del> public function assertErrorRegExp($pattern, $message = '')
<add> public function assertErrorRegExp(string $pattern, string $message = ''): void
<ide> {
<ide> $this->assertThat($pattern, new ContentsRegExp($this->err->messages(), 'error output'), $message);
<ide> }
<ide> public function assertErrorRegExp($pattern, $message = '')
<ide> * @param string $message The message to output when the assertion fails.
<ide> * @return void
<ide> */
<del> public function assertErrorEmpty($message = '')
<add> public function assertErrorEmpty(string $message = ''): void
<ide> {
<ide> $this->assertThat(null, new ContentsEmpty($this->err->messages(), 'error output'), $message);
<ide> }
<ide> protected function makeRunner()
<ide> * @param string $command Command string
<ide> * @return array
<ide> */
<del> protected function commandStringToArgs($command)
<add> protected function commandStringToArgs(string $command): array
<ide> {
<ide> $charCount = strlen($command);
<ide> $argv = [];
<ide><path>src/TestSuite/EmailTrait.php
<ide> trait EmailTrait
<ide> * Asserts an expected number of emails were sent
<ide> *
<ide> * @param int $count Email count
<del> * @param string $message Message
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailCount($count, $message = null)
<add> public function assertMailCount(int $count, ?string $message = null): void
<ide> {
<ide> $this->assertThat($count, new MailCount(), $message);
<ide> }
<ide> /**
<ide> *
<ide> * Asserts that no emails were sent
<ide> *
<del> * @param string $message Message
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertNoMailSent($message = null)
<add> public function assertNoMailSent(?string $message = null): void
<ide> {
<ide> $this->assertThat(null, new NoMailSent(), $message);
<ide> }
<ide> public function assertNoMailSent($message = null)
<ide> * Asserts an email at a specific index was sent to an address
<ide> *
<ide> * @param int $at Email index
<del> * @param int $address Email address
<del> * @param string $message Message
<add> * @param string $address Email address
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailSentToAt($at, $address, $message = null)
<add> public function assertMailSentToAt(int $at, string $address, ?string $message = null): void
<ide> {
<ide> $this->assertThat($address, new MailSentTo($at), $message);
<ide> }
<ide> public function assertMailSentToAt($at, $address, $message = null)
<ide> * Asserts an email at a specific index was sent from an address
<ide> *
<ide> * @param int $at Email index
<del> * @param int $address Email address
<del> * @param string $message Message
<add> * @param string $address Email address
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailSentFromAt($at, $address, $message = null)
<add> public function assertMailSentFromAt(int $at, string $address, ?string $message = null): void
<ide> {
<ide> $this->assertThat($address, new MailSentFrom($at), $message);
<ide> }
<ide> public function assertMailSentFromAt($at, $address, $message = null)
<ide> * Asserts an email at a specific index contains expected contents
<ide> *
<ide> * @param int $at Email index
<del> * @param int $contents Contents
<del> * @param string $message Message
<add> * @param string $contents Contents
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailContainsAt($at, $contents, $message = null)
<add> public function assertMailContainsAt(int $at, string $contents, ?string $message = null): void
<ide> {
<ide> $this->assertThat($contents, new MailContains($at), $message);
<ide> }
<ide> public function assertMailContainsAt($at, $contents, $message = null)
<ide> * Asserts an email at a specific index contains expected html contents
<ide> *
<ide> * @param int $at Email index
<del> * @param int $contents Contents
<del> * @param string $message Message
<add> * @param string $contents Contents
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailContainsHtmlAt($at, $contents, $message = null)
<add> public function assertMailContainsHtmlAt(int $at, string $contents, ?string $message = null): void
<ide> {
<ide> $this->assertThat($contents, new MailContainsHtml($at), $message);
<ide> }
<ide> public function assertMailContainsHtmlAt($at, $contents, $message = null)
<ide> * Asserts an email at a specific index contains expected text contents
<ide> *
<ide> * @param int $at Email index
<del> * @param int $contents Contents
<del> * @param string $message Message
<add> * @param string $contents Contents
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailContainsTextAt($at, $contents, $message = null)
<add> public function assertMailContainsTextAt(int $at, string $contents, ?string $message = null): void
<ide> {
<ide> $this->assertThat($contents, new MailContainsText($at), $message);
<ide> }
<ide> public function assertMailContainsTextAt($at, $contents, $message = null)
<ide> * Asserts an email at a specific index contains the expected value within an Email getter
<ide> *
<ide> * @param int $at Email index
<del> * @param int $expected Contents
<del> * @param int $parameter Email getter parameter (e.g. "cc", "subject")
<del> * @param string $message Message
<add> * @param string $expected Contents
<add> * @param string $parameter Email getter parameter (e.g. "cc", "subject")
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailSentWithAt($at, $expected, $parameter, $message = null)
<add> public function assertMailSentWithAt(int $at, string $expected, string $parameter, ?string $message = null): void
<ide> {
<ide> $this->assertThat($expected, new MailSentWith($at, $parameter), $message);
<ide> }
<ide>
<ide> /**
<ide> * Asserts an email was sent to an address
<ide> *
<del> * @param int $address Email address
<add> * @param string $address Email address
<ide> * @param string $message Message
<ide> * @return void
<ide> */
<del> public function assertMailSentTo($address, $message = null)
<add> public function assertMailSentTo(string $address, ?string $message = null): void
<ide> {
<ide> $this->assertThat($address, new MailSentTo(), $message);
<ide> }
<ide>
<ide> /**
<ide> * Asserts an email was sent from an address
<ide> *
<del> * @param int $address Email address
<del> * @param string $message Message
<add> * @param string $address Email address
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailSentFrom($address, $message = null)
<add> public function assertMailSentFrom(string $address, ?string $message = null): void
<ide> {
<ide> $this->assertThat($address, new MailSentFrom(), $message);
<ide> }
<ide>
<ide> /**
<ide> * Asserts an email contains expected contents
<ide> *
<del> * @param int $contents Contents
<del> * @param string $message Message
<add> * @param string $contents Contents
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailContains($contents, $message = null)
<add> public function assertMailContains(string $contents, ?string $message = null): void
<ide> {
<ide> $this->assertThat($contents, new MailContains(), $message);
<ide> }
<ide>
<ide> /**
<ide> * Asserts an email contains expected html contents
<ide> *
<del> * @param int $contents Contents
<del> * @param string $message Message
<add> * @param string $contents Contents
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailContainsHtml($contents, $message = null)
<add> public function assertMailContainsHtml(string $contents, ?string $message = null): void
<ide> {
<ide> $this->assertThat($contents, new MailContainsHtml(), $message);
<ide> }
<ide>
<ide> /**
<ide> * Asserts an email contains expected text contents
<ide> *
<del> * @param int $contents Contents
<del> * @param string $message Message
<add> * @param string $contents Contents
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailContainsText($contents, $message = null)
<add> public function assertMailContainsText(string $contents, ?string $message = null): void
<ide> {
<ide> $this->assertThat($contents, new MailContainsText(), $message);
<ide> }
<ide>
<ide> /**
<ide> * Asserts an email contains the expected value within an Email getter
<ide> *
<del> * @param int $expected Contents
<del> * @param int $parameter Email getter parameter (e.g. "cc", "subject")
<del> * @param string $message Message
<add> * @param string $expected Contents
<add> * @param string $parameter Email getter parameter (e.g. "cc", "subject")
<add> * @param string|null $message Message
<ide> * @return void
<ide> */
<del> public function assertMailSentWith($expected, $parameter, $message = null)
<add> public function assertMailSentWith(string $expected, string $parameter, ?string $message = null): void
<ide> {
<ide> $this->assertThat($expected, new MailSentWith(null, $parameter), $message);
<ide> }
<ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> public function tearDown()
<ide> * @param bool $enable Enable/disable the usage of the HTTP Stack.
<ide> * @return void
<ide> */
<del> public function useHttpServer($enable)
<add> public function useHttpServer(bool $enable): void
<ide> {
<ide> if ($enable === false) {
<ide> deprecationWarning('Calling `useHttpServer(false)` does nothing, and will be removed.');
<ide> public function useHttpServer($enable)
<ide> * @param array|null $constructorArgs The constructor arguments for your application class.
<ide> * @return void
<ide> */
<del> public function configApplication($class, $constructorArgs)
<add> public function configApplication(string $class, ?array $constructorArgs): void
<ide> {
<ide> $this->_appClass = $class;
<ide> $this->_appArgs = $constructorArgs;
<ide> public function configApplication($class, $constructorArgs)
<ide> *
<ide> * @return void
<ide> */
<del> public function enableSecurityToken()
<add> public function enableSecurityToken(): void
<ide> {
<ide> $this->_securityToken = true;
<ide> }
<ide> public function enableSecurityToken()
<ide> *
<ide> * @return void
<ide> */
<del> public function enableCsrfToken()
<add> public function enableCsrfToken(): void
<ide> {
<ide> $this->_csrfToken = true;
<ide> }
<ide> public function enableCsrfToken()
<ide> *
<ide> * @return void
<ide> */
<del> public function enableRetainFlashMessages()
<add> public function enableRetainFlashMessages(): void
<ide> {
<ide> $this->_retainFlashMessages = true;
<ide> }
<ide> public function enableRetainFlashMessages()
<ide> * @param array $data The request data to use.
<ide> * @return void
<ide> */
<del> public function configRequest(array $data)
<add> public function configRequest(array $data): void
<ide> {
<ide> $this->_request = $data + $this->_request;
<ide> }
<ide> public function configRequest(array $data)
<ide> * @param array $data The session data to use.
<ide> * @return void
<ide> */
<del> public function session(array $data)
<add> public function session(array $data): void
<ide> {
<ide> $this->_session = $data + $this->_session;
<ide> }
<ide> public function session(array $data)
<ide> * @param mixed $value The value of the cookie.
<ide> * @return void
<ide> */
<del> public function cookie($name, $value)
<add> public function cookie(string $name, $value): void
<ide> {
<ide> $this->_cookie[$name] = $value;
<ide> }
<ide> public function cookie($name, $value)
<ide> *
<ide> * @return string
<ide> */
<del> protected function _getCookieEncryptionKey()
<add> protected function _getCookieEncryptionKey(): string
<ide> {
<ide> if (isset($this->_cookieEncryptionKey)) {
<ide> return $this->_cookieEncryptionKey;
<ide> protected function _getCookieEncryptionKey()
<ide> * @return void
<ide> * @see \Cake\Utility\CookieCryptTrait::_encrypt()
<ide> */
<del> public function cookieEncrypted($name, $value, $encrypt = 'aes', $key = null)
<add> public function cookieEncrypted(string $name, $value, $encrypt = 'aes', $key = null): void
<ide> {
<ide> $this->_cookieEncryptionKey = $key;
<ide> $this->_cookie[$name] = $this->_encrypt($value, $encrypt);
<ide> public function cookieEncrypted($name, $value, $encrypt = 'aes', $key = null)
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<del> public function get($url)
<add> public function get($url): void
<ide> {
<ide> $this->_sendRequest($url, 'GET');
<ide> }
<ide> public function get($url)
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<del> public function post($url, $data = [])
<add> public function post($url, $data = []): void
<ide> {
<ide> $this->_sendRequest($url, 'POST', $data);
<ide> }
<ide> public function post($url, $data = [])
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<del> public function patch($url, $data = [])
<add> public function patch($url, $data = []): void
<ide> {
<ide> $this->_sendRequest($url, 'PATCH', $data);
<ide> }
<ide> public function patch($url, $data = [])
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<del> public function put($url, $data = [])
<add> public function put($url, $data = []): void
<ide> {
<ide> $this->_sendRequest($url, 'PUT', $data);
<ide> }
<ide> public function put($url, $data = [])
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<del> public function delete($url)
<add> public function delete($url): void
<ide> {
<ide> $this->_sendRequest($url, 'DELETE');
<ide> }
<ide> public function delete($url)
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<del> public function head($url)
<add> public function head($url): void
<ide> {
<ide> $this->_sendRequest($url, 'HEAD');
<ide> }
<ide> public function head($url)
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<del> public function options($url)
<add> public function options($url): void
<ide> {
<ide> $this->_sendRequest($url, 'OPTIONS');
<ide> }
<ide> public function options($url)
<ide> * @return void
<ide> * @throws \PHPUnit\Exception
<ide> */
<del> protected function _sendRequest($url, $method, $data = [])
<add> protected function _sendRequest($url, $method, $data = []): void
<ide> {
<ide> $dispatcher = $this->_makeDispatcher();
<ide> $url = $dispatcher->resolveUrl($url);
<ide> protected function _sendRequest($url, $method, $data = [])
<ide> *
<ide> * @return \Cake\TestSuite\MiddlewareDispatcher A dispatcher instance
<ide> */
<del> protected function _makeDispatcher()
<add> protected function _makeDispatcher(): \Cake\TestSuite\MiddlewareDispatcher
<ide> {
<ide> return new MiddlewareDispatcher($this, $this->_appClass, $this->_appArgs);
<ide> }
<ide> protected function _makeDispatcher()
<ide> * @param \Cake\Controller\Controller|null $controller Controller instance.
<ide> * @return void
<ide> */
<del> public function controllerSpy($event, $controller = null)
<add> public function controllerSpy(\Cake\Event\EventInterface $event, ?\Cake\Controller\Controller $controller = null): void
<ide> {
<ide> if (!$controller) {
<ide> /** @var \Cake\Controller\Controller $controller */
<ide> $controller = $event->getSubject();
<ide> }
<ide> $this->_controller = $controller;
<ide> $events = $controller->getEventManager();
<del> $events->on('View.beforeRender', function ($event, $viewFile) use ($controller) {
<add> $events->on('View.beforeRender', function ($event, $viewFile) use ($controller): void {
<ide> if (!$this->_viewName) {
<ide> $this->_viewName = $viewFile;
<ide> }
<ide> if ($this->_retainFlashMessages) {
<ide> $this->_flashMessages = $controller->getRequest()->getSession()->read('Flash');
<ide> }
<ide> });
<del> $events->on('View.beforeLayout', function ($event, $viewFile) {
<add> $events->on('View.beforeLayout', function ($event, $viewFile): void {
<ide> $this->_layoutName = $viewFile;
<ide> });
<ide> }
<ide> public function controllerSpy($event, $controller = null)
<ide> * @return void
<ide> * @throws \Exception
<ide> */
<del> protected function _handleError($exception)
<add> protected function _handleError(\Exception $exception): void
<ide> {
<ide> $class = Configure::read('Error.exceptionRenderer');
<ide> if (empty($class) || !class_exists($class)) {
<ide> protected function _handleError($exception)
<ide> * @param array|null $data The request data.
<ide> * @return array The request context
<ide> */
<del> protected function _buildRequest($url, $method, $data)
<add> protected function _buildRequest($url, $method, $data): array
<ide> {
<ide> $sessionConfig = (array)Configure::read('Session') + [
<ide> 'defaults' => 'php',
<ide> protected function _buildRequest($url, $method, $data)
<ide> * @param array $data The request body data.
<ide> * @return array The request body with tokens added.
<ide> */
<del> protected function _addTokens($url, $data)
<add> protected function _addTokens(string $url, array $data): array
<ide> {
<ide> if ($this->_securityToken === true) {
<ide> $keys = array_map(function ($field) {
<ide> protected function _addTokens($url, $data)
<ide> * @param array $data POST data
<ide> * @return array
<ide> */
<del> protected function _castToString($data)
<add> protected function _castToString(array $data): array
<ide> {
<ide> foreach ($data as $key => $value) {
<ide> if (is_scalar($value)) {
<ide> protected function _castToString($data)
<ide> * @param string|array $url The URL
<ide> * @return array Qualified URL and the query parameters
<ide> */
<del> protected function _url($url)
<add> protected function _url($url): array
<ide> {
<ide> // re-create URL in ServerRequest's context so
<ide> // query strings are encoded as expected
<ide> protected function _url($url)
<ide> *
<ide> * @return string The response body.
<ide> */
<del> protected function _getBodyAsString()
<add> protected function _getBodyAsString(): string
<ide> {
<ide> if (!$this->_response) {
<ide> $this->fail('No response set, cannot assert content.');
<ide> protected function _getBodyAsString()
<ide> * @param string $name The view variable to get.
<ide> * @return mixed The view variable if set.
<ide> */
<del> public function viewVariable($name)
<add> public function viewVariable(string $name)
<ide> {
<ide> if (empty($this->_controller->viewVars)) {
<ide> $this->fail('There are no view variables, perhaps you need to run a request?');
<ide> public function viewVariable($name)
<ide> * @param string $message Custom message for failure.
<ide> * @return void
<ide> */
<del> public function assertResponseOk($message = null)
<add> public function assertResponseOk(string $message = null): void
<ide> {
<ide> $this->assertThat(null, new StatusOk($this->_response), $message);
<ide> }
<ide> public function assertResponseOk($message = null)
<ide> * @param string $message Custom message for failure.
<ide> * @return void
<ide> */
<del> public function assertResponseSuccess($message = null)
<add> public function assertResponseSuccess(string $message = null): void
<ide> {
<ide> $this->assertThat(null, new StatusSuccess($this->_response), $message);
<ide> }
<ide> public function assertResponseSuccess($message = null)
<ide> * @param string $message Custom message for failure.
<ide> * @return void
<ide> */
<del> public function assertResponseError($message = null)
<add> public function assertResponseError(string $message = null): void
<ide> {
<ide> $this->assertThat(null, new StatusError($this->_response), $message);
<ide> }
<ide> public function assertResponseError($message = null)
<ide> * @param string $message Custom message for failure.
<ide> * @return void
<ide> */
<del> public function assertResponseFailure($message = null)
<add> public function assertResponseFailure(string $message = null): void
<ide> {
<ide> $this->assertThat(null, new StatusFailure($this->_response), $message);
<ide> }
<ide> public function assertResponseFailure($message = null)
<ide> * @param string $message Custom message for failure.
<ide> * @return void
<ide> */
<del> public function assertResponseCode($code, $message = null)
<add> public function assertResponseCode(int $code, string $message = null): void
<ide> {
<ide> $this->assertThat($code, new StatusCode($this->_response), $message);
<ide> }
<ide> public function assertResponseCode($code, $message = null)
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertRedirect($url = null, $message = '')
<add> public function assertRedirect($url = null, $message = ''): void
<ide> {
<ide> $this->assertThat(null, new HeaderSet($this->_response, 'Location'), $message);
<ide>
<ide> public function assertRedirect($url = null, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertRedirectContains($url, $message = '')
<add> public function assertRedirectContains(string $url, string $message = ''): void
<ide> {
<ide> $this->assertThat(null, new HeaderSet($this->_response, 'Location'), $message);
<ide> $this->assertThat($url, new HeaderContains($this->_response, 'Location'), $message);
<ide> public function assertRedirectContains($url, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertNoRedirect($message = '')
<add> public function assertNoRedirect(string $message = ''): void
<ide> {
<ide> $this->assertThat(null, new HeaderNotSet($this->_response, 'Location'), $message);
<ide> }
<ide> public function assertNoRedirect($message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertHeader($header, $content, $message = '')
<add> public function assertHeader(string $header, string $content, string $message = ''): void
<ide> {
<ide> $this->assertThat(null, new HeaderSet($this->_response, $header), $message);
<ide> $this->assertThat($content, new HeaderEquals($this->_response, $header), $message);
<ide> public function assertHeader($header, $content, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertHeaderContains($header, $content, $message = '')
<add> public function assertHeaderContains(string $header, string $content, string $message = ''): void
<ide> {
<ide> $this->assertThat(null, new HeaderSet($this->_response, $header), $message);
<ide> $this->assertThat($content, new HeaderContains($this->_response, $header), $message);
<ide> public function assertHeaderContains($header, $content, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertContentType($type, $message = '')
<add> public function assertContentType(string $type, string $message = ''): void
<ide> {
<ide> $this->assertThat($type, new ContentType($this->_response), $message);
<ide> }
<ide> public function assertContentType($type, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertResponseEquals($content, $message = '')
<add> public function assertResponseEquals($content, $message = ''): void
<ide> {
<ide> $this->assertThat($content, new BodyEquals($this->_response), $message);
<ide> }
<ide> public function assertResponseEquals($content, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertResponseNotEquals($content, $message = '')
<add> public function assertResponseNotEquals($content, $message = ''): void
<ide> {
<ide> $this->assertThat($content, new BodyNotEquals($this->_response), $message);
<ide> }
<ide> public function assertResponseNotEquals($content, $message = '')
<ide> * @param bool $ignoreCase A flag to check whether we should ignore case or not.
<ide> * @return void
<ide> */
<del> public function assertResponseContains($content, $message = '', $ignoreCase = false)
<add> public function assertResponseContains(string $content, string $message = '', bool $ignoreCase = false): void
<ide> {
<ide> $this->assertThat($content, new BodyContains($this->_response, $ignoreCase), $message);
<ide> }
<ide> public function assertResponseContains($content, $message = '', $ignoreCase = fa
<ide> * @param bool $ignoreCase A flag to check whether we should ignore case or not.
<ide> * @return void
<ide> */
<del> public function assertResponseNotContains($content, $message = '', $ignoreCase = false)
<add> public function assertResponseNotContains(string $content, string $message = '', bool $ignoreCase = false): void
<ide> {
<ide> $this->assertThat($content, new BodyNotContains($this->_response, $ignoreCase), $message);
<ide> }
<ide> public function assertResponseNotContains($content, $message = '', $ignoreCase =
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertResponseRegExp($pattern, $message = '')
<add> public function assertResponseRegExp(string $pattern, string $message = ''): void
<ide> {
<ide> $this->assertThat($pattern, new BodyRegExp($this->_response), $message);
<ide> }
<ide> public function assertResponseRegExp($pattern, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertResponseNotRegExp($pattern, $message = '')
<add> public function assertResponseNotRegExp(string $pattern, string $message = ''): void
<ide> {
<ide> $this->assertThat($pattern, new BodyNotRegExp($this->_response), $message);
<ide> }
<ide> public function assertResponseNotRegExp($pattern, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertResponseNotEmpty($message = '')
<add> public function assertResponseNotEmpty(string $message = ''): void
<ide> {
<ide> $this->assertThat(null, new BodyNotEmpty($this->_response), $message);
<ide> }
<ide> public function assertResponseNotEmpty($message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertResponseEmpty($message = '')
<add> public function assertResponseEmpty(string $message = ''): void
<ide> {
<ide> $this->assertThat(null, new BodyEmpty($this->_response), $message);
<ide> }
<ide> public function assertResponseEmpty($message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertTemplate($content, $message = '')
<add> public function assertTemplate(string $content, string $message = ''): void
<ide> {
<ide> $this->assertThat($content, new TemplateFileEquals($this->_viewName), $message);
<ide> }
<ide> public function assertTemplate($content, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertLayout($content, $message = '')
<add> public function assertLayout(string $content, string $message = ''): void
<ide> {
<ide> $this->assertThat($content, new LayoutFileEquals($this->_layoutName), $message);
<ide> }
<ide> public function assertLayout($content, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertSession($expected, $path, $message = '')
<add> public function assertSession(string $expected, string $path, string $message = ''): void
<ide> {
<ide> $this->assertThat($expected, new SessionEquals($this->_requestSession, $path), $message);
<ide> }
<ide> public function assertSession($expected, $path, $message = '')
<ide> * @param string $message Assertion failure message
<ide> * @return void
<ide> */
<del> public function assertFlashMessage($expected, $key = 'flash', $message = '')
<add> public function assertFlashMessage(string $expected, string $key = 'flash', string $message = ''): void
<ide> {
<ide> $this->assertThat($expected, new FlashParamEquals($this->_requestSession, $key, 'message'), $message);
<ide> }
<ide> public function assertFlashMessage($expected, $key = 'flash', $message = '')
<ide> * @param string $message Assertion failure message
<ide> * @return void
<ide> */
<del> public function assertFlashMessageAt($at, $expected, $key = 'flash', $message = '')
<add> public function assertFlashMessageAt(int $at, string $expected, string $key = 'flash', string $message = ''): void
<ide> {
<ide> $this->assertThat($expected, new FlashParamEquals($this->_requestSession, $key, 'message', $at), $message);
<ide> }
<ide> public function assertFlashMessageAt($at, $expected, $key = 'flash', $message =
<ide> * @param string $message Assertion failure message
<ide> * @return void
<ide> */
<del> public function assertFlashElement($expected, $key = 'flash', $message = '')
<add> public function assertFlashElement(string $expected, string $key = 'flash', string $message = ''): void
<ide> {
<ide> $this->assertThat($expected, new FlashParamEquals($this->_requestSession, $key, 'element'), $message);
<ide> }
<ide> public function assertFlashElement($expected, $key = 'flash', $message = '')
<ide> * @param string $message Assertion failure message
<ide> * @return void
<ide> */
<del> public function assertFlashElementAt($at, $expected, $key = 'flash', $message = '')
<add> public function assertFlashElementAt(int $at, string $expected, string $key = 'flash', string $message = ''): void
<ide> {
<ide> $this->assertThat($expected, new FlashParamEquals($this->_requestSession, $key, 'element', $at), $message);
<ide> }
<ide>
<ide> /**
<ide> * Asserts cookie values
<ide> *
<del> * @param string $expected The expected contents.
<add> * @param mixed $expected The expected contents.
<ide> * @param string $name The cookie name.
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertCookie($expected, $name, $message = '')
<add> public function assertCookie($expected, string $name, string $message = ''): void
<ide> {
<ide> $this->assertThat($name, new CookieSet($this->_response), $message);
<ide> $this->assertThat($expected, new CookieEquals($this->_response, $name), $message);
<ide> public function assertCookie($expected, $name, $message = '')
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertCookieNotSet($cookie, $message = '')
<add> public function assertCookieNotSet(string $cookie, string $message = ''): void
<ide> {
<ide> $this->assertThat($cookie, new CookieNotSet($this->_response), $message);
<ide> }
<ide> public function assertCookieNotSet($cookie, $message = '')
<ide> *
<ide> * @return void
<ide> */
<del> public function disableErrorHandlerMiddleware()
<add> public function disableErrorHandlerMiddleware(): void
<ide> {
<ide> Configure::write('Error.exceptionRenderer', TestExceptionRenderer::class);
<ide> }
<ide> public function disableErrorHandlerMiddleware()
<ide> * @return void
<ide> * @see \Cake\Utility\CookieCryptTrait::_encrypt()
<ide> */
<del> public function assertCookieEncrypted($expected, $name, $encrypt = 'aes', $key = null, $message = '')
<add> public function assertCookieEncrypted(string $expected, string $name, $encrypt = 'aes', $key = null, $message = ''): void
<ide> {
<ide> $this->assertThat($name, new CookieSet($this->_response), $message);
<ide>
<ide> public function assertCookieEncrypted($expected, $name, $encrypt = 'aes', $key =
<ide> * @param string $message The failure message that will be appended to the generated message.
<ide> * @return void
<ide> */
<del> public function assertFileResponse($expected, $message = '')
<add> public function assertFileResponse(string $expected, string $message = ''): void
<ide> {
<ide> $this->assertThat(null, new FileSent($this->_response), $message);
<ide> $this->assertThat($expected, new FileSentAs($this->_response), $message);
<ide><path>src/TestSuite/LegacyCommandRunner.php
<ide> class LegacyCommandRunner
<ide> * @param \Cake\Console\ConsoleIo $io A ConsoleIo instance.
<ide> * @return int
<ide> */
<del> public function run(array $argv, ?ConsoleIo $io = null)
<add> public function run(array $argv, ?ConsoleIo $io = null): int
<ide> {
<ide> $dispatcher = new LegacyShellDispatcher($argv, true, $io);
<ide>
<ide><path>src/TestSuite/LegacyShellDispatcher.php
<ide> */
<ide> namespace Cake\TestSuite;
<ide>
<add>use Cake\Console\ConsoleIo;
<add>use Cake\Console\Shell;
<ide> use Cake\Console\ShellDispatcher;
<ide>
<ide> /**
<ide> class LegacyShellDispatcher extends ShellDispatcher
<ide> * @param bool $bootstrap Initialize environment
<ide> * @param \Cake\Console\ConsoleIo $io ConsoleIo
<ide> */
<del> public function __construct($args = [], $bootstrap = true, $io = null)
<add> public function __construct(array $args = [], bool $bootstrap = true, ?ConsoleIo $io = null)
<ide> {
<ide> $this->_io = $io;
<ide> parent::__construct($args, $bootstrap);
<ide> public function __construct($args = [], $bootstrap = true, $io = null)
<ide> * @param string $shortName Short name
<ide> * @return \Cake\Console\Shell
<ide> */
<del> protected function _createShell($className, $shortName)
<add> protected function _createShell(string $className, string $shortName): Shell
<ide> {
<ide> list($plugin) = pluginSplit($shortName);
<ide> $instance = new $className($this->_io);
<ide><path>src/TestSuite/MiddlewareDispatcher.php
<ide> class MiddlewareDispatcher
<ide> * @param array|null $constructorArgs The constructor arguments for your application class.
<ide> * Defaults to `['./config']`
<ide> */
<del> public function __construct($test, $class = null, $constructorArgs = null)
<add> public function __construct(\Cake\TestSuite\IntegrationTestCase $test, ?string $class = null, ?array $constructorArgs = null)
<ide> {
<ide> $this->_test = $test;
<ide> $this->_class = $class ?: Configure::read('App.namespace') . '\Application';
<ide> public function __construct($test, $class = null, $constructorArgs = null)
<ide> * @param array|string $url The URL array/string to resolve.
<ide> * @return string
<ide> */
<del> public function resolveUrl($url)
<add> public function resolveUrl($url): string
<ide> {
<ide> // If we need to resolve a Route URL but there are no routes, load routes.
<ide> if (is_array($url) && count(Router::getRouteCollection()->routes()) === 0) {
<ide> public function resolveUrl($url)
<ide> * @param array $url The url to resolve
<ide> * @return string
<ide> */
<del> protected function resolveRoute(array $url)
<add> protected function resolveRoute(array $url): string
<ide> {
<ide> // Simulate application bootstrap and route loading.
<ide> // We need both to ensure plugins are loaded.
<ide> protected function resolveRoute(array $url)
<ide> * @param array $spec The request spec.
<ide> * @return \Psr\Http\Message\ServerRequestInterface
<ide> */
<del> protected function _createRequest($spec)
<add> protected function _createRequest(array $spec): \Psr\Http\Message\ServerRequestInterface
<ide> {
<ide> if (isset($spec['input'])) {
<ide> $spec['post'] = [];
<ide> protected function _createRequest($spec)
<ide> * @param array $requestSpec The request spec to execute.
<ide> * @return \Psr\Http\Message\ResponseInterface The generated response.
<ide> */
<del> public function execute($requestSpec)
<add> public function execute(array $requestSpec): \Psr\Http\Message\ResponseInterface
<ide> {
<ide> try {
<ide> $reflect = new ReflectionClass($this->_class);
<ide><path>src/TestSuite/StringCompareTrait.php
<ide> trait StringCompareTrait
<ide> * @param string $result test result as a string
<ide> * @return void
<ide> */
<del> public function assertSameAsFile($path, $result)
<add> public function assertSameAsFile(string $path, string $result): void
<ide> {
<ide> if (!file_exists($path)) {
<ide> $path = $this->_compareBasePath . $path;
<ide><path>src/TestSuite/TestCase.php
<ide> abstract class TestCase extends BaseTestCase
<ide> * @param string $message The message to display.
<ide> * @return bool
<ide> */
<del> public function skipIf($shouldSkip, $message = '')
<add> public function skipIf(bool $shouldSkip, string $message = ''): bool
<ide> {
<ide> if ($shouldSkip) {
<ide> $this->markTestSkipped($message);
<ide> public function skipIf($shouldSkip, $message = '')
<ide> * @param callable $callable callable function that will receive asserts
<ide> * @return void
<ide> */
<del> public function withErrorReporting($errorLevel, $callable)
<add> public function withErrorReporting(int $errorLevel, callable $callable): void
<ide> {
<ide> $default = error_reporting();
<ide> error_reporting($errorLevel);
<ide> public function withErrorReporting($errorLevel, $callable)
<ide> * @param callable $callable callable function that will receive asserts
<ide> * @return void
<ide> */
<del> public function deprecated($callable)
<add> public function deprecated(callable $callable): void
<ide> {
<ide> $errorLevel = error_reporting();
<ide> error_reporting(E_ALL ^ E_USER_DEPRECATED);
<ide> public function tearDown()
<ide> * @see \Cake\TestSuite\TestCase::$autoFixtures
<ide> * @throws \Exception when no fixture manager is available.
<ide> */
<del> public function loadFixtures()
<add> public function loadFixtures(): void
<ide> {
<ide> if ($this->fixtureManager === null) {
<ide> throw new Exception('No fixture manager to load the test fixture');
<ide> public function loadFixtures()
<ide> * @param array $plugins list of Plugins to load
<ide> * @return \Cake\Http\BaseApplication
<ide> */
<del> public function loadPlugins(array $plugins = [])
<add> public function loadPlugins(array $plugins = []): \Cake\Http\BaseApplication
<ide> {
<ide> $app = $this->getMockForAbstractClass(
<ide> BaseApplication::class,
<ide> public function loadPlugins(array $plugins = [])
<ide> * @param string $message Assertion failure message
<ide> * @return void
<ide> */
<del> public function assertEventFired($name, $eventManager = null, $message = '')
<add> public function assertEventFired(string $name, ?\Cake\Event\EventManager $eventManager = null, string $message = ''): void
<ide> {
<ide> if (!$eventManager) {
<ide> $eventManager = EventManager::instance();
<ide> public function assertEventFired($name, $eventManager = null, $message = '')
<ide> * @param string $message Assertion failure message
<ide> * @return void
<ide> */
<del> public function assertEventFiredWith($name, $dataKey, $dataValue, $eventManager = null, $message = '')
<add> public function assertEventFiredWith(string $name, string $dataKey, string $dataValue, ?\Cake\Event\EventManager $eventManager = null, string $message = ''): void
<ide> {
<ide> if (!$eventManager) {
<ide> $eventManager = EventManager::instance();
<ide> public function assertEventFiredWith($name, $dataKey, $dataValue, $eventManager
<ide> * @param string $message The message to use for failure.
<ide> * @return void
<ide> */
<del> public function assertTextNotEquals($expected, $result, $message = '')
<add> public function assertTextNotEquals(string $expected, string $result, string $message = ''): void
<ide> {
<ide> $expected = str_replace(["\r\n", "\r"], "\n", $expected);
<ide> $result = str_replace(["\r\n", "\r"], "\n", $result);
<ide> public function assertTextNotEquals($expected, $result, $message = '')
<ide> * @param string $message The message to use for failure.
<ide> * @return void
<ide> */
<del> public function assertTextEquals($expected, $result, $message = '')
<add> public function assertTextEquals(string $expected, string $result, string $message = ''): void
<ide> {
<ide> $expected = str_replace(["\r\n", "\r"], "\n", $expected);
<ide> $result = str_replace(["\r\n", "\r"], "\n", $result);
<ide> public function assertTextEquals($expected, $result, $message = '')
<ide> * @param string $message The message to use for failure.
<ide> * @return void
<ide> */
<del> public function assertTextStartsWith($prefix, $string, $message = '')
<add> public function assertTextStartsWith(string $prefix, string $string, string $message = ''): void
<ide> {
<ide> $prefix = str_replace(["\r\n", "\r"], "\n", $prefix);
<ide> $string = str_replace(["\r\n", "\r"], "\n", $string);
<ide> public function assertTextStartsWith($prefix, $string, $message = '')
<ide> * @param string $message The message to use for failure.
<ide> * @return void
<ide> */
<del> public function assertTextStartsNotWith($prefix, $string, $message = '')
<add> public function assertTextStartsNotWith(string $prefix, string $string, string $message = ''): void
<ide> {
<ide> $prefix = str_replace(["\r\n", "\r"], "\n", $prefix);
<ide> $string = str_replace(["\r\n", "\r"], "\n", $string);
<ide> public function assertTextStartsNotWith($prefix, $string, $message = '')
<ide> * @param string $message The message to use for failure.
<ide> * @return void
<ide> */
<del> public function assertTextEndsWith($suffix, $string, $message = '')
<add> public function assertTextEndsWith(string $suffix, string $string, string $message = ''): void
<ide> {
<ide> $suffix = str_replace(["\r\n", "\r"], "\n", $suffix);
<ide> $string = str_replace(["\r\n", "\r"], "\n", $string);
<ide> public function assertTextEndsWith($suffix, $string, $message = '')
<ide> * @param string $message The message to use for failure.
<ide> * @return void
<ide> */
<del> public function assertTextEndsNotWith($suffix, $string, $message = '')
<add> public function assertTextEndsNotWith(string $suffix, string $string, string $message = ''): void
<ide> {
<ide> $suffix = str_replace(["\r\n", "\r"], "\n", $suffix);
<ide> $string = str_replace(["\r\n", "\r"], "\n", $string);
<ide> public function assertTextEndsNotWith($suffix, $string, $message = '')
<ide> * @param bool $ignoreCase Whether or not the search should be case-sensitive.
<ide> * @return void
<ide> */
<del> public function assertTextContains($needle, $haystack, $message = '', $ignoreCase = false)
<add> public function assertTextContains(string $needle, string $haystack, string $message = '', bool $ignoreCase = false): void
<ide> {
<ide> $needle = str_replace(["\r\n", "\r"], "\n", $needle);
<ide> $haystack = str_replace(["\r\n", "\r"], "\n", $haystack);
<ide> public function assertTextContains($needle, $haystack, $message = '', $ignoreCas
<ide> * @param bool $ignoreCase Whether or not the search should be case-sensitive.
<ide> * @return void
<ide> */
<del> public function assertTextNotContains($needle, $haystack, $message = '', $ignoreCase = false)
<add> public function assertTextNotContains(string $needle, string $haystack, string $message = '', bool $ignoreCase = false): void
<ide> {
<ide> $needle = str_replace(["\r\n", "\r"], "\n", $needle);
<ide> $haystack = str_replace(["\r\n", "\r"], "\n", $haystack);
<ide> public function assertTextNotContains($needle, $haystack, $message = '', $ignore
<ide> * @param bool $fullDebug Whether or not more verbose output should be used.
<ide> * @return bool
<ide> */
<del> public function assertHtml($expected, $string, $fullDebug = false)
<add> public function assertHtml(array $expected, string $string, bool $fullDebug = false): bool
<ide> {
<ide> $regex = [];
<ide> $normalized = [];
<ide> public function assertHtml($expected, $string, $fullDebug = false)
<ide> * @param array|string $regex Full regexp from `assertHtml`
<ide> * @return string|bool
<ide> */
<del> protected function _assertAttributes($assertions, $string, $fullDebug = false, $regex = '')
<add> protected function _assertAttributes(array $assertions, string $string, bool $fullDebug = false, $regex = '')
<ide> {
<ide> $asserts = $assertions['attrs'];
<ide> $explains = $assertions['explains'];
<ide> protected function _assertAttributes($assertions, $string, $fullDebug = false, $
<ide> * @param string $path Path separated by "/" slash.
<ide> * @return string Normalized path separated by DIRECTORY_SEPARATOR.
<ide> */
<del> protected function _normalizePath($path)
<add> protected function _normalizePath(string $path): string
<ide> {
<ide> return str_replace('/', DIRECTORY_SEPARATOR, $path);
<ide> }
<ide> protected function skipUnless($condition, $message = '')
<ide> * @throws \Cake\ORM\Exception\MissingTableClassException
<ide> * @return \Cake\ORM\Table|\PHPUnit_Framework_MockObject_MockObject
<ide> */
<del> public function getMockForModel($alias, array $methods = [], array $options = [])
<add> public function getMockForModel(string $alias, array $methods = [], array $options = [])
<ide> {
<ide> /** @var \Cake\ORM\Table $className */
<ide> $className = $this->_getTableClassName($alias, $options);
<ide> public function getMockForModel($alias, array $methods = [], array $options = []
<ide> * @return string
<ide> * @throws \Cake\ORM\Exception\MissingTableClassException
<ide> */
<del> protected function _getTableClassName($alias, array $options)
<add> protected function _getTableClassName(string $alias, array $options): string
<ide> {
<ide> if (empty($options['className'])) {
<ide> $class = Inflector::camelize($alias);
<ide> protected function _getTableClassName($alias, array $options)
<ide> * @param string $appNamespace The app namespace, defaults to "TestApp".
<ide> * @return void
<ide> */
<del> public static function setAppNamespace($appNamespace = 'TestApp')
<add> public static function setAppNamespace(string $appNamespace = 'TestApp'): void
<ide> {
<ide> Configure::write('App.namespace', $appNamespace);
<ide> }
<ide><path>src/TestSuite/TestEmailTransport.php
<ide> public function send(Email $email): array
<ide> *
<ide> * @return void
<ide> */
<del> public static function replaceAllTransports()
<add> public static function replaceAllTransports(): void
<ide> {
<ide> $configuredTransports = Email::configuredTransport();
<ide>
<ide> public static function getEmails()
<ide> *
<ide> * @return void
<ide> */
<del> public static function clearEmails()
<add> public static function clearEmails(): void
<ide> {
<ide> static::$emails = [];
<ide> }
<ide><path>src/TestSuite/TestSuite.php
<ide> class TestSuite extends BaseTestSuite
<ide> * @param string $directory The directory to add tests from.
<ide> * @return void
<ide> */
<del> public function addTestDirectory($directory = '.')
<add> public function addTestDirectory(string $directory = '.'): void
<ide> {
<ide> $Folder = new Folder($directory);
<ide> list(, $files) = $Folder->read(true, true, true);
<ide> public function addTestDirectory($directory = '.')
<ide> * @param string $directory The directory subtree to add tests from.
<ide> * @return void
<ide> */
<del> public function addTestDirectoryRecursive($directory = '.')
<add> public function addTestDirectoryRecursive(string $directory = '.'): void
<ide> {
<ide> $Folder = new Folder($directory);
<ide> $files = $Folder->tree(null, true, 'files'); | 11 |
Python | Python | resolve state issue for url_for with forced scheme | 6aee9f6d77e0696bd570d6095445d73c48539f8a | <ide><path>flask/helpers.py
<ide> def external_url_handler(error, endpoint, values):
<ide> scheme = values.pop('_scheme', None)
<ide> appctx.app.inject_url_defaults(endpoint, values)
<ide>
<add> # This is not the best way to deal with this but currently the
<add> # underlying Werkzeug router does not support overriding the scheme on
<add> # a per build call basis.
<add> old_scheme = None
<ide> if scheme is not None:
<ide> if not external:
<ide> raise ValueError('When specifying _scheme, _external must be True')
<add> old_scheme = url_adapter.url_scheme
<ide> url_adapter.url_scheme = scheme
<ide>
<ide> try:
<del> rv = url_adapter.build(endpoint, values, method=method,
<del> force_external=external)
<add> try:
<add> rv = url_adapter.build(endpoint, values, method=method,
<add> force_external=external)
<add> finally:
<add> if old_scheme is not None:
<add> url_adapter.url_scheme = old_scheme
<ide> except BuildError as error:
<ide> # We need to inject the values again so that the app callback can
<ide> # deal with that sort of stuff.
<ide><path>tests/test_helpers.py
<ide> def index():
<ide> 'index',
<ide> _scheme='https')
<ide>
<add> def test_url_for_with_alternating_schemes(self):
<add> app = flask.Flask(__name__)
<add> @app.route('/')
<add> def index():
<add> return '42'
<add> with app.test_request_context():
<add> assert flask.url_for('index', _external=True) == 'http://localhost/'
<add> assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'
<add> assert flask.url_for('index', _external=True) == 'http://localhost/'
<add>
<ide> def test_url_with_method(self):
<ide> from flask.views import MethodView
<ide> app = flask.Flask(__name__) | 2 |
Python | Python | introduce logging_strategy training argument | 709c86b5a925f1efe650e24ee8b1f52bdc5a3acb | <ide><path>src/transformers/trainer_callback.py
<ide> import numpy as np
<ide> from tqdm.auto import tqdm
<ide>
<del>from .trainer_utils import EvaluationStrategy
<add>from .trainer_utils import EvaluationStrategy, LoggingStrategy
<ide> from .training_args import TrainingArguments
<ide> from .utils import logging
<ide>
<ide> def on_step_end(self, args: TrainingArguments, state: TrainerState, control: Tra
<ide> # Log
<ide> if state.global_step == 1 and args.logging_first_step:
<ide> control.should_log = True
<del> if args.logging_steps > 0 and state.global_step % args.logging_steps == 0:
<add> if (
<add> args.logging_strategy == LoggingStrategy.STEPS
<add> and args.logging_steps > 0
<add> and state.global_step % args.logging_steps == 0
<add> ):
<ide> control.should_log = True
<ide>
<ide> # Evaluate
<ide> def on_step_end(self, args: TrainingArguments, state: TrainerState, control: Tra
<ide> return control
<ide>
<ide> def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
<add> # Log
<add> if args.logging_strategy == LoggingStrategy.EPOCH:
<add> control.should_log = True
<add>
<add> # Evaluate
<ide> if args.evaluation_strategy == EvaluationStrategy.EPOCH:
<ide> control.should_evaluate = True
<ide> if args.load_best_model_at_end:
<ide><path>src/transformers/trainer_utils.py
<ide> class EvaluationStrategy(ExplicitEnum):
<ide> EPOCH = "epoch"
<ide>
<ide>
<add>class LoggingStrategy(ExplicitEnum):
<add> NO = "no"
<add> STEPS = "steps"
<add> EPOCH = "epoch"
<add>
<add>
<ide> class BestRun(NamedTuple):
<ide> """
<ide> The best run found by an hyperparameter search (see :class:`~transformers.Trainer.hyperparameter_search`).
<ide><path>src/transformers/training_args.py
<ide> is_torch_tpu_available,
<ide> torch_required,
<ide> )
<del>from .trainer_utils import EvaluationStrategy, SchedulerType
<add>from .trainer_utils import EvaluationStrategy, LoggingStrategy, SchedulerType
<ide> from .utils import logging
<ide>
<ide>
<ide> class TrainingArguments:
<ide> logging_dir (:obj:`str`, `optional`):
<ide> `TensorBoard <https://www.tensorflow.org/tensorboard>`__ log directory. Will default to
<ide> `runs/**CURRENT_DATETIME_HOSTNAME**`.
<add> logging_strategy (:obj:`str` or :class:`~transformers.trainer_utils.LoggingStrategy`, `optional`, defaults to :obj:`"steps"`):
<add> The logging strategy to adopt during training. Possible values are:
<add>
<add> * :obj:`"no"`: No logging is done during training.
<add> * :obj:`"epoch"`: Logging is done at the end of each epoch.
<add> * :obj:`"steps"`: Logging is done every :obj:`logging_steps`.
<add>
<ide> logging_first_step (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Whether to log and evaluate the first :obj:`global_step` or not.
<ide> logging_steps (:obj:`int`, `optional`, defaults to 500):
<del> Number of update steps between two logs.
<add> Number of update steps between two logs if :obj:`logging_strategy="steps"`.
<ide> save_steps (:obj:`int`, `optional`, defaults to 500):
<ide> Number of updates steps before two checkpoint saves.
<ide> save_total_limit (:obj:`int`, `optional`):
<ide> class TrainingArguments:
<ide> warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."})
<ide>
<ide> logging_dir: Optional[str] = field(default_factory=default_logdir, metadata={"help": "Tensorboard log dir."})
<add> logging_strategy: LoggingStrategy = field(
<add> default="steps",
<add> metadata={"help": "The logging strategy to use."},
<add> )
<ide> logging_first_step: bool = field(default=False, metadata={"help": "Log the first global_step"})
<ide> logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."})
<ide> save_steps: int = field(default=500, metadata={"help": "Save checkpoint every X updates steps."})
<ide> def __post_init__(self):
<ide> if self.disable_tqdm is None:
<ide> self.disable_tqdm = logger.getEffectiveLevel() > logging.WARN
<ide> self.evaluation_strategy = EvaluationStrategy(self.evaluation_strategy)
<add> self.logging_strategy = LoggingStrategy(self.logging_strategy)
<ide> self.lr_scheduler_type = SchedulerType(self.lr_scheduler_type)
<ide> if self.do_eval is False and self.evaluation_strategy != EvaluationStrategy.NO:
<ide> self.do_eval = True
<ide><path>src/transformers/training_args_tf.py
<ide> class TFTrainingArguments(TrainingArguments):
<ide> logging_dir (:obj:`str`, `optional`):
<ide> `TensorBoard <https://www.tensorflow.org/tensorboard>`__ log directory. Will default to
<ide> `runs/**CURRENT_DATETIME_HOSTNAME**`.
<add> logging_strategy (:obj:`str` or :class:`~transformers.trainer_utils.LoggingStrategy`, `optional`, defaults to :obj:`"steps"`):
<add> The logging strategy to adopt during training. Possible values are:
<add>
<add> * :obj:`"no"`: No logging is done during training.
<add> * :obj:`"epoch"`: Logging is done at the end of each epoch.
<add> * :obj:`"steps"`: Logging is done every :obj:`logging_steps`.
<add>
<ide> logging_first_step (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Whether to log and evaluate the first :obj:`global_step` or not.
<ide> logging_steps (:obj:`int`, `optional`, defaults to 500):
<del> Number of update steps between two logs.
<add> Number of update steps between two logs if :obj:`logging_strategy="steps"`.
<ide> save_steps (:obj:`int`, `optional`, defaults to 500):
<ide> Number of updates steps before two checkpoint saves.
<ide> save_total_limit (:obj:`int`, `optional`): | 4 |
Javascript | Javascript | add toonmap support to materialloader | c6f7ce7eb0d289ee6ccc53dee10221da43c50902 | <ide><path>src/loaders/MaterialLoader.js
<ide> Object.assign( MaterialLoader.prototype, {
<ide> if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
<ide> if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
<ide>
<add> if ( json.toonMap !== undefined ) material.toonMap = getTexture( json.toonMap );
<add> if ( json.toonMapDirectionY !== undefined ) material.toonMapDirectionY = json.toonMapDirectionY;
<add>
<ide> // MultiMaterial
<ide>
<ide> if ( json.materials !== undefined ) { | 1 |
Java | Java | ignore dropview method when view is null | e5d975b5c75945b04d2e8cf7fa7ceac00194e6e8 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java
<ide> protected synchronized final void addRootViewGroup(int tag, View view) {
<ide> */
<ide> protected synchronized void dropView(View view) {
<ide> UiThreadUtil.assertOnUiThread();
<add> if (view == null) {
<add> // Ignore this drop operation when view is null.
<add> return;
<add> }
<ide> if (mTagsToViewManagers.get(view.getId()) == null) {
<ide> // This view has already been dropped (likely due to a threading issue caused by async js
<ide> // execution). Ignore this drop operation. | 1 |
Mixed | Javascript | support checkbox tinting | 976f4be4578bd5ce8556b40f98dd4407b5f1ea48 | <ide><path>Libraries/Components/CheckBox/AndroidCheckBoxNativeComponent.js
<ide> type NativeProps = $ReadOnly<{|
<ide>
<ide> on?: ?boolean,
<ide> enabled?: boolean,
<add> tintColors: {|true: ?number, false: ?number|} | typeof undefined,
<ide> |}>;
<ide>
<ide> type CheckBoxNativeType = Class<NativeComponent<NativeProps>>;
<ide><path>Libraries/Components/CheckBox/CheckBox.android.js
<ide>
<ide> const React = require('React');
<ide> const StyleSheet = require('StyleSheet');
<add>const processColor = require('processColor');
<ide>
<ide> const AndroidCheckBoxNativeComponent = require('AndroidCheckBoxNativeComponent');
<ide> const nullthrows = require('nullthrows');
<ide> const setAndForwardRef = require('setAndForwardRef');
<ide> import type {ViewProps} from 'ViewPropTypes';
<ide> import type {SyntheticEvent} from 'CoreEventTypes';
<ide> import type {NativeComponent} from 'ReactNative';
<add>import type {ColorValue} from 'StyleSheetTypes';
<ide>
<ide> type CheckBoxEvent = SyntheticEvent<
<ide> $ReadOnly<{|
<ide> type NativeProps = $ReadOnly<{|
<ide>
<ide> on?: ?boolean,
<ide> enabled?: boolean,
<add> tintColors: {|true: ?number, false: ?number|} | typeof undefined,
<ide> |}>;
<ide>
<ide> type CheckBoxNativeType = Class<NativeComponent<NativeProps>>;
<ide> type Props = $ReadOnly<{|
<ide> * Used to get the ref for the native checkbox
<ide> */
<ide> forwardedRef?: ?React.Ref<CheckBoxNativeType>,
<add>
<add> /**
<add> * Controls the colors the checkbox has in checked and unchecked states.
<add> */
<add> tintColors?: {|true?: ?ColorValue, false?: ?ColorValue|},
<ide> |}>;
<ide>
<ide> /**
<ide> class CheckBox extends React.Component<Props> {
<ide> this.props.onValueChange(event.nativeEvent.value);
<ide> };
<ide>
<add> getTintColors(tintColors) {
<add> return tintColors
<add> ? {
<add> true: processColor(tintColors.true),
<add> false: processColor(tintColors.false),
<add> }
<add> : undefined;
<add> }
<add>
<ide> render() {
<del> const {disabled: _, value: __, style, forwardedRef, ...props} = this.props;
<add> const {
<add> disabled: _,
<add> value: __,
<add> tintColors,
<add> style,
<add> forwardedRef,
<add> ...props
<add> } = this.props;
<ide> const disabled = this.props.disabled ?? false;
<ide> const value = this.props.value ?? false;
<ide>
<ide> class CheckBox extends React.Component<Props> {
<ide> onResponderTerminationRequest: () => false,
<ide> enabled: !disabled,
<ide> on: value,
<add> tintColors: this.getTintColors(tintColors),
<ide> style: [styles.rctCheckBox, style],
<ide> };
<del>
<ide> return (
<ide> <AndroidCheckBoxNativeComponent
<ide> {...nativeProps}
<ide><path>RNTester/js/CheckBoxExample.js
<ide> class BasicCheckBoxExample extends React.Component<BasicProps, BasicState> {
<ide> onValueChange={value => this.setState({falseCheckBoxIsOn: value})}
<ide> style={styles.checkbox}
<ide> value={this.state.falseCheckBoxIsOn}
<add> tintColors={{false: 'red'}}
<ide> />
<ide> <CheckBox
<ide> onValueChange={value => this.setState({trueCheckBoxIsOn: value})}
<ide> value={this.state.trueCheckBoxIsOn}
<add> tintColors={{true: 'green'}}
<ide> />
<ide> </View>
<ide> );
<ide> exports.displayName = 'CheckBoxExample';
<ide> exports.description = 'Native boolean input';
<ide> exports.examples = [
<ide> {
<del> title: 'CheckBoxes can be set to true or false',
<add> title:
<add> 'CheckBoxes can be set to true or false, and the color of both states can be specified.',
<ide> render(): React.Element<any> {
<ide> return <BasicCheckBoxExample />;
<ide> },
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxManager.java
<ide> package com.facebook.react.views.checkbox;
<ide>
<ide> import android.content.Context;
<add>import android.content.res.ColorStateList;
<add>import android.support.v4.widget.CompoundButtonCompat;
<ide> import android.support.v7.widget.TintContextWrapper;
<add>import android.util.TypedValue;
<ide> import android.widget.CompoundButton;
<add>
<ide> import com.facebook.react.bridge.ReactContext;
<add>import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.uimanager.SimpleViewManager;
<ide> import com.facebook.react.uimanager.ThemedReactContext;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> import com.facebook.react.uimanager.ViewProps;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<ide>
<add>import javax.annotation.Nullable;
<add>
<ide> /** View manager for {@link ReactCheckBox} components. */
<ide> public class ReactCheckBoxManager extends SimpleViewManager<ReactCheckBox> {
<ide>
<ide> public void setOn(ReactCheckBox view, boolean on) {
<ide> view.setOn(on);
<ide> view.setOnCheckedChangeListener(ON_CHECKED_CHANGE_LISTENER);
<ide> }
<add>
<add> private static int getThemeColor(final Context context, String colorId) {
<add> final TypedValue value = new TypedValue();
<add> context.getTheme().resolveAttribute(getIdentifier(context, colorId), value, true);
<add> return value.data;
<add> }
<add>
<add> /**
<add> * The appcompat-v7 BUCK dep is listed as a provided_dep, which complains that
<add> * com.facebook.react.R doesn't exist. Since the attributes are provided from a parent, we can access
<add> * those attributes dynamically.
<add> */
<add> private static int getIdentifier(Context context, String name) {
<add> return context.getResources().getIdentifier(name, "attr", context.getPackageName());
<add> }
<add>
<add> @ReactProp(name = "tintColors")
<add> public void setTintColors(ReactCheckBox view, @Nullable ReadableMap colorsMap) {
<add> String defaultColorIdOfCheckedState = "colorAccent";
<add> int trueColor = colorsMap == null || !colorsMap.hasKey("true") ?
<add> getThemeColor(view.getContext(), defaultColorIdOfCheckedState) : colorsMap.getInt("true");
<add>
<add> String defaultColorIdOfUncheckedState = "colorPrimaryDark";
<add> int falseColor = colorsMap == null || !colorsMap.hasKey("false") ?
<add> getThemeColor(view.getContext(), defaultColorIdOfUncheckedState) : colorsMap.getInt("false");
<add>
<add> ColorStateList csl = new ColorStateList(
<add> new int[][]{
<add> new int[]{android.R.attr.state_checked},
<add> new int[]{-android.R.attr.state_checked}
<add> },
<add> new int[]{
<add> trueColor,
<add> falseColor,
<add> }
<add> );
<add>
<add> CompoundButtonCompat.setButtonTintList(view, csl);
<add> }
<add>
<ide> } | 4 |
PHP | PHP | replace function join (alias) by implode | df9e1e0bd1a1445e3854c41f5af6d1f2a7679476 | <ide><path>cake/basics.php
<ide> function env($key) {
<ide> /**
<ide> * Writes data into file.
<ide> *
<del> * If file exists, it will be overwritten. If data is an array, it will be join()ed with an empty string.
<add> * If file exists, it will be overwritten. If data is an array, it will be implode()ed with an empty string.
<ide> *
<ide> * @param string $fileName File name.
<ide> * @param mixed $data String or array.
<ide> * @return boolean Success
<ide> */
<ide> function file_put_contents($fileName, $data) {
<ide> if (is_array($data)) {
<del> $data = join('', $data);
<add> $data = implode('', $data);
<ide> }
<ide> $res = @fopen($fileName, 'w+b');
<ide>
<ide><path>cake/console/libs/console.php
<ide> function main($command = null) {
<ide> break;
<ide> case (preg_match("/^routes\s+show/i", $command, $tmp) == true):
<ide> $router =& Router::getInstance();
<del> $this->out(join("\n", Set::extract($router->routes, '{n}.0')));
<add> $this->out(implode("\n", Set::extract($router->routes, '{n}.0')));
<ide> break;
<ide> case (preg_match("/^route\s+(.*)/i", $command, $tmp) == true):
<ide> $this->out(var_export(Router::parse($tmp[1]), true));
<ide><path>cake/console/libs/tasks/controller.php
<ide> function __interactive($controllerName = false) {
<ide> if (file_exists($this->path . $controllerFile .'_controller.php')) {
<ide> $question[] = sprintf(__("Warning: Choosing no will overwrite the %sController.", true), $controllerName);
<ide> }
<del> $doItInteractive = $this->in(join("\n", $question), array('y','n'), 'y');
<add> $doItInteractive = $this->in(implode("\n", $question), array('y','n'), 'y');
<ide>
<ide> if (strtolower($doItInteractive) == 'y' || strtolower($doItInteractive) == 'yes') {
<ide> $this->interactive = true;
<ide> function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
<ide> }
<ide> }
<ide> if (!empty($compact)) {
<del> $actions .= "\t\t\$this->set(compact(" . join(', ', $compact) . "));\n";
<add> $actions .= "\t\t\$this->set(compact(" . implode(', ', $compact) . "));\n";
<ide> }
<ide> $actions .= "\t}\n";
<ide> $actions .= "\n";
<ide> function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
<ide> }
<ide> }
<ide> if (!empty($compact)) {
<del> $actions .= "\t\t\$this->set(compact(" . join(',', $compact) . "));\n";
<add> $actions .= "\t\t\$this->set(compact(" . implode(',', $compact) . "));\n";
<ide> }
<ide> $actions .= "\t}\n";
<ide> $actions .= "\n";
<ide><path>cake/console/libs/tasks/extract.php
<ide> function __buildFiles() {
<ide>
<ide> if ($this->__oneFile === true) {
<ide> foreach ($fileInfo as $file => $lines) {
<del> $occured[] = "$file:" . join(';', $lines);
<add> $occured[] = "$file:" . implode(';', $lines);
<ide>
<ide> if (isset($this->__fileVersions[$file])) {
<ide> $fileList[] = $this->__fileVersions[$file];
<ide> }
<ide> }
<del> $occurances = join("\n#: ", $occured);
<add> $occurances = implode("\n#: ", $occured);
<ide> $occurances = str_replace($this->path, '', $occurances);
<ide> $output = "#: $occurances\n";
<ide> $filename = $this->__filename;
<ide> function __buildFiles() {
<ide> } else {
<ide> foreach ($fileInfo as $file => $lines) {
<ide> $filename = $str;
<del> $occured = array("$str:" . join(';', $lines));
<add> $occured = array("$str:" . implode(';', $lines));
<ide>
<ide> if (isset($this->__fileVersions[$str])) {
<ide> $fileList[] = $this->__fileVersions[$str];
<ide> }
<del> $occurances = join("\n#: ", $occured);
<add> $occurances = implode("\n#: ", $occured);
<ide> $occurances = str_replace($this->path, '', $occurances);
<ide> $output .= "#: $occurances\n";
<ide>
<ide> function __writeFiles() {
<ide> $fileList = str_replace(array($this->path), '', $fileList);
<ide>
<ide> if (count($fileList) > 1) {
<del> $fileList = "Generated from files:\n# " . join("\n# ", $fileList);
<add> $fileList = "Generated from files:\n# " . implode("\n# ", $fileList);
<ide> } elseif (count($fileList) == 1) {
<del> $fileList = 'Generated from file: ' . join('', $fileList);
<add> $fileList = 'Generated from file: ' . implode('', $fileList);
<ide> } else {
<ide> $fileList = 'No version information was available in the source files.';
<ide> }
<ide> function __writeFiles() {
<ide> }
<ide> }
<ide> $fp = fopen($this->__output . $file, 'w');
<del> fwrite($fp, str_replace('--VERSIONS--', $fileList, join('', $content)));
<add> fwrite($fp, str_replace('--VERSIONS--', $fileList, implode('', $content)));
<ide> fclose($fp);
<ide> }
<ide> }
<ide><path>cake/console/libs/tasks/model.php
<ide> function bakeTest($className, $useTable = null, $associations = array()) {
<ide> }
<ide> }
<ide> }
<del> $fixture = join(", ", $fixture);
<add> $fixture = implode(", ", $fixture);
<ide>
<ide> $import = $className;
<ide> if (isset($this->plugin)) {
<ide> function fixture($model, $useTable = null) {
<ide> }
<ide> $records[] = "\t\t'$field' => $insert";
<ide> unset($value['type']);
<del> $col .= join(', ', $schema->__values($value));
<add> $col .= implode(', ', $schema->__values($value));
<ide> } else {
<ide> $col = "\t\t'indexes' => array(";
<ide> $props = array();
<ide> foreach ((array)$value as $key => $index) {
<del> $props[] = "'{$key}' => array(" . join(', ', $schema->__values($index)) . ")";
<add> $props[] = "'{$key}' => array(" . implode(', ', $schema->__values($index)) . ")";
<ide> }
<del> $col .= join(', ', $props);
<add> $col .= implode(', ', $props);
<ide> }
<ide> $col .= ")";
<ide> $cols[] = $col;
<ide> }
<del> $out .= join(",\n", $cols);
<add> $out .= implode(",\n", $cols);
<ide> }
<ide> $out .= "\n\t);\n";
<ide> }
<ide> }
<del> $records = join(",\n", $records);
<add> $records = implode(",\n", $records);
<ide> $out .= "\tvar \$records = array(array(\n$records\n\t));\n";
<ide> $out .= "}\n";
<ide> $path = TESTS . DS . 'fixtures' . DS;
<ide><path>cake/console/libs/templates/skel/controllers/pages_controller.php
<ide> function display() {
<ide> $title = Inflector::humanize($path[$count - 1]);
<ide> }
<ide> $this->set(compact('page', 'subpage', 'title'));
<del> $this->render(join('/', $path));
<add> $this->render(implode('/', $path));
<ide> }
<ide> }
<ide>
<ide><path>cake/libs/controller/components/security.php
<ide> function loginRequest($options = array()) {
<ide> $out[] = 'opaque="' . md5($options['realm']).'"';
<ide> }
<ide>
<del> return $auth . ' ' . join(',', $out);
<add> return $auth . ' ' . implode(',', $out);
<ide> }
<ide> /**
<ide> * Parses an HTTP digest authentication response, and returns an array of the data, or null on failure.
<ide><path>cake/libs/controller/pages_controller.php
<ide> function display() {
<ide> $title = Inflector::humanize($path[$count - 1]);
<ide> }
<ide> $this->set(compact('page', 'subpage', 'title'));
<del> $this->render(join('/', $path));
<add> $this->render(implode('/', $path));
<ide> }
<ide> }
<ide>
<ide><path>cake/libs/debugger.php
<ide> function trace($options = array()) {
<ide> foreach ($next['args'] as $arg) {
<ide> $args[] = Debugger::exportVar($arg);
<ide> }
<del> $function .= join(', ', $args);
<add> $function .= implode(', ', $args);
<ide> }
<ide> $function .= ')';
<ide> }
<ide> function trace($options = array()) {
<ide> if ($options['format'] == 'array' || $options['format'] == 'points') {
<ide> return $back;
<ide> }
<del> return join("\n", $back);
<add> return implode("\n", $back);
<ide> }
<ide> /**
<ide> * Shortens file paths by replacing the application base path with 'APP', and the CakePHP core
<ide> function exportVar($var, $recursion = 0) {
<ide> if (count($vars) > 0) {
<ide> $n = "\n";
<ide> }
<del> return $out . join(",", $vars) . "{$n})";
<add> return $out . implode(",", $vars) . "{$n})";
<ide> break;
<ide> case 'resource':
<ide> return strtolower(gettype($var));
<ide> function __object($var) {
<ide> $out[] = "$className::$$key = " . $value;
<ide> }
<ide> }
<del> return join("\n", $out);
<add> return implode("\n", $out);
<ide> }
<ide> /**
<ide> * Handles object conversion to debug string.
<ide><path>cake/libs/flay.php
<ide> function markedSnippets($words, $string, $max_snippets = 5) {
<ide> if (count($snips) > $max_snippets) {
<ide> $snips = array_slice($snips, 0, $max_snippets);
<ide> }
<del> $joined = join(' <b>...</b> ', $snips);
<add> $joined = implode(' <b>...</b> ', $snips);
<ide> $snips = $joined ? "<b>...</b> {$joined} <b>...</b>" : substr($string, 0, 80) . '<b>...</b>';
<ide> return $this->colorMark($words, $snips);
<ide> }
<ide><path>cake/libs/http_socket.php
<ide> function buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
<ide> $request['uri'] = $this->buildUri($request['uri'], '/%path?%query');
<ide>
<ide> if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) {
<del> trigger_error(sprintf(__('HttpSocket::buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', true), join(',', $asteriskMethods)), E_USER_WARNING);
<add> trigger_error(sprintf(__('HttpSocket::buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', true), implode(',', $asteriskMethods)), E_USER_WARNING);
<ide> return false;
<ide> }
<ide> return $request['method'].' '.$request['uri'].' '.$versionToken.$this->lineBreak;
<ide> function buildHeader($header, $mode = 'standard') {
<ide> $returnHeader = '';
<ide> foreach ($header as $field => $contents) {
<ide> if (is_array($contents) && $mode == 'standard') {
<del> $contents = join(',', $contents);
<add> $contents = implode(',', $contents);
<ide> }
<ide> foreach ((array)$contents as $content) {
<ide> $contents = preg_replace("/\r\n(?![\t ])/", "\r\n ", $content);
<ide> function loadCookies() {
<ide> * @todo Test $chars parameter
<ide> */
<ide> function unescapeToken($token, $chars = null) {
<del> $regex = '/"(['.join('', $this->__tokenEscapeChars(true, $chars)).'])"/';
<add> $regex = '/"(['.implode('', $this->__tokenEscapeChars(true, $chars)).'])"/';
<ide> $token = preg_replace($regex, '\\1', $token);
<ide> return $token;
<ide> }
<ide> function unescapeToken($token, $chars = null) {
<ide> * @todo Test $chars parameter
<ide> */
<ide> function escapeToken($token, $chars = null) {
<del> $regex = '/(['.join('', $this->__tokenEscapeChars(true, $chars)).'])/';
<add> $regex = '/(['.implode('', $this->__tokenEscapeChars(true, $chars)).'])/';
<ide> $token = preg_replace($regex, '"\\1"', $token);
<ide> return $token;
<ide> }
<ide><path>cake/libs/inflector.php
<ide> function pluralize($word) {
<ide> extract($_this->pluralRules);
<ide>
<ide> if (!isset($regexUninflected) || !isset($regexIrregular)) {
<del> $regexUninflected = __enclose(join( '|', $uninflected));
<del> $regexIrregular = __enclose(join( '|', array_keys($irregular)));
<add> $regexUninflected = __enclose(implode( '|', $uninflected));
<add> $regexIrregular = __enclose(implode( '|', array_keys($irregular)));
<ide> $_this->pluralRules['regexUninflected'] = $regexUninflected;
<ide> $_this->pluralRules['regexIrregular'] = $regexIrregular;
<ide> }
<ide> function singularize($word) {
<ide> extract($_this->singularRules);
<ide>
<ide> if (!isset($regexUninflected) || !isset($regexIrregular)) {
<del> $regexUninflected = __enclose(join( '|', $uninflected));
<del> $regexIrregular = __enclose(join( '|', array_keys($irregular)));
<add> $regexUninflected = __enclose(implode( '|', $uninflected));
<add> $regexIrregular = __enclose(implode( '|', array_keys($irregular)));
<ide> $_this->singularRules['regexUninflected'] = $regexUninflected;
<ide> $_this->singularRules['regexIrregular'] = $regexIrregular;
<ide> }
<ide><path>cake/libs/model/behaviors/containable.php
<ide> function containments(&$Model, $contain, $containments = array(), $throwErrors =
<ide> if (strpos($name, '.') !== false) {
<ide> $chain = explode('.', $name);
<ide> $name = array_shift($chain);
<del> $children = array(join('.', $chain) => $children);
<add> $children = array(implode('.', $chain) => $children);
<ide> }
<ide>
<ide> $children = (array)$children;
<ide><path>cake/libs/model/datasources/dbo/dbo_mssql.php
<ide> function renderStatement($type, $data) {
<ide>
<ide> foreach (array('columns', 'indexes') as $var) {
<ide> if (is_array(${$var})) {
<del> ${$var} = "\t" . join(",\n\t", array_filter(${$var}));
<add> ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
<ide> }
<ide> }
<ide> return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
<ide> function buildIndex($indexes, $table = null) {
<ide> $out = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE";
<ide>
<ide> if (is_array($value['column'])) {
<del> $value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
<add> $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
<ide> } else {
<ide> $value['column'] = $this->name($value['column']);
<ide> }
<ide><path>cake/libs/model/datasources/dbo/dbo_mysql.php
<ide> function update(&$model, $fields = array(), $values = null, $conditions = null)
<ide>
<ide> $alias = $joins = false;
<ide> $fields = $this->_prepareUpdateFields($model, $combined, empty($conditions), !empty($conditions));
<del> $fields = join(', ', $fields);
<add> $fields = implode(', ', $fields);
<ide> $table = $this->fullTableName($model);
<ide>
<ide> if (!empty($conditions)) {
<ide> function alterSchema($compare, $table = null) {
<ide> }
<ide> }
<ide> $colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
<del> $out .= "\t" . join(",\n\t", $colList) . ";\n\n";
<add> $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
<ide> }
<ide> }
<ide> return $out;
<ide> function _alterIndexes($table, $indexes) {
<ide> }
<ide> }
<ide> if (is_array($value['column'])) {
<del> $out .= 'KEY '. $name .' (' . join(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
<add> $out .= 'KEY '. $name .' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
<ide> } else {
<ide> $out .= 'KEY '. $name .' (' . $this->name($value['column']) . ')';
<ide> }
<ide> function _alterIndexes($table, $indexes) {
<ide> function insertMulti($table, $fields, $values) {
<ide> $table = $this->fullTableName($table);
<ide> if (is_array($fields)) {
<del> $fields = join(', ', array_map(array(&$this, 'name'), $fields));
<add> $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
<ide> }
<ide> $values = implode(', ', $values);
<ide> $this->query("INSERT INTO {$table} ({$fields}) VALUES {$values}");
<ide><path>cake/libs/model/datasources/dbo/dbo_oracle.php
<ide> function alterSchema($compare, $table = null) {
<ide> break;
<ide> }
<ide> }
<del> $out .= "\t" . join(",\n\t", $colList) . ";\n\n";
<add> $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
<ide> }
<ide> }
<ide> return $out;
<ide> function renderStatement($type, $data) {
<ide> case 'schema':
<ide> foreach (array('columns', 'indexes') as $var) {
<ide> if (is_array(${$var})) {
<del> ${$var} = "\t" . join(",\n\t", array_filter(${$var}));
<add> ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
<ide> }
<ide> }
<ide> if (trim($indexes) != '') {
<ide> function queryAssociation(&$model, &$linkModel, $type, $association, $assocData,
<ide> $fetch = array();
<ide> $ins = array_chunk($ins, 1000);
<ide> foreach ($ins as $i) {
<del> $q = str_replace('{$__cakeID__$}', join(', ', $i), $query);
<add> $q = str_replace('{$__cakeID__$}', implode(', ', $i), $query);
<ide> $q = str_replace('= (', 'IN (', $q);
<ide> $res = $this->fetchAll($q, $model->cacheQueries, $model->alias);
<ide> $fetch = array_merge($fetch, $res);
<ide> function queryAssociation(&$model, &$linkModel, $type, $association, $assocData,
<ide> $fetch = array();
<ide> $ins = array_chunk($ins, 1000);
<ide> foreach ($ins as $i) {
<del> $q = str_replace('{$__cakeID__$}', '(' .join(', ', $i) .')', $query);
<add> $q = str_replace('{$__cakeID__$}', '(' .implode(', ', $i) .')', $query);
<ide> $q = str_replace('= (', 'IN (', $q);
<ide> $q = str_replace(' WHERE 1 = 1', '', $q);
<ide>
<ide><path>cake/libs/model/datasources/dbo/dbo_postgres.php
<ide> function alterSchema($compare, $table = null) {
<ide> }
<ide>
<ide> if (!empty($colList)) {
<del> $out .= "\t" . join(",\n\t", $colList) . ";\n\n";
<add> $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
<ide> } else {
<ide> $out = '';
<ide> }
<del> $out .= join(";\n\t", $this->_alterIndexes($curTable, $indexes)) . ";";
<add> $out .= implode(";\n\t", $this->_alterIndexes($curTable, $indexes)) . ";";
<ide> }
<ide> }
<ide> return $out;
<ide> function _alterIndexes($table, $indexes) {
<ide> $out .= 'INDEX ';
<ide> }
<ide> if (is_array($value['column'])) {
<del> $out .= $name . ' ON ' . $table . ' (' . join(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
<add> $out .= $name . ' ON ' . $table . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
<ide> } else {
<ide> $out .= $name . ' ON ' . $table . ' (' . $this->name($value['column']) . ')';
<ide> }
<ide> function buildIndex($indexes, $table = null) {
<ide> $out .= 'UNIQUE ';
<ide> }
<ide> if (is_array($value['column'])) {
<del> $value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
<add> $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
<ide> } else {
<ide> $value['column'] = $this->name($value['column']);
<ide> }
<ide> function renderStatement($type, $data) {
<ide>
<ide> foreach (array('columns', 'indexes') as $var) {
<ide> if (is_array(${$var})) {
<del> ${$var} = join($join[$var], array_filter(${$var}));
<add> ${$var} = implode($join[$var], array_filter(${$var}));
<ide> }
<ide> }
<ide> return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}";
<ide><path>cake/libs/model/datasources/dbo/dbo_sqlite.php
<ide> function buildIndex($indexes, $table = null) {
<ide> $out .= 'UNIQUE ';
<ide> }
<ide> if (is_array($value['column'])) {
<del> $value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
<add> $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
<ide> } else {
<ide> $value['column'] = $this->name($value['column']);
<ide> }
<ide> function renderStatement($type, $data) {
<ide>
<ide> foreach (array('columns', 'indexes') as $var) {
<ide> if (is_array(${$var})) {
<del> ${$var} = "\t" . join(",\n\t", array_filter(${$var}));
<add> ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
<ide> }
<ide> }
<ide> return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
<ide><path>cake/libs/model/datasources/dbo_source.php
<ide> function create(&$model, $fields = null, $values = null) {
<ide> }
<ide> $query = array(
<ide> 'table' => $this->fullTableName($model),
<del> 'fields' => join(', ', $fieldInsert),
<del> 'values' => join(', ', $valueInsert)
<add> 'fields' => implode(', ', $fieldInsert),
<add> 'values' => implode(', ', $valueInsert)
<ide> );
<ide>
<ide> if ($this->execute($this->renderStatement('create', $query))) {
<ide> function queryAssociation(&$model, &$linkModel, $type, $association, $assocData,
<ide> }
<ide> if (!empty($ins)) {
<ide> if (count($ins) > 1) {
<del> $query = str_replace('{$__cakeID__$}', '(' .join(', ', $ins) .')', $query);
<add> $query = str_replace('{$__cakeID__$}', '(' .implode(', ', $ins) .')', $query);
<ide> $query = str_replace('= (', 'IN (', $query);
<ide> $query = str_replace('= (', 'IN (', $query);
<ide> } else {
<ide> function queryAssociation(&$model, &$linkModel, $type, $association, $assocData,
<ide> * @return array Association results
<ide> */
<ide> function fetchAssociated($model, $query, $ids) {
<del> $query = str_replace('{$__cakeID__$}', join(', ', $ids), $query);
<add> $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
<ide> if (count($ids) > 1) {
<ide> $query = str_replace('= (', 'IN (', $query);
<ide> $query = str_replace('= (', 'IN (', $query);
<ide> function buildStatement($query, $model) {
<ide> }
<ide> return $this->renderStatement('select', array(
<ide> 'conditions' => $this->conditions($query['conditions'], true, true, $model),
<del> 'fields' => join(', ', $query['fields']),
<add> 'fields' => implode(', ', $query['fields']),
<ide> 'table' => $query['table'],
<ide> 'alias' => $this->alias . $this->name($query['alias']),
<ide> 'order' => $this->order($query['order']),
<ide> 'limit' => $this->limit($query['limit'], $query['offset']),
<del> 'joins' => join(' ', $query['joins']),
<add> 'joins' => implode(' ', $query['joins']),
<ide> 'group' => $this->group($query['group'])
<ide> ));
<ide> }
<ide> function renderStatement($type, $data) {
<ide> case 'schema':
<ide> foreach (array('columns', 'indexes') as $var) {
<ide> if (is_array(${$var})) {
<del> ${$var} = "\t" . join(",\n\t", array_filter(${$var}));
<add> ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
<ide> }
<ide> }
<ide> if (trim($indexes) != '') {
<ide> function update(&$model, $fields = array(), $values = null, $conditions = null)
<ide> } else {
<ide> $combined = array_combine($fields, $values);
<ide> }
<del> $fields = join(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions)));
<add> $fields = implode(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions)));
<ide>
<ide> $alias = $joins = null;
<ide> $table = $this->fullTableName($model);
<ide> function fields(&$model, $alias = null, $fields = array(), $quote = true) {
<ide> } else {
<ide> $field[0] = explode('.', $field[1]);
<ide> if (!Set::numeric($field[0])) {
<del> $field[0] = join('.', array_map(array($this, 'name'), $field[0]));
<add> $field[0] = implode('.', array_map(array($this, 'name'), $field[0]));
<ide> $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
<ide> }
<ide> }
<ide> function conditions($conditions, $quoteValues = true, $where = true, $model = nu
<ide> if (empty($out)) {
<ide> return $clause . ' 1 = 1';
<ide> }
<del> return $clause . join(' AND ', $out);
<add> return $clause . implode(' AND ', $out);
<ide> }
<ide>
<ide> if (empty($conditions) || trim($conditions) == '' || $conditions === true) {
<ide> function conditionKeysToString($conditions, $quoteValues = true, $model = null)
<ide> $out[] = $value[0] ;
<ide> }
<ide> } else {
<del> $out[] = '(' . $not . '(' . join(') ' . strtoupper($key) . ' (', $value) . '))';
<add> $out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
<ide> }
<ide>
<ide> } else {
<ide> function conditionKeysToString($conditions, $quoteValues = true, $model = null)
<ide> if (is_object($model)) {
<ide> $columnType = $model->getColumnType($key);
<ide> }
<del> $data .= join(', ', $this->value($value, $columnType));
<add> $data .= implode(', ', $this->value($value, $columnType));
<ide> }
<ide> $data .= ')';
<ide> } else {
<ide> $ret = $this->conditionKeysToString($value, $quoteValues, $model);
<ide> if (count($ret) > 1) {
<del> $data = '(' . join(') AND (', $ret) . ')';
<add> $data = '(' . implode(') AND (', $ret) . ')';
<ide> } elseif (isset($ret[0])) {
<ide> $data = $ret[0];
<ide> }
<ide> function conditionKeysToString($conditions, $quoteValues = true, $model = null)
<ide> * @access private
<ide> */
<ide> function __parseKey($model, $key, $value) {
<del> $operatorMatch = '/^((' . join(')|(', $this->__sqlOps);
<add> $operatorMatch = '/^((' . implode(')|(', $this->__sqlOps);
<ide> $operatorMatch .= '\\x20)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
<ide> $bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
<ide>
<ide> function __parseKey($model, $key, $value) {
<ide> $operator = trim($operator);
<ide>
<ide> if (is_array($value)) {
<del> $value = join(', ', $value);
<add> $value = implode(', ', $value);
<ide>
<ide> switch ($operator) {
<ide> case '=':
<ide> function order($keys, $direction = 'ASC') {
<ide> }
<ide> $order[] = $this->order($key . $value);
<ide> }
<del> return ' ORDER BY ' . trim(str_replace('ORDER BY', '', join(',', $order)));
<add> return ' ORDER BY ' . trim(str_replace('ORDER BY', '', implode(',', $order)));
<ide> }
<ide> $keys = preg_replace('/ORDER\\x20BY/i', '', $keys);
<ide>
<ide> function order($keys, $direction = 'ASC') {
<ide> function group($group) {
<ide> if ($group) {
<ide> if (is_array($group)) {
<del> $group = join(', ', $group);
<add> $group = implode(', ', $group);
<ide> }
<ide> return ' GROUP BY ' . $this->__quoteFields($group);
<ide> }
<ide> function boolean($data) {
<ide> function insertMulti($table, $fields, $values) {
<ide> $table = $this->fullTableName($table);
<ide> if (is_array($fields)) {
<del> $fields = join(', ', array_map(array(&$this, 'name'), $fields));
<add> $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
<ide> }
<ide> $count = count($values);
<ide> for ($x = 0; $x < $count; $x++) {
<ide> function buildIndex($indexes, $table = null) {
<ide> $name = $this->startQuote . $name . $this->endQuote;
<ide> }
<ide> if (is_array($value['column'])) {
<del> $out .= 'KEY ' . $name . ' (' . join(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
<add> $out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
<ide> } else {
<ide> $out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
<ide> }
<ide><path>cake/libs/model/model.php
<ide> function __saveMulti($joined, $id) {
<ide> if ($isUUID && $primaryAdded) {
<ide> $values[] = $db->value(String::uuid());
<ide> }
<del> $values = join(',', $values);
<add> $values = implode(',', $values);
<ide> $newValues[] = "({$values})";
<ide> unset($values);
<ide> } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
<ide> function __saveMulti($joined, $id) {
<ide> }
<ide>
<ide> if (!empty($newValues)) {
<del> $fields = join(',', $fields);
<add> $fields = implode(',', $fields);
<ide> $db->insertMulti($this->{$join}, $fields, $newValues);
<ide> }
<ide> }
<ide><path>cake/libs/model/schema.php
<ide> function write($object, $options = array()) {
<ide> }
<ide> $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
<ide> unset($value['type']);
<del> $col .= join(', ', $this->__values($value));
<add> $col .= implode(', ', $this->__values($value));
<ide> } else {
<ide> $col = "\t\t'indexes' => array(";
<ide> $props = array();
<ide> foreach ((array)$value as $key => $index) {
<del> $props[] = "'{$key}' => array(" . join(', ', $this->__values($index)) . ")";
<add> $props[] = "'{$key}' => array(" . implode(', ', $this->__values($index)) . ")";
<ide> }
<del> $col .= join(', ', $props);
<add> $col .= implode(', ', $props);
<ide> }
<ide> $col .= ")";
<ide> $cols[] = $col;
<ide> }
<del> $out .= join(",\n", $cols);
<add> $out .= implode(",\n", $cols);
<ide> }
<ide> $out .= "\n\t);\n";
<ide> }
<ide> function __values($values) {
<ide> if (is_array($values)) {
<ide> foreach ($values as $key => $val) {
<ide> if (is_array($val)) {
<del> $vals[] = "'{$key}' => array('" . join("', '", $val) . "')";
<add> $vals[] = "'{$key}' => array('" . implode("', '", $val) . "')";
<ide> } else if (!is_numeric($key)) {
<ide> $val = var_export($val, true);
<ide> $vals[] = "'{$key}' => {$val}";
<ide><path>cake/libs/router.php
<ide> function writeRoute($route, $default, $params) {
<ide> $parsed[] = '/' . $element;
<ide> }
<ide> }
<del> return array('#^' . join('', $parsed) . '[\/]*$#', $names);
<add> return array('#^' . implode('', $parsed) . '[\/]*$#', $names);
<ide> }
<ide> /**
<ide> * Returns the list of prefixes used in connected routes
<ide> function url($url = null, $full = false) {
<ide> if ($_this->__admin && isset($url[$_this->__admin])) {
<ide> array_unshift($urlOut, $_this->__admin);
<ide> }
<del> $output = join('/', $urlOut) . '/';
<add> $output = implode('/', $urlOut) . '/';
<ide> }
<ide>
<ide> if (!empty($args)) {
<del> $args = join('/', $args);
<add> $args = implode('/', $args);
<ide> if ($output{strlen($output) - 1} != '/') {
<ide> $args = '/'. $args;
<ide> }
<ide> function __mapRoute($route, $params = array()) {
<ide> for ($i = 0; $i < $count; $i++) {
<ide> $named[] = $keys[$i] . $this->named['separator'] . $params['named'][$keys[$i]];
<ide> }
<del> $params['named'] = join('/', $named);
<add> $params['named'] = implode('/', $named);
<ide> }
<ide> $params['pass'] = str_replace('//', '/', $params['pass'] . '/' . $params['named']);
<ide> }
<ide><path>cake/libs/set.php
<ide> function extract($path, $data = null, $options = array()) {
<ide> if (count($context['trace']) == 1) {
<ide> $context['trace'][] = $context['key'];
<ide> }
<del> $parent = join('/', $context['trace']) . '/.';
<add> $parent = implode('/', $context['trace']) . '/.';
<ide> $context['item'] = Set::extract($parent, $data);
<ide> $context['key'] = array_pop($context['trace']);
<ide> if (isset($context['trace'][1]) && $context['trace'][1] > 0) {
<ide><path>cake/libs/view/helper.php
<ide> function setEntity($entity, $setScope = false) {
<ide>
<ide> if ($setScope) {
<ide> $view->modelScope = false;
<del> } elseif (join('.', $view->entity()) == $entity) {
<add> } elseif (implode('.', $view->entity()) == $entity) {
<ide> return;
<ide> }
<ide>
<ide> function __name($options = array(), $field = null, $key = 'name') {
<ide> $name = $field;
<ide> break;
<ide> default:
<del> $name = 'data[' . join('][', $view->entity()) . ']';
<add> $name = 'data[' . implode('][', $view->entity()) . ']';
<ide> break;
<ide> }
<ide>
<ide><path>cake/libs/view/helpers/ajax.php
<ide> function remoteFunction($options) {
<ide> $options['requestHeaders'] = array();
<ide> }
<ide> if (is_array($options['update'])) {
<del> $options['update'] = join(' ', $options['update']);
<add> $options['update'] = implode(' ', $options['update']);
<ide> }
<ide> $options['requestHeaders']['X-Update'] = $options['update'];
<ide> } else {
<ide> function __optionsForAjax($options) {
<ide> $keys[] = "'" . $key . "'";
<ide> $keys[] = "'" . $val . "'";
<ide> }
<del> $jsOptions['requestHeaders'] = '[' . join(', ', $keys) . ']';
<add> $jsOptions['requestHeaders'] = '[' . implode(', ', $keys) . ']';
<ide> break;
<ide> }
<ide> }
<ide> function _buildOptions($options, $acceptable) {
<ide> }
<ide> }
<ide>
<del> $out = join(', ', $out);
<add> $out = implode(', ', $out);
<ide> $out = '{' . $out . '}';
<ide> return $out;
<ide> } else {
<ide> function afterRender() {
<ide> $data[] = $key . ':"' . rawurlencode($val) . '"';
<ide> }
<ide> }
<del> $out = 'var __ajaxUpdater__ = {' . join(", \n", $data) . '};' . "\n";
<add> $out = 'var __ajaxUpdater__ = {' . implode(", \n", $data) . '};' . "\n";
<ide> $out .= 'for (n in __ajaxUpdater__) { if (typeof __ajaxUpdater__[n] == "string"';
<ide> $out .= ' && $(n)) Element.update($(n), unescape(decodeURIComponent(';
<ide> $out .= '__ajaxUpdater__[n]))); }';
<ide><path>cake/libs/view/helpers/form.php
<ide> function __secure($field = null, $value = null) {
<ide> }
<ide> }
<ide> }
<del> $field = join('.', $field);
<add> $field = implode('.', $field);
<ide> if (!in_array($field, $this->fields)) {
<ide> if ($value !== null) {
<ide> return $this->fields[$field] = $value;
<ide> function inputs($fields = null, $blacklist = null) {
<ide> function input($fieldName, $options = array()) {
<ide> $view =& ClassRegistry::getObject('view');
<ide> $this->setEntity($fieldName);
<del> $entity = join('.', $view->entity());
<add> $entity = implode('.', $view->entity());
<ide>
<ide> $defaults = array('before' => null, 'between' => null, 'after' => null);
<ide> $options = array_merge($defaults, $options);
<ide> function radio($fieldName, $options = array(), $attributes = array()) {
<ide> 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
<ide> ));
<ide> }
<del> $out = $hidden . join($inbetween, $out);
<add> $out = $hidden . implode($inbetween, $out);
<ide>
<ide> if ($legend) {
<ide> $out = sprintf(
<ide><path>cake/libs/view/helpers/html.php
<ide> function style($data, $inline = true) {
<ide> $out[] = $key.':'.$value.';';
<ide> }
<ide> if ($inline) {
<del> return join(' ', $out);
<add> return implode(' ', $out);
<ide> }
<del> return join("\n", $out);
<add> return implode("\n", $out);
<ide> }
<ide> /**
<ide> * Returns the breadcrumb trail as a sequence of »-separated links.
<ide> function getCrumbs($separator = '»', $startText = false) {
<ide> $out[] = $crumb[0];
<ide> }
<ide> }
<del> return $this->output(join($separator, $out));
<add> return $this->output(implode($separator, $out));
<ide> } else {
<ide> return null;
<ide> }
<ide> function tableHeaders($names, $trOptions = null, $thOptions = null) {
<ide> foreach ($names as $arg) {
<ide> $out[] = sprintf($this->tags['tableheader'], $this->_parseAttributes($thOptions), $arg);
<ide> }
<del> $data = sprintf($this->tags['tablerow'], $this->_parseAttributes($trOptions), join(' ', $out));
<add> $data = sprintf($this->tags['tablerow'], $this->_parseAttributes($trOptions), implode(' ', $out));
<ide> return $this->output($data);
<ide> }
<ide> /**
<ide> function tableCells($data, $oddTrOptions = null, $evenTrOptions = null, $useCoun
<ide> $cellsOut[] = sprintf($this->tags['tablecell'], $this->_parseAttributes($cellOptions), $cell);
<ide> }
<ide> $options = $this->_parseAttributes($count % 2 ? $oddTrOptions : $evenTrOptions);
<del> $out[] = sprintf($this->tags['tablerow'], $options, join(' ', $cellsOut));
<add> $out[] = sprintf($this->tags['tablerow'], $options, implode(' ', $cellsOut));
<ide> }
<del> return $this->output(join("\n", $out));
<add> return $this->output(implode("\n", $out));
<ide> }
<ide> /**
<ide> * Returns a formatted block tag, i.e DIV, SPAN, P.
<ide><path>cake/libs/view/helpers/javascript.php
<ide> function object($data = array(), $options = array(), $prefix = null, $postfix =
<ide> }
<ide>
<ide> if (!$numeric) {
<del> $rt = '{' . join(',', $out) . '}';
<add> $rt = '{' . implode(',', $out) . '}';
<ide> } else {
<del> $rt = '[' . join(',', $out) . ']';
<add> $rt = '[' . implode(',', $out) . ']';
<ide> }
<ide> }
<ide> $rt = $options['prefix'] . $rt . $options['postfix'];
<ide><path>cake/libs/view/helpers/js.php
<ide> function load_($url = null, $options = array()) {
<ide> $options['requestHeaders'] = array();
<ide> }
<ide> if (is_array($options['update'])) {
<del> $options['update'] = join(' ', $options['update']);
<add> $options['update'] = implode(' ', $options['update']);
<ide> }
<ide> $options['requestHeaders']['X-Update'] = $options['update'];
<ide> } else {
<ide> function object($data = array(), $block = false, $prefix = '', $postfix = '', $s
<ide> }
<ide>
<ide> if (!$numeric) {
<del> $rt = '{' . join(', ', $out) . '}';
<add> $rt = '{' . implode(', ', $out) . '}';
<ide> } else {
<del> $rt = '[' . join(', ', $out) . ']';
<add> $rt = '[' . implode(', ', $out) . ']';
<ide> }
<ide> $rt = $prefix . $rt . $postfix;
<ide>
<ide> function __options($opts) {
<ide> }
<ide> $options[] = $key . ':' . $val;
<ide> }
<del> return join(', ', $options);
<add> return implode(', ', $options);
<ide> }
<ide> }
<ide> ?>
<ide>\ No newline at end of file
<ide><path>cake/libs/view/helpers/rss.php
<ide> function item($att = array(), $elements = array()) {
<ide> }
<ide> $categories[] = $this->elem($key, $attrib, $category);
<ide> }
<del> $elements[$key] = join('', $categories);
<add> $elements[$key] = implode('', $categories);
<ide> continue 2;
<ide> } else if (is_array($val) && isset($val['domain'])) {
<ide> $attrib['domain'] = $val['domain'];
<ide> function item($att = array(), $elements = array()) {
<ide> $elements[$key] = $this->elem($key, $attrib, $val);
<ide> }
<ide> if (!empty($elements)) {
<del> $content = join('', $elements);
<add> $content = implode('', $elements);
<ide> }
<ide> return $this->output($this->elem('item', $att, $content, !($content === null)));
<ide> }
<ide><path>cake/libs/view/view.php
<ide> function renderLayout($content_for_layout, $layout = null) {
<ide> $data_for_layout = array_merge($this->viewVars, array(
<ide> 'title_for_layout' => $pageTitle,
<ide> 'content_for_layout' => $content_for_layout,
<del> 'scripts_for_layout' => join("\n\t", $this->__scripts),
<add> 'scripts_for_layout' => implode("\n\t", $this->__scripts),
<ide> 'cakeDebug' => $debug
<ide> ));
<ide>
<ide><path>cake/tests/lib/cake_test_case.php
<ide> function assertTags($string, $expected, $fullDebug = false) {
<ide> $permutations = $this->__array_permute($attrs);
<ide> $permutationTokens = array();
<ide> foreach ($permutations as $permutation) {
<del> $permutationTokens[] = join('', $permutation);
<add> $permutationTokens[] = implode('', $permutation);
<ide> }
<ide> $regex[] = array(
<del> sprintf('%s', join(', ', $explanations)),
<add> sprintf('%s', implode(', ', $explanations)),
<ide> $permutationTokens,
<ide> $i,
<ide> );
<ide><path>cake/tests/lib/test_manager.php
<ide> function &getTestCaseList() {
<ide> foreach ($testCases as $testCaseFile => $testCase) {
<ide> $title = explode(strpos($testCase, '\\') ? '\\' : '/', str_replace('.test.php', '', $testCase));
<ide> $title[count($title) - 1] = Inflector::camelize($title[count($title) - 1]);
<del> $title = join(' / ', $title);
<add> $title = implode(' / ', $title);
<ide>
<ide> $buffer .= "<li><a href='" . $manager->getBaseURL() . "?case=" . urlencode($testCase) . $urlExtra ."'>" . $title . "</a></li>\n";
<ide> } | 33 |
Mixed | Go | add load/save image event support | 06561057103441fe176910e12674d998b8561b75 | <ide><path>daemon/daemon.go
<ide> func isBrokenPipe(e error) bool {
<ide> // the same tag are exported. names is the set of tags to export, and
<ide> // outStream is the writer which the images are written to.
<ide> func (daemon *Daemon) ExportImage(names []string, outStream io.Writer) error {
<del> imageExporter := tarexport.NewTarExporter(daemon.imageStore, daemon.layerStore, daemon.referenceStore)
<add> imageExporter := tarexport.NewTarExporter(daemon.imageStore, daemon.layerStore, daemon.referenceStore, daemon)
<ide> return imageExporter.Save(names, outStream)
<ide> }
<ide>
<ide> func (daemon *Daemon) LookupImage(name string) (*types.ImageInspect, error) {
<ide> // complement of ImageExport. The input stream is an uncompressed tar
<ide> // ball containing images and metadata.
<ide> func (daemon *Daemon) LoadImage(inTar io.ReadCloser, outStream io.Writer, quiet bool) error {
<del> imageExporter := tarexport.NewTarExporter(daemon.imageStore, daemon.layerStore, daemon.referenceStore)
<add> imageExporter := tarexport.NewTarExporter(daemon.imageStore, daemon.layerStore, daemon.referenceStore, daemon)
<ide> return imageExporter.Load(inTar, outStream, quiet)
<ide> }
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.24.md
<ide> Docker containers report the following events:
<ide>
<ide> Docker images report the following events:
<ide>
<del> delete, import, pull, push, tag, untag
<add> delete, import, load, pull, push, save, tag, untag
<ide>
<ide> Docker volumes report the following events:
<ide>
<ide><path>docs/reference/commandline/events.md
<ide> Docker containers report the following events:
<ide>
<ide> Docker images report the following events:
<ide>
<del> delete, import, pull, push, tag, untag
<add> delete, import, load, pull, push, save, tag, untag
<ide>
<ide> Docker volumes report the following events:
<ide>
<ide><path>image/tarexport/load.go
<ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool)
<ide> }
<ide>
<ide> parentLinks = append(parentLinks, parentLink{imgID, m.Parent})
<add> l.loggerImgEvent.LogImageEvent(imgID.String(), imgID.String(), "load")
<ide> }
<ide>
<ide> for _, p := range validatedParentLinks(parentLinks) {
<ide><path>image/tarexport/save.go
<ide> func (s *saveSession) save(outStream io.Writer) error {
<ide>
<ide> parentID, _ := s.is.GetParent(id)
<ide> parentLinks = append(parentLinks, parentLink{id, parentID})
<add> s.tarexporter.loggerImgEvent.LogImageEvent(id.String(), id.String(), "save")
<ide> }
<ide>
<ide> for i, p := range validatedParentLinks(parentLinks) {
<ide><path>image/tarexport/tarexport.go
<ide> type manifestItem struct {
<ide> }
<ide>
<ide> type tarexporter struct {
<del> is image.Store
<del> ls layer.Store
<del> rs reference.Store
<add> is image.Store
<add> ls layer.Store
<add> rs reference.Store
<add> loggerImgEvent LogImageEvent
<add>}
<add>
<add>// LogImageEvent defines interface for event generation related to image tar(load and save) operations
<add>type LogImageEvent interface {
<add> //LogImageEvent generates an event related to an image operation
<add> LogImageEvent(imageID, refName, action string)
<ide> }
<ide>
<ide> // NewTarExporter returns new ImageExporter for tar packages
<del>func NewTarExporter(is image.Store, ls layer.Store, rs reference.Store) image.Exporter {
<add>func NewTarExporter(is image.Store, ls layer.Store, rs reference.Store, loggerImgEvent LogImageEvent) image.Exporter {
<ide> return &tarexporter{
<del> is: is,
<del> ls: ls,
<del> rs: rs,
<add> is: is,
<add> ls: ls,
<add> rs: rs,
<add> loggerImgEvent: loggerImgEvent,
<ide> }
<ide> }
<ide><path>integration-cli/docker_cli_events_test.go
<ide> func (s *DockerSuite) TestEventsImageImport(c *check.C) {
<ide> c.Assert(matches["action"], checker.Equals, "import", check.Commentf("matches: %v\nout:\n%s\n", matches, out))
<ide> }
<ide>
<add>func (s *DockerSuite) TestEventsImageLoad(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add> myImageName := "footest:v1"
<add> dockerCmd(c, "tag", "busybox", myImageName)
<add> since := daemonUnixTime(c)
<add>
<add> out, _ := dockerCmd(c, "images", "-q", "--no-trunc", myImageName)
<add> longImageID := strings.TrimSpace(out)
<add> c.Assert(longImageID, checker.Not(check.Equals), "", check.Commentf("Id should not be empty"))
<add>
<add> dockerCmd(c, "save", "-o", "saveimg.tar", myImageName)
<add> dockerCmd(c, "rmi", myImageName)
<add> out, _ = dockerCmd(c, "images", "-q", myImageName)
<add> noImageID := strings.TrimSpace(out)
<add> c.Assert(noImageID, checker.Equals, "", check.Commentf("Should not have any image"))
<add> dockerCmd(c, "load", "-i", "saveimg.tar")
<add>
<add> cmd := exec.Command("rm", "-rf", "saveimg.tar")
<add> runCommand(cmd)
<add>
<add> out, _ = dockerCmd(c, "images", "-q", "--no-trunc", myImageName)
<add> imageID := strings.TrimSpace(out)
<add> c.Assert(imageID, checker.Equals, longImageID, check.Commentf("Should have same image id as before"))
<add>
<add> out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=load")
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> c.Assert(events, checker.HasLen, 1)
<add> matches := eventstestutils.ScanMap(events[0])
<add> c.Assert(matches["id"], checker.Equals, imageID, check.Commentf("matches: %v\nout:\n%s\n", matches, out))
<add> c.Assert(matches["action"], checker.Equals, "load", check.Commentf("matches: %v\nout:\n%s\n", matches, out))
<add>
<add> out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=save")
<add> events = strings.Split(strings.TrimSpace(out), "\n")
<add> c.Assert(events, checker.HasLen, 1)
<add> matches = eventstestutils.ScanMap(events[0])
<add> c.Assert(matches["id"], checker.Equals, imageID, check.Commentf("matches: %v\nout:\n%s\n", matches, out))
<add> c.Assert(matches["action"], checker.Equals, "save", check.Commentf("matches: %v\nout:\n%s\n", matches, out))
<add>}
<add>
<ide> func (s *DockerSuite) TestEventsFilters(c *check.C) {
<ide> since := daemonUnixTime(c)
<ide> dockerCmd(c, "run", "--rm", "busybox", "true")
<ide><path>man/docker-events.1.md
<ide> information and real-time information.
<ide>
<ide> Docker containers will report the following events:
<ide>
<del> attach, commit, copy, create, destroy, die, exec_create, exec_start, export, kill, oom, pause, rename, resize, restart, start, stop, top, unpause
<add> attach, commit, copy, create, destroy, die, exec_create, exec_start, export, kill, oom, pause, rename, resize, restart, start, stop, top, unpause, update
<ide>
<del>and Docker images will report:
<add>Docker images report the following events:
<ide>
<del> delete, import, pull, push, tag, untag
<add> delete, import, load, pull, push, save, tag, untag
<add>
<add>Docker volumes report the following events:
<add>
<add> create, mount, unmount, destroy
<add>
<add>Docker networks report the following events:
<add>
<add> create, connect, disconnect, destroy
<ide>
<ide> # OPTIONS
<ide> **--help** | 8 |
Ruby | Ruby | add collectionproxy#length documentation | eb2c0a4f712b015bf6886286efd6e5b2eeaf54aa | <ide><path>activerecord/lib/active_record/associations/collection_proxy.rb
<ide> class CollectionProxy < Relation
<ide> # has_many :pets
<ide> # end
<ide> #
<del> # # This will execute:
<del> # # SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = ? [["person_id", 1]]
<ide> # person.pets.size # => 3
<add> # # Executes:
<add> # #
<add> # # SELECT COUNT(*)
<add> # # FROM "pets"
<add> # # WHERE "pets"."person_id" = 1
<ide> #
<del> # person.pets
<add> # person.pets # This will execute a SELECT * FROM query
<ide> # # => [
<ide> # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
<ide> # # #<Pet id: 2, name: "Spook", person_id: 1>,
<ide> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<ide> # # ]
<ide> #
<del> # # Because the collection is already loaded, this will behave like
<del> # <tt>collection.size</tt> and no SQL count query is executed.
<ide> # person.pets.size # => 3
<add> # # Because the collection is already loaded, this will behave like
<add> # # collection.size and no SQL count query is executed.
<add>
<add> ##
<add> # :method: length
<add> #
<add> # Returns the size of the collection calling +size+ on the target.
<add> # If the collection has been already loaded +length+ and +size+ are
<add> # equivalent. If not and you are going to need the records anyway this
<add> # method will take one less query because loads the collection. Otherwise
<add> # +size+ is more efficient.
<add> #
<add> # class Person < ActiveRecord::Base
<add> # has_many :pets
<add> # end
<add> #
<add> # person.pets.length # => 3
<add> # # Executes:
<add> # #
<add> # # SELECT "pets".*
<add> # # FROM "pets"
<add> # # WHERE "pets"."person_id" = 1
<add> #
<add> # # Because the collection is loaded, you can
<add> # # call the collection without execute a query:
<add> # person.pets
<add> # # => [
<add> # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
<add> # # #<Pet id: 2, name: "Spook", person_id: 1>,
<add> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<add> # # ]
<ide>
<ide> ##
<ide> # :method: empty? | 1 |
Python | Python | fix code quality | d6175a4268b6617944f98c5ed947d34c0eea58e2 | <ide><path>examples/language-modeling/run_language_modeling.py
<ide> class DataTrainingArguments:
<ide> default=None, metadata={"help": "The input training data file (a text file)."}
<ide> )
<ide> train_data_files: Optional[str] = field(
<del> default=None, metadata={
<add> default=None,
<add> metadata={
<ide> "help": "The input training data files (multiple files in glob format). "
<del> "Very often splitting large files to smaller files can prevent tokenizer going out of memory"
<del> }
<add> "Very often splitting large files to smaller files can prevent tokenizer going out of memory"
<add> },
<ide> )
<ide> eval_data_file: Optional[str] = field(
<ide> default=None, | 1 |
Text | Text | add callbacks documentation for upgrading to 4.1 | 489e531334bc448c88f9b5a74f1bbbcaeb3f067b | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> symbol access is no longer supported. This is also the case for
<ide> `store_accessors` based on top of `json` or `hstore` columns. Make sure to use
<ide> string keys consistently.
<ide>
<add>### Explicit block use for `ActiveSupport::Callbacks`
<add>
<add>Rails 4.1 now expects an explicit block to be passed when calling
<add>`ActiveSupport::Callbacks.set_callback`. This change stems from
<add>`ActiveSupport::Callbacks` being largely rewritten for the 4.1 release.
<add>
<add>```ruby
<add># Rails 4.1
<add>set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff }
<add>
<add># Rails 4.0
<add>set_callback :save, :around, ->(r, &block) { stuff; result = block.call; stuff }
<add>```
<add>
<ide> Upgrading from Rails 3.2 to Rails 4.0
<ide> -------------------------------------
<ide> | 1 |
Javascript | Javascript | remove obsolete settimeout | 671cffa313784347583162f50029a59b3ec753d3 | <ide><path>lib/_debugger.js
<ide> function Interface(stdin, stdout, args) {
<ide> // Run script automatically
<ide> this.pause();
<ide>
<del> // XXX Need to figure out why we need this delay
<del> setTimeout(function() {
<del>
<del> self.run(function() {
<del> self.resume();
<del> });
<del> }, 10);
<add> setImmediate(() => { this.run(); });
<ide> }
<ide>
<ide> | 1 |
Java | Java | correct the assert imports | 8cea9ca96213aaa1c35bd755cb82b6265cda79ad | <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/MessageChannelArgumentResolver.java
<ide> import org.springframework.messaging.GenericMessage;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageChannel;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.web.messaging.PubSubHeaders;
<ide>
<del>import reactor.util.Assert;
<del>
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/MessageReturnValueHandler.java
<ide> import org.springframework.messaging.GenericMessage;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageChannel;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.web.messaging.PubSubHeaders;
<ide>
<del>import reactor.util.Assert;
<del>
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/StompHeaders.java
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageHeaders;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.messaging.PubSubHeaders;
<ide>
<del>import reactor.util.Assert;
<del>
<ide>
<ide> /**
<ide> * Can be used to prepare headers for a new STOMP message, or to access and/or modify
<ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageChannel;
<ide> import org.springframework.messaging.SubscribableChannel;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.web.messaging.MessageType;
<ide> import org.springframework.web.messaging.converter.CompositeMessageConverter;
<ide> import org.springframework.web.messaging.converter.MessageConverter;
<ide> import org.springframework.web.messaging.service.AbstractPubSubMessageHandler;
<ide> import org.springframework.web.messaging.stomp.StompCommand;
<ide> import org.springframework.web.messaging.stomp.StompHeaders;
<ide>
<del>import reactor.util.Assert;
<del>
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev | 4 |
Text | Text | add period for readability | 8c22432b177a9431ab488975865f8b596aa52c9a | <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md
<ide> You can nest links within other text elements.
<ide>
<ide> Let's break down the example: Normal text is wrapped in the `p` element:
<ide> `<p> Here's a ... for you to follow. </p>` Next is the *anchor* element `<a>` (which requires a closing tag `</a>`):
<del>`<a> ... </a>` `target` is an anchor tag attribute that specifies where to open the link and the value `"_blank"` specifies to open the link in a new tab `href` is an anchor tag attribute that contains the URL address of the link:
<add>`<a> ... </a>` `target` is an anchor tag attribute that specifies where to open the link and the value `"_blank"` specifies to open the link in a new tab. `href` is an anchor tag attribute that contains the URL address of the link:
<ide> `<a href="http://freecodecamp.org"> ... </a>` The text, **"link to freecodecamp.org"**, within the `a` element called `anchor text`, will display a link to click:
<ide> `<a href=" ... ">link to freecodecamp.org</a>` The final output of the example will look like this:
<ide> | 1 |
Text | Text | add missing comma in docs | 814bc06d7bf69c7775b775179c7a3edb8d30685c | <ide><path>docs/sources/reference/api/docker_remote_api_v1.15.md
<ide> Create a container
<ide> "Cmd":[
<ide> "date"
<ide> ],
<del> "Entrypoint": ""
<add> "Entrypoint": "",
<ide> "Image":"base",
<ide> "Volumes":{
<ide> "/tmp": {}
<ide><path>docs/sources/reference/api/docker_remote_api_v1.16.md
<ide> Create a container
<ide> "Cmd":[
<ide> "date"
<ide> ],
<del> "Entrypoint": ""
<add> "Entrypoint": "",
<ide> "Image":"base",
<ide> "Volumes":{
<ide> "/tmp": {} | 2 |
Text | Text | improve readme with testing instruction | 75b688fba8335598c19b9333459b6939dcf0a32c | <ide><path>packages/react-native-codegen/README.md
<ide> yarn add --dev react-native-codegen
<ide>
<ide> [version-badge]: https://img.shields.io/npm/v/react-native-codegen?style=flat-square
<ide> [package]: https://www.npmjs.com/package/react-native-codegen
<add>
<add>## Testing
<add>
<add>To run the tests in this package, run the following commands from the react Native root folder:
<add>
<add>1. `yarn` to install the dependencies. You just need to run this once
<add>2. `yarn jest react-native-codegen`. | 1 |
Javascript | Javascript | add tests for worker code | 07f67fa2259091824fd2ff28fd07034b57aa1def | <ide><path>packager/react-packager/src/ModuleGraph/types.flow.js
<ide> export type PackageData = {|
<ide> 'react-native'?: Object | string,
<ide> |};
<ide>
<del>export type TransformFnResult = {|
<add>export type TransformFnResult = {
<ide> ast: Object,
<del> map?: Object,
<del>|};
<add>};
<ide>
<ide> export type TransformFn = (
<ide> data: {|
<ide><path>packager/react-packager/src/ModuleGraph/worker/__tests__/optimize-module-test.js
<add>/**
<add> * Copyright (c) 2016-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>jest.disableAutomock();
<add>
<add>const optimizeModule = require('../optimize-module');
<add>const transformModule = require('../transform-module');
<add>const transform = require('../../../../../transformer.js');
<add>const {SourceMapConsumer} = require('source-map');
<add>
<add>const {objectContaining} = jasmine;
<add>
<add>describe('optimizing JS modules', () => {
<add> const filename = 'arbitrary/file.js';
<add> const optimizationOptions = {
<add> dev: false,
<add> platform: 'android',
<add> };
<add> const originalCode =
<add> `if (Platform.OS !== 'android') {
<add> require('arbitrary-dev');
<add> } else {
<add> __DEV__ ? require('arbitrary-android-dev') : require('arbitrary-android-prod');
<add> }`;
<add>
<add> let transformResult;
<add> beforeAll(done => {
<add> transformModule(originalCode, {filename, transform}, (error, result) => {
<add> if (error) {
<add> throw error;
<add> }
<add> transformResult = JSON.stringify(result);
<add> done();
<add> });
<add> });
<add>
<add> it('copies everything from the transformed file, except for transform results', done => {
<add> optimizeModule(transformResult, optimizationOptions, (error, result) => {
<add> const expected = JSON.parse(transformResult);
<add> delete expected.transformed;
<add> expect(result).toEqual(objectContaining(expected));
<add> done();
<add> });
<add> });
<add>
<add> describe('code optimization', () => {
<add> let dependencyMapName, injectedVars, optimized, requireName;
<add> beforeAll(done => {
<add> optimizeModule(transformResult, optimizationOptions, (error, result) => {
<add> optimized = result.transformed.default;
<add> injectedVars = optimized.code.match(/function\(([^)]*)/)[1].split(',');
<add> [requireName,,,, dependencyMapName] = injectedVars;
<add> done();
<add> });
<add> });
<add>
<add> it('optimizes code', () => {
<add> expect(optimized.code)
<add> .toEqual(`__d(function(${injectedVars}){${requireName}(${dependencyMapName}[0])});`);
<add> });
<add>
<add> it('extracts dependencies', () => {
<add> expect(optimized.dependencies).toEqual(['arbitrary-android-prod']);
<add> });
<add>
<add> it('creates source maps', () => {
<add> const consumer = new SourceMapConsumer(optimized.map);
<add> const column = optimized.code.lastIndexOf(requireName + '(');
<add> const loc = findLast(originalCode, 'require');
<add>
<add> expect(consumer.originalPositionFor({line: 1, column}))
<add> .toEqual(objectContaining(loc));
<add> });
<add>
<add> it('does not extract dependencies for polyfills', done => {
<add> optimizeModule(
<add> transformResult,
<add> {...optimizationOptions, isPolyfill: true},
<add> (error, result) => {
<add> expect(result.transformed.default.dependencies).toEqual([]);
<add> done();
<add> },
<add> );
<add> });
<add> });
<add>});
<add>
<add>function findLast(code, needle) {
<add> const lines = code.split(/(?:(?!.)\s)+/);
<add> let line = lines.length;
<add> while (line--) {
<add> const column = lines[line].lastIndexOf(needle);
<add> if (column !== -1) {
<add> return {line: line + 1, column};
<add> }
<add> }
<add>}
<ide><path>packager/react-packager/src/ModuleGraph/worker/__tests__/transform-module-test.js
<add>/**
<add> * Copyright (c) 2016-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>jest.disableAutomock();
<add>
<add>const transformModule = require('../transform-module');
<add>
<add>const t = require('babel-types');
<add>const {SourceMapConsumer} = require('source-map');
<add>const {fn} = require('../../test-helpers');
<add>const {parse} = require('babylon');
<add>const generate = require('babel-generator').default;
<add>const {traverse} = require('babel-core');
<add>
<add>const {any, objectContaining} = jasmine;
<add>
<add>describe('transforming JS modules:', () => {
<add> const filename = 'arbitrary';
<add>
<add> let transform;
<add>
<add> beforeEach(() => {
<add> transform = fn();
<add> transform.stub.yields(null, transformResult());
<add> });
<add>
<add> const {bodyAst, sourceCode, transformedCode} = createTestData();
<add>
<add> const options = variants => ({
<add> filename,
<add> transform,
<add> variants,
<add> });
<add>
<add> const transformResult = (body = bodyAst) => ({
<add> ast: t.file(t.program(body)),
<add> });
<add>
<add> it('passes through file name and code', done => {
<add> transformModule(sourceCode, options(), (error, result) => {
<add> expect(result).toEqual(objectContaining({
<add> code: sourceCode,
<add> file: filename,
<add> }));
<add> done();
<add> });
<add> });
<add>
<add> it('exposes a haste ID if present', done => {
<add> const hasteID = 'TheModule';
<add> const codeWithHasteID = `/** @providesModule ${hasteID} */`;
<add> transformModule(codeWithHasteID, options(), (error, result) => {
<add> expect(result).toEqual(objectContaining({hasteID}));
<add> done();
<add> });
<add> });
<add>
<add> it('sets `isPolyfill` to `false` by default', done => {
<add> transformModule(sourceCode, options(), (error, result) => {
<add> expect(result).toEqual(objectContaining({isPolyfill: false}));
<add> done();
<add> });
<add> });
<add>
<add> it('sets `isPolyfill` to `true` if the input is a polyfill', done => {
<add> transformModule(sourceCode, {...options(), polyfill: true}, (error, result) => {
<add> expect(result).toEqual(objectContaining({isPolyfill: true}));
<add> done();
<add> });
<add> });
<add>
<add> it('calls the passed-in transform function with code, file name, and options for all passed in variants', done => {
<add> const variants = {dev: {dev: true}, prod: {dev: false}};
<add>
<add> transformModule(sourceCode, options(variants), () => {
<add> expect(transform)
<add> .toBeCalledWith({filename, sourceCode, options: variants.dev}, any(Function));
<add> expect(transform)
<add> .toBeCalledWith({filename, sourceCode, options: variants.prod}, any(Function));
<add> done();
<add> });
<add> });
<add>
<add> it('calls back with any error yielded by the transform function', done => {
<add> const error = new Error();
<add> transform.stub.yields(error);
<add>
<add> transformModule(sourceCode, options(), e => {
<add> expect(e).toBe(error);
<add> done();
<add> });
<add> });
<add>
<add> it('wraps the code produced by the transform function into a module factory', done => {
<add> transformModule(sourceCode, options(), (error, result) => {
<add> expect(error).toEqual(null);
<add>
<add> const {code, dependencyMapName} = result.transformed.default;
<add> expect(code.replace(/\s+/g, ''))
<add> .toEqual(
<add> `__d(function(require,module,global,exports,${
<add> dependencyMapName}){${transformedCode}});`
<add> );
<add> done();
<add> });
<add> });
<add>
<add> it('wraps the code produced by the transform function into an immediately invoked function expression for polyfills', done => {
<add> transformModule(sourceCode, {...options(), polyfill: true}, (error, result) => {
<add> expect(error).toEqual(null);
<add>
<add> const {code} = result.transformed.default;
<add> expect(code.replace(/\s+/g, ''))
<add> .toEqual(`(function(global){${transformedCode}})(this);`);
<add> done();
<add> });
<add> });
<add>
<add> it('creates source maps', done => {
<add> transformModule(sourceCode, options(), (error, result) => {
<add> const {code, map} = result.transformed.default;
<add> const column = code.indexOf('code');
<add> const consumer = new SourceMapConsumer(map);
<add> expect(consumer.originalPositionFor({line: 1, column}))
<add> .toEqual(objectContaining({line: 1, column: sourceCode.indexOf('code')}));
<add> done();
<add> });
<add> });
<add>
<add> it('extracts dependencies (require calls)', done => {
<add> const dep1 = 'foo', dep2 = 'bar';
<add> const code = `require('${dep1}'),require('${dep2}')`;
<add> const {body} = parse(code).program;
<add> transform.stub.yields(null, transformResult(body));
<add>
<add> transformModule(code, options(), (error, result) => {
<add> expect(result.transformed.default)
<add> .toEqual(objectContaining({dependencies: [dep1, dep2]}));
<add> done();
<add> });
<add> });
<add>
<add> it('transforms for all variants', done => {
<add> const variants = {dev: {dev: true}, prod: {dev: false}};
<add> transform.stub
<add> .withArgs(filename, sourceCode, variants.dev)
<add> .yields(null, transformResult(bodyAst))
<add> .withArgs(filename, sourceCode, variants.prod)
<add> .yields(null, transformResult([]));
<add>
<add> transformModule(sourceCode, options(variants), (error, result) => {
<add> const {dev, prod} = result.transformed;
<add> expect(dev.code.replace(/\s+/g, ''))
<add> .toEqual(
<add> `__d(function(require,module,global,exports,${
<add> dev.dependencyMapName}){arbitrary(code);});`
<add> );
<add> expect(prod.code.replace(/\s+/g, ''))
<add> .toEqual(
<add> `__d(function(require,module,global,exports,${
<add> prod.dependencyMapName}){arbitrary(code);});`
<add> );
<add> done();
<add> });
<add> });
<add>
<add> it('prefixes JSON files with `module.exports = `', done => {
<add> const json = '{"foo":"bar"}';
<add>
<add> transformModule(json, {...options(), filename: 'some.json'}, (error, result) => {
<add> const {code} = result.transformed.default;
<add> expect(code.replace(/\s+/g, ''))
<add> .toEqual(
<add> '__d(function(require,module,global,exports){' +
<add> `module.exports=${json}});`
<add> );
<add> done();
<add> });
<add> });
<add>
<add> it('does not create source maps for JSON files', done => {
<add> transformModule('{}', {...options(), filename: 'some.json'}, (error, result) => {
<add> expect(result.transformed.default)
<add> .toEqual(objectContaining({map: null}));
<add> done();
<add> });
<add> });
<add>
<add> it('adds package data for `package.json` files', done => {
<add> const pkg = {
<add> name: 'package-name',
<add> main: 'package/main',
<add> browser: {browser: 'defs'},
<add> 'react-native': {'react-native': 'defs'},
<add> };
<add>
<add> transformModule(
<add> JSON.stringify(pkg),
<add> {...options(), filename: 'arbitrary/package.json'},
<add> (error, result) => {
<add> expect(result.package).toEqual(pkg);
<add> done();
<add> },
<add> );
<add> });
<add>});
<add>
<add>function createTestData() {
<add> // creates test data with an transformed AST, so that we can test source
<add> // map generation.
<add> const sourceCode = 'some(arbitrary(code));';
<add> const fileAst = parse(sourceCode);
<add> traverse(fileAst, {
<add> CallExpression(path) {
<add> if (path.node.callee.name === 'some') {
<add> path.replaceWith(path.node.arguments[0]);
<add> }
<add> }
<add> });
<add> return {
<add> bodyAst: fileAst.program.body,
<add> sourceCode,
<add> transformedCode: generate(fileAst).code,
<add> };
<add>}
<ide><path>packager/react-packager/src/ModuleGraph/worker/optimize-module.js
<ide> const sourceMap = require('source-map');
<ide> import type {Callback, TransformedFile, TransformResult} from '../types.flow';
<ide>
<ide> export type OptimizationOptions = {|
<del> dev?: boolean,
<add> dev: boolean,
<ide> isPolyfill?: boolean,
<del> platform?: string,
<add> platform: string,
<ide> |};
<ide>
<ide> function optimizeModule(
<ide><path>packager/react-packager/src/ModuleGraph/worker/transform-module.js
<ide> function transformJSON(json, options, callback) {
<ide> const code =
<ide> `__d(function(${moduleFactoryParameters.join(', ')}) { module.exports = \n${
<ide> json
<del> }\n})`;
<add> }\n});`;
<ide>
<ide> const moduleData = {
<ide> code, | 5 |
Text | Text | improve csp guide [ci-skip] | 2a3bc5bd180caf2197839ab82782ada7072b0c00 | <ide><path>guides/source/security.md
<ide> your application if you are aware of the risk and know how to handle it:
<ide> config.action_dispatch.perform_deep_munge = false
<ide> ```
<ide>
<del>Default Headers
<del>---------------
<add>HTTP Security Headers
<add>---------------------
<ide>
<ide> Every HTTP response from your Rails application receives the following default security headers.
<ide>
<ide> Here is a list of common headers:
<ide>
<ide> ### Content Security Policy
<ide>
<del>Rails provides a DSL that allows you to configure a
<add>To help protect against XSS and injection attacks, it is recommended to define a
<ide> [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)
<del>for your application. You can configure a global default policy and then
<add>for your application. Rails provides a DSL that allows you to configure a
<add>Content Security Policy. You can configure a global default policy and then
<ide> override it on a per-resource basis and even use lambdas to inject per-request
<del>values into the header such as account subdomains in a multi-tenant application.
<add>values into the header such as account subdomains in a multi-tenant
<add>application.
<ide>
<ide> Example global policy:
<ide>
<ide> class LegacyPagesController < ApplicationController
<ide> end
<ide> ```
<ide>
<add>#### Reporting Violations
<add>
<ide> Use the `content_security_policy_report_only`
<ide> configuration attribute to set
<ide> [Content-Security-Policy-Report-Only](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only)
<ide> class PostsController < ApplicationController
<ide> end
<ide> ```
<ide>
<del>You can enable automatic nonce generation:
<add>#### Adding a Nonce
<add>
<add>If you are considering 'unsafe-inline', consider using nonces instead. [Nonces
<add>provide a substantial improvement](https://www.w3.org/TR/CSP3/#security-nonces)
<add>over 'unsafe-inline' when implementing a Content Security Policy on top
<add>existing code.
<ide>
<ide> ```ruby
<ide> # config/initializers/content_security_policy.rb | 1 |
Javascript | Javascript | prevent spare datasets from breaking multitooltips | d7632efe65dde5deb2a19c01aa3d01d91458ef56 | <ide><path>src/Chart.Core.js
<ide> yMin;
<ide> helpers.each(this.datasets, function(dataset){
<ide> dataCollection = dataset.points || dataset.bars || dataset.segments;
<del> Elements.push(dataCollection[dataIndex]);
<add> if (dataCollection[dataIndex]){
<add> Elements.push(dataCollection[dataIndex]);
<add> }
<ide> });
<ide>
<ide> helpers.each(Elements, function(element) { | 1 |
Python | Python | finalise the feature | 0463d0df3bd7480391d8d2964e1b574c6aed7c86 | <ide><path>glances/outputs/glances_curses.py
<ide> def display(self, servers_list):
<ide>
<ide> # Display top header
<ide> if len(servers_list) == 0:
<del> if self.first_scan:
<add> if self.first_scan and not self.args.disable_autodiscover:
<ide> msg = _("Glances is scanning your network (please wait)...")
<ide> self.first_scan = False
<ide> else:
<del> msg = _("No Glances server detected on your network")
<add> msg = _("No Glances servers available")
<ide> elif len(servers_list) == 1:
<del> msg = _("One Glances server detected on your network")
<add> msg = _("One Glances server available")
<ide> else:
<del> msg = _("%d Glances servers detected on your network" %
<add> msg = _("%d Glances servers available" %
<ide> len(servers_list))
<ide> if self.args.disable_autodiscover:
<del> msg += ' ' + _("(autodiscover is disabled)")
<add> msg += ' ' + _("(auto discover is disabled)")
<ide> self.term_window.addnstr(y, x,
<ide> msg,
<ide> screen_x - x, | 1 |
Javascript | Javascript | add unit tests for new sc.eventmanager api | 1f800c3b339805ea0d072e62ad9fcf01fafac674 | <ide><path>packages/sproutcore-views/tests/system/event_dispatcher_test.js
<ide> test("should not interfere with event propagation", function() {
<ide> same(receivedEvent.target, SC.$('#propagate-test-div')[0], "target property is the element that was clicked");
<ide> });
<ide>
<add>test("should dispatch events to nearest event manager", function() {
<add> var receivedEvent=0;
<add> view = SC.ContainerView.create({
<add> render: function(buffer) {
<add> buffer.push('<input id="is-done" type="checkbox">');
<add> },
<add>
<add> eventManager: SC.Object.create({
<add> mouseDown: function() {
<add> receivedEvent++;
<add> }
<add> }),
<add>
<add> mouseDown: function() {}
<add> });
<add>
<add> SC.run(function() {
<add> view.append();
<add> });
<add>
<add> SC.$('#is-done').trigger('mousedown');
<add> equals(receivedEvent, 1, "event should go to manager and not view");
<add>});
<add>
<add>test("event manager should be able to re-dispatch events to view", function() {
<add>
<add> var receivedEvent=0;
<add> view = SC.ContainerView.create({
<add> elementId: 'containerView',
<add>
<add> eventManager: SC.Object.create({
<add> mouseDown: function() {
<add> receivedEvent++;
<add> }
<add> }),
<add>
<add> mouseDown: function() {}
<add> });
<add>
<add> SC.run(function() {
<add> view.append();
<add> });
<add>
<add> var childViews = get(view,'childViews');
<add>
<add> childViews.append(SC.View.create({
<add> elementId: 'nestedView'
<add> }));
<add>
<add> SC.$('#containerView').trigger('mousedown');
<add> equals(receivedEvent, 1, "event should go to manager and not view");
<add>}); | 1 |
Javascript | Javascript | treat rollup "warnings" as errors | dc3b144f4162087665f62f4fdac69549181ce310 | <ide><path>scripts/rollup/build.js
<ide> async function createBundle(bundle, bundleType) {
<ide> }
<ide>
<ide> function handleRollupWarning(warning) {
<del> if (warning.code === 'UNRESOLVED_IMPORT') {
<del> console.error(warning.message);
<del> process.exit(1);
<del> }
<ide> if (warning.code === 'UNUSED_EXTERNAL_IMPORT') {
<ide> const match = warning.message.match(/external module '([^']+)'/);
<ide> if (!match || typeof match[1] !== 'string') {
<ide> function handleRollupWarning(warning) {
<ide> // Don't warn. We will remove side effectless require() in a later pass.
<ide> return;
<ide> }
<del> console.warn(warning.message || warning);
<add>
<add> if (typeof warning.code === 'string') {
<add> // This is a warning coming from Rollup itself.
<add> // These tend to be important (e.g. clashes in namespaced exports)
<add> // so we'll fail the build on any of them.
<add> console.error();
<add> console.error(warning.message || warning);
<add> console.error();
<add> process.exit(1);
<add> } else {
<add> // The warning is from one of the plugins.
<add> // Maybe it's not important, so just print it.
<add> console.warn(warning.message || warning);
<add> }
<ide> }
<ide>
<ide> function handleRollupError(error) { | 1 |
Text | Text | update license year | ca19860684782531bd932b48a8428fc6249ed489 | <ide><path>license.md
<ide> The MIT License (MIT)
<ide>
<del>Copyright (c) 2021 Vercel, Inc.
<add>Copyright (c) 2022 Vercel, Inc.
<ide>
<ide> Permission is hereby granted, free of charge, to any person obtaining a copy
<ide> of this software and associated documentation files (the "Software"), to deal
<ide><path>packages/next-codemod/license.md
<ide> The MIT License (MIT)
<ide>
<del>Copyright (c) 2021 Vercel, Inc.
<add>Copyright (c) 2022 Vercel, Inc.
<ide>
<ide> Permission is hereby granted, free of charge, to any person obtaining a copy
<ide> of this software and associated documentation files (the "Software"), to deal
<ide><path>packages/next-mdx/license.md
<ide> The MIT License (MIT)
<ide>
<del>Copyright (c) 2021 Vercel, Inc.
<add>Copyright (c) 2022 Vercel, Inc.
<ide>
<ide> Permission is hereby granted, free of charge, to any person obtaining a copy
<ide> of this software and associated documentation files (the "Software"), to deal
<ide><path>packages/next/license.md
<ide> The MIT License (MIT)
<ide>
<del>Copyright (c) 2021 Vercel, Inc.
<add>Copyright (c) 2022 Vercel, Inc.
<ide>
<ide> Permission is hereby granted, free of charge, to any person obtaining a copy
<ide> of this software and associated documentation files (the "Software"), to deal | 4 |
Java | Java | add headers in interceptingclienthttprequest | 69c16f3821354c9b0732687825cb902375649c5a | <ide><path>spring-core/src/main/java/org/springframework/util/CollectionUtils.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 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 MultiValueMapAdapter(Map<K, List<V>> map) {
<ide>
<ide> @Override
<ide> public void add(K key, V value) {
<del> List<V> values = this.map.get(key);
<del> if (values == null) {
<del> values = new LinkedList<>();
<del> this.map.put(key, values);
<del> }
<add> List<V> values = this.map.computeIfAbsent(key, k -> new LinkedList<>());
<ide> values.add(value);
<ide> }
<ide>
<add> @Override
<add> public void addAll(K key, List<V> values) {
<add> List<V> currentValues = this.map.computeIfAbsent(key, k -> new LinkedList<>());
<add> currentValues.addAll(values);
<add> }
<add>
<ide> @Override
<ide> public V getFirst(K key) {
<ide> List<V> values = this.map.get(key);
<ide><path>spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 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 LinkedMultiValueMap(Map<K, List<V>> otherMap) {
<ide>
<ide> @Override
<ide> public void add(K key, V value) {
<del> List<V> values = this.targetMap.get(key);
<del> if (values == null) {
<del> values = new LinkedList<>();
<del> this.targetMap.put(key, values);
<del> }
<add> List<V> values = this.targetMap.computeIfAbsent(key, k -> new LinkedList<>());
<ide> values.add(value);
<ide> }
<ide>
<add> @Override
<add> public void addAll(K key, List<V> values) {
<add> List<V> currentValues = this.targetMap.computeIfAbsent(key, k -> new LinkedList<>());
<add> currentValues.addAll(values);
<add> }
<add>
<ide> @Override
<ide> public V getFirst(K key) {
<ide> List<V> values = this.targetMap.get(key);
<ide><path>spring-core/src/main/java/org/springframework/util/MultiValueMap.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> void add(K key, V value);
<ide>
<add> /**
<add> * Add all the values of the given list to the current list of values for the given key.
<add> * @param key they key
<add> * @param values the values to be added
<add> */
<add> void addAll(K key, List<V> values);
<add>
<ide> /**
<ide> * Set the given single value under the given key.
<ide> * @param key the key
<ide><path>spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 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> package org.springframework.util;
<ide>
<ide> import java.util.ArrayList;
<add>import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<del>import static org.junit.Assert.*;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertNull;
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<ide> public void add() {
<ide> assertEquals(expected, map.get("key"));
<ide> }
<ide>
<add> @Test
<add> public void addAll() throws Exception {
<add> map.add("key", "value1");
<add> map.addAll("key", Arrays.asList("value2", "value3"));
<add> assertEquals(1, map.size());
<add> List<String> expected = new ArrayList<>(2);
<add> expected.add("value1");
<add> expected.add("value2");
<add> expected.add("value3");
<add> assertEquals(expected, map.get("key"));
<add> }
<add>
<ide> @Test
<ide> public void getFirst() {
<ide> List<String> values = new ArrayList<>(2);
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompHeaders.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 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 String getFirst(String headerName) {
<ide> */
<ide> @Override
<ide> public void add(String headerName, String headerValue) {
<del> List<String> headerValues = headers.get(headerName);
<del> if (headerValues == null) {
<del> headerValues = new LinkedList<>();
<del> this.headers.put(headerName, headerValues);
<del> }
<add> List<String> headerValues = headers.computeIfAbsent(headerName, k -> new LinkedList<>());
<ide> headerValues.add(headerValue);
<ide> }
<ide>
<add> @Override
<add> public void addAll(String headerName, List<String> headerValues) {
<add> List<String> currentValues = headers.computeIfAbsent(headerName, k -> new LinkedList<>());
<add> currentValues.addAll(headerValues);
<add> }
<add>
<ide> /**
<ide> * Set the given, single header value under the given name.
<ide> * @param headerName the header name
<ide><path>spring-web/src/main/java/org/springframework/http/HttpHeaders.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 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 String getFirst(String headerName) {
<ide> */
<ide> @Override
<ide> public void add(String headerName, String headerValue) {
<del> List<String> headerValues = this.headers.get(headerName);
<del> if (headerValues == null) {
<del> headerValues = new LinkedList<>();
<del> this.headers.put(headerName, headerValues);
<del> }
<add> List<String> headerValues =
<add> this.headers.computeIfAbsent(headerName, k -> new LinkedList<>());
<ide> headerValues.add(headerValue);
<ide> }
<ide>
<add> @Override
<add> public void addAll(String key, List<String> values) {
<add> List<String> currentValues = this.headers.computeIfAbsent(key, k -> new LinkedList<>());
<add> currentValues.addAll(values);
<add> }
<add>
<ide> /**
<ide> * Set the given, single header value under the given name.
<ide> * @param headerName the header name
<ide><path>spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.net.URI;
<ide> import java.util.Iterator;
<ide> import java.util.List;
<add>import java.util.Map;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOExc
<ide> }
<ide> else {
<ide> ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod());
<del> delegate.getHeaders().putAll(request.getHeaders());
<add> for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
<add> delegate.getHeaders().addAll(entry.getKey(), entry.getValue());
<add> }
<ide> if (body.length > 0) {
<ide> StreamUtils.copy(body, delegate.getBody());
<ide> } | 7 |
Javascript | Javascript | use common.port not 8000 | cb14236bb442fa652c1f598576b868c2f878c2dd | <ide><path>test/simple/test-tls-securepair-server.js
<ide> var sentWorld = false;
<ide> var gotWorld = false;
<ide> var opensslExitCode = -1;
<ide>
<del>server.listen(8000, function() {
<add>server.listen(common.PORT, function() {
<ide> // To test use: openssl s_client -connect localhost:8000
<del> var client = spawn('openssl', ['s_client', '-connect', '127.0.0.1:8000']);
<add> var client = spawn('openssl', ['s_client', '-connect', '127.0.0.1:' + common.PORT]);
<ide>
<ide>
<ide> var out = ''; | 1 |
Javascript | Javascript | remove preparenewchildrenbeforeunmountinstack flag | b840229286ac2a82fa49553ce793cf7b953d1845 | <ide><path>src/renderers/shared/stack/reconciler/ReactChildReconciler.js
<ide> 'use strict';
<ide>
<ide> var KeyEscapeUtils = require('KeyEscapeUtils');
<del>var ReactFeatureFlags = require('ReactFeatureFlags');
<ide> var ReactReconciler = require('ReactReconciler');
<ide>
<ide> var instantiateReactComponent = require('instantiateReactComponent');
<ide> var ReactChildReconciler = {
<ide> );
<ide> nextChildren[name] = prevChild;
<ide> } else {
<del> if (
<del> !ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack &&
<del> prevChild
<del> ) {
<del> removedNodes[name] = ReactReconciler.getHostNode(prevChild);
<del> ReactReconciler.unmountComponent(
<del> prevChild,
<del> false /* safely */,
<del> false /* skipLifecycle */,
<del> );
<del> }
<ide> // The child must be instantiated before it's mounted.
<ide> var nextChildInstance = instantiateReactComponent(nextElement, true);
<ide> nextChildren[name] = nextChildInstance;
<ide> var ReactChildReconciler = {
<ide> selfDebugID,
<ide> );
<ide> mountImages.push(nextChildMountImage);
<del> if (
<del> ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack &&
<del> prevChild
<del> ) {
<add> if (prevChild) {
<ide> removedNodes[name] = ReactReconciler.getHostNode(prevChild);
<ide> ReactReconciler.unmountComponent(
<ide> prevChild,
<ide><path>src/renderers/shared/stack/reconciler/ReactCompositeComponent.js
<ide> var React = require('react');
<ide> var ReactComponentEnvironment = require('ReactComponentEnvironment');
<ide> var ReactCompositeComponentTypes = require('ReactCompositeComponentTypes');
<ide> var ReactErrorUtils = require('ReactErrorUtils');
<del>var ReactFeatureFlags = require('ReactFeatureFlags');
<ide> var ReactInstanceMap = require('ReactInstanceMap');
<ide> var ReactInstrumentation = require('ReactInstrumentation');
<ide> var ReactNodeTypes = require('ReactNodeTypes');
<ide> var ReactCompositeComponent = {
<ide> );
<ide> } else {
<ide> var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance);
<del>
<del> if (!ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack) {
<del> ReactReconciler.unmountComponent(
<del> prevComponentInstance,
<del> safely,
<del> false /* skipLifecycle */,
<del> );
<del> }
<del>
<ide> var nodeType = ReactNodeTypes.getType(nextRenderedElement);
<ide> this._renderedNodeType = nodeType;
<ide> var child = this._instantiateReactComponent(
<ide> var ReactCompositeComponent = {
<ide> debugID,
<ide> );
<ide>
<del> if (ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack) {
<del> ReactReconciler.unmountComponent(
<del> prevComponentInstance,
<del> safely,
<del> false /* skipLifecycle */,
<del> );
<del> }
<add> ReactReconciler.unmountComponent(
<add> prevComponentInstance,
<add> safely,
<add> false /* skipLifecycle */,
<add> );
<ide>
<ide> if (__DEV__) {
<ide> if (debugID !== 0) {
<ide><path>src/renderers/shared/utils/ReactFeatureFlags.js
<ide> 'use strict';
<ide>
<ide> var ReactFeatureFlags = {
<del> prepareNewChildrenBeforeUnmountInStack: true,
<ide> disableNewFiberFeatures: false,
<ide> enableAsyncSubtreeAPI: false,
<ide> }; | 3 |
Javascript | Javascript | pass transformoptions to getshallowdependencies | 82000416948edaf9431f94bdfc4db30e5fea529c | <ide><path>local-cli/server/util/attachHMRServer.js
<ide> function attachHMRServer({httpServer, path, packagerServer}) {
<ide> if (dep.isAsset() || dep.isAsset_DEPRECATED() || dep.isJSON()) {
<ide> return Promise.resolve({path: dep.path, deps: []});
<ide> }
<del> return packagerServer.getShallowDependencies(dep.path)
<add> return packagerServer.getShallowDependencies({
<add> platform: platform,
<add> dev: true,
<add> hot: true,
<add> entryFile: dep.path
<add> })
<ide> .then(deps => {
<ide> return {
<ide> path: dep.path,
<ide> function attachHMRServer({httpServer, path, packagerServer}) {
<ide>
<ide> client.ws.send(JSON.stringify({type: 'update-start'}));
<ide> stat.then(() => {
<del> return packagerServer.getShallowDependencies(filename)
<add> return packagerServer.getShallowDependencies({
<add> entryFile: filename,
<add> platform: client.platform,
<add> dev: true,
<add> hot: true,
<add> })
<ide> .then(deps => {
<ide> if (!client) {
<ide> return [];
<ide><path>packager/react-packager/src/Bundler/index.js
<ide> class Bundler {
<ide> this._cache.invalidate(filePath);
<ide> }
<ide>
<del> getShallowDependencies(entryFile) {
<del> return this._resolver.getShallowDependencies(entryFile);
<add> getShallowDependencies({
<add> entryFile,
<add> platform,
<add> dev = true,
<add> minify = !dev,
<add> hot = false,
<add> generateSourceMaps = false,
<add> }) {
<add> return this.getTransformOptions(
<add> entryFile,
<add> {
<add> dev,
<add> platform,
<add> hot,
<add> generateSourceMaps,
<add> projectRoots: this._projectRoots,
<add> },
<add> ).then(transformSpecificOptions => {
<add> const transformOptions = {
<add> minify,
<add> dev,
<add> platform,
<add> transform: transformSpecificOptions,
<add> };
<add>
<add> return this._resolver.getShallowDependencies(entryFile, transformOptions);
<add> });
<ide> }
<ide>
<ide> stat(filePath) {
<ide><path>packager/react-packager/src/Resolver/index.js
<ide> class Resolver {
<ide> });
<ide> }
<ide>
<del> getShallowDependencies(entryFile) {
<del> return this._depGraph.getShallowDependencies(entryFile);
<add> getShallowDependencies(entryFile, transformOptions) {
<add> return this._depGraph.getShallowDependencies(entryFile, transformOptions);
<ide> }
<ide>
<ide> stat(filePath) {
<ide><path>packager/react-packager/src/Server/index.js
<ide> class Server {
<ide> return this._bundler.hmrBundle(modules, host, port);
<ide> }
<ide>
<del> getShallowDependencies(entryFile) {
<del> return this._bundler.getShallowDependencies(entryFile);
<add> getShallowDependencies(options) {
<add> return Promise.resolve().then(() => {
<add> if (!options.platform) {
<add> options.platform = getPlatformExtension(options.entryFile);
<add> }
<add>
<add> const opts = dependencyOpts(options);
<add> return this._bundler.getShallowDependencies(opts);
<add> });
<ide> }
<ide>
<ide> getModuleForPath(entryFile) { | 4 |
Javascript | Javascript | remove ember.empty and ember.none | b98b1ff7084c051fad8a2c03b504dbd6c644940e | <ide><path>packages/ember-handlebars/lib/helpers/partial.js
<ide> import Ember from "ember-metal/core"; // Ember.assert
<ide> // var emberAssert = Ember.assert;
<ide>
<del>import { isNone } from 'ember-metal/is_none';
<add>import isNone from 'ember-metal/is_none';
<ide> import { bind } from "ember-handlebars/helpers/binding";
<ide>
<ide> /**
<ide><path>packages/ember-metal/lib/computed.js
<del>import Ember from "ember-metal/core";
<ide> import { set } from "ember-metal/property_set";
<ide> import {
<ide> meta,
<ide><path>packages/ember-metal/lib/computed_macros.js
<ide> import { get } from "ember-metal/property_get";
<ide> import { set } from "ember-metal/property_set";
<ide> import { computed } from "ember-metal/computed";
<ide> import isEmpty from 'ember-metal/is_empty';
<del>import { isNone } from 'ember-metal/is_none';
<add>import isNone from 'ember-metal/is_none';
<ide> import alias from 'ember-metal/alias';
<ide>
<ide> /**
<ide><path>packages/ember-metal/lib/is_empty.js
<del>import Ember from 'ember-metal/core'; // deprecateFunc
<ide> import { get } from 'ember-metal/property_get';
<ide> import isNone from 'ember-metal/is_none';
<ide>
<ide> function isEmpty(obj) {
<ide> return false;
<ide> }
<ide>
<del>var empty = Ember.deprecateFunc("Ember.empty is deprecated. Please use Ember.isEmpty instead.", isEmpty);
<del>
<ide> export default isEmpty;
<del>export {
<del> isEmpty,
<del> empty
<del>};
<ide><path>packages/ember-metal/lib/is_none.js
<del>import Ember from 'ember-metal/core'; // deprecateFunc
<del>
<ide> /**
<ide> Returns true if the passed value is null or undefined. This avoids errors
<ide> from JSLint complaining about use of ==, which can be technically
<ide> function isNone(obj) {
<ide> return obj === null || obj === undefined;
<ide> }
<ide>
<del>export var none = Ember.deprecateFunc("Ember.none is deprecated. Please use Ember.isNone instead.", isNone);
<del>
<ide> export default isNone;
<del>export { isNone };
<ide><path>packages/ember-metal/lib/main.js
<ide> import {
<ide> } from "ember-metal/binding";
<ide> import run from "ember-metal/run_loop";
<ide> import libraries from "ember-metal/libraries";
<del>import {
<del> isNone,
<del> none
<del>} from 'ember-metal/is_none';
<del>import {
<del> isEmpty,
<del> empty
<del>} from 'ember-metal/is_empty';
<add>import isNone from 'ember-metal/is_none';
<add>import isEmpty from 'ember-metal/is_empty';
<ide> import isBlank from 'ember-metal/is_blank';
<ide> import isPresent from 'ember-metal/is_present';
<ide> import keys from 'ember-metal/keys';
<ide> Ember.libraries = libraries;
<ide> Ember.libraries.registerCoreLibrary('Ember', Ember.VERSION);
<ide>
<ide> Ember.isNone = isNone;
<del>Ember.none = none;
<del>
<ide> Ember.isEmpty = isEmpty;
<del>Ember.empty = empty;
<del>
<ide> Ember.isBlank = isBlank;
<ide>
<ide> if (Ember.FEATURES.isEnabled('ember-metal-is-present')) {
<ide><path>packages/ember-routing/lib/system/route.js
<ide> import {
<ide> forEach,
<ide> replace
<ide> }from "ember-metal/enumerable_utils";
<del>import { isNone } from "ember-metal/is_none";
<add>import isNone from "ember-metal/is_none";
<ide> import { computed } from "ember-metal/computed";
<ide> import merge from "ember-metal/merge";
<ide> import {
<ide><path>packages/ember-runtime/lib/mixins/array.js
<ide> import {
<ide> computed,
<ide> cacheFor
<ide> } from 'ember-metal/computed';
<del>import {
<del> isNone
<del>} from 'ember-metal/is_none';
<add>import isNone from 'ember-metal/is_none';
<ide> import Enumerable from 'ember-runtime/mixins/enumerable';
<ide> import { map } from 'ember-metal/enumerable_utils';
<ide> import {
<ide><path>packages/ember-runtime/lib/mixins/observable.js
<ide> import {
<ide> observersFor
<ide> } from "ember-metal/observer";
<ide> import { cacheFor } from "ember-metal/computed";
<del>import { isNone } from "ember-metal/is_none";
<add>import isNone from "ember-metal/is_none";
<ide>
<ide>
<ide> var slice = Array.prototype.slice;
<ide><path>packages/ember-runtime/lib/system/set.js
<ide> import Ember from "ember-metal/core"; // Ember.isNone, Ember.A
<ide> import { get } from "ember-metal/property_get";
<ide> import { set } from "ember-metal/property_set";
<ide> import { guidFor } from "ember-metal/utils";
<del>import { isNone } from 'ember-metal/is_none';
<add>import isNone from 'ember-metal/is_none';
<ide> import { fmt } from "ember-runtime/system/string";
<ide> import CoreObject from "ember-runtime/system/core_object";
<ide> import MutableEnumerable from "ember-runtime/mixins/mutable_enumerable";
<ide><path>packages/ember-runtime/tests/core/is_empty_test.js
<ide> import Ember from "ember-metal/core";
<del>import {isEmpty} from 'ember-metal/is_empty';
<add>import isEmpty from 'ember-metal/is_empty';
<ide> import ArrayProxy from "ember-runtime/system/array_proxy";
<ide>
<ide> QUnit.module("Ember.isEmpty");
<ide><path>packages/ember-runtime/tests/legacy_1x/system/set_test.js
<ide> import Ember from "ember-metal/core";
<del>import { isNone } from 'ember-metal/is_none';
<add>import isNone from 'ember-metal/is_none';
<ide> import Set from "ember-runtime/system/set";
<ide> import EmberObject from 'ember-runtime/system/object';
<ide> import EmberArray from "ember-runtime/mixins/array";
<ide><path>packages/ember-views/lib/system/event_dispatcher.js
<ide> import Ember from "ember-metal/core"; // Ember.assert
<ide>
<ide> import { get } from "ember-metal/property_get";
<ide> import { set } from "ember-metal/property_set";
<del>import { isNone } from 'ember-metal/is_none';
<add>import isNone from 'ember-metal/is_none';
<ide> import run from "ember-metal/run_loop";
<ide> import { typeOf } from "ember-metal/utils";
<ide> import { fmt } from "ember-runtime/system/string";
<ide><path>packages/ember-views/lib/views/component.js
<ide> import View from "ember-views/views/view";
<ide>
<ide> import { get } from "ember-metal/property_get";
<ide> import { set } from "ember-metal/property_set";
<del>import { isNone } from 'ember-metal/is_none';
<add>import isNone from 'ember-metal/is_none';
<ide>
<ide> import { computed } from "ember-metal/computed";
<ide>
<ide><path>packages/ember-views/lib/views/view.js
<ide> import {
<ide> typeOf,
<ide> isArray
<ide> } from "ember-metal/utils";
<del>import { isNone } from 'ember-metal/is_none';
<add>import isNone from 'ember-metal/is_none';
<ide> import { Mixin } from 'ember-metal/mixin';
<ide> import { deprecateProperty } from "ember-metal/deprecate_property";
<ide> import { A as emberA } from "ember-runtime/system/native_array"; | 15 |
Python | Python | add iteration version (#322) | faf16d7ced7f563bb0c92265bef27b6664156fb5 | <ide><path>traversals/binary_tree_traversals.py
<ide> def build_tree():
<ide> node_found.right = right_node
<ide> q.put(right_node)
<ide>
<del>
<ide> def pre_order(node):
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<ide> print(node.data, end=" ")
<ide> pre_order(node.left)
<ide> pre_order(node.right)
<ide>
<del>
<ide> def in_order(node):
<ide> if not isinstance(node, TreeNode) or not node:
<ide> return
<ide> def level_order(node):
<ide> if node_dequeued.right:
<ide> q.put(node_dequeued.right)
<ide>
<add>#iteration version
<add>def pre_order_iter(node):
<add> if not isinstance(node, TreeNode) or not node:
<add> return
<add> stack = []
<add> n = node
<add> while n or stack:
<add> while n: #start from root node, find its left child
<add> print(n.data, end=" ")
<add> stack.append(n)
<add> n = n.left
<add> #end of while means current node doesn't have left child
<add> n = stack.pop()
<add> #start to traverse its right child
<add> n = n.right
<add>
<add>def in_order_iter(node):
<add> if not isinstance(node, TreeNode) or not node:
<add> return
<add> stack = []
<add> n = node
<add> while n or stack:
<add> while n:
<add> stack.append(n)
<add> n = n.left
<add> n = stack.pop()
<add> print(n.data, end=" ")
<add> n = n.right
<add>
<add>def post_order_iter(node):
<add> if not isinstance(node, TreeNode) or not node:
<add> return
<add> stack1, stack2 = [], []
<add> n = node
<add> stack1.append(n)
<add> while stack1: #to find the reversed order of post order, store it in stack2
<add> n = stack1.pop()
<add> if n.left:
<add> stack1.append(n.left)
<add> if n.right:
<add> stack1.append(n.right)
<add> stack2.append(n)
<add> while stack2: #pop up from stack2 will be the post order
<add> print(stack2.pop().data, end=" ")
<ide>
<ide> if __name__ == '__main__':
<ide> print("\n********* Binary Tree Traversals ************\n")
<ide> def level_order(node):
<ide> print("\n********* Level Order Traversal ************")
<ide> level_order(node)
<ide> print("\n******************************************\n")
<add>
<add> print("\n********* Pre Order Traversal - Iteration Version ************")
<add> pre_order_iter(node)
<add> print("\n******************************************\n")
<add>
<add> print("\n********* In Order Traversal - Iteration Version ************")
<add> in_order_iter(node)
<add> print("\n******************************************\n")
<add>
<add> print("\n********* Post Order Traversal - Iteration Version ************")
<add> post_order_iter(node)
<add> print("\n******************************************\n")
<ide>\ No newline at end of file | 1 |
Javascript | Javascript | fix asset httpserverlocation on windows | fe3686e126ee66adc6b2e44b46ba82e5ae6c434c | <ide><path>packager/react-packager/src/Bundler/index.js
<ide> class Bundler {
<ide>
<ide> generateAssetModule(bundle, module, platform = null) {
<ide> const relPath = getPathRelativeToRoot(this._projectRoots, module.path);
<add> var assetUrlPath = path.join('/assets', path.dirname(relPath));
<add>
<add> // On Windows, change backslashes to slashes to get proper URL path from file path.
<add> if (path.sep === '\\') {
<add> assetUrlPath = assetUrlPath.replace(/\\/g, '/');
<add> }
<ide>
<ide> return Promise.all([
<ide> sizeOf(module.path),
<ide> class Bundler {
<ide> const img = {
<ide> __packager_asset: true,
<ide> fileSystemLocation: path.dirname(module.path),
<del> httpServerLocation: path.join('/assets', path.dirname(relPath)),
<add> httpServerLocation: assetUrlPath,
<ide> width: dimensions.width / module.resolution,
<ide> height: dimensions.height / module.resolution,
<ide> scales: assetData.scales, | 1 |
Text | Text | fix typo in action view changelog [ci skip] | 65bbfa9519990c218b8dee740722d57a4ae117c4 | <ide><path>actionview/CHANGELOG.md
<del>* Add `caching?` helper that returns whether the current code path is being cached and `unacheable!` to denote helper methods that can't participate in fragment caching.
<add>* Add `caching?` helper that returns whether the current code path is being cached and `uncacheable!` to denote helper methods that can't participate in fragment caching.
<ide>
<ide> *Ben Toews*, *John Hawthorn*, *Kasper Timm Hansen*, *Joel Hawksley*
<ide> | 1 |
Javascript | Javascript | add simple explicit export types to devtools | e6a062bd2a1d53f7349a0d0950d89593b63a0c3c | <ide><path>packages/react-devtools-core/src/standalone.js
<ide> function initialize(socket: WebSocket) {
<ide>
<ide> let startServerTimeoutID: TimeoutID | null = null;
<ide>
<del>function connectToSocket(socket: WebSocket) {
<add>function connectToSocket(socket: WebSocket): {close(): void} {
<ide> socket.onerror = err => {
<ide> onDisconnected();
<ide> log.error('Error with websocket connection', err);
<ide> function startServer(
<ide> host?: string = 'localhost',
<ide> httpsOptions?: ServerOptions,
<ide> loggerOptions?: LoggerOptions,
<del>) {
<add>): {close(): void} {
<ide> registerDevToolsEventLogger(loggerOptions?.surface ?? 'standalone');
<ide>
<ide> const useHttps = !!httpsOptions;
<ide><path>packages/react-devtools-shared/src/backend/views/utils.js
<ide> export function getOwnerIframe(node: HTMLElement): HTMLElement | null {
<ide>
<ide> // Get a bounding client rect for a node, with an
<ide> // offset added to compensate for its border.
<del>export function getBoundingClientRectWithBorderOffset(node: HTMLElement) {
<add>export function getBoundingClientRectWithBorderOffset(node: HTMLElement): Rect {
<ide> const dimensions = getElementDimensions(node);
<ide> return mergeRectOffsets([
<ide> node.getBoundingClientRect(),
<ide> export function getNestedBoundingClientRect(
<ide> }
<ide> }
<ide>
<del>export function getElementDimensions(domElement: Element) {
<add>export function getElementDimensions(
<add> domElement: Element,
<add>): {
<add> borderBottom: number,
<add> borderLeft: number,
<add> borderRight: number,
<add> borderTop: number,
<add> marginBottom: number,
<add> marginLeft: number,
<add> marginRight: number,
<add> marginTop: number,
<add> paddingBottom: number,
<add> paddingLeft: number,
<add> paddingRight: number,
<add> paddingTop: number,
<add>} {
<ide> const calculatedStyle = window.getComputedStyle(domElement);
<ide> return {
<ide> borderLeft: parseInt(calculatedStyle.borderLeftWidth, 10),
<ide><path>packages/react-devtools-shared/src/bridge.js
<ide> class Bridge<
<ide> }
<ide> }
<ide>
<del> _flush = () => {
<add> _flush: () => void = () => {
<ide> // This method is used after the bridge is marked as destroyed in shutdown sequence,
<ide> // so we do not bail out if the bridge marked as destroyed.
<ide> // It is a private method that the bridge ensures is only called at the right times.
<ide> class Bridge<
<ide>
<ide> // Temporarily support older standalone backends by forwarding "overrideValueAtPath" commands
<ide> // to the older message types they may be listening to.
<del> overrideValueAtPath = ({
<add> overrideValueAtPath: OverrideValueAtPath => void = ({
<ide> id,
<ide> path,
<ide> rendererID,
<ide><path>packages/react-devtools-shared/src/constants.js
<ide> export const THEME_STYLES: {[style: Theme | DisplayDensity]: any, ...} = {
<ide> //
<ide> // Sometimes the inline target is rendered before root styles are applied,
<ide> // which would result in e.g. NaN itemSize being passed to react-window list.
<del>const COMFORTABLE_LINE_HEIGHT = parseInt(
<add>const COMFORTABLE_LINE_HEIGHT: number = parseInt(
<ide> THEME_STYLES.comfortable['--line-height-data'],
<ide> 10,
<ide> );
<del>const COMPACT_LINE_HEIGHT = parseInt(
<add>const COMPACT_LINE_HEIGHT: number = parseInt(
<ide> THEME_STYLES.compact['--line-height-data'],
<ide> 10,
<ide> );
<ide><path>packages/react-devtools-shared/src/devtools/ContextMenu/Contexts.js
<ide> function showMenu({
<ide> }
<ide> }
<ide>
<del>function registerMenu(id: string, showFn: ShowFn, hideFn: HideFn) {
<add>function registerMenu(id: string, showFn: ShowFn, hideFn: HideFn): () => void {
<ide> if (idToShowFnMap.has(id)) {
<ide> throw Error(`Context menu with id "${id}" already registered.`);
<ide> }
<ide><path>packages/react-devtools-shared/src/devtools/utils.js
<ide> import type {Element} from './views/Components/types';
<ide> import type {StateContext} from './views/Components/TreeContext';
<ide> import type Store from './store';
<ide>
<del>export function printElement(element: Element, includeWeight: boolean = false) {
<add>export function printElement(
<add> element: Element,
<add> includeWeight: boolean = false,
<add>): string {
<ide> let prefix = ' ';
<ide> if (element.children.length > 0) {
<ide> prefix = element.isCollapsed ? '▸' : '▾';
<ide> export function printElement(element: Element, includeWeight: boolean = false) {
<ide> export function printOwnersList(
<ide> elements: Array<Element>,
<ide> includeWeight: boolean = false,
<del>) {
<add>): string {
<ide> return elements
<ide> .map(element => printElement(element, includeWeight))
<ide> .join('\n');
<ide> export function printStore(
<ide> store: Store,
<ide> includeWeight: boolean = false,
<ide> state: StateContext | null = null,
<del>) {
<add>): string {
<ide> const snapshotLines = [];
<ide>
<ide> let rootWeight = 0;
<ide> export function smartParse(value: any) {
<ide> }
<ide> }
<ide>
<del>export function smartStringify(value: any) {
<add>export function smartStringify(value: any): string {
<ide> if (typeof value === 'number') {
<ide> if (Number.isNaN(value)) {
<ide> return 'NaN';
<ide><path>packages/react-devtools-shared/src/devtools/views/ButtonIcon.js
<ide> type Props = {
<ide> type: IconType,
<ide> };
<ide>
<del>export default function ButtonIcon({className = '', type}: Props) {
<add>export default function ButtonIcon({className = '', type}: Props): React.Node {
<ide> let pathData = null;
<ide> switch (type) {
<ide> case 'add':
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/Badge.js
<ide> export default function Badge({
<ide> hocDisplayNames,
<ide> type,
<ide> children,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> if (hocDisplayNames === null || hocDisplayNames.length === 0) {
<ide> return null;
<ide> }
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/CannotSuspendWarningMessage.js
<ide> import {
<ide> ElementTypeSuspense,
<ide> } from 'react-devtools-shared/src/types';
<ide>
<del>export default function CannotSuspendWarningMessage() {
<add>export default function CannotSuspendWarningMessage(): React.Node {
<ide> const store = useContext(StoreContext);
<ide> const areSuspenseElementsHidden = !!store.componentFilters.find(
<ide> filter =>
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/ComponentSearchInput.js
<ide> import SearchInput from '../SearchInput';
<ide>
<ide> type Props = {};
<ide>
<del>export default function ComponentSearchInput(props: Props) {
<add>export default function ComponentSearchInput(props: Props): React.Node {
<ide> const {searchIndex, searchResults, searchText} = useContext(TreeStateContext);
<ide> const dispatch = useContext(TreeDispatcherContext);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/EditableName.js
<ide> export default function EditableName({
<ide> overrideName,
<ide> path,
<ide> type,
<del>}: EditableNameProps) {
<add>}: EditableNameProps): React.Node {
<ide> const [editableName, setEditableName] = useState(initialValue);
<ide> const [isValid, setIsValid] = useState(false);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/EditableValue.js
<ide> export default function EditableValue({
<ide> overrideValue,
<ide> path,
<ide> value,
<del>}: EditableValueProps) {
<add>}: EditableValueProps): React.Node {
<ide> const [state, dispatch] = useEditableValue(value);
<ide> const {editableValue, hasPendingChanges, isValid, parsedValue} = state;
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/Element.js
<ide> type Props = {
<ide> ...
<ide> };
<ide>
<del>export default function Element({data, index, style}: Props) {
<add>export default function Element({data, index, style}: Props): React.Node {
<ide> const store = useContext(StoreContext);
<ide> const {ownerFlatTree, ownerID, selectedElementID} = useContext(
<ide> TreeStateContext,
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/HocBadges.js
<ide> type Props = {
<ide> element: Element,
<ide> };
<ide>
<del>export default function HocBadges({element}: Props) {
<add>export default function HocBadges({element}: Props): React.Node {
<ide> const {hocDisplayNames} = ((element: any): Element);
<ide>
<ide> if (hocDisplayNames === null) {
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectHostNodesToggle.js
<ide> import Toggle from '../Toggle';
<ide> import ButtonIcon from '../ButtonIcon';
<ide> import {logEvent} from 'react-devtools-shared/src/Logger';
<ide>
<del>export default function InspectHostNodesToggle() {
<add>export default function InspectHostNodesToggle(): React.Node {
<ide> const [isInspecting, setIsInspecting] = useState(false);
<ide> const bridge = useContext(BridgeContext);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElement.js
<ide> export type Props = {};
<ide>
<ide> // TODO Make edits and deletes also use transition API!
<ide>
<del>export default function InspectedElementWrapper(_: Props) {
<add>export default function InspectedElementWrapper(_: Props): React.Node {
<ide> const {inspectedElementID} = useContext(TreeStateContext);
<ide> const dispatch = useContext(TreeDispatcherContext);
<ide> const {canViewElementSourceFunction, viewElementSourceFunction} = useContext(
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContextTree.js
<ide> export default function InspectedElementContextTree({
<ide> element,
<ide> inspectedElement,
<ide> store,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const {hasLegacyContext, context, type} = inspectedElement;
<ide>
<ide> const isReadOnly = type !== ElementTypeClass && type !== ElementTypeFunction;
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementErrorBoundary.js
<ide> type WrapperProps = {
<ide>
<ide> export default function InspectedElementErrorBoundaryWrapper({
<ide> children,
<del>}: WrapperProps) {
<add>}: WrapperProps): React.Node {
<ide> // Key on the selected element ID so that changing the selected element automatically hides the boundary.
<ide> // This seems best since an error inspecting one element isn't likely to be relevant to another element.
<ide> const {selectedElementID} = useContext(TreeStateContext);
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementErrorsAndWarningsTree.js
<ide> export default function InspectedElementErrorsAndWarningsTree({
<ide> bridge,
<ide> inspectedElement,
<ide> store,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const refresh = useCacheRefresh();
<ide>
<ide> const [
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementHooksTree.js
<ide> export function InspectedElementHooksTree({
<ide> parseHookNames,
<ide> store,
<ide> toggleParseHookNames,
<del>}: HooksTreeViewProps) {
<add>}: HooksTreeViewProps): React.Node {
<ide> const {hooks, id} = inspectedElement;
<ide>
<ide> // Changing parseHookNames is done in a transition, because it suspends.
<ide> export function InnerHooksTreeView({
<ide> id,
<ide> inspectedElement,
<ide> path,
<del>}: InnerHooksTreeViewProps) {
<add>}: InnerHooksTreeViewProps): React.Node {
<ide> // $FlowFixMe "Missing type annotation for U" whatever that means
<ide> return hooks.map((hook, index) => (
<ide> <HookView
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementPropsTree.js
<ide> export default function InspectedElementPropsTree({
<ide> element,
<ide> inspectedElement,
<ide> store,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const {readOnly} = React.useContext(OptionsContext);
<ide>
<ide> const {
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementStateTree.js
<ide> export default function InspectedElementStateTree({
<ide> element,
<ide> inspectedElement,
<ide> store,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const {state} = inspectedElement;
<ide>
<ide> const entries = state != null ? Object.entries(state) : null;
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementStyleXPlugin.js
<ide> export default function InspectedElementStyleXPlugin({
<ide> element,
<ide> inspectedElement,
<ide> store,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> if (!enableStyleXFeatures) {
<ide> return null;
<ide> }
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementSuspenseToggle.js
<ide> export default function InspectedElementSuspenseToggle({
<ide> bridge,
<ide> inspectedElement,
<ide> store,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const {readOnly} = React.useContext(OptionsContext);
<ide>
<ide> const {id, state, type} = inspectedElement;
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementView.js
<ide> export default function InspectedElementView({
<ide> inspectedElement,
<ide> parseHookNames,
<ide> toggleParseHookNames,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const {id} = element;
<ide> const {
<ide> owners,
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/LoadingAnimation.js
<ide> type Props = {
<ide> className?: string,
<ide> };
<ide>
<del>export default function LoadingAnimation({className = ''}: Props) {
<add>export default function LoadingAnimation({className = ''}: Props): React.Node {
<ide> return (
<ide> <svg
<ide> xmlns="http://www.w3.org/2000/svg"
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/AutoSizeInput.js
<ide> export default function AutoSizeInput({
<ide> testName,
<ide> value,
<ide> ...rest
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const onFocusWrapper = event => {
<ide> const input = event.target;
<ide> if (input !== null) {
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/LayoutViewer.js
<ide> type Props = {
<ide> layout: Layout,
<ide> };
<ide>
<del>export default function LayoutViewer({id, layout}: Props) {
<add>export default function LayoutViewer({id, layout}: Props): React.Node {
<ide> const {height, margin, padding, y, width, x} = layout;
<ide>
<ide> return (
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/StyleEditor.js
<ide> type Props = {
<ide> type ChangeAttributeFn = (oldName: string, newName: string, value: any) => void;
<ide> type ChangeValueFn = (name: string, value: any) => void;
<ide>
<del>export default function StyleEditor({id, style}: Props) {
<add>export default function StyleEditor({id, style}: Props): React.Node {
<ide> const bridge = useContext(BridgeContext);
<ide> const store = useContext(StoreContext);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/index.js
<ide> import {TreeStateContext} from '../TreeContext';
<ide>
<ide> type Props = {};
<ide>
<del>export default function NativeStyleEditorWrapper(_: Props) {
<add>export default function NativeStyleEditorWrapper(_: Props): React.Node {
<ide> const store = useContext(StoreContext);
<ide>
<ide> const subscription = useMemo(
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/NewArrayValue.js
<ide> export default function NewArrayValue({
<ide> path,
<ide> store,
<ide> type,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const [key, setKey] = useState<number>(0);
<ide> const [isInvalid, setIsInvalid] = useState(false);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/NewKeyValue.js
<ide> export default function NewKeyValue({
<ide> path,
<ide> store,
<ide> type,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const [newPropKey, setNewPropKey] = useState<number>(0);
<ide> const [newPropName, setNewPropName] = useState<string>('');
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/OwnersStack.js
<ide> function dialogReducer(state, action) {
<ide> }
<ide> }
<ide>
<del>export default function OwnerStack() {
<add>export default function OwnerStack(): React.Node {
<ide> const read = useContext(OwnersListContext);
<ide> const {ownerID} = useContext(TreeStateContext);
<ide> const treeDispatch = useContext(TreeDispatcherContext);
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/SelectedTreeHighlight.js
<ide> type Data = {
<ide> stopIndex: number,
<ide> };
<ide>
<del>export default function SelectedTreeHighlight(_: {}) {
<add>export default function SelectedTreeHighlight(_: {}): React.Node {
<ide> const {lineHeight} = useContext(SettingsContext);
<ide> const store = useContext(StoreContext);
<ide> const treeFocused = useContext(TreeFocusedContext);
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/Tree.js
<ide> export type ItemData = {
<ide>
<ide> type Props = {};
<ide>
<del>export default function Tree(props: Props) {
<add>export default function Tree(props: Props): React.Node {
<ide> const dispatch = useContext(TreeDispatcherContext);
<ide> const {
<ide> numElements,
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/reach-ui/menu-button.js
<ide> import {
<ide> } from '@reach/menu-button';
<ide> import useThemeStyles from '../../useThemeStyles';
<ide>
<del>const MenuList = ({children, ...props}: {children: React$Node, ...}) => {
<add>const MenuList = ({
<add> children,
<add> ...props
<add>}: {
<add> children: React$Node,
<add> ...
<add>}): React.Node => {
<ide> const style = useThemeStyles();
<ide> return (
<ide> // $FlowFixMe unsafe spread
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/reach-ui/tooltip.js
<ide> const Tooltip = ({
<ide> children: React$Node,
<ide> className: string,
<ide> ...
<del>}) => {
<add>}): React.Node => {
<ide> const style = useThemeStyles();
<ide> return (
<ide> // $FlowFixMe unsafe spread
<ide><path>packages/react-devtools-shared/src/devtools/views/DevTools.js
<ide> export default function DevTools({
<ide> hideToggleSuspenseAction,
<ide> hideLogAction,
<ide> hideViewSourceAction,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const [currentTab, setTab] = useLocalStorage<TabID>(
<ide> LOCAL_STORAGE_DEFAULT_TAB_KEY,
<ide> defaultTab,
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/CaughtErrorView.js
<ide> export default function CaughtErrorView({
<ide> info,
<ide> componentStack,
<ide> errorMessage,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> return (
<ide> <div className={styles.ErrorBoundary}>
<ide> {children}
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/ErrorView.js
<ide> export default function ErrorView({
<ide> componentStack,
<ide> dismissError = null,
<ide> errorMessage,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> return (
<ide> <div className={styles.ErrorBoundary}>
<ide> {children}
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/ReportNewIssue.js
<ide> export default function ReportNewIssue({
<ide> callStack,
<ide> componentStack,
<ide> errorMessage,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> let bugURL = process.env.GITHUB_URL;
<ide> if (!bugURL) {
<ide> return null;
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/SearchingGitHubIssues.js
<ide> import * as React from 'react';
<ide> import LoadingAnimation from 'react-devtools-shared/src/devtools/views/Components/LoadingAnimation';
<ide> import styles from './shared.css';
<ide>
<del>export default function SearchingGitHubIssues() {
<add>export default function SearchingGitHubIssues(): React.Node {
<ide> return (
<ide> <div className={styles.GitHubLinkRow}>
<ide> <LoadingAnimation className={styles.LoadingIcon} />
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/SuspendingErrorView.js
<ide> export default function SuspendingErrorView({
<ide> callStack,
<ide> componentStack,
<ide> errorMessage,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const maybeItem =
<ide> errorMessage !== null ? findGitHubIssue(errorMessage) : null;
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/TimeoutView.js
<ide> export default function TimeoutView({
<ide> componentStack,
<ide> dismissError = null,
<ide> errorMessage,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> return (
<ide> <div className={styles.ErrorBoundary}>
<ide> {children}
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/UnsupportedBridgeOperationView.js
<ide> export default function UnsupportedBridgeOperationView({
<ide> children,
<ide> componentStack,
<ide> errorMessage,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> return (
<ide> <div className={styles.ErrorBoundary}>
<ide> {children}
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/UpdateExistingIssue.js
<ide> export default function UpdateExistingIssue({
<ide> gitHubIssue,
<ide> }: {
<ide> gitHubIssue: GitHubIssue,
<del>}) {
<add>}): React.Node {
<ide> const {title, url} = gitHubIssue;
<ide> return (
<ide> <div className={styles.GitHubLinkRow}>
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/WorkplaceGroup.js
<ide> import {REACT_DEVTOOLS_WORKPLACE_URL} from 'react-devtools-shared/src/constants'
<ide> import Icon from '../Icon';
<ide> import styles from './shared.css';
<ide>
<del>export default function WorkplaceGroup() {
<add>export default function WorkplaceGroup(): React.Node {
<ide> if (!isInternalFacebookBuild) {
<ide> return null;
<ide> }
<ide><path>packages/react-devtools-shared/src/devtools/views/Icon.js
<ide> type Props = {
<ide> type: IconType,
<ide> };
<ide>
<del>export default function Icon({className = '', title = '', type}: Props) {
<add>export default function Icon({
<add> className = '',
<add> title = '',
<add> type,
<add>}: Props): React.Node {
<ide> let pathData = null;
<ide> switch (type) {
<ide> case 'arrow':
<ide><path>packages/react-devtools-shared/src/devtools/views/ModalDialog.js
<ide> type Props = {
<ide> children: React$Node,
<ide> };
<ide>
<del>function ModalDialogContextController({children}: Props) {
<add>function ModalDialogContextController({children}: Props): React.Node {
<ide> const [state, dispatch] = useReducer<State, State, Action>(dialogReducer, {
<ide> dialogs: [],
<ide> });
<ide> function ModalDialogContextController({children}: Props) {
<ide> );
<ide> }
<ide>
<del>function ModalDialog(_: {}) {
<add>function ModalDialog(_: {}): React.Node {
<ide> const {dialogs, dispatch} = useContext(ModalDialogContext);
<ide>
<ide> if (dialogs.length === 0) {
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/ChartNode.js
<ide> export default function ChartNode({
<ide> width,
<ide> x,
<ide> y,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> return (
<ide> <g className={styles.Group} transform={`translate(${x},${y})`}>
<ide> <rect
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/ClearProfilingDataButton.js
<ide> import ButtonIcon from '../ButtonIcon';
<ide> import {StoreContext} from '../context';
<ide> import {TimelineContext} from 'react-devtools-timeline/src/TimelineContext';
<ide>
<del>export default function ClearProfilingDataButton() {
<add>export default function ClearProfilingDataButton(): React.Node {
<ide> const store = useContext(StoreContext);
<ide> const {didRecordCommits, isProfiling} = useContext(ProfilerContext);
<ide> const {file, setFile} = useContext(TimelineContext);
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js
<ide> export type ItemData = {
<ide> width: number,
<ide> };
<ide>
<del>export default function CommitFlamegraphAutoSizer(_: {}) {
<add>export default function CommitFlamegraphAutoSizer(_: {}): React.Node {
<ide> const {profilerStore} = useContext(StoreContext);
<ide> const {rootID, selectedCommitIndex, selectFiber} = useContext(
<ide> ProfilerContext,
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js
<ide> export type ItemData = {
<ide> width: number,
<ide> };
<ide>
<del>export default function CommitRankedAutoSizer(_: {}) {
<add>export default function CommitRankedAutoSizer(_: {}): React.Node {
<ide> const {profilerStore} = useContext(StoreContext);
<ide> const {rootID, selectedCommitIndex, selectFiber} = useContext(
<ide> ProfilerContext,
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/HoveredFiberInfo.js
<ide> export type Props = {
<ide> fiberData: ChartNode,
<ide> };
<ide>
<del>export default function HoveredFiberInfo({fiberData}: Props) {
<add>export default function HoveredFiberInfo({fiberData}: Props): React.Node {
<ide> const {profilerStore} = useContext(StoreContext);
<ide> const {rootID, selectedCommitIndex} = useContext(ProfilerContext);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/NoCommitData.js
<ide> import * as React from 'react';
<ide>
<ide> import styles from './NoCommitData.css';
<ide>
<del>export default function NoCommitData(_: {}) {
<add>export default function NoCommitData(_: {}): React.Node {
<ide> return (
<ide> <div className={styles.NoCommitData}>
<ide> <div className={styles.Header}>
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/NoProfilingData.js
<ide> import RecordToggle from './RecordToggle';
<ide>
<ide> import styles from './Profiler.css';
<ide>
<del>export default function NoProfilingData() {
<add>export default function NoProfilingData(): React.Node {
<ide> return (
<ide> <div className={styles.Column}>
<ide> <div className={styles.Header}>No profiling data has been recorded.</div>
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/ProcessingData.js
<ide> import * as React from 'react';
<ide>
<ide> import styles from './Profiler.css';
<ide>
<del>export default function ProcessingData() {
<add>export default function ProcessingData(): React.Node {
<ide> return (
<ide> <div className={styles.Column}>
<ide> <div className={styles.Header}>Processing data...</div>
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js
<ide> type Props = {
<ide> children: React$Node,
<ide> };
<ide>
<del>function ProfilerContextController({children}: Props) {
<add>function ProfilerContextController({children}: Props): React.Node {
<ide> const store = useContext(StoreContext);
<ide> const {selectedElementID} = useContext(TreeStateContext);
<ide> const dispatch = useContext(TreeDispatcherContext);
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js
<ide> import styles from './ProfilingImportExportButtons.css';
<ide>
<ide> import type {ProfilingDataExport} from './types';
<ide>
<del>export default function ProfilingImportExportButtons() {
<add>export default function ProfilingImportExportButtons(): React.Node {
<ide> const {isProfiling, profilingData, rootID} = useContext(ProfilerContext);
<ide> const {setFile} = useContext(TimelineContext);
<ide> const store = useContext(StoreContext);
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingNotSupported.js
<ide> import * as React from 'react';
<ide>
<ide> import styles from './Profiler.css';
<ide>
<del>export default function ProfilingNotSupported() {
<add>export default function ProfilingNotSupported(): React.Node {
<ide> return (
<ide> <div className={styles.Column}>
<ide> <div className={styles.Header}>Profiling not supported.</div>
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/RecordToggle.js
<ide> export type Props = {
<ide> disabled?: boolean,
<ide> };
<ide>
<del>export default function RecordToggle({disabled}: Props) {
<add>export default function RecordToggle({disabled}: Props): React.Node {
<ide> const {isProfiling, startProfiling, stopProfiling} = useContext(
<ide> ProfilerContext,
<ide> );
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/RecordingInProgress.js
<ide> import RecordToggle from './RecordToggle';
<ide>
<ide> import styles from './Profiler.css';
<ide>
<del>export default function RecordingInProgress() {
<add>export default function RecordingInProgress(): React.Node {
<ide> return (
<ide> <div className={styles.Column}>
<ide> <div className={styles.Header}>Profiling is in progress...</div>
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/ReloadAndProfileButton.js
<ide> export default function ReloadAndProfileButton({
<ide> disabled,
<ide> }: {
<ide> disabled: boolean,
<del>}) {
<add>}): React.Node {
<ide> const bridge = useContext(BridgeContext);
<ide> const store = useContext(StoreContext);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/RootSelector.js
<ide> import {ProfilerContext} from './ProfilerContext';
<ide>
<ide> import styles from './RootSelector.css';
<ide>
<del>export default function RootSelector(_: {}) {
<add>export default function RootSelector(_: {}): React.Node {
<ide> const {profilingData, rootID, setRootID} = useContext(ProfilerContext);
<ide>
<ide> const options = [];
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/SidebarCommitInfo.js
<ide> import styles from './SidebarCommitInfo.css';
<ide>
<ide> export type Props = {};
<ide>
<del>export default function SidebarCommitInfo(_: Props) {
<add>export default function SidebarCommitInfo(_: Props): React.Node {
<ide> const {selectedCommitIndex, rootID} = useContext(ProfilerContext);
<ide>
<ide> const {profilerStore} = useContext(StoreContext);
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/SidebarEventInfo.js
<ide> function SchedulingEventInfo({eventInfo}: SchedulingEventProps) {
<ide> );
<ide> }
<ide>
<del>export default function SidebarEventInfo(_: Props) {
<add>export default function SidebarEventInfo(_: Props): React.Node {
<ide> const {selectedEvent} = useContext(TimelineContext);
<ide> // (TODO) Refactor in next PR so this supports multiple types of events
<ide> if (selectedEvent && selectedEvent.schedulingEvent) {
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/SidebarSelectedFiberInfo.js
<ide> import styles from './SidebarSelectedFiberInfo.css';
<ide>
<ide> export type Props = {};
<ide>
<del>export default function SidebarSelectedFiberInfo(_: Props) {
<add>export default function SidebarSelectedFiberInfo(_: Props): React.Node {
<ide> const {profilerStore} = useContext(StoreContext);
<ide> const {
<ide> rootID,
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitList.js
<ide> export default function SnapshotCommitList({
<ide> selectedFilteredCommitIndex,
<ide> selectCommitIndex,
<ide> totalDurations,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> return (
<ide> <AutoSizer>
<ide> {({height, width}) => (
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js
<ide> import styles from './SnapshotSelector.css';
<ide>
<ide> export type Props = {};
<ide>
<del>export default function SnapshotSelector(_: Props) {
<add>export default function SnapshotSelector(_: Props): React.Node {
<ide> const {
<ide> isCommitFilterEnabled,
<ide> minCommitDuration,
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/Tooltip.js
<ide> import styles from './Tooltip.css';
<ide>
<ide> const initialTooltipState = {height: 0, mouseX: 0, mouseY: 0, width: 0};
<ide>
<del>export default function Tooltip({children, className, label, style}: any) {
<add>export default function Tooltip({
<add> children,
<add> className,
<add> label,
<add> style,
<add>}: any): React.Node {
<ide> const containerRef = useRef(null);
<ide> const tooltipRef = useRef(null);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/Updaters.js
<ide> export type Props = {
<ide> updaters: Array<SerializedElement>,
<ide> };
<ide>
<del>export default function Updaters({commitTree, updaters}: Props) {
<add>export default function Updaters({commitTree, updaters}: Props): React.Node {
<ide> const {selectFiber} = useContext(ProfilerContext);
<ide>
<ide> const children =
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/WhatChanged.js
<ide> type Props = {
<ide> fiberID: number,
<ide> };
<ide>
<del>export default function WhatChanged({fiberID}: Props) {
<add>export default function WhatChanged({fiberID}: Props): React.Node {
<ide> const {profilerStore} = useContext(StoreContext);
<ide> const {rootID, selectedCommitIndex} = useContext(ProfilerContext);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Profiler/utils.js
<ide> export function prepareProfilingDataExport(
<ide> };
<ide> }
<ide>
<del>export const getGradientColor = (value: number) => {
<add>export const getGradientColor = (value: number): string => {
<ide> const maxIndex = commitGradient.length - 1;
<ide> let index;
<ide> if (Number.isNaN(value)) {
<ide> export const getGradientColor = (value: number) => {
<ide> return commitGradient[Math.round(index)];
<ide> };
<ide>
<del>export const formatDuration = (duration: number) =>
<add>export const formatDuration = (duration: number): number | string =>
<ide> Math.round(duration * 10) / 10 || '<0.1';
<del>export const formatPercentage = (percentage: number) =>
<add>export const formatPercentage = (percentage: number): number =>
<ide> Math.round(percentage * 100);
<del>export const formatTime = (timestamp: number) =>
<add>export const formatTime = (timestamp: number): number =>
<ide> Math.round(Math.round(timestamp) / 100) / 10;
<ide>
<ide> export const scale = (
<ide> minValue: number,
<ide> maxValue: number,
<ide> minRange: number,
<ide> maxRange: number,
<del>) => (value: number, fallbackValue: number) =>
<add>): ((value: number, fallbackValue: number) => number) => (
<add> value: number,
<add> fallbackValue: number,
<add>) =>
<ide> maxValue - minValue === 0
<ide> ? fallbackValue
<ide> : ((value - minValue) / (maxValue - minValue)) * (maxRange - minRange);
<ide><path>packages/react-devtools-shared/src/devtools/views/ReactLogo.js
<ide> type Props = {
<ide> className?: string,
<ide> };
<ide>
<del>export default function ReactLogo({className}: Props) {
<add>export default function ReactLogo({className}: Props): React.Node {
<ide> return (
<ide> <svg
<ide> xmlns="http://www.w3.org/2000/svg"
<ide><path>packages/react-devtools-shared/src/devtools/views/SearchInput.js
<ide> export default function SearchInput({
<ide> searchResultsCount,
<ide> searchText,
<ide> testName,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const inputRef = useRef<HTMLInputElement | null>(null);
<ide>
<ide> const resetSearch = () => search('');
<ide><path>packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js
<ide> import type {
<ide> RegExpComponentFilter,
<ide> } from 'react-devtools-shared/src/types';
<ide>
<del>export default function ComponentsSettings(_: {}) {
<add>export default function ComponentsSettings(_: {}): React.Node {
<ide> const store = useContext(StoreContext);
<ide> const {parseHookNames, setParseHookNames} = useContext(SettingsContext);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/Settings/DebuggingSettings.js
<ide> import {SettingsContext} from './SettingsContext';
<ide>
<ide> import styles from './SettingsShared.css';
<ide>
<del>export default function DebuggingSettings(_: {}) {
<add>export default function DebuggingSettings(_: {}): React.Node {
<ide> const {
<ide> appendComponentStack,
<ide> breakOnConsoleErrors,
<ide><path>packages/react-devtools-shared/src/devtools/views/Settings/GeneralSettings.js
<ide> function getChangeLogUrl(version: ?string): string | null {
<ide> return `${CHANGE_LOG_URL}#${versionAnchor}`;
<ide> }
<ide>
<del>export default function GeneralSettings(_: {}) {
<add>export default function GeneralSettings(_: {}): React.Node {
<ide> const {
<ide> displayDensity,
<ide> setDisplayDensity,
<ide><path>packages/react-devtools-shared/src/devtools/views/Settings/ProfilerSettings.js
<ide> import {ProfilerContext} from 'react-devtools-shared/src/devtools/views/Profiler
<ide>
<ide> import styles from './SettingsShared.css';
<ide>
<del>export default function ProfilerSettings(_: {}) {
<add>export default function ProfilerSettings(_: {}): React.Node {
<ide> const {
<ide> isCommitFilterEnabled,
<ide> minCommitDuration,
<ide><path>packages/react-devtools-shared/src/devtools/views/Settings/SettingsModal.js
<ide> import styles from './SettingsModal.css';
<ide>
<ide> type TabID = 'general' | 'components' | 'profiler';
<ide>
<del>export default function SettingsModal(_: {}) {
<add>export default function SettingsModal(_: {}): React.Node {
<ide> const {isModalShowing, setIsModalShowing} = useContext(SettingsModalContext);
<ide> const store = useContext(StoreContext);
<ide> const {profilerStore} = store;
<ide><path>packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContextToggle.js
<ide> import ButtonIcon from '../ButtonIcon';
<ide> import {StoreContext} from '../context';
<ide> import {useSubscription} from '../hooks';
<ide>
<del>export default function SettingsModalContextToggle() {
<add>export default function SettingsModalContextToggle(): React.Node {
<ide> const {setIsModalShowing} = useContext(SettingsModalContext);
<ide> const store = useContext(StoreContext);
<ide> const {profilerStore} = store;
<ide><path>packages/react-devtools-shared/src/devtools/views/TabBar.js
<ide> export default function TabBar({
<ide> selectTab,
<ide> tabs,
<ide> type,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> if (!tabs.some(tab => tab !== null && tab.id === currentTab)) {
<ide> const firstTab = ((tabs.find(tab => tab !== null): any): TabInfo);
<ide> selectTab(firstTab.id);
<ide><path>packages/react-devtools-shared/src/devtools/views/ThemeProvider.js
<ide> import * as React from 'react';
<ide> import useThemeStyles from './useThemeStyles';
<ide>
<del>export default function ThemeProvider({children}: {children: React$Node}) {
<add>export default function ThemeProvider({
<add> children,
<add>}: {
<add> children: React.Node,
<add>}): React.Node {
<ide> const themeStyle = useThemeStyles();
<ide>
<ide> const style = React.useMemo(() => {
<ide><path>packages/react-devtools-shared/src/devtools/views/Toggle.js
<ide> export default function Toggle({
<ide> onChange,
<ide> testName,
<ide> title,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> let defaultClassName;
<ide> if (isDisabled) {
<ide> defaultClassName = styles.ToggleDisabled;
<ide><path>packages/react-devtools-shared/src/devtools/views/WarnIfLegacyBackendDetected.js
<ide> import {ModalDialogContext} from './ModalDialog';
<ide>
<ide> import styles from './WarnIfLegacyBackendDetected.css';
<ide>
<del>export default function WarnIfLegacyBackendDetected(_: {}) {
<add>export default function WarnIfLegacyBackendDetected(_: {}): null {
<ide> const bridge = useContext(BridgeContext);
<ide> const {dispatch} = useContext(ModalDialogContext);
<ide>
<ide><path>packages/react-devtools-shared/src/devtools/views/hooks.js
<ide> export function useSubscription<Value>({
<ide> return state.value;
<ide> }
<ide>
<del>export function useHighlightNativeElement() {
<add>export function useHighlightNativeElement(): {
<add> clearHighlightNativeElement: () => void,
<add> highlightNativeElement: (id: number) => void,
<add>} {
<ide> const bridge = useContext(BridgeContext);
<ide> const store = useContext(StoreContext);
<ide>
<ide><path>packages/react-devtools-shared/src/hydration.js
<ide> import {
<ide> import type {DehydratedData} from 'react-devtools-shared/src/devtools/views/Components/types';
<ide>
<ide> export const meta = {
<del> inspectable: Symbol('inspectable'),
<del> inspected: Symbol('inspected'),
<del> name: Symbol('name'),
<del> preview_long: Symbol('preview_long'),
<del> preview_short: Symbol('preview_short'),
<del> readonly: Symbol('readonly'),
<del> size: Symbol('size'),
<del> type: Symbol('type'),
<del> unserializable: Symbol('unserializable'),
<add> inspectable: (Symbol('inspectable'): symbol),
<add> inspected: (Symbol('inspected'): symbol),
<add> name: (Symbol('name'): symbol),
<add> preview_long: (Symbol('preview_long'): symbol),
<add> preview_short: (Symbol('preview_short'): symbol),
<add> readonly: (Symbol('readonly'): symbol),
<add> size: (Symbol('size'): symbol),
<add> type: (Symbol('type'): symbol),
<add> unserializable: (Symbol('unserializable'): symbol),
<ide> };
<ide>
<ide> export type Dehydrated = {
<ide><path>packages/react-devtools-shell/src/app/DeeplyNestedComponents/index.js
<ide> function Nested() {
<ide>
<ide> const DeeplyNested = wrapWithNested(Nested, 100);
<ide>
<del>export default function DeeplyNestedComponents() {
<add>export default function DeeplyNestedComponents(): React.Node {
<ide> return (
<ide> <Fragment>
<ide> <h1>Deeply nested component</h1>
<ide><path>packages/react-devtools-shell/src/app/EditableProps/index.js
<ide> const ForwardRef = forwardRef<{name: string}, HTMLUListElement>(
<ide> },
<ide> );
<ide>
<del>export default function EditableProps() {
<add>export default function EditableProps(): React.Node {
<ide> return (
<ide> <Fragment>
<ide> <h1>Editable props</h1>
<ide><path>packages/react-devtools-shell/src/app/ElementTypes/index.js
<ide> const LazyComponent = lazy(() =>
<ide> }),
<ide> );
<ide>
<del>export default function ElementTypes() {
<add>export default function ElementTypes(): React.Node {
<ide> return (
<ide> <Profiler id="test" onRender={() => {}}>
<ide> <Fragment>
<ide><path>packages/react-devtools-shell/src/app/ErrorBoundaries/index.js
<ide> function Component({label}) {
<ide> return <div>{label}</div>;
<ide> }
<ide>
<del>export default function ErrorBoundaries() {
<add>export default function ErrorBoundaries(): React.Node {
<ide> return (
<ide> <Fragment>
<ide> <h1>Nested error boundaries demo</h1>
<ide><path>packages/react-devtools-shell/src/app/Hydration/index.js
<ide> function useInnerBaz() {
<ide> return count;
<ide> }
<ide>
<del>export default function Hydration() {
<add>export default function Hydration(): React.Node {
<ide> return (
<ide> <Fragment>
<ide> <h1>Hydration</h1>
<ide><path>packages/react-devtools-shell/src/app/Iframe/index.js
<ide> import * as React from 'react';
<ide> import {Fragment} from 'react';
<ide> import {createPortal} from 'react-dom';
<ide>
<del>export default function Iframe() {
<add>export default function Iframe(): React.Node {
<ide> return (
<ide> <Fragment>
<ide> <h2>Iframe</h2>
<ide><path>packages/react-devtools-shell/src/app/InlineWarnings/index.js
<ide> function ComponentWithSymbolWarning() {
<ide> return null;
<ide> }
<ide>
<del>export default function ErrorsAndWarnings() {
<add>export default function ErrorsAndWarnings(): React.Node {
<ide> const [count, setCount] = useState(0);
<ide> const handleClick = () => setCount(count + 1);
<ide> return (
<ide><path>packages/react-devtools-shell/src/app/InspectableElements/CircularReferences.js
<ide> const objectOne = {};
<ide> const objectTwo = {objectOne};
<ide> objectOne.objectTwo = objectTwo;
<ide>
<del>export default function CircularReferences() {
<add>export default function CircularReferences(): React.Node {
<ide> return <ChildComponent arrayOne={arrayOne} objectOne={objectOne} />;
<ide> }
<ide>
<ide><path>packages/react-devtools-shell/src/app/InspectableElements/Contexts.js
<ide> class ModernClassContextConsumerWithUpdates extends Component<any> {
<ide> }
<ide> }
<ide>
<del>export default function Contexts() {
<add>export default function Contexts(): React.Node {
<ide> return (
<ide> <div>
<ide> <h1>Contexts</h1>
<ide><path>packages/react-devtools-shell/src/app/InspectableElements/CustomHooks.js
<ide> function wrapWithHoc(Component) {
<ide> }
<ide> const HocWithHooks = wrapWithHoc(FunctionWithHooks);
<ide>
<del>export default function CustomHooks() {
<add>export default function CustomHooks(): React.Node {
<ide> return (
<ide> <Fragment>
<ide> <FunctionWithHooks />
<ide><path>packages/react-devtools-shell/src/app/InspectableElements/CustomObject.js
<ide> class Custom {
<ide> }
<ide> }
<ide>
<del>export default function CustomObject() {
<add>export default function CustomObject(): React.Node {
<ide> return <ChildComponent customObject={new Custom()} />;
<ide> }
<ide>
<ide><path>packages/react-devtools-shell/src/app/InspectableElements/EdgeCaseObjects.js
<ide> const objectWithNullProto = Object.create(null);
<ide> objectWithNullProto.foo = 'abc';
<ide> objectWithNullProto.bar = 123;
<ide>
<del>export default function EdgeCaseObjects() {
<add>export default function EdgeCaseObjects(): React.Node {
<ide> return (
<ide> <ChildComponent
<ide> objectWithModifiedHasOwnProperty={objectWithModifiedHasOwnProperty}
<ide><path>packages/react-devtools-shell/src/app/InspectableElements/InspectableElements.js
<ide> import SymbolKeys from './SymbolKeys';
<ide>
<ide> // TODO Add Immutable JS example
<ide>
<del>export default function InspectableElements() {
<add>export default function InspectableElements(): React.Node {
<ide> return (
<ide> <Fragment>
<ide> <h1>Inspectable elements</h1>
<ide><path>packages/react-devtools-shell/src/app/InspectableElements/NestedProps.js
<ide> const object = {
<ide> null: null,
<ide> };
<ide>
<del>export default function ObjectProps() {
<add>export default function ObjectProps(): React.Node {
<ide> return (
<ide> <ChildComponent
<ide> object={{
<ide><path>packages/react-devtools-shell/src/app/InspectableElements/SymbolKeys.js
<ide> const data = Object.create(base, {
<ide> },
<ide> });
<ide>
<del>export default function SymbolKeys() {
<add>export default function SymbolKeys(): React.Node {
<ide> return <ChildComponent data={data} />;
<ide> }
<ide>
<ide><path>packages/react-devtools-shell/src/app/InspectableElements/UnserializableProps.js
<ide> const immutable = Immutable.fromJS({
<ide> // $FlowFixMe
<ide> const bigInt = BigInt(123); // eslint-disable-line no-undef
<ide>
<del>export default function UnserializableProps() {
<add>export default function UnserializableProps(): React.Node {
<ide> return (
<ide> <ChildComponent
<ide> arrayBuffer={arrayBuffer}
<ide><path>packages/react-devtools-shell/src/app/PartiallyStrictApp/index.js
<ide> import * as React from 'react';
<ide> import {StrictMode} from 'react';
<ide>
<del>export default function PartiallyStrictApp() {
<add>export default function PartiallyStrictApp(): React.Node {
<ide> return (
<ide> <>
<ide> <Child />
<ide><path>packages/react-devtools-shell/src/app/ReactNativeWeb/index.js
<ide> import {Fragment, useState} from 'react';
<ide> // $FlowFixMe
<ide> import {Button, Text, View} from 'react-native-web';
<ide>
<del>export default function ReactNativeWeb() {
<add>export default function ReactNativeWeb(): React.Node {
<ide> const [backgroundColor, setBackgroundColor] = useState('purple');
<ide> const toggleColor = () =>
<ide> setBackgroundColor(backgroundColor === 'purple' ? 'green' : 'purple');
<ide><path>packages/react-devtools-shell/src/app/SuspenseTree/index.js
<ide> import * as React from 'react';
<ide> import {Fragment, Suspense, SuspenseList, useState} from 'react';
<ide>
<del>function SuspenseTree() {
<add>function SuspenseTree(): React.Node {
<ide> return (
<ide> <Fragment>
<ide> <h1>Suspense</h1>
<ide><path>packages/react-devtools-shell/src/app/ToDoList/List.js
<ide> export type Item = {
<ide>
<ide> type Props = {};
<ide>
<del>export default function List(props: Props) {
<add>export default function List(props: Props): React.Node {
<ide> const [newItemText, setNewItemText] = useState<string>('');
<ide> const [items, setItems] = useState<Array<Item>>([
<ide> {id: 1, isComplete: true, text: 'First'},
<ide><path>packages/react-devtools-shell/src/e2e-apps/ListApp.js
<ide> import * as React from 'react';
<ide> import {useRef, useState} from 'react';
<ide>
<del>export default function App() {
<add>export default function App(): React.Node {
<ide> return <List />;
<ide> }
<ide>
<ide><path>packages/react-devtools-shell/src/e2e-apps/ListAppLegacy.js
<ide>
<ide> import * as React from 'react';
<ide>
<del>export default function App() {
<add>export default function App(): React.Node {
<ide> return <List />;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/CanvasPage.js
<ide> type Props = {
<ide> viewState: ViewState,
<ide> };
<ide>
<del>function CanvasPage({profilerData, viewState}: Props) {
<add>function CanvasPage({profilerData, viewState}: Props): React.Node {
<ide> return (
<ide> <div
<ide> className={styles.CanvasPage}
<ide><path>packages/react-devtools-timeline/src/EventTooltip.js
<ide> export default function EventTooltip({
<ide> hoveredEvent,
<ide> origin,
<ide> width,
<del>}: Props) {
<add>}: Props): React.Node {
<ide> const ref = useSmartTooltip({
<ide> canvasRef,
<ide> mouseX: origin.x,
<ide><path>packages/react-devtools-timeline/src/Timeline.js
<ide> import {TimelineSearchContextController} from './TimelineSearchContext';
<ide>
<ide> import styles from './Timeline.css';
<ide>
<del>export function Timeline(_: {}) {
<add>export function Timeline(_: {}): React.Node {
<ide> const {
<ide> file,
<ide> inMemoryTimelineData,
<ide><path>packages/react-devtools-timeline/src/TimelineNotSupported.js
<ide> import {isInternalFacebookBuild} from 'react-devtools-feature-flags';
<ide>
<ide> import styles from './TimelineNotSupported.css';
<ide>
<del>export default function TimelineNotSupported() {
<add>export default function TimelineNotSupported(): React.Node {
<ide> return (
<ide> <div className={styles.Column}>
<ide> <div className={styles.Header}>Timeline profiling not supported.</div>
<ide><path>packages/react-devtools-timeline/src/TimelineSearchInput.js
<ide> import {TimelineSearchContext} from './TimelineSearchContext';
<ide>
<ide> type Props = {};
<ide>
<del>export default function TimelineSearchInput(props: Props) {
<add>export default function TimelineSearchInput(props: Props): React.Node {
<ide> const {searchInputContainerRef} = useContext(TimelineContext);
<ide> const {dispatch, searchIndex, searchResults, searchText} = useContext(
<ide> TimelineSearchContext,
<ide><path>packages/react-devtools-timeline/src/content-views/ComponentMeasuresView.js
<ide> export class ComponentMeasuresView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): IntrinsicSize {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/FlamechartView.js
<ide> class FlamechartStackLayerView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): Size {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide> export class FlamechartView extends View {
<ide> this._flamechartRowViews.forEach(rowView => (rowView._onHover = onHover));
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): {
<add> height: number,
<add> hideScrollBarIfLessThanHeight?: number,
<add> maxInitialHeight?: number,
<add> width: number,
<add> } {
<ide> // Ignore the wishes of the background color view
<ide> const intrinsicSize = this._verticalStackView.desiredSize();
<ide> return {
<ide><path>packages/react-devtools-timeline/src/content-views/NativeEventsView.js
<ide> export class NativeEventsView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): IntrinsicSize {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/NetworkMeasuresView.js
<ide> export class NetworkMeasuresView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): IntrinsicSize {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/ReactMeasuresView.js
<ide> export class ReactMeasuresView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): IntrinsicSize {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/SchedulingEventsView.js
<ide> export class SchedulingEventsView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): Size {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/SnapshotsView.js
<ide> export class SnapshotsView extends View {
<ide> this._profilerData = profilerData;
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): Size {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/SuspenseEventsView.js
<ide> export class SuspenseEventsView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): IntrinsicSize {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/ThrownErrorsView.js
<ide> export class ThrownErrorsView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): Size {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/TimeAxisMarkersView.js
<ide> export class TimeAxisMarkersView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): Size {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/UserTimingMarksView.js
<ide> export class UserTimingMarksView extends View {
<ide> };
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): Size {
<ide> return this._intrinsicSize;
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/content-views/constants.js
<ide> export const INTERVAL_TIMES = [
<ide> export const MIN_INTERVAL_SIZE_PX = 70;
<ide>
<ide> // TODO Replace this with "export let" vars
<del>export let COLORS = {
<add>export let COLORS: {
<add> BACKGROUND: string,
<add> INTERNAL_MODULE_FRAME: string,
<add> INTERNAL_MODULE_FRAME_HOVER: string,
<add> INTERNAL_MODULE_FRAME_TEXT: string,
<add> NATIVE_EVENT: string,
<add> NATIVE_EVENT_HOVER: string,
<add> NETWORK_PRIMARY: string,
<add> NETWORK_PRIMARY_HOVER: string,
<add> NETWORK_SECONDARY: string,
<add> NETWORK_SECONDARY_HOVER: string,
<add> PRIORITY_BACKGROUND: string,
<add> PRIORITY_BORDER: string,
<add> PRIORITY_LABEL: string,
<add> REACT_COMMIT: string,
<add> REACT_COMMIT_HOVER: string,
<add> REACT_COMMIT_TEXT: string,
<add> REACT_IDLE: string,
<add> REACT_IDLE_HOVER: string,
<add> REACT_LAYOUT_EFFECTS: string,
<add> REACT_LAYOUT_EFFECTS_HOVER: string,
<add> REACT_LAYOUT_EFFECTS_TEXT: string,
<add> REACT_PASSIVE_EFFECTS: string,
<add> REACT_PASSIVE_EFFECTS_HOVER: string,
<add> REACT_PASSIVE_EFFECTS_TEXT: string,
<add> REACT_RENDER: string,
<add> REACT_RENDER_HOVER: string,
<add> REACT_RENDER_TEXT: string,
<add> REACT_RESIZE_BAR: string,
<add> REACT_RESIZE_BAR_ACTIVE: string,
<add> REACT_RESIZE_BAR_BORDER: string,
<add> REACT_RESIZE_BAR_DOT: string,
<add> REACT_SCHEDULE: string,
<add> REACT_SCHEDULE_HOVER: string,
<add> REACT_SUSPENSE_REJECTED_EVENT: string,
<add> REACT_SUSPENSE_REJECTED_EVENT_HOVER: string,
<add> REACT_SUSPENSE_RESOLVED_EVENT: string,
<add> REACT_SUSPENSE_RESOLVED_EVENT_HOVER: string,
<add> REACT_SUSPENSE_UNRESOLVED_EVENT: string,
<add> REACT_SUSPENSE_UNRESOLVED_EVENT_HOVER: string,
<add> REACT_THROWN_ERROR: string,
<add> REACT_THROWN_ERROR_HOVER: string,
<add> REACT_WORK_BORDER: string,
<add> SCROLL_CARET: string,
<add> SCRUBBER_BACKGROUND: string,
<add> SCRUBBER_BORDER: string,
<add> SEARCH_RESULT_FILL: string,
<add> TEXT_COLOR: string,
<add> TEXT_DIM_COLOR: string,
<add> TIME_MARKER_LABEL: string,
<add> USER_TIMING: string,
<add> USER_TIMING_HOVER: string,
<add> WARNING_BACKGROUND: string,
<add> WARNING_BACKGROUND_HOVER: string,
<add> WARNING_TEXT: string,
<add> WARNING_TEXT_INVERED: string,
<add>} = {
<ide> BACKGROUND: '',
<ide> INTERNAL_MODULE_FRAME: '',
<ide> INTERNAL_MODULE_FRAME_HOVER: '',
<ide><path>packages/react-devtools-timeline/src/utils/formatting.js
<ide> import type {SchedulingEvent} from '../types';
<ide>
<ide> import prettyMilliseconds from 'pretty-ms';
<ide>
<del>export function formatTimestamp(ms: number) {
<add>export function formatTimestamp(ms: number): string {
<ide> return (
<ide> ms.toLocaleString(undefined, {
<ide> minimumFractionDigits: 1,
<ide><path>packages/react-devtools-timeline/src/utils/getBatchRange.js
<ide> function unmemoizedGetBatchRange(
<ide> return [startTime, stopTime];
<ide> }
<ide>
<del>export const getBatchRange = memoize(unmemoizedGetBatchRange);
<add>export const getBatchRange: (
<add> batchUID: BatchUID,
<add> data: TimelineData,
<add> minStartTime?: number,
<add>) => [Milliseconds, Milliseconds] = memoize(unmemoizedGetBatchRange);
<ide><path>packages/react-devtools-timeline/src/utils/useSmartTooltip.js
<ide> export default function useSmartTooltip({
<ide> canvasRef: {current: HTMLCanvasElement | null},
<ide> mouseX: number,
<ide> mouseY: number,
<del>}) {
<add>}): {current: HTMLElement | null} {
<ide> const ref = useRef<HTMLElement | null>(null);
<ide>
<ide> // HACK: Browser extension reports window.innerHeight of 0,
<ide><path>packages/react-devtools-timeline/src/view-base/HorizontalPanAndZoomView.js
<ide> * @flow
<ide> */
<ide>
<add>import type {Size, IntrinsicSize} from './geometry';
<ide> import type {
<ide> Interaction,
<ide> MouseDownInteraction,
<ide> import {
<ide> export class HorizontalPanAndZoomView extends View {
<ide> _contentView: View;
<ide> _intrinsicContentWidth: number;
<del> _isPanning = false;
<add> _isPanning: boolean = false;
<ide> _viewState: ViewState;
<ide>
<ide> constructor(
<ide> export class HorizontalPanAndZoomView extends View {
<ide> this.setScrollState(newState);
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): Size | IntrinsicSize {
<ide> return this._contentView.desiredSize();
<ide> }
<ide>
<ide><path>packages/react-devtools-timeline/src/view-base/resizable/ResizableView.js
<ide> export class ResizableView extends View {
<ide> this._restoreMutableViewState();
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): {+height: number, +width: number} {
<ide> const subviewDesiredSize = this._subview.desiredSize();
<ide>
<ide> if (this._shouldRenderResizeBar()) {
<ide> export class ResizableView extends View {
<ide> this.setNeedsDisplay();
<ide> }
<ide>
<del> _shouldRenderResizeBar() {
<add> _shouldRenderResizeBar(): boolean {
<ide> const subviewDesiredSize = this._subview.desiredSize();
<ide> return subviewDesiredSize.hideScrollBarIfLessThanHeight != null
<ide> ? subviewDesiredSize.height >
<ide> export class ResizableView extends View {
<ide> });
<ide> }
<ide>
<del> _handleClick(interaction: ClickInteraction) {
<add> _handleClick(interaction: ClickInteraction): void | boolean {
<ide> if (!this._shouldRenderResizeBar()) {
<ide> return;
<ide> }
<ide> export class ResizableView extends View {
<ide> }
<ide> }
<ide>
<del> _handleDoubleClick(interaction: DoubleClickInteraction) {
<add> _handleDoubleClick(interaction: DoubleClickInteraction): void | boolean {
<ide> if (!this._shouldRenderResizeBar()) {
<ide> return;
<ide> }
<ide> export class ResizableView extends View {
<ide> }
<ide> }
<ide>
<del> _handleMouseDown(interaction: MouseDownInteraction) {
<add> _handleMouseDown(interaction: MouseDownInteraction): void | boolean {
<ide> const cursorLocation = interaction.payload.location;
<ide> const resizeBarFrame = this._resizeBar.frame;
<ide> if (rectContainsPoint(cursorLocation, resizeBarFrame)) {
<ide> export class ResizableView extends View {
<ide> }
<ide> }
<ide>
<del> _handleMouseMove(interaction: MouseMoveInteraction) {
<add> _handleMouseMove(interaction: MouseMoveInteraction): void | boolean {
<ide> const {_resizingState} = this;
<ide> if (_resizingState) {
<ide> this._resizingState = {
<ide> export class ResizableView extends View {
<ide> }
<ide> }
<ide>
<del> handleInteraction(interaction: Interaction, viewRefs: ViewRefs) {
<add> handleInteraction(
<add> interaction: Interaction,
<add> viewRefs: ViewRefs,
<add> ): void | boolean {
<ide> switch (interaction.type) {
<ide> case 'click':
<ide> return this._handleClick(interaction);
<ide><path>packages/react-devtools-timeline/src/view-base/vertical-scroll-overflow/VerticalScrollBarView.js
<ide> export class VerticalScrollBarView extends View {
<ide> this._verticalScrollOverflowView = verticalScrollOverflowView;
<ide> }
<ide>
<del> desiredSize() {
<add> desiredSize(): {+height: number, +width: number} {
<ide> return {
<ide> width: SCROLL_BAR_SIZE,
<ide> height: 0, // No desired height
<ide><path>packages/react-devtools-timeline/src/view-base/vertical-scroll-overflow/VerticalScrollOverflowView.js
<ide> export class VerticalScrollOverflowView extends View {
<ide> this.setNeedsDisplay();
<ide> }
<ide>
<del> _onVerticalScrollViewChange = (
<add> _onVerticalScrollViewChange: (
<ide> scrollState: ScrollState,
<ide> containerLength: number,
<del> ) => {
<add> ) => void = (scrollState: ScrollState, containerLength: number) => {
<ide> const maxOffset = scrollState.length - containerLength;
<ide> if (maxOffset === 0) {
<ide> return; | 133 |
Javascript | Javascript | exclude watch test cases | 4b7263525e0366b99194e2a71595f7abce07864f | <ide><path>test/RemoveFiles.test.js
<ide> const createSingleCompiler = () => {
<ide> };
<ide>
<ide> describe("RemovedFiles", () => {
<add> if (process.env.NO_WATCH_TESTS) {
<add> it.skip("watch tests excluded", () => {});
<add> return;
<add> }
<add>
<ide> jest.setTimeout(20000);
<ide>
<ide> function cleanup() { | 1 |
PHP | PHP | add more detail to pagination exception message | 46a15cf857cc29cb27075783f1ff29b568be5ba4 | <ide><path>system/db/eloquent.php
<ide> private function _paginate($per_page = null)
<ide> {
<ide> if ( ! property_exists(get_class($this), 'per_page'))
<ide> {
<del> throw new \Exception("The number of models to display per page has not been specified.");
<add> throw new \Exception("The number of models to display per page for model [".get_class($this)."] has not been specified.");
<ide> }
<ide>
<ide> $per_page = static::$per_page; | 1 |
Ruby | Ruby | allow multi-digit minor versions | 84de3c1eb6c5f69ac08a8a4ef81060e037cc0e5c | <ide><path>Library/Homebrew/language/python.rb
<ide> module Language
<ide> # @api public
<ide> module Python
<ide> def self.major_minor_version(python)
<del> version = /\d\.\d/.match `#{python} --version 2>&1`
<add> version = /\d\.\d+/.match `#{python} --version 2>&1`
<ide> return unless version
<ide>
<ide> Version.create(version.to_s) | 1 |
PHP | PHP | add filtering of the route list by domain | 11251f24318ed806f07323faf747d7e318922723 | <ide><path>src/Illuminate/Foundation/Console/RouteListCommand.php
<ide> protected function getMiddleware($route)
<ide> */
<ide> protected function filterRoute(array $route)
<ide> {
<del> if (($this->option('name') && ! str_contains($route['name'], $this->option('name'))) ||
<del> $this->option('path') && ! str_contains($route['uri'], $this->option('path')) ||
<del> $this->option('method') && ! str_contains($route['method'], strtoupper($this->option('method')))) {
<add> if (($this->option('name') && ! Str::contains($route['name'], $this->option('name'))) ||
<add> ($this->option('path') && ! Str::contains($route['uri'], $this->option('path'))) ||
<add> ($this->option('method') && ! Str::contains($route['method'], strtoupper($this->option('method')))) ||
<add> ($this->option('domain') && ! Str::contains($route['domain'], $this->option('domain')))) {
<ide> return;
<ide> }
<ide>
<ide> protected function getOptions()
<ide> ['json', null, InputOption::VALUE_NONE, 'Output the route list as JSON'],
<ide> ['method', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by method'],
<ide> ['name', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by name'],
<add> ['domain', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by domain'],
<ide> ['path', null, InputOption::VALUE_OPTIONAL, 'Only show routes matching the given path pattern'],
<ide> ['except-path', null, InputOption::VALUE_OPTIONAL, 'Do not display the routes matching the given path pattern'],
<ide> ['reverse', 'r', InputOption::VALUE_NONE, 'Reverse the ordering of the routes'], | 1 |
Go | Go | check the length of the correct variable | 8d73c1ad688b8212bb424e536c4622162ba29387 | <ide><path>daemon/logger/loginfo.go
<ide> func (info *Info) ExtraAttributes(keyMod func(string) string) (map[string]string
<ide> }
<ide>
<ide> labelsRegex, ok := info.Config["labels-regex"]
<del> if ok && len(labels) > 0 {
<add> if ok && len(labelsRegex) > 0 {
<ide> re, err := regexp.Compile(labelsRegex)
<ide> if err != nil {
<ide> return nil, err | 1 |
PHP | PHP | remove message assertions | da3b7081206266e7baa071676b50b354a374029e | <ide><path>tests/Integration/Support/ManagerTest.php
<ide> class ManagerTest extends TestCase
<ide> {
<ide> /**
<ide> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Unable to resolve NULL driver for Illuminate\Tests\Integration\Support\Fixtures\NullableManager
<ide> */
<ide> public function testDefaultDriverCannotBeNull()
<ide> { | 1 |
Javascript | Javascript | improve progress reporting | 586d5abc2c017f303ac70a96fd698167b4a8bdc4 | <ide><path>lib/SourceMapDevToolPlugin.js
<ide> class SourceMapDevToolPlugin {
<ide> }
<ide>
<ide> reportProgress(
<del> (0.5 * fileIndex++) / files.length,
<add> (0.5 * ++fileIndex) / files.length,
<ide> file,
<del> "generate SourceMap"
<add> "restored cached SourceMap"
<ide> );
<ide>
<ide> return callback();
<ide> }
<ide>
<add> reportProgress(
<add> (0.5 * fileIndex) / files.length,
<add> file,
<add> "generate SourceMap"
<add> );
<add>
<ide> /** @type {SourceMapTask | undefined} */
<ide> const task = getTaskForFile(
<ide> file,
<ide> class SourceMapDevToolPlugin {
<ide> }
<ide>
<ide> reportProgress(
<del> (0.5 * fileIndex++) / files.length,
<add> (0.5 * ++fileIndex) / files.length,
<ide> file,
<del> "generate SourceMap"
<add> "generated SourceMap"
<ide> );
<ide>
<ide> callback();
<ide> class SourceMapDevToolPlugin {
<ide> const sourceMap = task.sourceMap;
<ide> const source = task.source;
<ide> const modules = task.modules;
<add>
<add> reportProgress(
<add> 0.5 + (0.5 * taskIndex) / tasks.length,
<add> file,
<add> "attach SourceMap"
<add> );
<add>
<ide> const moduleFilenames = modules.map(m =>
<ide> moduleToSourceNameMapping.get(m)
<ide> );
<ide> class SourceMapDevToolPlugin {
<ide> assets,
<ide> err => {
<ide> reportProgress(
<del> 0.5 + (0.5 * taskIndex++) / tasks.length,
<add> 0.5 + (0.5 * ++taskIndex) / tasks.length,
<ide> task.file,
<del> "attach SourceMap"
<add> "attached SourceMap"
<ide> );
<ide>
<ide> if (err) { | 1 |
Java | Java | switch some observable ops to direct, map fuseable | 05e160c7cfd2212a0b9a985c5294c7de5c844d90 | <ide><path>src/main/java/io/reactivex/Observable.java
<ide> public static <T, R> Observable<R> zipIterable(Function<? super Object[], ? exte
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Observable<Boolean> all(Predicate<? super T> predicate) {
<ide> Objects.requireNonNull(predicate, "predicate is null");
<del> return lift(new NbpOperatorAll<T>(predicate));
<add> return (new ObservableAll<T>(this, predicate));
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> public final Observable<T> ambWith(ObservableConsumable<? extends T> other) {
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Observable<Boolean> any(Predicate<? super T> predicate) {
<ide> Objects.requireNonNull(predicate, "predicate is null");
<del> return lift(new NbpOperatorAny<T>(predicate));
<add> return new ObservableAny<T>(this, predicate);
<ide> }
<ide>
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final <U extends Collection<? super T>> Observable<U> buffer(int count, i
<ide> throw new IllegalArgumentException("skip > 0 required but it was " + count);
<ide> }
<ide> Objects.requireNonNull(bufferSupplier, "bufferSupplier is null");
<del> return lift(new NbpOperatorBuffer<T, U>(count, skip, bufferSupplier));
<add> return new ObservableBuffer<T, U>(this, count, skip, bufferSupplier);
<ide> }
<ide>
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final <U extends Collection<? super T>> Observable<U> buffer(long timespa
<ide> Objects.requireNonNull(unit, "unit is null");
<ide> Objects.requireNonNull(scheduler, "scheduler is null");
<ide> Objects.requireNonNull(bufferSupplier, "bufferSupplier is null");
<del> return lift(new NbpOperatorBufferTimed<T, U>(timespan, timeskip, unit, scheduler, bufferSupplier, Integer.MAX_VALUE, false));
<add> return new ObservableBufferTimed<T, U>(this, timespan, timeskip, unit, scheduler, bufferSupplier, Integer.MAX_VALUE, false);
<ide> }
<ide>
<ide> @SchedulerSupport(SchedulerSupport.COMPUTATION)
<ide> public final <U extends Collection<? super T>> Observable<U> buffer(
<ide> if (count <= 0) {
<ide> throw new IllegalArgumentException("count > 0 required but it was " + count);
<ide> }
<del> return lift(new NbpOperatorBufferTimed<T, U>(timespan, timespan, unit, scheduler, bufferSupplier, count, restartTimerOnMaxSize));
<add> return new ObservableBufferTimed<T, U>(this, timespan, timespan, unit, scheduler, bufferSupplier, count, restartTimerOnMaxSize);
<ide> }
<ide>
<ide> @SchedulerSupport(SchedulerSupport.CUSTOM)
<ide> public final <TOpening, TClosing, U extends Collection<? super T>> Observable<U>
<ide> Objects.requireNonNull(bufferOpenings, "bufferOpenings is null");
<ide> Objects.requireNonNull(bufferClosingSelector, "bufferClosingSelector is null");
<ide> Objects.requireNonNull(bufferSupplier, "bufferSupplier is null");
<del> return lift(new NbpOperatorBufferBoundary<T, U, TOpening, TClosing>(bufferOpenings, bufferClosingSelector, bufferSupplier));
<add> return new ObservableBufferBoundary<T, U, TOpening, TClosing>(this, bufferOpenings, bufferClosingSelector, bufferSupplier);
<ide> }
<ide>
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public List<T> get() {
<ide> public final <B, U extends Collection<? super T>> Observable<U> buffer(ObservableConsumable<B> boundary, Supplier<U> bufferSupplier) {
<ide> Objects.requireNonNull(boundary, "boundary is null");
<ide> Objects.requireNonNull(bufferSupplier, "bufferSupplier is null");
<del> return lift(new NbpOperatorBufferExactBoundary<T, U, B>(boundary, bufferSupplier));
<add> return new ObservableBufferExactBoundary<T, U, B>(this, boundary, bufferSupplier);
<ide> }
<ide>
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public List<T> get() {
<ide> public final <B, U extends Collection<? super T>> Observable<U> buffer(Supplier<? extends ObservableConsumable<B>> boundarySupplier, Supplier<U> bufferSupplier) {
<ide> Objects.requireNonNull(boundarySupplier, "boundarySupplier is null");
<ide> Objects.requireNonNull(bufferSupplier, "bufferSupplier is null");
<del> return lift(new NbpOperatorBufferBoundarySupplier<T, U, B>(boundarySupplier, bufferSupplier));
<add> return new ObservableBufferBoundarySupplier<T, U, B>(this, boundarySupplier, bufferSupplier);
<ide> }
<ide>
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide><path>src/main/java/io/reactivex/disposables/CompositeDisposable.java
<ide> public boolean isDisposed() {
<ide> return disposed;
<ide> }
<ide>
<del> public void add(Disposable d) {
<add> public boolean add(Disposable d) {
<ide> Objects.requireNonNull(d, "d is null");
<ide> if (!disposed) {
<ide> synchronized (this) {
<ide> public void add(Disposable d) {
<ide> resources = set;
<ide> }
<ide> set.add(d);
<del> return;
<add> return true;
<ide> }
<ide> }
<ide> }
<ide> d.dispose();
<add> return false;
<ide> }
<ide>
<del> public void addAll(Disposable... ds) {
<add> public boolean addAll(Disposable... ds) {
<ide> Objects.requireNonNull(ds, "ds is null");
<ide> if (!disposed) {
<ide> synchronized (this) {
<ide> public void addAll(Disposable... ds) {
<ide> Objects.requireNonNull(d, "d is null");
<ide> set.add(d);
<ide> }
<del> return;
<add> return true;
<ide> }
<ide> }
<ide> }
<ide> for (Disposable d : ds) {
<ide> d.dispose();
<ide> }
<add> return false;
<ide> }
<ide>
<del> public void remove(Disposable d) {
<del> Objects.requireNonNull(d, "Disposable item is null");
<del> if (disposed) {
<del> return;
<del> }
<del> synchronized (this) {
<del> if (disposed) {
<del> return;
<del> }
<del>
<del> OpenHashSet<Disposable> set = resources;
<del> if (set == null || !set.remove(d)) {
<del> return;
<del> }
<add> public boolean remove(Disposable d) {
<add> if (delete(d)) {
<add> d.dispose();
<add> return true;
<ide> }
<del> d.dispose();
<add> return false;
<ide> }
<ide>
<del> public void delete(Disposable d) {
<add> public boolean delete(Disposable d) {
<ide> Objects.requireNonNull(d, "Disposable item is null");
<ide> if (disposed) {
<del> return;
<add> return false;
<ide> }
<ide> synchronized (this) {
<ide> if (disposed) {
<del> return;
<add> return false;
<ide> }
<ide>
<ide> OpenHashSet<Disposable> set = resources;
<ide> if (set == null || !set.remove(d)) {
<del> return;
<add> return false;
<ide> }
<ide> }
<add> return true;
<ide> }
<ide>
<ide> public void clear() {
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java
<ide>
<ide> import io.reactivex.Flowable;
<ide> import io.reactivex.functions.Function;
<del>import io.reactivex.internal.subscriptions.SubscriptionHelper;
<del>import io.reactivex.plugins.RxJavaPlugins;
<add>import io.reactivex.internal.fuseable.ConditionalSubscriber;
<add>import io.reactivex.internal.subscribers.flowable.*;
<ide>
<ide> public final class FlowableMap<T, U> extends Flowable<U> {
<ide> final Publisher<T> source;
<del> final Function<? super T, ? extends U> function;
<del> public FlowableMap(Publisher<T> source, Function<? super T, ? extends U> function) {
<add> final Function<? super T, ? extends U> mapper;
<add> public FlowableMap(Publisher<T> source, Function<? super T, ? extends U> mapper) {
<ide> this.source = source;
<del> this.function = function;
<add> this.mapper = mapper;
<ide> }
<ide>
<ide> @Override
<ide> protected void subscribeActual(Subscriber<? super U> s) {
<del> source.subscribe(new MapperSubscriber<T, U>(s, function));
<del> }
<del>
<del> static final class MapperSubscriber<T, U> implements Subscriber<T> {
<del> final Subscriber<? super U> actual;
<del> final Function<? super T, ? extends U> function;
<del>
<del> Subscription subscription;
<del>
<del> boolean done;
<del>
<del> public MapperSubscriber(Subscriber<? super U> actual, Function<? super T, ? extends U> function) {
<del> this.actual = actual;
<del> this.function = function;
<add> if (s instanceof ConditionalSubscriber) {
<add> source.subscribe(new MapConditionalSubscriber<T, U>((ConditionalSubscriber<? super U>)s, mapper));
<add> } else {
<add> source.subscribe(new MapSubscriber<T, U>(s, mapper));
<ide> }
<del> @Override
<del> public void onSubscribe(Subscription s) {
<del> if (SubscriptionHelper.validateSubscription(this.subscription, s)) {
<del> subscription = s;
<del> actual.onSubscribe(s);
<del> }
<add> }
<add>
<add> static final class MapSubscriber<T, U> extends BasicFuseableSubscriber<T, U> {
<add> final Function<? super T, ? extends U> mapper;
<add>
<add> public MapSubscriber(Subscriber<? super U> actual, Function<? super T, ? extends U> mapper) {
<add> super(actual);
<add> this.mapper = mapper;
<ide> }
<add>
<ide> @Override
<ide> public void onNext(T t) {
<ide> if (done) {
<ide> return;
<ide> }
<del> U u;
<del> try {
<del> u = function.apply(t);
<del> } catch (Throwable e) {
<del> done = true;
<del> subscription.cancel();
<del> actual.onError(e);
<add>
<add> if (sourceMode == ASYNC) {
<add> actual.onNext(null);
<ide> return;
<ide> }
<del> if (u == null) {
<del> done = true;
<del> subscription.cancel();
<del> actual.onError(new NullPointerException("Value returned by the function is null"));
<add>
<add> U v;
<add>
<add> try {
<add> v = nullCheck(mapper.apply(t), "The mapper function returned a null value.");
<add> } catch (Throwable ex) {
<add> fail(ex);
<ide> return;
<ide> }
<del> actual.onNext(u);
<add> actual.onNext(v);
<add> }
<add>
<add> @Override
<add> public int requestFusion(int mode) {
<add> return transitiveBoundaryFusion(mode);
<add> }
<add>
<add> @Override
<add> public U poll() {
<add> T t = qs.poll();
<add> return t != null ? nullCheck(mapper.apply(t), "The mapper function returned a null value.") : null;
<add> }
<add> }
<add>
<add> static final class MapConditionalSubscriber<T, U> extends BasicFuseableConditionalSubscriber<T, U> {
<add> final Function<? super T, ? extends U> mapper;
<add>
<add> public MapConditionalSubscriber(ConditionalSubscriber<? super U> actual, Function<? super T, ? extends U> function) {
<add> super(actual);
<add> this.mapper = function;
<ide> }
<add>
<ide> @Override
<del> public void onError(Throwable t) {
<add> public void onNext(T t) {
<ide> if (done) {
<del> RxJavaPlugins.onError(t);
<ide> return;
<ide> }
<del> done = true;
<del> actual.onError(t);
<add>
<add> if (sourceMode == ASYNC) {
<add> actual.onNext(null);
<add> return;
<add> }
<add>
<add> U v;
<add>
<add> try {
<add> v = nullCheck(mapper.apply(t), "The mapper function returned a null value.");
<add> } catch (Throwable ex) {
<add> fail(ex);
<add> return;
<add> }
<add> actual.onNext(v);
<ide> }
<add>
<ide> @Override
<del> public void onComplete() {
<add> public boolean tryOnNext(T t) {
<ide> if (done) {
<del> return;
<add> return false;
<ide> }
<del> done = true;
<del> actual.onComplete();
<add>
<add> if (sourceMode == ASYNC) {
<add> actual.onNext(null);
<add> return true;
<add> }
<add>
<add> U v;
<add>
<add> try {
<add> v = mapper.apply(t);
<add> } catch (Throwable ex) {
<add> fail(ex);
<add> return true;
<add> }
<add> return actual.tryOnNext(v);
<add> }
<add>
<add> @Override
<add> public int requestFusion(int mode) {
<add> return transitiveBoundaryFusion(mode);
<add> }
<add>
<add> @Override
<add> public U poll() {
<add> T t = qs.poll();
<add> return t != null ? nullCheck(mapper.apply(t), "The mapper function returned a null value.") : null;
<ide> }
<ide> }
<add>
<ide> }
<add><path>src/main/java/io/reactivex/internal/operators/observable/ObservableAll.java
<del><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorAll.java
<ide> */
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import io.reactivex.Observable.NbpOperator;
<del>import io.reactivex.Observer;
<add>import io.reactivex.*;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.functions.Predicate;
<ide> import io.reactivex.internal.disposables.DisposableHelper;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide>
<del>public final class NbpOperatorAll<T> implements NbpOperator<Boolean, T> {
<add>public final class ObservableAll<T> extends Observable<Boolean> {
<add> final ObservableConsumable<T> source;
<add>
<ide> final Predicate<? super T> predicate;
<del> public NbpOperatorAll(Predicate<? super T> predicate) {
<add> public ObservableAll(ObservableConsumable<T> source, Predicate<? super T> predicate) {
<add> this.source = source;
<ide> this.predicate = predicate;
<ide> }
<ide>
<ide> @Override
<del> public Observer<? super T> apply(Observer<? super Boolean> t) {
<del> return new AllSubscriber<T>(t, predicate);
<add> protected void subscribeActual(Observer<? super Boolean> t) {
<add> source.subscribe(new AllSubscriber<T>(t, predicate));
<ide> }
<ide>
<ide> static final class AllSubscriber<T> implements Observer<T> {
<add><path>src/main/java/io/reactivex/internal/operators/observable/ObservableAny.java
<del><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorAny.java
<ide> */
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import io.reactivex.Observable.NbpOperator;
<del>import io.reactivex.Observer;
<add>import io.reactivex.*;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.functions.Predicate;
<ide> import io.reactivex.internal.disposables.DisposableHelper;
<ide>
<del>public final class NbpOperatorAny<T> implements NbpOperator<Boolean, T> {
<add>public final class ObservableAny<T> extends Observable<Boolean> {
<add> final ObservableConsumable<T> source;
<ide> final Predicate<? super T> predicate;
<del> public NbpOperatorAny(Predicate<? super T> predicate) {
<add> public ObservableAny(ObservableConsumable<T> source, Predicate<? super T> predicate) {
<add> this.source = source;
<ide> this.predicate = predicate;
<ide> }
<ide>
<ide> @Override
<del> public Observer<? super T> apply(Observer<? super Boolean> t) {
<del> return new AnySubscriber<T>(t, predicate);
<add> protected void subscribeActual(Observer<? super Boolean> t) {
<add> source.subscribe(new AnySubscriber<T>(t, predicate));
<ide> }
<ide>
<ide> static final class AnySubscriber<T> implements Observer<T> {
<add><path>src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java
<del><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorBuffer.java
<ide> import java.util.*;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<ide>
<del>import io.reactivex.Observable.NbpOperator;
<add>import io.reactivex.Observable;
<add>import io.reactivex.ObservableConsumable;
<ide> import io.reactivex.Observer;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.functions.Supplier;
<ide> import io.reactivex.internal.disposables.*;
<del>import io.reactivex.internal.subscribers.observable.NbpEmptySubscriber;
<ide>
<del>public final class NbpOperatorBuffer<T, U extends Collection<? super T>> implements NbpOperator<U, T> {
<add>public final class ObservableBuffer<T, U extends Collection<? super T>> extends Observable<U> {
<add> final ObservableConsumable<T> source;
<ide> final int count;
<ide> final int skip;
<ide> final Supplier<U> bufferSupplier;
<ide>
<del> public NbpOperatorBuffer(int count, int skip, Supplier<U> bufferSupplier) {
<add> public ObservableBuffer(ObservableConsumable<T> source, int count, int skip, Supplier<U> bufferSupplier) {
<add> this.source = source;
<ide> this.count = count;
<ide> this.skip = skip;
<ide> this.bufferSupplier = bufferSupplier;
<ide> }
<ide>
<ide> @Override
<del> public Observer<? super T> apply(Observer<? super U> t) {
<add> protected void subscribeActual(Observer<? super U> t) {
<ide> if (skip == count) {
<ide> BufferExactSubscriber<T, U> bes = new BufferExactSubscriber<T, U>(t, count, bufferSupplier);
<ide> if (bes.createBuffer()) {
<del> return bes;
<add> source.subscribe(bes);
<ide> }
<del> return NbpEmptySubscriber.INSTANCE;
<add> } else {
<add> source.subscribe(new BufferSkipSubscriber<T, U>(t, count, skip, bufferSupplier));
<ide> }
<del> return new BufferSkipSubscriber<T, U>(t, count, skip, bufferSupplier);
<ide> }
<ide>
<ide> static final class BufferExactSubscriber<T, U extends Collection<? super T>> implements Observer<T> {
<add><path>src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundary.java
<del><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorBufferBoundary.java
<ide> import java.util.*;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<del>import io.reactivex.Observable.NbpOperator;
<add>import io.reactivex.Observable;
<ide> import io.reactivex.ObservableConsumable;
<ide> import io.reactivex.Observer;
<ide> import io.reactivex.disposables.*;
<ide> import io.reactivex.observers.SerializedObserver;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide>
<del>public final class NbpOperatorBufferBoundary<T, U extends Collection<? super T>, Open, Close> implements NbpOperator<U, T> {
<add>public final class ObservableBufferBoundary<T, U extends Collection<? super T>, Open, Close>
<add>extends Observable<U> {
<add> final ObservableConsumable<T> source;
<ide> final Supplier<U> bufferSupplier;
<ide> final ObservableConsumable<? extends Open> bufferOpen;
<ide> final Function<? super Open, ? extends ObservableConsumable<? extends Close>> bufferClose;
<ide>
<del> public NbpOperatorBufferBoundary(ObservableConsumable<? extends Open> bufferOpen,
<add> public ObservableBufferBoundary(ObservableConsumable<T> source, ObservableConsumable<? extends Open> bufferOpen,
<ide> Function<? super Open, ? extends ObservableConsumable<? extends Close>> bufferClose, Supplier<U> bufferSupplier) {
<add> this.source = source;
<ide> this.bufferOpen = bufferOpen;
<ide> this.bufferClose = bufferClose;
<ide> this.bufferSupplier = bufferSupplier;
<ide> }
<ide>
<ide> @Override
<del> public Observer<? super T> apply(Observer<? super U> t) {
<del> return new BufferBoundarySubscriber<T, U, Open, Close>(
<add> protected void subscribeActual(Observer<? super U> t) {
<add> source.subscribe(new BufferBoundarySubscriber<T, U, Open, Close>(
<ide> new SerializedObserver<U>(t),
<ide> bufferOpen, bufferClose, bufferSupplier
<del> );
<add> ));
<ide> }
<ide>
<ide> static final class BufferBoundarySubscriber<T, U extends Collection<? super T>, Open, Close>
<ide> extends NbpQueueDrainSubscriber<T, U, U> implements Disposable {
<ide> final ObservableConsumable<? extends Open> bufferOpen;
<ide> final Function<? super Open, ? extends ObservableConsumable<? extends Close>> bufferClose;
<ide> final Supplier<U> bufferSupplier;
<del> final SetCompositeResource<Disposable> resources;
<add> final CompositeDisposable resources;
<ide>
<ide> Disposable s;
<ide>
<ide> public BufferBoundarySubscriber(Observer<? super U> actual,
<ide> this.bufferClose = bufferClose;
<ide> this.bufferSupplier = bufferSupplier;
<ide> this.buffers = new LinkedList<U>();
<del> this.resources = new SetCompositeResource<Disposable>(Disposables.consumeAndDispose());
<add> this.resources = new CompositeDisposable();
<ide> }
<ide> @Override
<ide> public void onSubscribe(Disposable s) {
<add><path>src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java
<del><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorBufferBoundarySupplier.java
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide>
<ide> import io.reactivex.*;
<del>import io.reactivex.Observable.NbpOperator;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.functions.Supplier;
<ide> import io.reactivex.internal.disposables.*;
<ide> import io.reactivex.observers.SerializedObserver;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide>
<del>public final class NbpOperatorBufferBoundarySupplier<T, U extends Collection<? super T>, B> implements NbpOperator<U, T> {
<add>public final class ObservableBufferBoundarySupplier<T, U extends Collection<? super T>, B>
<add>extends Observable<U> {
<add> final ObservableConsumable<T> source;
<ide> final Supplier<? extends ObservableConsumable<B>> boundarySupplier;
<ide> final Supplier<U> bufferSupplier;
<ide>
<del> public NbpOperatorBufferBoundarySupplier(Supplier<? extends ObservableConsumable<B>> boundarySupplier, Supplier<U> bufferSupplier) {
<add> public ObservableBufferBoundarySupplier(ObservableConsumable<T> source, Supplier<? extends ObservableConsumable<B>> boundarySupplier, Supplier<U> bufferSupplier) {
<add> this.source = source;
<ide> this.boundarySupplier = boundarySupplier;
<ide> this.bufferSupplier = bufferSupplier;
<ide> }
<ide>
<ide> @Override
<del> public Observer<? super T> apply(Observer<? super U> t) {
<del> return new BufferBondarySupplierSubscriber<T, U, B>(new SerializedObserver<U>(t), bufferSupplier, boundarySupplier);
<add> protected void subscribeActual(Observer<? super U> t) {
<add> source.subscribe(new BufferBondarySupplierSubscriber<T, U, B>(new SerializedObserver<U>(t), bufferSupplier, boundarySupplier));
<ide> }
<ide>
<ide> static final class BufferBondarySupplierSubscriber<T, U extends Collection<? super T>, B>
<add><path>src/main/java/io/reactivex/internal/operators/observable/ObservableBufferExactBoundary.java
<del><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorBufferExactBoundary.java
<ide> import java.util.Collection;
<ide>
<ide> import io.reactivex.*;
<del>import io.reactivex.Observable.NbpOperator;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.functions.Supplier;
<ide> import io.reactivex.internal.disposables.*;
<ide> import io.reactivex.internal.util.QueueDrainHelper;
<ide> import io.reactivex.observers.SerializedObserver;
<ide>
<del>public final class NbpOperatorBufferExactBoundary<T, U extends Collection<? super T>, B> implements NbpOperator<U, T> {
<add>public final class ObservableBufferExactBoundary<T, U extends Collection<? super T>, B>
<add>extends Observable<U> {
<add> final ObservableConsumable<T> source;
<ide> final ObservableConsumable<B> boundary;
<ide> final Supplier<U> bufferSupplier;
<ide>
<del> public NbpOperatorBufferExactBoundary(ObservableConsumable<B> boundary, Supplier<U> bufferSupplier) {
<add> public ObservableBufferExactBoundary(ObservableConsumable<T> source, ObservableConsumable<B> boundary, Supplier<U> bufferSupplier) {
<add> this.source = source;
<ide> this.boundary = boundary;
<ide> this.bufferSupplier = bufferSupplier;
<ide> }
<del>
<add>
<ide> @Override
<del> public Observer<? super T> apply(Observer<? super U> t) {
<del> return new BufferExactBondarySubscriber<T, U, B>(new SerializedObserver<U>(t), bufferSupplier, boundary);
<add> protected void subscribeActual(Observer<? super U> t) {
<add> source.subscribe(new BufferExactBondarySubscriber<T, U, B>(new SerializedObserver<U>(t), bufferSupplier, boundary));
<ide> }
<ide>
<ide> static final class BufferExactBondarySubscriber<T, U extends Collection<? super T>, B>
<add><path>src/main/java/io/reactivex/internal/operators/observable/ObservableBufferTimed.java
<del><path>src/main/java/io/reactivex/internal/operators/observable/NbpOperatorBufferTimed.java
<ide> import java.util.concurrent.*;
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide>
<del>import io.reactivex.Observable.NbpOperator;
<add>import io.reactivex.*;
<add>import io.reactivex.Observable;
<ide> import io.reactivex.Observer;
<del>import io.reactivex.Scheduler;
<ide> import io.reactivex.Scheduler.Worker;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.functions.Supplier;
<ide> import io.reactivex.internal.util.QueueDrainHelper;
<ide> import io.reactivex.observers.SerializedObserver;
<ide>
<del>public final class NbpOperatorBufferTimed<T, U extends Collection<? super T>> implements NbpOperator<U, T> {
<add>public final class ObservableBufferTimed<T, U extends Collection<? super T>>
<add>extends Observable<U> {
<ide>
<add> final ObservableConsumable<T> source;
<ide> final long timespan;
<ide> final long timeskip;
<ide> final TimeUnit unit;
<ide> final int maxSize;
<ide> final boolean restartTimerOnMaxSize;
<ide>
<del> public NbpOperatorBufferTimed(long timespan, long timeskip, TimeUnit unit, Scheduler scheduler, Supplier<U> bufferSupplier, int maxSize,
<add> public ObservableBufferTimed(ObservableConsumable<T> source, long timespan, long timeskip, TimeUnit unit, Scheduler scheduler, Supplier<U> bufferSupplier, int maxSize,
<ide> boolean restartTimerOnMaxSize) {
<add> this.source = source;
<ide> this.timespan = timespan;
<ide> this.timeskip = timeskip;
<ide> this.unit = unit;
<ide> public NbpOperatorBufferTimed(long timespan, long timeskip, TimeUnit unit, Sched
<ide> }
<ide>
<ide> @Override
<del> public Observer<? super T> apply(Observer<? super U> t) {
<add> protected void subscribeActual(Observer<? super U> t) {
<ide> if (timespan == timeskip && maxSize == Integer.MAX_VALUE) {
<del> return new BufferExactUnboundedSubscriber<T, U>(
<add> source.subscribe(new BufferExactUnboundedSubscriber<T, U>(
<ide> new SerializedObserver<U>(t),
<del> bufferSupplier, timespan, unit, scheduler);
<add> bufferSupplier, timespan, unit, scheduler));
<add> return;
<ide> }
<ide> Scheduler.Worker w = scheduler.createWorker();
<ide>
<ide> if (timespan == timeskip) {
<del> return new BufferExactBoundedSubscriber<T, U>(
<add> source.subscribe(new BufferExactBoundedSubscriber<T, U>(
<ide> new SerializedObserver<U>(t),
<ide> bufferSupplier,
<ide> timespan, unit, maxSize, restartTimerOnMaxSize, w
<del> );
<add> ));
<add> return;
<ide> }
<ide> // Can't use maxSize because what to do if a buffer is full but its
<ide> // timespan hasn't been elapsed?
<del> return new BufferSkipBoundedSubscriber<T, U>(
<add> source.subscribe(new BufferSkipBoundedSubscriber<T, U>(
<ide> new SerializedObserver<U>(t),
<del> bufferSupplier, timespan, timeskip, unit, w);
<add> bufferSupplier, timespan, timeskip, unit, w));
<add>
<ide> }
<ide>
<ide> static final class BufferExactUnboundedSubscriber<T, U extends Collection<? super T>>
<ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/BasicFuseableConditionalSubscriber.java
<ide>
<ide> import org.reactivestreams.Subscription;
<ide>
<add>import io.reactivex.internal.functions.Objects;
<ide> import io.reactivex.internal.fuseable.*;
<ide> import io.reactivex.internal.subscriptions.SubscriptionHelper;
<ide> import io.reactivex.internal.util.Exceptions;
<ide> protected final boolean tryNext(R value) {
<ide> return actual.tryOnNext(value);
<ide> }
<ide>
<del> /**
<del> * Emits the throwable to the actual subscriber if {@link #done} is false,
<del> * signals the throwable to {@link RxJavaPlugins#onError(Throwable)} otherwise.
<del> * @param t the throwable t signal
<del> */
<del> protected final void error(Throwable t) {
<add> @Override
<add> public void onError(Throwable t) {
<ide> if (done) {
<ide> RxJavaPlugins.onError(t);
<ide> return;
<ide> protected final void error(Throwable t) {
<ide> */
<ide> protected final void fail(Throwable t) {
<ide> Exceptions.throwIfFatal(t);
<del> error(t);
<add> s.cancel();
<add> onError(t);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> if (done) {
<add> return;
<add> }
<add> done = true;
<add> actual.onComplete();
<add> }
<add>
<add> /**
<add> * Checks if the value is null and if so, throws a NullPointerException.
<add> * @param value the value to check
<add> * @param message the message to indicate the source of the value
<add> * @return the value if not null
<add> */
<add> protected final <V> V nullCheck(V value, String message) {
<add> return Objects.requireNonNull(value, message);
<ide> }
<ide>
<ide> /**
<ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/BasicFuseableSubscriber.java
<ide>
<ide> import org.reactivestreams.*;
<ide>
<add>import io.reactivex.internal.functions.Objects;
<ide> import io.reactivex.internal.fuseable.QueueSubscription;
<ide> import io.reactivex.internal.subscriptions.SubscriptionHelper;
<ide> import io.reactivex.internal.util.Exceptions;
<ide> protected final void next(R value) {
<ide> actual.onNext(value);
<ide> }
<ide>
<del> /**
<del> * Emits the throwable to the actual subscriber if {@link #done} is false,
<del> * signals the throwable to {@link RxJavaPlugins#onError(Throwable)} otherwise.
<del> * @param t the throwable t signal
<del> */
<del> protected final void error(Throwable t) {
<add> @Override
<add> public void onError(Throwable t) {
<ide> if (done) {
<ide> RxJavaPlugins.onError(t);
<ide> return;
<ide> protected final void error(Throwable t) {
<ide> */
<ide> protected final void fail(Throwable t) {
<ide> Exceptions.throwIfFatal(t);
<del> error(t);
<add> s.cancel();
<add> onError(t);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> if (done) {
<add> return;
<add> }
<add> done = true;
<add> actual.onComplete();
<add> }
<add>
<add> /**
<add> * Checks if the value is null and if so, throws a NullPointerException.
<add> * @param value the value to check
<add> * @param message the message to indicate the source of the value
<add> * @return the value if not null
<add> */
<add> protected final <V> V nullCheck(V value, String message) {
<add> return Objects.requireNonNull(value, message);
<ide> }
<ide>
<ide> /**
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureDropTest.java
<ide> public void testWithObserveOn() throws InterruptedException {
<ide> ts.awaitTerminalEvent();
<ide> }
<ide>
<del> @Test(timeout = 500)
<add> @Test(timeout = 5000)
<ide> public void testFixBackpressureWithBuffer() throws InterruptedException {
<ide> final CountDownLatch l1 = new CountDownLatch(100);
<ide> final CountDownLatch l2 = new CountDownLatch(150); | 13 |
Ruby | Ruby | remove xattr unsupported option in macos 10.15 | 24ef7fa5c8eb8e313a7169e4a55f88e21dea277b | <ide><path>Library/Homebrew/cask/quarantine.rb
<ide> def propagate(from: nil, to: nil)
<ide> "--",
<ide> xattr,
<ide> "-w",
<del> "-s",
<ide> QUARANTINE_ATTRIBUTE,
<ide> quarantine_status,
<ide> ], | 1 |
Python | Python | move asarray helpers into their own module | 82641c61b1a2d6d1b8cccce5a65f4215c94b99b2 | <ide><path>numpy/core/_asarray.py
<add>"""
<add>Functions in the ``as*array`` family that promote array-likes into arrays.
<add>
<add>`require` fits this category despite its name not matching this pattern.
<add>"""
<add>from __future__ import division, absolute_import, print_function
<add>
<add>from .overrides import set_module
<add>from .multiarray import array
<add>
<add>
<add>__all__ = [
<add> "asarray", "asanyarray", "ascontiguousarray", "asfortranarray", "require",
<add>]
<add>
<add>@set_module('numpy')
<add>def asarray(a, dtype=None, order=None):
<add> """Convert the input to an array.
<add>
<add> Parameters
<add> ----------
<add> a : array_like
<add> Input data, in any form that can be converted to an array. This
<add> includes lists, lists of tuples, tuples, tuples of tuples, tuples
<add> of lists and ndarrays.
<add> dtype : data-type, optional
<add> By default, the data-type is inferred from the input data.
<add> order : {'C', 'F'}, optional
<add> Whether to use row-major (C-style) or
<add> column-major (Fortran-style) memory representation.
<add> Defaults to 'C'.
<add>
<add> Returns
<add> -------
<add> out : ndarray
<add> Array interpretation of `a`. No copy is performed if the input
<add> is already an ndarray with matching dtype and order. If `a` is a
<add> subclass of ndarray, a base class ndarray is returned.
<add>
<add> See Also
<add> --------
<add> asanyarray : Similar function which passes through subclasses.
<add> ascontiguousarray : Convert input to a contiguous array.
<add> asfarray : Convert input to a floating point ndarray.
<add> asfortranarray : Convert input to an ndarray with column-major
<add> memory order.
<add> asarray_chkfinite : Similar function which checks input for NaNs and Infs.
<add> fromiter : Create an array from an iterator.
<add> fromfunction : Construct an array by executing a function on grid
<add> positions.
<add>
<add> Examples
<add> --------
<add> Convert a list into an array:
<add>
<add> >>> a = [1, 2]
<add> >>> np.asarray(a)
<add> array([1, 2])
<add>
<add> Existing arrays are not copied:
<add>
<add> >>> a = np.array([1, 2])
<add> >>> np.asarray(a) is a
<add> True
<add>
<add> If `dtype` is set, array is copied only if dtype does not match:
<add>
<add> >>> a = np.array([1, 2], dtype=np.float32)
<add> >>> np.asarray(a, dtype=np.float32) is a
<add> True
<add> >>> np.asarray(a, dtype=np.float64) is a
<add> False
<add>
<add> Contrary to `asanyarray`, ndarray subclasses are not passed through:
<add>
<add> >>> issubclass(np.recarray, np.ndarray)
<add> True
<add> >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
<add> >>> np.asarray(a) is a
<add> False
<add> >>> np.asanyarray(a) is a
<add> True
<add>
<add> """
<add> return array(a, dtype, copy=False, order=order)
<add>
<add>
<add>@set_module('numpy')
<add>def asanyarray(a, dtype=None, order=None):
<add> """Convert the input to an ndarray, but pass ndarray subclasses through.
<add>
<add> Parameters
<add> ----------
<add> a : array_like
<add> Input data, in any form that can be converted to an array. This
<add> includes scalars, lists, lists of tuples, tuples, tuples of tuples,
<add> tuples of lists, and ndarrays.
<add> dtype : data-type, optional
<add> By default, the data-type is inferred from the input data.
<add> order : {'C', 'F'}, optional
<add> Whether to use row-major (C-style) or column-major
<add> (Fortran-style) memory representation. Defaults to 'C'.
<add>
<add> Returns
<add> -------
<add> out : ndarray or an ndarray subclass
<add> Array interpretation of `a`. If `a` is an ndarray or a subclass
<add> of ndarray, it is returned as-is and no copy is performed.
<add>
<add> See Also
<add> --------
<add> asarray : Similar function which always returns ndarrays.
<add> ascontiguousarray : Convert input to a contiguous array.
<add> asfarray : Convert input to a floating point ndarray.
<add> asfortranarray : Convert input to an ndarray with column-major
<add> memory order.
<add> asarray_chkfinite : Similar function which checks input for NaNs and
<add> Infs.
<add> fromiter : Create an array from an iterator.
<add> fromfunction : Construct an array by executing a function on grid
<add> positions.
<add>
<add> Examples
<add> --------
<add> Convert a list into an array:
<add>
<add> >>> a = [1, 2]
<add> >>> np.asanyarray(a)
<add> array([1, 2])
<add>
<add> Instances of `ndarray` subclasses are passed through as-is:
<add>
<add> >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
<add> >>> np.asanyarray(a) is a
<add> True
<add>
<add> """
<add> return array(a, dtype, copy=False, order=order, subok=True)
<add>
<add>
<add>@set_module('numpy')
<add>def ascontiguousarray(a, dtype=None):
<add> """
<add> Return a contiguous array (ndim >= 1) in memory (C order).
<add>
<add> Parameters
<add> ----------
<add> a : array_like
<add> Input array.
<add> dtype : str or dtype object, optional
<add> Data-type of returned array.
<add>
<add> Returns
<add> -------
<add> out : ndarray
<add> Contiguous array of same shape and content as `a`, with type `dtype`
<add> if specified.
<add>
<add> See Also
<add> --------
<add> asfortranarray : Convert input to an ndarray with column-major
<add> memory order.
<add> require : Return an ndarray that satisfies requirements.
<add> ndarray.flags : Information about the memory layout of the array.
<add>
<add> Examples
<add> --------
<add> >>> x = np.arange(6).reshape(2,3)
<add> >>> np.ascontiguousarray(x, dtype=np.float32)
<add> array([[0., 1., 2.],
<add> [3., 4., 5.]], dtype=float32)
<add> >>> x.flags['C_CONTIGUOUS']
<add> True
<add>
<add> Note: This function returns an array with at least one-dimension (1-d)
<add> so it will not preserve 0-d arrays.
<add>
<add> """
<add> return array(a, dtype, copy=False, order='C', ndmin=1)
<add>
<add>
<add>@set_module('numpy')
<add>def asfortranarray(a, dtype=None):
<add> """
<add> Return an array (ndim >= 1) laid out in Fortran order in memory.
<add>
<add> Parameters
<add> ----------
<add> a : array_like
<add> Input array.
<add> dtype : str or dtype object, optional
<add> By default, the data-type is inferred from the input data.
<add>
<add> Returns
<add> -------
<add> out : ndarray
<add> The input `a` in Fortran, or column-major, order.
<add>
<add> See Also
<add> --------
<add> ascontiguousarray : Convert input to a contiguous (C order) array.
<add> asanyarray : Convert input to an ndarray with either row or
<add> column-major memory order.
<add> require : Return an ndarray that satisfies requirements.
<add> ndarray.flags : Information about the memory layout of the array.
<add>
<add> Examples
<add> --------
<add> >>> x = np.arange(6).reshape(2,3)
<add> >>> y = np.asfortranarray(x)
<add> >>> x.flags['F_CONTIGUOUS']
<add> False
<add> >>> y.flags['F_CONTIGUOUS']
<add> True
<add>
<add> Note: This function returns an array with at least one-dimension (1-d)
<add> so it will not preserve 0-d arrays.
<add>
<add> """
<add> return array(a, dtype, copy=False, order='F', ndmin=1)
<add>
<add>
<add>@set_module('numpy')
<add>def require(a, dtype=None, requirements=None):
<add> """
<add> Return an ndarray of the provided type that satisfies requirements.
<add>
<add> This function is useful to be sure that an array with the correct flags
<add> is returned for passing to compiled code (perhaps through ctypes).
<add>
<add> Parameters
<add> ----------
<add> a : array_like
<add> The object to be converted to a type-and-requirement-satisfying array.
<add> dtype : data-type
<add> The required data-type. If None preserve the current dtype. If your
<add> application requires the data to be in native byteorder, include
<add> a byteorder specification as a part of the dtype specification.
<add> requirements : str or list of str
<add> The requirements list can be any of the following
<add>
<add> * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
<add> * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
<add> * 'ALIGNED' ('A') - ensure a data-type aligned array
<add> * 'WRITEABLE' ('W') - ensure a writable array
<add> * 'OWNDATA' ('O') - ensure an array that owns its own data
<add> * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
<add>
<add> See Also
<add> --------
<add> asarray : Convert input to an ndarray.
<add> asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
<add> ascontiguousarray : Convert input to a contiguous array.
<add> asfortranarray : Convert input to an ndarray with column-major
<add> memory order.
<add> ndarray.flags : Information about the memory layout of the array.
<add>
<add> Notes
<add> -----
<add> The returned array will be guaranteed to have the listed requirements
<add> by making a copy if needed.
<add>
<add> Examples
<add> --------
<add> >>> x = np.arange(6).reshape(2,3)
<add> >>> x.flags
<add> C_CONTIGUOUS : True
<add> F_CONTIGUOUS : False
<add> OWNDATA : False
<add> WRITEABLE : True
<add> ALIGNED : True
<add> WRITEBACKIFCOPY : False
<add> UPDATEIFCOPY : False
<add>
<add> >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
<add> >>> y.flags
<add> C_CONTIGUOUS : False
<add> F_CONTIGUOUS : True
<add> OWNDATA : True
<add> WRITEABLE : True
<add> ALIGNED : True
<add> WRITEBACKIFCOPY : False
<add> UPDATEIFCOPY : False
<add>
<add> """
<add> possible_flags = {'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C',
<add> 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F',
<add> 'A': 'A', 'ALIGNED': 'A',
<add> 'W': 'W', 'WRITEABLE': 'W',
<add> 'O': 'O', 'OWNDATA': 'O',
<add> 'E': 'E', 'ENSUREARRAY': 'E'}
<add> if not requirements:
<add> return asanyarray(a, dtype=dtype)
<add> else:
<add> requirements = {possible_flags[x.upper()] for x in requirements}
<add>
<add> if 'E' in requirements:
<add> requirements.remove('E')
<add> subok = False
<add> else:
<add> subok = True
<add>
<add> order = 'A'
<add> if requirements >= {'C', 'F'}:
<add> raise ValueError('Cannot specify both "C" and "F" order')
<add> elif 'F' in requirements:
<add> order = 'F'
<add> requirements.remove('F')
<add> elif 'C' in requirements:
<add> order = 'C'
<add> requirements.remove('C')
<add>
<add> arr = array(a, dtype=dtype, order=order, copy=False, subok=subok)
<add>
<add> for prop in requirements:
<add> if not arr.flags[prop]:
<add> arr = arr.copy(order)
<add> break
<add> return arr
<ide><path>numpy/core/_methods.py
<ide>
<ide> from numpy.core import multiarray as mu
<ide> from numpy.core import umath as um
<del>from numpy.core.numeric import asanyarray
<add>from numpy.core._asarray import asanyarray
<ide> from numpy.core import numerictypes as nt
<ide> from numpy._globals import _NoValue
<ide>
<ide><path>numpy/core/fromnumeric.py
<ide> from . import overrides
<ide> from . import umath as um
<ide> from . import numerictypes as nt
<del>from .numeric import asarray, array, asanyarray, concatenate
<add>from ._asarray import asarray, array, asanyarray
<add>from .multiarray import concatenate
<ide> from . import _methods
<ide>
<ide> _dt_ = nt.sctype2char
<ide><path>numpy/core/numeric.py
<ide> from . import numerictypes
<ide> from .numerictypes import longlong, intc, int_, float_, complex_, bool_
<ide> from ._exceptions import TooHardError, AxisError
<add>from ._asarray import asarray, asanyarray
<ide>
<ide> bitwise_not = invert
<ide> ufunc = type(sin)
<ide> def loads(*args, **kwargs):
<ide> 'fromstring', 'fromfile', 'frombuffer', 'int_asbuffer', 'where',
<ide> 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort',
<ide> 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type',
<del> 'result_type', 'asarray', 'asanyarray', 'ascontiguousarray',
<del> 'asfortranarray', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
<add> 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
<ide> 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
<del> 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'require',
<add> 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian',
<ide> 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
<ide> 'isclose', 'load', 'loads', 'isscalar', 'binary_repr', 'base_repr', 'ones',
<ide> 'identity', 'allclose', 'compare_chararrays', 'putmask', 'seterr',
<ide> def count_nonzero(a, axis=None):
<ide> return a_bool.sum(axis=axis, dtype=np.intp)
<ide>
<ide>
<del>@set_module('numpy')
<del>def asarray(a, dtype=None, order=None):
<del> """Convert the input to an array.
<del>
<del> Parameters
<del> ----------
<del> a : array_like
<del> Input data, in any form that can be converted to an array. This
<del> includes lists, lists of tuples, tuples, tuples of tuples, tuples
<del> of lists and ndarrays.
<del> dtype : data-type, optional
<del> By default, the data-type is inferred from the input data.
<del> order : {'C', 'F'}, optional
<del> Whether to use row-major (C-style) or
<del> column-major (Fortran-style) memory representation.
<del> Defaults to 'C'.
<del>
<del> Returns
<del> -------
<del> out : ndarray
<del> Array interpretation of `a`. No copy is performed if the input
<del> is already an ndarray with matching dtype and order. If `a` is a
<del> subclass of ndarray, a base class ndarray is returned.
<del>
<del> See Also
<del> --------
<del> asanyarray : Similar function which passes through subclasses.
<del> ascontiguousarray : Convert input to a contiguous array.
<del> asfarray : Convert input to a floating point ndarray.
<del> asfortranarray : Convert input to an ndarray with column-major
<del> memory order.
<del> asarray_chkfinite : Similar function which checks input for NaNs and Infs.
<del> fromiter : Create an array from an iterator.
<del> fromfunction : Construct an array by executing a function on grid
<del> positions.
<del>
<del> Examples
<del> --------
<del> Convert a list into an array:
<del>
<del> >>> a = [1, 2]
<del> >>> np.asarray(a)
<del> array([1, 2])
<del>
<del> Existing arrays are not copied:
<del>
<del> >>> a = np.array([1, 2])
<del> >>> np.asarray(a) is a
<del> True
<del>
<del> If `dtype` is set, array is copied only if dtype does not match:
<del>
<del> >>> a = np.array([1, 2], dtype=np.float32)
<del> >>> np.asarray(a, dtype=np.float32) is a
<del> True
<del> >>> np.asarray(a, dtype=np.float64) is a
<del> False
<del>
<del> Contrary to `asanyarray`, ndarray subclasses are not passed through:
<del>
<del> >>> issubclass(np.recarray, np.ndarray)
<del> True
<del> >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
<del> >>> np.asarray(a) is a
<del> False
<del> >>> np.asanyarray(a) is a
<del> True
<del>
<del> """
<del> return array(a, dtype, copy=False, order=order)
<del>
<del>
<del>@set_module('numpy')
<del>def asanyarray(a, dtype=None, order=None):
<del> """Convert the input to an ndarray, but pass ndarray subclasses through.
<del>
<del> Parameters
<del> ----------
<del> a : array_like
<del> Input data, in any form that can be converted to an array. This
<del> includes scalars, lists, lists of tuples, tuples, tuples of tuples,
<del> tuples of lists, and ndarrays.
<del> dtype : data-type, optional
<del> By default, the data-type is inferred from the input data.
<del> order : {'C', 'F'}, optional
<del> Whether to use row-major (C-style) or column-major
<del> (Fortran-style) memory representation. Defaults to 'C'.
<del>
<del> Returns
<del> -------
<del> out : ndarray or an ndarray subclass
<del> Array interpretation of `a`. If `a` is an ndarray or a subclass
<del> of ndarray, it is returned as-is and no copy is performed.
<del>
<del> See Also
<del> --------
<del> asarray : Similar function which always returns ndarrays.
<del> ascontiguousarray : Convert input to a contiguous array.
<del> asfarray : Convert input to a floating point ndarray.
<del> asfortranarray : Convert input to an ndarray with column-major
<del> memory order.
<del> asarray_chkfinite : Similar function which checks input for NaNs and
<del> Infs.
<del> fromiter : Create an array from an iterator.
<del> fromfunction : Construct an array by executing a function on grid
<del> positions.
<del>
<del> Examples
<del> --------
<del> Convert a list into an array:
<del>
<del> >>> a = [1, 2]
<del> >>> np.asanyarray(a)
<del> array([1, 2])
<del>
<del> Instances of `ndarray` subclasses are passed through as-is:
<del>
<del> >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
<del> >>> np.asanyarray(a) is a
<del> True
<del>
<del> """
<del> return array(a, dtype, copy=False, order=order, subok=True)
<del>
<del>
<del>@set_module('numpy')
<del>def ascontiguousarray(a, dtype=None):
<del> """
<del> Return a contiguous array (ndim >= 1) in memory (C order).
<del>
<del> Parameters
<del> ----------
<del> a : array_like
<del> Input array.
<del> dtype : str or dtype object, optional
<del> Data-type of returned array.
<del>
<del> Returns
<del> -------
<del> out : ndarray
<del> Contiguous array of same shape and content as `a`, with type `dtype`
<del> if specified.
<del>
<del> See Also
<del> --------
<del> asfortranarray : Convert input to an ndarray with column-major
<del> memory order.
<del> require : Return an ndarray that satisfies requirements.
<del> ndarray.flags : Information about the memory layout of the array.
<del>
<del> Examples
<del> --------
<del> >>> x = np.arange(6).reshape(2,3)
<del> >>> np.ascontiguousarray(x, dtype=np.float32)
<del> array([[0., 1., 2.],
<del> [3., 4., 5.]], dtype=float32)
<del> >>> x.flags['C_CONTIGUOUS']
<del> True
<del>
<del> Note: This function returns an array with at least one-dimension (1-d)
<del> so it will not preserve 0-d arrays.
<del>
<del> """
<del> return array(a, dtype, copy=False, order='C', ndmin=1)
<del>
<del>
<del>@set_module('numpy')
<del>def asfortranarray(a, dtype=None):
<del> """
<del> Return an array (ndim >= 1) laid out in Fortran order in memory.
<del>
<del> Parameters
<del> ----------
<del> a : array_like
<del> Input array.
<del> dtype : str or dtype object, optional
<del> By default, the data-type is inferred from the input data.
<del>
<del> Returns
<del> -------
<del> out : ndarray
<del> The input `a` in Fortran, or column-major, order.
<del>
<del> See Also
<del> --------
<del> ascontiguousarray : Convert input to a contiguous (C order) array.
<del> asanyarray : Convert input to an ndarray with either row or
<del> column-major memory order.
<del> require : Return an ndarray that satisfies requirements.
<del> ndarray.flags : Information about the memory layout of the array.
<del>
<del> Examples
<del> --------
<del> >>> x = np.arange(6).reshape(2,3)
<del> >>> y = np.asfortranarray(x)
<del> >>> x.flags['F_CONTIGUOUS']
<del> False
<del> >>> y.flags['F_CONTIGUOUS']
<del> True
<del>
<del> Note: This function returns an array with at least one-dimension (1-d)
<del> so it will not preserve 0-d arrays.
<del>
<del> """
<del> return array(a, dtype, copy=False, order='F', ndmin=1)
<del>
<del>
<del>@set_module('numpy')
<del>def require(a, dtype=None, requirements=None):
<del> """
<del> Return an ndarray of the provided type that satisfies requirements.
<del>
<del> This function is useful to be sure that an array with the correct flags
<del> is returned for passing to compiled code (perhaps through ctypes).
<del>
<del> Parameters
<del> ----------
<del> a : array_like
<del> The object to be converted to a type-and-requirement-satisfying array.
<del> dtype : data-type
<del> The required data-type. If None preserve the current dtype. If your
<del> application requires the data to be in native byteorder, include
<del> a byteorder specification as a part of the dtype specification.
<del> requirements : str or list of str
<del> The requirements list can be any of the following
<del>
<del> * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
<del> * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
<del> * 'ALIGNED' ('A') - ensure a data-type aligned array
<del> * 'WRITEABLE' ('W') - ensure a writable array
<del> * 'OWNDATA' ('O') - ensure an array that owns its own data
<del> * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
<del>
<del> See Also
<del> --------
<del> asarray : Convert input to an ndarray.
<del> asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
<del> ascontiguousarray : Convert input to a contiguous array.
<del> asfortranarray : Convert input to an ndarray with column-major
<del> memory order.
<del> ndarray.flags : Information about the memory layout of the array.
<del>
<del> Notes
<del> -----
<del> The returned array will be guaranteed to have the listed requirements
<del> by making a copy if needed.
<del>
<del> Examples
<del> --------
<del> >>> x = np.arange(6).reshape(2,3)
<del> >>> x.flags
<del> C_CONTIGUOUS : True
<del> F_CONTIGUOUS : False
<del> OWNDATA : False
<del> WRITEABLE : True
<del> ALIGNED : True
<del> WRITEBACKIFCOPY : False
<del> UPDATEIFCOPY : False
<del>
<del> >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
<del> >>> y.flags
<del> C_CONTIGUOUS : False
<del> F_CONTIGUOUS : True
<del> OWNDATA : True
<del> WRITEABLE : True
<del> ALIGNED : True
<del> WRITEBACKIFCOPY : False
<del> UPDATEIFCOPY : False
<del>
<del> """
<del> possible_flags = {'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C',
<del> 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F',
<del> 'A': 'A', 'ALIGNED': 'A',
<del> 'W': 'W', 'WRITEABLE': 'W',
<del> 'O': 'O', 'OWNDATA': 'O',
<del> 'E': 'E', 'ENSUREARRAY': 'E'}
<del> if not requirements:
<del> return asanyarray(a, dtype=dtype)
<del> else:
<del> requirements = {possible_flags[x.upper()] for x in requirements}
<del>
<del> if 'E' in requirements:
<del> requirements.remove('E')
<del> subok = False
<del> else:
<del> subok = True
<del>
<del> order = 'A'
<del> if requirements >= {'C', 'F'}:
<del> raise ValueError('Cannot specify both "C" and "F" order')
<del> elif 'F' in requirements:
<del> order = 'F'
<del> requirements.remove('F')
<del> elif 'C' in requirements:
<del> order = 'C'
<del> requirements.remove('C')
<del>
<del> arr = array(a, dtype=dtype, order=order, copy=False, subok=subok)
<del>
<del> for prop in requirements:
<del> if not arr.flags[prop]:
<del> arr = arr.copy(order)
<del> break
<del> return arr
<del>
<del>
<ide> @set_module('numpy')
<ide> def isfortran(a):
<ide> """
<ide> def extend_all(module):
<ide> from .fromnumeric import *
<ide> from . import arrayprint
<ide> from .arrayprint import *
<add>from . import _asarray
<add>from ._asarray import *
<ide> extend_all(fromnumeric)
<ide> extend_all(umath)
<ide> extend_all(numerictypes)
<ide> extend_all(arrayprint)
<add>extend_all(_asarray) | 4 |
Python | Python | add dry run for backfill cli | d9ca46ea997485e4fbb53061be20ff41814f5e98 | <ide><path>airflow/bin/cli.py
<ide> def backfill(args):
<ide> dag = dag.sub_dag(
<ide> task_regex=args.task_regex,
<ide> include_upstream=not args.ignore_dependencies)
<del> dag.run(
<del> start_date=args.start_date,
<del> end_date=args.end_date,
<del> mark_success=args.mark_success,
<del> include_adhoc=args.include_adhoc,
<del> local=args.local,
<del> donot_pickle=args.donot_pickle,
<del> ignore_dependencies=args.ignore_dependencies)
<add>
<add> if args.dry_run:
<add> print("Dry run of DAG {0} on {1}".format(args.dag_id,
<add> args.start_date))
<add> for task in dag.tasks:
<add> print("Task {0}".format(task.task_id))
<add> ti = TaskInstance(task, args.start_date)
<add> ti.dry_run()
<add> else:
<add> dag.run(
<add> start_date=args.start_date,
<add> end_date=args.end_date,
<add> mark_success=args.mark_success,
<add> include_adhoc=args.include_adhoc,
<add> local=args.local,
<add> donot_pickle=args.donot_pickle,
<add> ignore_dependencies=args.ignore_dependencies)
<ide>
<ide>
<ide> def run(args):
<ide> def get_parser():
<ide> parser_backfill.add_argument(
<ide> "-sd", "--subdir", help=subdir_help,
<ide> default=DAGS_FOLDER)
<add> parser_backfill.add_argument(
<add> "-dr", "--dry_run", help="Perform a dry run", action="store_true")
<ide> parser_backfill.set_defaults(func=backfill)
<ide>
<ide> ht = "Clear a set of task instance, as if they never ran" | 1 |
Text | Text | add v3.0.0 to changelog.md | 080ba6643251209dd7f88974955aae5848bdc8e2 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### 3.0.0-beta.6 (February 5, 2018)
<add>### v3.0.0 (February 13, 2018)
<ide>
<add>- [#16218](https://github.com/emberjs/ember.js/pull/16218) [BUGFIX beta] Prevent errors when using const `(get arr 1)`.
<add>- [#16241](https://github.com/emberjs/ember.js/pull/16241) [BUGFIX lts] Avoid excessively calling Glimmer AST transforms.
<ide> - [#16199](https://github.com/emberjs/ember.js/pull/16199) [BUGFIX] Mention "computed properties" in the assertion message
<ide> - [#16200](https://github.com/emberjs/ember.js/pull/16200) [BUGFIX] Prevent test error by converting illegal characters
<del>
<del>### 3.0.0-beta.5 (January 29, 2018)
<del>
<ide> - [#16179](https://github.com/emberjs/ember.js/pull/16179) [BUGFIX] Fix a few bugs in the caching ArrayProxy implementation
<del>
<del>### 3.0.0-beta.4 (January 25, 2018)
<del>
<ide> - [#16160](https://github.com/emberjs/ember.js/pull/16160) [BUGFIX] Remove humanize() call from generated test descriptions
<ide> - [#16101](https://github.com/emberjs/ember.js/pull/16101) [CLEANUP] Remove legacy ArrayProxy features
<ide> - [#16116](https://github.com/emberjs/ember.js/pull/16116) [CLEANUP] Remove private enumerable observers
<ide> - [#16163](https://github.com/emberjs/ember.js/pull/16163) [CLEANUP] Remove unused path caches
<ide> - [#16169](https://github.com/emberjs/ember.js/pull/16169) [BUGFIX] Fix various issues with descriptor trap.
<ide> - [#16174](https://github.com/emberjs/ember.js/pull/16174) [BUGFIX] Enable _some_ recovery of errors thrown during render.
<del>
<del>
<del>### 3.0.0-beta.3 (January 15, 2018)
<del>
<ide> - [#16095](https://github.com/emberjs/ember.js/pull/16095) [CLEANUP] Fix ember-2-legacy support for Ember.Binding.
<ide> - [#16117](https://github.com/emberjs/ember.js/pull/16117) [BUGFIX] link-to active class applied when params change
<ide> - [#16097](https://github.com/emberjs/ember.js/pull/16097) / [#16110](https://github.com/emberjs/ember.js/pull/16110) [CLEANUP] Remove `sync` runloop queue.
<ide> - [#16099](https://github.com/emberjs/ember.js/pull/16099) [CLEANUP] Remove custom eventManager support.
<del>
<del>### 3.0.0-beta.2 (January 8, 2018)
<del>
<ide> - [#16067](https://github.com/emberjs/ember.js/pull/16067) [BUGFIX] Fix issues with `run.debounce` with only method and wait.
<ide> - [#16045](https://github.com/emberjs/ember.js/pull/16045) [BUGFIX] Fix double debug output
<ide> - [#16050](https://github.com/emberjs/ember.js/pull/16050) [BUGFIX] Add inspect and constructor to list of descriptor exceptions
<ide> - [#16080](https://github.com/emberjs/ember.js/pull/16080) [BUGFIX] Add missing modules docs for tryInvoke, compare, isEqual #16079
<ide> - [#16084](https://github.com/emberjs/ember.js/pull/16084) [BUGFIX] Update `computed.sort` docs to avoid state leakage
<ide> - [#16087](https://github.com/emberjs/ember.js/pull/16087) [BUGFIX] Ensure `App.visit` resolves when rendering completed.
<ide> - [#16090](https://github.com/emberjs/ember.js/pull/16090) [CLEANUP] Remove Ember.Binding support
<del>
<del>
<del>### 3.0.0-beta.1 (January 1, 2018)
<del>
<ide> - [#15901](https://github.com/emberjs/ember.js/pull/15901) [CLEANUP] Remove Ember.Handlebars.SafeString
<ide> - [#15894](https://github.com/emberjs/ember.js/pull/15894) [CLEANUP] removed `immediateObserver`
<ide> - [#15897](https://github.com/emberjs/ember.js/pull/15897) [CLEANUP] Remove controller wrapped param deprecation | 1 |
Javascript | Javascript | simplify `console` event handler | a92a7cd003f7202a397aef2bbe95397ffe483034 | <ide><path>bin/run-tests.js
<ide> function runInBrowser(url, retries, resolve, reject) {
<ide>
<ide> puppeteer.launch().then(function(browser) {
<ide> browser.newPage().then(function(page) {
<del> page.on('console', function() {
<add> page.on('console', function(msg) {
<add> console.log(msg.text);
<ide>
<del> var string = Array.prototype.slice.call(arguments).join('');
<del> var lines = string.split('\n');
<del>
<del> lines.forEach(function(line) {
<del> if (line.indexOf('0 failed.') > -1) {
<del> console.log(chalk.green(line));
<del> } else {
<del> console.log(line);
<del> }
<del> });
<del>
<del> result.output.push(string);
<add> result.output.push(msg.text);
<ide> });
<ide>
<ide> page.on('error', function(err) { | 1 |
Text | Text | update doc for android mainapplication.java | 875d5d2364d940f2a7eca2f78b26632e6985aa00 | <ide><path>docs/NativeModulesAndroid.md
<ide> class AnExampleReactPackage implements ReactPackage {
<ide> }
<ide> ```
<ide>
<del>The package needs to be provided in the `getPackages` method of the `MainActivity.java` file. This file exists under the android folder in your react-native application directory. The path to this file is: `android/app/src/main/java/com/your-app-name/MainActivity.java`.
<add>The package needs to be provided in the `getPackages` method of the `MainApplication.java` file. This file exists under the android folder in your react-native application directory. The path to this file is: `android/app/src/main/java/com/your-app-name/MainApplication.java`.
<ide>
<ide> ```java
<ide> protected List<ReactPackage> getPackages() { | 1 |
Text | Text | add the release blockers | 033451d9047e26e472738e3f1973aeff72abd9dd | <ide><path>docs/focus/2018-03-12.md
<ide> - Finish "Remember me" within the credential dialog [#1327](https://github.com/atom/github/pull/1327)
<ide> - Sanitize stderr from git in error notifications [#1331](https://github.com/atom/github/pull/1331)
<ide> - Upgrade MacOS build to CircleCI 2.0 [#1334](https://github.com/atom/github/pull/1334)
<add> - Fix a stack trace when shifting focus to and from the FilePatchView [#1342](https://github.com/atom/github/pull/1342)
<add> - Fix sluggish performance when editing commit messages while a large file patch is visible [#1347](https://github.com/atom/github/pull/1347)
<add> - Fix stack trace caused by upstream changes in Relay [#1344](https://github.com/atom/github/pull/1344)
<ide> - Begin packaging bundled GPG binaries akin to the way we handle git [atom/squeegpg-native](https://github.com/atom/squeegpg-native)
<ide> - Teletype
<ide> - Released [Teletype 0.10.0](https://github.com/atom/teletype/releases/tag/v0.10.0), introducing a streamlined view of your collaborators' avatars inside the editor ([atom/teletype#332](https://github.com/atom/teletype/issues/332)) | 1 |
Python | Python | remove redundant line in run_pl_glue.py | eb2bd8d6eba96db67a59679b16e173ade97ba09d | <ide><path>examples/text-classification/run_pl_glue.py
<ide> def prepare_data(self):
<ide> cached_features_file = self._feature_file(mode)
<ide> if os.path.exists(cached_features_file) and not args.overwrite_cache:
<ide> logger.info("Loading features from cached file %s", cached_features_file)
<del> features = torch.load(cached_features_file)
<ide> else:
<ide> logger.info("Creating features from dataset file at %s", args.data_dir)
<ide> examples = ( | 1 |
PHP | PHP | add union type for expected listener | 75d10c51a9cd08c9f8c95444088d8987febd11ea | <ide><path>src/Illuminate/Support/Facades/Event.php
<ide> * @method static void assertDispatchedTimes(string $event, int $times = 1)
<ide> * @method static void assertNotDispatched(string|\Closure $event, callable|int $callback = null)
<ide> * @method static void assertNothingDispatched()
<del> * @method static void assertListening(string $expectedEvent, string $expectedListener)
<add> * @method static void assertListening(string $expectedEvent, string|array $expectedListener)
<ide> * @method static void flush(string $event)
<ide> * @method static void forget(string $event)
<ide> * @method static void forgetPushed() | 1 |
Javascript | Javascript | remove \t \n \r in url.parse() similar to whatwg | fa7e08cfc9fdc6f58cef7af6443d2d2070aa541b | <ide><path>lib/url.js
<ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
<ide> case CHAR_TAB:
<ide> case CHAR_LINE_FEED:
<ide> case CHAR_CARRIAGE_RETURN:
<add> // WHATWG URL removes tabs, newlines, and carriage returns. Let's do that too.
<add> rest = rest.slice(0, i) + rest.slice(i + 1);
<add> i -= 1;
<add> break;
<ide> case CHAR_SPACE:
<ide> case CHAR_DOUBLE_QUOTE:
<ide> case CHAR_PERCENT:
<ide><path>test/parallel/test-url-parse-format.js
<ide> const parseTests = {
<ide> 'http://a\r" \t\n<\'b:b@c\r\nd/e?f': {
<ide> protocol: 'http:',
<ide> slashes: true,
<del> auth: 'a\r" \t\n<\'b:b',
<del> host: 'c',
<add> auth: 'a" <\'b:b',
<add> host: 'cd',
<ide> port: null,
<del> hostname: 'c',
<add> hostname: 'cd',
<ide> hash: null,
<ide> search: '?f',
<ide> query: 'f',
<del> pathname: '%0D%0Ad/e',
<del> path: '%0D%0Ad/e?f',
<del> href: 'http://a%0D%22%20%09%0A%3C\'b:b@c/%0D%0Ad/e?f'
<add> pathname: '/e',
<add> path: '/e?f',
<add> href: 'http://a%22%20%3C\'b:b@cd/e?f'
<ide> },
<ide>
<ide> 'https://*': {
<ide> for (const u in parseTests) {
<ide> assert.deepStrictEqual(
<ide> actual,
<ide> expected,
<del> `expected ${inspect(expected)}, got ${inspect(actual)}`
<add> `parsing ${u} and expected ${inspect(expected)} but got ${inspect(actual)}`
<ide> );
<ide> assert.deepStrictEqual(
<ide> spaced, | 2 |
Ruby | Ruby | remove misleading reference to polymorphic_url | 28185ebc2ee501e6acecc18569f110fd33acde47 | <ide><path>actionpack/lib/action_controller/metal/responder.rb
<ide> module ActionController #:nodoc:
<ide> #
<ide> # respond_with(@project, :manager, @task)
<ide> #
<del> # Check <code>polymorphic_url</code> documentation for more examples.
<del> #
<ide> class Responder
<ide> attr_reader :controller, :request, :format, :resource, :resources, :options
<ide> | 1 |
Python | Python | simplify skipping of integer types in _add_aliases | 38e709522b754a2297b3119e7c80bf5811539fc7 | <ide><path>numpy/core/numerictypes.py
<ide> def _add_types():
<ide> allTypes[name] = info
<ide> _add_types()
<ide>
<add># This is the priority order used to assign the bit-sized NPY_INTxx names, which
<add># must match the order in npy_common.h in order for NPY_INTxx and np.intxx to be
<add># consistent.
<add># If two C types have the same size, then the earliest one in this list is used
<add># as the sized name.
<add>_int_ctypes = ['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE']
<add>_uint_ctypes = list('U' + t for t in _int_ctypes)
<add>
<ide> def _add_aliases():
<ide> for type_name, info in typeinfo.items():
<ide> if isinstance(info, type):
<ide> continue
<add>
<add> # these are handled by _add_integer_aliases
<add> if type_name in _int_ctypes or type_name in _uint_ctypes:
<add> continue
<ide> name = english_lower(type_name)
<ide>
<ide> # insert bit-width version for this class (if relevant)
<ide> base, bit, char = bitname(info.type)
<del> if base[-3:] == 'int' or char[0] in 'ui':
<del> continue
<ide> if base != '':
<ide> myname = "%s%d" % (base, bit)
<ide> if (name not in ('longdouble', 'clongdouble') or
<ide> def _add_aliases():
<ide> sctypeNA[char] = na_name
<ide> _add_aliases()
<ide>
<del># Integers are handled so that the int32 and int64 types should agree
<del># exactly with NPY_INT32, NPY_INT64. We need to enforce the same checking
<del># as is done in arrayobject.h where the order of getting a bit-width match
<del># is long, longlong, int, short, char.
<ide> def _add_integer_aliases():
<del> _ctypes = ['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE']
<ide> seen_bits = set()
<del> for ctype in _ctypes:
<del> i_info = typeinfo[ctype]
<del> u_info = typeinfo['U'+ctype]
<add> for i_ctype, u_ctype in zip(_int_ctypes, _uint_ctypes):
<add> i_info = typeinfo[i_ctype]
<add> u_info = typeinfo[u_ctype]
<ide> bits = i_info.bits # same for both
<ide>
<ide> for info, charname, intname, Intname in [ | 1 |
Python | Python | change trunk to version 1.1 | dcad2cefe8a76b72e7ab93498db61edac41d5748 | <ide><path>numpy/version.py
<del>version='0.9.9'
<add>version='1.1'
<ide>
<ide> import os
<ide> svn_version_file = os.path.join(os.path.dirname(__file__), | 1 |
Javascript | Javascript | replace var to let/const | ce8f01cf0c3a3b31b35353ec0de665cb04c8a6bc | <ide><path>tools/eslint-rules/crypto-check.js
<ide> const bindingModules = cryptoModules.concat(['tls_wrap']);
<ide> module.exports = function(context) {
<ide> const missingCheckNodes = [];
<ide> const requireNodes = [];
<del> var commonModuleNode = null;
<del> var hasSkipCall = false;
<add> let commonModuleNode = null;
<add> let hasSkipCall = false;
<ide>
<ide> function testCryptoUsage(node) {
<ide> if (utils.isRequired(node, requireModules) ||
<ide><path>tools/eslint-rules/eslint-check.js
<ide> const msg = 'Please add a skipIfEslintMissing() call to allow this test to ' +
<ide>
<ide> module.exports = function(context) {
<ide> const missingCheckNodes = [];
<del> var commonModuleNode = null;
<del> var hasEslintCheck = false;
<add> let commonModuleNode = null;
<add> let hasEslintCheck = false;
<ide>
<ide> function testEslintUsage(context, node) {
<ide> if (utils.isRequired(node, ['../../tools/node_modules/eslint'])) {
<ide><path>tools/eslint-rules/inspector-check.js
<ide> const msg = 'Please add a skipIfInspectorDisabled() call to allow this ' +
<ide>
<ide> module.exports = function(context) {
<ide> const missingCheckNodes = [];
<del> var commonModuleNode = null;
<del> var hasInspectorCheck = false;
<add> let commonModuleNode = null;
<add> let hasInspectorCheck = false;
<ide>
<ide> function testInspectorUsage(context, node) {
<ide> if (utils.isRequired(node, ['inspector'])) {
<ide><path>tools/eslint-rules/no-unescaped-regexp-dot.js
<ide> module.exports = function(context) {
<ide> const sourceCode = context.getSourceCode();
<ide> const regexpStack = [];
<del> var regexpBuffer = [];
<del> var inRegExp = false;
<add> let regexpBuffer = [];
<add> let inRegExp = false;
<ide>
<ide> function report(node, startOffset) {
<ide> const indexOfDot = sourceCode.getIndexFromLoc(node.loc.start) + startOffset;
<ide> module.exports = function(context) {
<ide>
<ide> const allowedModifiers = ['+', '*', '?', '{'];
<ide> function checkRegExp(nodes) {
<del> var escaping = false;
<del> var inCharClass = false;
<del> for (var n = 0; n < nodes.length; ++n) {
<add> let escaping = false;
<add> let inCharClass = false;
<add> for (let n = 0; n < nodes.length; ++n) {
<ide> const pair = nodes[n];
<ide> const node = pair[0];
<ide> const str = pair[1];
<del> for (var i = 0; i < str.length; ++i) {
<add> for (let i = 0; i < str.length; ++i) {
<ide> switch (str[i]) {
<ide> case '[':
<ide> if (!escaping)
<ide> module.exports = function(context) {
<ide> node.quasis.length);
<ide> if (inRegExp &&
<ide> (isTemplate || (typeof node.value === 'string' && node.value.length))) {
<del> var p = node.parent;
<add> let p = node.parent;
<ide> while (p && p.type === 'BinaryExpression') {
<ide> p = p.parent;
<ide> }
<ide> module.exports = function(context) {
<ide> p.callee.name === 'RegExp') {
<ide> if (isTemplate) {
<ide> const quasis = node.quasis;
<del> for (var i = 0; i < quasis.length; ++i) {
<add> for (let i = 0; i < quasis.length; ++i) {
<ide> const el = quasis[i];
<ide> if (el.type === 'TemplateElement' && el.value && el.value.cooked)
<ide> regexpBuffer.push([el, el.value.cooked]);
<ide><path>tools/eslint-rules/prefer-assert-iferror.js
<ide> const utils = require('./rules-utils.js');
<ide> module.exports = {
<ide> create(context) {
<ide> const sourceCode = context.getSourceCode();
<del> var assertImported = false;
<add> let assertImported = false;
<ide>
<ide> function hasSameTokens(nodeA, nodeB) {
<ide> const aTokens = sourceCode.getTokens(nodeA);
<ide><path>tools/eslint-rules/required-modules.js
<ide> const path = require('path');
<ide>
<ide> module.exports = function(context) {
<ide> // trim required module names
<del> var requiredModules = context.options;
<add> const requiredModules = context.options;
<ide> const isESM = context.parserOptions.sourceType === 'module';
<ide>
<ide> const foundModules = [];
<ide> module.exports = function(context) {
<ide> * @returns {undefined|String} required module name or undefined
<ide> */
<ide> function getRequiredModuleName(str) {
<del> var value = path.basename(str);
<add> const value = path.basename(str);
<ide>
<ide> // Check if value is in required modules array
<ide> return requiredModules.indexOf(value) !== -1 ? value : undefined;
<ide> module.exports = function(context) {
<ide> const rules = {
<ide> 'Program:exit'(node) {
<ide> if (foundModules.length < requiredModules.length) {
<del> var missingModules = requiredModules.filter(
<add> const missingModules = requiredModules.filter(
<ide> (module) => foundModules.indexOf(module) === -1
<ide> );
<ide> missingModules.forEach((moduleName) => {
<ide> module.exports = function(context) {
<ide>
<ide> if (isESM) {
<ide> rules.ImportDeclaration = (node) => {
<del> var requiredModuleName = getRequiredModuleName(node.source.value);
<add> const requiredModuleName = getRequiredModuleName(node.source.value);
<ide> if (requiredModuleName) {
<ide> foundModules.push(requiredModuleName);
<ide> }
<ide> };
<ide> } else {
<ide> rules.CallExpression = (node) => {
<ide> if (isRequireCall(node)) {
<del> var requiredModuleName = getRequiredModuleNameFromCall(node);
<add> const requiredModuleName = getRequiredModuleNameFromCall(node);
<ide>
<ide> if (requiredModuleName) {
<ide> foundModules.push(requiredModuleName);
<ide><path>tools/eslint-rules/rules-utils.js
<ide> module.exports.isRequired = function(node, modules) {
<ide> * Return true if common module is required
<ide> * in AST Node under inspection
<ide> */
<del>var commonModuleRegExp = new RegExp(/^(\.\.\/)*common(\.js)?$/);
<add>const commonModuleRegExp = new RegExp(/^(\.\.\/)*common(\.js)?$/);
<ide> module.exports.isCommonModule = function(node) {
<ide> return node.callee.name === 'require' &&
<ide> node.arguments.length !== 0 &&
<ide> module.exports.usesCommonProperty = function(node, properties) {
<ide> * and the block also has a call to skip.
<ide> */
<ide> module.exports.inSkipBlock = function(node) {
<del> var hasSkipBlock = false;
<add> let hasSkipBlock = false;
<ide> if (node.test &&
<ide> node.test.type === 'UnaryExpression' &&
<ide> node.test.operator === '!') {
<ide><path>tools/lint-js.js
<ide> if (process.argv.indexOf('-F') !== -1)
<ide> const cli = new CLIEngine(cliOptions);
<ide>
<ide> if (cluster.isMaster) {
<del> var numCPUs = 1;
<add> let numCPUs = 1;
<ide> const paths = [];
<del> var files = null;
<del> var totalPaths = 0;
<del> var failures = 0;
<del> var successes = 0;
<del> var lastLineLen = 0;
<del> var curPath = 'Starting ...';
<del> var showProgress = true;
<add> let files = null;
<add> let totalPaths = 0;
<add> let failures = 0;
<add> let successes = 0;
<add> let lastLineLen = 0;
<add> let curPath = 'Starting ...';
<add> let showProgress = true;
<ide> const globOptions = {
<ide> nodir: true
<ide> };
<ide> const workerConfig = {};
<del> var startTime;
<del> var formatter;
<del> var outFn;
<del> var fd;
<del> var i;
<add> let startTime;
<add> let formatter;
<add> let outFn;
<add> let fd;
<add> let i;
<ide>
<ide> // Check if spreading work among all cores/cpus
<ide> if (process.argv.indexOf('-J') !== -1)
<ide> if (cluster.isMaster) {
<ide> // We either just started or we have no more files to lint for the current
<ide> // path. Find the next path that has some files to be linted.
<ide> while (paths.length) {
<del> var dir = paths.shift();
<add> let dir = paths.shift();
<ide> curPath = dir;
<ide> const patterns = cli.resolveFileGlobPatterns([dir]);
<ide> dir = path.resolve(patterns[0]);
<ide> if (cluster.isMaster) {
<ide> // workers busy most of the time instead of only a minority doing most of
<ide> // the work.
<ide> const sliceLen = Math.min(maxWorkload, Math.ceil(files.length / numCPUs));
<del> var slice;
<add> let slice;
<ide> if (sliceLen === files.length) {
<ide> // Micro-optimization to avoid splicing to an empty array
<ide> slice = files;
<ide> if (cluster.isMaster) {
<ide> const secs = `${elapsed % 60}`.padStart(2, '0');
<ide> const passed = `${successes}`.padStart(6);
<ide> const failed = `${failures}`.padStart(6);
<del> var pct = Math.ceil(((totalPaths - paths.length) / totalPaths) * 100);
<del> pct = `${pct}`.padStart(3);
<add> let pct = `${Math.ceil(((totalPaths - paths.length) / totalPaths) * 100)}`;
<add> pct = pct.padStart(3);
<ide>
<del> var line = `[${mins}:${secs}|%${pct}|+${passed}|-${failed}]: ${curPath}`;
<add> let line = `[${mins}:${secs}|%${pct}|+${passed}|-${failed}]: ${curPath}`;
<ide>
<ide> // Truncate line like cpplint does in case it gets too long
<ide> if (line.length > 75)
<ide> if (cluster.isMaster) {
<ide> } else {
<ide> // Worker
<ide>
<del> var config = {};
<add> let config = {};
<ide> process.on('message', (files) => {
<ide> if (files instanceof Array) {
<ide> // Lint some files
<ide> if (cluster.isMaster) {
<ide> // Silence warnings for files with no errors while keeping the "ok"
<ide> // status
<ide> if (report.warningCount > 0) {
<del> for (var i = 0; i < results.length; ++i) {
<add> for (let i = 0; i < results.length; ++i) {
<ide> const result = results[i];
<ide> if (result.errorCount === 0 && result.warningCount > 0) {
<ide> result.warningCount = 0; | 8 |
Javascript | Javascript | add redirectsto in routes | 91a8975b8d3a0b873b421f1dbc4ea41f92c92bc2 | <ide><path>packages/ember-states/lib/routable.js
<ide> var paramForClass = function(classObject) {
<ide>
<ide> Ember.Routable = Ember.Mixin.create({
<ide> init: function() {
<add> var redirection;
<ide> this.on('connectOutlets', this, this.stashContext);
<ide>
<add> if (redirection = get(this, 'redirectsTo')) {
<add> Ember.assert("You cannot use `redirectsTo` if you already have a `connectOutlets` method", this.connectOutlets === Ember.K);
<add>
<add> this.connectOutlets = function(router) {
<add> router.transitionTo(redirection);
<add> };
<add> }
<add>
<ide> this._super();
<add>
<add> Ember.assert("You cannot use `redirectsTo` on a state that has child states", !redirection || (!!redirection && !!get(this, 'isLeaf')));
<ide> },
<ide>
<ide> stashContext: function(manager, context) {
<ide><path>packages/ember-states/tests/routable_test.js
<ide> test("should use a specified String `modelType` in the default `deserialize`", f
<ide>
<ide> router.route("/posts/1");
<ide> });
<add>
<add>module("redirectsTo");
<add>
<add>test("if a leaf state has a redirectsTo, it automatically transitions into that state", function() {
<add> var router = Ember.Router.create({
<add> initialState: 'root',
<add> root: Ember.State.create({
<add>
<add> index: Ember.State.create({
<add> route: '/',
<add> redirectsTo: 'someOtherState'
<add> }),
<add>
<add> someOtherState: Ember.State.create({
<add> route: '/other'
<add> })
<add> })
<add> });
<add>
<add> Ember.run(function() {
<add> router.route("/");
<add> });
<add>
<add> equal(router.getPath('currentState.path'), "root.someOtherState");
<add>});
<add>
<add>test("you cannot define connectOutlets AND redirectsTo", function() {
<add> raises(function() {
<add> Ember.Router.create({
<add> initialState: 'root',
<add> root: Ember.State.create({
<add> index: Ember.State.create({
<add> route: '/',
<add> redirectsTo: 'someOtherState',
<add> connectOutlets: function() {}
<add> })
<add> })
<add> });
<add> });
<add>});
<add>
<add>test("you cannot have a redirectsTo in a non-leaf state", function () {
<add> raises(function() {
<add> Ember.Router.create({
<add> initialState: 'root',
<add> root: Ember.State.create({
<add> redirectsTo: 'someOtherState',
<add>
<add> index: Ember.State.create()
<add> })
<add> });
<add> });
<add>}); | 2 |
Text | Text | add format examples | a61f86551815f023666921dc6169c59751772a7f | <ide><path>docs/api-guide/fields.md
<ide> A field that ensures the input is a valid UUID string. The `to_internal_value` m
<ide> **Signature:** `UUIDField(format='hex_verbose')`
<ide>
<ide> - `format`: Determines the representation format of the uuid value
<del> - `'hex_verbose'` - The cannoncical hex representation, including hyphens
<del> - `'hex'` - The compact hex representation of the UUID, not including hyphens
<del> - `'int'` - A 128 bit integer representation of the UUID.
<del> - `'urn'` - RFC 4122 URN representation of the UUID
<add> - `'hex_verbose'` - The cannoncical hex representation, including hyphens: "5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
<add> - `'hex'` - The compact hex representation of the UUID, not including hyphens: "5ce0e9a55ffa654bcee01238041fb31a"
<add> - `'int'` - A 128 bit integer representation of the UUID: "123456789012312313134124512351145145114"
<add> - `'urn'` - RFC 4122 URN representation of the UUID: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
<ide> Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
<ide>
<ide> --- | 1 |
Go | Go | add test for parsenetmode | 7118416aeeb779373685d192c26a329e9acdef89 | <ide><path>runconfig/parse.go
<ide> func parseKeyValueOpts(opts opts.ListOpts) ([]utils.KeyValuePair, error) {
<ide>
<ide> func parseNetMode(netMode string) (string, string, error) {
<ide> parts := strings.Split(netMode, ":")
<del> if len(parts) < 1 {
<del> return "", "", fmt.Errorf("'netmode' cannot be empty", netMode)
<del> }
<del> mode := parts[0]
<del> var container string
<del> if mode == "container" {
<del> if len(parts) < 2 {
<add> switch mode := parts[0]; mode {
<add> case "bridge", "disable":
<add> return mode, "", nil
<add> case "container":
<add> var container string
<add> if len(parts) < 2 || parts[1] == "" {
<ide> return "", "", fmt.Errorf("'container:' netmode requires a container id or name", netMode)
<ide> }
<ide> container = parts[1]
<add> return mode, container, nil
<add> default:
<add> return "", "", fmt.Errorf("invalid netmode: %q", netMode)
<ide> }
<del> return mode, container, nil
<ide> }
<ide><path>runconfig/parse_test.go
<ide> package runconfig
<ide>
<ide> import (
<del> "github.com/dotcloud/docker/utils"
<ide> "testing"
<add>
<add> "github.com/dotcloud/docker/utils"
<ide> )
<ide>
<ide> func TestParseLxcConfOpt(t *testing.T) {
<ide> func TestParseLxcConfOpt(t *testing.T) {
<ide> }
<ide> }
<ide> }
<add>
<add>func TestParseNetMode(t *testing.T) {
<add> testFlags := []struct {
<add> flag string
<add> mode string
<add> container string
<add> err bool
<add> }{
<add> {"", "", "", true},
<add> {"bridge", "bridge", "", false},
<add> {"disable", "disable", "", false},
<add> {"container:foo", "container", "foo", false},
<add> {"container:", "", "", true},
<add> {"container", "", "", true},
<add> {"unknown", "", "", true},
<add> }
<add>
<add> for _, to := range testFlags {
<add> mode, container, err := parseNetMode(to.flag)
<add> if mode != to.mode {
<add> t.Fatalf("-net %s: expected net mode: %q, got: %q", to.flag, to.mode, mode)
<add> }
<add> if container != to.container {
<add> t.Fatalf("-net %s: expected net container: %q, got: %q", to.flag, to.container, container)
<add> }
<add> if (err != nil) != to.err {
<add> t.Fatal("-net %s: expected an error got none", to.flag)
<add> }
<add> }
<add>} | 2 |
Javascript | Javascript | update openssl 3.x expected error message | 7216eb67dfc93d88570cf3c02b4321211593f13a | <ide><path>test/parallel/test-crypto-dh.js
<ide> if (common.hasOpenSSL3) {
<ide> assert.throws(() => {
<ide> dh3.computeSecret('');
<ide> }, { message: common.hasOpenSSL3 ?
<del> 'error:02800066:Diffie-Hellman routines::invalid public key' :
<add> 'error:02800080:Diffie-Hellman routines::invalid secret' :
<ide> 'Supplied key is too small' });
<ide>
<ide> // Create a shared using a DH group. | 1 |
PHP | PHP | fix failing test | ef508e785b34547dbfc1473b46dbae53a4541806 | <ide><path>tests/TestCase/Error/DebuggerTest.php
<ide> public function testExportVar() {
<ide> request => object(Cake\Network\Request) {}
<ide> response => object(Cake\Network\Response) {}
<ide> elementCache => 'default'
<del> elementCacheSettings => []
<ide> viewVars => []
<ide> Html => object(Cake\View\Helper\HtmlHelper) {}
<ide> Form => object(Cake\View\Helper\FormHelper) {} | 1 |
Javascript | Javascript | improve arrayclone performance | 4ba90809edec189a2c4662258ef6cadb9d9620b4 | <ide><path>benchmark/events/ee-emit.js
<ide> const bench = common.createBenchmark(main, {
<ide>
<ide> function main({ n, argc, listeners }) {
<ide> const ee = new EventEmitter();
<add> ee.setMaxListeners(listeners + 1);
<ide>
<ide> for (let k = 0; k < listeners; k += 1)
<ide> ee.on('dummy', () => {});
<ide><path>benchmark/events/ee-listeners-many.js
<del>'use strict';
<del>const common = require('../common.js');
<del>const EventEmitter = require('events').EventEmitter;
<del>
<del>const bench = common.createBenchmark(main, { n: [5e6] });
<del>
<del>function main({ n }) {
<del> const ee = new EventEmitter();
<del> ee.setMaxListeners(101);
<del>
<del> for (let k = 0; k < 50; k += 1) {
<del> ee.on('dummy0', () => {});
<del> ee.on('dummy1', () => {});
<del> }
<del>
<del> bench.start();
<del> for (let i = 0; i < n; i += 1) {
<del> const dummy = (i % 2 === 0) ? 'dummy0' : 'dummy1';
<del> ee.listeners(dummy);
<del> }
<del> bench.end(n);
<del>}
<ide><path>benchmark/events/ee-listeners.js
<ide> const common = require('../common.js');
<ide> const EventEmitter = require('events').EventEmitter;
<ide>
<del>const bench = common.createBenchmark(main, { n: [5e6] });
<add>const bench = common.createBenchmark(main, {
<add> n: [5e6],
<add> listeners: [5, 50],
<add> raw: ['true', 'false']
<add>});
<ide>
<del>function main({ n }) {
<add>function main({ n, listeners, raw }) {
<ide> const ee = new EventEmitter();
<add> ee.setMaxListeners(listeners * 2 + 1);
<ide>
<del> for (let k = 0; k < 5; k += 1) {
<add> for (let k = 0; k < listeners; k += 1) {
<ide> ee.on('dummy0', () => {});
<ide> ee.on('dummy1', () => {});
<ide> }
<ide>
<del> bench.start();
<del> for (let i = 0; i < n; i += 1) {
<del> const dummy = (i % 2 === 0) ? 'dummy0' : 'dummy1';
<del> ee.listeners(dummy);
<add> if (raw === 'true') {
<add> bench.start();
<add> for (let i = 0; i < n; i += 1) {
<add> const dummy = (i % 2 === 0) ? 'dummy0' : 'dummy1';
<add> ee.rawListeners(dummy);
<add> }
<add> bench.end(n);
<add> } else {
<add> bench.start();
<add> for (let i = 0; i < n; i += 1) {
<add> const dummy = (i % 2 === 0) ? 'dummy0' : 'dummy1';
<add> ee.listeners(dummy);
<add> }
<add> bench.end(n);
<ide> }
<del> bench.end(n);
<ide> }
<ide><path>lib/events.js
<ide> EventEmitter.prototype.emit = function emit(type, ...args) {
<ide> }
<ide> } else {
<ide> const len = handler.length;
<del> const listeners = arrayClone(handler, len);
<add> const listeners = arrayClone(handler);
<ide> for (let i = 0; i < len; ++i) {
<ide> const result = ReflectApply(listeners[i], this, args);
<ide>
<ide> function _listeners(target, type, unwrap) {
<ide> return unwrap ? [evlistener.listener || evlistener] : [evlistener];
<ide>
<ide> return unwrap ?
<del> unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
<add> unwrapListeners(evlistener) : arrayClone(evlistener);
<ide> }
<ide>
<ide> EventEmitter.prototype.listeners = function listeners(type) {
<ide> EventEmitter.prototype.eventNames = function eventNames() {
<ide> return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
<ide> };
<ide>
<del>function arrayClone(arr, n) {
<del> const copy = new Array(n);
<del> for (let i = 0; i < n; ++i)
<del> copy[i] = arr[i];
<del> return copy;
<add>function arrayClone(arr) {
<add> // At least since V8 8.3, this implementation is faster than the previous
<add> // which always used a simple for-loop
<add> switch (arr.length) {
<add> case 2: return [arr[0], arr[1]];
<add> case 3: return [arr[0], arr[1], arr[2]];
<add> case 4: return [arr[0], arr[1], arr[2], arr[3]];
<add> case 5: return [arr[0], arr[1], arr[2], arr[3], arr[4]];
<add> case 6: return [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]];
<add> }
<add> return arr.slice();
<ide> }
<ide>
<ide> function unwrapListeners(arr) { | 4 |
Text | Text | add option for developer tools inside browsers | cef06eac6b9154f14c35dc49e61fea0f1c263853 | <ide><path>guide/spanish/developer-tools/index.md
<ide> Algunos ejemplos de estas herramientas:
<ide> * Sistemas de control de versiones
<ide> * Herramientas devOps
<ide> * Construir herramientas
<del>* Gestores de paquetes
<ide>\ No newline at end of file
<add>* Gestores de paquetes
<add>* Herramientas de desarrollador en los navegadores | 1 |
Text | Text | update translation of index.md | 998264c2e904314f19571828024d1b83f221b423 | <ide><path>guide/portuguese/user-experience-design/index.md
<ide> localeTitle: Design de experiência do usuário
<ide> ---
<ide> ## Design de experiência do usuário
<ide>
<del>User Experience Design é um campo que se concentra em como os usuários finais de um produto interagem com ele e como eles se sentem em relação ao produto.
<add>Design de experiência do usuário é um campo que se concentra em como os usuários finais de um produto interagem com ele e como eles se sentem em relação ao produto. Design de experiência de abrange uma ampla gama de aspectos relacionados com um produto e não só com o aspecto visual (como o GUI). Um designer de UX é responsável pela experiência geral que os usuários finais tem com o produto e assim, a função do designer de UX poderia se extender da parte comercial do produto, como comércio e pesquisa de usuário, para os aspectos gráficos como o GUI, Interaction Design (as vezes conhecido como IxD) e Sound Design. Devido à ampla área que um designer de UX abrange, não é incomum que as pessoas se ramificam e se especializam em certos aspectos do campo experiência do usuário como, pesquisa de usuário, interfaces de usuário, interações de usuário, motion design, copywriter, etc.
<ide>
<ide> Nesta seção, teremos guias para uma ampla variedade de conceitos de design de experiência do usuário.
<ide>
<ide> Nesta seção, teremos guias para uma ampla variedade de conceitos de design de
<ide>
<ide> #### Principalmente Currículo de Design UX Online Grátis
<ide>
<del>[Caminho de aprendizado do Springboard: Design de experiência do usuário - Julia Debari](https://www.springboard.com/learning-paths/user-experience-design/learn/#)
<ide>\ No newline at end of file
<add>[Caminho de aprendizado do Springboard: Design de experiência do usuário - Julia Debari](https://www.springboard.com/learning-paths/user-experience-design/learn/#) | 1 |
Javascript | Javascript | remove minor typo in webpackoptionsapply | 96ad1c65a6d4c69560be640068f0c208b76ed2f3 | <ide><path>lib/WebpackOptionsApply.js
<ide> class WebpackOptionsApply extends OptionsApply {
<ide> if (!options.experiments.outputModule) {
<ide> if (options.output.module) {
<ide> throw new Error(
<del> "'output.module: true' is only allowed when 'experiements.outputModule' is enabled"
<add> "'output.module: true' is only allowed when 'experiments.outputModule' is enabled"
<ide> );
<ide> }
<ide> if (options.output.libraryTarget === "module") {
<ide> throw new Error(
<del> "'output.libraryTarget: \"module\"' is only allowed when 'experiements.outputModule' is enabled"
<add> "'output.libraryTarget: \"module\"' is only allowed when 'experiments.outputModule' is enabled"
<ide> );
<ide> }
<ide> } | 1 |
Javascript | Javascript | replace anonymous closure function | a19a2689eabc9fe2e8083a564e9d29ee746a91ec | <ide><path>test/parallel/test-http-pipeline-socket-parser-typeerror.js
<ide> let more;
<ide> let done;
<ide>
<ide> const server = http
<del> .createServer(function(req, res) {
<add> .createServer((req, res) => {
<ide> if (!once) server.close();
<ide> once = true;
<ide>
<ide> const server = http
<ide> }
<ide> done();
<ide> })
<del> .on('upgrade', function(req, socket) {
<del> second.end(chunk, function() {
<add> .on('upgrade', (req, socket) => {
<add> second.end(chunk, () => {
<ide> socket.end();
<ide> });
<ide> first.end('hello');
<ide> })
<del> .listen(0, function() {
<del> const s = net.connect(this.address().port);
<del> more = function() {
<add> .listen(0, () => {
<add> const s = net.connect(server.address().port);
<add> more = () => {
<ide> s.write('GET / HTTP/1.1\r\n\r\n');
<ide> };
<del> done = function() {
<add> done = () => {
<ide> s.write(
<ide> 'GET / HTTP/1.1\r\n\r\n' +
<ide> 'GET / HTTP/1.1\r\nConnection: upgrade\r\nUpgrade: ws\r\n\r\naaa' | 1 |
Text | Text | remove license from guide | be04413f4d9cfbbe2cb88315aa110606b8fcd948 | <ide><path>client/src/pages/guide/LICENSE.md
<del>Attribution-ShareAlike 4.0 International
<del>
<del>=======================================================================
<del>
<del>Creative Commons Corporation ("Creative Commons") is not a law firm and does not
<del>provide legal services or legal advice. Distribution of Creative Commons public
<del>licenses does not create a lawyer-client or other relationship. Creative Commons
<del>makes its licenses and related information available on an "as-is" basis.
<del>Creative Commons gives no warranties regarding its licenses, any material
<del>licensed under their terms and conditions, or any related information. Creative
<del>Commons disclaims all liability for damages resulting from their use to the
<del>fullest extent possible.
<del>
<del>Using Creative Commons Public Licenses
<del>
<del>Creative Commons public licenses provide a standard set of terms and conditions
<del>that creators and other rights holders may use to share original works of
<del>authorship and other material subject to copyright and certain other rights
<del>specified in the public license below. The following considerations are for
<del>informational purposes only, are not exhaustive, and do not form part of our
<del>licenses.
<del>
<del> Considerations for licensors: Our public licenses are
<del> intended for use by those authorized to give the public
<del> permission to use material in ways otherwise restricted by
<del> copyright and certain other rights. Our licenses are
<del> irrevocable. Licensors should read and understand the terms
<del> and conditions of the license they choose before applying it.
<del> Licensors should also secure all rights necessary before
<del> applying our licenses so that the public can reuse the
<del> material as expected. Licensors should clearly mark any
<del> material not subject to the license. This includes other CC-
<del> licensed material, or material used under an exception or
<del> limitation to copyright. More considerations for licensors:
<del>
<del>wiki.creativecommons.org/Considerations_for_licensors
<del>
<del> Considerations for the public: By using one of our public
<del> licenses, a licensor grants the public permission to use the
<del> licensed material under specified terms and conditions. If
<del> the licensor's permission is not necessary for any reason--for
<del> example, because of any applicable exception or limitation to
<del> copyright--then that use is not regulated by the license. Our
<del> licenses grant only permissions under copyright and certain
<del> other rights that a licensor has authority to grant. Use of
<del> the licensed material may still be restricted for other
<del> reasons, including because others have copyright or other
<del> rights in the material. A licensor may make special requests,
<del> such as asking that all changes be marked or described.
<del> Although not required by our licenses, you are encouraged to
<del> respect those requests where reasonable. More_considerations
<del> for the public:
<del>
<del>wiki.creativecommons.org/Considerations_for_licensees
<del>
<del>=======================================================================
<del>
<del>Creative Commons Attribution-ShareAlike 4.0 International Public License
<del>
<del>By exercising the Licensed Rights (defined below), You accept and agree to be
<del>bound by the terms and conditions of this Creative Commons
<del>Attribution-ShareAlike 4.0 International Public License ("Public License"). To
<del>the extent this Public License may be interpreted as a contract, You are granted
<del>the Licensed Rights in consideration of Your acceptance of these terms and
<del>conditions, and the Licensor grants You such rights in consideration of benefits
<del>the Licensor receives from making the Licensed Material available under these
<del>terms and conditions.
<del>
<del>Section 1 -- Definitions.
<del>
<del>a. Adapted Material means material subject to Copyright and Similar Rights that
<del>is derived from or based upon the Licensed Material and in which the Licensed
<del>Material is translated, altered, arranged, transformed, or otherwise modified in
<del>a manner requiring permission under the Copyright and Similar Rights held by the
<del>Licensor. For purposes of this Public License, where the Licensed Material is a
<del>musical work, performance, or sound recording, Adapted Material is always
<del>produced where the Licensed Material is synched in timed relation with a moving
<del>image.
<del>
<del>b. Adapter's License means the license You apply to Your Copyright and Similar
<del>Rights in Your contributions to Adapted Material in accordance with the terms
<del>and conditions of this Public License.
<del>
<del>c. BY-SA Compatible License means a license listed at
<del>creativecommons.org/compatiblelicenses, approved by Creative Commons as
<del>essentially the equivalent of this Public License.
<del>
<del>d. Copyright and Similar Rights means copyright and/or similar rights closely
<del>related to copyright including, without limitation, performance, broadcast,
<del>sound recording, and Sui Generis Database Rights, without regard to how the
<del>rights are labeled or categorized. For purposes of this Public License, the
<del>rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
<del>
<del>e. Effective Technological Measures means those measures that, in the absence of
<del>proper authority, may not be circumvented under laws fulfilling obligations
<del>under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996,
<del>and/or similar international agreements.
<del>
<del>f. Exceptions and Limitations means fair use, fair dealing, and/or any other
<del>exception or limitation to Copyright and Similar Rights that applies to Your use
<del>of the Licensed Material.
<del>
<del>g. License Elements means the license attributes listed in the name of a
<del>Creative Commons Public License. The License Elements of this Public License are
<del>Attribution and ShareAlike.
<del>
<del>h. Licensed Material means the artistic or literary work, database, or other
<del>material to which the Licensor applied this Public License.
<del>
<del>i. Licensed Rights means the rights granted to You subject to the terms and
<del>conditions of this Public License, which are limited to all Copyright and
<del>Similar Rights that apply to Your use of the Licensed Material and that the
<del>Licensor has authority to license.
<del>
<del>j. Licensor means the individual(s) or entity(ies) granting rights under this
<del>Public License.
<del>
<del>k. Share means to provide material to the public by any means or process that
<del>requires permission under the Licensed Rights, such as reproduction, public
<del>display, public performance, distribution, dissemination, communication, or
<del>importation, and to make material available to the public including in ways that
<del>members of the public may access the material from a place and at a time
<del>individually chosen by them.
<del>
<del>l. Sui Generis Database Rights means rights other than copyright resulting from
<del>Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996
<del>on the legal protection of databases, as amended and/or succeeded, as well as
<del>other essentially equivalent rights anywhere in the world.
<del>
<del>m. You means the individual or entity exercising the Licensed Rights under this
<del>Public License. Your has a corresponding meaning.
<del>
<del>Section 2 -- Scope.
<del>
<del>a. License grant.
<del>
<del> 1. Subject to the terms and conditions of this Public License,
<del> the Licensor hereby grants You a worldwide, royalty-free,
<del> non-sublicensable, non-exclusive, irrevocable license to
<del> exercise the Licensed Rights in the Licensed Material to:
<del>
<del> a. reproduce and Share the Licensed Material, in whole or
<del> in part; and
<del>
<del> b. produce, reproduce, and Share Adapted Material.
<del>
<del> 2. Exceptions and Limitations. For the avoidance of doubt, where
<del> Exceptions and Limitations apply to Your use, this Public
<del> License does not apply, and You do not need to comply with
<del> its terms and conditions.
<del>
<del> 3. Term. The term of this Public License is specified in Section
<del> 6(a).
<del>
<del> 4. Media and formats; technical modifications allowed. The
<del> Licensor authorizes You to exercise the Licensed Rights in
<del> all media and formats whether now known or hereafter created,
<del> and to make technical modifications necessary to do so. The
<del> Licensor waives and/or agrees not to assert any right or
<del> authority to forbid You from making technical modifications
<del> necessary to exercise the Licensed Rights, including
<del> technical modifications necessary to circumvent Effective
<del> Technological Measures. For purposes of this Public License,
<del> simply making modifications authorized by this Section 2(a)
<del> (4) never produces Adapted Material.
<del>
<del> 5. Downstream recipients.
<del>
<del> a. Offer from the Licensor -- Licensed Material. Every
<del> recipient of the Licensed Material automatically
<del> receives an offer from the Licensor to exercise the
<del> Licensed Rights under the terms and conditions of this
<del> Public License.
<del>
<del> b. Additional offer from the Licensor -- Adapted Material.
<del> Every recipient of Adapted Material from You
<del> automatically receives an offer from the Licensor to
<del> exercise the Licensed Rights in the Adapted Material
<del> under the conditions of the Adapter's License You apply.
<del>
<del> c. No downstream restrictions. You may not offer or impose
<del> any additional or different terms or conditions on, or
<del> apply any Effective Technological Measures to, the
<del> Licensed Material if doing so restricts exercise of the
<del> Licensed Rights by any recipient of the Licensed
<del> Material.
<del>
<del> 6. No endorsement. Nothing in this Public License constitutes or
<del> may be construed as permission to assert or imply that You
<del> are, or that Your use of the Licensed Material is, connected
<del> with, or sponsored, endorsed, or granted official status by,
<del> the Licensor or others designated to receive attribution as
<del> provided in Section 3(a)(1)(A)(i).
<del>
<del>b. Other rights.
<del>
<del> 1. Moral rights, such as the right of integrity, are not
<del> licensed under this Public License, nor are publicity,
<del> privacy, and/or other similar personality rights; however, to
<del> the extent possible, the Licensor waives and/or agrees not to
<del> assert any such rights held by the Licensor to the limited
<del> extent necessary to allow You to exercise the Licensed
<del> Rights, but not otherwise.
<del>
<del> 2. Patent and trademark rights are not licensed under this
<del> Public License.
<del>
<del> 3. To the extent possible, the Licensor waives any right to
<del> collect royalties from You for the exercise of the Licensed
<del> Rights, whether directly or through a collecting society
<del> under any voluntary or waivable statutory or compulsory
<del> licensing scheme. In all other cases the Licensor expressly
<del> reserves any right to collect such royalties.
<del>
<del>Section 3 -- License Conditions.
<del>
<del>Your exercise of the Licensed Rights is expressly made subject to the following
<del>conditions.
<del>
<del>a. Attribution.
<del>
<del> 1. If You Share the Licensed Material (including in modified
<del> form), You must:
<del>
<del> a. retain the following if it is supplied by the Licensor
<del> with the Licensed Material:
<del>
<del> i. identification of the creator(s) of the Licensed
<del> Material and any others designated to receive
<del> attribution, in any reasonable manner requested by
<del> the Licensor (including by pseudonym if
<del> designated);
<del>
<del> ii. a copyright notice;
<del>
<del> iii. a notice that refers to this Public License;
<del>
<del> iv. a notice that refers to the disclaimer of
<del> warranties;
<del>
<del> v. a URI or hyperlink to the Licensed Material to the
<del> extent reasonably practicable;
<del>
<del> b. indicate if You modified the Licensed Material and
<del> retain an indication of any previous modifications; and
<del>
<del> c. indicate the Licensed Material is licensed under this
<del> Public License, and include the text of, or the URI or
<del> hyperlink to, this Public License.
<del>
<del> 2. You may satisfy the conditions in Section 3(a)(1) in any
<del> reasonable manner based on the medium, means, and context in
<del> which You Share the Licensed Material. For example, it may be
<del> reasonable to satisfy the conditions by providing a URI or
<del> hyperlink to a resource that includes the required
<del> information.
<del>
<del> 3. If requested by the Licensor, You must remove any of the
<del> information required by Section 3(a)(1)(A) to the extent
<del> reasonably practicable.
<del>
<del>b. ShareAlike.
<del>
<del> In addition to the conditions in Section 3(a), if You Share
<del> Adapted Material You produce, the following conditions also apply.
<del>
<del> 1. The Adapter's License You apply must be a Creative Commons
<del> license with the same License Elements, this version or
<del> later, or a BY-SA Compatible License.
<del>
<del> 2. You must include the text of, or the URI or hyperlink to, the
<del> Adapter's License You apply. You may satisfy this condition
<del> in any reasonable manner based on the medium, means, and
<del> context in which You Share Adapted Material.
<del>
<del> 3. You may not offer or impose any additional or different terms
<del> or conditions on, or apply any Effective Technological
<del> Measures to, Adapted Material that restrict exercise of the
<del> rights granted under the Adapter's License You apply.
<del>
<del>Section 4 -- Sui Generis Database Rights.
<del>
<del>Where the Licensed Rights include Sui Generis Database Rights that apply to Your
<del>use of the Licensed Material:
<del>
<del>a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract,
<del>reuse, reproduce, and Share all or a substantial portion of the contents of the
<del>database;
<del>
<del>b. if You include all or a substantial portion of the database contents in a
<del>database in which You have Sui Generis Database Rights, then the database in
<del>which You have Sui Generis Database Rights (but not its individual contents) is
<del>Adapted Material,
<del>
<del> including for purposes of Section 3(b); and
<del>
<del>c. You must comply with the conditions in Section 3(a) if You Share all or a
<del>substantial portion of the contents of the database.
<del>
<del>For the avoidance of doubt, this Section 4 supplements and does not replace Your
<del>obligations under this Public License where the Licensed Rights include other
<del>Copyright and Similar Rights.
<del>
<del>Section 5 -- Disclaimer of Warranties and Limitation of Liability.
<del>
<del>a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT
<del>POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND
<del>MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED
<del>MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT
<del>LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
<del>PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE
<del>PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE
<del>DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER
<del>MAY NOT APPLY TO YOU.
<del>
<del>b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY
<del>LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY
<del>DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR
<del>OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
<del>USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE
<del>POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF
<del>LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO
<del>YOU.
<del>
<del>c. The disclaimer of warranties and limitation of liability provided above shall
<del>be interpreted in a manner that, to the extent possible, most closely
<del>approximates an absolute disclaimer and waiver of all liability.
<del>
<del>Section 6 -- Term and Termination.
<del>
<del>a. This Public License applies for the term of the Copyright and Similar Rights
<del>licensed here. However, if You fail to comply with this Public License, then
<del>Your rights under this Public License terminate automatically.
<del>
<del>b. Where Your right to use the Licensed Material has terminated under Section
<del>6(a), it reinstates:
<del>
<del> 1. automatically as of the date the violation is cured, provided
<del> it is cured within 30 days of Your discovery of the
<del> violation; or
<del>
<del> 2. upon express reinstatement by the Licensor.
<del>
<del> For the avoidance of doubt, this Section 6(b) does not affect any
<del> right the Licensor may have to seek remedies for Your violations
<del> of this Public License.
<del>
<del>c. For the avoidance of doubt, the Licensor may also offer the Licensed Material
<del>under separate terms or conditions or stop distributing the Licensed Material at
<del>any time; however, doing so will not terminate this Public License.
<del>
<del>d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
<del>
<del>Section 7 -- Other Terms and Conditions.
<del>
<del>a. The Licensor shall not be bound by any additional or different terms or
<del>conditions communicated by You unless expressly agreed.
<del>
<del>b. Any arrangements, understandings, or agreements regarding the Licensed
<del>Material not stated herein are separate from and independent of the terms and
<del>conditions of this Public License.
<del>
<del>Section 8 -- Interpretation.
<del>
<del>a. For the avoidance of doubt, this Public License does not, and shall not be
<del>interpreted to, reduce, limit, restrict, or impose conditions on any use of the
<del>Licensed Material that could lawfully be made without permission under this
<del>Public License.
<del>
<del>b. To the extent possible, if any provision of this Public License is deemed
<del>unenforceable, it shall be automatically reformed to the minimum extent
<del>necessary to make it enforceable. If the provision cannot be reformed, it shall
<del>be severed from this Public License without affecting the enforceability of the
<del>remaining terms and conditions.
<del>
<del>c. No term or condition of this Public License will be waived and no failure to
<del>comply consented to unless expressly agreed to by the Licensor.
<del>
<del>d. Nothing in this Public License constitutes or may be interpreted as a
<del>limitation upon, or waiver of, any privileges and immunities that apply to the
<del>Licensor or You, including from the legal processes of any jurisdiction or
<del>authority.
<del>
<del>=======================================================================
<del>
<del>Creative Commons is not a party to its public licenses. Notwithstanding,
<del>Creative Commons may elect to apply one of its public licenses to material it
<del>publishes and in those instances will be considered the “Licensor.” The text of
<del>the Creative Commons public licenses is dedicated to the public domain under the
<del>CC0 Public Domain Dedication. Except for the limited purpose of indicating that
<del>material is shared under a Creative Commons public license or as otherwise
<del>permitted by the Creative Commons policies published at
<del>creativecommons.org/policies, Creative Commons does not authorize the use of the
<del>trademark "Creative Commons" or any other trademark or logo of Creative Commons
<del>without its prior written consent including, without limitation, in connection
<del>with any unauthorized modifications to any of its public licenses or any other
<del>arrangements, understandings, or agreements concerning use of licensed material.
<del>For the avoidance of doubt, this paragraph does not form part of the public
<del>licenses.
<del>
<del>Creative Commons may be contacted at creativecommons.org. | 1 |
Javascript | Javascript | use lane to track root callback priority | dcd13045ef5d4e42bbda6ec2a493ac2ea507c018 | <ide><path>packages/react-reconciler/src/ReactFiberLane.new.js
<ide> * @flow
<ide> */
<ide>
<del>import type {FiberRoot, ReactPriorityLevel} from './ReactInternalTypes';
<add>import type {FiberRoot} from './ReactInternalTypes';
<ide>
<ide> // TODO: Ideally these types would be opaque but that doesn't work well with
<ide> // our reconciler fork infra, since these leak into non-reconciler packages.
<ide> export type Lanes = number;
<ide> export type Lane = number;
<ide> export type LaneMap<T> = Array<T>;
<ide>
<del>import invariant from 'shared/invariant';
<ide> import {enableCache, enableSchedulingProfiler} from 'shared/ReactFeatureFlags';
<ide>
<del>import {
<del> ImmediatePriority as ImmediateSchedulerPriority,
<del> UserBlockingPriority as UserBlockingSchedulerPriority,
<del> NormalPriority as NormalSchedulerPriority,
<del> IdlePriority as IdleSchedulerPriority,
<del> NoPriority as NoSchedulerPriority,
<del>} from './SchedulerWithReactIntegration.new';
<del>
<ide> export const SyncLanePriority: LanePriority = 12;
<ide>
<ide> const InputContinuousHydrationLanePriority: LanePriority = 11;
<ide> function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes {
<ide> }
<ide> }
<ide>
<del>export function lanePriorityToSchedulerPriority(
<del> lanePriority: LanePriority,
<del>): ReactPriorityLevel {
<del> switch (lanePriority) {
<del> case SyncLanePriority:
<del> return ImmediateSchedulerPriority;
<del> case InputContinuousHydrationLanePriority:
<del> case InputContinuousLanePriority:
<del> return UserBlockingSchedulerPriority;
<del> case DefaultHydrationLanePriority:
<del> case DefaultLanePriority:
<del> case TransitionHydrationPriority:
<del> case TransitionPriority:
<del> case SelectiveHydrationLanePriority:
<del> case RetryLanePriority:
<del> return NormalSchedulerPriority;
<del> case IdleHydrationLanePriority:
<del> case IdleLanePriority:
<del> case OffscreenLanePriority:
<del> return IdleSchedulerPriority;
<del> case NoLanePriority:
<del> return NoSchedulerPriority;
<del> default:
<del> invariant(
<del> false,
<del> 'Invalid update priority: %s. This is a bug in React.',
<del> lanePriority,
<del> );
<del> }
<del>}
<del>
<ide> export function getNextLanes(root: FiberRoot, wipLanes: Lanes): Lanes {
<ide> // Early bailout if there's no pending work left.
<ide> const pendingLanes = root.pendingLanes;
<ide><path>packages/react-reconciler/src/ReactFiberLane.old.js
<ide> * @flow
<ide> */
<ide>
<del>import type {FiberRoot, ReactPriorityLevel} from './ReactInternalTypes';
<add>import type {FiberRoot} from './ReactInternalTypes';
<ide>
<ide> // TODO: Ideally these types would be opaque but that doesn't work well with
<ide> // our reconciler fork infra, since these leak into non-reconciler packages.
<ide> export type Lanes = number;
<ide> export type Lane = number;
<ide> export type LaneMap<T> = Array<T>;
<ide>
<del>import invariant from 'shared/invariant';
<ide> import {enableCache, enableSchedulingProfiler} from 'shared/ReactFeatureFlags';
<ide>
<del>import {
<del> ImmediatePriority as ImmediateSchedulerPriority,
<del> UserBlockingPriority as UserBlockingSchedulerPriority,
<del> NormalPriority as NormalSchedulerPriority,
<del> IdlePriority as IdleSchedulerPriority,
<del> NoPriority as NoSchedulerPriority,
<del>} from './SchedulerWithReactIntegration.old';
<del>
<ide> export const SyncLanePriority: LanePriority = 12;
<ide>
<ide> const InputContinuousHydrationLanePriority: LanePriority = 11;
<ide> function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes {
<ide> }
<ide> }
<ide>
<del>export function lanePriorityToSchedulerPriority(
<del> lanePriority: LanePriority,
<del>): ReactPriorityLevel {
<del> switch (lanePriority) {
<del> case SyncLanePriority:
<del> return ImmediateSchedulerPriority;
<del> case InputContinuousHydrationLanePriority:
<del> case InputContinuousLanePriority:
<del> return UserBlockingSchedulerPriority;
<del> case DefaultHydrationLanePriority:
<del> case DefaultLanePriority:
<del> case TransitionHydrationPriority:
<del> case TransitionPriority:
<del> case SelectiveHydrationLanePriority:
<del> case RetryLanePriority:
<del> return NormalSchedulerPriority;
<del> case IdleHydrationLanePriority:
<del> case IdleLanePriority:
<del> case OffscreenLanePriority:
<del> return IdleSchedulerPriority;
<del> case NoLanePriority:
<del> return NoSchedulerPriority;
<del> default:
<del> invariant(
<del> false,
<del> 'Invalid update priority: %s. This is a bug in React.',
<del> lanePriority,
<del> );
<del> }
<del>}
<del>
<ide> export function getNextLanes(root: FiberRoot, wipLanes: Lanes): Lanes {
<ide> // Early bailout if there's no pending work left.
<ide> const pendingLanes = root.pendingLanes;
<ide><path>packages/react-reconciler/src/ReactFiberRoot.new.js
<ide> import type {RootTag} from './ReactRootTags';
<ide> import {noTimeout, supportsHydration} from './ReactFiberHostConfig';
<ide> import {createHostRootFiber} from './ReactFiber.new';
<ide> import {
<add> NoLane,
<ide> NoLanes,
<del> NoLanePriority,
<ide> NoTimestamp,
<ide> createLaneMap,
<ide> } from './ReactFiberLane.new';
<ide> function FiberRootNode(containerInfo, tag, hydrate) {
<ide> this.pendingContext = null;
<ide> this.hydrate = hydrate;
<ide> this.callbackNode = null;
<del> this.callbackPriority = NoLanePriority;
<add> this.callbackPriority = NoLane;
<ide> this.eventTimes = createLaneMap(NoLanes);
<ide> this.expirationTimes = createLaneMap(NoTimestamp);
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberRoot.old.js
<ide> import type {RootTag} from './ReactRootTags';
<ide> import {noTimeout, supportsHydration} from './ReactFiberHostConfig';
<ide> import {createHostRootFiber} from './ReactFiber.old';
<ide> import {
<add> NoLane,
<ide> NoLanes,
<del> NoLanePriority,
<ide> NoTimestamp,
<ide> createLaneMap,
<ide> } from './ReactFiberLane.old';
<ide> function FiberRootNode(containerInfo, tag, hydrate) {
<ide> this.pendingContext = null;
<ide> this.hydrate = hydrate;
<ide> this.callbackNode = null;
<del> this.callbackPriority = NoLanePriority;
<add> this.callbackPriority = NoLane;
<ide> this.eventTimes = createLaneMap(NoLanes);
<ide> this.expirationTimes = createLaneMap(NoTimestamp);
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> requestPaint,
<ide> now,
<ide> ImmediatePriority as ImmediateSchedulerPriority,
<add> UserBlockingPriority as UserBlockingSchedulerPriority,
<ide> NormalPriority as NormalSchedulerPriority,
<add> IdlePriority as IdleSchedulerPriority,
<ide> flushSyncCallbackQueue,
<ide> scheduleSyncCallback,
<ide> } from './SchedulerWithReactIntegration.new';
<ide> import {
<ide> MountLayoutDev,
<ide> } from './ReactFiberFlags';
<ide> import {
<del> NoLanePriority,
<del> SyncLanePriority,
<ide> NoLanes,
<ide> NoLane,
<ide> SyncLane,
<ide> import {
<ide> includesOnlyRetries,
<ide> includesOnlyTransitions,
<ide> getNextLanes,
<del> returnNextLanesPriority,
<ide> markStarvedLanesAsExpired,
<ide> getLanesToRetrySynchronouslyOnError,
<ide> getMostRecentEventTime,
<ide> import {
<ide> markRootPinged,
<ide> markRootExpired,
<ide> markRootFinished,
<del> lanePriorityToSchedulerPriority,
<ide> areLanesExpired,
<add> getHighestPriorityLane,
<ide> } from './ReactFiberLane.new';
<ide> import {
<ide> DiscreteEventPriority,
<add> ContinuousEventPriority,
<ide> DefaultEventPriority,
<add> IdleEventPriority,
<ide> getCurrentUpdatePriority,
<ide> setCurrentUpdatePriority,
<ide> higherEventPriority,
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> root,
<ide> root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes,
<ide> );
<del> // This returns the priority level computed during the `getNextLanes` call.
<del> const newCallbackPriority = returnNextLanesPriority();
<ide>
<ide> if (nextLanes === NoLanes) {
<ide> // Special case: There's nothing to work on.
<ide> if (existingCallbackNode !== null) {
<ide> cancelCallback(existingCallbackNode);
<ide> }
<ide> root.callbackNode = null;
<del> root.callbackPriority = NoLanePriority;
<add> root.callbackPriority = NoLane;
<ide> return;
<ide> }
<ide>
<add> // We use the highest priority lane to represent the priority of the callback.
<add> const newCallbackPriority = getHighestPriorityLane(nextLanes);
<add>
<ide> // Check if there's an existing task. We may be able to reuse it.
<ide> const existingCallbackPriority = root.callbackPriority;
<ide> if (existingCallbackPriority === newCallbackPriority) {
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> // TODO: Temporary until we confirm this warning is not fired.
<ide> if (
<ide> existingCallbackNode == null &&
<del> existingCallbackPriority !== SyncLanePriority
<add> existingCallbackPriority !== SyncLane
<ide> ) {
<ide> console.error(
<ide> 'Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.',
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide>
<ide> // Schedule a new callback.
<ide> let newCallbackNode;
<del> if (newCallbackPriority === SyncLanePriority) {
<add> if (newCallbackPriority === SyncLane) {
<ide> // Special case: Sync React callbacks are scheduled on a special
<ide> // internal queue
<ide> scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> }
<ide> newCallbackNode = null;
<ide> } else {
<del> const schedulerPriorityLevel = lanePriorityToSchedulerPriority(
<del> newCallbackPriority,
<del> );
<add> let schedulerPriorityLevel;
<add> switch (lanesToEventPriority(nextLanes)) {
<add> case DiscreteEventPriority:
<add> schedulerPriorityLevel = ImmediateSchedulerPriority;
<add> break;
<add> case ContinuousEventPriority:
<add> schedulerPriorityLevel = UserBlockingSchedulerPriority;
<add> break;
<add> case DefaultEventPriority:
<add> schedulerPriorityLevel = NormalSchedulerPriority;
<add> break;
<add> case IdleEventPriority:
<add> schedulerPriorityLevel = IdleSchedulerPriority;
<add> break;
<add> default:
<add> schedulerPriorityLevel = NormalSchedulerPriority;
<add> break;
<add> }
<ide> newCallbackNode = scheduleCallback(
<ide> schedulerPriorityLevel,
<ide> performConcurrentWorkOnRoot.bind(null, root),
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> // commitRoot never returns a continuation; it always finishes synchronously.
<ide> // So we can clear these now to allow a new callback to be scheduled.
<ide> root.callbackNode = null;
<del> root.callbackPriority = NoLanePriority;
<add> root.callbackPriority = NoLane;
<ide>
<ide> // Update the first and last pending times on this root. The new first
<ide> // pending time is whatever is left on the root fiber.
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> requestPaint,
<ide> now,
<ide> ImmediatePriority as ImmediateSchedulerPriority,
<add> UserBlockingPriority as UserBlockingSchedulerPriority,
<ide> NormalPriority as NormalSchedulerPriority,
<add> IdlePriority as IdleSchedulerPriority,
<ide> flushSyncCallbackQueue,
<ide> scheduleSyncCallback,
<ide> } from './SchedulerWithReactIntegration.old';
<ide> import {
<ide> MountLayoutDev,
<ide> } from './ReactFiberFlags';
<ide> import {
<del> NoLanePriority,
<del> SyncLanePriority,
<ide> NoLanes,
<ide> NoLane,
<ide> SyncLane,
<ide> import {
<ide> includesOnlyRetries,
<ide> includesOnlyTransitions,
<ide> getNextLanes,
<del> returnNextLanesPriority,
<ide> markStarvedLanesAsExpired,
<ide> getLanesToRetrySynchronouslyOnError,
<ide> getMostRecentEventTime,
<ide> import {
<ide> markRootPinged,
<ide> markRootExpired,
<ide> markRootFinished,
<del> lanePriorityToSchedulerPriority,
<ide> areLanesExpired,
<add> getHighestPriorityLane,
<ide> } from './ReactFiberLane.old';
<ide> import {
<ide> DiscreteEventPriority,
<add> ContinuousEventPriority,
<ide> DefaultEventPriority,
<add> IdleEventPriority,
<ide> getCurrentUpdatePriority,
<ide> setCurrentUpdatePriority,
<ide> higherEventPriority,
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> root,
<ide> root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes,
<ide> );
<del> // This returns the priority level computed during the `getNextLanes` call.
<del> const newCallbackPriority = returnNextLanesPriority();
<ide>
<ide> if (nextLanes === NoLanes) {
<ide> // Special case: There's nothing to work on.
<ide> if (existingCallbackNode !== null) {
<ide> cancelCallback(existingCallbackNode);
<ide> }
<ide> root.callbackNode = null;
<del> root.callbackPriority = NoLanePriority;
<add> root.callbackPriority = NoLane;
<ide> return;
<ide> }
<ide>
<add> // We use the highest priority lane to represent the priority of the callback.
<add> const newCallbackPriority = getHighestPriorityLane(nextLanes);
<add>
<ide> // Check if there's an existing task. We may be able to reuse it.
<ide> const existingCallbackPriority = root.callbackPriority;
<ide> if (existingCallbackPriority === newCallbackPriority) {
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> // TODO: Temporary until we confirm this warning is not fired.
<ide> if (
<ide> existingCallbackNode == null &&
<del> existingCallbackPriority !== SyncLanePriority
<add> existingCallbackPriority !== SyncLane
<ide> ) {
<ide> console.error(
<ide> 'Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.',
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide>
<ide> // Schedule a new callback.
<ide> let newCallbackNode;
<del> if (newCallbackPriority === SyncLanePriority) {
<add> if (newCallbackPriority === SyncLane) {
<ide> // Special case: Sync React callbacks are scheduled on a special
<ide> // internal queue
<ide> scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> }
<ide> newCallbackNode = null;
<ide> } else {
<del> const schedulerPriorityLevel = lanePriorityToSchedulerPriority(
<del> newCallbackPriority,
<del> );
<add> let schedulerPriorityLevel;
<add> switch (lanesToEventPriority(nextLanes)) {
<add> case DiscreteEventPriority:
<add> schedulerPriorityLevel = ImmediateSchedulerPriority;
<add> break;
<add> case ContinuousEventPriority:
<add> schedulerPriorityLevel = UserBlockingSchedulerPriority;
<add> break;
<add> case DefaultEventPriority:
<add> schedulerPriorityLevel = NormalSchedulerPriority;
<add> break;
<add> case IdleEventPriority:
<add> schedulerPriorityLevel = IdleSchedulerPriority;
<add> break;
<add> default:
<add> schedulerPriorityLevel = NormalSchedulerPriority;
<add> break;
<add> }
<ide> newCallbackNode = scheduleCallback(
<ide> schedulerPriorityLevel,
<ide> performConcurrentWorkOnRoot.bind(null, root),
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> // commitRoot never returns a continuation; it always finishes synchronously.
<ide> // So we can clear these now to allow a new callback to be scheduled.
<ide> root.callbackNode = null;
<del> root.callbackPriority = NoLanePriority;
<add> root.callbackPriority = NoLane;
<ide>
<ide> // Update the first and last pending times on this root. The new first
<ide> // pending time is whatever is left on the root fiber.
<ide><path>packages/react-reconciler/src/ReactInternalTypes.js
<ide> import type {SuspenseInstance} from './ReactFiberHostConfig';
<ide> import type {WorkTag} from './ReactWorkTags';
<ide> import type {TypeOfMode} from './ReactTypeOfMode';
<ide> import type {Flags} from './ReactFiberFlags';
<del>import type {Lane, LanePriority, Lanes, LaneMap} from './ReactFiberLane.old';
<add>import type {Lane, Lanes, LaneMap} from './ReactFiberLane.old';
<ide> import type {RootTag} from './ReactRootTags';
<ide> import type {TimeoutHandle, NoTimeout} from './ReactFiberHostConfig';
<ide> import type {Wakeable} from 'shared/ReactTypes';
<ide> type BaseFiberRootProperties = {|
<ide> // Node returned by Scheduler.scheduleCallback. Represents the next rendering
<ide> // task that the root will work on.
<ide> callbackNode: *,
<del> callbackPriority: LanePriority,
<add> callbackPriority: Lane,
<ide> eventTimes: LaneMap<number>,
<ide> expirationTimes: LaneMap<number>,
<ide> | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.