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 | fix wrong order of the 'div' command | 21ee01eb7c75e3727dea6a1a498fa85c11e684d1 | <ide><path>fonts.js
<ide> CFF.prototype = {
<ide> case "div":
<ide> var num2 = aCharstring[i - 1];
<ide> var num1 = aCharstring[i - 2];
<del> aCharstring.splice(i - 2, 3, num2 / num1);
<add> aCharstring.splice(i - 2, 3, num1 / num2);
<ide> i -= 2;
<ide> break;
<ide>
<ide> CFF.prototype = {
<ide> }
<ide>
<ide> var charstringsIndex = this.createCFFIndexHeader([[0x40, 0x0E]].concat(glyphs), true);
<del> charstringsIndex = charstringsIndex.join(" ").split(" "); // XXX why?
<ide>
<ide> //Top Dict Index
<ide> var topDictIndex = [
<ide> CFF.prototype = {
<ide> var privateOffset = charstringsOffset + charstringsIndex.length;
<ide> topDictIndex = topDictIndex.concat(this.encodeNumber(privateOffset));
<ide> topDictIndex.push(18); // Private
<del> topDictIndex = topDictIndex.join(" ").split(" ");
<ide>
<ide> var indexes = [
<ide> topDictIndex, stringsIndex,
<ide> CFF.prototype = {
<ide> 139, 12, 14,
<ide> 28, 0, 55, 19
<ide> ]);
<del> privateData = privateData.join(" ").split(" ");
<ide> cff.set(privateData, currentOffset);
<ide> currentOffset += privateData.length;
<ide> | 1 |
Text | Text | add benchmark who-to-cc info | a528d0dd052be94ab56908a633372ef2609ad1dd | <ide><path>doc/onboarding-extras.md
<ide>
<ide> | subsystem | maintainers |
<ide> | --- | --- |
<add>| `benchmark/*` | @nodejs/benchmarking, @mscdex |
<add>| `bootstrap_node.js` | @fishrock123 |
<ide> | `lib/assert` | @nodejs/testing |
<ide> | `lib/buffer` | @nodejs/buffer |
<ide> | `lib/child_process` | @bnoordhuis, @cjihrig |
<ide> | `lib/timers` | @fishrock123, @misterdjules |
<ide> | `lib/util` | @bnoordhuis, @cjihrig, @evanlucas |
<ide> | `lib/zlib` | @addaleax, @bnoordhuis, @indutny |
<del>| `bootstrap_node.js` | @fishrock123 |
<ide> | `src/async-wrap.*` | @trevnorris |
<ide> | `src/node_crypto.*` | @nodejs/crypto |
<ide> | `test/*` | @nodejs/testing | | 1 |
Text | Text | clarify use of napi_experimental | f4586c902a721164c8af3c0e11db859f102dfe2e | <ide><path>doc/api/n-api.md
<ide> listed as supporting a later version.
<ide> version 1 but continued to evolve until Node.js 8.6.0. The API is different in
<ide> versions prior to Node.js 8.6.0. We recommend N-API version 3 or later.
<ide>
<add>Each API documented for N-API will have a header named `added in:`, and APIs
<add>which are stable will have the additional header `N-API version:`.
<add>APIs are directly usable when using a Node.js version which supports
<add>the N-API version shown in `N-API version:` or higher.
<add>When using a Node.js version that does not support the
<add>`N-API version:` listed or if there is no `N-API version:` listed,
<add>then the API will only be available if
<add>`#define NAPI_EXPERIMENTAL` precedes the inclusion of `node_api.h`
<add>or `js_native_api.h`. If an API appears not to be available on
<add>a version of Node.js which is later than the one shown in `added in:` then
<add>this is most likely the reason for the apparent absence.
<add>
<ide> The N-APIs associated strictly with accessing ECMAScript features from native
<ide> code can be found separately in `js_native_api.h` and `js_native_api_types.h`.
<ide> The APIs defined in these headers are included in `node_api.h` and | 1 |
Text | Text | release notes for 1.2.12 | 5cc5cc13b9beb996e0173e97db5c0e04d0204dfb | <ide><path>CHANGELOG.md
<add><a name="1.2.12"></a>
<add># 1.2.12 cauliflower-eradication (2014-02-07)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$compile:** retain CSS classes added in cloneAttachFn on asynchronous directives
<add> ([5ed721b9](https://github.com/angular/angular.js/commit/5ed721b9b5e95ae08450e1ae9d5202e7f3f79295),
<add> [#5439](https://github.com/angular/angular.js/issues/5439), [#5617](https://github.com/angular/angular.js/issues/5617))
<add>- **$http:**
<add> - ignore xhr.responseType setter exception if value is "json"
<add> ([24699ee8](https://github.com/angular/angular.js/commit/24699ee8f04c1f1459be1d36207e654421d58ff0),
<add> [#6115](https://github.com/angular/angular.js/issues/6115), [#6122](https://github.com/angular/angular.js/issues/6122))
<add> - update httpBackend to use ActiveXObject on IE8 if necessary
<add> ([ef210e5e](https://github.com/angular/angular.js/commit/ef210e5e119db4f5bfc9d2428b19f9b335c4f976),
<add> [#5677](https://github.com/angular/angular.js/issues/5677), [#5679](https://github.com/angular/angular.js/issues/5679))
<add>- **$locale:** minor grammar amends for the locale `locale_lt`
<add> ([95be253f](https://github.com/angular/angular.js/commit/95be253fe55d35336d425d3d600a36158fc3519d),
<add> [#6164](https://github.com/angular/angular.js/issues/6164))
<add>- **$q:** make $q.reject support `finally` and `catch`
<add> ([074b0675](https://github.com/angular/angular.js/commit/074b0675a1f97dce07f520f1ae6198ed3c604000),
<add> [#6048](https://github.com/angular/angular.js/issues/6048), [#6076](https://github.com/angular/angular.js/issues/6076))
<add>- **docs:** clarify doc for "args" in $broadcast and $emit
<add> ([caed2dfe](https://github.com/angular/angular.js/commit/caed2dfe4feeac5d19ecea2dbb1456b7fde21e6d),
<add> [#6047](https://github.com/angular/angular.js/issues/6047))
<add>- **filterFilter:** don't interpret dots in predicate object fields as paths
<add> ([339a1658](https://github.com/angular/angular.js/commit/339a1658cd9bfa5e322a01c45aa0a1df67e3a842),
<add> [#6005](https://github.com/angular/angular.js/issues/6005), [#6009](https://github.com/angular/angular.js/issues/6009))
<add>- **http:** make jshint happy
<add> ([6609e3da](https://github.com/angular/angular.js/commit/6609e3da76dd898cfe85f75f23ab2e39fee65fe5))
<add>- **jqLite:** trim HTML string in jqLite constructor
<add> ([36d37c0e](https://github.com/angular/angular.js/commit/36d37c0e3880c774d20c014ade60d2331beefa15),
<add> [#6053](https://github.com/angular/angular.js/issues/6053))
<add>- **mocks:**
<add> - rename mock.animate to ngAnimateMock and ensure it contains all test helper code for ngAnimate
<add> ([4224cd51](https://github.com/angular/angular.js/commit/4224cd5182bc93e4a210f75e0a4e4de7f3c544e8),
<add> [#5822](https://github.com/angular/angular.js/issues/5822), [#5917](https://github.com/angular/angular.js/issues/5917))
<add> - remove usage of $animate.flushNext in favour of queing
<add> ([906fdad0](https://github.com/angular/angular.js/commit/906fdad0f95465842e336e057ea97d0633712189))
<add> - always call functions injected with `inject` with `this` set to the current spec
<add> ([3bf43903](https://github.com/angular/angular.js/commit/3bf43903397c703aa2e9ba1e1a48dbc9e8286ee2),
<add> [#6102](https://github.com/angular/angular.js/issues/6102))
<add> - refactor currentSpec to work w/ Jasmine 2
<add> ([95f0bf9b](https://github.com/angular/angular.js/commit/95f0bf9b526fda8964527c6d4aef1ad50a47f1f3),
<add> [#5662](https://github.com/angular/angular.js/issues/5662))
<add>- **ngMock:** return false from mock $interval.cancel() when no argument is supplied
<add> ([dd24c783](https://github.com/angular/angular.js/commit/dd24c78373b5d24ecb3b9d19e61e1b3b6c74d155),
<add> [#6103](https://github.com/angular/angular.js/issues/6103))
<add>- **ngResource:**
<add> - don't filter "$"-prefixed properties from ngResource requests/responses
<add> ([d2e4e499](https://github.com/angular/angular.js/commit/d2e4e499862aeca157dbe7a7422c465e7c79205e),
<add> [#5666](https://github.com/angular/angular.js/issues/5666), [#6080](https://github.com/angular/angular.js/issues/6080), [#6033](https://github.com/angular/angular.js/issues/6033))
<add> - don't append number to '$' in url param value when encoding URI
<add> ([ce1f1f97](https://github.com/angular/angular.js/commit/ce1f1f97f0ebf77941b2bdaf5e8352d33786524d),
<add> [#6003](https://github.com/angular/angular.js/issues/6003), [#6004](https://github.com/angular/angular.js/issues/6004))
<add>
<add>## Breaking Changes
<add>
<add>The animation mock module has been renamed from `mock.animate` to `ngAnimateMock`. In addition to the rename, animations will not block within test code even when ngAnimateMock is used. However, all function calls to $animate will be recorded into `$animate.queue` and are available within test code to assert animation calls. In addition, `$animate.triggerReflow()` is now only available when `ngAnimateMock` is used.
<add>
<add>
<ide> <a name="1.2.11"></a>
<ide> # 1.2.11 cryptocurrency-hyperdeflation (2014-02-03)
<ide> | 1 |
Javascript | Javascript | remove unused htmlbars code in router | d2cd0d35fa487c3ae500e779c5751d50e96a2db7 | <ide><path>packages/ember-routing/lib/system/router.js
<ide> const EmberRouter = EmberObject.extend(Evented, {
<ide> init() {
<ide> this._super(...arguments);
<ide>
<del> this._activeViews = {};
<ide> this._qpCache = new EmptyObject();
<ide> this._resetQueuedQueryParameterChanges();
<ide> this._handledErrors = dictionary(null);
<ide> const EmberRouter = EmberObject.extend(Evented, {
<ide> this.reset();
<ide> },
<ide>
<del> _lookupActiveComponentNode(templateName) {
<del> return this._activeViews[templateName];
<del> },
<del>
<ide> /*
<ide> Called when an active route's query parameter has changed.
<ide> These changes are batched into a runloop run and trigger
<ide> const EmberRouter = EmberObject.extend(Evented, {
<ide> this._resetQueuedQueryParameterChanges();
<ide> },
<ide>
<del> _connectActiveComponentNode(templateName, componentNode) {
<del> assert('cannot connect an activeView that already exists', !this._activeViews[templateName]);
<del>
<del> let _activeViews = this._activeViews;
<del> function disconnectActiveView() {
<del> delete _activeViews[templateName];
<del> }
<del>
<del> this._activeViews[templateName] = componentNode;
<del> componentNode.renderNode.addDestruction({ destroy: disconnectActiveView });
<del> },
<del>
<ide> _setupLocation() {
<ide> let location = get(this, 'location');
<ide> let rootURL = get(this, 'rootURL'); | 1 |
Text | Text | remove obsolete ref to sha1 | f30221c7e1d626ddce3d923bc9da2ba880a7ceee | <ide><path>share/doc/homebrew/Tips-N'-Tricks.md
<ide> renaming the file from <code>otp_src_R13B03</code> to
<ide> download. This means instead of manually renaming a formula, you can
<ide> run `mv the_tarball $(brew --cache -s $FORMULA)`.
<ide>
<del>You can also pre-cache the download by using the command `brew fetch formula` which also displays the SHA1 and SHA256 values. This can be useful for updating formulae to new versions.
<add>You can also pre-cache the download by using the command `brew fetch formula` which also displays the SHA256 value. This can be useful for updating formulae to new versions.
<ide>
<ide> ## Using Homebrew behind a proxy
<ide> | 1 |
Ruby | Ruby | update command line outputs | 507fba73c493dc8d05fcd836e1a8f58471fe04d5 | <ide><path>Library/Homebrew/cask/cmd/upgrade.rb
<ide> def run
<ide> *casks,
<ide> force: args.force?,
<ide> greedy: args.greedy?,
<del> greedy_latest: args.greedy_latest,
<del> greedy_auto_updates: args.greedy_auto_updates,
<add> greedy_latest: args.greedy_latest?,
<add> greedy_auto_updates: args.greedy_auto_updates?,
<ide> dry_run: args.dry_run?,
<ide> binaries: args.binaries?,
<ide> quarantine: args.quarantine?,
<ide> def run
<ide> force: T.nilable(T::Boolean),
<ide> greedy: T.nilable(T::Boolean),
<ide> greedy_latest: T.nilable(T::Boolean),
<del> greedy_auto_updates: T.nilabel(T::Boolean),
<add> greedy_auto_updates: T.nilable(T::Boolean),
<ide> dry_run: T.nilable(T::Boolean),
<ide> skip_cask_deps: T.nilable(T::Boolean),
<ide> verbose: T.nilable(T::Boolean),
<ide> def self.upgrade_casks(
<ide> return false if outdated_casks.empty?
<ide>
<ide> if casks.empty? && !greedy
<del> ohai "Casks with 'auto_updates' or 'version :latest' will not be upgraded; pass `--greedy` to upgrade them."
<add> ohai "Casks with 'auto_updates true' or 'version :latest' will not be upgraded; pass `--greedy` to upgrade them." if !args.greedy_auto_updates? && !args.greedy_latest?
<add> ohai "Casks with 'version :latest' will not be upgraded; pass `--greedy-latest` to upgrade them." if args.greedy_auto_updates? && !args.greedy_latest?
<add> ohai "Casks with 'auto_updates true' will not be upgraded; pass `--greedy-auto-updates` to upgrade them." if !args.greedy_auto_updates? && args.greedy_latest?
<ide> end
<ide>
<ide> verb = dry_run ? "Would upgrade" : "Upgrading"
<ide><path>Library/Homebrew/cmd/outdated.rb
<ide> def outdated_args
<ide> "formula is outdated. Otherwise, the repository's HEAD will only be checked for "\
<ide> "updates when a new stable or development version has been released."
<ide> switch "--greedy",
<del> description: "Print outdated casks with `auto_updates` or `version :latest`."
<add> description: "Print outdated casks with `auto_updates true` or `version :latest`."
<ide>
<ide> switch "--greedy-latest",
<ide> description: "Print outdated casks including those with `version :latest`."
<ide>
<ide> switch "--greedy-auto-updates",
<del> description: "Print outdated casks including those with `auto_updates`."
<add> description: "Print outdated casks including those with `auto_updates true`."
<ide>
<ide> conflicts "--quiet", "--verbose", "--json"
<ide> conflicts "--formula", "--cask"
<ide> def json_info(formulae_or_casks, args:)
<ide> else
<ide> c = formula_or_cask
<ide>
<del> c.outdated_info(args.greedy?, verbose?, true)
<add> c.outdated_info(args.greedy?, verbose?, true, greedy_latest: args.greedy_latest?,
<add> greedy_auto_updates: args.greedy_auto_updates?)
<ide> end
<ide> end
<ide> end | 2 |
PHP | PHP | get exception property only if it exists | 052ebceb4a26b47d294600976d8756f77245eee2 | <ide><path>src/Illuminate/Foundation/Testing/CrawlerTrait.php
<ide> protected function assertPageLoaded($uri, $message = null)
<ide> } catch (PHPUnitException $e) {
<ide> $message = $message ?: "A request to [{$uri}] failed. Received status code [{$status}].";
<ide>
<del> throw new HttpException($message, null, $this->response->exception);
<add> throw new HttpException($message, null, data_get($this->response, 'exception'));
<ide> }
<ide> }
<ide> | 1 |
Go | Go | add err handling, close fd | 2281ce7e98ec983514450c33c0ef1d90262c3b4f | <ide><path>plugin/backend.go
<ide> func (pm *Manager) List() ([]types.Plugin, error) {
<ide> // Push pushes a plugin to the store.
<ide> func (pm *Manager) Push(name string, metaHeader http.Header, authConfig *types.AuthConfig) error {
<ide> p, err := pm.get(name)
<add> if err != nil {
<add> return err
<add> }
<ide> dest := filepath.Join(pm.libRoot, p.P.ID)
<ide> config, err := os.Open(filepath.Join(dest, "manifest.json"))
<ide> if err != nil {
<ide> return err
<ide> }
<add> defer config.Close()
<add>
<ide> rootfs, err := archive.Tar(filepath.Join(dest, "rootfs"), archive.Gzip)
<ide> if err != nil {
<ide> return err
<ide><path>plugin/distribution/pull.go
<ide> func WritePullData(pd PullData, dest string, extract bool) error {
<ide> if !extract {
<ide> f, err := os.Create(filepath.Join(dest, fmt.Sprintf("layer%d.tar", i)))
<ide> if err != nil {
<add> l.Close()
<ide> return err
<ide> }
<ide> io.Copy(f, l)
<ide><path>plugin/distribution/push.go
<ide> func Push(name string, rs registry.Service, metaHeader http.Header, authConfig *
<ide> r := io.TeeReader(f, h)
<ide> _, err = io.Copy(bw, r)
<ide> if err != nil {
<add> f.Close()
<ide> logrus.Debugf("Error in io.Copy: %v", err)
<ide> return "", err
<ide> }
<ide><path>plugin/manager.go
<ide> func Handle(capability string, callback func(string, *plugins.Client)) {
<ide>
<ide> func (pm *Manager) get(name string) (*plugin, error) {
<ide> pm.RLock()
<add> defer pm.RUnlock()
<add>
<ide> id, nameOk := pm.nameToID[name]
<add> if !nameOk {
<add> return nil, ErrNotFound(name)
<add> }
<add>
<ide> p, idOk := pm.plugins[id]
<del> pm.RUnlock()
<del> if !nameOk || !idOk {
<add> if !idOk {
<ide> return nil, ErrNotFound(name)
<ide> }
<add>
<ide> return p, nil
<ide> }
<ide> | 4 |
Python | Python | fix the if | 2b5c71b81773623c1d2ef280f6d406631727a34c | <ide><path>setup.py
<ide> def _run_tests(self):
<ide> for t in glob(pjoin(self._dir, test_path, 'test_*.py')):
<ide> if (sys.version_info >= (3, 2) and sys.version_info < (3, 3) or
<ide> sys.version_info >= (2, 5) and sys.version_info < (2, 6)) \
<del> and t.find('test_local'):
<add> and t.find('test_local') == 0:
<ide> # Lockfile doesn't work with 2.5 and 3.2. Temporary disable
<ide> # local_storage test until fixes have been submitted
<ide> # upstream | 1 |
Go | Go | clarify doc for parsetimestamp | 9cd67df5b283dc8cd13e85af8f191756fe1a6363 | <ide><path>api/types/time/timestamp.go
<ide> func GetTimestamp(value string, reference time.Time) (string, error) {
<ide> return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond())), nil
<ide> }
<ide>
<del>// ParseTimestamps returns seconds and nanoseconds from a timestamp that has the
<del>// format "%d.%09d", time.Unix(), int64(time.Nanosecond()))
<del>// if the incoming nanosecond portion is longer or shorter than 9 digits it is
<del>// converted to nanoseconds. The expectation is that the seconds and
<del>// seconds will be used to create a time variable. For example:
<add>// ParseTimestamps returns seconds and nanoseconds from a timestamp that has
<add>// the format ("%d.%09d", time.Unix(), int64(time.Nanosecond())).
<add>// If the incoming nanosecond portion is longer than 9 digits it is truncated.
<add>// The expectation is that the seconds and nanoseconds will be used to create a
<add>// time variable. For example:
<ide> //
<del>// seconds, nanoseconds, err := ParseTimestamp("1136073600.000000001",0)
<del>// if err == nil since := time.Unix(seconds, nanoseconds)
<add>// seconds, nanoseconds, _ := ParseTimestamp("1136073600.000000001",0)
<add>// since := time.Unix(seconds, nanoseconds)
<ide> //
<del>// returns seconds as def(aultSeconds) if value == ""
<del>func ParseTimestamps(value string, def int64) (int64, int64, error) {
<add>// returns seconds as defaultSeconds if value == ""
<add>func ParseTimestamps(value string, defaultSeconds int64) (int64, int64, error) {
<ide> if value == "" {
<del> return def, 0, nil
<add> return defaultSeconds, 0, nil
<ide> }
<ide> return parseTimestamp(value)
<ide> }
<ide><path>api/types/time/timestamp_test.go
<ide> func TestParseTimestamps(t *testing.T) {
<ide> {"1136073600", 0, 1136073600, 0, false},
<ide> {"1136073600.000000001", 0, 1136073600, 1, false},
<ide> {"1136073600.0000000010", 0, 1136073600, 1, false},
<add> {"1136073600.0000000001", 0, 1136073600, 0, false},
<add> {"1136073600.0000000009", 0, 1136073600, 0, false},
<ide> {"1136073600.00000001", 0, 1136073600, 10, false},
<ide> {"foo.bar", 0, 0, 0, true},
<ide> {"1136073600.bar", 0, 1136073600, 0, true}, | 2 |
Javascript | Javascript | fix persistent history and env variable name | 2e2fce0502399db5d0902a0d3eb9528e1d9420c4 | <ide><path>lib/internal/repl.js
<ide> module.paths = require('module')._nodeModulePaths(module.filename);
<ide>
<ide> function createRepl(env, cb) {
<ide> const opts = {
<del> useGlobal: true,
<del> ignoreUndefined: false
<add> ignoreUndefined: false,
<add> terminal: process.stdout.isTTY,
<add> useGlobal: true
<ide> };
<ide>
<ide> if (parseInt(env.NODE_NO_READLINE)) {
<ide> function createRepl(env, cb) {
<ide> }
<ide>
<ide> const repl = REPL.start(opts);
<del> if (opts.terminal && env.NODE_REPL_HISTORY_PATH) {
<del> return setupHistory(repl, env.NODE_REPL_HISTORY_PATH, cb);
<add> if (opts.terminal && env.NODE_REPL_HISTORY_FILE) {
<add> return setupHistory(repl, env.NODE_REPL_HISTORY_FILE, cb);
<ide> }
<ide> repl._historyPrev = _replHistoryMessage;
<ide> cb(null, repl);
<ide> function _replHistoryMessage() {
<ide> if (this.history.length === 0) {
<ide> this._writeToOutput(
<ide> '\nPersistent history support disabled. ' +
<del> 'Set the NODE_REPL_HISTORY_PATH environment variable to ' +
<add> 'Set the NODE_REPL_HISTORY_FILE environment variable to ' +
<ide> 'a valid, user-writable path to enable.\n'
<ide> );
<ide> this._refreshLine(); | 1 |
Mixed | Python | add maskedlm for keras_nlp | 96ca6e05d7d96d554cbb38bf7c7b6e14c1fc4031 | <ide><path>official/nlp/keras_nlp/README.md
<add># keras-nlp
<add>
<add>## Layers
<add>
<add>Layers are the fundamental building blocks for NLP models. They can be used to
<add>assemble new layers, networks, or models.
<add>
<add>* [TransformerEncoderBlock](layers/transformer_encoder_block.py) implements
<add> an optionally masked transformer as described in
<add> ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762).
<add>
<add>* [OnDeviceEmbedding](layers/on_device_embedding.py) implements efficient
<add> embedding lookups designed for TPU-based models.
<add>
<add>* [PositionalEmbedding](layers/position_embedding.py) creates a positional
<add> embedding as described in ["BERT: Pre-training of Deep Bidirectional
<add> Transformers for Language Understanding"](https://arxiv.org/abs/1810.04805).
<add>
<add>* [SelfAttentionMask](layers/self_attention_mask.py) creates a 3D attention
<add> mask from a 2D tensor mask.
<add>
<add>* [`MaskedLM`](layers/masked_lm.py) implements a masked language model. It
<add> assumes the embedding table variable is passed to it.
<add>
<add>
<add>## Encoders
<add>
<add>Encoders are combinations of layers (and possibly other encoders). They are
<add>sub-units of models that would not be trained alone. It encapsulates common
<add>network structures like a classification head or a transformer encoder into an
<add>easily handled object with a standardized configuration.
<add>
<add>* [`BertEncoder`](encoders/bert_encoder.py) implements a bi-directional
<add> Transformer-based encoder as described in
<add> ["BERT: Pre-training of Deep Bidirectional Transformers for Language
<add> Understanding"](https://arxiv.org/abs/1810.04805). It includes the embedding
<add> lookups, transformer layers and pooling layer.
<ide><path>official/nlp/keras_nlp/layers/__init__.py
<ide> # limitations under the License.
<ide> # ==============================================================================
<ide> """Keras-NLP layers package definition."""
<add>from official.nlp.keras_nlp.layers.masked_lm import MaskedLM
<ide> from official.nlp.keras_nlp.layers.on_device_embedding import OnDeviceEmbedding
<ide> from official.nlp.keras_nlp.layers.position_embedding import PositionEmbedding
<ide> from official.nlp.keras_nlp.layers.self_attention_mask import SelfAttentionMask
<ide><path>official/nlp/keras_nlp/layers/masked_lm.py
<add># Copyright 2019 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Masked language model network."""
<add># pylint: disable=g-classes-have-attributes
<add>import tensorflow as tf
<add>
<add>
<add>@tf.keras.utils.register_keras_serializable(package='keras_nlp')
<add>class MaskedLM(tf.keras.layers.Layer):
<add> """Masked language model network head for BERT modeling.
<add>
<add> This layer implements a masked language model based on the provided
<add> transformer based encoder. It assumes that the encoder network being passed
<add> has a "get_embedding_table()" method.
<add>
<add> Example:
<add> ```python
<add> encoder=keras_nlp.BertEncoder(...)
<add> lm_layer=MaskedLM(embedding_table=encoder.get_embedding_table())
<add> ```
<add>
<add> Arguments:
<add> embedding_table: The embedding table from encoder network.
<add> activation: The activation, if any, for the dense layer.
<add> initializer: The initializer for the dense layer. Defaults to a Glorot
<add> uniform initializer.
<add> output: The output style for this layer. Can be either 'logits' or
<add> 'predictions'.
<add> """
<add>
<add> def __init__(self,
<add> embedding_table,
<add> activation=None,
<add> initializer='glorot_uniform',
<add> output='logits',
<add> name=None,
<add> **kwargs):
<add> super(MaskedLM, self).__init__(name=name, **kwargs)
<add> self.embedding_table = embedding_table
<add> self.activation = activation
<add> self.initializer = tf.keras.initializers.get(initializer)
<add>
<add> if output not in ('predictions', 'logits'):
<add> raise ValueError(
<add> ('Unknown `output` value "%s". `output` can be either "logits" or '
<add> '"predictions"') % output)
<add> self._output_type = output
<add>
<add> def build(self, input_shape):
<add> self._vocab_size, hidden_size = self.embedding_table.shape
<add> self.dense = tf.keras.layers.Dense(
<add> hidden_size,
<add> activation=self.activation,
<add> kernel_initializer=self.initializer,
<add> name='transform/dense')
<add> self.layer_norm = tf.keras.layers.LayerNormalization(
<add> axis=-1, epsilon=1e-12, name='transform/LayerNorm')
<add> self.bias = self.add_weight(
<add> 'output_bias/bias',
<add> shape=(self._vocab_size,),
<add> initializer='zeros',
<add> trainable=True)
<add>
<add> super(MaskedLM, self).build(input_shape)
<add>
<add> def call(self, sequence_data, masked_positions):
<add> masked_lm_input = self._gather_indexes(sequence_data, masked_positions)
<add> lm_data = self.dense(masked_lm_input)
<add> lm_data = self.layer_norm(lm_data)
<add> lm_data = tf.matmul(lm_data, self.embedding_table, transpose_b=True)
<add> logits = tf.nn.bias_add(lm_data, self.bias)
<add>
<add> masked_positions_length = masked_positions.shape[1] or tf.shape(
<add> masked_positions)[1]
<add> logits = tf.reshape(logits,
<add> [-1, masked_positions_length, self._vocab_size])
<add> if self._output_type == 'logits':
<add> return logits
<add> return tf.nn.log_softmax(logits)
<add>
<add> def get_config(self):
<add> raise NotImplementedError('MaskedLM cannot be directly serialized because '
<add> 'it has variable sharing logic.')
<add>
<add> def _gather_indexes(self, sequence_tensor, positions):
<add> """Gathers the vectors at the specific positions.
<add>
<add> Args:
<add> sequence_tensor: Sequence output of `BertModel` layer of shape
<add> (`batch_size`, `seq_length`, num_hidden) where num_hidden is number of
<add> hidden units of `BertModel` layer.
<add> positions: Positions ids of tokens in sequence to mask for pretraining
<add> of with dimension (batch_size, num_predictions) where
<add> `num_predictions` is maximum number of tokens to mask out and predict
<add> per each sequence.
<add>
<add> Returns:
<add> Masked out sequence tensor of shape (batch_size * num_predictions,
<add> num_hidden).
<add> """
<add> sequence_shape = tf.shape(sequence_tensor)
<add> batch_size, seq_length = sequence_shape[0], sequence_shape[1]
<add> width = sequence_tensor.shape.as_list()[2] or sequence_shape[2]
<add>
<add> flat_offsets = tf.reshape(
<add> tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
<add> flat_positions = tf.reshape(positions + flat_offsets, [-1])
<add> flat_sequence_tensor = tf.reshape(sequence_tensor,
<add> [batch_size * seq_length, width])
<add> output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
<add>
<add> return output_tensor
<ide><path>official/nlp/modeling/layers/masked_lm.py
<ide> # ==============================================================================
<ide> """Masked language model network."""
<ide> # pylint: disable=g-classes-have-attributes
<del>import tensorflow as tf
<add>from official.nlp import keras_nlp
<ide>
<del>from official.modeling import tf_utils
<ide>
<del>
<del>@tf.keras.utils.register_keras_serializable(package='Text')
<del>class MaskedLM(tf.keras.layers.Layer):
<del> """Masked language model network head for BERT modeling.
<del>
<del> This network implements a masked language model based on the provided network.
<del> It assumes that the network being passed has a "get_embedding_table()" method.
<del>
<del> Arguments:
<del> embedding_table: The embedding table of the targets.
<del> activation: The activation, if any, for the dense layer.
<del> initializer: The initializer for the dense layer. Defaults to a Glorot
<del> uniform initializer.
<del> output: The output style for this network. Can be either 'logits' or
<del> 'predictions'.
<del> """
<del>
<del> def __init__(self,
<del> embedding_table,
<del> activation=None,
<del> initializer='glorot_uniform',
<del> output='logits',
<del> name='cls/predictions',
<del> **kwargs):
<del> super(MaskedLM, self).__init__(name=name, **kwargs)
<del> self.embedding_table = embedding_table
<del> self.activation = activation
<del> self.initializer = tf.keras.initializers.get(initializer)
<del>
<del> if output not in ('predictions', 'logits'):
<del> raise ValueError(
<del> ('Unknown `output` value "%s". `output` can be either "logits" or '
<del> '"predictions"') % output)
<del> self._output_type = output
<del>
<del> def build(self, input_shape):
<del> self._vocab_size, hidden_size = self.embedding_table.shape
<del> self.dense = tf.keras.layers.Dense(
<del> hidden_size,
<del> activation=self.activation,
<del> kernel_initializer=self.initializer,
<del> name='transform/dense')
<del> self.layer_norm = tf.keras.layers.LayerNormalization(
<del> axis=-1, epsilon=1e-12, name='transform/LayerNorm')
<del> self.bias = self.add_weight(
<del> 'output_bias/bias',
<del> shape=(self._vocab_size,),
<del> initializer='zeros',
<del> trainable=True)
<del>
<del> super(MaskedLM, self).build(input_shape)
<del>
<del> def call(self, sequence_data, masked_positions):
<del> masked_lm_input = self._gather_indexes(sequence_data, masked_positions)
<del> lm_data = self.dense(masked_lm_input)
<del> lm_data = self.layer_norm(lm_data)
<del> lm_data = tf.matmul(lm_data, self.embedding_table, transpose_b=True)
<del> logits = tf.nn.bias_add(lm_data, self.bias)
<del>
<del> masked_positions_shape = tf_utils.get_shape_list(
<del> masked_positions, name='masked_positions_tensor')
<del> logits = tf.reshape(logits,
<del> [-1, masked_positions_shape[1], self._vocab_size])
<del> if self._output_type == 'logits':
<del> return logits
<del> return tf.nn.log_softmax(logits)
<del>
<del> def get_config(self):
<del> raise NotImplementedError('MaskedLM cannot be directly serialized because '
<del> 'it has variable sharing logic.')
<del>
<del> def _gather_indexes(self, sequence_tensor, positions):
<del> """Gathers the vectors at the specific positions.
<del>
<del> Args:
<del> sequence_tensor: Sequence output of `BertModel` layer of shape
<del> (`batch_size`, `seq_length`, num_hidden) where num_hidden is number of
<del> hidden units of `BertModel` layer.
<del> positions: Positions ids of tokens in sequence to mask for pretraining
<del> of with dimension (batch_size, num_predictions) where
<del> `num_predictions` is maximum number of tokens to mask out and predict
<del> per each sequence.
<del>
<del> Returns:
<del> Masked out sequence tensor of shape (batch_size * num_predictions,
<del> num_hidden).
<del> """
<del> sequence_shape = tf_utils.get_shape_list(
<del> sequence_tensor, name='sequence_output_tensor')
<del> batch_size, seq_length, width = sequence_shape
<del>
<del> flat_offsets = tf.reshape(
<del> tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
<del> flat_positions = tf.reshape(positions + flat_offsets, [-1])
<del> flat_sequence_tensor = tf.reshape(sequence_tensor,
<del> [batch_size * seq_length, width])
<del> output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
<del>
<del> return output_tensor
<add>MaskedLM = keras_nlp.layers.MaskedLM | 4 |
Javascript | Javascript | fix jshint task | 6001a1e4e7d4a572e70cd55c049449ac85cbe134 | <ide><path>gulpfile.js
<ide> function releaseTask() {
<ide>
<ide>
<ide> function jshintTask() {
<del> return gulp.src(srcDir + '*.js')
<add> return gulp.src(srcDir + '**/*.js')
<ide> .pipe(jshint())
<ide> .pipe(jshint.reporter('default'));
<ide> } | 1 |
Go | Go | fix empty-lines (revive) | ecb4ed172b8ec01819c62b95d6ece5fe184637e1 | <ide><path>builder/builder-next/adapters/containerimage/pull.go
<ide> func (is *Source) Resolve(ctx context.Context, id source.Identifier, sm *session
<ide> p := &puller{
<ide> src: imageIdentifier,
<ide> is: is,
<del> //resolver: is.getResolver(is.RegistryHosts, imageIdentifier.Reference.String(), sm, g),
<add> // resolver: is.getResolver(is.RegistryHosts, imageIdentifier.Reference.String(), sm, g),
<ide> platform: platform,
<ide> sm: sm,
<ide> }
<ide> func (p *puller) Snapshot(ctx context.Context, g session.Group) (cache.Immutable
<ide> // TODO: Optimize to do dispatch and integrate pulling with download manager,
<ide> // leverage existing blob mapping and layer storage
<ide> } else {
<del>
<ide> // TODO: need a wrapper snapshot interface that combines content
<ide> // and snapshots as 1) buildkit shouldn't have a dependency on contentstore
<ide> // or 2) cachemanager should manage the contentstore
<ide><path>builder/builder-next/adapters/localinlinecache/inlinecache.go
<ide> import (
<ide>
<ide> // ResolveCacheImporterFunc returns a resolver function for local inline cache
<ide> func ResolveCacheImporterFunc(sm *session.Manager, resolverFunc docker.RegistryHosts, cs content.Store, rs reference.Store, is imagestore.Store) remotecache.ResolveCacheImporterFunc {
<del>
<ide> upstream := registryremotecache.ResolveCacheImporterFunc(sm, cs, resolverFunc)
<ide>
<ide> return func(ctx context.Context, group session.Group, attrs map[string]string) (remotecache.Importer, specs.Descriptor, error) {
<ide><path>builder/dockerfile/builder.go
<ide> func (b *Builder) dispatchDockerfileWithCancellation(parseResult []instructions.
<ide> }
<ide> dispatchRequest.state.updateRunConfig()
<ide> fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
<del>
<ide> }
<ide> if err := emitImageID(b.Aux, dispatchRequest.state); err != nil {
<ide> return nil, err
<ide><path>builder/dockerfile/copy.go
<ide> func copierFromDispatchRequest(req dispatchRequest, download sourceDownloader, i
<ide> imageSource: imageSource,
<ide> platform: platform,
<ide> }
<del>
<ide> }
<ide>
<ide> func (o *copier) createCopyInstruction(sourcesAndDest instructions.SourcesAndDest, cmdName string) (copyInstruction, error) {
<ide><path>builder/dockerfile/dispatchers.go
<ide> func dispatchEnv(d dispatchRequest, c *instructions.EnvCommand) error {
<ide> //
<ide> // Sets the maintainer metadata.
<ide> func dispatchMaintainer(d dispatchRequest, c *instructions.MaintainerCommand) error {
<del>
<ide> d.state.maintainer = c.Maintainer
<ide> return d.builder.commit(d.state, "MAINTAINER "+c.Maintainer)
<ide> }
<ide> func dispatchVolume(d dispatchRequest, c *instructions.VolumeCommand) error {
<ide> //
<ide> // Set the signal that will be used to kill the container.
<ide> func dispatchStopSignal(d dispatchRequest, c *instructions.StopSignalCommand) error {
<del>
<ide> _, err := signal.ParseSignal(c.Signal)
<ide> if err != nil {
<ide> return errdefs.InvalidParameter(err)
<ide><path>builder/dockerfile/dispatchers_test.go
<ide> func TestHealthcheckNone(t *testing.T) {
<ide> }
<ide>
<ide> func TestHealthcheckCmd(t *testing.T) {
<del>
<ide> b := newBuilderWithMockBackend()
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> expectedTest := []string{"CMD-SHELL", "curl -f http://localhost/ || exit 1"}
<ide><path>builder/dockerfile/internals_test.go
<ide> func TestCopyRunConfig(t *testing.T) {
<ide> // Assert the original was not modified
<ide> assert.Check(t, runConfig != runConfigCopy, testcase.doc)
<ide> }
<del>
<ide> }
<ide>
<ide> func fullMutableRunConfig() *container.Config {
<ide><path>builder/remotecontext/detect_test.go
<ide> func TestProcessShouldRemoveDockerfileDockerignore(t *testing.T) {
<ide> executeProcess(t, contextDir)
<ide>
<ide> checkDirectory(t, contextDir, []string{shouldStayFilename})
<del>
<ide> }
<ide>
<ide> func TestProcessNoDockerignore(t *testing.T) {
<ide> func TestProcessNoDockerignore(t *testing.T) {
<ide> executeProcess(t, contextDir)
<ide>
<ide> checkDirectory(t, contextDir, []string{shouldStayFilename, builder.DefaultDockerfileName})
<del>
<ide> }
<ide>
<ide> func TestProcessShouldLeaveAllFiles(t *testing.T) {
<ide> func TestProcessShouldLeaveAllFiles(t *testing.T) {
<ide> executeProcess(t, contextDir)
<ide>
<ide> checkDirectory(t, contextDir, []string{shouldStayFilename, builder.DefaultDockerfileName, dockerignoreFilename})
<del>
<ide> }
<ide>
<ide> // TODO: remove after moving to a separate pkg | 8 |
Python | Python | set version to 2.1.0a2 | 5fc98ade04fef211cfc617129fb2103fabd0f1cc | <ide><path>spacy/about.py
<ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
<ide>
<ide> __title__ = 'spacy-nightly'
<del>__version__ = '2.1.0a1'
<add>__version__ = '2.1.0a2'
<ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
<ide> __uri__ = 'https://spacy.io'
<ide> __author__ = 'Explosion AI'
<ide> __email__ = 'contact@explosion.ai'
<ide> __license__ = 'MIT'
<del>__release__ = False
<add>__release__ = True
<ide>
<ide> __download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
<ide> __compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json' | 1 |
PHP | PHP | fix failing tests | 89ecd95e55c16259f9222ea3e00dd1c6eeaa7293 | <ide><path>lib/Cake/Controller/Component/Auth/BasicAuthenticate.php
<ide> public function getUser(CakeRequest $request) {
<ide> *
<ide> * @param CakeRequest $request A request object.
<ide> * @param CakeResponse $response A response object.
<del> * @return boolean True
<add> * @return void
<add> * @throws UnauthorizedException
<ide> */
<ide> public function unauthenticated(CakeRequest $request, CakeResponse $response) {
<ide> $Exception = new UnauthorizedException();
<del> $Exception->responseHeader($this->loginHeaders());
<add> $Exception->responseHeader(array($this->loginHeaders()));
<ide> throw $Exception;
<del> return true;
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Controller/Component/Auth/BasicAuthenticateTest.php
<ide> public function testAuthenticateChallenge() {
<ide> $request = new CakeRequest('posts/index', false);
<ide> $request->addParams(array('pass' => array(), 'named' => array()));
<ide>
<del> $this->response->expects($this->at(0))
<del> ->method('header')
<del> ->with('WWW-Authenticate: Basic realm="localhost"');
<add> try {
<add> $this->auth->unauthenticated($request, $this->response);
<add> } catch (UnauthorizedException $e) {}
<ide>
<del> $this->response->expects($this->at(1))
<del> ->method('send');
<add> $this->assertNotEmpty($e);
<ide>
<del> $result = $this->auth->unauthenticated($request, $this->response);
<del> $this->assertTrue($result);
<add> $expected = array('WWW-Authenticate: Basic realm="localhost"');
<add> $this->assertEquals($expected, $e->responseHeader());
<ide> }
<ide>
<ide> /**
<ide> public function testAuthenticateSuccess() {
<ide> /**
<ide> * test scope failure.
<ide> *
<add> * @expectedException UnauthorizedException
<add> * @expectedExceptionCode 401
<ide> * @return void
<ide> */
<ide> public function testAuthenticateFailReChallenge() {
<ide> public function testAuthenticateFailReChallenge() {
<ide> $_SERVER['PHP_AUTH_USER'] = 'mariano';
<ide> $_SERVER['PHP_AUTH_PW'] = 'password';
<ide>
<del> $this->response->expects($this->at(0))
<del> ->method('header')
<del> ->with('WWW-Authenticate: Basic realm="localhost"');
<del>
<del> $this->response->expects($this->at(1))
<del> ->method('statusCode')
<del> ->with(401);
<del>
<del> $this->response->expects($this->at(2))
<del> ->method('send');
<del>
<del> $this->assertTrue($this->auth->unauthenticated($request, $this->response));
<add> $this->auth->unauthenticated($request, $this->response);
<ide> }
<ide>
<ide> }
<ide><path>lib/Cake/Test/Case/Controller/Component/Auth/DigestAuthenticateTest.php
<ide> public function testAuthenticateNoData() {
<ide> /**
<ide> * test the authenticate method
<ide> *
<add> * @expectedException UnauthorizedException
<add> * @expectedExceptionCode 401
<ide> * @return void
<ide> */
<ide> public function testAuthenticateWrongUsername() {
<ide> public function testAuthenticateWrongUsername() {
<ide> opaque="123abc"
<ide> DIGEST;
<ide>
<del> $this->response->expects($this->at(0))
<del> ->method('header')
<del> ->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
<del>
<del> $this->response->expects($this->at(1))
<del> ->method('statusCode')
<del> ->with(401);
<del>
<del> $this->response->expects($this->at(2))
<del> ->method('send');
<del>
<del> $this->assertTrue($this->auth->unauthenticated($request, $this->response));
<add> $this->auth->unauthenticated($request, $this->response);
<ide> }
<ide>
<ide> /**
<ide> public function testAuthenticateChallenge() {
<ide> $request = new CakeRequest('posts/index', false);
<ide> $request->addParams(array('pass' => array(), 'named' => array()));
<ide>
<del> $this->response->expects($this->at(0))
<del> ->method('header')
<del> ->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
<del>
<del> $this->response->expects($this->at(1))
<del> ->method('statusCode')
<del> ->with(401);
<add> try {
<add> $this->auth->unauthenticated($request, $this->response);
<add> } catch (UnauthorizedException $e) {}
<ide>
<del> $this->response->expects($this->at(2))
<del> ->method('send');
<add> $this->assertNotEmpty($e);
<ide>
<del> $result = $this->auth->unauthenticated($request, $this->response);
<del> $this->assertTrue($result);
<add> $expected = array('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
<add> $this->assertEquals($expected, $e->responseHeader());
<ide> }
<ide>
<ide> /**
<ide> public function testAuthenticateSuccess() {
<ide> /**
<ide> * test scope failure.
<ide> *
<add> * @expectedException UnauthorizedException
<add> * @expectedExceptionCode 401
<ide> * @return void
<ide> */
<ide> public function testAuthenticateFailReChallenge() {
<ide> public function testAuthenticateFailReChallenge() {
<ide> opaque="123abc"
<ide> DIGEST;
<ide>
<del> $this->response->expects($this->at(0))
<del> ->method('header')
<del> ->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
<del>
<del> $this->response->expects($this->at(1))
<del> ->method('statusCode')
<del> ->with(401);
<del>
<del> $this->response->expects($this->at(2))
<del> ->method('send');
<del>
<del> $this->assertTrue($this->auth->unauthenticated($request, $this->response));
<add> $this->auth->unauthenticated($request, $this->response);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php
<ide> public function testUser() {
<ide> /**
<ide> * testStatelessAuthNoRedirect method
<ide> *
<add> * @expectedException UnauthorizedException
<add> * @expectedExceptionCode 401
<ide> * @return void
<ide> */
<ide> public function testStatelessAuthNoRedirect() {
<ide> public function testStatelessAuthNoRedirect() {
<ide> $this->Auth->authenticate = array('Basic');
<ide> $this->Controller->request['action'] = 'admin_add';
<ide>
<del> $this->Auth->response->expects($this->once())
<del> ->method('statusCode')
<del> ->with(401);
<del>
<del> $this->Auth->response->expects($this->once())
<del> ->method('send');
<del>
<del> $result = $this->Auth->startup($this->Controller);
<del> $this->assertFalse($result);
<del>
<del> $this->assertNull($this->Controller->testUrl);
<del> $this->assertNull(CakeSession::id());
<add> $this->Auth->startup($this->Controller);
<ide> }
<ide>
<ide> /** | 4 |
Javascript | Javascript | ensure failed assertions cause build to fail | 8995125c1427545118f68e82eea2a622878af875 | <ide><path>test/parallel/test-assert-async.js
<ide> const wait = promisify(setTimeout);
<ide> // Test assert.rejects() and assert.doesNotReject() by checking their
<ide> // expected output and by verifying that they do not work sync
<ide>
<del>assert.rejects(
<del> () => assert.fail(),
<del> common.expectsError({
<del> code: 'ERR_ASSERTION',
<del> type: assert.AssertionError,
<del> message: 'Failed'
<del> })
<del>);
<add>common.crashOnUnhandledRejection();
<ide>
<del>assert.doesNotReject(() => {});
<add>(async () => {
<add> await assert.rejects(
<add> () => assert.fail(),
<add> common.expectsError({
<add> code: 'ERR_ASSERTION',
<add> type: assert.AssertionError,
<add> message: 'Failed'
<add> })
<add> );
<ide>
<del>{
<del> const promise = assert.rejects(async () => {
<del> await wait(1);
<del> assert.fail();
<del> }, common.expectsError({
<del> code: 'ERR_ASSERTION',
<del> type: assert.AssertionError,
<del> message: 'Failed'
<del> }));
<del> assert.doesNotReject(() => promise);
<del>}
<add> await assert.doesNotReject(() => {});
<ide>
<del>{
<del> const promise = assert.doesNotReject(async () => {
<del> await wait(1);
<del> throw new Error();
<del> });
<del> assert.rejects(() => promise,
<del> (err) => {
<del> assert(err instanceof assert.AssertionError,
<del> `${err.name} is not instance of AssertionError`);
<del> assert.strictEqual(err.code, 'ERR_ASSERTION');
<del> assert(/^Got unwanted rejection\.\n$/.test(err.message));
<del> assert.strictEqual(err.operator, 'doesNotReject');
<del> assert.ok(!err.stack.includes('at Function.doesNotReject'));
<del> return true;
<del> }
<del> );
<del>}
<add> {
<add> const promise = assert.doesNotReject(async () => {
<add> await wait(1);
<add> throw new Error();
<add> });
<add> await assert.rejects(
<add> () => promise,
<add> (err) => {
<add> assert(err instanceof assert.AssertionError,
<add> `${err.name} is not instance of AssertionError`);
<add> assert.strictEqual(err.code, 'ERR_ASSERTION');
<add> assert(/^Got unwanted rejection\.\n$/.test(err.message));
<add> assert.strictEqual(err.operator, 'doesNotReject');
<add> assert.ok(!err.stack.includes('at Function.doesNotReject'));
<add> return true;
<add> }
<add> );
<add> }
<ide>
<del>{
<del> const promise = assert.rejects(() => {});
<del> assert.rejects(() => promise,
<del> (err) => {
<del> assert(err instanceof assert.AssertionError,
<del> `${err.name} is not instance of AssertionError`);
<del> assert.strictEqual(err.code, 'ERR_ASSERTION');
<del> assert(/^Missing expected rejection\.$/.test(err.message));
<del> assert.strictEqual(err.operator, 'rejects');
<del> assert.ok(!err.stack.includes('at Function.rejects'));
<del> return true;
<del> }
<del> );
<del>}
<add> {
<add> const promise = assert.rejects(() => {});
<add> await assert.rejects(
<add> () => promise,
<add> (err) => {
<add> assert(err instanceof assert.AssertionError,
<add> `${err.name} is not instance of AssertionError`);
<add> assert.strictEqual(err.code, 'ERR_ASSERTION');
<add> assert(/^Missing expected rejection\.$/.test(err.message));
<add> assert.strictEqual(err.operator, 'rejects');
<add> assert.ok(!err.stack.includes('at Function.rejects'));
<add> return true;
<add> }
<add> );
<add> }
<add>})().then(common.mustCall()); | 1 |
Javascript | Javascript | fix failing unit tests due to deferred teardown | 8118866ef1c6838a5c08ac3b1a9d092fd023f835 | <ide><path>packages/ember-application/tests/system/application_test.js
<ide> test("acts like a namespace", function() {
<ide> });
<ide> app.Foo = Ember.Object.extend();
<ide> equal(app.Foo.toString(), "TestApp.Foo", "Classes pick up their parent namespace");
<del> app.destroy();
<add> Ember.run(function() {
<add> app.destroy();
<add> });
<ide> window.TestApp = undefined;
<ide> });
<ide>
<ide> module("Ember.Application initialization", {
<ide> });
<ide>
<ide> test("initialize controllers into a state manager", function() {
<del> app = Ember.Application.create();
<add> Ember.run(function() {
<add> app = Ember.Application.create();
<add> });
<ide>
<ide> app.FooController = Ember.Object.extend();
<ide> app.BarController = Ember.ArrayController.extend();
<ide><path>packages/ember-handlebars/tests/controls/select_test.js
<ide> module("Ember.Select", {
<ide> },
<ide>
<ide> teardown: function() {
<del> dispatcher.destroy();
<del> select.destroy();
<add> Ember.run(function() {
<add> dispatcher.destroy();
<add> select.destroy();
<add> });
<ide> }
<ide> });
<ide>
<ide> module("Ember.Select - usage inside templates", {
<ide> },
<ide>
<ide> teardown: function() {
<del> dispatcher.destroy();
<add> Ember.run(function() {
<add> dispatcher.destroy();
<add> });
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-handlebars/tests/controls/text_area_test.js
<ide> module("Ember.TextArea", {
<ide> },
<ide>
<ide> teardown: function() {
<del> textArea.destroy();
<add> Ember.run(function() {
<add> textArea.destroy();
<add> });
<ide> TestObject = textArea = null;
<ide> }
<ide> });
<ide><path>packages/ember-handlebars/tests/controls/text_field_test.js
<ide> module("Ember.TextField", {
<ide> },
<ide>
<ide> teardown: function() {
<del> textField.destroy();
<add> Ember.run(function() {
<add> textField.destroy();
<add> });
<ide> TestObject = textField = null;
<ide> }
<ide> });
<ide><path>packages/ember-handlebars/tests/handlebars_test.js
<ide> module("Ember.View - handlebars integration", {
<ide>
<ide> teardown: function() {
<ide> if (view) {
<del> view.destroy();
<add> Ember.run(function() {
<add> view.destroy();
<add> });
<ide> view = null;
<ide> }
<ide> window.TemplateTests = undefined;
<ide> test("Handlebars templates update properties if a content object changes", funct
<ide>
<ide> equal(view.$('#price').text(), "$5", "should update price field when price property is changed");
<ide>
<del> view.destroy();
<add> Ember.run(function() {
<add> view.destroy();
<add> });
<ide> });
<ide>
<ide> test("Template updates correctly if a path is passed to the bind helper", function() {
<ide> test("should warn if setting a template on a view with a templateName already sp
<ide> appendView();
<ide> }, Error, "raises if conflicting template and templateName are provided");
<ide>
<del> view.destroy();
<add> Ember.run(function() {
<add> view.destroy();
<add> });
<ide>
<ide> view = Ember.View.create({
<ide> childView: Ember.View.extend(),
<ide> test("Collection views that specify an example view class have their children be
<ide>
<ide> ok(firstGrandchild(parentView).isCustom, "uses the example view class");
<ide>
<del> parentView.destroy();
<add> Ember.run(function() {
<add> parentView.destroy();
<add> });
<ide> });
<ide>
<ide> test("itemViewClass works in the #collection helper", function() {
<ide> test("itemViewClass works in the #collection helper", function() {
<ide>
<ide> ok(firstGrandchild(parentView).isAlsoCustom, "uses the example view class specified in the #collection helper");
<ide>
<del> parentView.destroy();
<add> Ember.run(function() {
<add> parentView.destroy();
<add> });
<ide> });
<ide>
<ide> test("itemViewClass works in the #collection helper relatively", function() {
<ide> test("itemViewClass works in the #collection helper relatively", function() {
<ide>
<ide> ok(firstGrandchild(parentView).isAlsoCustom, "uses the example view class specified in the #collection helper");
<ide>
<del> parentView.destroy();
<add> Ember.run(function() {
<add> parentView.destroy();
<add> });
<ide> });
<ide>
<ide> test("should update boundIf blocks if the conditional changes", function() {
<ide> test("should not reset cursor position when text field receives keyUp event", fu
<ide>
<ide> equal(view.$().caretPosition(), 5, "The keyUp event should not result in the cursor being reset due to the bindAttr observers");
<ide>
<del> view.destroy();
<add> Ember.run(function() {
<add> view.destroy();
<add> });
<ide> });
<ide>
<ide> test("should be able to bind element attributes using {{bindAttr}} inside a block", function() {
<ide> test("should expose a controller keyword when present on the view", function() {
<ide>
<ide> equal(view.$().text(), "BARBLARGH", "updates the DOM when a bound value is updated");
<ide>
<del> view.destroy();
<add> Ember.run(function() {
<add> view.destroy();
<add> });
<ide>
<ide> view = Ember.View.create({
<ide> controller: "aString",
<ide> module("Templates redrawing and bindings", {
<ide> MyApp = Ember.Object.create({});
<ide> },
<ide> teardown: function(){
<del> if (view) view.destroy();
<add> Ember.run(function() {
<add> if (view) view.destroy();
<add> });
<ide> window.MyApp = null;
<ide> }
<ide> });
<ide> test("bindings can be 'this', in which case they *are* the current context", fun
<ide> test("should not enter an infinite loop when binding an attribute in Handlebars", function() {
<ide> expect(0);
<ide>
<del> App = Ember.Application.create();
<add> Ember.run(function() {
<add> App = Ember.Application.create();
<add> });
<add>
<ide> App.test = Ember.Object.create({ href: 'test' });
<ide> App.Link = Ember.View.extend({
<ide> classNames: ['app-link'],
<ide> test("should not enter an infinite loop when binding an attribute in Handlebars"
<ide> });
<ide> // equal(view.$().attr('href'), 'test');
<ide>
<del> parentView.destroy();
<add> Ember.run(function() {
<add> parentView.destroy();
<add> });
<ide>
<ide> Ember.run(function() {
<ide> App.destroy();
<ide><path>packages/ember-handlebars/tests/views/collection_view_test.js
<ide> test("collection helper should accept relative paths", function() {
<ide> });
<ide>
<ide> test("empty views should be removed when content is added to the collection (regression, ht: msofaer)", function() {
<del> window.App = Ember.Application.create();
<add> Ember.run(function() {
<add> window.App = Ember.Application.create();
<add> });
<ide>
<ide> App.EmptyView = Ember.View.extend({
<ide> template : Ember.Handlebars.compile("<td>No Rows Yet</td>")
<ide><path>packages/ember-states/tests/state_manager_test.js
<ide> module("Ember.StateManager", {
<ide> },
<ide>
<ide> teardown: function() {
<del> if (stateManager) {
<del> stateManager.destroy();
<del> }
<add> Ember.run(function() {
<add> if (stateManager) {
<add> stateManager.destroy();
<add> }
<add> });
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-views/tests/system/event_dispatcher_test.js
<ide> var set = Ember.set, get = Ember.get;
<ide>
<ide> module("Ember.EventDispatcher", {
<ide> setup: function() {
<del> dispatcher = Ember.EventDispatcher.create();
<del> dispatcher.setup();
<add> Ember.run(function() {
<add> dispatcher = Ember.EventDispatcher.create();
<add> dispatcher.setup();
<add> });
<ide> },
<ide>
<ide> teardown: function() {
<del> if (view) { view.destroy(); }
<del> dispatcher.destroy();
<add> Ember.run(function() {
<add> if (view) { view.destroy(); }
<add> dispatcher.destroy();
<add> });
<ide> }
<ide> });
<ide>
<ide> test("events should stop propagating if the view is destroyed", function() {
<ide>
<ide> change: function(evt) {
<ide> receivedEvent = true;
<del> get(this, 'parentView').destroy();
<add> var self = this;
<add> Ember.run(function() {
<add> get(self, 'parentView').destroy();
<add> });
<ide> }
<ide> });
<ide> | 8 |
Python | Python | fix flake8 error | 64febd83cc72fed286e9d5d0cdcd113e5ab1246a | <ide><path>celery/concurrency/asynpool.py
<ide> def _select(readers=None, writers=None, err=None, timeout=0,
<ide> errno = exc.errno
<ide> except AttributeError:
<ide> errno = exc.args[0]
<del>
<add>
<ide> if errno == errno.EINTR:
<ide> return set(), set(), 1
<ide> elif errno in SELECT_BAD_FD: | 1 |
PHP | PHP | remove deprecated test | d9670cae26efbb3214fb8f28aa266a62e036e699 | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testCreateAutoUrl()
<ide> */
<ide> public function testCreateNoUrl()
<ide> {
<del> $result = $this->Form->create(false, ['url' => false]);
<add> $result = $this->Form->create(false, ['url' => ['action' => false]]);
<ide> $expected = [
<ide> 'form' => [
<ide> 'method' => 'post',
<ide> public function testCreateNoUrl()
<ide> '/div'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<del>
<del> $result = $this->Form->create(false, ['url' => ['action' => false]]);
<del> $this->assertHtml($expected, $result);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | update vm.md for link linting | c4de76f7a66d285d5914e329663f65f4c6e69381 | <ide><path>doc/api/vm.md
<ide> flag enabled.*
<ide> The `vm.SourceTextModule` class provides the [Source Text Module Record][] as
<ide> defined in the ECMAScript specification.
<ide>
<del>### Constructor: new vm.SourceTextModule(code[, options])
<add>### Constructor: new vm.SourceTextModule(code\[, options\])
<ide>
<ide> * `code` {string} JavaScript Module code to parse
<ide> * `options`
<ide> const module = new vm.SyntheticModule(['default'], function() {
<ide> // Use `module` in linking...
<ide> ```
<ide>
<del>### Constructor: new vm.SyntheticModule(exportNames, evaluateCallback[, options])
<add>### Constructor: new vm.SyntheticModule(exportNames, evaluateCallback\[, options\])
<ide> <!-- YAML
<ide> added: REPLACEME
<ide> -->
<ide> queues.
<ide> [GetModuleNamespace]: https://tc39.es/ecma262/#sec-getmodulenamespace
<ide> [HostResolveImportedModule]: https://tc39.es/ecma262/#sec-hostresolveimportedmodule
<ide> [Link() concrete method]: https://tc39.es/ecma262/#sec-moduledeclarationlinking
<add>[Module Record]: https://www.ecma-international.org/ecma-262/#sec-abstract-module-records
<ide> [Source Text Module Record]: https://tc39.es/ecma262/#sec-source-text-module-records
<ide> [Synthetic Module Record]: https://heycam.github.io/webidl/#synthetic-module-records
<ide> [V8 Embedder's Guide]: https://v8.dev/docs/embed#contexts | 1 |
Python | Python | fix valueerror typo | c2e4c9c034a3446de643fb4f8e96d21249abb7b9 | <ide><path>numpy/polynomial/hermite_e.py
<ide> def hermefit(x, y, deg, rcond=None, full=False, w=None):
<ide>
<ide> # check arguments.
<ide> if deg < 0 :
<del> raise valueerror, "expected deg >= 0"
<add> raise ValueError, "expected deg >= 0"
<ide> if x.ndim != 1:
<ide> raise TypeError, "expected 1D vector for x"
<ide> if x.size == 0: | 1 |
Javascript | Javascript | publish glimmer builds to s3 | a233059b52fa865eac093f6076bf8736d49afe18 | <ide><path>config/s3ProjectConfig.js
<ide> function fileObject(baseName, extension, contentType, currentRevision, tag, date
<ide> var obj = {
<ide> contentType: contentType,
<ide> destinations: {
<add> glimmer: [
<add> "glimmer" + fullName,
<add> "canary/shas/" + currentRevision + fullName
<add> ],
<ide> canary: [
<ide> "latest" + fullName,
<ide> "canary" + fullName, | 1 |
Text | Text | add option to require 'process' to api docs | 136c805b6e4dbcb8996ecad7a7d882fbf83e3e7c | <ide><path>doc/api/process.md
<ide>
<ide> The `process` object is a `global` that provides information about, and control
<ide> over, the current Node.js process. As a global, it is always available to
<del>Node.js applications without using `require()`.
<add>Node.js applications without using `require()`. It can also be explicitly
<add>accessed using `require()`:
<add>
<add>```js
<add>const process = require('process');
<add>```
<ide>
<ide> ## Process Events
<ide> | 1 |
Javascript | Javascript | remove memory fix | 329d5e1d0328a5e638d4041e913fe1faccd919f3 | <ide><path>src/manipulation.js
<ide> jQuery.fn.extend({
<ide> // Hope ajax is available...
<ide> jQuery.ajax({
<ide> url: node.src,
<del> type: "GET",
<ide> dataType: "script",
<ide> async: false,
<ide> global: false,
<ide> jQuery.fn.extend({
<ide> }
<ide> }
<ide> }
<del>
<del> // Fix #11809: Avoid leaking memory
<del> fragment = first = null;
<ide> }
<ide> }
<ide>
<ide> jQuery.extend({
<ide> setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
<ide> }
<ide>
<del> destElements = srcElements = node = null;
<del>
<ide> // Return the cloned set
<ide> return clone;
<ide> }, | 1 |
Javascript | Javascript | remove unused _valuedidchange function | 7e07f49637323180f8896a6480aa449ebe48faf3 | <ide><path>packages/sproutcore-handlebars/lib/controls/text_field.js
<ide> SC.TextField = SC.View.extend(
<ide> set(this, 'value', this.$().val());
<ide> },
<ide>
<del> _valueDidChange: function() {
<del> SC.run.once(this, this._updateElementValue);
<del> },
<del>
<ide> _updateElementValue: function() {
<ide> this.$().val(get(this, 'value'));
<ide> } | 1 |
Text | Text | add github actions badge to readme | befff3eb7af36e0fef4cbec3bd9ef5575ee03b90 | <ide><path>README.md
<ide> # Apache Airflow
<ide>
<ide> [](https://badge.fury.io/py/apache-airflow)
<add>
<ide> [](https://travis-ci.org/apache/airflow)
<ide> [](https://codecov.io/github/apache/airflow?branch=master)
<ide> [](https://airflow.readthedocs.io/en/latest/?badge=latest) | 1 |
Javascript | Javascript | move texture.image order | ae249e1bf75acb093a87d2ef32335968ad76e6cd | <ide><path>src/loaders/TextureLoader.js
<ide> Object.assign( TextureLoader.prototype, {
<ide> var loader = new ImageLoader( this.manager );
<ide> loader.setCrossOrigin( this.crossOrigin );
<ide> loader.setPath( this.path );
<del> loader.load( url, function ( image ) {
<add> var image = loader.load( url, function ( image ) {
<ide>
<ide> // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
<ide> var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
<ide>
<ide> texture.format = isJPEG ? RGBFormat : RGBAFormat;
<del> texture.image = image;
<ide> texture.needsUpdate = true;
<ide>
<ide> if ( onLoad !== undefined ) {
<ide> Object.assign( TextureLoader.prototype, {
<ide>
<ide> }, onProgress, onError );
<ide>
<add> texture.image = image;
<ide> return texture;
<ide>
<ide> }, | 1 |
Text | Text | update example url for add_source | 706063f1eef607746f264822194d1457051d4d68 | <ide><path>guides/source/rails_application_templates.md
<ide> end
<ide>
<ide> Adds the given source to the generated application's `Gemfile`.
<ide>
<del>For example, if you need to source a gem from `"http://code.whytheluckystiff.net"`:
<add>For example, if you need to source a gem from `"http://gems.github.com"`:
<ide>
<ide> ```ruby
<del>add_source "http://code.whytheluckystiff.net"
<add>add_source "http://gems.github.com"
<ide> ```
<ide>
<ide> If block is given, gem entries in block are wrapped into the source group. | 1 |
Text | Text | add reference to backbone-redux-migrator | 55db7dd29e7750cd0f48f96736bec16cf8b577bf | <ide><path>docs/recipes/MigratingToRedux.md
<ide> Your process will look like this:
<ide> ## From Backbone
<ide>
<ide> Backbone's model layer is quite different from Redux, so we don't suggest mixing them. If possible, it is best that you rewrite your app's model layer from scratch instead of connecting Backbone to Redux. However, if a rewrite is not feasible, you may use [backbone-redux](https://github.com/redbooth/backbone-redux) to migrate gradually, and keep the Redux store in sync with Backbone models and collections.
<add>
<add>If your Backbone codebase is too big for a quick rewrite or you don't want to manage interactions between store and models, use [backbone-redux-migrator](https://github.com/naugtur/backbone-redux-migrator) to help your two codebases coexist while keeping healthy separation. Once your rewrite finishes, Backbone code can be discarded and your Redux application can work on its own once you configure router. | 1 |
Go | Go | update sig message | ac9b06ae95f1da8407934036ab1e4019a96a6b21 | <ide><path>server/server.go
<ide> func InitServer(job *engine.Job) engine.Status {
<ide> gosignal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
<ide> go func() {
<ide> sig := <-c
<del> log.Printf("Received signal '%v', exiting\n", sig)
<add> log.Printf("Received signal '%v', starting shutdown of docker...\n", sig)
<ide> utils.RemovePidFile(srv.runtime.Config().Pidfile)
<ide> srv.Close()
<ide> os.Exit(0) | 1 |
Javascript | Javascript | add test for enter-append | c88d9d14c9b4343e2dc78ae9ef2b1740c48b3d98 | <ide><path>test/core/selection-append-test.js
<ide> suite.addBatch({
<ide> }
<ide> });
<ide>
<del>// TODO enter().append()
<add>suite.addBatch({
<add> "selectAll(div).data(…).enter()": {
<add> topic: function() {
<add> return d3.select("body");
<add> },
<add> "appends to the parent node": function(body) {
<add> var div = body.html("").selectAll("div").data(d3.range(2)).enter().append("div");
<add> assert.equal(div.length, 1);
<add> assert.equal(div[0].length, 2);
<add> assert.domEqual(div[0][0].parentNode, document.body);
<add> assert.domEqual(div[0][1].parentNode, document.body);
<add> },
<add> "propagates data to new elements": function(body) {
<add> var a = new Object(), b = new Object(), div = body.html("").selectAll("div").data([a, b]).enter().append("div");
<add> assert.strictEqual(div[0][0].__data__, a);
<add> assert.strictEqual(div[0][1].__data__, b);
<add> },
<add> "ignores null nodes": function(body) {
<add> body.html("").append("div");
<add> var div = body.selectAll("div").data(d3.range(3)).enter().append("div");
<add> assert.equal(div.length, 1);
<add> assert.equal(div[0].length, 3);
<add> assert.domNull(div[0][0]);
<add> assert.domEqual(div[0][1].parentNode, document.body);
<add> assert.domEqual(div[0][2].parentNode, document.body);
<add> }
<add> }
<add>});
<ide>
<ide> suite.export(module); | 1 |
Javascript | Javascript | remove iterableforobject tests | 3da5219649a7e2cd2a929468e97b7a11f7641590 | <ide><path>packages/ember-glimmer/tests/unit/utils/iterable-test.js
<ide> moduleFor('Iterable', class extends TestCase {
<ide> }
<ide> }
<ide>
<del> ['@test iterates over an object\'s own properties']() {
<del> let iterator = iteratorForObject({ first: 'foo', second: 'bar' });
<del>
<del> this.assert.deepEqual(iterator.next(), { key: 'first', memo: 'first', value: 'foo' });
<del> this.assert.deepEqual(iterator.next(), { key: 'second', memo: 'second', value: 'bar' });
<del> }
<del>
<del> ['@test iterates over an object\'s own properties with indices as keys']() {
<del> let iterator = iteratorForObject({ first: 'foo', second: 'bar' }, '@index');
<del>
<del> this.assert.deepEqual(iterator.next(), { key: 'first', memo: 'first', value: 'foo' });
<del> this.assert.deepEqual(iterator.next(), { key: 'second', memo: 'second', value: 'bar' });
<del> }
<del>
<del> ['@test iterates over an object\'s own properties with identities as keys']() {
<del> let iterator = iteratorForObject({ first: 'foo', second: 'bar' }, '@identity');
<del>
<del> this.assert.deepEqual(iterator.next(), { key: 'foo', memo: 'first', value: 'foo' });
<del> this.assert.deepEqual(iterator.next(), { key: 'bar', memo: 'second', value: 'bar' });
<del> }
<del>
<del> ['@test iterates over an object\'s own properties with arbitrary properties as keys']() {
<del> let iterator = iteratorForObject({ first: { k: 'uno', v: 'foo' }, second: { k: 'dos', v: 'bar' } }, 'k');
<del>
<del> this.assert.deepEqual(iterator.next(), { key: 'uno', memo: 'first', value: { k: 'uno', v: 'foo' } });
<del> this.assert.deepEqual(iterator.next(), { key: 'dos', memo: 'second', value: { k: 'dos', v: 'bar' } });
<del> }
<del>
<del> ['@test each-in errors on `#next` with an undefined ref']() {
<del> let iterator = iteratorForObject(undefined);
<del>
<del> this.assert.expect(1);
<del>
<del> try {
<del> iterator.next();
<del> } catch({ message }) {
<del> this.assert.equal(message, 'Cannot call next() on an empty iterator');
<del> }
<del> }
<del>
<del> ['@test each-in errors on `#next` with a null ref']() {
<del> let iterator = iteratorForObject(null);
<del>
<del> this.assert.expect(1);
<del>
<del> try {
<del> iterator.next();
<del> } catch({ message }) {
<del> this.assert.equal(message, 'Cannot call next() on an empty iterator');
<del> }
<del> }
<del>
<del> ['@test each-in errors on `#next` with an invalid ref type']() {
<del> let iterator = iteratorForObject('string');
<del>
<del> this.assert.expect(1);
<del>
<del> try {
<del> iterator.next();
<del> } catch({ message }) {
<del> this.assert.equal(message, 'Cannot call next() on an empty iterator');
<del> }
<del> }
<del>
<ide> ['@test ensures keys are unique']() {
<ide> let iterator = iteratorForArray([{ k: 'qux', v: 'foo' }, { k: 'qux', v: 'bar' }, { k: 'qux', v: 'baz' }], 'k');
<ide>
<ide> function iteratorForArray(arr, keyPath) {
<ide>
<ide> return iterable.iterate();
<ide> }
<del>
<del>function iteratorForObject(obj, keyPath) {
<del> let vm = null;
<del> let positionalArgs = EvaluatedPositionalArgs.create([new UpdatableReference(obj)]);
<del> let ref = eachIn(vm, { positional: positionalArgs });
<del> let iterable = iterableFor(ref, keyPath);
<del>
<del> return iterable.iterate();
<del>} | 1 |
Javascript | Javascript | remove mu support in component blueprints | 4427edd2db29b4fda0a246ac695315f10e23f0eb | <ide><path>blueprints/component-test/index.js
<ide> const isPackageMissing = require('ember-cli-is-package-missing');
<ide> const getPathOption = require('ember-cli-get-component-path-option');
<ide>
<ide> const useTestFrameworkDetector = require('../test-framework-detector');
<del>const isModuleUnificationProject = require('../module-unification').isModuleUnificationProject;
<ide>
<ide> function needsCurlyBracketInvocation(options) {
<ide> let path = options.path || '';
<ide> module.exports = useTestFrameworkDetector({
<ide> ],
<ide>
<ide> fileMapTokens: function() {
<del> if (isModuleUnificationProject(this.project)) {
<del> return {
<del> __test__() {
<del> return 'component-test';
<del> },
<del> __root__(options) {
<del> if (options.inRepoAddon) {
<del> return path.join('packages', options.inRepoAddon, 'src');
<del> }
<del> return 'src';
<del> },
<del> __testType__(options) {
<del> if (options.locals.testType === 'unit') {
<del> throw new Error("The --unit flag isn't supported within a module unification app");
<del> }
<del>
<del> return '';
<del> },
<del> __path__(options) {
<del> if (options.pod) {
<del> throw new Error("Pods aren't supported within a module unification app");
<del> }
<del> return path.join('ui', 'components', options.dasherizedModuleName);
<del> },
<del> };
<del> } else {
<del> return {
<del> __root__() {
<del> return 'tests';
<del> },
<del> __testType__(options) {
<del> return options.locals.testType || 'integration';
<del> },
<del> __path__(options) {
<del> if (options.pod) {
<del> return path.join(options.podPath, options.locals.path, options.dasherizedModuleName);
<del> }
<del> return 'components';
<del> },
<del> };
<del> }
<add> return {
<add> __root__() {
<add> return 'tests';
<add> },
<add> __testType__(options) {
<add> return options.locals.testType || 'integration';
<add> },
<add> __path__(options) {
<add> if (options.pod) {
<add> return path.join(options.podPath, options.locals.path, options.dasherizedModuleName);
<add> }
<add> return 'components';
<add> },
<add> };
<ide> },
<ide>
<ide> locals: function(options) {
<ide> module.exports = useTestFrameworkDetector({
<ide>
<ide> if (options.pod && options.path !== 'components' && options.path !== '') {
<ide> componentPathName = [options.path, dasherizedModuleName].filter(Boolean).join('/');
<del> } else if (isModuleUnificationProject(this.project)) {
<del> if (options.inRepoAddon) {
<del> componentPathName = `${options.inRepoAddon}::${dasherizedModuleName}`;
<del> templateInvocation = `${stringUtil.classify(options.inRepoAddon)}::${classifiedModuleName}`;
<del> } else if (this.project.isEmberCLIAddon()) {
<del> componentPathName = `${this.project.pkg.name}::${dasherizedModuleName}`;
<del> templateInvocation = `${stringUtil.classify(
<del> this.project.pkg.name
<del> )}::${classifiedModuleName}`;
<del> }
<ide> }
<ide>
<ide> if (needsCurlyBracketInvocation(options)) {
<ide><path>blueprints/component/index.js
<ide> const stringUtil = require('ember-cli-string-utils');
<ide> const pathUtil = require('ember-cli-path-utils');
<ide> const getPathOption = require('ember-cli-get-component-path-option');
<ide> const normalizeEntityName = require('ember-cli-normalize-entity-name');
<del>const { isModuleUnificationProject } = require('../module-unification');
<ide> const { EOL } = require('os');
<ide> const { has } = require('@ember/edition-utils');
<ide>
<ide> module.exports = {
<ide> fileMapTokens(options) {
<ide> let commandOptions = this.options;
<ide>
<del> if (isModuleUnificationProject(this.project)) {
<del> return {
<del> __name__: function() {
<del> return 'component';
<del> },
<del> __root__(options) {
<del> if (options.inRepoAddon) {
<del> return path.join('packages', options.inRepoAddon, 'src');
<del> }
<del> if (options.inDummy) {
<del> return path.join('tests', 'dummy', 'src');
<del> }
<del> return 'src';
<del> },
<del> __path__(options) {
<del> return path.join('ui', 'components', options.dasherizedModuleName);
<del> },
<del> __templatepath__(options) {
<del> return path.join('ui', 'components', options.dasherizedModuleName);
<del> },
<del> __templatename__: function() {
<del> return 'template';
<del> },
<del> };
<del> } else if (commandOptions.pod) {
<add> if (commandOptions.pod) {
<ide> return {
<ide> __path__() {
<ide> return path.join(options.podPath, options.locals.path, options.dasherizedModuleName);
<ide> module.exports = {
<ide> let defaultExport = '';
<ide> let contents = '';
<ide>
<del> if (!isModuleUnificationProject(this.project)) {
<del> // if we're in an addon, build import statement
<del> if (options.project.isEmberCLIAddon() || (options.inRepoAddon && !options.inDummy)) {
<del> if (options.pod) {
<del> templatePath = './template';
<del> } else {
<del> templatePath =
<del> pathUtil.getRelativeParentPath(options.entity.name) +
<del> 'templates/components/' +
<del> stringUtil.dasherize(options.entity.name);
<del> }
<del> importTemplate = "import layout from '" + templatePath + "';" + EOL;
<del> contents = EOL + ' layout';
<add> // if we're in an addon, build import statement
<add> if (options.project.isEmberCLIAddon() || (options.inRepoAddon && !options.inDummy)) {
<add> if (options.pod) {
<add> templatePath = './template';
<add> } else {
<add> templatePath =
<add> pathUtil.getRelativeParentPath(options.entity.name) +
<add> 'templates/components/' +
<add> stringUtil.dasherize(options.entity.name);
<ide> }
<add> importTemplate = "import layout from '" + templatePath + "';" + EOL;
<add> contents = EOL + ' layout';
<ide> }
<ide>
<ide> let componentClass = this.EMBER_GLIMMER_SET_COMPONENT_TEMPLATE
<ide><path>node-tests/blueprints/component-test-test.js
<ide> const fs = require('fs-extra');
<ide> const blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers');
<ide> const setupTestHooks = blueprintHelpers.setupTestHooks;
<ide> const emberNew = blueprintHelpers.emberNew;
<del>const emberGenerate = blueprintHelpers.emberGenerate;
<ide> const emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy;
<ide> const modifyPackages = blueprintHelpers.modifyPackages;
<del>const expectError = require('../helpers/expect-error');
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const fixture = require('../helpers/fixture');
<ide>
<del>const setupTestEnvironment = require('../helpers/setup-test-environment');
<del>const enableModuleUnification = setupTestEnvironment.enableModuleUnification;
<del>
<ide> describe('Blueprint: component-test', function() {
<ide> setupTestHooks(this);
<ide>
<ide> describe('Blueprint: component-test', function() {
<ide> });
<ide> });
<ide>
<del> describe('in app - module unification', function() {
<del> enableModuleUnification();
<del>
<del> beforeEach(function() {
<del> return emberNew();
<del> });
<del>
<del> describe('with ember-cli-qunit@4.1.0', function() {
<del> beforeEach(function() {
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-qunit', dev: true },
<del> ]);
<del> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<del> });
<del>
<del> it('component-test x-foo', function() {
<del> return emberGenerateDestroy(['component-test', 'x-foo'], _file => {
<del> expect(_file('src/ui/components/x-foo/component-test.js')).to.equal(
<del> fixture('component-test/default.js')
<del> );
<del> });
<del> });
<del>
<del> it('component-test x-foo --unit', function() {
<del> return expectError(
<del> emberGenerate(['component-test', 'x-foo', '--unit']),
<del> "The --unit flag isn't supported within a module unification app"
<del> );
<del> });
<del>
<del> describe('with usePods=true', function() {
<del> beforeEach(function() {
<del> fs.writeFileSync(
<del> '.ember-cli',
<del> `{
<del> "disableAnalytics": false,
<del> "usePods": true
<del> }`
<del> );
<del> });
<del>
<del> it('component-test x-foo', function() {
<del> return expectError(
<del> emberGenerate(['component-test', 'x-foo']),
<del> "Pods aren't supported within a module unification app"
<del> );
<del> });
<del> });
<del> });
<del>
<del> describe('with ember-cli-qunit@4.2.0', function() {
<del> beforeEach(function() {
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-qunit', dev: true },
<del> ]);
<del> generateFakePackageManifest('ember-cli-qunit', '4.2.0');
<del> });
<del>
<del> it('component-test x-foo', function() {
<del> return emberGenerateDestroy(['component-test', 'x-foo'], _file => {
<del> expect(_file('src/ui/components/x-foo/component-test.js')).to.equal(
<del> fixture('component-test/rfc232.js')
<del> );
<del> });
<del> });
<del>
<del> it('component-test x-foo --unit', function() {
<del> return expectError(
<del> emberGenerate(['component-test', 'x-foo', '--unit']),
<del> "The --unit flag isn't supported within a module unification app"
<del> );
<del> });
<del> });
<del>
<del> describe('with ember-cli-mocha@0.11.0', function() {
<del> beforeEach(function() {
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-mocha', dev: true },
<del> ]);
<del> generateFakePackageManifest('ember-cli-mocha', '0.11.0');
<del> });
<del>
<del> it('component-test x-foo', function() {
<del> return emberGenerateDestroy(['component-test', 'x-foo'], _file => {
<del> expect(_file('src/ui/components/x-foo/component-test.js')).to.equal(
<del> fixture('component-test/mocha.js')
<del> );
<del> });
<del> });
<del>
<del> it('component-test x-foo --unit', function() {
<del> return expectError(
<del> emberGenerate(['component-test', 'x-foo', '--unit']),
<del> "The --unit flag isn't supported within a module unification app"
<del> );
<del> });
<del> });
<del>
<del> describe('with ember-cli-mocha@0.12.0', function() {
<del> beforeEach(function() {
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-mocha', dev: true },
<del> ]);
<del> generateFakePackageManifest('ember-cli-mocha', '0.12.0');
<del> });
<del>
<del> it('component-test x-foo', function() {
<del> return emberGenerateDestroy(['component-test', 'x-foo'], _file => {
<del> expect(_file('src/ui/components/x-foo/component-test.js')).to.equal(
<del> fixture('component-test/mocha-0.12.js')
<del> );
<del> });
<del> });
<del>
<del> it('component-test x-foo --unit', function() {
<del> return expectError(
<del> emberGenerate(['component-test', 'x-foo', '--unit']),
<del> "The --unit flag isn't supported within a module unification app"
<del> );
<del> });
<del> });
<del>
<del> describe('with ember-mocha@0.14.0', function() {
<del> beforeEach(function() {
<del> modifyPackages([{ name: 'ember-qunit', delete: true }, { name: 'ember-mocha', dev: true }]);
<del> generateFakePackageManifest('ember-mocha', '0.14.0');
<del> });
<del>
<del> it('component-test x-foo', function() {
<del> return emberGenerateDestroy(['component-test', 'x-foo'], _file => {
<del> expect(_file('src/ui/components/x-foo/component-test.js')).to.equal(
<del> fixture('component-test/mocha-rfc232.js')
<del> );
<del> });
<del> });
<del>
<del> it('component-test x-foo --unit', function() {
<del> return expectError(
<del> emberGenerate(['component-test', 'x-foo', '--unit']),
<del> "The --unit flag isn't supported within a module unification app"
<del> );
<del> });
<del> });
<del> });
<del>
<ide> describe('in addon', function() {
<ide> beforeEach(function() {
<ide> return emberNew({ target: 'addon' })
<ide><path>node-tests/blueprints/component-test.js
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-ma
<ide> const fixture = require('../helpers/fixture');
<ide>
<ide> const setupTestEnvironment = require('../helpers/setup-test-environment');
<del>const enableModuleUnification = setupTestEnvironment.enableModuleUnification;
<ide> const enableOctane = setupTestEnvironment.enableOctane;
<ide>
<ide> const { EMBER_SET_COMPONENT_TEMPLATE } = require('../../blueprints/component');
<ide> describe('Blueprint: component', function() {
<ide> });
<ide> });
<ide>
<del> describe('in app - module unification', function() {
<del> enableModuleUnification();
<del>
<del> beforeEach(function() {
<del> return emberNew()
<del> .then(() =>
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-qunit', dev: true },
<del> ])
<del> )
<del> .then(() => generateFakePackageManifest('ember-cli-qunit', '4.1.0'));
<del> });
<del>
<del> it('component foo', function() {
<del> return emberGenerateDestroy(['component', 'foo'], _file => {
<del> expect(_file('src/ui/components/foo/component.js')).to.equal(
<del> fixture('component/component.js')
<del> );
<del>
<del> expect(_file('src/ui/components/foo/template.hbs')).to.equal('{{yield}}');
<del>
<del> expect(_file('src/ui/components/foo/component-test.js')).to.equal(
<del> fixture('component-test/default-template.js', {
<del> replace: {
<del> component: 'foo',
<del> componentInvocation: 'Foo',
<del> },
<del> })
<del> );
<del> });
<del> });
<del>
<del> it('component x-foo', function() {
<del> return emberGenerateDestroy(['component', 'x-foo'], _file => {
<del> expect(_file('src/ui/components/x-foo/component.js')).to.equal(
<del> fixture('component/component-dash.js')
<del> );
<del>
<del> expect(_file('src/ui/components/x-foo/template.hbs')).to.equal('{{yield}}');
<del>
<del> expect(_file('src/ui/components/x-foo/component-test.js')).to.equal(
<del> fixture('component-test/default-template.js', {
<del> replace: {
<del> component: 'x-foo',
<del> componentInvocation: 'XFoo',
<del> },
<del> })
<del> );
<del> });
<del> });
<del>
<del> it('component foo/x-foo', function() {
<del> return emberGenerateDestroy(['component', 'foo/x-foo'], _file => {
<del> expect(_file('src/ui/components/foo/x-foo/component.js')).to.equal(
<del> fixture('component/component-nested.js')
<del> );
<del>
<del> expect(_file('src/ui/components/foo/x-foo/template.hbs')).to.equal('{{yield}}');
<del>
<del> expect(_file('src/ui/components/foo/x-foo/component-test.js')).to.equal(
<del> fixture('component-test/default-curly-template.js', {
<del> replace: {
<del> component: 'foo/x-foo',
<del> },
<del> })
<del> );
<del> });
<del> });
<del>
<del> it('component foo.js', function() {
<del> return emberGenerateDestroy(['component', 'foo.js'], _file => {
<del> expect(_file('src/ui/components/foo.js/component.js')).to.not.exist;
<del> expect(_file('src/ui/components/foo.js/template.hbs')).to.not.exist;
<del> expect(_file('src/ui/components/foo.js/component-test.js')).to.not.exist;
<del>
<del> expect(_file('src/ui/components/foo/component.js')).to.equal(
<del> fixture('component/component.js')
<del> );
<del>
<del> expect(_file('src/ui/components/foo/template.hbs')).to.equal('{{yield}}');
<del>
<del> expect(_file('src/ui/components/foo/component-test.js')).to.equal(
<del> fixture('component-test/default-template.js', {
<del> replace: {
<del> component: 'foo',
<del> componentInvocation: 'Foo',
<del> },
<del> })
<del> );
<del> });
<del> });
<del> });
<del>
<ide> describe('in app - octane', function() {
<ide> enableOctane();
<ide> | 4 |
Text | Text | remove etw from diag tierlist | 3786ef63b02c5b29a65de974d4b0846c732f6c40 | <ide><path>doc/contributing/diagnostic-tooling-support-tiers.md
<ide> The tools are currently assigned to Tiers as follows:
<ide> | Tracing | trace\_gc | No | Yes | 1 |
<ide> | Tracing | DTrace | No | Partial | 3 |
<ide> | Tracing | LTTng | No | Removed? | N/A |
<del>| Tracing | ETW | No | Partial | 3 |
<ide> | Tracing | Systemtap | No | Partial | ? |
<ide> | Profiling | DTrace | No | Partial | 3 |
<ide> | Profiling | Windows Xperf | No | ? | ? | | 1 |
Ruby | Ruby | make model.find_by! error consistent | afab1ef7c37a2d6a772c8f0c3a124313de816eb7 | <ide><path>activerecord/lib/active_record/core.rb
<ide> def find_by(*args) # :nodoc:
<ide> end
<ide>
<ide> def find_by!(*args) # :nodoc:
<del> find_by(*args) || raise(RecordNotFound.new("Couldn't find #{name}", name))
<add> find_by(*args) || where(*args).raise_record_not_found_exception!
<ide> end
<ide>
<ide> def default_timezone # :nodoc:
<ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_finder_with_offset_string
<ide> end
<ide>
<ide> test "find_by! raises RecordNotFound if the record is missing" do
<del> assert_raises(ActiveRecord::RecordNotFound) do
<add> error = assert_raises(ActiveRecord::RecordNotFound) do
<ide> Post.find_by!("1 = 0")
<ide> end
<add>
<add> assert_equal "Couldn't find Post with [WHERE (1 = 0)]", error.message
<ide> end
<ide>
<ide> test "find on a scope does not perform statement caching" do | 2 |
Javascript | Javascript | add html5 srcdoc property for iframes | 40547125f89255f35a43e5a995568744c0f65a60 | <ide><path>src/browser/dom/DefaultDOMPropertyConfig.js
<ide> var DefaultDOMPropertyConfig = {
<ide> span: HAS_POSITIVE_NUMERIC_VALUE,
<ide> spellCheck: null,
<ide> src: null,
<add> srcDoc: MUST_USE_PROPERTY,
<ide> step: null,
<ide> style: null,
<ide> tabIndex: null,
<ide> var DefaultDOMPropertyConfig = {
<ide> autoPlay: 'autoplay',
<ide> encType: 'enctype',
<ide> radioGroup: 'radiogroup',
<del> spellCheck: 'spellcheck'
<add> spellCheck: 'spellcheck',
<add> srcDoc: 'srcdoc'
<ide> },
<ide> DOMMutationMethods: {
<ide> /** | 1 |
Go | Go | fix tests for pkg/archive | 108bbd96cb6f9aaa2a761e1a33250f36d58882f9 | <ide><path>pkg/archive/archive_test.go
<ide> func TestCompressStreamBzip2Unsupported(t *testing.T) {
<ide> }
<ide> defer dest.Close()
<ide>
<del> _, err = CompressStream(dest, Xz)
<add> _, err = CompressStream(dest, Bzip2)
<ide> if err == nil {
<del> t.Fatalf("Should fail as xz is unsupported for compression format.")
<add> t.Fatalf("Should fail as bzip2 is unsupported for compression format.")
<ide> }
<ide> }
<ide>
<ide> func TestExtensionGzip(t *testing.T) {
<ide> compression := Gzip
<ide> output := compression.Extension()
<ide> if output != "tar.gz" {
<del> t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'")
<add> t.Fatalf("The extension of a gzip archive should be 'tar.gz'")
<ide> }
<ide> }
<ide> func TestExtensionXz(t *testing.T) {
<ide> compression := Xz
<ide> output := compression.Extension()
<ide> if output != "tar.xz" {
<del> t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'")
<add> t.Fatalf("The extension of a xz archive should be 'tar.xz'")
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | add some debug info in the netlify command | 8f450ea0b4750253a2986fec8c10481b32afeaf3 | <ide><path>build/netlify-docs.js
<ide> const sh = require('shelljs');
<ide>
<ide> const GIT_CONTAINS = `git tag --contains ${process.env.COMMIT_REF}`;
<del>
<ide> const output = sh.exec(GIT_CONTAINS, {async: false, silent:true}).stdout;
<ide>
<add>console.log('CONTAINS command:', GIT_CONTAINS);
<add>console.log('BRANCH:', process.env.BRANCH);
<add>console.log('OUTPUT', output);
<add>
<add>
<ide> // if we're on master branch and not on a tagged commit,
<ide> // error the build so it doesn't redeploy the docs
<ide> if (process.env.BRANCH === 'master' && output === '') { | 1 |
PHP | PHP | implement ttl parameters for cache engines | 0110ea823e1c06460dd4086cfab04da7cb889fa1 | <ide><path>src/Cache/CacheEngine.php
<ide> namespace Cake\Cache;
<ide>
<ide> use Cake\Core\InstanceConfigTrait;
<add>use DateInterval;
<ide> use Psr\SimpleCache\CacheInterface;
<ide>
<ide> /**
<ide> protected function warning(string $message): void
<ide>
<ide> triggerWarning($message);
<ide> }
<add>
<add> /**
<add> * Convert the various expressions of a TTL value into duration in seconds
<add> *
<add> * @param null|int|\DateInterval $ttl The TTL value of this item. If null is sent, the
<add> * driver's default duration will be used.
<add> * @return int
<add> */
<add> protected function duration($ttl): int
<add> {
<add> if ($ttl === null) {
<add> return $this->_config['duration'];
<add> }
<add> if (is_int($ttl)) {
<add> return $ttl;
<add> }
<add> if ($ttl instanceof DateInterval) {
<add> return (int)$ttl->format('%s');
<add> }
<add>
<add> throw new InvalidArgumentException('TTL values must be one of null, int, \DateInterval');
<add> }
<ide> }
<ide><path>src/Cache/Engine/ApcuEngine.php
<ide> public function init(array $config = []): bool
<ide> public function set($key, $value, $ttl = null)
<ide> {
<ide> $key = $this->_key($key);
<del> $duration = $this->_config['duration'];
<add> $duration = $this->duration($ttl);
<ide>
<ide> return apcu_store($key, $value, $duration);
<ide> }
<ide><path>src/Cache/Engine/FileEngine.php
<ide> public function set($key, $data, $ttl = null)
<ide> }
<ide> }
<ide>
<del> $duration = $this->_config['duration'];
<del> $expires = time() + $duration;
<add> $expires = time() + $this->duration($ttl);
<ide> $contents = implode([$expires, $lineBreak, $data, $lineBreak]);
<ide>
<ide> if ($this->_config['lock']) {
<ide><path>src/Cache/Engine/MemcachedEngine.php
<ide> public function getOption($name)
<ide> */
<ide> public function set($key, $value, $ttl = null)
<ide> {
<del> $duration = $this->_config['duration'];
<add> $duration = $this->duration($ttl);
<ide> if ($duration > 30 * DAY) {
<ide> $duration = 0;
<ide> }
<ide> public function setMultiple($data, $ttl = null): bool
<ide> foreach ($data as $key => $value) {
<ide> $cacheData[$this->_key($key)] = $value;
<ide> }
<add> $duration = $this->duration($ttl);
<add> if ($duration > 30 * DAY) {
<add> $duration = 0;
<add> }
<ide>
<del> return (bool)$this->_Memcached->setMulti($cacheData);
<add> return (bool)$this->_Memcached->setMulti($cacheData, $duration);
<ide> }
<ide>
<ide> /**
<ide><path>src/Cache/Engine/RedisEngine.php
<ide> public function set($key, $value, $ttl = null)
<ide> $value = serialize($value);
<ide> }
<ide>
<del> $duration = $this->_config['duration'];
<add> $duration = $this->duration($ttl);
<ide> if ($duration === 0) {
<ide> return $this->_Redis->set($key, $value);
<ide> }
<ide><path>src/Cache/Engine/WincacheEngine.php
<ide> public function init(array $config = []): bool
<ide> public function set($key, $value, $ttl = null)
<ide> {
<ide> $key = $this->_key($key);
<del> $duration = $this->_config['duration'];
<add> $duration = $this->duration($ttl);
<ide>
<ide> return wincache_ucache_set($key, $value, $duration);
<ide> }
<ide><path>tests/TestCase/Cache/Engine/ApcuEngineTest.php
<ide>
<ide> use Cake\Cache\Cache;
<ide> use Cake\TestSuite\TestCase;
<add>use DateInterval;
<ide>
<ide> /**
<ide> * ApcuEngineTest class
<ide> public function testExpiry()
<ide> $this->assertSame(0, Cache::pool('apcu')->get('other_test', 0), 'expired values get default.');
<ide> }
<ide>
<add> /**
<add> * test set ttl parameter
<add> *
<add> * @return void
<add> */
<add> public function testSetWithTtl()
<add> {
<add> $this->_configCache(['duration' => 99]);
<add> $engine = Cache::pool('apcu');
<add> $this->assertNull($engine->get('test'));
<add>
<add> $data = 'this is a test of the emergency broadcasting system';
<add> $this->assertTrue($engine->set('default_ttl', $data));
<add> $this->assertTrue($engine->set('int_ttl', $data, 1));
<add> $this->assertTrue($engine->set('interval_ttl', $data, new DateInterval('PT1S')));
<add>
<add> sleep(2);
<add> $this->assertNull($engine->get('int_ttl'));
<add> $this->assertNull($engine->get('interval_ttl'));
<add> $this->assertSame($data, $engine->get('default_ttl'));
<add> }
<add>
<ide> /**
<ide> * testDeleteCache method
<ide> *
<ide><path>tests/TestCase/Cache/Engine/FileEngineTest.php
<ide> use Cake\Cache\InvalidArgumentException;
<ide> use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<add>use DateInterval;
<ide>
<ide> /**
<ide> * FileEngineTest class
<ide> public function testExpiry()
<ide> $this->assertNull($result);
<ide> }
<ide>
<add> /**
<add> * test set ttl parameter
<add> *
<add> * @return void
<add> */
<add> public function testSetWithTtl()
<add> {
<add> $this->_configCache(['duration' => 99]);
<add> $engine = Cache::pool('file_test');
<add> $this->assertNull($engine->get('test'));
<add>
<add> $data = 'this is a test of the emergency broadcasting system';
<add> $this->assertTrue($engine->set('default_ttl', $data));
<add> $this->assertTrue($engine->set('int_ttl', $data, 1));
<add> $this->assertTrue($engine->set('interval_ttl', $data, new DateInterval('PT1S')));
<add>
<add> sleep(2);
<add> $this->assertNull($engine->get('int_ttl'));
<add> $this->assertNull($engine->get('interval_ttl'));
<add> $this->assertSame($data, $engine->get('default_ttl'));
<add> }
<add>
<ide> /**
<ide> * testDeleteCache method
<ide> *
<ide><path>tests/TestCase/Cache/Engine/MemcachedEngineTest.php
<ide> use Cake\Cache\Cache;
<ide> use Cake\Cache\Engine\MemcachedEngine;
<ide> use Cake\TestSuite\TestCase;
<add>use DateInterval;
<ide> use Memcached;
<ide>
<ide> /**
<ide> public function testExpiry()
<ide> $this->assertEquals($expecting, $result);
<ide> }
<ide>
<add> /**
<add> * test set ttl parameter
<add> *
<add> * @return void
<add> */
<add> public function testSetWithTtl()
<add> {
<add> $this->_configCache(['duration' => 99]);
<add> $engine = Cache::pool('memcached');
<add> $this->assertNull($engine->get('test'));
<add>
<add> $data = 'this is a test of the emergency broadcasting system';
<add> $this->assertTrue($engine->set('default_ttl', $data));
<add> $this->assertTrue($engine->set('int_ttl', $data, 1));
<add> $this->assertTrue($engine->set('interval_ttl', $data, new DateInterval('PT1S')));
<add>
<add> sleep(2);
<add> $this->assertNull($engine->get('int_ttl'));
<add> $this->assertNull($engine->get('interval_ttl'));
<add> $this->assertSame($data, $engine->get('default_ttl'));
<add> }
<add>
<ide> /**
<ide> * testDeleteCache method
<ide> *
<ide><path>tests/TestCase/Cache/Engine/RedisEngineTest.php
<ide> use Cake\Cache\Cache;
<ide> use Cake\Cache\Engine\RedisEngine;
<ide> use Cake\TestSuite\TestCase;
<add>use DateInterval;
<ide>
<ide> /**
<ide> * RedisEngineTest class
<ide> public function testExpiry()
<ide> $this->assertEquals($expecting, $result);
<ide> }
<ide>
<add> /**
<add> * test set ttl parameter
<add> *
<add> * @return void
<add> */
<add> public function testSetWithTtl()
<add> {
<add> $this->_configCache(['duration' => 99]);
<add> $engine = Cache::pool('redis');
<add> $this->assertNull($engine->get('test'));
<add>
<add> $data = 'this is a test of the emergency broadcasting system';
<add> $this->assertTrue($engine->set('default_ttl', $data));
<add> $this->assertTrue($engine->set('int_ttl', $data, 1));
<add> $this->assertTrue($engine->set('interval_ttl', $data, new DateInterval('PT1S')));
<add>
<add> sleep(2);
<add> $this->assertNull($engine->get('int_ttl'));
<add> $this->assertNull($engine->get('interval_ttl'));
<add> $this->assertSame($data, $engine->get('default_ttl'));
<add> }
<add>
<ide> /**
<ide> * testDeleteCache method
<ide> *
<ide><path>tests/TestCase/Cache/Engine/WincacheEngineTest.php
<ide> public function testExpiry()
<ide> $this->assertNull($result);
<ide> }
<ide>
<add> /**
<add> * test set ttl parameter
<add> *
<add> * @return void
<add> */
<add> public function testSetWithTtl()
<add> {
<add> $this->_configCache(['duration' => 99]);
<add> $engine = Cache::pool('wincache');
<add> $this->assertNull($engine->get('test'));
<add>
<add> $data = 'this is a test of the emergency broadcasting system';
<add> $this->assertTrue($engine->set('default_ttl', $data));
<add> $this->assertTrue($engine->set('int_ttl', $data, 1));
<add> $this->assertTrue($engine->set('interval_ttl', $data, new DateInterval('PT1S')));
<add>
<add> sleep(2);
<add> $this->assertNull($engine->get('int_ttl'));
<add> $this->assertNull($engine->get('interval_ttl'));
<add> $this->assertSame($data, $engine->get('default_ttl'));
<add> }
<add>
<ide> /**
<ide> * testDeleteCache method
<ide> * | 11 |
Javascript | Javascript | use fetch as a polyfill | 2fe3dd2e7d27789918079c66636c5161e22c5c33 | <ide><path>Libraries/Network/fetch.js
<ide>
<ide> 'use strict';
<ide>
<del>const whatwg = require('whatwg-fetch');
<add>// side-effectful require() to put fetch,
<add>// Headers, Request, Response in global scope
<add>require('whatwg-fetch');
<ide>
<del>if (whatwg && whatwg.fetch) {
<del> module.exports = whatwg;
<del>} else {
<del> module.exports = {fetch, Headers, Request, Response};
<del>}
<add>module.exports = {fetch, Headers, Request, Response}; | 1 |
Python | Python | catch attributeerror on missing "tasks" module | 2b72d6346fc8f82c4e4da1b2b2edc841682f8da1 | <ide><path>celery/loaders/djangoapp.py
<ide> def find_related_module(app, related_name):
<ide>
<ide> module = importlib.import_module("%s.%s" % (app, related_name))
<ide>
<del> return getattr(module, related_name)
<add> try:
<add> return getattr(module, related_name)
<add> except AttributeError:
<add> return | 1 |
PHP | PHP | throw excption if file dumping fails | c1a1c30d30329a77d6acd67e4d4b941ffd317ba2 | <ide><path>src/Filesystem/Filesystem.php
<ide> public function dumpFile(string $filename, string $content): void
<ide> $exits = file_exists($filename);
<ide>
<ide> if ($this->isStream($filename)) {
<del> file_put_contents($filename, $content);
<add> $success = @file_put_contents($filename, $content);
<ide> } else {
<del> file_put_contents($filename, $content, LOCK_EX);
<add> $success = @file_put_contents($filename, $content, LOCK_EX);
<add> }
<add>
<add> if (!$success) {
<add> throw new Exception(sprintf('Failed dumping content to file "%s"', $dir));
<ide> }
<ide>
<ide> if (!$exits) { | 1 |
Javascript | Javascript | improve test case | 81913dc224833c8056d9d75f7fd84ac38866e104 | <ide><path>test/configCases/output/inner-dirs-entries/a.js
<del>import dummy from './dep';
<add>import dummy from 'dummy_module';
<ide>
<del>it("should load", done => {
<del> dummy();
<del> done();
<add>it("should load", () => {
<add> expect(dummy()).toBe('this is just a dummy function');
<add> return import("./inner-dir/b").then(importedModule => {
<add> expect(importedModule.dummy()).toBe('this is just a dummy function');
<add> })
<ide> });
<ide><path>test/configCases/output/inner-dirs-entries/inner-dir/b.js
<del>import dummy from '../dep';
<add>import dummy from 'dummy_module';
<add>
<ide> it("should load", done => {
<del> dummy();
<add> expect(dummy()).toBe('this is just a dummy function');
<ide> done();
<ide> });
<ide><path>test/configCases/output/inner-dirs-entries/inner-dir/some-module.js
<add>export dummy from 'dummy-module';
<ide>\ No newline at end of file
<add><path>test/configCases/output/inner-dirs-entries/node_modules/dummy_module/index.js
<del><path>test/configCases/output/inner-dirs-entries/dep.js
<del>import glob from 'glob';
<del>
<ide> export default function someDummyFunction() {
<del> typeof glob;
<ide> return 'this is just a dummy function';
<ide> }
<ide><path>test/configCases/output/inner-dirs-entries/webpack.config.js
<ide> module.exports = {
<ide> minimize: false,
<ide> concatenateModules: false,
<ide> splitChunks: {
<del> cacheGroups: {
<del> commons: {
<del> name: "commons",
<del> chunks: "all",
<del> maxSize: 512000,
<del> minChunks: 2
<del> }
<del> }
<add> chunks: "all",
<add> minSize: 0
<ide> }
<ide> }
<ide> }; | 5 |
Text | Text | fix typo in changelog entry for | 7e356750591e103b2857fee111914a37114b60c6 | <ide><path>activerecord/CHANGELOG.md
<ide> * Restrict deletion of record when using `delete_all` with `uniq`, `group`, `having`
<ide> or `offset`.
<ide>
<del> I these cases the generated query ignores them and that causes unintended
<add> In these cases the generated query ignored them and that caused unintended
<ide> records to be deleted.
<ide>
<add> Fixes #11985.
<add>
<ide> *Leandro Facchinetti*
<ide>
<ide> * Floats with limit >= 25 that get turned into doubles in MySQL no longer have | 1 |
Python | Python | fix polynomial comparison. closes ticket #554 | 393473fbace1bb64ef73ab3ebd11a78db832dca1 | <ide><path>numpy/core/tests/test_regression.py
<ide> def check_numeric_random(self, level=rlevel):
<ide> from numpy.oldnumeric.random_array import randint
<ide> randint(0,50,[2,3])
<ide>
<add> def check_poly_eq(self, level=rlevel):
<add> """Ticket #554"""
<add> x = N.poly1d([1,2,3])
<add> y = N.poly1d([3,4])
<add> assert x != y
<add> assert x == x
<add>
<ide>
<ide> if __name__ == "__main__":
<ide> NumpyTest().run()
<ide><path>numpy/lib/polynomial.py
<ide> def __rdiv__(self, other):
<ide> return polydiv(other, self)
<ide>
<ide> def __eq__(self, other):
<del> return (self.coeffs == other.coeffs).all()
<add> return NX.alltrue(self.coeffs == other.coeffs)
<ide>
<ide> def __ne__(self, other):
<del> return (self.coeffs != other.coeffs).any()
<add> return NX.any(self.coeffs != other.coeffs)
<ide>
<ide> def __setattr__(self, key, val):
<ide> raise ValueError, "Attributes cannot be changed this way." | 2 |
Java | Java | support strict uri variable encoding | 6f2c968925c28d7269e1dada1d97b7dff2d6cf07 | <ide><path>spring-web/src/main/java/org/springframework/web/util/DefaultUriTemplateHandler.java
<ide>
<ide> package org.springframework.web.util;
<ide>
<add>import java.io.UnsupportedEncodingException;
<ide> import java.net.URI;
<ide> import java.net.URISyntaxException;
<add>import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> public class DefaultUriTemplateHandler implements UriTemplateHandler {
<ide>
<ide> private boolean parsePath;
<ide>
<add> private boolean strictEncoding;
<add>
<ide>
<ide> /**
<ide> * Configure a base URL to prepend URI templates with. The base URL must
<ide> public boolean shouldParsePath() {
<ide> return this.parsePath;
<ide> }
<ide>
<add> /**
<add> * Whether to encode characters outside the unreserved set as defined in
<add> * <a href="https://tools.ietf.org/html/rfc3986#section-2">RFC 3986 Section 2</a>.
<add> * This ensures a URI variable value will not contain any characters with a
<add> * reserved purpose.
<add> * <p>By default this is set to {@code false} in which case only characters
<add> * illegal for the given URI component are encoded. For example when expanding
<add> * a URI variable into a path segment the "/" character is illegal and
<add> * encoded. The ";" character however is legal and not encoded even though
<add> * it has a reserved purpose.
<add> * <p><strong>Note:</strong> this property supersedes the need to also set
<add> * the {@link #setParsePath parsePath} property.
<add> * @param strictEncoding whether to perform strict encoding
<add> * @since 4.3
<add> */
<add> public void setStrictEncoding(boolean strictEncoding) {
<add> this.strictEncoding = strictEncoding;
<add> }
<add>
<add> /**
<add> * Whether to strictly encode any character outside the unreserved set.
<add> */
<add> public boolean isStrictEncoding() {
<add> return this.strictEncoding;
<add> }
<add>
<ide>
<ide> @Override
<ide> public URI expand(String uriTemplate, Map<String, ?> uriVariables) {
<del> UriComponentsBuilder builder = initUriComponentsBuilder(uriTemplate);
<del> UriComponents url = builder.build().expand(uriVariables).encode();
<del> return insertBaseUrl(url);
<add> UriComponentsBuilder uriComponentsBuilder = initUriComponentsBuilder(uriTemplate);
<add> UriComponents uriComponents = expandAndEncode(uriComponentsBuilder, uriVariables);
<add> return insertBaseUrl(uriComponents);
<ide> }
<ide>
<ide> @Override
<ide> public URI expand(String uriTemplate, Object... uriVariables) {
<del> UriComponentsBuilder builder = initUriComponentsBuilder(uriTemplate);
<del> UriComponents url = builder.build().expand(uriVariables).encode();
<del> return insertBaseUrl(url);
<add> UriComponentsBuilder uriComponentsBuilder = initUriComponentsBuilder(uriTemplate);
<add> UriComponents uriComponents = expandAndEncode(uriComponentsBuilder, uriVariables);
<add> return insertBaseUrl(uriComponents);
<ide> }
<ide>
<ide> /**
<ide> public URI expand(String uriTemplate, Object... uriVariables) {
<ide> */
<ide> protected UriComponentsBuilder initUriComponentsBuilder(String uriTemplate) {
<ide> UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uriTemplate);
<del> if (shouldParsePath()) {
<add> if (shouldParsePath() && !isStrictEncoding()) {
<ide> List<String> pathSegments = builder.build().getPathSegments();
<ide> builder.replacePath(null);
<ide> for (String pathSegment : pathSegments) {
<ide> protected UriComponentsBuilder initUriComponentsBuilder(String uriTemplate) {
<ide> return builder;
<ide> }
<ide>
<add> protected UriComponents expandAndEncode(UriComponentsBuilder builder, Map<String, ?> uriVariables) {
<add> if (!isStrictEncoding()) {
<add> return builder.build().expand(uriVariables).encode();
<add> }
<add> else {
<add> Map<String, Object> encodedUriVars = new HashMap<String, Object>(uriVariables.size());
<add> for (Map.Entry<String, ?> entry : uriVariables.entrySet()) {
<add> encodedUriVars.put(entry.getKey(), encodeValue(entry.getValue()));
<add> }
<add> return builder.build().expand(encodedUriVars);
<add> }
<add> }
<add>
<add> protected UriComponents expandAndEncode(UriComponentsBuilder builder, Object[] uriVariables) {
<add> if (!isStrictEncoding()) {
<add> return builder.build().expand(uriVariables).encode();
<add> }
<add> else {
<add> Object[] encodedUriVars = new Object[uriVariables.length];
<add> for (int i = 0; i < uriVariables.length; i++) {
<add> encodedUriVars[i] = encodeValue(uriVariables[i]);
<add> }
<add> return builder.build().expand(encodedUriVars);
<add> }
<add> }
<add>
<add> private String encodeValue(Object value) {
<add> String stringValue = (value != null ? value.toString() : "");
<add> try {
<add> return UriUtils.encode(stringValue, "UTF-8");
<add> }
<add> catch (UnsupportedEncodingException ex) {
<add> // Should never happen
<add> throw new IllegalStateException("Failed to encode URI variable", ex);
<add> }
<add> }
<add>
<ide> /**
<ide> * Invoked after the URI template has been expanded and encoded to prepend
<ide> * the configured {@link #setBaseUrl(String) baseUrl} if any.
<ide> * @param uriComponents the expanded and encoded URI
<ide> * @return the final URI
<ide> */
<ide> protected URI insertBaseUrl(UriComponents uriComponents) {
<del> if (getBaseUrl() == null || uriComponents.getHost() != null) {
<del> return uriComponents.toUri();
<add> String url = uriComponents.toUriString();
<add> if (getBaseUrl() != null && uriComponents.getHost() == null) {
<add> url = getBaseUrl() + url;
<ide> }
<del> String url = getBaseUrl() + uriComponents.toUriString();
<ide> try {
<ide> return new URI(url);
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/web/util/DefaultUriTemplateHandlerTests.java
<ide> public void baseUrlWithPartialPath() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void expandWithFullPath() throws Exception {
<add> public void parsePathOff() throws Exception {
<add> this.handler.setParsePath(false);
<ide> Map<String, String> vars = new HashMap<>(2);
<ide> vars.put("hotel", "1");
<ide> vars.put("publicpath", "pics/logo.png");
<ide> public void expandWithFullPath() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void expandWithFullPathAndParsePathEnabled() throws Exception {
<add> public void parsePathOn() throws Exception {
<ide> this.handler.setParsePath(true);
<ide> Map<String, String> vars = new HashMap<>(2);
<ide> vars.put("hotel", "1");
<ide> public void expandWithFullPathAndParsePathEnabled() throws Exception {
<ide> assertEquals(expected, actual);
<ide> }
<ide>
<add> @Test
<add> public void strictEncodingOff() throws Exception {
<add> this.handler.setStrictEncoding(false);
<add> Map<String, String> vars = new HashMap<>(2);
<add> vars.put("userId", "john;doe");
<add> String template = "http://www.example.com/user/{userId}/dashboard";
<add> URI actual = this.handler.expand(template, vars);
<add> URI expected = new URI("http://www.example.com/user/john;doe/dashboard");
<add> assertEquals(expected, actual);
<add> }
<add>
<add> @Test
<add> public void strictEncodingOnWithMap() throws Exception {
<add> this.handler.setStrictEncoding(true);
<add> Map<String, String> vars = new HashMap<>(2);
<add> vars.put("userId", "john;doe");
<add> String template = "http://www.example.com/user/{userId}/dashboard";
<add> URI actual = this.handler.expand(template, vars);
<add> URI expected = new URI("http://www.example.com/user/john%3Bdoe/dashboard");
<add> assertEquals(expected, actual);
<add> }
<add>
<add> @Test
<add> public void strictEncodingOnWithArray() throws Exception {
<add> this.handler.setStrictEncoding(true);
<add> String template = "http://www.example.com/user/{userId}/dashboard";
<add> URI actual = this.handler.expand(template, "john;doe");
<add> URI expected = new URI("http://www.example.com/user/john%3Bdoe/dashboard");
<add> assertEquals(expected, actual);
<add> }
<add>
<ide> } | 2 |
Java | Java | reduce string creation in beanpropertyrowmapper | 6316a353bb074b118ab71ad89fe60553c4d073c9 | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java
<ide> protected String underscoreName(String name) {
<ide> if (!StringUtils.hasLength(name)) {
<ide> return "";
<ide> }
<add>
<ide> StringBuilder result = new StringBuilder();
<del> result.append(lowerCaseName(name.substring(0, 1)));
<del> for (int i = 1; i < name.length(); i++) {
<del> String s = name.substring(i, i + 1);
<del> String slc = lowerCaseName(s);
<del> if (!s.equals(slc)) {
<del> result.append("_").append(slc);
<add> for (int i = 0; i < name.length(); i++) {
<add> char s = name.charAt(i);
<add> if (Character.isUpperCase(s)) {
<add> result.append('_').append(Character.toLowerCase(s));
<ide> }
<ide> else {
<del> result.append(s);
<add> result.append(Character.toLowerCase(s));
<ide> }
<ide> }
<ide> return result.toString(); | 1 |
Go | Go | add login check before pull user's repo | 1b0b962b43afe2f0e07b31fe03e64db4e7d97854 | <ide><path>commands.go
<ide> func (cli *DockerCli) CmdPush(args ...string) error {
<ide> return nil
<ide> }
<ide>
<del> body, _, err := cli.call("GET", "/auth", nil)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> var out auth.AuthConfig
<del> err = json.Unmarshal(body, &out)
<add> username, err := cli.checkIfLogged(*registry == "", "push", args...)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> // If the login failed AND we're using the index, abort
<del> if *registry == "" && out.Username == "" {
<del> if err := cli.CmdLogin(args...); err != nil {
<del> return err
<del> }
<del>
<del> body, _, err = cli.call("GET", "/auth", nil)
<del> if err != nil {
<del> return err
<del> }
<del> err = json.Unmarshal(body, &out)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if out.Username == "" {
<del> return fmt.Errorf("Please login prior to push. ('docker login')")
<del> }
<del> }
<del>
<ide> if len(strings.SplitN(name, "/", 2)) == 1 {
<del> return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", out.Username, name)
<add> return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
<ide> }
<ide>
<ide> v := url.Values{}
<ide> func (cli *DockerCli) CmdPull(args ...string) error {
<ide> remote = remoteParts[0]
<ide> }
<ide>
<add> if strings.Contains(remote, "/") {
<add> fmt.Println("Login is required before pull an user's repository")
<add> if _, err := cli.checkIfLogged(true, "pull", args...); err != nil {
<add> return err
<add> }
<add> }
<add>
<ide> v := url.Values{}
<ide> v.Set("fromImage", remote)
<ide> v.Set("tag", *tag)
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> return nil
<ide> }
<ide>
<add>func (cli *DockerCli) checkIfLogged(condition bool, action string, args ...string) (string, error) {
<add> body, _, err := cli.call("GET", "/auth", nil)
<add> if err != nil {
<add> return "", err
<add> }
<add>
<add> var out auth.AuthConfig
<add> err = json.Unmarshal(body, &out)
<add> if err != nil {
<add> return "", err
<add> }
<add>
<add> // If the login failed
<add> if condition && out.Username == "" {
<add> if err := cli.CmdLogin(args...); err != nil {
<add> return "", err
<add> }
<add>
<add> body, _, err = cli.call("GET", "/auth", nil)
<add> if err != nil {
<add> return "", err
<add> }
<add> err = json.Unmarshal(body, &out)
<add> if err != nil {
<add> return "", err
<add> }
<add>
<add> if out.Username == "" {
<add> return "", fmt.Errorf("Please login prior to %s. ('docker login')", action)
<add> }
<add> }
<add> return out.Username, nil
<add>}
<add>
<ide> func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
<ide> var params io.Reader
<ide> if data != nil { | 1 |
Ruby | Ruby | extract the scope building to a class method | c1cd3424569cf76b0e19e2854ec2829d87ed02bd | <ide><path>activerecord/lib/active_record/associations/builder/association.rb
<ide> def self.create_builder(model, name, scope, options, extension = nil)
<ide>
<ide> def initialize(name, scope, options, extension)
<ide> @name = name
<del> @scope = scope
<ide> @options = options
<ide>
<ide> self.class.validate_options(options)
<ide>
<add> @scope = self.class.build_scope(scope, extension)
<add> end
<add>
<add> def self.build_scope(scope, extension)
<add> new_scope = scope
<add>
<ide> if scope && scope.arity == 0
<del> @scope = proc { instance_exec(&scope) }
<add> new_scope = proc { instance_exec(&scope) }
<add> end
<add>
<add> if extension
<add> new_scope = wrap_scope new_scope, extension
<ide> end
<add>
<add> new_scope
<add> end
<add>
<add> def self.wrap_scope(scope, extension)
<add> scope
<ide> end
<ide>
<ide> def build(model)
<ide><path>activerecord/lib/active_record/associations/builder/collection_association.rb
<ide> def self.valid_options(options)
<ide> :after_add, :before_remove, :after_remove, :extend]
<ide> end
<ide>
<del> def initialize(name, scope, options, extension)
<del> super
<del>
<del> if extension
<del> @scope = self.class.wrap_scope @scope, extension
<del> end
<del> end
<del>
<ide> def self.define_callbacks(model, reflection)
<ide> super
<ide> name = reflection.name | 2 |
PHP | PHP | use proper tests assertions | 9522b1f18491c17f31c0aa57a3032364f5cf4216 | <ide><path>tests/Bus/BusBatchTest.php
<ide> public function test_jobs_can_be_added_to_the_batch()
<ide>
<ide> $this->assertEquals(3, $batch->totalJobs);
<ide> $this->assertEquals(3, $batch->pendingJobs);
<del> $this->assertTrue(is_string($job->batchId));
<add> $this->assertIsString($job->batchId);
<ide> $this->assertInstanceOf(CarbonImmutable::class, $batch->createdAt);
<ide> }
<ide>
<ide> public function test_batch_state_can_be_inspected()
<ide> $batch->cancelledAt = now();
<ide> $this->assertTrue($batch->cancelled());
<ide>
<del> $this->assertTrue(is_string(json_encode($batch)));
<add> $this->assertIsString(json_encode($batch));
<ide> }
<ide>
<ide> public function test_chain_can_be_added_to_batch()
<ide> public function test_chain_can_be_added_to_batch()
<ide> $this->assertEquals(3, $batch->totalJobs);
<ide> $this->assertEquals(3, $batch->pendingJobs);
<ide> $this->assertSame('test-queue', $chainHeadJob->chainQueue);
<del> $this->assertTrue(is_string($chainHeadJob->batchId));
<del> $this->assertTrue(is_string($secondJob->batchId));
<del> $this->assertTrue(is_string($thirdJob->batchId));
<add> $this->assertIsString($chainHeadJob->batchId);
<add> $this->assertIsString($secondJob->batchId);
<add> $this->assertIsString($thirdJob->batchId);
<ide> $this->assertInstanceOf(CarbonImmutable::class, $batch->createdAt);
<ide> }
<ide>
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> public function testBelongsToManyRelationshipModelsAreProperlyHydratedWithSoleQu
<ide> $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
<ide>
<ide> $user->friends()->get()->each(function ($friend) {
<del> $this->assertTrue($friend->pivot instanceof EloquentTestFriendPivot);
<add> $this->assertInstanceOf(EloquentTestFriendPivot::class, $friend->pivot);
<ide> });
<ide>
<ide> $soleFriend = $user->friends()->where('email', 'abigailotwell@gmail.com')->sole();
<ide>
<del> $this->assertTrue($soleFriend->pivot instanceof EloquentTestFriendPivot);
<add> $this->assertInstanceOf(EloquentTestFriendPivot::class, $soleFriend->pivot);
<ide> }
<ide>
<ide> public function testBelongsToManyRelationshipMissingModelExceptionWithSoleQueryWorks()
<ide><path>tests/Http/HttpRequestTest.php
<ide> public function testMagicMethods()
<ide> // Parameter 'foo' is 'bar', then it ISSET and is NOT EMPTY.
<ide> $this->assertSame('bar', $request->foo);
<ide> $this->assertTrue(isset($request->foo));
<del> $this->assertFalse(empty($request->foo));
<add> $this->assertNotEmpty($request->foo);
<ide>
<ide> // Parameter 'empty' is '', then it ISSET and is EMPTY.
<ide> $this->assertSame('', $request->empty);
<ide> public function testMagicMethods()
<ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY.
<ide> $this->assertNull($request->undefined);
<ide> $this->assertFalse(isset($request->undefined));
<del> $this->assertTrue(empty($request->undefined));
<add> $this->assertEmpty($request->undefined);
<ide>
<ide> // Simulates Route parameters.
<ide> $request = Request::create('/example/bar', 'GET', ['xyz' => 'overwritten']);
<ide> public function testMagicMethods()
<ide> $this->assertSame('bar', $request->foo);
<ide> $this->assertSame('bar', $request['foo']);
<ide> $this->assertTrue(isset($request->foo));
<del> $this->assertFalse(empty($request->foo));
<add> $this->assertNotEmpty($request->foo);
<ide>
<ide> // Router parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY.
<ide> $this->assertNull($request->undefined);
<ide> $this->assertFalse(isset($request->undefined));
<del> $this->assertTrue(empty($request->undefined));
<add> $this->assertEmpty($request->undefined);
<ide>
<ide> // Special case: router parameter 'xyz' is 'overwritten' by QueryString, then it ISSET and is NOT EMPTY.
<ide> // Basically, QueryStrings have priority over router parameters.
<ide> $this->assertSame('overwritten', $request->xyz);
<ide> $this->assertTrue(isset($request->foo));
<del> $this->assertFalse(empty($request->foo));
<add> $this->assertNotEmpty($request->foo);
<ide>
<ide> // Simulates empty QueryString and Routes.
<ide> $request = Request::create('/', 'GET');
<ide> public function testMagicMethods()
<ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY.
<ide> $this->assertNull($request->undefined);
<ide> $this->assertFalse(isset($request->undefined));
<del> $this->assertTrue(empty($request->undefined));
<add> $this->assertEmpty($request->undefined);
<ide>
<ide> // Special case: simulates empty QueryString and Routes, without the Route Resolver.
<ide> // It'll happen when you try to get a parameter outside a route.
<ide> public function testMagicMethods()
<ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY.
<ide> $this->assertNull($request->undefined);
<ide> $this->assertFalse(isset($request->undefined));
<del> $this->assertTrue(empty($request->undefined));
<add> $this->assertEmpty($request->undefined);
<ide> }
<ide>
<ide> public function testHttpRequestFlashCallsSessionFlashInputWithInputData()
<ide><path>tests/Integration/Database/DatabaseEloquentModelCustomCastingTest.php
<ide> public function testBasicCustomCasting()
<ide>
<ide> $model = new TestEloquentModelWithCustomCast;
<ide> $model->birthday_at = now();
<del> $this->assertTrue(is_string($model->toArray()['birthday_at']));
<add> $this->assertIsString($model->toArray()['birthday_at']);
<ide> }
<ide>
<ide> public function testGetOriginalWithCastValueObjects()
<ide><path>tests/Integration/Database/DatabaseSchemaBuilderAlterTableWithEnumTest.php
<ide>
<ide> use Illuminate\Database\Schema\Blueprint;
<ide> use Illuminate\Support\Facades\Schema;
<add>use stdClass;
<ide>
<ide> class DatabaseSchemaBuilderAlterTableWithEnumTest extends DatabaseMySqlTestCase
<ide> {
<ide> public function testGetAllTablesAndColumnListing()
<ide> $tables = Schema::getAllTables();
<ide>
<ide> $this->assertCount(1, $tables);
<del> $this->assertSame('stdClass', get_class($tables[0]));
<add> $this->assertInstanceOf(stdClass::class, $tables[0]);
<ide>
<ide> $tableProperties = array_values((array) $tables[0]);
<ide> $this->assertEquals(['users', 'BASE TABLE'], $tableProperties);
<ide><path>tests/Integration/Http/ResourceTest.php
<ide> public function testCollectionResourcesAreCountable()
<ide> $collection = new PostCollectionResource($posts);
<ide>
<ide> $this->assertCount(2, $collection);
<del> $this->assertSame(2, count($collection));
<add> $this->assertCount(2, $collection);
<ide> }
<ide>
<ide> public function testKeysArePreservedIfTheResourceIsFlaggedToPreserveKeys()
<ide><path>tests/Validation/ValidationAddFailureTest.php
<ide> public function testAddFailureExists()
<ide> $validator = $this->makeValidator();
<ide> $method_name = 'addFailure';
<ide> $this->assertTrue(method_exists($validator, $method_name));
<del> $this->assertTrue(is_callable([$validator, $method_name]));
<add> $this->assertIsCallable([$validator, $method_name]);
<ide> }
<ide>
<ide> public function testAddFailureIsFunctional()
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function message()
<ide> );
<ide>
<ide> $this->assertFalse($v->passes());
<del> $this->assertTrue(is_array($v->failed()['foo.foo.bar']));
<add> $this->assertIsArray($v->failed()['foo.foo.bar']);
<ide> }
<ide>
<ide> public function testImplicitCustomValidationObjects() | 8 |
Javascript | Javascript | add continuous stress test | 12a90e98bfc347d78e622f0839898c065ed31dc1 | <ide><path>benchmark/http_bench.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var spawn = require('child_process').spawn;
<add>var cluster = require('cluster');
<add>var http = require('http');
<add>
<add>var options = {
<add> mode: 'master',
<add> host: '127.0.0.1',
<add> port: 22344,
<add> path: '/',
<add> servers: 1,
<add> clients: 1
<add>};
<add>
<add>for (var i = 2; i < process.argv.length; ++i) {
<add> var args = process.argv[i].split('=', 2);
<add> var key = args[0];
<add> var val = args[1];
<add> options[key] = val;
<add>}
<add>
<add>switch (options.mode) {
<add>case 'master': startMaster(); break;
<add>case 'server': startServer(); break;
<add>case 'client': startClient(); break;
<add>default: throw new Error('Bad mode: ' + options.mode);
<add>}
<add>
<add>process.title = 'http_bench[' + options.mode + ']';
<add>
<add>// monkey-patch the log functions so they include name + pid
<add>console.log = patch(console.log);
<add>console.trace = patch(console.trace);
<add>console.error = patch(console.error);
<add>
<add>function patch(fun) {
<add> var prefix = process.title + '[' + process.pid + '] ';
<add> return function() {
<add> var args = Array.prototype.slice.call(arguments);
<add> args[0] = prefix + args[0];
<add> return fun.apply(console, args);
<add> };
<add>}
<add>
<add>function startMaster() {
<add> if (!cluster.isMaster) return startServer();
<add>
<add> for (var i = ~~options.servers; i > 0; --i) cluster.fork();
<add>
<add> for (var i = ~~options.clients; i > 0; --i) {
<add> var cp = spawn(process.execPath, [__filename, 'mode=client']);
<add> cp.stdout.pipe(process.stdout);
<add> cp.stderr.pipe(process.stderr);
<add> }
<add>}
<add>
<add>function startServer() {
<add> http.createServer(onRequest).listen(options.port, options.host);
<add>
<add> var body = Array(1024).join('x');
<add> var headers = {'Content-Length': '' + body.length};
<add>
<add> function onRequest(req, res) {
<add> req.on('error', onError);
<add> res.on('error', onError);
<add> res.writeHead(200, headers);
<add> res.end(body);
<add> }
<add>
<add> function onError(err) {
<add> console.error(err.stack);
<add> }
<add>}
<add>
<add>function startClient() {
<add> // send off a bunch of concurrent requests
<add> // TODO make configurable
<add> sendRequest();
<add> sendRequest();
<add>
<add> function sendRequest() {
<add> var req = http.request(options, onConnection);
<add> req.on('error', onError);
<add> req.end();
<add> }
<add>
<add> // add a little back-off to prevent EADDRNOTAVAIL errors, it's pretty easy
<add> // to exhaust the available port range
<add> function relaxedSendRequest() {
<add> setTimeout(sendRequest, 1);
<add> }
<add>
<add> function onConnection(res) {
<add> res.on('error', onError);
<add> res.on('data', onData);
<add> res.on('end', relaxedSendRequest);
<add> }
<add>
<add> function onError(err) {
<add> console.error(err.stack);
<add> relaxedSendRequest();
<add> }
<add>
<add> function onData(data) {
<add> // this space intentionally left blank
<add> }
<add>} | 1 |
PHP | PHP | remove unused file | 9138f7810d72c55a8f9673cf18ae0c4ade175f6a | <ide><path>tests/test_app/Plugin/TestPlugin/config/Schema/schema.php
<del><?php
<del>/**
<del> * TestAppSchema file
<del> *
<del> * Use for testing the loading of schema files from plugins.
<del> *
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since 1.3.0
<del> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<del> */
<del>
<del>/**
<del> * Class TestPluginAppSchema
<del> *
<del> */
<del>namespace TestPlugin\Config\Schema;
<del>
<del>use Cake\Model\Schema;
<del>
<del>class TestPluginAppSchema extends Schema {
<del>
<del> public $test_plugin_acos = array(
<del> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => 10, 'key' => 'primary'),
<del> 'parent_id' => array('type' => 'integer', 'null' => true, 'default' => null, 'length' => 10),
<del> 'model' => array('type' => 'string', 'null' => true),
<del> 'foreign_key' => array('type' => 'integer', 'null' => true, 'default' => null, 'length' => 10),
<del> 'alias' => array('type' => 'string', 'null' => true),
<del> 'lft' => array('type' => 'integer', 'null' => true, 'default' => null, 'length' => 10),
<del> 'rght' => array('type' => 'integer', 'null' => true, 'default' => null, 'length' => 10),
<del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1))
<del> );
<del>} | 1 |
Javascript | Javascript | use a single brush for scatterplot matrix | 6aad8c7c44bc77b329edbcb780f215efc1629dce | <ide><path>examples/splom/splom.js
<ide> d3.json("flowers.json", function(flower) {
<ide> .ticks(5)
<ide> .tickSize(size * n);
<ide>
<add> // Brush.
<add> var brush = d3.svg.brush()
<add> .on("brushstart", brushstart)
<add> .on("brush", brush)
<add> .on("brushend", brushend);
<add>
<ide> // Root panel.
<ide> var svg = d3.select("#chart").append("svg:svg")
<ide> .attr("width", size * n + padding)
<ide> d3.json("flowers.json", function(flower) {
<ide> .attr("cy", function(d) { return y[p.y](d[p.y]); })
<ide> .attr("r", 3);
<ide>
<del> // Plot brush; stash in the data so that we can clear programmatically.
<del> cell.call(p.brush = d3.svg.brush()
<del> .x(x[p.x])
<del> .y(y[p.y])
<del> .on("brush", brush)
<del> .on("brushend", brushend));
<add> // Plot brush.
<add> cell.call(brush.x(x[p.x]).y(y[p.y]));
<ide> }
<ide>
<del> var b; // the active brush
<add> // Clear the previously-active brush, if any.
<add> function brushstart(p) {
<add> if (brush.data !== p) {
<add> cell.call(brush.clear());
<add> brush.x(x[p.x]).y(y[p.y]).data = p;
<add> }
<add> }
<ide>
<del> // Clear the previously-active brush, if any, and highlight selected circles.
<add> // Highlight the selected circles.
<ide> function brush(p) {
<del> if (b && b !== d3.event.target) cell.filter(function(d) { return d.brush === b; }).call(b.clear());
<del> var e = (b = d3.event.target).extent();
<add> var e = brush.extent();
<ide> svg.selectAll("circle").attr("class", function(d) {
<ide> return e[0][0] <= d[p.x] && d[p.x] < e[1][0]
<ide> && e[0][1] <= d[p.y] && d[p.y] < e[1][1]
<ide> ? d.species : null;
<ide> });
<ide> }
<ide>
<del> // If the active brush is empty, select all circles.
<add> // If the brush is empty, select all circles.
<ide> function brushend() {
<del> if (b.empty()) svg.selectAll("circle").attr("class", function(d) {
<add> if (brush.empty()) svg.selectAll("circle").attr("class", function(d) {
<ide> return d.species;
<ide> });
<ide> } | 1 |
Go | Go | fix error code message upon error on push | 30f009150f303ff496307778722ed5c2c3ad80c8 | <ide><path>registry.go
<ide> func (graph *Graph) PushRepository(stdout io.Writer, remote string, localRepo Re
<ide> if errBody, err := ioutil.ReadAll(res2.Body); err != nil {
<ide> return err
<ide> } else {
<del> return fmt.Errorf("Error: Status %d trying to push checksums %s: %s", res.StatusCode, remote, errBody)
<add> return fmt.Errorf("Error: Status %d trying to push checksums %s: %s", res2.StatusCode, remote, errBody)
<ide> }
<ide> }
<ide> | 1 |
Text | Text | add new animated api to animation docs | bda7f7389a7b6d4d0bb92ca28f0627a2c775b327 | <ide><path>docs/Animations.md
<ide> permalink: docs/animations.html
<ide> next: accessibility
<ide> ---
<ide>
<del>Fluid, meaningful animations are essential to the mobile user
<del>experience. Animation APIs for React Native are currently under heavy
<del>development, the recommendations in this article are intended to be up
<del>to date with the current best-practices.
<add>Fluid, meaningful animations are essential to the mobile user experience. Like
<add>everything in React Native, Animation APIs for React Native are currently under
<add>development, but have started to coalesce around two complementary systems:
<add>`LayoutAnimation` for animated global layout transactions, and `Animated` for
<add>more granular and interactive control of specific values.
<add>
<add>### Animated ###
<add>
<add>The `Animated` library is designed to make it very easy to concisely express a
<add>wide variety of interesting animation and interaction patterns in a very
<add>performant way. `Animated` focuses on declarative relationships between inputs
<add>and outputs, with configurable transforms in between, and simple `start`/`stop`
<add>methods to control time-based animation execution. For example, a complete
<add>component with a simple spring bounce on mount looks like this:
<add>
<add>```javascript
<add>class Playground extends React.Component {
<add> constructor(props: any) {
<add> super(props);
<add> this.state = {
<add> bounceValue: new Animated.Value(0),
<add> };
<add> }
<add> render(): ReactElement {
<add> return (
<add> <Animated.Image // Base: Image, Text, View
<add> source={{uri: 'http://i.imgur.com/XMKOH81.jpg'}}
<add> style={{
<add> flex: 1,
<add> transform: [ // `transform` is an ordered array
<add> {scale: this.state.bounceValue}, // Map `bounceValue` to `scale`
<add> ]
<add> }}
<add> />
<add> );
<add> }
<add> componentDidMount() {
<add> this.state.bounceValue.setValue(1.5); // Start large
<add> Animated.spring( // Base: spring, decay, timing
<add> this.state.bounceValue, // Animate `bounceValue`
<add> {
<add> toValue: 0.8, // Animate to smaller size
<add> friction: 1, // Bouncier spring
<add> }
<add> ).start(); // Start the animation
<add> }
<add>}
<add>```
<add>
<add>`bounceValue` is initialized as part of `state` in the constructor, and mapped
<add>to the scale transform on the image. Behind the scenes, the numeric value is
<add>extracted and used to set scale. When the component mounts, the scale is set to
<add>1.5 and then a spring animation is started on `bounceValue` which will update
<add>all of its dependent mappings on each frame as the spring animates (in this
<add>case, just the scale). This is done in an optimized way that is faster than
<add>calling `setState` and re-rendering. Because the entire configuration is
<add>declarative, we will be able to implement further optimizations that serialize
<add>the configuration and runs the animation on a high-priority thread.
<add>
<add>#### Core API
<add>
<add>Most everything you need hangs directly off the `Animated` module. This
<add>includes two value types, `Value` for single values and `ValueXY` for vectors,
<add>three animation types, `spring`, `decay`, and `timing`, and three component
<add>types, `View`, `Text`, and `Image`. You can make any other component animated with
<add>`Animated.createAnimatedComponent`.
<add>
<add>The three animation types can be used to create almost any animation curve you
<add>want because each can be customized:
<add>
<add>* `spring`: Simple single-spring physics model that matches [Origami](https://facebook.github.io/origami/).
<add> * `friction`: Controls "bounciness"/overshoot. Default 7.
<add> * `tension`: Controls speed. Default 40.
<add>* `decay`: Starts with an initial velocity and gradually slows to a stop.
<add> * `velocity`: Initial velocity. Required.
<add> * `deceleration`: Rate of decay. Default 0.997.
<add>* `timing`: Maps time range to easing value.
<add> * `duration`: Length of animation (milliseconds). Default 500.
<add> * `easing`: Easing function to define curve. See `Easing` module for several
<add> predefined functions. iOS default is `Easing.inOut(Easing.ease)`.
<add> * `delay`: Start the animation after delay (milliseconds). Default 0.
<add>
<add>Animations are started by calling `start`. `start` takes a completion callback
<add>that will be called when the animation is done. If the animation is done
<add>because it finished running normally, the completion callback will be invoked
<add>with `{finished: true}`, but if the animation is done because `stop` was called
<add>on it before it could finish (e.g. because it was interrupted by a gesture or
<add>another animation), then it will receive `{finished: false}`.
<add>
<add>#### Composing Animations
<add>
<add>Animations can also be composed with `parallel`, `sequence`, `stagger`, and
<add>`delay`, each of which simply take an array of animations to execute and
<add>automatically calls start/stop as appropriate. For example:
<add>
<add>```javascript
<add>Animated.sequence([ // spring to start and twirl after decay finishes
<add> Animated.decay(position, { // coast to a stop
<add> velocity: {x: gestureState.vx, y: gestureState.vy}, // velocity from gesture release
<add> deceleration: 0.997,
<add> }),
<add> Animated.parallel([ // after decay, in parallel:
<add> Animated.spring(position, {
<add> toValue: {x: 0, y: 0} // return to start
<add> }),
<add> Animated.timing(twirl, { // and twirl
<add> toValue: 360,
<add> }),
<add> ]),
<add>]).start(); // start the sequence group
<add>```
<add>
<add>By default, if one animation is stopped or interrupted, then all other
<add>animations in the group are also stopped. Parallel has a `stopTogether` option
<add>that can be set to `false` to disable this.
<add>
<add>#### Interpolation
<add>
<add>Another powerful part of the `Animated` API is the `interpolate` function. It
<add>allows input ranges to map to different output ranges. For example, a simple
<add>mapping to convert a 0-1 range to a 0-100 range would be
<add>
<add>```javascript
<add>value.interpolate({
<add> inputRange: [0, 1],
<add> outputRange: [0, 100],
<add>});
<add>```
<add>
<add>`interpolate` supports multiple range segments as well, which is handy for
<add>defining dead zones and other handy tricks. For example, to get an negation
<add>relationship at -300 that goes to 0 at -100, then back up to 1 at 0, and then
<add>back down to zero at 100 followed by a dead-zone that remains at 0 for
<add>everything beyond that, you could do:
<add>
<add>```javascript
<add>value.interpolate({
<add> inputRange: [-300, -100, 0, 100, 101],
<add> outputRange: [300, 0, 1, 0, 0],
<add>});
<add>```
<add>
<add>Which would map like so:
<add>
<add>Input | Output
<add>------|-------
<add> -400| 450
<add> -300| 300
<add> -200| 150
<add> -100| 0
<add> -50| 0.5
<add> 0| 1
<add> 50| 0.5
<add> 100| 0
<add> 101| 0
<add> 200| 0
<add>
<add>`interpolation` also supports arbitrary easing functions, many of which are
<add>already implemented in the
<add>[`Easing`](https://github.com/facebook/react-native/blob/master/Libraries/Animation/Animated/Easing.js)
<add>class including quadradic, exponential, and bezier curves as well as functions
<add>like step and bounce. `interpolation` also has configurable behavior for
<add>extrapolation, the default being `'extend'`, but `'clamp'` is also very useful
<add>to prevent the output value from exceeding `outputRange`.
<add>
<add>#### Tracking Dynamic Values
<add>
<add>Animated values can also track other values. Just set the `toValue` of an
<add>animation to another animated value instead of a plain number, for example with
<add>spring physics for an interaction like "Chat Heads", or via `timing` with
<add>`duration: 0` for rigid/instant tracking. They can also be composed with
<add>interpolations:
<add>
<add>```javascript
<add>Animated.spring(follower, {toValue: leader}).start();
<add>Animated.timing(opacity, {
<add> toValue: pan.x.interpolate({
<add> inputRange: [0, 300],
<add> outputRange: [1, 0],
<add> }),
<add>}).start();
<add>```
<add>
<add>`ValueXY` is a handy way to deal with 2D interactions, such as panning/dragging.
<add>It is a simple wrapper that basically just contains two `Animated.Value`
<add>instances and some helper functions that call through to them, making `ValueXY`
<add>a drop-in replacement for `Value` in many cases. For example, in the code
<add>snippet above, `leader` and `follower` could both be of type `ValueXY` and the x
<add>and y values will both track as you would expect.
<add>
<add>#### Input Events
<add>
<add>`Animated.event` is the input side of the Animated API, allowing gestures and
<add>other events to map directly to animated values. This is done with a structured
<add>map syntax so that values can be extracted from complex event objects. The
<add>first level is an array to allow mapping across multiple args, and that array
<add>contains nested objects. In the example, you can see that `scrollX` maps to
<add>`event.nativeEvent.contentOffset.x` (`event` is normally the first arg to the
<add>handler), and `pan.x` maps to `gestureState.dx` (`gestureState` is the second
<add>arg passed to the `PanResponder` handler).
<add>
<add>```javascript
<add>onScroll={Animated.event(
<add> [{nativeEvent: {contentOffset: {y: pan.y}}}] // pan.y = e.nativeEvent.contentOffset.y
<add>)}
<add>onPanResponderMove={Animated.event([
<add> null, // ignore the native event
<add> {dx: pan.x, dy: pan.y} // extract dx and dy from gestureState
<add>]);
<add>```
<add>
<add>#### Responding to the Current Animation Value
<add>
<add>You may notice that there is no obvious way to read the current value while
<add>animating - this is because the value may only be known in the native runtime
<add>due to optimizations. If you need to run JavaScript in response to the current
<add>value, there are two approaches:
<add>
<add>- `spring.stopAnimation(callback)` will stop the animation and invoke `callback`
<add>with the final value - this is useful when making gesture transitions.
<add>- `spring.addListener(callback)` will invoke `callback` asynchronously while the
<add>animation is running, providing a recent value. This is useful for triggering
<add>state changes, for example snapping a bobble to a new option as the user drags
<add>it closer, because these larger state changes are less sensitive to a few frames
<add>of lag compared to continuous gestures like panning which need to run at 60fps.
<add>
<add>#### Future Work
<add>
<add>As previously mentioned, we're planning on optimizing Animated under the hood to
<add>make it even more performant. We would also like to experiment with more
<add>declarative and higher level gestures and triggers, such as horizontal vs.
<add>vertical panning.
<add>
<add>The above API gives a powerful tool for expressing all sorts of animations in a
<add>concise, robust, and performant way. Check out more example code in
<add>[UIExplorer/AnimationExample](https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/AnimationExample). Of course there may still be times where `Animated`
<add>doesn't support what you need, and the following sections cover other animation
<add>systems.
<add>
<add>### LayoutAnimation
<add>
<add>`LayoutAnimation` allows you to globally configure `create` and `update`
<add>animations that will be used for all views in the next render/layout cycle.
<add>This is useful for doing flexbox layout updates without bothering to measure or
<add>calculate specific properties in order to animate them directly, and is
<add>especially useful when layout changes may affect ancestors, for example a "see
<add>more" expansion that also increases the size of the parent and pushes down the
<add>row below which would otherwise require explicit coordination between the
<add>components in order to animate them all in sync.
<add>
<add>Note that although `LayoutAnimation` is very powerful and can be quite useful,
<add>it provides much less control than `Animated` and other animation libraries, so
<add>you may need to use another approach if you can't get `LayoutAnimation` to do
<add>what you want.
<add>
<add>
<add>
<add>```javascript
<add>var App = React.createClass({
<add> componentWillMount() {
<add> // Animate creation
<add> LayoutAnimation.spring();
<add> },
<add>
<add> getInitialState() {
<add> return { w: 100, h: 100 }
<add> },
<add>
<add> _onPress() {
<add> // Animate the update
<add> LayoutAnimation.spring();
<add> this.setState({w: this.state.w + 15, h: this.state.h + 15})
<add> },
<add>
<add> render: function() {
<add> return (
<add> <View style={styles.container}>
<add> <View style={[styles.box, {width: this.state.w, height: this.state.h}]} />
<add> <TouchableOpacity onPress={this._onPress}>
<add> <View style={styles.button}>
<add> <Text style={styles.buttonText}>Press me!</Text>
<add> </View>
<add> </TouchableOpacity>
<add> </View>
<add> );
<add> }
<add>});
<add>```
<add>[Run this example](https://rnplay.org/apps/uaQrGQ)
<add>
<add>This example uses a preset value, you can customize the animations as
<add>you need, see [LayoutAnimation.js](https://github.com/facebook/react-native/blob/master/Libraries/Animation/LayoutAnimation.js)
<add>for more information.
<ide>
<ide> ### requestAnimationFrame
<ide>
<ide> `requestAnimationFrame` is a polyfill from the browser that you might be
<ide> familiar with. It accepts a function as its only argument and calls that
<ide> function before the next repaint. It is an essential building block for
<del>animations that underlies all of the JavaScript-based animation APIs.
<del>
<del>### JavaScript-based Animation APIs
<add>animations that underlies all of the JavaScript-based animation APIs. In
<add>general, you shouldn't need to call this yourself - the animation API's will
<add>manage frame updates for you.
<ide>
<del>These APIs do all of the calculations in JavaScript, then send over
<del>updated properties to the native side on each frame.
<del>
<del>#### react-tween-state
<add>### react-tween-state
<ide>
<ide> [react-tween-state](https://github.com/chenglou/react-tween-state) is a
<ide> minimal library that does exactly what its name suggests: it *tweens* a
<ide> Here we animated the opacity, but as you might guess, we can animate any
<ide> numeric value. Read more about react-tween-state in its
<ide> [README](https://github.com/chenglou/react-tween-state).
<ide>
<del>#### Rebound
<add>### Rebound
<ide>
<ide> [Rebound.js](https://github.com/facebook/rebound-js) is a JavaScript port of
<ide> [Rebound for Android](https://github.com/facebook/rebound). It is
<ide> using the
<ide> can monitor the frame rate by using the In-App Developer Menu "FPS
<ide> Monitor" tool.
<ide>
<del>#### Navigator Scene Transitions
<add>### Navigator Scene Transitions
<ide>
<ide> As mentioned in the [Navigator
<ide> Comparison](https://facebook.github.io/react-native/docs/navigator-comparison.html#content),
<ide> var CustomSceneConfig = Object.assign({}, BaseConfig, {
<ide> For further information about customizing scene transitions, [read the
<ide> source](https://github.com/facebook/react-native/blob/master/Libraries/CustomComponents/Navigator/NavigatorSceneConfigs.js).
<ide>
<del>### Native-based Animation APIs
<del>
<del>#### LayoutAnimation
<del>
<del>LayoutAnimation allows you to globally configure `create` and `update`
<del>animations that will be used for all views in the next render cycle.
<del>
<del>
<del>
<del>```javascript
<del>var App = React.createClass({
<del> componentWillMount() {
<del> // Animate creation
<del> LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
<del> },
<del>
<del> getInitialState() {
<del> return { w: 100, h: 100 }
<del> },
<del>
<del> _onPress() {
<del> // Animate the update
<del> LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
<del> this.setState({w: this.state.w + 15, h: this.state.h + 15})
<del> },
<del>
<del> render: function() {
<del> return (
<del> <View style={styles.container}>
<del> <View style={[styles.box, {width: this.state.w, height: this.state.h}]} />
<del> <TouchableOpacity onPress={this._onPress}>
<del> <View style={styles.button}>
<del> <Text style={styles.buttonText}>Press me!</Text>
<del> </View>
<del> </TouchableOpacity>
<del> </View>
<del> );
<del> }
<del>});
<del>```
<del>[Run this example](https://rnplay.org/apps/uaQrGQ)
<del>
<del>This example uses a preset value, you can customize the animations as
<del>you need, see [LayoutAnimation.js](https://github.com/facebook/react-native/blob/master/Libraries/Animation/LayoutAnimation.js)
<del>for more information.
<del>
<del>#### AnimationExperimental *(Deprecated)*
<add>### AnimationExperimental *(Deprecated)*
<ide>
<ide> As the name would suggest, this was only ever an experimental API and it
<ide> is **not recommended to use this on your apps**. It has some rough edges
<ide> AnimationExperimental.startAnimation(
<ide>
<ide> 
<ide>
<del>#### Pop *(Unsupported, not recommended)*
<add>### Pop *(Unsupported, not recommended)*
<ide>
<ide> [Facebook Pop](https://github.com/facebook/pop) "supports spring and
<ide> decay dynamic animations, making it useful for building realistic, | 1 |
Text | Text | improve promise terminology | 271e04f5ba4eac406d3898fd844c72117762961d | <ide><path>doc/api/fs.md
<ide> fs.unlink('/tmp/hello', (err) => {
<ide>
<ide> ## Promise example
<ide>
<del>Promise-based operations return a `Promise` that is resolved when the
<add>Promise-based operations return a `Promise` that is fulfilled when the
<ide> asynchronous operation is complete.
<ide>
<ide> ```js
<ide> added: v12.12.0
<ide> Asynchronously close the directory's underlying resource handle.
<ide> Subsequent reads will result in errors.
<ide>
<del>A `Promise` is returned that will be resolved after the resource has been
<add>A `Promise` is returned that will be fulfilled after the resource has been
<ide> closed.
<ide>
<ide> ### `dir.close(callback)`
<ide> added: v12.12.0
<ide> Asynchronously read the next directory entry via readdir(3) as an
<ide> [`fs.Dirent`][].
<ide>
<del>After the read is completed, a `Promise` is returned that will be resolved with
<del>an [`fs.Dirent`][], or `null` if there are no more directory entries to read.
<add>After the read is completed, a `Promise` is returned that will be fulfilled
<add>with an [`fs.Dirent`][], or `null` if there are no more directory entries to
<add>read.
<ide>
<ide> Directory entries returned by this function are in no particular order as
<ide> provided by the operating system's underlying directory mechanisms.
<ide> Instances of the `FileHandle` object are created internally by the
<ide> Unlike the callback-based API (`fs.fstat()`, `fs.fchown()`, `fs.fchmod()`, and
<ide> so on), a numeric file descriptor is not used by the promise-based API. Instead,
<ide> the promise-based API uses the `FileHandle` class in order to help avoid
<del>accidental leaking of unclosed file descriptors after a `Promise` is resolved or
<del>rejected.
<add>accidental leaking of unclosed file descriptors after a `Promise` is fulfilled
<add>or rejected.
<ide>
<ide> #### Event: `'close'`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> * `mode` {integer}
<ide> * Returns: {Promise}
<ide>
<del>Modifies the permissions on the file. The `Promise` is resolved with no
<add>Modifies the permissions on the file. The `Promise` is fulfilled with no
<ide> arguments upon success.
<ide>
<ide> #### `filehandle.chown(uid, gid)`
<ide> added: v10.0.0
<ide> * `gid` {integer}
<ide> * Returns: {Promise}
<ide>
<del>Changes the ownership of the file then resolves the `Promise` with no arguments
<add>Changes the ownership of the file then fulfills the `Promise` with no arguments
<ide> upon success.
<ide>
<ide> #### `filehandle.close()`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide>
<del>* Returns: {Promise} A `Promise` that will be resolved once the underlying
<add>* Returns: {Promise} A `Promise` that will be fulfilled once the underlying
<ide> file descriptor is closed, or will be rejected if an error occurs while
<ide> closing.
<ide>
<ide> added: v10.0.0
<ide>
<ide> * Returns: {Promise}
<ide>
<del>Asynchronous fdatasync(2). The `Promise` is resolved with no arguments upon
<add>Asynchronous fdatasync(2). The `Promise` is fulfilled with no arguments upon
<ide> success.
<ide>
<ide> #### `filehandle.fd`
<ide> If `position` is `null`, data will be read from the current file position,
<ide> and the file position will be updated.
<ide> If `position` is an integer, the file position will remain unchanged.
<ide>
<del>Following successful read, the `Promise` is resolved with an object with a
<add>Following successful read, the `Promise` is fulfilled with an object with a
<ide> `bytesRead` property specifying the number of bytes read, and a `buffer`
<ide> property that is a reference to the passed in `buffer` argument.
<ide>
<ide> added: v10.0.0
<ide>
<ide> Asynchronously reads the entire contents of a file.
<ide>
<del>The `Promise` is resolved with the contents of the file. If no encoding is
<add>The `Promise` is fulfilled with the contents of the file. If no encoding is
<ide> specified (using `options.encoding`), the data is returned as a `Buffer`
<ide> object. Otherwise, the data will be a string.
<ide>
<ide> added:
<ide>
<ide> Read from a file and write to an array of `ArrayBufferView`s
<ide>
<del>The `Promise` is resolved with an object containing a `bytesRead` property
<add>The `Promise` is fulfilled with an object containing a `bytesRead` property
<ide> identifying the number of bytes read, and a `buffers` property containing
<ide> a reference to the `buffers` input.
<ide>
<ide> added: v10.0.0
<ide>
<ide> * Returns: {Promise}
<ide>
<del>Asynchronous fsync(2). The `Promise` is resolved with no arguments upon
<add>Asynchronous fsync(2). The `Promise` is fulflled with no arguments upon
<ide> success.
<ide>
<ide> #### `filehandle.truncate(len)`
<ide> added: v10.0.0
<ide> * `len` {integer} **Default:** `0`
<ide> * Returns: {Promise}
<ide>
<del>Truncates the file then resolves the `Promise` with no arguments upon success.
<add>Truncates the file then fulfills the `Promise` with no arguments upon success.
<ide>
<ide> If the file was larger than `len` bytes, only the first `len` bytes will be
<ide> retained in the file.
<ide> added: v10.0.0
<ide> * Returns: {Promise}
<ide>
<ide> Change the file system timestamps of the object referenced by the `FileHandle`
<del>then resolves the `Promise` with no arguments upon success.
<add>then fulfills the `Promise` with no arguments upon success.
<ide>
<del>This function does not work on AIX versions before 7.1, it will resolve the
<add>This function does not work on AIX versions before 7.1, it will reject the
<ide> `Promise` with an error using code `UV_ENOSYS`.
<ide>
<ide> #### `filehandle.write(buffer[, offset[, length[, position]]])`
<ide> changes:
<ide>
<ide> Write `buffer` to the file.
<ide>
<del>The `Promise` is resolved with an object containing a `bytesWritten` property
<add>The `Promise` is fulfilled with an object containing a `bytesWritten` property
<ide> identifying the number of bytes written, and a `buffer` property containing
<ide> a reference to the `buffer` written.
<ide>
<ide> should be written. If `typeof position !== 'number'`, the data will be written
<ide> at the current position. See pwrite(2).
<ide>
<ide> It is unsafe to use `filehandle.write()` multiple times on the same file
<del>without waiting for the `Promise` to be resolved (or rejected). For this
<add>without waiting for the `Promise` to be fulfilled (or rejected). For this
<ide> scenario, use [`fs.createWriteStream()`][].
<ide>
<ide> On Linux, positional writes do not work when the file is opened in append mode.
<ide> changes:
<ide> Write `string` to the file. If `string` is not a string, or an
<ide> object with an own `toString` function property, then an exception is thrown.
<ide>
<del>The `Promise` is resolved with an object containing a `bytesWritten` property
<add>The `Promise` is fulfilled with an object containing a `bytesWritten` property
<ide> identifying the number of bytes written, and a `buffer` property containing
<ide> a reference to the `string` written.
<ide>
<ide> will be written at the current position. See pwrite(2).
<ide> `encoding` is the expected string encoding.
<ide>
<ide> It is unsafe to use `filehandle.write()` multiple times on the same file
<del>without waiting for the `Promise` to be resolved (or rejected). For this
<add>without waiting for the `Promise` to be fulfilled (or rejected). For this
<ide> scenario, use [`fs.createWriteStream()`][].
<ide>
<ide> On Linux, positional writes do not work when the file is opened in append mode.
<ide> changes:
<ide>
<ide> Asynchronously writes data to a file, replacing the file if it already exists.
<ide> `data` can be a string, a buffer, or an object with an own `toString` function
<del>property. The `Promise` is resolved with no arguments upon success.
<add>property. The `Promise` is fulfilled with no arguments upon success.
<ide>
<ide> The `encoding` option is ignored if `data` is a buffer.
<ide>
<ide> If `options` is a string, then it specifies the encoding.
<ide> The `FileHandle` has to support writing.
<ide>
<ide> It is unsafe to use `filehandle.writeFile()` multiple times on the same file
<del>without waiting for the `Promise` to be resolved (or rejected).
<add>without waiting for the `Promise` to be fulfilled (or rejected).
<ide>
<ide> If one or more `filehandle.write()` calls are made on a file handle and then a
<ide> `filehandle.writeFile()` call is made, the data will be written from the
<ide> added: v12.9.0
<ide>
<ide> Write an array of `ArrayBufferView`s to the file.
<ide>
<del>The `Promise` is resolved with an object containing a `bytesWritten` property
<add>The `Promise` is fulfilled with an object containing a `bytesWritten` property
<ide> identifying the number of bytes written, and a `buffers` property containing
<ide> a reference to the `buffers` input.
<ide>
<ide> checks to be performed. Check [File access constants][] for possible values
<ide> of `mode`. It is possible to create a mask consisting of the bitwise OR of
<ide> two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
<ide>
<del>If the accessibility check is successful, the `Promise` is resolved with no
<add>If the accessibility check is successful, the `Promise` is fulfilled with no
<ide> value. If any of the accessibility checks fail, the `Promise` is rejected
<ide> with an `Error` object. The following example checks if the file
<ide> `/etc/passwd` can be read and written by the current process.
<ide> added: v10.0.0
<ide>
<ide> Asynchronously append data to a file, creating the file if it does not yet
<ide> exist. `data` can be a string or a [`Buffer`][]. The `Promise` will be
<del>resolved with no arguments upon success.
<add>fulfilled with no arguments upon success.
<ide>
<ide> If `options` is a string, then it specifies the encoding.
<ide>
<ide> added: v10.0.0
<ide> * `mode` {string|integer}
<ide> * Returns: {Promise}
<ide>
<del>Changes the permissions of a file then resolves the `Promise` with no
<add>Changes the permissions of a file then fulfills the `Promise` with no
<ide> arguments upon succces.
<ide>
<ide> ### `fsPromises.chown(path, uid, gid)`
<ide> added: v10.0.0
<ide> * `gid` {integer}
<ide> * Returns: {Promise}
<ide>
<del>Changes the ownership of a file then resolves the `Promise` with no arguments
<add>Changes the ownership of a file then fulfills the `Promise` with no arguments
<ide> upon success.
<ide>
<ide> ### `fsPromises.copyFile(src, dest[, mode])`
<ide> changes:
<ide> * Returns: {Promise}
<ide>
<ide> Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
<del>already exists. The `Promise` will be resolved with no arguments upon success.
<add>already exists. The `Promise` will be fulfilled with no arguments upon success.
<ide>
<ide> Node.js makes no guarantees about the atomicity of the copy operation. If an
<ide> error occurs after the destination file has been opened for writing, Node.js
<ide> deprecated: v10.0.0
<ide> * `mode` {integer}
<ide> * Returns: {Promise}
<ide>
<del>Changes the permissions on a symbolic link then resolves the `Promise` with
<add>Changes the permissions on a symbolic link then fulfills the `Promise` with
<ide> no arguments upon success. This method is only implemented on macOS.
<ide>
<ide> ### `fsPromises.lchown(path, uid, gid)`
<ide> changes:
<ide> * `gid` {integer}
<ide> * Returns: {Promise}
<ide>
<del>Changes the ownership on a symbolic link then resolves the `Promise` with
<add>Changes the ownership on a symbolic link then fulfills the `Promise` with
<ide> no arguments upon success.
<ide>
<ide> ### `fsPromises.lutimes(path, atime, mtime)`
<ide> Changes the access and modification times of a file in the same way as
<ide> symbolic link, then the link is not dereferenced: instead, the timestamps of
<ide> the symbolic link itself are changed.
<ide>
<del>Upon success, the `Promise` is resolved without arguments.
<add>Upon success, the `Promise` is fulfilled without arguments.
<ide>
<ide> ### `fsPromises.link(existingPath, newPath)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> * `newPath` {string|Buffer|URL}
<ide> * Returns: {Promise}
<ide>
<del>Asynchronous link(2). The `Promise` is resolved with no arguments upon success.
<add>Asynchronous link(2). The `Promise` is fulfilled with no arguments upon success.
<ide>
<ide> ### `fsPromises.lstat(path[, options])`
<ide> <!-- YAML
<ide> changes:
<ide> [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
<ide> * Returns: {Promise}
<ide>
<del>Asynchronous lstat(2). The `Promise` is resolved with the [`fs.Stats`][] object
<del>for the given symbolic link `path`.
<add>Asynchronous lstat(2). The `Promise` is fulfilled with the [`fs.Stats`][]
<add>object for the given symbolic link `path`.
<ide>
<ide> ### `fsPromises.mkdir(path[, options])`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> * `mode` {string|integer} Not supported on Windows. **Default:** `0o777`.
<ide> * Returns: {Promise}
<ide>
<del>Asynchronously creates a directory then resolves the `Promise` with either no
<add>Asynchronously creates a directory then fulfills the `Promise` with either no
<ide> arguments, or the first directory path created if `recursive` is `true`.
<ide>
<ide> The optional `options` argument can be an integer specifying `mode` (permission
<ide> added: v10.0.0
<ide> * `encoding` {string} **Default:** `'utf8'`
<ide> * Returns: {Promise}
<ide>
<del>Creates a unique temporary directory and resolves the `Promise` with the created
<del>directory path. A unique directory name is generated by appending six random
<del>characters to the end of the provided `prefix`. Due to platform
<add>Creates a unique temporary directory and fulfills the `Promise` with the
<add>created directory path. A unique directory name is generated by appending six
<add>random characters to the end of the provided `prefix`. Due to platform
<ide> inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms,
<ide> notably the BSDs, can return more than six random characters, and replace
<ide> trailing `X` characters in `prefix` with random characters.
<ide> changes:
<ide> * `mode` {string|integer} **Default:** `0o666` (readable and writable)
<ide> * Returns: {Promise}
<ide>
<del>Asynchronous file open that returns a `Promise` that, when resolved, yields a
<add>Asynchronous file open that returns a `Promise` that, when fulfilled, yields a
<ide> `FileHandle` object. See open(2).
<ide>
<ide> `mode` sets the file mode (permission and sticky bits), but only if the file was
<ide> changes:
<ide> * `withFileTypes` {boolean} **Default:** `false`
<ide> * Returns: {Promise}
<ide>
<del>Reads the contents of a directory then resolves the `Promise` with an array
<add>Reads the contents of a directory then fulfills the `Promise` with an array
<ide> of the names of the files in the directory excluding `'.'` and `'..'`.
<ide>
<ide> The optional `options` argument can be a string specifying an encoding, or an
<ide> object with an `encoding` property specifying the character encoding to use for
<ide> the filenames. If the `encoding` is set to `'buffer'`, the filenames returned
<ide> will be passed as `Buffer` objects.
<ide>
<del>If `options.withFileTypes` is set to `true`, the resolved array will contain
<add>If `options.withFileTypes` is set to `true`, the array will contain
<ide> [`fs.Dirent`][] objects.
<ide>
<ide> ```js
<ide> changes:
<ide>
<ide> Asynchronously reads the entire contents of a file.
<ide>
<del>The `Promise` is resolved with the contents of the file. If no encoding is
<add>The `Promise` is fulfilled with the contents of the file. If no encoding is
<ide> specified (using `options.encoding`), the data is returned as a `Buffer`
<ide> object. Otherwise, the data will be a string.
<ide>
<ide> added: v10.0.0
<ide> * `encoding` {string} **Default:** `'utf8'`
<ide> * Returns: {Promise}
<ide>
<del>Asynchronous readlink(2). The `Promise` is resolved with the `linkString` upon
<add>Asynchronous readlink(2). The `Promise` is fulfilled with the `linkString` upon
<ide> success.
<ide>
<ide> The optional `options` argument can be a string specifying an encoding, or an
<ide> added: v10.0.0
<ide> * Returns: {Promise}
<ide>
<ide> Determines the actual location of `path` using the same semantics as the
<del>`fs.realpath.native()` function then resolves the `Promise` with the resolved
<add>`fs.realpath.native()` function then fulfills the `Promise` with the resolved
<ide> path.
<ide>
<ide> Only paths that can be converted to UTF8 strings are supported.
<ide> added: v10.0.0
<ide> * `newPath` {string|Buffer|URL}
<ide> * Returns: {Promise}
<ide>
<del>Renames `oldPath` to `newPath` and resolves the `Promise` with no arguments
<add>Renames `oldPath` to `newPath` and fulfills the `Promise` with no arguments
<ide> upon success.
<ide>
<ide> ### `fsPromises.rmdir(path[, options])`
<ide> changes:
<ide> **Default:** `100`.
<ide> * Returns: {Promise}
<ide>
<del>Removes the directory identified by `path` then resolves the `Promise` with
<add>Removes the directory identified by `path` then fulfills the `Promise` with
<ide> no arguments upon success.
<ide>
<ide> Using `fsPromises.rmdir()` on a file (not a directory) results in the
<ide> added: v14.14.0
<ide> **Default:** `100`.
<ide>
<ide> Removes files and directories (modeled on the standard POSIX `rm` utility).
<del>Resolves the `Promise` with no arguments on success.
<add>Fulfills the `Promise` with no arguments on success.
<ide>
<ide> ### `fsPromises.stat(path[, options])`
<ide> <!-- YAML
<ide> changes:
<ide> [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
<ide> * Returns: {Promise}
<ide>
<del>The `Promise` is resolved with the [`fs.Stats`][] object for the given `path`.
<add>The `Promise` is fulfilled with the [`fs.Stats`][] object for the given `path`.
<ide>
<ide> ### `fsPromises.symlink(target, path[, type])`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> * `type` {string} **Default:** `'file'`
<ide> * Returns: {Promise}
<ide>
<del>Creates a symbolic link then resolves the `Promise` with no arguments upon
<add>Creates a symbolic link then fulfills the `Promise` with no arguments upon
<ide> success.
<ide>
<ide> The `type` argument is only used on Windows platforms and can be one of `'dir'`,
<ide> added: v10.0.0
<ide> * `len` {integer} **Default:** `0`
<ide> * Returns: {Promise}
<ide>
<del>Truncates the `path` then resolves the `Promise` with no arguments upon
<add>Truncates the `path` then fulfills the `Promise` with no arguments upon
<ide> success. The `path` *must* be a string or `Buffer`.
<ide>
<ide> ### `fsPromises.unlink(path)`
<ide> added: v10.0.0
<ide> * `path` {string|Buffer|URL}
<ide> * Returns: {Promise}
<ide>
<del>Asynchronous unlink(2). The `Promise` is resolved with no arguments upon
<add>Asynchronous unlink(2). The `Promise` is fulfilled with no arguments upon
<ide> success.
<ide>
<ide> ### `fsPromises.utimes(path, atime, mtime)`
<ide> added: v10.0.0
<ide> * Returns: {Promise}
<ide>
<ide> Change the file system timestamps of the object referenced by `path` then
<del>resolves the `Promise` with no arguments upon success.
<add>fulfills the `Promise` with no arguments upon success.
<ide>
<ide> The `atime` and `mtime` arguments follow these rules:
<ide>
<ide> changes:
<ide>
<ide> Asynchronously writes data to a file, replacing the file if it already exists.
<ide> `data` can be a string, a buffer, or an object with an own `toString` function
<del>property. The `Promise` is resolved with no arguments upon success.
<add>property. The `Promise` is fulfilled with no arguments upon success.
<ide>
<ide> The `encoding` option is ignored if `data` is a buffer.
<ide> | 1 |
Python | Python | reset password hashers cache on settings_changed | 2a09404792f9d369718143fdfbe9530fe2e60912 | <ide><path>django/contrib/auth/hashers.py
<ide> import hashlib
<ide>
<add>from django.dispatch import receiver
<ide> from django.conf import settings
<add>from django.test.signals import setting_changed
<ide> from django.utils import importlib
<ide> from django.utils.datastructures import SortedDict
<ide> from django.utils.encoding import smart_str
<ide> HASHERS = None # lazily loaded from PASSWORD_HASHERS
<ide> PREFERRED_HASHER = None # defaults to first item in PASSWORD_HASHERS
<ide>
<add>@receiver(setting_changed)
<add>def reset_hashers(**kwargs):
<add> if kwargs['setting'] == 'PASSWORD_HASHERS':
<add> global HASHERS, PREFERRED_HASHER
<add> HASHERS = None
<add> PREFERRED_HASHER = None
<add>
<ide>
<ide> def is_password_usable(encoded):
<ide> return (encoded is not None and encoded != UNUSABLE_PASSWORD) | 1 |
Javascript | Javascript | fix broken preventdefault test | 5cec32492c52209ce11b38b8180f9bdb909d041b | <ide><path>test/ng/directive/formSpec.js
<ide> describe('form', function() {
<ide> describe('preventing default submission', function() {
<ide>
<ide> it('should prevent form submission', function() {
<del> var startingUrl = '' + window.location;
<del> doc = jqLite('<form name="myForm"><input type="submit" value="submit" />');
<add> var nextTurn = false,
<add> reloadPrevented;
<add>
<add> doc = jqLite('<form><input type="submit" value="submit" ></form>');
<ide> $compile(doc)(scope);
<ide>
<add> doc.bind('submit', function(e) {
<add> reloadPrevented = e.defaultPrevented;
<add> });
<add>
<ide> browserTrigger(doc.find('input'));
<del> waitsFor(
<del> function() { return true; },
<del> 'let browser breath, so that the form submission can manifest itself', 10);
<add>
<add> // let the browser process all events (and potentially reload the page)
<add> setTimeout(function() { nextTurn = true;});
<add>
<add> waitsFor(function() { return nextTurn; });
<ide>
<ide> runs(function() {
<del> expect('' + window.location).toEqual(startingUrl);
<add> expect(reloadPrevented).toBe(true);
<ide> });
<ide> });
<ide> | 1 |
Text | Text | hide solution from tests in portuguese challenge | 4438eb0f331c8f5646935ce26f2202392e69154a | <ide><path>curriculum/challenges/portuguese/01-responsive-web-design/css-grid/use-grid-area-without-creating-an-areas-template.portuguese.md
<ide> localeTitle: Usar área de grade sem criar um modelo de áreas
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>item5</code> classe <code>item5</code> deve ter uma propriedade de <code>grid-area</code> que tenha o valor de <code>3/1/4/4</code> .
<del> testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-area\s*?:\s*?3\s*?\/\s*?1\s*?\/\s*?4\s*?\/\s*?4\s*?;[\s\S]*}/gi), "<code>item5</code> class should have a <code>grid-area</code> property that has the value of <code>3/1/4/4</code>.");'
<del>
<add> - text: A classe <code>item5</code> deve ter uma propriedade <code>grid-area</code> de tal forma que esteja entre a terceira e a quarta linhas horizontais e entre a primeira e a quarta linhas verticais.
<add> testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-area\s*?:\s*?3\s*?\/\s*?1\s*?\/\s*?4\s*?\/\s*?4\s*?;[\s\S]*}/gi));'
<ide> ```
<ide>
<ide> </section> | 1 |
Javascript | Javascript | return consistent datastructure type | fc3fe304d9b15578a304927832efaea6d293cfa0 | <ide><path>lib/ModuleGraph.js
<ide> const WeakTupleMap = require("./util/WeakTupleMap");
<ide> * @returns {string}
<ide> */
<ide>
<del>const EMPTY_ARRAY = [];
<add>const EMPTY_SET = new Set();
<ide>
<ide> /**
<ide> * @param {SortableSet<ModuleGraphConnection>} set input
<ide> class ModuleGraph {
<ide> */
<ide> getOutgoingConnections(module) {
<ide> const connections = this._getModuleGraphModule(module).outgoingConnections;
<del> return connections === undefined ? EMPTY_ARRAY : connections;
<add> return connections === undefined ? EMPTY_SET : connections;
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | accept undefined scene.nodes | 6c96a31043f2e41884c4471abfa07698013a0861 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> if ( scene.extras ) _scene.userData = scene.extras;
<ide>
<del> var nodes = scene.nodes;
<add> var nodes = scene.nodes || [];
<ide>
<ide> for ( var i = 0, l = nodes.length; i < l; i ++ ) {
<ide> | 1 |
Javascript | Javascript | fix typing of more resolver options | efc12cd5bffcc5161f7002a63506be893b8794e1 | <ide><path>packager/react-packager/src/Resolver/index.js
<ide>
<ide> const DependencyGraph = require('../node-haste');
<ide>
<del>const declareOpts = require('../lib/declareOpts');
<ide> const defaults = require('../../../defaults');
<ide> const pathJoin = require('path').join;
<ide>
<ide> type Options = {
<ide> watch?: boolean,
<ide> };
<ide>
<del>const getDependenciesValidateOpts = declareOpts({
<del> dev: {
<del> type: 'boolean',
<del> default: true,
<del> },
<del> platform: {
<del> type: 'string',
<del> required: false,
<del> },
<del> unbundle: {
<del> type: 'boolean',
<del> default: false,
<del> },
<del> recursive: {
<del> type: 'boolean',
<del> default: true,
<del> },
<del>});
<del>
<ide> class Resolver {
<ide>
<ide> _depGraph: DependencyGraph;
<ide> class Resolver {
<ide>
<ide> getDependencies(
<ide> entryPath: string,
<del> options: {},
<add> options: {platform: string, recursive?: boolean},
<ide> transformOptions: TransformOptions,
<ide> onProgress?: ?(finishedModules: number, totalModules: number) => mixed,
<ide> getModuleId: mixed,
<ide> ): Promise<ResolutionResponse> {
<del> const {platform, recursive} = getDependenciesValidateOpts(options);
<add> const {platform, recursive = true} = options;
<ide> return this._depGraph.getDependencies({
<ide> entryPath,
<ide> platform,
<ide> class Resolver {
<ide> });
<ide> }
<ide>
<del> getModuleSystemDependencies(options: {}): Array<Module> {
<del> const opts = getDependenciesValidateOpts(options);
<add> getModuleSystemDependencies({dev = true}: {dev?: boolean}): Array<Module> {
<ide>
<del> const prelude = opts.dev
<add> const prelude = dev
<ide> ? pathJoin(__dirname, 'polyfills/prelude_dev.js')
<ide> : pathJoin(__dirname, 'polyfills/prelude.js');
<ide> | 1 |
Text | Text | fix partial spanish translations | 15da2cf118de8187792e3635f24b39cb3e4d06d4 | <ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.spanish.md
<ide> localeTitle: Contar hacia atrás con un bucle for
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Un bucle for también puede contar hacia atrás, siempre que podamos definir las condiciones correctas. Para contar hacia atrás de dos en dos, necesitaremos cambiar nuestra <code>initialization</code> , <code>condition</code> y <code>final-expression</code> . Comenzaremos en <code>i = 10</code> y haremos un bucle mientras <code>i > 0</code> . Disminuiremos <code>i</code> en 2 cada bucle con <code>i -= 2</code> . <blockquote> var ourArray = []; <br> para (var i = 10; i> 0; i- = 2) { <br> nuestroArray.push (i); <br> } </blockquote> <code>ourArray</code> ahora contendrá <code>[10,8,6,4,2]</code> . Cambiemos nuestra <code>initialization</code> y <code>final-expression</code> para que podamos contar hacia atrás de dos en dos por números impares. </section>
<add><section id="description"> Un bucle for también puede contar hacia atrás, siempre que podamos definir las condiciones correctas. Para contar hacia atrás de dos en dos, necesitaremos cambiar nuestra <code>initialization</code> , <code>condition</code> y <code>final-expression</code> . Comenzaremos en <code>i = 10</code> y haremos un bucle mientras <code>i > 0</code> . Disminuiremos <code>i</code> en 2 cada bucle con <code>i -= 2</code> . <blockquote> var ourArray = []; <br> for (var i = 10; i> 0; i- = 2) { <br> ourArray.push (i); <br> } </blockquote> <code>ourArray</code> ahora contendrá <code>[10,8,6,4,2]</code> . Cambiemos nuestra <code>initialization</code> y <code>final-expression</code> para que podamos contar hacia atrás de dos en dos por números impares. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> Empuje los números impares del 9 al 1 a <code>myArray</code> usando un bucle <code>for</code> . </section>
<ide> localeTitle: Contar hacia atrás con un bucle for
<ide>
<ide> ```yml
<ide> tests:
<del> - text: Usted debe estar usando una <code>for</code> bucle para esto.
<del> testString: 'assert(code.match(/for\s*\(/g).length > 1, "You should be using a <code>for</code> loop for this.");'
<del> - text: Deberías estar usando el método de matriz <code>push</code> .
<del> testString: 'assert(code.match(/myArray.push/), "You should be using the array method <code>push</code>.");'
<del> - text: '<code>myArray</code> debe ser igual a <code>[9,7,5,3,1]</code> .'
<del> testString: 'assert.deepEqual(myArray, [9,7,5,3,1], "<code>myArray</code> should equal <code>[9,7,5,3,1]</code>.");'
<add> - text: Usted debe estar usando un bucle <code>for</code> para esto.
<add> testString: 'assert(code.match(/for\s*\(/g).length > 1, "Usted debe estar usando un bucle <code>for</code> para esto.");'
<add> - text: Deberías estar usando el método de matriz <code>push</code>.
<add> testString: 'assert(code.match(/myArray.push/), "Deberías estar usando el método de matriz <code>push</code>.");'
<add> - text: '<code>myArray</code> debe ser igual a <code>[9,7,5,3,1]</code>.'
<add> testString: 'assert.deepEqual(myArray, [9,7,5,3,1], "<code>myArray</code> debe ser igual a <code>[9,7,5,3,1]</code>.");'
<ide>
<ide> ```
<ide> | 1 |
Text | Text | suggest checkhost in checkserveridentity docs | 1000eb168a06cc4403454c48dd1a2f8bdfd60275 | <ide><path>doc/api/tls.md
<ide> Verifies the certificate `cert` is issued to `hostname`.
<ide> Returns {Error} object, populating it with `reason`, `host`, and `cert` on
<ide> failure. On success, returns {undefined}.
<ide>
<add>This function is intended to be used in combination with the
<add>`checkServerIdentity` option that can be passed to [`tls.connect()`][] and as
<add>such operates on a [certificate object][]. For other purposes, consider using
<add>[`x509.checkHost()`][] instead.
<add>
<ide> This function can be overwritten by providing an alternative function as the
<ide> `options.checkServerIdentity` option that is passed to `tls.connect()`. The
<ide> overwriting function can call `tls.checkServerIdentity()` of course, to augment
<ide> added: v11.4.0
<ide> [`tls.createServer()`]: #tlscreateserveroptions-secureconnectionlistener
<ide> [`tls.getCiphers()`]: #tlsgetciphers
<ide> [`tls.rootCertificates`]: #tlsrootcertificates
<add>[`x509.checkHost()`]: crypto.md#x509checkhostname-options
<ide> [asn1.js]: https://www.npmjs.com/package/asn1.js
<ide> [certificate object]: #certificate-object
<ide> [cipher list format]: https://www.openssl.org/docs/man1.1.1/man1/ciphers.html#CIPHER-LIST-FORMAT | 1 |
Python | Python | finalize context rcnn tf2 support | 8b6a462814f8495c544d41973017d67e13112c44 | <ide><path>research/object_detection/meta_architectures/context_rcnn_lib_tf2.py
<ide> def call(self, box_features, context_features, valid_context_size):
<ide> # box_features becomes [batch_size, max_num_proposals, channels].
<ide> box_features = tf.reduce_mean(box_features, [2, 3])
<ide>
<del> with tf.name_scope("AttentionBlock"):
<del> queries = project_features(
<del> box_features, self._bottleneck_dimension, self._is_training,
<del> self._query_proj, normalize=True)
<del> keys = project_features(
<del> context_features, self._bottleneck_dimension, self._is_training,
<del> self._key_proj, normalize=True)
<del> values = project_features(
<del> context_features, self._bottleneck_dimension, self._is_training,
<del> self._val_proj, normalize=True)
<add> queries = project_features(
<add> box_features, self._bottleneck_dimension, self._is_training,
<add> self._query_proj, normalize=True)
<add> keys = project_features(
<add> context_features, self._bottleneck_dimension, self._is_training,
<add> self._key_proj, normalize=True)
<add> values = project_features(
<add> context_features, self._bottleneck_dimension, self._is_training,
<add> self._val_proj, normalize=True)
<ide>
<ide> weights = tf.matmul(queries, keys, transpose_b=True)
<ide> weights, values = filter_weight_value(weights, values, valid_mask) | 1 |
Ruby | Ruby | rename the variable to make more sense with a tree | 86640e1ddca949913360247f473dc917484f6f9c | <ide><path>activerecord/lib/active_record/associations/join_dependency.rb
<ide> def self.walk_tree(associations, hash)
<ide> def initialize(base, associations, joins)
<ide> @base_klass = base
<ide> @table_joins = joins
<del> @join_parts = Node.new JoinBase.new(base)
<add> @join_root = Node.new JoinBase.new(base)
<ide> @alias_tracker = AliasTracker.new(base.connection, joins)
<ide> @alias_tracker.aliased_name_for(base.table_name) # Updates the count for base.table_name to 1
<ide> tree = self.class.make_tree associations
<del> build tree, @join_parts, Arel::InnerJoin
<add> build tree, @join_root, Arel::InnerJoin
<ide> end
<ide>
<ide> class Node # :nodoc:
<ide> def name
<ide> end
<ide>
<ide> def join_parts
<del> @join_parts.map(&:join_part)
<add> @join_root.map(&:join_part)
<ide> end
<ide>
<ide> def graft(*associations)
<ide> def graft(*associations)
<ide> associations.reject { |association|
<ide> join_assocs.detect { |a| association == a }
<ide> }.each { |association|
<del> join_node = find_parent_node(association.parent) || @join_parts
<add> join_node = find_parent_node(association.parent) || @join_root
<ide> type = association.join_type
<ide> find_or_build_scalar association.reflection, join_node, type
<ide> }
<ide> def instantiate(result_set)
<ide> parents = {}
<ide>
<ide> type_caster = result_set.column_type primary_key
<del> assoc = @join_parts.children
<add> assoc = @join_root.children
<ide>
<ide> records = result_set.map { |row_hash|
<ide> primary_id = type_caster.type_cast row_hash[primary_key]
<ide> def instantiate(result_set)
<ide> private
<ide>
<ide> def find_parent_node(parent)
<del> @join_parts.find { |node|
<add> @join_root.find { |node|
<ide> join_part = node.join_part
<ide> case parent
<ide> when JoinBase
<ide> def find_parent_node(parent)
<ide> end
<ide>
<ide> def join_base
<del> @join_parts.join_part
<add> @join_root.join_part
<ide> end
<ide>
<ide> def remove_duplicate_results!(base, records, associations) | 1 |
Python | Python | pass decay_mask fn to optimizer | d1500d9151ae1b728aa3561f035d96f139d0f5ca | <ide><path>examples/flax/language-modeling/run_mlm_flax.py
<ide> import jax
<ide> import jax.numpy as jnp
<ide> import optax
<del>from flax import jax_utils
<add>from flax import jax_utils, traverse_util
<ide> from flax.training import train_state
<ide> from flax.training.common_utils import get_metrics, onehot, shard
<ide> from transformers import (
<ide> def group_texts(examples):
<ide> schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
<ide> )
<ide>
<add> # We use Optax's "masking" functionality to not apply weight decay
<add> # to bias and LayerNorm scale parameters. decay_mask_fn returns a
<add> # mask boolean with the same structure as the parameters.
<add> # The mask is True for parameters that should be decayed.
<add> def decay_mask_fn(params):
<add> flat_params = traverse_util.flatten_dict(params)
<add> flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
<add> return traverse_util.unflatten_dict(flat_mask)
<add>
<ide> # create adam optimizer
<ide> adamw = optax.adamw(
<ide> learning_rate=linear_decay_lr_schedule_fn,
<ide> b1=training_args.adam_beta1,
<ide> b2=training_args.adam_beta2,
<ide> eps=1e-8,
<ide> weight_decay=training_args.weight_decay,
<add> mask=decay_mask_fn,
<ide> )
<ide>
<ide> # Setup train state | 1 |
Ruby | Ruby | simplify some rails info methods | 16c3ec7b2807f2f57d86399e6f62163a8962ec8b | <ide><path>railties/builtin/rails_info/rails/info.rb
<ide> module Info
<ide> mattr_accessor :properties
<ide> class << (@@properties = [])
<ide> def names
<del> map { |name, value| name }
<add> map &:first
<ide> end
<ide>
<ide> def value_for(property_name)
<del> if property = find { |name, value| name == property_name }
<add> if property = assoc(property_name)
<ide> property.last
<ide> end
<ide> end
<ide> def value_for(property_name)
<ide> class << self #:nodoc:
<ide> def property(name, value = nil)
<ide> value ||= yield
<del> properties << [name, value] if value
<add> properties << [name, value] if value
<ide> rescue Exception
<ide> end
<ide>
<ide> def components
<ide> %w( active_record action_pack active_resource action_mailer active_support )
<ide> end
<del>
<add>
<ide> def component_version(component)
<ide> require "#{component}/version"
<ide> "#{component.classify}::VERSION::STRING".constantize
<ide> end
<del>
<add>
<ide> def edge_rails_revision(info = svn_info)
<ide> info[/^Revision: (\d+)/, 1] || freeze_edge_version
<ide> end
<ide> def to_s
<ide> end
<ide>
<ide> alias inspect to_s
<del>
<add>
<ide> def to_html
<ide> returning table = '<table>' do
<ide> properties.each do |(name, value)|
<ide> def svn_info
<ide> property 'RubyGems version' do
<ide> Gem::RubyGemsVersion
<ide> end
<del>
<add>
<ide> # The Rails version.
<ide> property 'Rails version' do
<ide> Rails::VERSION::STRING
<ide> end
<del>
<del> # Versions of each Rails component (Active Record, Action Pack,
<add>
<add> # Versions of each Rails component (Active Record, Action Pack,
<ide> # Active Resource, Action Mailer, and Active Support).
<ide> components.each do |component|
<del> property "#{component.titlecase} version" do
<add> property "#{component.titlecase} version" do
<ide> component_version(component)
<ide> end
<ide> end
<del>
<add>
<ide> # The Rails SVN revision, if it's checked out into vendor/rails.
<ide> property 'Edge Rails revision' do
<ide> edge_rails_revision
<ide> end
<del>
<add>
<ide> # The application's location on the filesystem.
<ide> property 'Application root' do
<ide> File.expand_path(RAILS_ROOT)
<ide> def svn_info
<ide> property 'Environment' do
<ide> RAILS_ENV
<ide> end
<del>
<add>
<ide> # The name of the database adapter for the current environment.
<ide> property 'Database adapter' do
<ide> ActiveRecord::Base.configurations[RAILS_ENV]['adapter'] | 1 |
Ruby | Ruby | remove dead code | bb21d6ed7adc899435f32e297115fe98381e71d4 | <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> class NamedRouteCollection #:nodoc:
<ide> def initialize
<ide> @routes = {}
<ide> @helpers = []
<del> @module = Module.new do
<del> protected
<del>
<del> end
<add> @module = Module.new
<ide> end
<ide>
<ide> def helper_names | 1 |
Javascript | Javascript | refine the heuristics around beforeblur/afterblur | a152827ef697c55f89926f9b6b7aa436f1c0504e | <ide><path>packages/react-art/src/ReactARTHostConfig.js
<ide> export function getPublicInstance(instance) {
<ide>
<ide> export function prepareForCommit() {
<ide> // Noop
<add> return null;
<ide> }
<ide>
<ide> export function prepareUpdate(domElement, type, oldProps, newProps) {
<ide> export function unmountEventListener(listener: any) {
<ide> export function validateEventListenerTarget(target: any, listener: any) {
<ide> throw new Error('Not yet implemented.');
<ide> }
<add>
<add>export function beforeActiveInstanceBlur() {
<add> // noop
<add>}
<add>
<add>export function afterActiveInstanceBlur() {
<add> // noop
<add>}
<ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js
<ide> import {
<ide> import {getListenerMapForElement} from '../events/DOMEventListenerMap';
<ide> import {TOP_BEFORE_BLUR, TOP_AFTER_BLUR} from '../events/DOMTopLevelEventTypes';
<ide>
<del>// TODO: This is an exposed internal, we should move this around
<del>// so this isn't the case.
<del>import {isFiberInsideHiddenOrRemovedTree} from 'react-reconciler/src/ReactFiberTreeReflection';
<del>
<ide> export type ReactListenerEvent = ReactDOMListenerEvent;
<ide> export type ReactListenerMap = ReactDOMListenerMap;
<ide> export type ReactListener = ReactDOMListener;
<ide> export opaque type OpaqueIDType =
<ide> };
<ide>
<ide> type SelectionInformation = {|
<del> activeElementDetached: null | HTMLElement,
<ide> focusedElem: null | HTMLElement,
<ide> selectionRange: mixed,
<ide> |};
<ide> export function getPublicInstance(instance: Instance): * {
<ide> return instance;
<ide> }
<ide>
<del>export function prepareForCommit(containerInfo: Container): void {
<add>export function prepareForCommit(containerInfo: Container): Object | null {
<ide> eventsEnabled = ReactBrowserEventEmitterIsEnabled();
<ide> selectionInformation = getSelectionInformation();
<add> let activeInstance = null;
<ide> if (enableDeprecatedFlareAPI || enableUseEventAPI) {
<ide> const focusedElem = selectionInformation.focusedElem;
<ide> if (focusedElem !== null) {
<del> const instance = getClosestInstanceFromNode(focusedElem);
<del> if (instance !== null && isFiberInsideHiddenOrRemovedTree(instance)) {
<del> dispatchBeforeDetachedBlur(focusedElem);
<del> }
<add> activeInstance = getClosestInstanceFromNode(focusedElem);
<ide> }
<ide> }
<ide> ReactBrowserEventEmitterSetEnabled(false);
<add> return activeInstance;
<add>}
<add>
<add>export function beforeActiveInstanceBlur(): void {
<add> if (enableDeprecatedFlareAPI || enableUseEventAPI) {
<add> ReactBrowserEventEmitterSetEnabled(true);
<add> dispatchBeforeDetachedBlur((selectionInformation: any).focusedElem);
<add> ReactBrowserEventEmitterSetEnabled(false);
<add> }
<add>}
<add>
<add>export function afterActiveInstanceBlur(): void {
<add> if (enableDeprecatedFlareAPI || enableUseEventAPI) {
<add> ReactBrowserEventEmitterSetEnabled(true);
<add> dispatchAfterDetachedBlur((selectionInformation: any).focusedElem);
<add> ReactBrowserEventEmitterSetEnabled(false);
<add> }
<ide> }
<ide>
<ide> export function resetAfterCommit(containerInfo: Container): void {
<ide> restoreSelection(selectionInformation);
<ide> ReactBrowserEventEmitterSetEnabled(eventsEnabled);
<ide> eventsEnabled = null;
<del> if (enableDeprecatedFlareAPI || enableUseEventAPI) {
<del> const activeElementDetached = (selectionInformation: any)
<del> .activeElementDetached;
<del> if (activeElementDetached !== null) {
<del> dispatchAfterDetachedBlur(activeElementDetached);
<del> }
<del> }
<ide> selectionInformation = null;
<ide> }
<ide>
<ide> function createEvent(type: TopLevelType): Event {
<ide> }
<ide>
<ide> function dispatchBeforeDetachedBlur(target: HTMLElement): void {
<del> ((selectionInformation: any): SelectionInformation).activeElementDetached = target;
<del>
<ide> if (enableDeprecatedFlareAPI || enableUseEventAPI) {
<ide> const event = createEvent(TOP_BEFORE_BLUR);
<ide> // Dispatch "beforeblur" directly on the target,
<ide><path>packages/react-dom/src/client/ReactInputSelection.js
<ide> export function hasSelectionCapabilities(elem) {
<ide> export function getSelectionInformation() {
<ide> const focusedElem = getActiveElementDeep();
<ide> return {
<del> // Used by Flare
<del> activeElementDetached: null,
<ide> focusedElem: focusedElem,
<ide> selectionRange: hasSelectionCapabilities(focusedElem)
<ide> ? getSelection(focusedElem)
<ide><path>packages/react-interactions/events/src/dom/__tests__/FocusWithin-test.internal.js
<ide> let ReactFeatureFlags;
<ide> let ReactDOM;
<ide> let FocusWithinResponder;
<ide> let useFocusWithin;
<del>let Scheduler;
<add>let ReactTestRenderer;
<add>let act;
<ide>
<ide> const initializeModules = hasPointerEvents => {
<ide> setPointerEvent(hasPointerEvents);
<ide> const initializeModules = hasPointerEvents => {
<ide> ReactFeatureFlags.enableScopeAPI = true;
<ide> React = require('react');
<ide> ReactDOM = require('react-dom');
<del> Scheduler = require('scheduler');
<add> ReactTestRenderer = require('react-test-renderer');
<add> act = ReactTestRenderer.act;
<ide>
<ide> // TODO: This import throws outside of experimental mode. Figure out better
<ide> // strategy for gated imports.
<ide> const table = [[forcePointerEvents], [!forcePointerEvents]];
<ide>
<ide> describe.each(table)('FocusWithin responder', hasPointerEvents => {
<ide> let container;
<add> let container2;
<ide>
<ide> beforeEach(() => {
<ide> initializeModules();
<ide> container = document.createElement('div');
<ide> document.body.appendChild(container);
<add> container2 = document.createElement('div');
<add> document.body.appendChild(container2);
<ide> });
<ide>
<ide> afterEach(() => {
<ide> ReactDOM.render(null, container);
<ide> document.body.removeChild(container);
<add> document.body.removeChild(container2);
<ide> container = null;
<add> container2 = null;
<ide> });
<ide>
<ide> describe('disabled', () => {
<ide> describe.each(table)('FocusWithin responder', hasPointerEvents => {
<ide> );
<ide> });
<ide>
<add> // @gate experimental
<add> it('is called after many elements are unmounted', () => {
<add> const buttonRef = React.createRef();
<add> const inputRef = React.createRef();
<add>
<add> const Component = ({show}) => {
<add> const listener = useFocusWithin({
<add> onBeforeBlurWithin,
<add> onAfterBlurWithin,
<add> });
<add> return (
<add> <div ref={ref} DEPRECATED_flareListeners={listener}>
<add> {show && <button>Press me!</button>}
<add> {show && <button>Press me!</button>}
<add> {show && <input ref={inputRef} />}
<add> {show && <button>Press me!</button>}
<add> {!show && <button ref={buttonRef}>Press me!</button>}
<add> {show && <button>Press me!</button>}
<add> <button>Press me!</button>
<add> <button>Press me!</button>
<add> </div>
<add> );
<add> };
<add>
<add> ReactDOM.render(<Component show={true} />, container);
<add>
<add> inputRef.current.focus();
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
<add> ReactDOM.render(<Component show={false} />, container);
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
<add> });
<add>
<ide> // @gate experimental
<ide> it('is called after a nested focused element is unmounted (with scope query)', () => {
<ide> const TestScope = React.unstable_createScope();
<ide> describe.each(table)('FocusWithin responder', hasPointerEvents => {
<ide> );
<ide> };
<ide>
<del> const container2 = document.createElement('div');
<del> document.body.appendChild(container2);
<del>
<ide> const root = ReactDOM.createRoot(container2);
<del> root.render(<Component />);
<del> Scheduler.unstable_flushAll();
<add> act(() => {
<add> root.render(<Component />);
<add> });
<ide> jest.runAllTimers();
<ide> expect(container2.innerHTML).toBe('<div><input></div>');
<ide>
<ide> describe.each(table)('FocusWithin responder', hasPointerEvents => {
<ide> expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
<ide>
<ide> suspend = true;
<del> root.render(<Component />);
<del> Scheduler.unstable_flushAll();
<add> act(() => {
<add> root.render(<Component />);
<add> });
<ide> jest.runAllTimers();
<ide> expect(container2.innerHTML).toBe(
<ide> '<div><input style="display: none;">Loading...</div>',
<ide> );
<ide> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
<ide> expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
<ide> resolve();
<add> });
<add>
<add> // @gate experimental
<add> it('is called after a focused suspended element is hidden then shown', () => {
<add> const Suspense = React.Suspense;
<add> let suspend = false;
<add> let resolve;
<add> const promise = new Promise(resolvePromise => (resolve = resolvePromise));
<add> const buttonRef = React.createRef();
<add>
<add> function Child() {
<add> if (suspend) {
<add> throw promise;
<add> } else {
<add> return <input ref={innerRef} />;
<add> }
<add> }
<ide>
<del> document.body.removeChild(container2);
<add> const Component = ({show}) => {
<add> const listener = useFocusWithin({
<add> onBeforeBlurWithin,
<add> onAfterBlurWithin,
<add> });
<add>
<add> return (
<add> <div ref={ref} DEPRECATED_flareListeners={listener}>
<add> <Suspense fallback={<button ref={buttonRef}>Loading...</button>}>
<add> <Child />
<add> </Suspense>
<add> </div>
<add> );
<add> };
<add>
<add> const root = ReactDOM.createRoot(container2);
<add>
<add> act(() => {
<add> root.render(<Component />);
<add> });
<add> jest.runAllTimers();
<add>
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
<add>
<add> suspend = true;
<add> act(() => {
<add> root.render(<Component />);
<add> });
<add> jest.runAllTimers();
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
<add>
<add> act(() => {
<add> root.render(<Component />);
<add> });
<add> jest.runAllTimers();
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
<add>
<add> buttonRef.current.focus();
<add> suspend = false;
<add> act(() => {
<add> root.render(<Component />);
<add> });
<add> jest.runAllTimers();
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
<add>
<add> resolve();
<ide> });
<ide> });
<ide>
<ide><path>packages/react-interactions/events/src/dom/use-event/__tests__/useFocusWithin-test.internal.js
<ide> const table = [[forcePointerEvents], [!forcePointerEvents]];
<ide>
<ide> describe.each(table)(`useFocus`, hasPointerEvents => {
<ide> let container;
<add> let container2;
<ide>
<ide> beforeEach(() => {
<ide> initializeModules(hasPointerEvents);
<ide> container = document.createElement('div');
<ide> document.body.appendChild(container);
<add> container2 = document.createElement('div');
<add> document.body.appendChild(container2);
<ide> });
<ide>
<ide> afterEach(() => {
<ide> ReactDOM.render(null, container);
<ide> document.body.removeChild(container);
<add> document.body.removeChild(container2);
<ide> container = null;
<add> container2 = null;
<ide> });
<ide>
<ide> describe('disabled', () => {
<ide> describe.each(table)(`useFocus`, hasPointerEvents => {
<ide> );
<ide> });
<ide>
<add> // @gate experimental
<add> it('is called after many elements are unmounted', () => {
<add> const buttonRef = React.createRef();
<add> const inputRef = React.createRef();
<add>
<add> const Component = ({show}) => {
<add> useFocusWithin(ref, {
<add> onBeforeBlurWithin,
<add> onAfterBlurWithin,
<add> });
<add> return (
<add> <div ref={ref}>
<add> {show && <button>Press me!</button>}
<add> {show && <button>Press me!</button>}
<add> {show && <input ref={inputRef} />}
<add> {show && <button>Press me!</button>}
<add> {!show && <button ref={buttonRef}>Press me!</button>}
<add> {show && <button>Press me!</button>}
<add> <button>Press me!</button>
<add> <button>Press me!</button>
<add> </div>
<add> );
<add> };
<add>
<add> ReactDOM.render(<Component show={true} />, container);
<add>
<add> inputRef.current.focus();
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
<add> ReactDOM.render(<Component show={false} />, container);
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
<add> });
<add>
<ide> // @gate experimental
<ide> it('is called after a nested focused element is unmounted (with scope query)', () => {
<ide> const TestScope = React.unstable_createScope();
<ide> describe.each(table)(`useFocus`, hasPointerEvents => {
<ide> );
<ide> };
<ide>
<del> const container2 = document.createElement('div');
<del> document.body.appendChild(container2);
<del>
<ide> const root = ReactDOM.createRoot(container2);
<ide>
<ide> act(() => {
<ide> describe.each(table)(`useFocus`, hasPointerEvents => {
<ide> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
<ide> expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
<ide> resolve();
<add> });
<ide>
<del> document.body.removeChild(container2);
<add> // @gate experimental
<add> it('is called after a focused suspended element is hidden then shown', () => {
<add> const Suspense = React.Suspense;
<add> let suspend = false;
<add> let resolve;
<add> const promise = new Promise(resolvePromise => (resolve = resolvePromise));
<add> const buttonRef = React.createRef();
<add>
<add> function Child() {
<add> if (suspend) {
<add> throw promise;
<add> } else {
<add> return <input ref={innerRef} />;
<add> }
<add> }
<add>
<add> const Component = ({show}) => {
<add> useFocusWithin(ref, {
<add> onBeforeBlurWithin,
<add> onAfterBlurWithin,
<add> });
<add>
<add> return (
<add> <div ref={ref}>
<add> <Suspense fallback={<button ref={buttonRef}>Loading...</button>}>
<add> <Child />
<add> </Suspense>
<add> </div>
<add> );
<add> };
<add>
<add> const root = ReactDOM.createRoot(container2);
<add>
<add> act(() => {
<add> root.render(<Component />);
<add> });
<add> jest.runAllTimers();
<add>
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
<add>
<add> suspend = true;
<add> act(() => {
<add> root.render(<Component />);
<add> });
<add> jest.runAllTimers();
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
<add>
<add> act(() => {
<add> root.render(<Component />);
<add> });
<add> jest.runAllTimers();
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
<add>
<add> buttonRef.current.focus();
<add> suspend = false;
<add> act(() => {
<add> root.render(<Component />);
<add> });
<add> jest.runAllTimers();
<add> expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
<add> expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
<add>
<add> resolve();
<ide> });
<ide> });
<ide> });
<ide><path>packages/react-native-renderer/src/ReactFabricHostConfig.js
<ide> export function getPublicInstance(instance: Instance): * {
<ide> return instance.canonical;
<ide> }
<ide>
<del>export function prepareForCommit(containerInfo: Container): void {
<add>export function prepareForCommit(containerInfo: Container): null | Object {
<ide> // Noop
<add> return null;
<ide> }
<ide>
<ide> export function prepareUpdate(
<ide> export function unmountEventListener(listener: any) {
<ide> export function validateEventListenerTarget(target: any, listener: any) {
<ide> throw new Error('Not yet implemented.');
<ide> }
<add>
<add>export function beforeActiveInstanceBlur() {
<add> // noop
<add>}
<add>
<add>export function afterActiveInstanceBlur() {
<add> // noop
<add>}
<ide><path>packages/react-native-renderer/src/ReactNativeHostConfig.js
<ide> export function getPublicInstance(instance: Instance): * {
<ide> return instance;
<ide> }
<ide>
<del>export function prepareForCommit(containerInfo: Container): void {
<add>export function prepareForCommit(containerInfo: Container): null | Object {
<ide> // Noop
<add> return null;
<ide> }
<ide>
<ide> export function prepareUpdate(
<ide> export function unmountEventListener(listener: any) {
<ide> export function validateEventListenerTarget(target: any, listener: any) {
<ide> throw new Error('Not yet implemented.');
<ide> }
<add>
<add>export function beforeActiveInstanceBlur() {
<add> // noop
<add>}
<add>
<add>export function afterActiveInstanceBlur() {
<add> // noop
<add>}
<ide><path>packages/react-noop-renderer/src/createReactNoop.js
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> cancelTimeout: clearTimeout,
<ide> noTimeout: -1,
<ide>
<del> prepareForCommit(): void {},
<add> prepareForCommit(): null | Object {
<add> return null;
<add> },
<ide>
<ide> resetAfterCommit(): void {},
<ide>
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> beforeRemoveInstance(instance: any): void {
<ide> // NO-OP
<ide> },
<add>
<add> beforeActiveInstanceBlur() {
<add> // NO-OP
<add> },
<add>
<add> afterActiveInstanceBlur() {
<add> // NO-OP
<add> },
<ide> };
<ide>
<ide> const hostConfig = useMutation
<ide><path>packages/react-reconciler/src/ReactFiberTreeReflection.js
<ide> export function isFiberSuspenseAndTimedOut(fiber: Fiber): boolean {
<ide> );
<ide> }
<ide>
<del>// This is only safe to call in the commit phase when the return tree is consistent.
<del>// It should not be used anywhere else. See PR #18609 for details.
<del>export function isFiberInsideHiddenOrRemovedTree(fiber: Fiber): boolean {
<del> let node = fiber;
<del> let lastChild = null;
<add>function doesFiberContain(parentFiber: Fiber, childFiber: Fiber): boolean {
<add> let node = childFiber;
<add> const parentFiberAlternate = parentFiber.alternate;
<ide> while (node !== null) {
<del> if (
<del> node.effectTag & Deletion ||
<del> (isFiberSuspenseAndTimedOut(node) && node.child === lastChild)
<del> ) {
<add> if (node === parentFiber || node === parentFiberAlternate) {
<ide> return true;
<ide> }
<del> lastChild = node;
<ide> node = node.return;
<ide> }
<ide> return false;
<ide> }
<add>
<add>function isFiberTimedOutSuspenseThatContainsTargetFiber(
<add> fiber: Fiber,
<add> targetFiber: Fiber,
<add>): boolean {
<add> const child = fiber.child;
<add> return (
<add> isFiberSuspenseAndTimedOut(fiber) &&
<add> child !== null &&
<add> doesFiberContain(child, targetFiber)
<add> );
<add>}
<add>
<add>function isFiberDeletedAndContainsTargetFiber(
<add> fiber: Fiber,
<add> targetFiber: Fiber,
<add>): boolean {
<add> return (
<add> (fiber.effectTag & Deletion) !== 0 && doesFiberContain(fiber, targetFiber)
<add> );
<add>}
<add>
<add>export function isFiberHiddenOrDeletedAndContains(
<add> parentFiber: Fiber,
<add> childFiber: Fiber,
<add>): boolean {
<add> return (
<add> isFiberDeletedAndContainsTargetFiber(parentFiber, childFiber) ||
<add> isFiberTimedOutSuspenseThatContainsTargetFiber(parentFiber, childFiber)
<add> );
<add>}
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> cancelTimeout,
<ide> noTimeout,
<ide> warnsIfNotActing,
<add> beforeActiveInstanceBlur,
<add> afterActiveInstanceBlur,
<ide> } from './ReactFiberHostConfig';
<ide>
<ide> import {
<ide> import {onCommitRoot} from './ReactFiberDevToolsHook.new';
<ide>
<ide> // Used by `act`
<ide> import enqueueTask from 'shared/enqueueTask';
<add>import {isFiberHiddenOrDeletedAndContains} from './ReactFiberTreeReflection';
<ide>
<ide> const ceil = Math.ceil;
<ide>
<ide> let currentEventTime: ExpirationTime = NoWork;
<ide> // We warn about state updates for unmounted components differently in this case.
<ide> let isFlushingPassiveEffects = false;
<ide>
<add>let focusedInstanceHandle: null | Fiber = null;
<add>let shouldFireAfterActiveInstanceBlur: boolean = false;
<add>
<ide> export function getWorkInProgressRoot(): FiberRoot | null {
<ide> return workInProgressRoot;
<ide> }
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> // The first phase a "before mutation" phase. We use this phase to read the
<ide> // state of the host tree right before we mutate it. This is where
<ide> // getSnapshotBeforeUpdate is called.
<del> prepareForCommit(root.containerInfo);
<add> focusedInstanceHandle = prepareForCommit(root.containerInfo);
<add> shouldFireAfterActiveInstanceBlur = false;
<add>
<ide> nextEffect = firstEffect;
<ide> do {
<ide> if (__DEV__) {
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> }
<ide> } while (nextEffect !== null);
<ide>
<add> // We no longer need to track the active instance fiber
<add> focusedInstanceHandle = null;
<add>
<ide> if (enableProfilerTimer) {
<ide> // Mark the current commit time to be shared by all Profilers in this
<ide> // batch. This enables them to be grouped later.
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> }
<ide> }
<ide> } while (nextEffect !== null);
<add>
<add> if (shouldFireAfterActiveInstanceBlur) {
<add> afterActiveInstanceBlur();
<add> }
<ide> resetAfterCommit(root.containerInfo);
<ide>
<ide> // The work-in-progress tree is now the current tree. This must come after
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide>
<ide> function commitBeforeMutationEffects() {
<ide> while (nextEffect !== null) {
<add> if (
<add> !shouldFireAfterActiveInstanceBlur &&
<add> focusedInstanceHandle !== null &&
<add> isFiberHiddenOrDeletedAndContains(nextEffect, focusedInstanceHandle)
<add> ) {
<add> shouldFireAfterActiveInstanceBlur = true;
<add> beforeActiveInstanceBlur();
<add> }
<ide> const effectTag = nextEffect.effectTag;
<ide> if ((effectTag & Snapshot) !== NoEffect) {
<ide> setCurrentDebugFiberInDEV(nextEffect);
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> cancelTimeout,
<ide> noTimeout,
<ide> warnsIfNotActing,
<add> beforeActiveInstanceBlur,
<add> afterActiveInstanceBlur,
<ide> } from './ReactFiberHostConfig';
<ide>
<ide> import {
<ide> import {onCommitRoot} from './ReactFiberDevToolsHook.old';
<ide>
<ide> // Used by `act`
<ide> import enqueueTask from 'shared/enqueueTask';
<add>import {isFiberHiddenOrDeletedAndContains} from './ReactFiberTreeReflection';
<ide>
<ide> const ceil = Math.ceil;
<ide>
<ide> let currentEventTime: ExpirationTime = NoWork;
<ide> // We warn about state updates for unmounted components differently in this case.
<ide> let isFlushingPassiveEffects = false;
<ide>
<add>let focusedInstanceHandle: null | Fiber = null;
<add>let shouldFireAfterActiveInstanceBlur: boolean = false;
<add>
<ide> export function getWorkInProgressRoot(): FiberRoot | null {
<ide> return workInProgressRoot;
<ide> }
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> // The first phase a "before mutation" phase. We use this phase to read the
<ide> // state of the host tree right before we mutate it. This is where
<ide> // getSnapshotBeforeUpdate is called.
<del> prepareForCommit(root.containerInfo);
<add> focusedInstanceHandle = prepareForCommit(root.containerInfo);
<add> shouldFireAfterActiveInstanceBlur = false;
<add>
<ide> nextEffect = firstEffect;
<ide> do {
<ide> if (__DEV__) {
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> }
<ide> } while (nextEffect !== null);
<ide>
<add> // We no longer need to track the active instance fiber
<add> focusedInstanceHandle = null;
<add>
<ide> if (enableProfilerTimer) {
<ide> // Mark the current commit time to be shared by all Profilers in this
<ide> // batch. This enables them to be grouped later.
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> }
<ide> }
<ide> } while (nextEffect !== null);
<add>
<add> if (shouldFireAfterActiveInstanceBlur) {
<add> afterActiveInstanceBlur();
<add> }
<ide> resetAfterCommit(root.containerInfo);
<ide>
<ide> // The work-in-progress tree is now the current tree. This must come after
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide>
<ide> function commitBeforeMutationEffects() {
<ide> while (nextEffect !== null) {
<add> if (
<add> !shouldFireAfterActiveInstanceBlur &&
<add> focusedInstanceHandle !== null &&
<add> isFiberHiddenOrDeletedAndContains(nextEffect, focusedInstanceHandle)
<add> ) {
<add> shouldFireAfterActiveInstanceBlur = true;
<add> beforeActiveInstanceBlur();
<add> }
<ide> const effectTag = nextEffect.effectTag;
<ide> if ((effectTag & Snapshot) !== NoEffect) {
<ide> setCurrentDebugFiberInDEV(nextEffect);
<ide><path>packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.internal.js
<ide> describe('ReactFiberHostContext', () => {
<ide> it('works with null host context', () => {
<ide> let creates = 0;
<ide> const Renderer = ReactFiberReconciler({
<del> prepareForCommit: function() {},
<add> prepareForCommit: function() {
<add> return null;
<add> },
<ide> resetAfterCommit: function() {},
<ide> getRootHostContext: function() {
<ide> return null;
<ide> describe('ReactFiberHostContext', () => {
<ide> const Renderer = ReactFiberReconciler({
<ide> prepareForCommit: function(hostContext) {
<ide> expect(hostContext).toBe(rootContext);
<add> return null;
<ide> },
<ide> resetAfterCommit: function(hostContext) {
<ide> expect(hostContext).toBe(rootContext);
<ide><path>packages/react-reconciler/src/forks/ReactFiberHostConfig.custom.js
<ide> export const makeOpaqueHydratingObject =
<ide> export const makeClientId = $$$hostConfig.makeClientId;
<ide> export const makeClientIdInDEV = $$$hostConfig.makeClientIdInDEV;
<ide> export const makeServerId = $$$hostConfig.makeServerId;
<add>export const beforeActiveInstanceBlur = $$$hostConfig.beforeActiveInstanceBlur;
<add>export const afterActiveInstanceBlur = $$$hostConfig.afterActiveInstanceBlur;
<ide>
<ide> // -------------------
<ide> // Mutation
<ide><path>packages/react-test-renderer/src/ReactTestHostConfig.js
<ide> export function getChildHostContext(
<ide> return NO_CONTEXT;
<ide> }
<ide>
<del>export function prepareForCommit(containerInfo: Container): void {
<add>export function prepareForCommit(containerInfo: Container): null | Object {
<ide> // noop
<add> return null;
<ide> }
<ide>
<ide> export function resetAfterCommit(containerInfo: Container): void {
<ide> export function unmountEventListener(listener: any) {
<ide> export function validateEventListenerTarget(target: any, listener: any) {
<ide> throw new Error('Not yet implemented.');
<ide> }
<add>
<add>export function beforeActiveInstanceBlur() {
<add> // noop
<add>}
<add>
<add>export function afterActiveInstanceBlur() {
<add> // noop
<add>} | 14 |
Ruby | Ruby | extract controller checks to methods | ddda5e70f79288f03a873cc8b4dbc6c086f4ad82 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def default_controller_and_action
<ide> end
<ide> end
<ide>
<del> if controller.is_a?(String) && controller =~ %r{\A/}
<del> raise ArgumentError, "controller name should not start with a slash"
<del> end
<del>
<ide> controller = controller.to_s unless controller.is_a?(Regexp)
<ide> action = action.to_s unless action.is_a?(Regexp)
<ide>
<del> if controller.blank? && segment_keys.exclude?(:controller)
<del> message = "Missing :controller key on routes definition, please check your routes."
<del> raise ArgumentError, message
<del> end
<del>
<del> if action.blank? && segment_keys.exclude?(:action)
<del> message = "Missing :action key on routes definition, please check your routes."
<del> raise ArgumentError, message
<del> end
<del>
<del> if controller.is_a?(String) && controller !~ /\A[a-z_0-9\/]*\z/
<del> message = "'#{controller}' is not a supported controller name. This can lead to potential routing problems."
<del> message << " See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use"
<del> raise ArgumentError, message
<del> end
<add> check_action! action
<add> check_controller! controller
<ide>
<ide> hash = {}
<ide> hash[:controller] = controller unless controller.blank?
<ide> def default_controller_and_action
<ide> end
<ide> end
<ide>
<add> def check_action!(action)
<add> if action.blank? && segment_keys.exclude?(:action)
<add> message = "Missing :action key on routes definition, please check your routes."
<add> raise ArgumentError, message
<add> end
<add> end
<add>
<add> def check_controller!(controller)
<add> if controller.is_a?(String) && controller =~ %r{\A/}
<add> raise ArgumentError, "controller name should not start with a slash"
<add> end
<add>
<add> if controller.blank? && segment_keys.exclude?(:controller)
<add> message = "Missing :controller key on routes definition, please check your routes."
<add> raise ArgumentError, message
<add> end
<add>
<add> if controller.is_a?(String) && controller !~ /\A[a-z_0-9\/]*\z/
<add> message = "'#{controller}' is not a supported controller name. This can lead to potential routing problems."
<add> message << " See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use"
<add> raise ArgumentError, message
<add> end
<add> end
<add>
<ide> def blocks
<ide> if options[:constraints].present? && !options[:constraints].is_a?(Hash)
<ide> [options[:constraints]] | 1 |
Python | Python | use increasing batch sizes in ud-train | d7ce6527fbdfb52aa47a02c1fc2a7dd69faff932 | <ide><path>spacy/cli/ud_train.py
<ide> import spacy.util
<ide> from ..tokens import Token, Doc
<ide> from ..gold import GoldParse
<add>from ..util import compounding
<ide> from ..syntax.nonproj import projectivize
<ide> from ..matcher import Matcher
<ide> from collections import defaultdict, Counter
<ide> random.seed(0)
<ide> numpy.random.seed(0)
<ide>
<del>def minibatch_by_words(items, size=5000):
<add>def minibatch_by_words(items, size):
<ide> random.shuffle(items)
<ide> if isinstance(size, int):
<ide> size_ = itertools.repeat(size)
<ide> def main(ud_dir, parses_dir, config, corpus, limit=0):
<ide>
<ide> optimizer = initialize_pipeline(nlp, docs, golds, config)
<ide>
<add> batch_sizes = compounding(config.batch_size //10, config.batch_size, 1.001)
<ide> for i in range(config.nr_epoch):
<ide> docs = [nlp.make_doc(doc.text) for doc in docs]
<del> batches = minibatch_by_words(list(zip(docs, golds)), size=config.batch_size)
<add> batches = minibatch_by_words(list(zip(docs, golds)), size=batch_sizes)
<ide> losses = {}
<ide> n_train_words = sum(len(doc) for doc in docs)
<ide> with tqdm.tqdm(total=n_train_words, leave=False) as pbar: | 1 |
Python | Python | fix convert_tokens_to_string calls | 15d19ecfda5de8c4b50e2cd3129a16de281dbd6d | <ide><path>src/transformers/models/albert/tokenization_albert.py
<ide> def _convert_id_to_token(self, index):
<ide> return self.sp_model.IdToPiece(index)
<ide>
<ide> def convert_tokens_to_string(self, tokens):
<del> out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
<del> return out_string
<add> return self.sp_model.decode(tokens)
<ide>
<ide> def build_inputs_with_special_tokens(
<ide> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
<ide><path>src/transformers/models/barthez/tokenization_barthez.py
<ide> def __setstate__(self, d):
<ide>
<ide> def convert_tokens_to_string(self, tokens):
<ide> """Converts a sequence of tokens (strings for sub-words) in a single string."""
<del> out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
<del> return out_string
<add> return self.sp_model.decode(tokens)
<ide>
<ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
<ide> if not os.path.isdir(save_directory):
<ide><path>src/transformers/models/camembert/tokenization_camembert.py
<ide> def __setstate__(self, d):
<ide>
<ide> def convert_tokens_to_string(self, tokens):
<ide> """Converts a sequence of tokens (strings for sub-words) in a single string."""
<del> out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
<del> return out_string
<add> return self.sp_model.decode(tokens)
<ide>
<ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
<ide> if not os.path.isdir(save_directory):
<ide><path>src/transformers/models/m2m_100/tokenization_m2m_100.py
<ide> def _convert_id_to_token(self, index: int) -> str:
<ide>
<ide> def convert_tokens_to_string(self, tokens: List[str]) -> str:
<ide> """Converts a sequence of tokens (strings for sub-words) in a single string."""
<del> out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
<del> return out_string
<add> return self.sp_model.decode(tokens)
<ide>
<ide> def get_special_tokens_mask(
<ide> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
<ide><path>src/transformers/models/mbart/tokenization_mbart50.py
<ide> def _convert_id_to_token(self, index: int) -> str:
<ide>
<ide> def convert_tokens_to_string(self, tokens: List[str]) -> str:
<ide> """Converts a sequence of tokens (strings for sub-words) in a single string."""
<del> out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
<del> return out_string
<add> return self.sp_model.decode(tokens)
<ide>
<ide> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
<ide> if not os.path.isdir(save_directory):
<ide><path>src/transformers/models/speech_to_text/tokenization_speech_to_text.py
<ide> def _convert_id_to_token(self, index: int) -> str:
<ide>
<ide> def convert_tokens_to_string(self, tokens: List[str]) -> str:
<ide> """Converts a sequence of tokens (strings for sub-words) in a single string."""
<del> out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
<add> out_string = self.sp_model.decode(tokens)
<ide>
<ide> if self.do_upper_case:
<ide> out_string = out_string.upper() | 6 |
Text | Text | add metadata for vm code generation options | 54fbbb1037f92e7dc2ecd933e59586c3e6ab7796 | <ide><path>doc/api/vm.md
<ide> overhead.
<ide> ### script.runInNewContext([sandbox[, options]])
<ide> <!-- YAML
<ide> added: v0.3.1
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/19016
<add> description: The `contextCodeGeneration` option is supported now.
<ide> -->
<ide>
<ide> * `sandbox` {Object} An object that will be [contextified][]. If `undefined`, a
<ide> console.log(globalVar);
<ide> ## vm.createContext([sandbox[, options]])
<ide> <!-- YAML
<ide> added: v0.3.1
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/19016
<add> description: The `codeGeneration` option is supported now.
<ide> -->
<ide>
<ide> * `sandbox` {Object} | 1 |
Ruby | Ruby | use merge! instead reverse_merge! here | 2c0add7103e967a7de2df42675eb49e093327c58 | <ide><path>actionpack/lib/action_view/helpers/url_helper.rb
<ide> def url_for(options = nil)
<ide> options
<ide> when nil, Hash
<ide> options ||= {}
<del> options = options.symbolize_keys.reverse_merge!(:only_path => options[:host].nil?)
<add> options = { :only_path => options[:host].nil? }.merge!(options.symbolize_keys)
<ide> super
<ide> when :back
<ide> controller.request.env["HTTP_REFERER"] || 'javascript:history.back()' | 1 |
Text | Text | declare all parameter types | 40c85ff0634913f4c61e13cbb7cacb7e2c76120f | <ide><path>doc/api/console.md
<ide> console.profileEnd('MyLabel');
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> -->
<add>* `label` {string}
<ide>
<ide> This method does not display anything unless used in the inspector. Stops the
<ide> current JavaScript CPU profiling session if one has been started and prints
<ide><path>doc/api/crypto.md
<ide> data. The most common usage is handling output generated by the HTML5
<ide> <!-- YAML
<ide> added: v9.0.0
<ide> -->
<del>- `spkac` {string | Buffer | TypedArray | DataView}
<del>- Returns: {Buffer} The challenge component of the `spkac` data structure, which
<add>* `spkac` {string | Buffer | TypedArray | DataView}
<add>* Returns: {Buffer} The challenge component of the `spkac` data structure, which
<ide> includes a public key and a challenge.
<ide>
<ide> ```js
<ide> console.log(challenge.toString('utf8'));
<ide> <!-- YAML
<ide> added: v9.0.0
<ide> -->
<del>- `spkac` {string | Buffer | TypedArray | DataView}
<del>- `encoding` {string}
<del>- Returns: {Buffer} The public key component of the `spkac` data structure,
<add>* `spkac` {string | Buffer | TypedArray | DataView}
<add>* `encoding` {string}
<add>* Returns: {Buffer} The public key component of the `spkac` data structure,
<ide> which includes a public key and a challenge.
<ide>
<ide> ```js
<ide> console.log(publicKey);
<ide> <!-- YAML
<ide> added: v9.0.0
<ide> -->
<del>- `spkac` {Buffer | TypedArray | DataView}
<del>- Returns: {boolean} `true` if the given `spkac` data structure is valid,
<add>* `spkac` {Buffer | TypedArray | DataView}
<add>* Returns: {boolean} `true` if the given `spkac` data structure is valid,
<ide> `false` otherwise.
<ide>
<ide> ```js
<ide> const cert2 = crypto.Certificate();
<ide> <!-- YAML
<ide> added: v0.11.8
<ide> -->
<del>- `spkac` {string | Buffer | TypedArray | DataView}
<del>- Returns: {Buffer} The challenge component of the `spkac` data structure, which
<add>* `spkac` {string | Buffer | TypedArray | DataView}
<add>* Returns: {Buffer} The challenge component of the `spkac` data structure, which
<ide> includes a public key and a challenge.
<ide>
<ide> ```js
<ide> console.log(challenge.toString('utf8'));
<ide> <!-- YAML
<ide> added: v0.11.8
<ide> -->
<del>- `spkac` {string | Buffer | TypedArray | DataView}
<del>- Returns: {Buffer} The public key component of the `spkac` data structure,
<add>* `spkac` {string | Buffer | TypedArray | DataView}
<add>* Returns: {Buffer} The public key component of the `spkac` data structure,
<ide> which includes a public key and a challenge.
<ide>
<ide> ```js
<ide> console.log(publicKey);
<ide> <!-- YAML
<ide> added: v0.11.8
<ide> -->
<del>- `spkac` {Buffer | TypedArray | DataView}
<del>- Returns: {boolean} `true` if the given `spkac` data structure is valid,
<add>* `spkac` {Buffer | TypedArray | DataView}
<add>* Returns: {boolean} `true` if the given `spkac` data structure is valid,
<ide> `false` otherwise.
<ide>
<ide> ```js
<ide> console.log(encrypted);
<ide> <!-- YAML
<ide> added: v0.1.94
<ide> -->
<del>- `outputEncoding` {string}
<del>- Returns: {Buffer | string} Any remaining enciphered contents.
<add>* `outputEncoding` {string}
<add>* Returns: {Buffer | string} Any remaining enciphered contents.
<ide> If `outputEncoding` is one of `'latin1'`, `'base64'` or `'hex'`, a string is
<ide> returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.
<ide>
<ide> once will result in an error being thrown.
<ide> <!-- YAML
<ide> added: v1.0.0
<ide> -->
<del>- `buffer` {Buffer}
<del>- `options` {Object} [`stream.transform` options][]
<add>* `buffer` {Buffer}
<add>* `options` {Object} [`stream.transform` options][]
<ide> - `plaintextLength` {number}
<del>- Returns: {Cipher} for method chaining.
<add>* Returns: {Cipher} for method chaining.
<ide>
<ide> When using an authenticated encryption mode (only `GCM` and `CCM` are currently
<ide> supported), the `cipher.setAAD()` method sets the value used for the
<ide> The `cipher.setAAD()` method must be called before [`cipher.update()`][].
<ide> <!-- YAML
<ide> added: v1.0.0
<ide> -->
<del>- Returns: {Buffer} When using an authenticated encryption mode (only `GCM` and
<add>* Returns: {Buffer} When using an authenticated encryption mode (only `GCM` and
<ide> `CCM` are currently supported), the `cipher.getAuthTag()` method returns a
<ide> [`Buffer`][] containing the _authentication tag_ that has been computed from
<ide> the given data.
<ide> been completed using the [`cipher.final()`][] method.
<ide> <!-- YAML
<ide> added: v0.7.1
<ide> -->
<del>- `autoPadding` {boolean} **Default:** `true`
<del>- Returns: {Cipher} for method chaining.
<add>* `autoPadding` {boolean} **Default:** `true`
<add>* Returns: {Cipher} for method chaining.
<ide>
<ide> When using block encryption algorithms, the `Cipher` class will automatically
<ide> add padding to the input data to the appropriate block size. To disable the
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/5522
<ide> description: The default `inputEncoding` changed from `binary` to `utf8`.
<ide> -->
<del>- `data` {string | Buffer | TypedArray | DataView}
<del>- `inputEncoding` {string}
<del>- `outputEncoding` {string}
<del>- Returns: {Buffer | string}
<add>* `data` {string | Buffer | TypedArray | DataView}
<add>* `inputEncoding` {string}
<add>* `outputEncoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Updates the cipher with `data`. If the `inputEncoding` argument is given,
<ide> its value must be one of `'utf8'`, `'ascii'`, or `'latin1'` and the `data`
<ide> console.log(decrypted);
<ide> <!-- YAML
<ide> added: v0.1.94
<ide> -->
<del>- `outputEncoding` {string}
<del>- Returns: {Buffer | string} Any remaining deciphered contents.
<add>* `outputEncoding` {string}
<add>* Returns: {Buffer | string} Any remaining deciphered contents.
<ide> If `outputEncoding` is one of `'latin1'`, `'ascii'` or `'utf8'`, a string is
<ide> returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.
<ide>
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/9398
<ide> description: This method now returns a reference to `decipher`.
<ide> -->
<del>- `buffer` {Buffer | TypedArray | DataView}
<del>- `options` {Object} [`stream.transform` options][]
<add>* `buffer` {Buffer | TypedArray | DataView}
<add>* `options` {Object} [`stream.transform` options][]
<ide> - `plaintextLength` {number}
<del>- Returns: {Decipher} for method chaining.
<add>* Returns: {Decipher} for method chaining.
<ide>
<ide> When using an authenticated encryption mode (only `GCM` and `CCM` are currently
<ide> supported), the `decipher.setAAD()` method sets the value used for the
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/9398
<ide> description: This method now returns a reference to `decipher`.
<ide> -->
<del>- `buffer` {Buffer | TypedArray | DataView}
<del>- Returns: {Decipher} for method chaining.
<add>* `buffer` {Buffer | TypedArray | DataView}
<add>* Returns: {Decipher} for method chaining.
<ide>
<ide> When using an authenticated encryption mode (only `GCM` and `CCM` are currently
<ide> supported), the `decipher.setAuthTag()` method is used to pass in the
<ide> The `decipher.setAuthTag()` method must be called before
<ide> <!-- YAML
<ide> added: v0.7.1
<ide> -->
<del>- `autoPadding` {boolean} **Default:** `true`
<del>- Returns: {Decipher} for method chaining.
<add>* `autoPadding` {boolean} **Default:** `true`
<add>* Returns: {Decipher} for method chaining.
<ide>
<ide> When data has been encrypted without standard block padding, calling
<ide> `decipher.setAutoPadding(false)` will disable automatic padding to prevent
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/5522
<ide> description: The default `inputEncoding` changed from `binary` to `utf8`.
<ide> -->
<del>- `data` {string | Buffer | TypedArray | DataView}
<del>- `inputEncoding` {string}
<del>- `outputEncoding` {string}
<del>- Returns: {Buffer | string}
<add>* `data` {string | Buffer | TypedArray | DataView}
<add>* `inputEncoding` {string}
<add>* `outputEncoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Updates the decipher with `data`. If the `inputEncoding` argument is given,
<ide> its value must be one of `'latin1'`, `'base64'`, or `'hex'` and the `data`
<ide> assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<del>- `otherPublicKey` {string | Buffer | TypedArray | DataView}
<del>- `inputEncoding` {string}
<del>- `outputEncoding` {string}
<del>- Returns: {Buffer | string}
<add>* `otherPublicKey` {string | Buffer | TypedArray | DataView}
<add>* `inputEncoding` {string}
<add>* `outputEncoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Computes the shared secret using `otherPublicKey` as the other
<ide> party's public key and returns the computed shared secret. The supplied
<ide> If `outputEncoding` is given a string is returned; otherwise, a
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<del>- `encoding` {string}
<del>- Returns: {Buffer | string}
<add>* `encoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Generates private and public Diffie-Hellman key values, and returns
<ide> the public key in the specified `encoding`. This key should be
<ide> or `'base64'`. If `encoding` is provided a string is returned; otherwise a
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<del>- `encoding` {string}
<del>- Returns: {Buffer | string}
<add>* `encoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Returns the Diffie-Hellman generator in the specified `encoding`, which can
<ide> be `'latin1'`, `'hex'`, or `'base64'`. If `encoding` is provided a string is
<ide> returned; otherwise a [`Buffer`][] is returned.
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<del>- `encoding` {string}
<del>- Returns: {Buffer | string}
<add>* `encoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Returns the Diffie-Hellman prime in the specified `encoding`, which can
<ide> be `'latin1'`, `'hex'`, or `'base64'`. If `encoding` is provided a string is
<ide> returned; otherwise a [`Buffer`][] is returned.
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<del>- `encoding` {string}
<del>- Returns: {Buffer | string}
<add>* `encoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Returns the Diffie-Hellman private key in the specified `encoding`,
<ide> which can be `'latin1'`, `'hex'`, or `'base64'`. If `encoding` is provided a
<ide> string is returned; otherwise a [`Buffer`][] is returned.
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<del>- `encoding` {string}
<del>- Returns: {Buffer | string}
<add>* `encoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Returns the Diffie-Hellman public key in the specified `encoding`, which
<ide> can be `'latin1'`, `'hex'`, or `'base64'`. If `encoding` is provided a
<ide> string is returned; otherwise a [`Buffer`][] is returned.
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<del>- `privateKey` {string | Buffer | TypedArray | DataView}
<del>- `encoding` {string}
<add>* `privateKey` {string | Buffer | TypedArray | DataView}
<add>* `encoding` {string}
<ide>
<ide> Sets the Diffie-Hellman private key. If the `encoding` argument is provided
<ide> and is either `'latin1'`, `'hex'`, or `'base64'`, `privateKey` is expected
<ide> to be a [`Buffer`][], `TypedArray`, or `DataView`.
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<del>- `publicKey` {string | Buffer | TypedArray | DataView}
<del>- `encoding` {string}
<add>* `publicKey` {string | Buffer | TypedArray | DataView}
<add>* `encoding` {string}
<ide>
<ide> Sets the Diffie-Hellman public key. If the `encoding` argument is provided
<ide> and is either `'latin1'`, `'hex'` or `'base64'`, `publicKey` is expected
<ide> assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
<ide> added: v10.0.0
<ide> -->
<ide>
<del>- `key` {string | Buffer | TypedArray | DataView}
<del>- `curve` {string}
<del>- `inputEncoding` {string}
<del>- `outputEncoding` {string}
<del>- `format` {string} **Default:** `'uncompressed'`
<del>- Returns: {Buffer | string}
<add>* `key` {string | Buffer | TypedArray | DataView}
<add>* `curve` {string}
<add>* `inputEncoding` {string}
<add>* `outputEncoding` {string}
<add>* `format` {string} **Default:** `'uncompressed'`
<add>* Returns: {Buffer | string}
<ide>
<ide> Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the
<ide> format specified by `format`. The `format` argument specifies point encoding
<ide> changes:
<ide> description: Changed error format to better support invalid public key
<ide> error
<ide> -->
<del>- `otherPublicKey` {string | Buffer | TypedArray | DataView}
<del>- `inputEncoding` {string}
<del>- `outputEncoding` {string}
<del>- Returns: {Buffer | string}
<add>* `otherPublicKey` {string | Buffer | TypedArray | DataView}
<add>* `inputEncoding` {string}
<add>* `outputEncoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Computes the shared secret using `otherPublicKey` as the other
<ide> party's public key and returns the computed shared secret. The supplied
<ide> its recommended for developers to handle this exception accordingly.
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<del>- `encoding` {string}
<del>- `format` {string} **Default:** `'uncompressed'`
<del>- Returns: {Buffer | string}
<add>* `encoding` {string}
<add>* `format` {string} **Default:** `'uncompressed'`
<add>* Returns: {Buffer | string}
<ide>
<ide> Generates private and public EC Diffie-Hellman key values, and returns
<ide> the public key in the specified `format` and `encoding`. This key should be
<ide> is returned.
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<del>- `encoding` {string}
<del>- Returns: {Buffer | string} The EC Diffie-Hellman private key in the specified
<add>* `encoding` {string}
<add>* Returns: {Buffer | string} The EC Diffie-Hellman private key in the specified
<ide> `encoding`, which can be `'latin1'`, `'hex'`, or `'base64'`. If `encoding`
<ide> is provided a string is returned; otherwise a [`Buffer`][] is returned.
<ide>
<ide> ### ecdh.getPublicKey([encoding][, format])
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<del>- `encoding` {string}
<del>- `format` {string} **Default:** `'uncompressed'`
<del>- Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified
<add>* `encoding` {string}
<add>* `format` {string} **Default:** `'uncompressed'`
<add>* Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified
<ide> `encoding` and `format`.
<ide>
<ide> The `format` argument specifies point encoding and can be `'compressed'` or
<ide> returned.
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<del>- `privateKey` {string | Buffer | TypedArray | DataView}
<del>- `encoding` {string}
<add>* `privateKey` {string | Buffer | TypedArray | DataView}
<add>* `encoding` {string}
<ide>
<ide> Sets the EC Diffie-Hellman private key. The `encoding` can be `'latin1'`,
<ide> `'hex'` or `'base64'`. If `encoding` is provided, `privateKey` is expected
<ide> deprecated: v5.2.0
<ide>
<ide> > Stability: 0 - Deprecated
<ide>
<del>- `publicKey` {string | Buffer | TypedArray | DataView}
<del>- `encoding` {string}
<add>* `publicKey` {string | Buffer | TypedArray | DataView}
<add>* `encoding` {string}
<ide>
<ide> Sets the EC Diffie-Hellman public key. Key encoding can be `'latin1'`,
<ide> `'hex'` or `'base64'`. If `encoding` is provided `publicKey` is expected to
<ide> console.log(hash.digest('hex'));
<ide> <!-- YAML
<ide> added: v0.1.92
<ide> -->
<del>- `encoding` {string}
<del>- Returns: {Buffer | string}
<add>* `encoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Calculates the digest of all of the data passed to be hashed (using the
<ide> [`hash.update()`][] method). The `encoding` can be `'hex'`, `'latin1'` or
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/5522
<ide> description: The default `inputEncoding` changed from `binary` to `utf8`.
<ide> -->
<del>- `data` {string | Buffer | TypedArray | DataView}
<del>- `inputEncoding` {string}
<add>* `data` {string | Buffer | TypedArray | DataView}
<add>* `inputEncoding` {string}
<ide>
<ide> Updates the hash content with the given `data`, the encoding of which
<ide> is given in `inputEncoding` and can be `'utf8'`, `'ascii'` or
<ide> console.log(hmac.digest('hex'));
<ide> <!-- YAML
<ide> added: v0.1.94
<ide> -->
<del>- `encoding` {string}
<del>- Returns: {Buffer | string}
<add>* `encoding` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Calculates the HMAC digest of all of the data passed using [`hmac.update()`][].
<ide> The `encoding` can be `'hex'`, `'latin1'` or `'base64'`. If `encoding` is
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/5522
<ide> description: The default `inputEncoding` changed from `binary` to `utf8`.
<ide> -->
<del>- `data` {string | Buffer | TypedArray | DataView}
<del>- `inputEncoding` {string}
<add>* `data` {string | Buffer | TypedArray | DataView}
<add>* `inputEncoding` {string}
<ide>
<ide> Updates the `Hmac` content with the given `data`, the encoding of which
<ide> is given in `inputEncoding` and can be `'utf8'`, `'ascii'` or
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/11705
<ide> description: Support for RSASSA-PSS and additional options was added.
<ide> -->
<del>- `privateKey` {string | Object}
<add>* `privateKey` {string | Object}
<ide> - `key` {string}
<ide> - `passphrase` {string}
<del>- `outputFormat` {string}
<del>- Returns: {Buffer | string}
<add>* `outputFormat` {string}
<add>* Returns: {Buffer | string}
<ide>
<ide> Calculates the signature on all the data passed through using either
<ide> [`sign.update()`][] or [`sign.write()`][stream-writable-write].
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/5522
<ide> description: The default `inputEncoding` changed from `binary` to `utf8`.
<ide> -->
<del>- `data` {string | Buffer | TypedArray | DataView}
<del>- `inputEncoding` {string}
<add>* `data` {string | Buffer | TypedArray | DataView}
<add>* `inputEncoding` {string}
<ide>
<ide> Updates the `Sign` content with the given `data`, the encoding of which
<ide> is given in `inputEncoding` and can be `'utf8'`, `'ascii'` or
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/5522
<ide> description: The default `inputEncoding` changed from `binary` to `utf8`.
<ide> -->
<del>- `data` {string | Buffer | TypedArray | DataView}
<del>- `inputEncoding` {string}
<add>* `data` {string | Buffer | TypedArray | DataView}
<add>* `inputEncoding` {string}
<ide>
<ide> Updates the `Verify` content with the given `data`, the encoding of which
<ide> is given in `inputEncoding` and can be `'utf8'`, `'ascii'` or
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/11705
<ide> description: Support for RSASSA-PSS and additional options was added.
<ide> -->
<del>- `object` {string | Object}
<del>- `signature` {string | Buffer | TypedArray | DataView}
<del>- `signatureFormat` {string}
<del>- Returns: {boolean} `true` or `false` depending on the validity of the
<add>* `object` {string | Object}
<add>* `signature` {string | Buffer | TypedArray | DataView}
<add>* `signatureFormat` {string}
<add>* Returns: {boolean} `true` or `false` depending on the validity of the
<ide> signature for the data and public key.
<ide>
<ide> Verifies the provided data using the given `object` and `signature`.
<ide> thrown.
<ide> <!-- YAML
<ide> added: v6.3.0
<ide> -->
<del>- Returns: {Object} An object containing commonly used constants for crypto and
<add>* Returns: {Object} An object containing commonly used constants for crypto and
<ide> security related operations. The specific constants currently defined are
<ide> described in [Crypto Constants][].
<ide>
<ide> changes:
<ide>
<ide> > Stability: 0 - Deprecated: Use [`crypto.createCipheriv()`][] instead.
<ide>
<del>- `algorithm` {string}
<del>- `password` {string | Buffer | TypedArray | DataView}
<del>- `options` {Object} [`stream.transform` options][]
<del>- Returns: {Cipher}
<add>* `algorithm` {string}
<add>* `password` {string | Buffer | TypedArray | DataView}
<add>* `options` {Object} [`stream.transform` options][]
<add>* Returns: {Cipher}
<ide>
<ide> Creates and returns a `Cipher` object that uses the given `algorithm` and
<ide> `password`.
<ide> changes:
<ide> description: The `iv` parameter may now be `null` for ciphers which do not
<ide> need an initialization vector.
<ide> -->
<del>- `algorithm` {string}
<del>- `key` {string | Buffer | TypedArray | DataView}
<del>- `iv` {string | Buffer | TypedArray | DataView}
<del>- `options` {Object} [`stream.transform` options][]
<del>- Returns: {Cipher}
<add>* `algorithm` {string}
<add>* `key` {string | Buffer | TypedArray | DataView}
<add>* `iv` {string | Buffer | TypedArray | DataView}
<add>* `options` {Object} [`stream.transform` options][]
<add>* Returns: {Cipher}
<ide>
<ide> Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
<ide> initialization vector (`iv`).
<ide> deprecated: v10.0.0
<ide>
<ide> > Stability: 0 - Deprecated: Use [`crypto.createDecipheriv()`][] instead.
<ide>
<del>- `algorithm` {string}
<del>- `password` {string | Buffer | TypedArray | DataView}
<del>- `options` {Object} [`stream.transform` options][]
<del>- Returns: {Decipher}
<add>* `algorithm` {string}
<add>* `password` {string | Buffer | TypedArray | DataView}
<add>* `options` {Object} [`stream.transform` options][]
<add>* Returns: {Decipher}
<ide>
<ide> Creates and returns a `Decipher` object that uses the given `algorithm` and
<ide> `password` (key).
<ide> changes:
<ide> description: The `iv` parameter may now be `null` for ciphers which do not
<ide> need an initialization vector.
<ide> -->
<del>- `algorithm` {string}
<del>- `key` {string | Buffer | TypedArray | DataView}
<del>- `iv` {string | Buffer | TypedArray | DataView}
<del>- `options` {Object} [`stream.transform` options][]
<del>- Returns: {Decipher}
<add>* `algorithm` {string}
<add>* `key` {string | Buffer | TypedArray | DataView}
<add>* `iv` {string | Buffer | TypedArray | DataView}
<add>* `options` {Object} [`stream.transform` options][]
<add>* Returns: {Decipher}
<ide>
<ide> Creates and returns a `Decipher` object that uses the given `algorithm`, `key`
<ide> and initialization vector (`iv`).
<ide> changes:
<ide> description: The default for the encoding parameters changed
<ide> from `binary` to `utf8`.
<ide> -->
<del>- `prime` {string | Buffer | TypedArray | DataView}
<del>- `primeEncoding` {string}
<del>- `generator` {number | string | Buffer | TypedArray | DataView} **Default:**
<add>* `prime` {string | Buffer | TypedArray | DataView}
<add>* `primeEncoding` {string}
<add>* `generator` {number | string | Buffer | TypedArray | DataView} **Default:**
<ide> `2`
<del>- `generatorEncoding` {string}
<add>* `generatorEncoding` {string}
<ide>
<ide> Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
<ide> optional specific `generator`.
<ide> otherwise a number, [`Buffer`][], `TypedArray`, or `DataView` is expected.
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<del>- `primeLength` {number}
<del>- `generator` {number | string | Buffer | TypedArray | DataView} **Default:**
<add>* `primeLength` {number}
<add>* `generator` {number | string | Buffer | TypedArray | DataView} **Default:**
<ide> `2`
<ide>
<ide> Creates a `DiffieHellman` key exchange object and generates a prime of
<ide> If `generator` is not specified, the value `2` is used.
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<del>- `curveName` {string}
<add>* `curveName` {string}
<ide>
<ide> Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
<ide> predefined curve specified by the `curveName` string. Use
<ide> and description of each available elliptic curve.
<ide> <!-- YAML
<ide> added: v0.1.92
<ide> -->
<del>- `algorithm` {string}
<del>- `options` {Object} [`stream.transform` options][]
<del>- Returns: {Hash}
<add>* `algorithm` {string}
<add>* `options` {Object} [`stream.transform` options][]
<add>* Returns: {Hash}
<ide>
<ide> Creates and returns a `Hash` object that can be used to generate hash digests
<ide> using the given `algorithm`. Optional `options` argument controls stream
<ide> input.on('readable', () => {
<ide> <!-- YAML
<ide> added: v0.1.94
<ide> -->
<del>- `algorithm` {string}
<del>- `key` {string | Buffer | TypedArray | DataView}
<del>- `options` {Object} [`stream.transform` options][]
<del>- Returns: {Hmac}
<add>* `algorithm` {string}
<add>* `key` {string | Buffer | TypedArray | DataView}
<add>* `options` {Object} [`stream.transform` options][]
<add>* Returns: {Hmac}
<ide>
<ide> Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
<ide> Optional `options` argument controls stream behavior.
<ide> input.on('readable', () => {
<ide> <!-- YAML
<ide> added: v0.1.92
<ide> -->
<del>- `algorithm` {string}
<del>- `options` {Object} [`stream.Writable` options][]
<del>- Returns: {Sign}
<add>* `algorithm` {string}
<add>* `options` {Object} [`stream.Writable` options][]
<add>* Returns: {Sign}
<ide>
<ide> Creates and returns a `Sign` object that uses the given `algorithm`.
<ide> Use [`crypto.getHashes()`][] to obtain an array of names of the available
<ide> signing algorithms. Optional `options` argument controls the
<ide> <!-- YAML
<ide> added: v0.1.92
<ide> -->
<del>- `algorithm` {string}
<del>- `options` {Object} [`stream.Writable` options][]
<del>- Returns: {Verify}
<add>* `algorithm` {string}
<add>* `options` {Object} [`stream.Writable` options][]
<add>* Returns: {Verify}
<ide>
<ide> Creates and returns a `Verify` object that uses the given algorithm.
<ide> Use [`crypto.getHashes()`][] to obtain an array of names of the available
<ide> signing algorithms. Optional `options` argument controls the
<ide> <!-- YAML
<ide> added: v0.9.3
<ide> -->
<del>- Returns: {string[]} An array with the names of the supported cipher
<add>* Returns: {string[]} An array with the names of the supported cipher
<ide> algorithms.
<ide>
<ide> Example:
<ide> console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
<ide> <!-- YAML
<ide> added: v2.3.0
<ide> -->
<del>- Returns: {string[]} An array with the names of the supported elliptic curves.
<add>* Returns: {string[]} An array with the names of the supported elliptic curves.
<ide>
<ide> Example:
<ide>
<ide> console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
<ide> <!-- YAML
<ide> added: v0.7.5
<ide> -->
<del>- `groupName` {string}
<del>- Returns: {Object}
<add>* `groupName` {string}
<add>* Returns: {Object}
<ide>
<ide> Creates a predefined `DiffieHellman` key exchange object. The
<ide> supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in
<ide> console.log(aliceSecret === bobSecret);
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<del>- Returns: {boolean} `true` if and only if a FIPS compliant crypto provider is
<add>* Returns: {boolean} `true` if and only if a FIPS compliant crypto provider is
<ide> currently in use.
<ide>
<ide> ### crypto.getHashes()
<ide> <!-- YAML
<ide> added: v0.9.3
<ide> -->
<del>- Returns: {string[]} An array of the names of the supported hash algorithms,
<add>* Returns: {string[]} An array of the names of the supported hash algorithms,
<ide> such as `'RSA-SHA256'`.
<ide>
<ide> Example:
<ide> changes:
<ide> description: The default encoding for `password` if it is a string changed
<ide> from `binary` to `utf8`.
<ide> -->
<del>- `password` {string|Buffer|TypedArray|DataView}
<del>- `salt` {string|Buffer|TypedArray|DataView}
<del>- `iterations` {number}
<del>- `keylen` {number}
<del>- `digest` {string}
<del>- `callback` {Function}
<add>* `password` {string|Buffer|TypedArray|DataView}
<add>* `salt` {string|Buffer|TypedArray|DataView}
<add>* `iterations` {number}
<add>* `keylen` {number}
<add>* `digest` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `derivedKey` {Buffer}
<ide>
<ide> changes:
<ide> description: The default encoding for `password` if it is a string changed
<ide> from `binary` to `utf8`.
<ide> -->
<del>- `password` {string|Buffer|TypedArray|DataView}
<del>- `salt` {string|Buffer|TypedArray|DataView}
<del>- `iterations` {number}
<del>- `keylen` {number}
<del>- `digest` {string}
<del>- Returns: {Buffer}
<add>* `password` {string|Buffer|TypedArray|DataView}
<add>* `salt` {string|Buffer|TypedArray|DataView}
<add>* `iterations` {number}
<add>* `keylen` {number}
<add>* `digest` {string}
<add>* Returns: {Buffer}
<ide>
<ide> Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
<ide> implementation. A selected HMAC digest algorithm specified by `digest` is
<ide> An array of supported digest functions can be retrieved using
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<del>- `privateKey` {Object | string}
<add>* `privateKey` {Object | string}
<ide> - `key` {string} A PEM encoded private key.
<ide> - `passphrase` {string} An optional passphrase for the private key.
<ide> - `padding` {crypto.constants} An optional padding value defined in
<ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`,
<ide> `crypto.constants.RSA_PKCS1_PADDING`, or
<ide> `crypto.constants.RSA_PKCS1_OAEP_PADDING`.
<del>- `buffer` {Buffer | TypedArray | DataView}
<del>- Returns: {Buffer} A new `Buffer` with the decrypted content.
<add>* `buffer` {Buffer | TypedArray | DataView}
<add>* Returns: {Buffer} A new `Buffer` with the decrypted content.
<ide>
<ide> Decrypts `buffer` with `privateKey`.
<ide>
<ide> treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`.
<ide> <!-- YAML
<ide> added: v1.1.0
<ide> -->
<del>- `privateKey` {Object | string}
<add>* `privateKey` {Object | string}
<ide> - `key` {string} A PEM encoded private key.
<ide> - `passphrase` {string} An optional passphrase for the private key.
<ide> - `padding` {crypto.constants} An optional padding value defined in
<ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or
<ide> `crypto.constants.RSA_PKCS1_PADDING`.
<del>- `buffer` {Buffer | TypedArray | DataView}
<del>- Returns: {Buffer} A new `Buffer` with the encrypted content.
<add>* `buffer` {Buffer | TypedArray | DataView}
<add>* Returns: {Buffer} A new `Buffer` with the encrypted content.
<ide>
<ide> Encrypts `buffer` with `privateKey`.
<ide>
<ide> treated as the key with no passphrase and will use `RSA_PKCS1_PADDING`.
<ide> <!-- YAML
<ide> added: v1.1.0
<ide> -->
<del>- `key` {Object | string}
<add>* `key` {Object | string}
<ide> - `key` {string} A PEM encoded public or private key.
<ide> - `passphrase` {string} An optional passphrase for the private key.
<ide> - `padding` {crypto.constants} An optional padding value defined in
<ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or
<ide> `crypto.constants.RSA_PKCS1_PADDING`.
<del>- `buffer` {Buffer | TypedArray | DataView}
<del>- Returns: {Buffer} A new `Buffer` with the decrypted content.
<add>* `buffer` {Buffer | TypedArray | DataView}
<add>* Returns: {Buffer} A new `Buffer` with the decrypted content.
<ide>
<ide> Decrypts `buffer` with `key`.
<ide>
<ide> be passed instead of a public key.
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<del>- `key` {Object | string}
<add>* `key` {Object | string}
<ide> - `key` {string} A PEM encoded public or private key.
<ide> - `passphrase` {string} An optional passphrase for the private key.
<ide> - `padding` {crypto.constants} An optional padding value defined in
<ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`,
<ide> `crypto.constants.RSA_PKCS1_PADDING`, or
<ide> `crypto.constants.RSA_PKCS1_OAEP_PADDING`.
<del>- `buffer` {Buffer | TypedArray | DataView}
<del>- Returns: {Buffer} A new `Buffer` with the encrypted content.
<add>* `buffer` {Buffer | TypedArray | DataView}
<add>* Returns: {Buffer} A new `Buffer` with the encrypted content.
<ide>
<ide> Encrypts the content of `buffer` with `key` and returns a new
<ide> [`Buffer`][] with encrypted content.
<ide> changes:
<ide> description: Passing `null` as the `callback` argument now throws
<ide> `ERR_INVALID_CALLBACK`.
<ide> -->
<del>- `size` {number}
<del>- `callback` {Function}
<add>* `size` {number}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `buf` {Buffer}
<del>- Returns: {Buffer} if the `callback` function is not provided.
<add>* Returns: {Buffer} if the `callback` function is not provided.
<ide>
<ide> Generates cryptographically strong pseudo-random data. The `size` argument
<ide> is a number indicating the number of bytes to generate.
<ide> request.
<ide> <!-- YAML
<ide> added: v10.5.0
<ide> -->
<del>- `password` {string|Buffer|TypedArray|DataView}
<del>- `salt` {string|Buffer|TypedArray|DataView}
<del>- `keylen` {number}
<del>- `options` {Object}
<add>* `password` {string|Buffer|TypedArray|DataView}
<add>* `salt` {string|Buffer|TypedArray|DataView}
<add>* `keylen` {number}
<add>* `options` {Object}
<ide> - `N` {number} CPU/memory cost parameter. Must be a power of two greater
<ide> than one. **Default:** `16384`.
<ide> - `r` {number} Block size parameter. **Default:** `8`.
<ide> - `p` {number} Parallelization parameter. **Default:** `1`.
<ide> - `maxmem` {number} Memory upper bound. It is an error when (approximately)
<ide> `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.
<del>- `callback` {Function}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `derivedKey` {Buffer}
<ide>
<ide> crypto.scrypt('secret', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
<ide> <!-- YAML
<ide> added: v10.5.0
<ide> -->
<del>- `password` {string|Buffer|TypedArray|DataView}
<del>- `salt` {string|Buffer|TypedArray|DataView}
<del>- `keylen` {number}
<del>- `options` {Object}
<add>* `password` {string|Buffer|TypedArray|DataView}
<add>* `salt` {string|Buffer|TypedArray|DataView}
<add>* `keylen` {number}
<add>* `options` {Object}
<ide> - `N` {number} CPU/memory cost parameter. Must be a power of two greater
<ide> than one. **Default:** `16384`.
<ide> - `r` {number} Block size parameter. **Default:** `8`.
<ide> - `p` {number} Parallelization parameter. **Default:** `1`.
<ide> - `maxmem` {number} Memory upper bound. It is an error when (approximately)
<ide> `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.
<del>- Returns: {Buffer}
<add>* Returns: {Buffer}
<ide>
<ide> Provides a synchronous [scrypt][] implementation. Scrypt is a password-based
<ide> key derivation function that is designed to be expensive computationally and
<ide> console.log(key2.toString('hex')); // '3745e48...aa39b34'
<ide> <!-- YAML
<ide> added: v0.11.11
<ide> -->
<del>- `engine` {string}
<del>- `flags` {crypto.constants} **Default:** `crypto.constants.ENGINE_METHOD_ALL`
<add>* `engine` {string}
<add>* `flags` {crypto.constants} **Default:** `crypto.constants.ENGINE_METHOD_ALL`
<ide>
<ide> Load and set the `engine` for some or all OpenSSL functions (selected by flags).
<ide>
<ide> Throws an error if FIPS mode is not available.
<ide> <!-- YAML
<ide> added: v6.6.0
<ide> -->
<del>- `a` {Buffer | TypedArray | DataView}
<del>- `b` {Buffer | TypedArray | DataView}
<del>- Returns: {boolean}
<add>* `a` {Buffer | TypedArray | DataView}
<add>* `b` {Buffer | TypedArray | DataView}
<add>* Returns: {boolean}
<ide>
<ide> This function is based on a constant-time algorithm.
<ide> Returns true if `a` is equal to `b`, without leaking timing information that
<ide><path>doc/api/dgram.md
<ide> socket.bind({
<ide> <!-- YAML
<ide> added: v0.1.99
<ide> -->
<add>* `callback` {Function} Called when the socket has been closed.
<ide>
<ide> Close the underlying socket and stop listening for data on it. If a callback is
<ide> provided, it is added as a listener for the [`'close'`][] event.
<ide><path>doc/api/dns.md
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/744
<ide> description: The `all` option is supported now.
<ide> -->
<del>- `hostname` {string}
<del>- `options` {integer | Object}
<add>* `hostname` {string}
<add>* `options` {integer | Object}
<ide> - `family` {integer} The record family. Must be `4` or `6`. IPv4
<ide> and IPv6 addresses are both returned by default.
<ide> - `hints` {number} One or more [supported `getaddrinfo` flags][]. Multiple
<ide> changes:
<ide> **Default:** currently `false` (addresses are reordered) but this is
<ide> expected to change in the not too distant future.
<ide> New code should use `{ verbatim: true }`.
<del>- `callback` {Function}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `address` {string} A string representation of an IPv4 or IPv6 address.
<ide> - `family` {integer} `4` or `6`, denoting the family of `address`.
<ide> on some operating systems (e.g FreeBSD 10.1).
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<del>- `address` {string}
<del>- `port` {number}
<del>- `callback` {Function}
<add>* `address` {string}
<add>* `port` {number}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `hostname` {string} e.g. `example.com`
<ide> - `service` {string} e.g. `http`
<ide> If this method is invoked as its [`util.promisify()`][]ed version, it returns a
<ide> <!-- YAML
<ide> added: v0.1.27
<ide> -->
<del>- `hostname` {string} Hostname to resolve.
<del>- `rrtype` {string} Resource record type. **Default:** `'A'`.
<del>- `callback` {Function}
<add>* `hostname` {string} Hostname to resolve.
<add>* `rrtype` {string} Resource record type. **Default:** `'A'`.
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `records` {string[] | Object[] | Object}
<ide>
<ide> changes:
<ide> description: This method now supports passing `options`,
<ide> specifically `options.ttl`.
<ide> -->
<del>- `hostname` {string} Hostname to resolve.
<del>- `options` {Object}
<add>* `hostname` {string} Hostname to resolve.
<add>* `options` {Object}
<ide> - `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record.
<ide> When `true`, the callback receives an array of
<ide> `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings,
<ide> with the TTL expressed in seconds.
<del>- `callback` {Function}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `addresses` {string[] | Object[]}
<ide>
<ide> changes:
<ide> description: This method now supports passing `options`,
<ide> specifically `options.ttl`.
<ide> -->
<del>- `hostname` {string} Hostname to resolve.
<del>- `options` {Object}
<add>* `hostname` {string} Hostname to resolve.
<add>* `options` {Object}
<ide> - `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record.
<ide> When `true`, the callback receives an array of
<ide> `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of
<ide> strings, with the TTL expressed in seconds.
<del>- `callback` {Function}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `addresses` {string[] | Object[]}
<ide>
<ide> will contain an array of IPv6 addresses.
<ide>
<ide> ## dns.resolveAny(hostname, callback)
<ide>
<del>- `hostname` {string}
<del>- `callback` {Function}
<add>* `hostname` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `ret` {Object[]}
<ide>
<ide> Here is an example of the `ret` object passed to the callback:
<ide> <!-- YAML
<ide> added: v0.3.2
<ide> -->
<del>- `hostname` {string}
<del>- `callback` {Function}
<add>* `hostname` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `addresses` {string[]}
<ide>
<ide> will contain an array of canonical name records available for the `hostname`
<ide> <!-- YAML
<ide> added: v0.1.27
<ide> -->
<del>- `hostname` {string}
<del>- `callback` {Function}
<add>* `hostname` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `addresses` {Object[]}
<ide>
<ide> property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
<ide> <!-- YAML
<ide> added: v0.9.12
<ide> -->
<del>- `hostname` {string}
<del>- `callback` {Function}
<add>* `hostname` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `addresses` {Object[]}
<ide>
<ide> function will contain an array of objects with the following properties:
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<del>- `hostname` {string}
<del>- `callback` {Function}
<add>* `hostname` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `addresses` {string[]}
<ide>
<ide> contain an array of name server records available for `hostname`
<ide> <!-- YAML
<ide> added: v6.0.0
<ide> -->
<del>- `hostname` {string}
<del>- `callback` {Function}
<add>* `hostname` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `addresses` {string[]}
<ide>
<ide> be an array of strings containing the reply records.
<ide> <!-- YAML
<ide> added: v0.11.10
<ide> -->
<del>- `hostname` {string}
<del>- `callback` {Function}
<add>* `hostname` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `address` {Object}
<ide>
<ide> be an object with the following properties:
<ide> <!-- YAML
<ide> added: v0.1.27
<ide> -->
<del>- `hostname` {string}
<del>- `callback` {Function}
<add>* `hostname` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `addresses` {Object[]}
<ide>
<ide> be an array of objects with the following properties:
<ide> <!-- YAML
<ide> added: v0.1.27
<ide> -->
<del>- `hostname` {string}
<del>- `callback` {Function}
<add>* `hostname` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `records` {string[][]}
<ide>
<ide> treated separately.
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<del>- `ip` {string}
<del>- `callback` {Function}
<add>* `ip` {string}
<add>* `callback` {Function}
<ide> - `err` {Error}
<ide> - `hostnames` {string[]}
<ide>
<ide> one of the [DNS error codes][].
<ide> <!-- YAML
<ide> added: v0.11.3
<ide> -->
<del>- `servers` {string[]} array of [rfc5952][] formatted addresses
<add>* `servers` {string[]} array of [rfc5952][] formatted addresses
<ide>
<ide> Sets the IP address and port of servers to be used when performing DNS
<ide> resolution. The `servers` argument is an array of [rfc5952][] formatted
<ide> section if a custom port is used.
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<del>- `options` {integer | Object}
<add>* `hostname` {string}
<add>* `options` {integer | Object}
<ide> - `family` {integer} The record family. Must be `4` or `6`. IPv4
<ide> and IPv6 addresses are both returned by default.
<ide> - `hints` {number} One or more [supported `getaddrinfo` flags][]. Multiple
<ide> dnsPromises.lookup('example.com', options).then((result) => {
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `address` {string}
<del>- `port` {number}
<add>* `address` {string}
<add>* `port` {number}
<ide>
<ide> Resolves the given `address` and `port` into a hostname and service using
<ide> the operating system's underlying `getnameinfo` implementation.
<ide> dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string} Hostname to resolve.
<del>- `rrtype` {string} Resource record type. **Default:** `'A'`.
<add>* `hostname` {string} Hostname to resolve.
<add>* `rrtype` {string} Resource record type. **Default:** `'A'`.
<ide>
<ide> Uses the DNS protocol to resolve a hostname (e.g. `'nodejs.org'`) into an array
<ide> of the resource records. When successful, the `Promise` is resolved with an
<ide> is one of the [DNS error codes](#dns_error_codes).
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string} Hostname to resolve.
<del>- `options` {Object}
<add>* `hostname` {string} Hostname to resolve.
<add>* `options` {Object}
<ide> - `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record.
<ide> When `true`, the `Promise` is resolved with an array of
<ide> `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings,
<ide> addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string} Hostname to resolve.
<del>- `options` {Object}
<add>* `hostname` {string} Hostname to resolve.
<add>* `options` {Object}
<ide> - `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record.
<ide> When `true`, the `Promise` is resolved with an array of
<ide> `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of
<ide> addresses.
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<add>* `hostname` {string}
<ide>
<ide> Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
<ide> On success, the `Promise` is resolved with an array containing various types of
<ide> Here is an example of the result object:
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<add>* `hostname` {string}
<ide>
<ide> Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success,
<ide> the `Promise` is resolved with an array of canonical name records available for
<ide> the `hostname` (e.g. `['bar.example.com']`).
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<add>* `hostname` {string}
<ide>
<ide> Uses the DNS protocol to resolve mail exchange records (`MX` records) for the
<ide> `hostname`. On success, the `Promise` is resolved with an array of objects
<ide> containing both a `priority` and `exchange` property (e.g.
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<add>* `hostname` {string}
<ide>
<ide> Uses the DNS protocol to resolve regular expression based records (`NAPTR`
<ide> records) for the `hostname`. On success, the `Promise` is resolved with an array
<ide> of objects with the following properties:
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<add>* `hostname` {string}
<ide>
<ide> Uses the DNS protocol to resolve name server records (`NS` records) for the
<ide> `hostname`. On success, the `Promise` is resolved with an array of name server
<ide> records available for `hostname` (e.g.
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<add>* `hostname` {string}
<ide>
<ide> Uses the DNS protocol to resolve pointer records (`PTR` records) for the
<ide> `hostname`. On success, the `Promise` is resolved with an array of strings
<ide> containing the reply records.
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<add>* `hostname` {string}
<ide>
<ide> Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
<ide> the `hostname`. On success, the `Promise` is resolved with an object with the
<ide> following properties:
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<add>* `hostname` {string}
<ide>
<ide> Uses the DNS protocol to resolve service records (`SRV` records) for the
<ide> `hostname`. On success, the `Promise` is resolved with an array of objects with
<ide> the following properties:
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `hostname` {string}
<add>* `hostname` {string}
<ide>
<ide> Uses the DNS protocol to resolve text queries (`TXT` records) for the
<ide> `hostname`. On success, the `Promise` is resolved with a two-dimensional array
<ide> treated separately.
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `ip` {string}
<add>* `ip` {string}
<ide>
<ide> Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
<ide> array of hostnames.
<ide> is one of the [DNS error codes](#dns_error_codes).
<ide> <!-- YAML
<ide> added: v10.6.0
<ide> -->
<del>- `servers` {string[]} array of [rfc5952][] formatted addresses
<add>* `servers` {string[]} array of [rfc5952][] formatted addresses
<ide>
<ide> Sets the IP address and port of servers to be used when performing DNS
<ide> resolution. The `servers` argument is an array of [rfc5952][] formatted
<ide><path>doc/api/events.md
<ide> The `'removeListener'` event is emitted *after* the `listener` is removed.
<ide> added: v0.9.12
<ide> deprecated: v4.0.0
<ide> -->
<add>* `emitter` {EventEmitter} The emitter to query
<add>* `eventName` {string|symbol} The event name
<ide>
<ide> > Stability: 0 - Deprecated: Use [`emitter.listenerCount()`][] instead.
<ide>
<ide> Its `name` property is set to `'MaxListenersExceededWarning'`.
<ide> <!-- YAML
<ide> added: v0.1.26
<ide> -->
<del>- `eventName` {string|symbol}
<del>- `listener` {Function}
<add>* `eventName` {string|symbol}
<add>* `listener` {Function}
<ide>
<ide> Alias for `emitter.on(eventName, listener)`.
<ide>
<ide> ### emitter.emit(eventName[, ...args])
<ide> <!-- YAML
<ide> added: v0.1.26
<ide> -->
<del>- `eventName` {string|symbol}
<add>* `eventName` {string|symbol}
<ide> - `...args` {any}
<del>- Returns: {boolean}
<add>* Returns: {boolean}
<ide>
<ide> Synchronously calls each of the listeners registered for the event named
<ide> `eventName`, in the order they were registered, passing the supplied arguments
<ide> Returns `true` if the event had listeners, `false` otherwise.
<ide> added: v6.0.0
<ide> -->
<ide>
<del>- Returns: {Array}
<add>* Returns: {Array}
<ide>
<ide> Returns an array listing the events for which the emitter has registered
<ide> listeners. The values in the array will be strings or `Symbol`s.
<ide> console.log(myEE.eventNames());
<ide> added: v1.0.0
<ide> -->
<ide>
<del>- Returns: {integer}
<add>* Returns: {integer}
<ide>
<ide> Returns the current max listener value for the `EventEmitter` which is either
<ide> set by [`emitter.setMaxListeners(n)`][] or defaults to
<ide> changes:
<ide> description: For listeners attached using `.once()` this returns the
<ide> original listeners instead of wrapper functions now.
<ide> -->
<del>- `eventName` {string|symbol}
<del>- Returns: {Function[]}
<add>* `eventName` {string|symbol}
<add>* Returns: {Function[]}
<ide>
<ide> Returns a copy of the array of listeners for the event named `eventName`.
<ide>
<ide> Returns a reference to the `EventEmitter`, so that calls can be chained.
<ide> <!-- YAML
<ide> added: v0.1.26
<ide> -->
<del>- `eventName` {string|symbol}
<del>- Returns: {EventEmitter}
<add>* `eventName` {string|symbol}
<add>* Returns: {EventEmitter}
<ide>
<ide> Removes all listeners, or those of the specified `eventName`.
<ide>
<ide> Returns a reference to the `EventEmitter`, so that calls can be chained.
<ide> <!-- YAML
<ide> added: v0.1.26
<ide> -->
<del>- `eventName` {string|symbol}
<del>- `listener` {Function}
<del>- Returns: {EventEmitter}
<add>* `eventName` {string|symbol}
<add>* `listener` {Function}
<add>* Returns: {EventEmitter}
<ide>
<ide> Removes the specified `listener` from the listener array for the event named
<ide> `eventName`.
<ide> Returns a reference to the `EventEmitter`, so that calls can be chained.
<ide> <!-- YAML
<ide> added: v0.3.5
<ide> -->
<del>- `n` {integer}
<del>- Returns: {EventEmitter}
<add>* `n` {integer}
<add>* Returns: {EventEmitter}
<ide>
<ide> By default `EventEmitter`s will print a warning if more than `10` listeners are
<ide> added for a particular event. This is a useful default that helps finding
<ide> Returns a reference to the `EventEmitter`, so that calls can be chained.
<ide> <!-- YAML
<ide> added: v9.4.0
<ide> -->
<del>- `eventName` {string|symbol}
<del>- Returns: {Function[]}
<add>* `eventName` {string|symbol}
<add>* Returns: {Function[]}
<ide>
<ide> Returns a copy of the array of listeners for the event named `eventName`,
<ide> including any wrappers (such as those created by `.once()`).
<ide><path>doc/api/http.md
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/15752
<ide> description: The `options` argument is supported now.
<ide> -->
<del>- `options` {Object}
<add>* `options` {Object}
<ide> * `IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage`
<ide> class to be used. Useful for extending the original `IncomingMessage`.
<ide> **Default:** `IncomingMessage`.
<ide> * `ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class
<ide> to be used. Useful for extending the original `ServerResponse`. **Default:**
<ide> `ServerResponse`.
<del>- `requestListener` {Function}
<add>* `requestListener` {Function}
<ide>
<ide> * Returns: {http.Server}
<ide>
<ide><path>doc/api/http2.md
<ide> a given number of milliseconds set using `http2server.setTimeout()`.
<ide> <!-- YAML
<ide> added: v8.4.0
<ide> -->
<del>- `callback` {Function}
<add>* `callback` {Function}
<ide>
<ide> Stops the server from accepting new connections. See [`net.Server.close()`][].
<ide>
<ide> the connection is terminated. See the [Compatibility API][].
<ide> <!-- YAML
<ide> added: v8.4.0
<ide> -->
<del>- `callback` {Function}
<add>* `callback` {Function}
<ide>
<ide> Stops the server from accepting new connections. See [`tls.Server.close()`][].
<ide>
<ide> will result in a [`TypeError`][] being thrown.
<ide> <!-- YAML
<ide> added: v8.4.0
<ide> -->
<add>* `headers` {HTTP/2 Headers Object} An object describing the headers
<add>* `callback` {Function}
<ide>
<ide> Call [`http2stream.pushStream()`][] with the given headers, and wraps the
<ide> given newly created [`Http2Stream`] on `Http2ServerResponse`.
<ide><path>doc/api/https.md
<ide> This class is a subclass of `tls.Server` and emits events same as
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<del>- `callback` {Function}
<add>* `callback` {Function}
<ide>
<ide> See [`server.close()`][`http.close()`] from the HTTP module for details.
<ide>
<ide> See [`http.Server#maxHeadersCount`][].
<ide> <!-- YAML
<ide> added: v0.11.2
<ide> -->
<del>- `msecs` {number} **Default:** `120000` (2 minutes)
<del>- `callback` {Function}
<add>* `msecs` {number} **Default:** `120000` (2 minutes)
<add>* `callback` {Function}
<ide>
<ide> See [`http.Server#setTimeout()`][].
<ide>
<ide> See [`http.Server#keepAliveTimeout`][].
<ide> <!-- YAML
<ide> added: v0.3.4
<ide> -->
<del>- `options` {Object} Accepts `options` from [`tls.createServer()`][],
<add>* `options` {Object} Accepts `options` from [`tls.createServer()`][],
<ide> [`tls.createSecureContext()`][] and [`http.createServer()`][].
<del>- `requestListener` {Function} A listener to be added to the `'request'` event.
<add>* `requestListener` {Function} A listener to be added to the `'request'` event.
<ide>
<ide> Example:
<ide>
<ide> changes:
<ide> description: The `options` parameter can be a WHATWG `URL` object.
<ide> -->
<ide> - `url` {string | URL}
<del>- `options` {Object} Accepts the same `options` as
<add>* `options` {Object | string | URL} Accepts the same `options` as
<ide> [`https.request()`][], with the `method` always set to `GET`.
<del>- `callback` {Function}
<add>* `callback` {Function}
<ide>
<ide> Like [`http.get()`][] but for HTTPS.
<ide>
<ide> changes:
<ide> description: The `options` parameter can be a WHATWG `URL` object.
<ide> -->
<ide> - `url` {string | URL}
<del>- `options` {Object} Accepts all `options` from
<add>* `options` {Object | string | URL} Accepts all `options` from
<ide> [`http.request()`][], with some differences in default values:
<ide> - `protocol` **Default:** `'https:'`
<ide> - `port` **Default:** `443`
<ide> - `agent` **Default:** `https.globalAgent`
<del>- `callback` {Function}
<add>* `callback` {Function}
<ide>
<ide> Makes a request to a secure web server.
<ide>
<ide><path>doc/api/net.md
<ide> This class is used to create a TCP or [IPC][] server.
<ide>
<ide> ### new net.Server([options][, connectionListener])
<ide>
<add>* `options` {Object} See
<add> [`net.createServer([options][, connectionListener])`][`net.createServer()`].
<add>* `connectionListener` {Function} Automatically set as a listener for the
<add> [`'connection'`][] event.
<ide> * Returns: {net.Server}
<ide>
<del>See [`net.createServer([options][, connectionListener])`][`net.createServer()`].
<del>
<ide> `net.Server` is an [`EventEmitter`][] with the following events:
<ide>
<ide> ### Event: 'close'
<ide> Don't call `server.address()` until the `'listening'` event has been emitted.
<ide> added: v0.1.90
<ide> -->
<ide>
<add>* `callback` {Function} Called when the server is closed
<ide> * Returns: {net.Server}
<ide>
<ide> Stops the server from accepting new connections and keeps existing
<ide> connections use asynchronous [`server.getConnections()`][] instead.
<ide> added: v0.9.7
<ide> -->
<ide>
<add>* `callback` {Function}
<ide> * Returns: {net.Server}
<ide>
<ide> Asynchronously get the number of concurrent connections on the server. Works
<ide> it to interact with the client.
<ide> added: v0.3.4
<ide> -->
<ide>
<del>Creates a new socket object.
<del>
<ide> * `options` {Object} Available options are:
<ide> * `fd` {number} If specified, wrap around an existing socket with
<ide> the given file descriptor, otherwise a new socket will be created.
<ide> Creates a new socket object.
<ide> otherwise ignored. **Default:** `false`.
<ide> * Returns: {net.Socket}
<ide>
<add>Creates a new socket object.
<add>
<ide> The newly created socket can be either a TCP socket or a streaming [IPC][]
<ide> endpoint, depending on what it [`connect()`][`socket.connect()`] to.
<ide>
<ide> callback.
<ide> added: v0.1.90
<ide> -->
<ide>
<add>* `exception` {Object}
<ide> * Returns: {net.Socket}
<ide>
<ide> Ensures that no more I/O activity happens on this socket. Only necessary in
<ide> listeners for that event will receive `exception` as an argument.
<ide> added: v0.1.90
<ide> -->
<ide>
<add>* `data` {string|Buffer|Uint8Array}
<add>* `encoding` {string} Only used when data is `string`. **Default:** `'utf8'`.
<ide> * Returns: {net.Socket} The socket itself.
<ide>
<ide> Half-closes the socket. i.e., it sends a FIN packet. It is possible the
<ide> Resumes reading after a call to [`socket.pause()`][].
<ide> added: v0.1.90
<ide> -->
<ide>
<add>* `encoding` {string}
<ide> * Returns: {net.Socket} The socket itself.
<ide>
<ide> Set the encoding for the socket as a [Readable Stream][]. See
<ide> algorithm, they buffer data before sending it off. Setting `true` for
<ide> added: v0.1.90
<ide> -->
<ide>
<add>* `timeout` {number}
<add>* `callback` {Function}
<ide> * Returns: {net.Socket} The socket itself.
<ide>
<ide> Sets the socket to timeout after `timeout` milliseconds of inactivity on
<ide> Possible signatures:
<ide> <!-- YAML
<ide> added: v0.7.0
<ide> -->
<add>* `options` {Object}
<add>* `connectListener` {Function}
<ide> Alias to
<ide> [`net.createConnection(options[, connectListener])`][`net.createConnection(options)`].
<ide>
<ide> ### net.connect(path[, connectListener])
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<add>* `path` {string}
<add>* `connectListener` {Function}
<ide>
<ide> Alias to
<ide> [`net.createConnection(path[, connectListener])`][`net.createConnection(path)`].
<ide> Alias to
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<add>* `port` {number}
<add>* `host` {string}
<add>* `connectListener` {Function}
<ide>
<ide> Alias to
<ide> [`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`].
<ide> then returns the `net.Socket` that starts the connection.
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<add>* `options` {Object}
<add>* `connectionListener` {Function}
<ide>
<ide> Creates a new TCP or [IPC][] server.
<ide>
<ide> $ nc -U /tmp/echo.sock
<ide> added: v0.3.0
<ide> -->
<ide>
<add>* `input` {string}
<ide> * Returns: {integer}
<ide>
<ide> Tests if input is an IP address. Returns `0` for invalid strings,
<ide> addresses.
<ide> added: v0.3.0
<ide> -->
<ide>
<add>* `input` {string}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if input is a version 4 IP address, otherwise returns `false`.
<ide> Returns `true` if input is a version 4 IP address, otherwise returns `false`.
<ide> added: v0.3.0
<ide> -->
<ide>
<add>* `input` {string}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if input is a version 6 IP address, otherwise returns `false`.
<ide><path>doc/api/process.md
<ide> This feature is not available in [`Worker`][] threads.
<ide> <!-- YAML
<ide> added: v0.1.28
<ide> -->
<add>* `id` {integer | string}
<ide>
<ide> The `process.setuid(id)` method sets the user identity of the process. (See
<ide> setuid(2).) The `id` can be passed as either a numeric ID or a username string.
<ide><path>doc/api/stream.md
<ide> See also: [`writable.uncork()`][].
<ide> added: v8.0.0
<ide> -->
<ide>
<add>* `error` {Error}
<ide> * Returns: {this}
<ide>
<ide> Destroy the stream, and emit the passed `'error'` and a `'close'` event.
<ide> Examples of `Transform` streams include:
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> -->
<add>* `error` {Error}
<ide>
<ide> Destroy the stream, and emit `'error'`. After this call, the
<ide> transform stream would release any internal resources.
<ide><path>doc/api/tty.md
<ide> A `boolean` that is always `true` for `tty.ReadStream` instances.
<ide> added: v0.7.7
<ide> -->
<ide>
<add>* `mode` {boolean} If `true`, configures the `tty.ReadStream` to operate as a
<add> raw device. If `false`, configures the `tty.ReadStream` to operate in its
<add> default mode. The `readStream.isRaw` property will be set to the resulting
<add> mode.
<add>
<ide> Allows configuration of `tty.ReadStream` so that it operates as a raw device.
<ide>
<ide> When in raw mode, input is always available character-by-character, not
<ide> including modifiers. Additionally, all special processing of characters by the
<ide> terminal is disabled, including echoing input characters.
<ide> Note that `CTRL`+`C` will no longer cause a `SIGINT` when in this mode.
<ide>
<del>* `mode` {boolean} If `true`, configures the `tty.ReadStream` to operate as a
<del> raw device. If `false`, configures the `tty.ReadStream` to operate in its
<del> default mode. The `readStream.isRaw` property will be set to the resulting
<del> mode.
<del>
<ide> ## Class: tty.WriteStream
<ide> <!-- YAML
<ide> added: v0.5.8
<ide><path>doc/api/util.md
<ide> changes:
<ide> description: The `constructor` parameter can refer to an ES6 class now.
<ide> -->
<ide>
<add>* `constructor` {Function}
<add>* `superConstructor` {Function}
<add>
<ide> Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and
<ide> `extends` keywords to get language level inheritance support. Also note
<ide> that the two styles are [semantically incompatible][].
<ide>
<del>* `constructor` {Function}
<del>* `superConstructor` {Function}
<del>
<ide> Inherit the prototype methods from one [constructor][] into another. The
<ide> prototype of `constructor` will be set to a new object created from
<ide> `superConstructor`.
<ide> useful for addon developers who prefer to do type checking in JavaScript.
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`ArrayBuffer`][] or
<ide> util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is an `arguments` object.
<ide> function foo() {
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`ArrayBuffer`][] instance.
<ide> util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is an [async function][].
<ide> util.types.isAsyncFunction(async function foo() {}); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a `BigInt64Array` instance. The
<ide> util.types.isBigInt64Array(new BigUint64Array()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a `BigUint64Array` instance. The
<ide> util.types.isBigUint64Array(new BigUint64Array()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a boolean object, e.g. created
<ide> util.types.isBooleanObject(Boolean(true)); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`DataView`][] instance.
<ide> See also [`ArrayBuffer.isView()`][].
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Date`][] instance.
<ide> util.types.isDate(new Date()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a native `External` value.
<ide> Returns `true` if the value is a native `External` value.
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Float32Array`][] instance.
<ide> util.types.isFloat32Array(new Float64Array()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Float64Array`][] instance.
<ide> util.types.isFloat64Array(new Float64Array()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a generator function.
<ide> util.types.isGeneratorFunction(function* foo() {}); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a generator object as returned from a
<ide> util.types.isGeneratorObject(generator); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Int8Array`][] instance.
<ide> util.types.isInt8Array(new Float64Array()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Int16Array`][] instance.
<ide> util.types.isInt16Array(new Float64Array()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Int32Array`][] instance.
<ide> util.types.isInt32Array(new Float64Array()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Map`][] instance.
<ide> util.types.isMap(new Map()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is an iterator returned for a built-in
<ide> util.types.isMapIterator(map[Symbol.iterator]()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is an instance of a [Module Namespace Object][].
<ide> util.types.isModuleNamespaceObject(ns); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is an instance of a built-in [`Error`][] type.
<ide> util.types.isNativeError(new RangeError()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a number object, e.g. created
<ide> util.types.isNumberObject(new Number(0)); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Promise`][].
<ide> util.types.isPromise(Promise.resolve(42)); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a [`Proxy`][] instance.
<ide> util.types.isProxy(proxy); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a regular expression object.
<ide> util.types.isRegExp(new RegExp('abc')); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Set`][] instance.
<ide> util.types.isSet(new Set()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is an iterator returned for a built-in
<ide> util.types.isSetIterator(set[Symbol.iterator]()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`SharedArrayBuffer`][] instance.
<ide> util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a string object, e.g. created
<ide> util.types.isStringObject(new String('foo')); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a symbol object, created
<ide> util.types.isSymbolObject(Object(symbol)); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`TypedArray`][] instance.
<ide> See also [`ArrayBuffer.isView()`][].
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Uint8Array`][] instance.
<ide> util.types.isUint8Array(new Float64Array()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Uint8ClampedArray`][] instance.
<ide> util.types.isUint8ClampedArray(new Float64Array()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Uint16Array`][] instance.
<ide> util.types.isUint16Array(new Float64Array()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`Uint32Array`][] instance.
<ide> util.types.isUint32Array(new Float64Array()); // Returns false
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`WeakMap`][] instance.
<ide> util.types.isWeakMap(new WeakMap()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`WeakSet`][] instance.
<ide> util.types.isWeakSet(new WeakSet()); // Returns true
<ide> added: v10.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the value is a built-in [`WebAssembly.Module`][] instance.
<ide> applications and modules should be updated to find alternative approaches.
<ide> added: v0.7.5
<ide> deprecated: v6.0.0
<ide> -->
<add>* `target` {Object}
<add>* `source` {Object}
<ide>
<ide> > Stability: 0 - Deprecated: Use [`Object.assign()`] instead.
<ide>
<ide><path>doc/api/v8.md
<ide> changes to the API or wire format) may occur until this warning is removed.
<ide> added: v8.0.0
<ide> -->
<ide>
<add>* `value` {any}
<ide> * Returns: {Buffer}
<ide>
<ide> Uses a [`DefaultSerializer`][] to serialize `value` into a buffer.
<ide> Writes out a header, which includes the serialization format version.
<ide>
<ide> #### serializer.writeValue(value)
<ide>
<add>* `value` {any}
<add>
<ide> Serializes a JavaScript value and adds the serialized representation to the
<ide> internal buffer.
<ide>
<ide> For use inside of a custom [`deserializer._readHostObject()`][].
<ide>
<ide> #### deserializer.readRawBytes(length)
<ide>
<add>* `length` {integer}
<ide> * Returns: {Buffer}
<ide>
<ide> Read raw bytes from the deserializer’s internal buffer. The `length` parameter
<ide><path>doc/api/zlib.md
<ide> as appropriate for the derived class).
<ide> added: v0.9.4
<ide> -->
<ide>
<add>* `callback` {Function}
<add>
<ide> Close the underlying handle.
<ide>
<ide> ### zlib.flush([kind], callback)
<ide> added: v0.5.8
<ide> -->
<ide>
<ide> * `kind` **Default:** `zlib.constants.Z_FULL_FLUSH`
<add>* `callback` {Function}
<ide>
<ide> Flush pending data. Don't call this frivolously, premature flushes negatively
<ide> impact the effectiveness of the compression algorithm.
<ide> writes and will only produce output when data is being read from the stream.
<ide> added: v0.11.4
<ide> -->
<ide>
<add>* `level` {integer}
<add>* `strategy` {integer}
<add>* `callback` {Function}
<add>
<ide> Dynamically update the compression level and compression strategy.
<ide> Only applicable to deflate algorithm.
<ide>
<ide> Provides an object enumerating Zlib-related constants.
<ide> added: v0.5.8
<ide> -->
<ide>
<add>* `options` {Object}
<add>
<ide> Creates and returns a new [`Deflate`][] object with the given [`options`][].
<ide>
<ide> ## zlib.createDeflateRaw([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<add>* `options` {Object}
<add>
<ide> Creates and returns a new [`DeflateRaw`][] object with the given [`options`][].
<ide>
<ide> An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when `windowBits`
<ide> that effectively uses an 8-bit window only.
<ide> added: v0.5.8
<ide> -->
<ide>
<add>* `options` {Object}
<add>
<ide> Creates and returns a new [`Gunzip`][] object with the given [`options`][].
<ide>
<ide> ## zlib.createGzip([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<add>* `options` {Object}
<add>
<ide> Creates and returns a new [`Gzip`][] object with the given [`options`][].
<ide>
<ide> ## zlib.createInflate([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<add>* `options` {Object}
<add>
<ide> Creates and returns a new [`Inflate`][] object with the given [`options`][].
<ide>
<ide> ## zlib.createInflateRaw([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<add>* `options` {Object}
<add>
<ide> Creates and returns a new [`InflateRaw`][] object with the given [`options`][].
<ide>
<ide> ## zlib.createUnzip([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<add>* `options` {Object}
<add>
<ide> Creates and returns a new [`Unzip`][] object with the given [`options`][].
<ide>
<ide> ## Convenience Methods
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/12001
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<add>* `callback` {Function}
<add>
<ide> ### zlib.deflateSync(buffer[, options])
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<ide>
<ide> Compress a chunk of data with [`Deflate`][].
<ide>
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/12001
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<add>
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<add>* `callback` {Function}
<add>
<ide> ### zlib.deflateRawSync(buffer[, options])
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<ide>
<ide> Compress a chunk of data with [`DeflateRaw`][].
<ide>
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/12001
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<add>
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<add>* `callback` {Function}
<add>
<ide> ### zlib.gunzipSync(buffer[, options])
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<ide>
<ide> Decompress a chunk of data with [`Gunzip`][].
<ide>
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/12001
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<add>
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<add>* `callback` {Function}
<add>
<ide> ### zlib.gzipSync(buffer[, options])
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<ide>
<ide> Compress a chunk of data with [`Gzip`][].
<ide>
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/12001
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<add>
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<add>* `callback` {Function}
<add>
<ide> ### zlib.inflateSync(buffer[, options])
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<ide>
<ide> Decompress a chunk of data with [`Inflate`][].
<ide>
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/12001
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<add>
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<add>* `callback` {Function}
<add>
<ide> ### zlib.inflateRawSync(buffer[, options])
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<ide>
<ide> Decompress a chunk of data with [`InflateRaw`][].
<ide>
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/12001
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<add>
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<add>* `callback` {Function}
<add>
<ide> ### zlib.unzipSync(buffer[, options])
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<add>* `options` {Object}
<ide>
<ide> Decompress a chunk of data with [`Unzip`][].
<ide> | 15 |
Python | Python | exclude strings from v3.2+ source vector checks | ea450d652c32f65b947a1e1a498b45f29ed4dc29 | <ide><path>spacy/language.py
<ide> def create_pipe_from_source(
<ide> if (
<ide> self.vocab.vectors.shape != source.vocab.vectors.shape
<ide> or self.vocab.vectors.key2row != source.vocab.vectors.key2row
<del> or self.vocab.vectors.to_bytes() != source.vocab.vectors.to_bytes()
<add> or self.vocab.vectors.to_bytes(exclude=["strings"])
<add> != source.vocab.vectors.to_bytes(exclude=["strings"])
<ide> ):
<ide> warnings.warn(Warnings.W113.format(name=source_name))
<ide> if source_name not in source.component_names:
<ide> def from_config(
<ide> )
<ide> if model not in source_nlp_vectors_hashes:
<ide> source_nlp_vectors_hashes[model] = hash(
<del> source_nlps[model].vocab.vectors.to_bytes()
<add> source_nlps[model].vocab.vectors.to_bytes(
<add> exclude=["strings"]
<add> )
<ide> )
<ide> if "_sourced_vectors_hashes" not in nlp.meta:
<ide> nlp.meta["_sourced_vectors_hashes"] = {}
<ide><path>spacy/training/initialize.py
<ide> def init_vocab(
<ide> logger.info(f"Added vectors: {vectors}")
<ide> # warn if source model vectors are not identical
<ide> sourced_vectors_hashes = nlp.meta.pop("_sourced_vectors_hashes", {})
<del> vectors_hash = hash(nlp.vocab.vectors.to_bytes())
<add> vectors_hash = hash(nlp.vocab.vectors.to_bytes(exclude=["strings"]))
<ide> for sourced_component, sourced_vectors_hash in sourced_vectors_hashes.items():
<ide> if vectors_hash != sourced_vectors_hash:
<ide> warnings.warn(Warnings.W113.format(name=sourced_component)) | 2 |
Ruby | Ruby | build fix for new routing inspector changes | a6c06217a55a75c33056cf7113cc189cb2134686 | <ide><path>railties/test/application/rake_test.rb
<ide> def test_rake_routes_calls_the_route_inspector
<ide> RUBY
<ide>
<ide> output = Dir.chdir(app_path){ `rake routes` }
<del> assert_equal "Prefix Verb URI Pattern Controller#Action\ncart GET /cart(.:format) cart#show\n", output
<add> assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
<ide> end
<ide>
<ide> def test_rake_routes_with_controller_environment
<ide> def test_rake_routes_with_controller_environment
<ide>
<ide> ENV['CONTROLLER'] = 'cart'
<ide> output = Dir.chdir(app_path){ `rake routes` }
<del> assert_equal "Prefix Verb URI Pattern Controller#Action\ncart GET /cart(.:format) cart#show\n", output
<add> assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
<ide> end
<ide>
<ide> def test_rake_routes_displays_message_when_no_routes_are_defined | 1 |
Python | Python | fix description of isinf in nan_to_num | 86e87cb1e56108ce6b5e1faeb2469cbee804e22e | <ide><path>numpy/lib/type_check.py
<ide> def nan_to_num(x):
<ide>
<ide> See Also
<ide> --------
<del> isinf : Shows which elements are negative or negative infinity.
<add> isinf : Shows which elements are positive or negative infinity.
<ide> isneginf : Shows which elements are negative infinity.
<ide> isposinf : Shows which elements are positive infinity.
<ide> isnan : Shows which elements are Not a Number (NaN). | 1 |
Ruby | Ruby | add test to check we read new path correctly | 36beec7b55f9f8e3181e31b7bcf8ef04e2907351 | <ide><path>railties/test/application/configuration_test.rb
<ide> def index
<ide> end
<ide> end
<ide>
<add> test "autoload paths will exclude changed path" do
<add> app_file "config/webpacker.yml", <<-YAML
<add> default: &default
<add> source_path: app/webpack
<add> check_yarn_integrity: false
<add> development:
<add> <<: *default
<add> test:
<add> <<: *default
<add> production:
<add> <<: *default
<add> YAML
<add>
<add> app "development"
<add>
<add> ActiveSupport::Dependencies.autoload_paths.each do |path|
<add> assert_not_operator path, :ends_with?, "app/assets"
<add> assert_not_operator path, :ends_with?, "app/webpack"
<add> end
<add> end
<add>
<ide> test "autoload paths are added to $LOAD_PATH by default" do
<ide> app "development"
<ide> | 1 |
Ruby | Ruby | add trunk prefix to formula version | bc2a996f9ee3f9cef1789382854184e035307dad | <ide><path>tools/formulas/gyp.rb
<ide> class Gyp < Formula
<ide> homepage 'http://code.google.com/p/gyp/'
<ide> url 'http://gyp.googlecode.com/svn/trunk', :revision => 1518
<del> version '1518'
<add> version 'trunk-1518'
<ide> head 'http://gyp.googlecode.com/svn/trunk'
<ide>
<ide> def install | 1 |
Javascript | Javascript | remove obsolete tls test | 5b3587dbc64cc298701b62f8767d37976d57a451 | <ide><path>test/internet/test-tls-connnect-melissadata.js
<del>'use strict';
<del>// Test for authorized access to the server which has a cross root
<del>// certification between Starfield Class 2 and ValiCert Class 2
<del>
<del>const common = require('../common');
<del>if (!common.hasCrypto)
<del> common.skip('missing crypto');
<del>
<del>const tls = require('tls');
<del>const socket = tls.connect(443, 'address.melissadata.net', function() {
<del> socket.resume();
<del> socket.destroy();
<del>}); | 1 |
PHP | PHP | add skip if response is invalid | 9011b42bb4329e67e40c864c80ac6ba88d92e934 | <ide><path>lib/Cake/Test/Case/Network/Http/HttpSocketTest.php
<ide> public function testVerifyPeer() {
<ide> $this->markTestSkipped('Found valid certificate, was expecting invalid certificate.');
<ide> } catch (SocketException $e) {
<ide> $message = $e->getMessage();
<add> $this->skipIf(strpos($message, 'Invalid HTTP'), 'Invalid HTTP Response received, skipping.');
<ide> $this->assertContains('Peer certificate CN', $message);
<ide> $this->assertContains('Failed to enable crypto', $message);
<ide> } | 1 |
Text | Text | add colgate-palmolive to users list | 0eec083adbbfa64493a760e1e1a196d07fa0666d | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [Classmethod, Inc.](https://classmethod.jp/) [[@shoito](https://github.com/shoito)]
<ide> 1. [Cleartax](https://cleartax.in/) [[@anks](https://github.com/anks) & [@codebuff](https://github.com/codebuff)]
<ide> 1. [Clover Health](https://www.cloverhealth.com) [[@gwax](https://github.com/gwax) & [@vansivallab](https://github.com/vansivallab)]
<add>1. [Colgate-Palmolive](https://www.colgatepalmolive.com/) [[@fhoda](https://github.com/fhoda)]
<ide> 1. [Collectivehealth Inc.](https://www.collectivehealth.com) [[@retornam](https://github.com/retornam)]
<ide> 1. [Compass](https://www.compass.com) [[@wdhorton](https://github.com/wdhorton)]
<ide> 1. [ConnectWise](https://www.connectwise.com/) [[@jacobeturpin](https://github.com/jacobeturpin)] | 1 |
Javascript | Javascript | fix a spelling bug in linesegmentsgeometry.js | a5a5351d0125c708bd7a96b6b7f459c3934957ad | <ide><path>examples/js/lines/LineSegmentsGeometry.js
<ide> THREE.LineSegmentsGeometry.prototype = Object.assign( Object.create( THREE.Insta
<ide>
<ide> },
<ide>
<del> fromLineSegements: function ( lineSegments ) {
<add> fromLineSegments: function ( lineSegments ) {
<ide>
<ide> var geometry = lineSegments.geometry;
<ide> | 1 |
Ruby | Ruby | remove unused ivars left from close checks | 8dba9f13ea91cc15c40a9b12e15ea65aae1024e4 | <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> def initialize(secret = nil, host = nil, secure = false)
<ide> @delete_cookies = {}
<ide> @host = host
<ide> @secure = secure
<del> @closed = false
<ide> @cookies = {}
<ide> end
<ide>
<ide><path>actionpack/lib/action_dispatch/middleware/flash.rb
<ide> class FlashHash
<ide>
<ide> def initialize #:nodoc:
<ide> @discard = Set.new
<del> @closed = false
<ide> @flashes = {}
<ide> @now = nil
<ide> end | 2 |
Mixed | Text | add example for device-cgroup-rule to man | fc2fc6565a370c8403734254f2197081046704dd | <ide><path>man/generate.go
<ide> func loadLongDescription(cmd *cobra.Command, path string) error {
<ide> return err
<ide> }
<ide> cmd.Long = string(content)
<add>
<add> fullpath = filepath.Join(path, cmd.Name()+"-example.md")
<add> if _, err := os.Stat(fullpath); err != nil {
<add> continue
<add> }
<add>
<add> content, err = ioutil.ReadFile(fullpath)
<add> if err != nil {
<add> return err
<add> }
<add> cmd.Example = string(content)
<add>
<ide> }
<ide> return nil
<ide> }
<ide><path>man/src/container/create-example.md
<add>### Specify isolation technology for container (--isolation)
<add>
<add>This option is useful in situations where you are running Docker containers on
<add>Windows. The `--isolation=<value>` option sets a container's isolation
<add>technology. On Linux, the only supported is the `default` option which uses
<add>Linux namespaces. On Microsoft Windows, you can specify these values:
<add>
<add>* `default`: Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value.
<add>* `process`: Namespace isolation only.
<add>* `hyperv`: Hyper-V hypervisor partition-based isolation.
<add>
<add>Specifying the `--isolation` flag without a value is the same as setting `--isolation="default"`.
<add>
<add>### Dealing with dynamically created devices (--device-cgroup-rule)
<add>
<add>Devices available to a container are assigned at creation time. The
<add>assigned devices will both be added to the cgroup.allow file and
<add>created into the container once it is run. This poses a problem when
<add>a new device needs to be added to running container.
<add>
<add>One of the solution is to add a more permissive rule to a container
<add>allowing it access to a wider range of devices. For example, supposing
<add>our container needs access to a character device with major `42` and
<add>any number of minor number (added as new devices appear), the
<add>following rule would be added:
<add>
<add>```
<add>docker create --device-cgroup-rule='c 42:* rmw' -name my-container my-image
<add>```
<add>
<add>Then, a user could ask `udev` to execute a script that would `docker exec my-container mknod newDevX c 42 <minor>`
<add>the required device when it is added.
<add>
<add>NOTE: initially present devices still need to be explicitely added to
<add>the create/run command
<ide><path>man/src/container/create.md
<ide> any point.
<ide>
<ide> The initial status of the container created with **docker create** is 'created'.
<ide>
<del># OPTIONS
<add>### OPTIONS
<ide>
<ide> The `CONTAINER-DIR` must be an absolute path such as `/src/docs`. The `HOST-DIR`
<ide> can be an absolute path or a `name` value. A `name` value must start with an
<ide> change propagation properties of source mount. Say `/` is source mount for
<ide>
<ide> To disable automatic copying of data from the container path to the volume, use
<ide> the `nocopy` flag. The `nocopy` flag can be set on bind mounts and named volumes.
<del>
<del># EXAMPLES
<del>
<del>## Specify isolation technology for container (--isolation)
<del>
<del>This option is useful in situations where you are running Docker containers on
<del>Windows. The `--isolation=<value>` option sets a container's isolation
<del>technology. On Linux, the only supported is the `default` option which uses
<del>Linux namespaces. On Microsoft Windows, you can specify these values:
<del>
<del>* `default`: Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value.
<del>* `process`: Namespace isolation only.
<del>* `hyperv`: Hyper-V hypervisor partition-based isolation.
<del>
<del>Specifying the `--isolation` flag without a value is the same as setting `--isolation="default"`. | 3 |
Javascript | Javascript | improve helper directives | 6b7a1b82bc26bbf4640506a9a3cf37ebf254d3d2 | <ide><path>docs/app/src/tutorials.js
<ide> angular.module('tutorials', [])
<ide> element.addClass('tutorial-nav');
<ide> element.append(templateMerge(
<ide> '<a href="tutorial/{{prev}}"><li class="btn btn-primary"><i class="glyphicon glyphicon-step-backward"></i> Previous</li></a>\n' +
<del> '<a href="http://angular.github.com/angular-phonecat/step-{{seq}}/app"><li class="btn btn-primary"><i class="glyphicon glyphicon-play"></i> Live Demo</li></a>\n' +
<add> '<a href="http://angular.github.io/angular-phonecat/step-{{seq}}/app"><li class="btn btn-primary"><i class="glyphicon glyphicon-play"></i> Live Demo</li></a>\n' +
<ide> '<a href="https://github.com/angular/angular-phonecat/compare/step-{{diffLo}}...step-{{diffHi}}"><li class="btn btn-primary"><i class="glyphicon glyphicon-search"></i> Code Diff</li></a>\n' +
<ide> '<a href="tutorial/{{next}}"><li class="btn btn-primary">Next <i class="glyphicon glyphicon-step-forward"></i></li></a>', props));
<ide> }
<ide> angular.module('tutorials', [])
<ide> 'step': '@docTutorialReset'
<ide> },
<ide> template:
<del> '<div ng-hide="show">' +
<del> '<p><a href="" ng-click="show=true;$event.stopPropagation()">Workspace Reset Instructions ➤</a></p>' +
<add> '<p><a href="" ng-click="show=!show;$event.stopPropagation()">Workspace Reset Instructions ➤</a></p>\n' +
<add> '<div class="alert alert-info" ng-show="show">\n' +
<add> ' <p>Reset the workspace to step {{step}}.</p>' +
<add> ' <p><pre>git checkout -f step-{{step}}</pre></p>\n' +
<add> ' <p>Refresh your browser or check out this step online: '+
<add> '<a href="http://angular.github.io/angular-phonecat/step-{{step}}/app">Step {{step}} Live Demo</a>.</p>\n' +
<ide> '</div>\n' +
<del> '<div class="tabbable" ng-show="show">\n' +
<del> ' <li><p>Reset the workspace to step {{step}}.</p>' +
<del> ' <pre>git checkout -f step-{{step}}</pre></li>\n' +
<del> ' <li><p>Refresh your browser or check the app out on <a href="http://angular.github.com/angular-phonecat/step-{{step}}/app">Angular\'s server</a>.</p></li>\n' +
<del> '</div>\n'
<add> '<p>The most important changes are listed below. You can see the full diff on ' +
<add> '<a ng-href="https://github.com/angular/angular-phonecat/compare/step-{{step ? (step - 1): \'0~1\'}}...step-{{step}}">GitHub</a>\n' +
<add> '</p>'
<ide> };
<ide> }); | 1 |
Javascript | Javascript | add faster failure, and link to " | ebb79cdabaa8a9b4f095dac841955dae696cdd92 | <ide><path>test/simple/test-fs-watch.js
<ide> var assert = require('assert');
<ide> var path = require('path');
<ide> var fs = require('fs');
<ide>
<del>
<del>if (process.platform === 'darwin') {
<del> assert(false,
<del> 'This test is known to fail on OS X\n' +
<del> 'See: https://github.com/joyent/node/issues/2813');
<del>}
<del>
<del>
<ide> var expectFilePath = process.platform == 'win32' || process.platform == 'linux';
<ide>
<ide> var watchSeenOne = 0; | 1 |
Java | Java | remove configurationclassparser from public api | 6fcea8b99da45f287149796ef2598f0d71758793 | <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java
<ide> public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
<ide> */
<ide> private void processConfigurationClasses(BeanDefinitionRegistry registry) {
<ide> ConfigurationClassBeanDefinitionReader reader = getConfigurationClassBeanDefinitionReader(registry);
<del> ConfigurationClassParser parser = new ConfigurationClassParser(
<del> this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, registry);
<del> processConfigBeanDefinitions(parser, reader, registry);
<add> processConfigBeanDefinitions(reader, registry);
<ide> enhanceConfigurationClasses((ConfigurableListableBeanFactory)registry);
<ide> }
<ide>
<ide> private ConfigurationClassBeanDefinitionReader getConfigurationClassBeanDefiniti
<ide> * Build and validate a configuration model based on the registry of
<ide> * {@link Configuration} classes.
<ide> */
<del> public void processConfigBeanDefinitions(ConfigurationClassParser parser, ConfigurationClassBeanDefinitionReader reader, BeanDefinitionRegistry registry) {
<add> public void processConfigBeanDefinitions(ConfigurationClassBeanDefinitionReader reader, BeanDefinitionRegistry registry) {
<ide> Set<BeanDefinitionHolder> configCandidates = new LinkedHashSet<BeanDefinitionHolder>();
<ide> for (String beanName : registry.getBeanDefinitionNames()) {
<ide> BeanDefinition beanDef = registry.getBeanDefinition(beanName);
<ide> public void processConfigBeanDefinitions(ConfigurationClassParser parser, Config
<ide> }
<ide>
<ide> // Parse each @Configuration class
<add> ConfigurationClassParser parser = new ConfigurationClassParser(
<add> this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, registry);
<ide> for (BeanDefinitionHolder holder : configCandidates) {
<ide> BeanDefinition bd = holder.getBeanDefinition();
<ide> try { | 1 |
Text | Text | fix typo in fresh_when example [ci skip] | 697688663fccd1ef38413cdeec6957fe8ba7f94f | <ide><path>actionpack/CHANGELOG.md
<ide>
<ide> # Before
<ide> def index
<del> @article = Article.all
<del> fresh_when(etag: @articles, last_modified: @articles.maximum(:created_at))
<add> @articles = Article.all
<add> fresh_when(etag: @articles, last_modified: @articles.maximum(:updated_at))
<ide> end
<ide>
<ide> # After
<ide> def index
<del> @article = Article.all
<add> @articles = Article.all
<ide> fresh_when(@articles)
<ide> end
<ide> | 1 |
Text | Text | fix indentation for code block in changelog | f57092ad728fa1de06c4f5fd9d09dcc2c4738fd9 | <ide><path>activerecord/CHANGELOG.md
<ide>
<ide> Example:
<ide>
<del> PriceEstimate.where(estimate_of: [Treasure.find(1), Car.find(2)])
<del> # => SELECT "price_estimates".* FROM "price_estimates"
<del> WHERE (("price_estimates"."estimate_of_type" = 'Treasure' AND "price_estimates"."estimate_of_id" = 1)
<del> OR ("price_estimates"."estimate_of_type" = 'Car' AND "price_estimates"."estimate_of_id" = 2))
<add> PriceEstimate.where(estimate_of: [Treasure.find(1), Car.find(2)])
<add> => SELECT "price_estimates".* FROM "price_estimates"
<add> WHERE (("price_estimates"."estimate_of_type" = 'Treasure' AND "price_estimates"."estimate_of_id" = 1)
<add> OR ("price_estimates"."estimate_of_type" = 'Car' AND "price_estimates"."estimate_of_id" = 2))
<ide>
<ide> *Philippe Huibonhoa*
<ide> | 1 |
Javascript | Javascript | fix broken segments in tubegeometry | e1ad0a648186dc94280877534ae4925f7cfac382 | <ide><path>src/extras/geometries/TubeGeometry.js
<ide> THREE.TubeGeometry = function(radius, segments, segmentsRadius, path, debug) {
<ide>
<ide> this.grid[i] = new Array(this.segmentsRadius);
<ide>
<del> u = i / this.segments;
<add> u = i / ( this.segments - 1 );
<ide>
<ide> var pos = this.path.getPointAt(u);
<ide> tang = this.path.getTangentAt(u);
<ide> THREE.TubeGeometry = function(radius, segments, segmentsRadius, path, debug) {
<ide> oldB = binormal;
<ide>
<ide> if (oldB.length()==0) {
<del>
<del> // When binormal is a zero vector, we could brute force another vector ?
<del> // oldB.set( 1, 0, 0 );
<del> // if (normal.cross(oldB, tang).normalize().length()==0) {
<del> // oldB.set( 0, 1, 0 );
<del> // if (normal.cross(oldB, tang).normalize().length()==0) {
<del> // oldB.set( 0, 0, 1 );
<del> // }
<del> // }
<del>
<del> // Method 4 - Sets binormal direction in the smallest tangent xyz component
<del> var smallest = Number.MAX_VALUE;
<del> var x, y, z;
<del> var tx = Math.abs(tang.x);
<del> var ty = Math.abs(tang.y);
<del> var tz = Math.abs(tang.z);
<del>
<del> if (tx <= smallest) {
<del> smallest = tx;
<del> oldB.set(1,0,0);
<del> }
<del>
<del> if (ty <= smallest) {
<del> smallest = ty;
<del> oldB.set(0,1,0);
<del> }
<del>
<del> if (tz <= smallest) {
<del> oldB.set(0,0,1);
<add> // When binormal is a zero vector, we could brute force another vector ?
<add> // oldB.set( 1, 0, 0 );
<add> // if (normal.cross(oldB, tang).normalize().length()==0) {
<add> // oldB.set( 0, 1, 0 );
<add> // if (normal.cross(oldB, tang).normalize().length()==0) {
<add> // oldB.set( 0, 0, 1 );
<add> // }
<add> // }
<add>
<add> // Method 4 - Sets binormal direction in the smallest tangent xyz component
<add> var smallest = Number.MAX_VALUE;
<add> var x, y, z;
<add> var tx = Math.abs(tang.x);
<add> var ty = Math.abs(tang.y);
<add> var tz = Math.abs(tang.z);
<add>
<add> if (tx <= smallest) {
<add> smallest = tx;
<add> oldB.set(1,0,0);
<add> }
<add>
<add> if (ty <= smallest) {
<add> smallest = ty;
<add> oldB.set(0,1,0);
<add> }
<add>
<add> if (tz <= smallest) {
<add> oldB.set(0,0,1);
<add> }
<ide> }
<ide>
<ide> }
<ide> THREE.TubeGeometry = function(radius, segments, segmentsRadius, path, debug) {
<ide> }
<ide> }
<ide>
<del> for (var i = 0; i < this.segments; ++i) { // segments -1 for non-closed loops, segment - 0 for closed ?
<add> for (var i = 0; i < this.segments -1; ++i) {
<ide>
<ide> for (var j = 0; j < this.segmentsRadius; ++j) {
<ide> | 1 |
Javascript | Javascript | write pending data on socket drain | 60238cce12d5c0c45c54c18033a439ac12429a29 | <ide><path>lib/tls.js
<ide> function pipe(pair, socket) {
<ide> // its data from the cleartext side, we have to give it a
<ide> // light kick to get in motion again.
<ide> socket.on('drain', function() {
<add> if (pair.encrypted._pending)
<add> pair.encrypted._writePending();
<add> if (pair.cleartext._pending)
<add> pair.cleartext._writePending();
<ide> pair.encrypted.read(0);
<ide> pair.cleartext.read(0);
<ide> }); | 1 |
PHP | PHP | add methods for determining if job has failed | fed36bd7e09658009d36d9dd568f19ddcb75172e | <ide><path>src/Illuminate/Queue/FailingJob.php
<ide> class FailingJob
<ide> */
<ide> public static function handle($connectionName, $job, $e = null)
<ide> {
<add> $job->markAsFailed();
<add>
<ide> if ($job->isDeleted()) {
<ide> return;
<ide> }
<ide><path>src/Illuminate/Queue/Jobs/Job.php
<ide> abstract class Job
<ide> */
<ide> protected $released = false;
<ide>
<add> /**
<add> * Indicates if the job has failed.
<add> *
<add> * @var bool
<add> */
<add> protected $failed = false;
<add>
<ide> /**
<ide> * The name of the connection the job belongs to.
<ide> */
<ide> public function isDeletedOrReleased()
<ide> return $this->isDeleted() || $this->isReleased();
<ide> }
<ide>
<add> /**
<add> * Determine if the job has been marked as a failure.
<add> *
<add> * @return bool
<add> */
<add> public function hasFailed()
<add> {
<add> return $this->failed;
<add> }
<add>
<add> /**
<add> * Mark the job as "failed".
<add> *
<add> * @return void
<add> */
<add> public function markAsFailed()
<add> {
<add> $this->failed = true;
<add> }
<add>
<ide> /**
<ide> * Process an exception that caused the job to fail.
<ide> *
<ide> public function isDeletedOrReleased()
<ide> */
<ide> public function failed($e)
<ide> {
<add> $this->markAsFailed();
<add>
<ide> $payload = $this->payload();
<ide>
<ide> list($class, $method) = JobName::parse($payload['job']);
<ide><path>tests/Queue/QueueWorkerTest.php
<ide> public function attempts()
<ide> return $this->attempts;
<ide> }
<ide>
<add> public function markAsFailed()
<add> {
<add> //
<add> }
<add>
<ide> public function failed($e)
<ide> {
<ide> $this->failedWith = $e;
<ide> public function setConnectionName($name)
<ide> {
<ide> $this->connectionName = $name;
<ide> }
<del>
<del> public function testJobSleepsWhenAnExceptionIsThrownForADaemonWorker()
<del> {
<del> $exceptionHandler = m::mock('Illuminate\Contracts\Debug\ExceptionHandler');
<del> $job = m::mock('Illuminate\Contracts\Queue\Job');
<del> $job->shouldReceive('fire')->once()->andReturnUsing(function () {
<del> throw new RuntimeException;
<del> });
<del> $worker = m::mock('Illuminate\Queue\Worker', [$manager = m::mock('Illuminate\Queue\QueueManager')])->makePartial();
<del> $manager->shouldReceive('connection')->once()->with('connection')->andReturn($connection = m::mock('StdClass'));
<del> $manager->shouldReceive('getName')->andReturn('connection');
<del> $connection->shouldReceive('pop')->once()->with('queue')->andReturn($job);
<del> $worker->shouldReceive('sleep')->once()->with(3);
<del>
<del> $exceptionHandler->shouldReceive('report')->once();
<del>
<del> $worker->setDaemonExceptionHandler($exceptionHandler);
<del> $worker->pop('connection', 'queue');
<del> }
<ide> } | 3 |
PHP | PHP | return the insertid of released jobs | 4a9e58918332bd33c71c931a3305f8a3a978b294 | <ide><path>src/Illuminate/Queue/Jobs/DatabaseJob.php
<ide> public function __construct(Container $container, DatabaseQueue $database, $job,
<ide> * Release the job back into the queue.
<ide> *
<ide> * @param int $delay
<del> * @return void
<add> * @return mixed
<ide> */
<ide> public function release($delay = 0)
<ide> {
<ide> parent::release($delay);
<ide>
<ide> $this->delete();
<ide>
<del> $this->database->release($this->queue, $this->job, $delay);
<add> return $this->database->release($this->queue, $this->job, $delay);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | use https url example for git clone commands. | fa57fb8aeb93c60dcb5eb75a7f88f61afaf35fb9 | <ide><path>CONTRIBUTING.md
<ide> Getting involved in triaging incoming issues is a good way to start contributing
<ide>
<ide> To start developing on Django REST framework, clone the repo:
<ide>
<del> git clone git@github.com:encode/django-rest-framework.git
<add> git clone https://github.com/encode/django-rest-framework
<ide>
<ide> Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
<ide>
<ide><path>docs/index.md
<ide> Install using `pip`, including any optional packages you want...
<ide>
<ide> ...or clone the project from github.
<ide>
<del> git clone git@github.com:encode/django-rest-framework.git
<add> git clone https://github.com/encode/django-rest-framework
<ide>
<ide> Add `'rest_framework'` to your `INSTALLED_APPS` setting.
<ide> | 2 |
Javascript | Javascript | add examples of usage | 1a8d83d6608f7c29116e4dc9dd565df21a4ae045 | <ide><path>src/ng/cacheFactory.js
<ide> function $CacheFactoryProvider() {
<ide> * @name ng.$templateCache
<ide> *
<ide> * @description
<del> * Cache used for storing html templates.
<del> *
<add> * The first time a template is used, it is loaded in the tempalte cache for quick retrieval. You can
<add> * load templates directly into the cache in a `script` tag, or by consuming the `$templateCache`
<add> * service directly.
<add> *
<add> * Adding via the `script` tag:
<add> * <pre>
<add> * <html ng-app>
<add> * <head>
<add> * <script type="text/ng-template" id="templateId.html">
<add> * This is the content of the template
<add> * </script>
<add> * </head>
<add> * ...
<add> * </html>
<add> * </pre>
<add> *
<add> * **Note:** the `script` tag containing the template does not need to be included in the `head` of the document, but
<add> * it must be below the `ng-app` definition.
<add> *
<add> * Adding via the $templateCache service:
<add> *
<add> * <pre>
<add> * var myApp = angular.module('myApp', []);
<add> * myApp.run(function($templateCache) {
<add> * $templateCache.put('templateId.html', 'This is the content of the template');
<add> * });
<add> * </pre>
<add> *
<add> * To retrieve the template later, simply use it in your HTML:
<add> * <pre>
<add> * <div ng-include=" 'templateId.html' "></div>
<add> * </pre>
<add> *
<add> * or get it via Javascript:
<add> * <pre>
<add> * $templateCache.get('templateId.html')
<add> * </pre>
<add> *
<ide> * See {@link ng.$cacheFactory $cacheFactory}.
<ide> *
<ide> */ | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.