content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Ruby | Ruby | use a single lock for all connections | ea549392986bcaa5546a61404a015b135b39a1a1 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def initialize(config_or_deprecated_connection, deprecated_logger = nil, depreca
<ide> @verified = false
<ide> end
<ide>
<add> THREAD_LOCK = ActiveSupport::Concurrency::ThreadLoadInterlockAwareMonitor.new
<add> private_constant :THREAD_LOCK
<add>
<add> FIBER_LOCK = ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new
<add> private_constant :FIBER_LOCK
<add>
<ide> def lock_thread=(lock_thread) # :nodoc:
<ide> @lock =
<ide> case lock_thread
<ide> when Thread
<del> ActiveSupport::Concurrency::ThreadLoadInterlockAwareMonitor.new
<add> THREAD_LOCK
<ide> when Fiber
<del> ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new
<add> FIBER_LOCK
<ide> else
<ide> ActiveSupport::Concurrency::NullLock
<ide> end | 1 |
Mixed | Text | add documentation for stack commands | 10919e890942cbdaa65f180dbcd475d21b9c6713 | <ide><path>api/client/stack/opts.go
<ide> import (
<ide> )
<ide>
<ide> func addBundlefileFlag(opt *string, flags *pflag.FlagSet) {
<del> flags.StringVarP(
<add> flags.StringVar(
<ide> opt,
<del> "bundle", "f", "",
<add> "bundle", "",
<ide> "Path to a Distributed Application Bundle file (Default: STACK.dab)")
<ide> }
<ide>
<ide><path>docs/reference/commandline/deploy.md
<add><!--[metadata]>
<add>+++
<add>title = "deploy"
<add>description = "The deploy command description and usage"
<add>keywords = ["stack, deploy"]
<add>advisory = "experimental"
<add>[menu.main]
<add>parent = "smn_cli"
<add>+++
<add><![end-metadata]-->
<add>
<add># stack deploy (experimental)
<add>
<add>```markdown
<add>Usage: docker deploy [OPTIONS] STACK
<add>
<add>Create and update a stack from a Distributed Application Bundle (DAB)
<add>
<add>Options:
<add> --bundle string Path to a Distributed Application Bundle file (Default: STACK.dab)
<add> --help Print usage
<add>```
<add>
<add>Create and update a stack from a `dab` file. This command has to be
<add>run targeting a manager node.
<add>
<add>```bash
<add>$ docker deploy vossibility-stack
<add>Loading bundle from vossibility-stack.dab
<add>Creating service vossibility-stack_elasticsearch
<add>Creating service vossibility-stack_kibana
<add>Creating service vossibility-stack_logstash
<add>Creating service vossibility-stack_lookupd
<add>Creating service vossibility-stack_nsqd
<add>Creating service vossibility-stack_vossibility-collector
<add>```
<add>
<add>You can verify that the services were correctly created:
<add>
<add>```bash
<add>$ docker service ls
<add>ID NAME REPLICAS IMAGE
<add>COMMAND
<add>29bv0vnlm903 vossibility-stack_lookupd 1 nsqio/nsq@sha256:eeba05599f31eba418e96e71e0984c3dc96963ceb66924dd37a47bf7ce18a662 /nsqlookupd
<add>4awt47624qwh vossibility-stack_nsqd 1 nsqio/nsq@sha256:eeba05599f31eba418e96e71e0984c3dc96963ceb66924dd37a47bf7ce18a662 /nsqd --data-path=/data --lookupd-tcp-address=lookupd:4160
<add>4tjx9biia6fs vossibility-stack_elasticsearch 1 elasticsearch@sha256:12ac7c6af55d001f71800b83ba91a04f716e58d82e748fa6e5a7359eed2301aa
<add>7563uuzr9eys vossibility-stack_kibana 1 kibana@sha256:6995a2d25709a62694a937b8a529ff36da92ebee74bafd7bf00e6caf6db2eb03
<add>9gc5m4met4he vossibility-stack_logstash 1 logstash@sha256:2dc8bddd1bb4a5a34e8ebaf73749f6413c101b2edef6617f2f7713926d2141fe logstash -f /etc/logstash/conf.d/logstash.conf
<add>axqh55ipl40h vossibility-stack_vossibility-collector 1 icecrime/vossibility-collector@sha256:f03f2977203ba6253988c18d04061c5ec7aab46bca9dfd89a9a1fa4500989fba --config /config/config.toml --debug
<add>```
<add>
<add>## Related information
<add>
<add>* [stack config](stack_config.md)
<add>* [stack deploy](stack_deploy.md)
<add>* [stack rm](stack_rm.md)
<add>* [stack tasks](stack_tasks.md)
<ide><path>docs/reference/commandline/stack_config.md
<add><!--[metadata]>
<add>+++
<add>title = "stack config"
<add>description = "The stack config command description and usage"
<add>keywords = ["stack, config"]
<add>advisory = "experimental"
<add>[menu.main]
<add>parent = "smn_cli"
<add>+++
<add><![end-metadata]-->
<add>
<add># stack config (experimental)
<add>
<add>```markdown
<add>Usage: docker stack config [OPTIONS] STACK
<add>
<add>Print the stack configuration
<add>
<add>Options:
<add> --bundle string Path to a Distributed Application Bundle file (Default: STACK.dab)
<add> --help Print usage
<add>```
<add>
<add>Displays the configuration of a stack.
<add>
<add>## Related information
<add>
<add>* [stack deploy](stack_deploy.md)
<add>* [stack rm](stack_rm.md)
<add>* [stack tasks](stack_tasks.md)
<ide><path>docs/reference/commandline/stack_deploy.md
<add><!--[metadata]>
<add>+++
<add>title = "stack deploy"
<add>description = "The stack deploy command description and usage"
<add>keywords = ["stack, deploy, up"]
<add>advisory = "experimental"
<add>[menu.main]
<add>parent = "smn_cli"
<add>+++
<add><![end-metadata]-->
<add>
<add># stack deploy (experimental)
<add>
<add>```markdown
<add>Usage: docker stack deploy [OPTIONS] STACK
<add>
<add>Create and update a stack from a Distributed Application Bundle (DAB)
<add>
<add>Aliases:
<add> deploy, up
<add>
<add>Options:
<add> --bundle string Path to a Distributed Application Bundle file (Default: STACK.dab)
<add> --help Print usage
<add>```
<add>
<add>Create and update a stack from a `dab` file on the swarm. This command
<add>has to be run targeting a manager node.
<add>
<add>```bash
<add>$ docker stack deploy vossibility-stack
<add>Loading bundle from vossibility-stack.dab
<add>Creating service vossibility-stack_elasticsearch
<add>Creating service vossibility-stack_kibana
<add>Creating service vossibility-stack_logstash
<add>Creating service vossibility-stack_lookupd
<add>Creating service vossibility-stack_nsqd
<add>Creating service vossibility-stack_vossibility-collector
<add>```
<add>
<add>You can verify that the services were correctly created:
<add>
<add>```bash
<add>$ docker service ls
<add>ID NAME REPLICAS IMAGE
<add>COMMAND
<add>29bv0vnlm903 vossibility-stack_lookupd 1 nsqio/nsq@sha256:eeba05599f31eba418e96e71e0984c3dc96963ceb66924dd37a47bf7ce18a662 /nsqlookupd
<add>4awt47624qwh vossibility-stack_nsqd 1 nsqio/nsq@sha256:eeba05599f31eba418e96e71e0984c3dc96963ceb66924dd37a47bf7ce18a662 /nsqd --data-path=/data --lookupd-tcp-address=lookupd:4160
<add>4tjx9biia6fs vossibility-stack_elasticsearch 1 elasticsearch@sha256:12ac7c6af55d001f71800b83ba91a04f716e58d82e748fa6e5a7359eed2301aa
<add>7563uuzr9eys vossibility-stack_kibana 1 kibana@sha256:6995a2d25709a62694a937b8a529ff36da92ebee74bafd7bf00e6caf6db2eb03
<add>9gc5m4met4he vossibility-stack_logstash 1 logstash@sha256:2dc8bddd1bb4a5a34e8ebaf73749f6413c101b2edef6617f2f7713926d2141fe logstash -f /etc/logstash/conf.d/logstash.conf
<add>axqh55ipl40h vossibility-stack_vossibility-collector 1 icecrime/vossibility-collector@sha256:f03f2977203ba6253988c18d04061c5ec7aab46bca9dfd89a9a1fa4500989fba --config /config/config.toml --debug
<add>```
<add>
<add>## Related information
<add>
<add>* [stack config](stack_config.md)
<add>* [stack rm](stack_rm.md)
<add>* [stack tasks](stack_tasks.md)
<ide><path>docs/reference/commandline/stack_rm.md
<add><!--[metadata]>
<add>+++
<add>title = "stack rm"
<add>description = "The stack rm command description and usage"
<add>keywords = ["stack, rm, remove, down"]
<add>advisory = "experimental"
<add>[menu.main]
<add>parent = "smn_cli"
<add>+++
<add><![end-metadata]-->
<add>
<add># stack rm (experimental)
<add>
<add>```markdown
<add>Usage: docker stack rm STACK
<add>
<add>Remove the stack
<add>
<add>Aliases:
<add> rm, remove, down
<add>
<add>Options:
<add> --help Print usage
<add>```
<add>
<add>Remove the stack from the swarm. This command has to be run targeting
<add>a manager node.
<add>
<add>## Related information
<add>
<add>* [stack config](stack_config.md)
<add>* [stack deploy](stack_deploy.md)
<add>* [stack tasks](stack_tasks.md)
<ide><path>docs/reference/commandline/stack_tasks.md
<add><!--[metadata]>
<add>+++
<add>title = "stack tasks"
<add>description = "The stack tasks command description and usage"
<add>keywords = ["stack, tasks"]
<add>advisory = "experimental"
<add>[menu.main]
<add>parent = "smn_cli"
<add>+++
<add><![end-metadata]-->
<add>
<add># stack tasks (experimental)
<add>
<add>```markdown
<add>Usage: docker stack tasks [OPTIONS] STACK
<add>
<add>List the tasks in the stack
<add>
<add>Options:
<add> -a, --all Display all tasks
<add> -f, --filter value Filter output based on conditions provided
<add> --help Print usage
<add> --no-resolve Do not map IDs to Names
<add>```
<add>
<add>Lists the tasks that are running as part of the specified stack. This
<add>command has to be run targeting a manager node.
<add>
<add>## Filtering
<add>
<add>The filtering flag (`-f` or `--filter`) format is a `key=value` pair. If there
<add>is more than one filter, then pass multiple flags (e.g. `--filter "foo=bar" --filter "bif=baz"`).
<add>Multiple filter flags are combined as an `OR` filter. For example,
<add>`-f name=redis.1 -f name=redis.7` returns both `redis.1` and `redis.7` tasks.
<add>
<add>The currently supported filters are:
<add>
<add>* [id](#id)
<add>* [name](#name)
<add>* [desired-state](#desired-state)
<add>
<add>## Related information
<add>
<add>* [stack config](stack_config.md)
<add>* [stack deploy](stack_deploy.md)
<add>* [stack rm](stack_rm.md) | 6 |
PHP | PHP | replace function sizeof (alias) by count | 71df8dbbba8ace80cd60b9019fc3ab65cca1df81 | <ide><path>cake/libs/model/datasources/dbo/dbo_adodb.php
<ide> function rollback(&$model) {
<ide> function listSources() {
<ide> $tables = $this->_adodb->MetaTables('TABLES');
<ide>
<del> if (!sizeof($tables) > 0) {
<add> if (!count($tables) > 0) {
<ide> trigger_error(ERROR_NO_TABLE_LIST, E_USER_NOTICE);
<ide> exit;
<ide> }
<ide><path>cake/libs/validation.php
<ide> function multiple($check, $options = array()) {
<ide> if (empty($check)) {
<ide> return false;
<ide> }
<del> if ($options['max'] && sizeof($check) > $options['max']) {
<add> if ($options['max'] && count($check) > $options['max']) {
<ide> return false;
<ide> }
<del> if ($options['min'] && sizeof($check) < $options['min']) {
<add> if ($options['min'] && count($check) < $options['min']) {
<ide> return false;
<ide> }
<ide> if ($options['in'] && is_array($options['in'])) {
<ide><path>cake/tests/cases/libs/model/behaviors/acl.test.php
<ide> function testAfterSave() {
<ide> $this->assertEqual($result['Aro']['parent_id'], 5);
<ide>
<ide> $node = $Person->node(array('model' => 'AclPerson', 'foreign_key' => 8));
<del> $this->assertEqual(sizeof($node), 2);
<add> $this->assertEqual(count($node), 2);
<ide> $this->assertEqual($node[0]['Aro']['parent_id'], 5);
<ide> $this->assertEqual($node[1]['Aro']['parent_id'], null);
<ide> }
<ide> function testAfterDelete() {
<ide> $Person->save($data);
<ide> $id = $Person->id;
<ide> $node = $Person->node();
<del> $this->assertEqual(sizeof($node), 2);
<add> $this->assertEqual(count($node), 2);
<ide> $this->assertEqual($node[0]['Aro']['parent_id'], 5);
<ide> $this->assertEqual($node[1]['Aro']['parent_id'], null);
<ide>
<ide> function testNode() {
<ide> $Person->id = 2;
<ide> $result = $Person->node();
<ide> $this->assertTrue(is_array($result));
<del> $this->assertEqual(sizeof($result), 1);
<add> $this->assertEqual(count($result), 1);
<ide> }
<ide> }
<ide> ?>
<ide>\ No newline at end of file | 3 |
Ruby | Ruby | reset argv in teardown | d86342a2519b6bdc5393302e3e81e5b72aa26e7f | <ide><path>Library/Homebrew/test/cleanup_test.rb
<ide> def setup
<ide>
<ide> def teardown
<ide> FileUtils.rm_f @ds_store
<del> ARGV.delete "--dry-run"
<del> ARGV.delete "--prune=all"
<ide> super
<ide> end
<ide>
<ide><path>Library/Homebrew/test/formula_installer_test.rb
<ide> def test_a_basic_install
<ide> assert_equal 3, bin.children.length
<ide> assert_predicate f.prefix/".brew/testball.rb", :readable?
<ide> end
<del> ensure
<del> ARGV.reject! { |a| a == "--with-invalid_flag" }
<ide> end
<ide>
<ide> def test_bottle_unneeded_formula_install
<ide> def test_not_poured_from_bottle_when_compiler_specified
<ide>
<ide> cc_arg = "--cc=clang"
<ide> ARGV << cc_arg
<del> begin
<del> temporary_install(TestballBottle.new) do |f|
<del> tab = Tab.for_formula(f)
<del> assert_equal "clang", tab.compiler
<del> end
<del> ensure
<del> ARGV.delete_if { |x| x == cc_arg }
<add>
<add> temporary_install(TestballBottle.new) do |f|
<add> tab = Tab.for_formula(f)
<add> assert_equal "clang", tab.compiler
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/support/helper/test_case.rb
<ide> class TestCase < ::Minitest::Test
<ide> TEST_SHA1 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze
<ide> TEST_SHA256 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze
<ide>
<add> def setup
<add> super
<add> @__argv = ARGV.dup
<add> end
<add>
<ide> def teardown
<ide> Tab.clear_cache
<add> ARGV.replace(@__argv)
<ide> super
<ide> end
<ide>
<ide><path>Library/Homebrew/test/uninstall_test.rb
<ide> def test_check_for_dependents_when_ignore_dependencies
<ide> assert_empty handle_unsatisfied_dependents
<ide> refute_predicate Homebrew, :failed?
<ide> end
<del> ensure
<del> ARGV.delete("--ignore-dependencies")
<ide> end
<ide> end
<ide> | 4 |
Python | Python | fix convert cli | 7cc9c3e9a6f28422485eb2a054d12850481aeb71 | <ide><path>spacy/cli/convert.py
<ide> def convert(_, input_file, output_dir, n_sents, morphology):
<ide> prints("Can't find converter for %s" % input_path.parts[-1],
<ide> title="Unknown format", exits=1)
<ide> CONVERTERS[file_ext](input_path, output_path,
<del> n_sents=n_sents, morphology=morphology)
<add> n_sents=n_sents, use_morphology=morphology) | 1 |
Text | Text | remove unecessary word | 2d7ea2cc2ba780a113e34b3cb8524eb6b1bd71f2 | <ide><path>guides/source/action_controller_overview.md
<ide> This will read and stream the file 4kB at the time, avoiding loading the entire
<ide>
<ide> If `:type` is not specified, it will be guessed from the file extension specified in `:filename`. If the content type is not registered for the extension, `application/octet-stream` will be used.
<ide>
<del>WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
<add>WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to.
<ide>
<ide> TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
<ide> | 1 |
Javascript | Javascript | fix close event of readline.interface() | e1aa066fe16e5feb2d5621ce0d2163703da1110c | <ide><path>lib/readline.js
<ide> function Interface(input, output, completer, terminal) {
<ide> self.close();
<ide> }
<ide>
<add> function ontermend() {
<add> if (util.isString(self.line) && self.line.length > 0) {
<add> self.emit('line', self.line);
<add> }
<add> self.close();
<add> }
<add>
<ide> function onkeypress(s, key) {
<ide> self._ttyWrite(s, key);
<ide> }
<ide> function Interface(input, output, completer, terminal) {
<ide>
<ide> // input usually refers to stdin
<ide> input.on('keypress', onkeypress);
<del> input.on('end', function inputEnd() {
<del> if (util.isString(self.line) && self.line.length > 0)
<del> self.emit('line', self.line);
<del> self.close();
<del> });
<add> input.on('end', ontermend);
<ide>
<ide> // Current line
<ide> this.line = '';
<ide> function Interface(input, output, completer, terminal) {
<ide> output.on('resize', onresize);
<ide> self.once('close', function() {
<ide> input.removeListener('keypress', onkeypress);
<add> input.removeListener('end', ontermend);
<ide> output.removeListener('resize', onresize);
<ide> });
<ide> }
<ide><path>test/simple/test-readline-interface.js
<ide> FakeInput.prototype.pause = function() {};
<ide> FakeInput.prototype.write = function() {};
<ide> FakeInput.prototype.end = function() {};
<ide>
<add>function isWarned(emitter) {
<add> for (var name in emitter) {
<add> var listeners = emitter[name];
<add> if (listeners.warned) return true;
<add> }
<add> return false;
<add>}
<add>
<ide> [ true, false ].forEach(function(terminal) {
<ide> var fi;
<ide> var rli;
<ide> FakeInput.prototype.end = function() {};
<ide> assert.equal(readline.getStringWidth('> '), 2);
<ide>
<ide> assert.deepEqual(fi.listeners(terminal ? 'keypress' : 'data'), []);
<add>
<add> // check EventEmitter memory leak
<add> for (var i=0; i<12; i++) {
<add> var rl = readline.createInterface({
<add> input: process.stdin,
<add> output: process.stdout
<add> });
<add> rl.close();
<add> assert.equal(isWarned(process.stdin._events), false);
<add> assert.equal(isWarned(process.stdout._events), false);
<add> }
<add>
<ide> });
<add> | 2 |
PHP | PHP | use fqcn in doc block | 432c45132f396ea0252e6e74606fc4b56d0ec01e | <ide><path>src/I18n/TranslatorRegistry.php
<ide> class TranslatorRegistry extends TranslatorLocator
<ide> *
<ide> * Constructor.
<ide> *
<del> * @param PackageLocator $packages The package locator.
<add> * @param \Aura\Intl\PackageLocator $packages The package locator.
<ide> *
<del> * @param FormatterLocator $formatters The formatter locator.
<add> * @param \Aura\Intl\FormatterLocator $formatters The formatter locator.
<ide> *
<del> * @param TranslatorFactory $factory A translator factory to
<add> * @param \Aura\Intl\TranslatorFactory $factory A translator factory to
<ide> * create translator objects for the locale and package.
<ide> *
<ide> * @param string $locale The default locale code to use. | 1 |
Python | Python | require thinc 7.1 | b8edc8dffb7fb5651973181a46ced5da5ec1a7cf | <ide><path>setup.py
<ide> def setup_package():
<ide> "murmurhash>=0.28.0,<1.1.0",
<ide> "cymem>=2.0.2,<2.1.0",
<ide> "preshed>=2.0.1,<2.1.0",
<del> "thinc>=7.0.8,<7.1.0",
<add> "thinc>=7.1.0,<7.2.0",
<ide> "blis>=0.4.0,<0.5.0",
<ide> "plac<1.0.0,>=0.9.6",
<ide> "requests>=2.13.0,<3.0.0", | 1 |
Python | Python | update the `nbitbase` example | 4ef10a55103ddf98730305db11461457cfc93e6e | <ide><path>numpy/typing/__init__.py
<ide> class NBitBase:
<ide>
<ide> .. code-block:: python
<ide>
<add> >>> from __future__ import annotations
<ide> >>> from typing import TypeVar, TYPE_CHECKING
<ide> >>> import numpy as np
<ide> >>> import numpy.typing as npt
<ide>
<del> >>> T = TypeVar("T", bound=npt.NBitBase)
<add> >>> T1 = TypeVar("T1", bound=npt.NBitBase)
<add> >>> T2 = TypeVar("T2", bound=npt.NBitBase)
<ide>
<del> >>> def add(a: "np.floating[T]", b: "np.integer[T]") -> "np.floating[T]":
<add> >>> def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[Union[T1, T2]]:
<ide> ... return a + b
<ide>
<ide> >>> a = np.float16()
<ide><path>numpy/typing/tests/data/reveal/nbit_base_example.py
<ide> import numpy as np
<ide> import numpy.typing as npt
<ide>
<del>T = TypeVar("T", bound=npt.NBitBase)
<add>T1 = TypeVar("T1", bound=npt.NBitBase)
<add>T2 = TypeVar("T2", bound=npt.NBitBase)
<ide>
<del>def add(a: np.floating[T], b: np.integer[T]) -> np.floating[T]:
<add>def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[Union[T1, T2]]:
<ide> return a + b
<ide>
<ide> i8: np.int64 | 2 |
Javascript | Javascript | remove unnecessary call to `isdefined()` | d088fbeae3bc718e5f29d84f46c7e3e1d8863064 | <ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> onChangesQueue.push(triggerOnChangesHook);
<ide> }
<ide> // If the has been a change on this property already then we need to reuse the previous value
<del> if (isDefined(changes[key])) {
<add> if (changes[key]) {
<ide> previousValue = changes[key].previousValue;
<ide> }
<ide> // Store this change | 1 |
Go | Go | add health check in docker cluster | 1ded1f26e154e283ab26f347971d4d4a51edc94f | <ide><path>daemon/cluster/executor/backend.go
<ide> package executor
<ide>
<ide> import (
<ide> "io"
<add> "time"
<ide>
<ide> clustertypes "github.com/docker/docker/daemon/cluster/provider"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/container"
<add> "github.com/docker/engine-api/types/events"
<add> "github.com/docker/engine-api/types/filters"
<ide> "github.com/docker/engine-api/types/network"
<ide> "github.com/docker/libnetwork/cluster"
<ide> networktypes "github.com/docker/libnetwork/types"
<ide> type Backend interface {
<ide> SetNetworkBootstrapKeys([]*networktypes.EncryptionKey) error
<ide> SetClusterProvider(provider cluster.Provider)
<ide> IsSwarmCompatible() error
<add> SubscribeToEvents(since, until time.Time, filter filters.Args) ([]events.Message, chan interface{})
<add> UnsubscribeFromEvents(listener chan interface{})
<ide> }
<ide><path>daemon/cluster/executor/container/adapter.go
<ide> import (
<ide> "io"
<ide> "strings"
<ide> "syscall"
<add> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/server/httputils"
<ide> executorpkg "github.com/docker/docker/daemon/cluster/executor"
<ide> "github.com/docker/engine-api/types"
<add> "github.com/docker/engine-api/types/events"
<ide> "github.com/docker/engine-api/types/versions"
<ide> "github.com/docker/libnetwork"
<ide> "github.com/docker/swarmkit/api"
<ide> func (c *containerAdapter) inspect(ctx context.Context) (types.ContainerJSON, er
<ide>
<ide> // events issues a call to the events API and returns a channel with all
<ide> // events. The stream of events can be shutdown by cancelling the context.
<del>//
<del>// A chan struct{} is returned that will be closed if the event processing
<del>// fails and needs to be restarted.
<add>func (c *containerAdapter) events(ctx context.Context) <-chan events.Message {
<add> log.G(ctx).Debugf("waiting on events")
<add> buffer, l := c.backend.SubscribeToEvents(time.Time{}, time.Time{}, c.container.eventFilter())
<add> eventsq := make(chan events.Message, len(buffer))
<add>
<add> for _, event := range buffer {
<add> eventsq <- event
<add> }
<add>
<add> go func() {
<add> defer c.backend.UnsubscribeFromEvents(l)
<add>
<add> for {
<add> select {
<add> case ev := <-l:
<add> jev, ok := ev.(events.Message)
<add> if !ok {
<add> log.G(ctx).Warnf("unexpected event message: %q", ev)
<add> continue
<add> }
<add> select {
<add> case eventsq <- jev:
<add> case <-ctx.Done():
<add> return
<add> }
<add> case <-ctx.Done():
<add> return
<add> }
<add> }
<add> }()
<add>
<add> return eventsq
<add>}
<add>
<ide> func (c *containerAdapter) wait(ctx context.Context) error {
<ide> return c.backend.ContainerWaitWithContext(ctx, c.container.name())
<ide> }
<ide><path>daemon/cluster/executor/container/container.go
<ide> import (
<ide> "github.com/docker/docker/reference"
<ide> "github.com/docker/engine-api/types"
<ide> enginecontainer "github.com/docker/engine-api/types/container"
<add> "github.com/docker/engine-api/types/events"
<add> "github.com/docker/engine-api/types/filters"
<ide> "github.com/docker/engine-api/types/network"
<ide> "github.com/docker/swarmkit/agent/exec"
<ide> "github.com/docker/swarmkit/api"
<ide> func (c *containerConfig) networkCreateRequest(name string) (clustertypes.Networ
<ide>
<ide> return clustertypes.NetworkCreateRequest{na.Network.ID, types.NetworkCreateRequest{Name: name, NetworkCreate: options}}, nil
<ide> }
<add>
<add>func (c containerConfig) eventFilter() filters.Args {
<add> filter := filters.NewArgs()
<add> filter.Add("type", events.ContainerEventType)
<add> filter.Add("name", c.name())
<add> filter.Add("label", fmt.Sprintf("%v.task.id=%v", systemLabelPrefix, c.task.ID))
<add> return filter
<add>}
<ide><path>daemon/cluster/executor/container/controller.go
<ide> import (
<ide>
<ide> executorpkg "github.com/docker/docker/daemon/cluster/executor"
<ide> "github.com/docker/engine-api/types"
<add> "github.com/docker/engine-api/types/events"
<ide> "github.com/docker/swarmkit/agent/exec"
<ide> "github.com/docker/swarmkit/api"
<ide> "github.com/docker/swarmkit/log"
<ide> func (r *controller) Wait(pctx context.Context) error {
<ide> ctx, cancel := context.WithCancel(pctx)
<ide> defer cancel()
<ide>
<add> healthErr := make(chan error, 1)
<add> go func() {
<add> ectx, cancel := context.WithCancel(ctx) // cancel event context on first event
<add> defer cancel()
<add> if err := r.checkHealth(ectx); err == ErrContainerUnhealthy {
<add> healthErr <- ErrContainerUnhealthy
<add> if err := r.Shutdown(ectx); err != nil {
<add> log.G(ectx).WithError(err).Debug("shutdown failed on unhealthy")
<add> }
<add> }
<add> }()
<add>
<ide> err := r.adapter.wait(ctx)
<ide> if ctx.Err() != nil {
<ide> return ctx.Err()
<ide> }
<add>
<ide> if err != nil {
<ide> ee := &exitError{}
<del> if err.Error() != "" {
<del> ee.cause = err
<del> }
<ide> if ec, ok := err.(exec.ExitCoder); ok {
<ide> ee.code = ec.ExitCode()
<ide> }
<add> select {
<add> case e := <-healthErr:
<add> ee.cause = e
<add> default:
<add> if err.Error() != "" {
<add> ee.cause = err
<add> }
<add> }
<ide> return ee
<ide> }
<add>
<ide> return nil
<ide> }
<ide>
<ide> func (r *controller) Close() error {
<ide> return nil
<ide> }
<ide>
<add>func (r *controller) matchevent(event events.Message) bool {
<add> if event.Type != events.ContainerEventType {
<add> return false
<add> }
<add>
<add> // TODO(stevvooe): Filter based on ID matching, in addition to name.
<add>
<add> // Make sure the events are for this container.
<add> if event.Actor.Attributes["name"] != r.adapter.container.name() {
<add> return false
<add> }
<add>
<add> return true
<add>}
<add>
<ide> func (r *controller) checkClosed() error {
<ide> select {
<ide> case <-r.closed:
<ide> func (e *exitError) ExitCode() int {
<ide> func (e *exitError) Cause() error {
<ide> return e.cause
<ide> }
<add>
<add>// checkHealth blocks until unhealthy container is detected or ctx exits
<add>func (r *controller) checkHealth(ctx context.Context) error {
<add> eventq := r.adapter.events(ctx)
<add>
<add> for {
<add> select {
<add> case <-ctx.Done():
<add> return nil
<add> case <-r.closed:
<add> return nil
<add> case event := <-eventq:
<add> if !r.matchevent(event) {
<add> continue
<add> }
<add>
<add> switch event.Action {
<add> case "health_status: unhealthy":
<add> return ErrContainerUnhealthy
<add> }
<add> }
<add> }
<add>}
<ide><path>daemon/cluster/executor/container/errors.go
<ide> var (
<ide> // ErrContainerDestroyed returned when a container is prematurely destroyed
<ide> // during a wait call.
<ide> ErrContainerDestroyed = fmt.Errorf("dockerexec: container destroyed")
<add>
<add> // ErrContainerUnhealthy returned if controller detects the health check failure
<add> ErrContainerUnhealthy = fmt.Errorf("dockerexec: unhealthy container")
<ide> )
<ide><path>daemon/cluster/executor/container/health_test.go
<add>// +build !windows
<add>
<add>package container
<add>
<add>import (
<add> "testing"
<add> "time"
<add>
<add> "github.com/docker/docker/container"
<add> "github.com/docker/docker/daemon"
<add> "github.com/docker/docker/daemon/events"
<add> containertypes "github.com/docker/engine-api/types/container"
<add> "github.com/docker/swarmkit/api"
<add> "golang.org/x/net/context"
<add>)
<add>
<add>func TestHealthStates(t *testing.T) {
<add>
<add> // set up environment: events, task, container ....
<add> e := events.New()
<add> _, l, _ := e.Subscribe()
<add> defer e.Evict(l)
<add>
<add> task := &api.Task{
<add> ID: "id",
<add> ServiceID: "sid",
<add> Spec: api.TaskSpec{
<add> Runtime: &api.TaskSpec_Container{
<add> Container: &api.ContainerSpec{
<add> Image: "image_name",
<add> Labels: map[string]string{
<add> "com.docker.swarm.task.id": "id",
<add> },
<add> },
<add> },
<add> },
<add> Annotations: api.Annotations{Name: "name"},
<add> }
<add>
<add> c := &container.Container{
<add> CommonContainer: container.CommonContainer{
<add> ID: "id",
<add> Name: "name",
<add> Config: &containertypes.Config{
<add> Image: "image_name",
<add> Labels: map[string]string{
<add> "com.docker.swarm.task.id": "id",
<add> },
<add> },
<add> },
<add> }
<add>
<add> daemon := &daemon.Daemon{
<add> EventsService: e,
<add> }
<add>
<add> controller, err := newController(daemon, task)
<add> if err != nil {
<add> t.Fatalf("create controller fail %v", err)
<add> }
<add>
<add> errChan := make(chan error, 1)
<add> ctx, cancel := context.WithCancel(context.Background())
<add> defer cancel()
<add>
<add> // fire checkHealth
<add> go func() {
<add> err := controller.checkHealth(ctx)
<add> select {
<add> case errChan <- err:
<add> case <-ctx.Done():
<add> }
<add> }()
<add>
<add> // send an event and expect to get expectedErr
<add> // if expectedErr is nil, shouldn't get any error
<add> logAndExpect := func(msg string, expectedErr error) {
<add> daemon.LogContainerEvent(c, msg)
<add>
<add> timer := time.NewTimer(1 * time.Second)
<add> defer timer.Stop()
<add>
<add> select {
<add> case err := <-errChan:
<add> if err != expectedErr {
<add> t.Fatalf("expect error %v, but get %v", expectedErr, err)
<add> }
<add> case <-timer.C:
<add> if expectedErr != nil {
<add> t.Fatalf("time limit exceeded, didn't get expected error")
<add> }
<add> }
<add> }
<add>
<add> // events that are ignored by checkHealth
<add> logAndExpect("health_status: running", nil)
<add> logAndExpect("health_status: healthy", nil)
<add> logAndExpect("die", nil)
<add>
<add> // unhealthy event will be caught by checkHealth
<add> logAndExpect("health_status: unhealthy", ErrContainerUnhealthy)
<add>} | 6 |
Python | Python | change exporter to allow dynamic batch inference | 4ddc9f2d806530ceb99a86a621075a4a9813df62 | <ide><path>object_detection/export_inference_graph.py
<ide>
<ide> The inference graph contains one of three input nodes depending on the user
<ide> specified option.
<del> * `image_tensor`: Accepts a uint8 4-D tensor of shape [1, None, None, 3]
<del> * `encoded_image_string_tensor`: Accepts a scalar string tensor of encoded PNG
<del> or JPEG image.
<del> * `tf_example`: Accepts a serialized TFExample proto. The batch size in this
<del> case is always 1.
<add> * `image_tensor`: Accepts a uint8 4-D tensor of shape [None, None, None, 3]
<add> * `encoded_image_string_tensor`: Accepts a 1-D string tensor of shape [None]
<add> containing encoded PNG or JPEG images. Image resolutions are expected to be
<add> the same if more than 1 image is provided.
<add> * `tf_example`: Accepts a 1-D string tensor of shape [None] containing
<add> serialized TFExample protos. Image resolutions are expected to be the same
<add> if more than 1 image is provided.
<ide>
<ide> and the following output nodes returned by the model.postprocess(..):
<ide> * `num_detections`: Outputs float32 tensors of the form [batch]
<ide> tensors returned by the model.
<ide>
<ide> Notes:
<del> * Currently `batch` is always 1, but we will support `batch` > 1 in the future.
<ide> * This tool uses `use_moving_averages` from eval_config to decide which
<ide> weights to freeze.
<ide>
<ide><path>object_detection/exporter.py
<ide> def freeze_graph_with_def_protos(
<ide> return output_graph_def
<ide>
<ide>
<del># TODO: Support batch tf example inputs.
<del>def _tf_example_input_placeholder():
<del> tf_example_placeholder = tf.placeholder(
<del> tf.string, shape=[], name='tf_example')
<del> tensor_dict = tf_example_decoder.TfExampleDecoder().decode(
<del> tf_example_placeholder)
<del> image = tensor_dict[fields.InputDataFields.image]
<del> return tf.expand_dims(image, axis=0)
<del>
<ide>
<ide> def _image_tensor_input_placeholder():
<add> """Returns input node that accepts a batch of uint8 images."""
<ide> return tf.placeholder(dtype=tf.uint8,
<del> shape=(1, None, None, 3),
<add> shape=(None, None, None, 3),
<ide> name='image_tensor')
<ide>
<ide>
<add>def _tf_example_input_placeholder():
<add> """Returns input node that accepts a batch of strings with tf examples."""
<add> batch_tf_example_placeholder = tf.placeholder(
<add> tf.string, shape=[None], name='tf_example')
<add> def decode(tf_example_string_tensor):
<add> tensor_dict = tf_example_decoder.TfExampleDecoder().decode(
<add> tf_example_string_tensor)
<add> image_tensor = tensor_dict[fields.InputDataFields.image]
<add> return image_tensor
<add> return tf.map_fn(decode,
<add> elems=batch_tf_example_placeholder,
<add> dtype=tf.uint8,
<add> parallel_iterations=32,
<add> back_prop=False)
<add>
<add>
<ide> def _encoded_image_string_tensor_input_placeholder():
<del> image_str = tf.placeholder(dtype=tf.string,
<del> shape=[],
<del> name='encoded_image_string_tensor')
<del> image_tensor = tf.image.decode_image(image_str, channels=3)
<del> image_tensor.set_shape((None, None, 3))
<del> return tf.expand_dims(image_tensor, axis=0)
<add> """Returns input node that accepts a batch of PNG or JPEG strings."""
<add> batch_image_str_placeholder = tf.placeholder(
<add> dtype=tf.string,
<add> shape=[None],
<add> name='encoded_image_string_tensor')
<add> def decode(encoded_image_string_tensor):
<add> image_tensor = tf.image.decode_image(encoded_image_string_tensor,
<add> channels=3)
<add> image_tensor.set_shape((None, None, 3))
<add> return image_tensor
<add> return tf.map_fn(decode,
<add> elems=batch_image_str_placeholder,
<add> dtype=tf.uint8,
<add> parallel_iterations=32,
<add> back_prop=False)
<ide>
<ide>
<ide> input_placeholder_fn_map = {
<ide><path>object_detection/exporter_test.py
<ide> def predict(self, preprocessed_inputs):
<ide> def postprocess(self, prediction_dict):
<ide> with tf.control_dependencies(prediction_dict.values()):
<ide> postprocessed_tensors = {
<del> 'detection_boxes': tf.constant([[0.0, 0.0, 0.5, 0.5],
<del> [0.5, 0.5, 0.8, 0.8]], tf.float32),
<del> 'detection_scores': tf.constant([[0.7, 0.6]], tf.float32),
<del> 'detection_classes': tf.constant([[0, 1]], tf.float32),
<del> 'num_detections': tf.constant([2], tf.float32)
<add> 'detection_boxes': tf.constant([[[0.0, 0.0, 0.5, 0.5],
<add> [0.5, 0.5, 0.8, 0.8]],
<add> [[0.5, 0.5, 1.0, 1.0],
<add> [0.0, 0.0, 0.0, 0.0]]], tf.float32),
<add> 'detection_scores': tf.constant([[0.7, 0.6],
<add> [0.9, 0.0]], tf.float32),
<add> 'detection_classes': tf.constant([[0, 1],
<add> [1, 0]], tf.float32),
<add> 'num_detections': tf.constant([2, 1], tf.float32)
<ide> }
<ide> if self._add_detection_masks:
<ide> postprocessed_tensors['detection_masks'] = tf.constant(
<del> np.arange(32).reshape([2, 4, 4]), tf.float32)
<add> np.arange(64).reshape([2, 2, 4, 4]), tf.float32)
<ide> return postprocessed_tensors
<ide>
<ide> def restore_map(self, checkpoint_path, from_detection_checkpoint):
<ide> def _save_checkpoint_from_mock_model(self, checkpoint_path,
<ide> with g.as_default():
<ide> mock_model = FakeModel()
<ide> preprocessed_inputs = mock_model.preprocess(
<del> tf.ones([1, 3, 4, 3], tf.float32))
<add> tf.placeholder(tf.float32, shape=[None, None, None, 3]))
<ide> predictions = mock_model.predict(preprocessed_inputs)
<ide> mock_model.postprocess(predictions)
<ide> if use_moving_averages:
<ide> def test_export_and_run_inference_with_image_tensor(self):
<ide> classes = inference_graph.get_tensor_by_name('detection_classes:0')
<ide> masks = inference_graph.get_tensor_by_name('detection_masks:0')
<ide> num_detections = inference_graph.get_tensor_by_name('num_detections:0')
<del> (boxes, scores, classes, masks, num_detections) = sess.run(
<add> (boxes_np, scores_np, classes_np, masks_np, num_detections_np) = sess.run(
<ide> [boxes, scores, classes, masks, num_detections],
<del> feed_dict={image_tensor: np.ones((1, 4, 4, 3)).astype(np.uint8)})
<del> self.assertAllClose(boxes, [[0.0, 0.0, 0.5, 0.5],
<del> [0.5, 0.5, 0.8, 0.8]])
<del> self.assertAllClose(scores, [[0.7, 0.6]])
<del> self.assertAllClose(classes, [[1, 2]])
<del> self.assertAllClose(masks, np.arange(32).reshape([2, 4, 4]))
<del> self.assertAllClose(num_detections, [2])
<add> feed_dict={image_tensor: np.ones((2, 4, 4, 3)).astype(np.uint8)})
<add> self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
<add> [0.5, 0.5, 0.8, 0.8]],
<add> [[0.5, 0.5, 1.0, 1.0],
<add> [0.0, 0.0, 0.0, 0.0]]])
<add> self.assertAllClose(scores_np, [[0.7, 0.6],
<add> [0.9, 0.0]])
<add> self.assertAllClose(classes_np, [[1, 2],
<add> [2, 1]])
<add> self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
<add> self.assertAllClose(num_detections_np, [2, 1])
<ide>
<ide> def _create_encoded_image_string(self, image_array_np, encoding_format):
<ide> od_graph = tf.Graph()
<ide> def test_export_and_run_inference_with_encoded_image_string_tensor(self):
<ide> masks = inference_graph.get_tensor_by_name('detection_masks:0')
<ide> num_detections = inference_graph.get_tensor_by_name('num_detections:0')
<ide> for image_str in [jpg_image_str, png_image_str]:
<add> image_str_batch_np = np.hstack([image_str]* 2)
<ide> (boxes_np, scores_np, classes_np, masks_np,
<ide> num_detections_np) = sess.run(
<ide> [boxes, scores, classes, masks, num_detections],
<del> feed_dict={image_str_tensor: image_str})
<del> self.assertAllClose(boxes_np, [[0.0, 0.0, 0.5, 0.5],
<del> [0.5, 0.5, 0.8, 0.8]])
<del> self.assertAllClose(scores_np, [[0.7, 0.6]])
<del> self.assertAllClose(classes_np, [[1, 2]])
<del> self.assertAllClose(masks_np, np.arange(32).reshape([2, 4, 4]))
<del> self.assertAllClose(num_detections_np, [2])
<add> feed_dict={image_str_tensor: image_str_batch_np})
<add> self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
<add> [0.5, 0.5, 0.8, 0.8]],
<add> [[0.5, 0.5, 1.0, 1.0],
<add> [0.0, 0.0, 0.0, 0.0]]])
<add> self.assertAllClose(scores_np, [[0.7, 0.6],
<add> [0.9, 0.0]])
<add> self.assertAllClose(classes_np, [[1, 2],
<add> [2, 1]])
<add> self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
<add> self.assertAllClose(num_detections_np, [2, 1])
<add>
<add> def test_raise_runtime_error_on_images_with_different_sizes(self):
<add> tmp_dir = self.get_temp_dir()
<add> trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt')
<add> self._save_checkpoint_from_mock_model(trained_checkpoint_prefix,
<add> use_moving_averages=True)
<add> output_directory = os.path.join(tmp_dir, 'output')
<add> inference_graph_path = os.path.join(output_directory,
<add> 'frozen_inference_graph.pb')
<add> with mock.patch.object(
<add> model_builder, 'build', autospec=True) as mock_builder:
<add> mock_builder.return_value = FakeModel(add_detection_masks=True)
<add> pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
<add> pipeline_config.eval_config.use_moving_averages = False
<add> exporter.export_inference_graph(
<add> input_type='encoded_image_string_tensor',
<add> pipeline_config=pipeline_config,
<add> trained_checkpoint_prefix=trained_checkpoint_prefix,
<add> output_directory=output_directory)
<add>
<add> inference_graph = self._load_inference_graph(inference_graph_path)
<add> large_image = self._create_encoded_image_string(
<add> np.ones((4, 4, 3)).astype(np.uint8), 'jpg')
<add> small_image = self._create_encoded_image_string(
<add> np.ones((2, 2, 3)).astype(np.uint8), 'jpg')
<add>
<add> image_str_batch_np = np.hstack([large_image, small_image])
<add> with self.test_session(graph=inference_graph) as sess:
<add> image_str_tensor = inference_graph.get_tensor_by_name(
<add> 'encoded_image_string_tensor:0')
<add> boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
<add> scores = inference_graph.get_tensor_by_name('detection_scores:0')
<add> classes = inference_graph.get_tensor_by_name('detection_classes:0')
<add> masks = inference_graph.get_tensor_by_name('detection_masks:0')
<add> num_detections = inference_graph.get_tensor_by_name('num_detections:0')
<add> with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,
<add> '^TensorArray has inconsistent shapes.'):
<add> sess.run([boxes, scores, classes, masks, num_detections],
<add> feed_dict={image_str_tensor: image_str_batch_np})
<ide>
<ide> def test_export_and_run_inference_with_tf_example(self):
<ide> tmp_dir = self.get_temp_dir()
<ide> def test_export_and_run_inference_with_tf_example(self):
<ide> output_directory=output_directory)
<ide>
<ide> inference_graph = self._load_inference_graph(inference_graph_path)
<add> tf_example_np = np.expand_dims(self._create_tf_example(
<add> np.ones((4, 4, 3)).astype(np.uint8)), axis=0)
<ide> with self.test_session(graph=inference_graph) as sess:
<ide> tf_example = inference_graph.get_tensor_by_name('tf_example:0')
<ide> boxes = inference_graph.get_tensor_by_name('detection_boxes:0')
<ide> scores = inference_graph.get_tensor_by_name('detection_scores:0')
<ide> classes = inference_graph.get_tensor_by_name('detection_classes:0')
<ide> masks = inference_graph.get_tensor_by_name('detection_masks:0')
<ide> num_detections = inference_graph.get_tensor_by_name('num_detections:0')
<del> (boxes, scores, classes, masks, num_detections) = sess.run(
<add> (boxes_np, scores_np, classes_np, masks_np, num_detections_np) = sess.run(
<ide> [boxes, scores, classes, masks, num_detections],
<del> feed_dict={tf_example: self._create_tf_example(
<del> np.ones((4, 4, 3)).astype(np.uint8))})
<del> self.assertAllClose(boxes, [[0.0, 0.0, 0.5, 0.5],
<del> [0.5, 0.5, 0.8, 0.8]])
<del> self.assertAllClose(scores, [[0.7, 0.6]])
<del> self.assertAllClose(classes, [[1, 2]])
<del> self.assertAllClose(masks, np.arange(32).reshape([2, 4, 4]))
<del> self.assertAllClose(num_detections, [2])
<add> feed_dict={tf_example: tf_example_np})
<add> self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
<add> [0.5, 0.5, 0.8, 0.8]],
<add> [[0.5, 0.5, 1.0, 1.0],
<add> [0.0, 0.0, 0.0, 0.0]]])
<add> self.assertAllClose(scores_np, [[0.7, 0.6],
<add> [0.9, 0.0]])
<add> self.assertAllClose(classes_np, [[1, 2],
<add> [2, 1]])
<add> self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
<add> self.assertAllClose(num_detections_np, [2, 1])
<ide>
<ide> def test_export_saved_model_and_run_inference(self):
<ide> tmp_dir = self.get_temp_dir()
<ide> def test_export_saved_model_and_run_inference(self):
<ide> trained_checkpoint_prefix=trained_checkpoint_prefix,
<ide> output_directory=output_directory)
<ide>
<add> tf_example_np = np.hstack([self._create_tf_example(
<add> np.ones((4, 4, 3)).astype(np.uint8))] * 2)
<ide> with tf.Graph().as_default() as od_graph:
<ide> with self.test_session(graph=od_graph) as sess:
<ide> tf.saved_model.loader.load(
<ide> def test_export_saved_model_and_run_inference(self):
<ide> classes = od_graph.get_tensor_by_name('detection_classes:0')
<ide> masks = od_graph.get_tensor_by_name('detection_masks:0')
<ide> num_detections = od_graph.get_tensor_by_name('num_detections:0')
<del> (boxes, scores, classes, masks, num_detections) = sess.run(
<del> [boxes, scores, classes, masks, num_detections],
<del> feed_dict={tf_example: self._create_tf_example(
<del> np.ones((4, 4, 3)).astype(np.uint8))})
<del> self.assertAllClose(boxes, [[0.0, 0.0, 0.5, 0.5],
<del> [0.5, 0.5, 0.8, 0.8]])
<del> self.assertAllClose(scores, [[0.7, 0.6]])
<del> self.assertAllClose(classes, [[1, 2]])
<del> self.assertAllClose(masks, np.arange(32).reshape([2, 4, 4]))
<del> self.assertAllClose(num_detections, [2])
<add> (boxes_np, scores_np, classes_np, masks_np,
<add> num_detections_np) = sess.run(
<add> [boxes, scores, classes, masks, num_detections],
<add> feed_dict={tf_example: tf_example_np})
<add> self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
<add> [0.5, 0.5, 0.8, 0.8]],
<add> [[0.5, 0.5, 1.0, 1.0],
<add> [0.0, 0.0, 0.0, 0.0]]])
<add> self.assertAllClose(scores_np, [[0.7, 0.6],
<add> [0.9, 0.0]])
<add> self.assertAllClose(classes_np, [[1, 2],
<add> [2, 1]])
<add> self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
<add> self.assertAllClose(num_detections_np, [2, 1])
<ide>
<ide> def test_export_checkpoint_and_run_inference(self):
<ide> tmp_dir = self.get_temp_dir()
<ide> def test_export_checkpoint_and_run_inference(self):
<ide> trained_checkpoint_prefix=trained_checkpoint_prefix,
<ide> output_directory=output_directory)
<ide>
<add> tf_example_np = np.hstack([self._create_tf_example(
<add> np.ones((4, 4, 3)).astype(np.uint8))] * 2)
<ide> with tf.Graph().as_default() as od_graph:
<ide> with self.test_session(graph=od_graph) as sess:
<ide> new_saver = tf.train.import_meta_graph(meta_graph_path)
<ide> def test_export_checkpoint_and_run_inference(self):
<ide> classes = od_graph.get_tensor_by_name('detection_classes:0')
<ide> masks = od_graph.get_tensor_by_name('detection_masks:0')
<ide> num_detections = od_graph.get_tensor_by_name('num_detections:0')
<del> (boxes, scores, classes, masks, num_detections) = sess.run(
<del> [boxes, scores, classes, masks, num_detections],
<del> feed_dict={tf_example: self._create_tf_example(
<del> np.ones((4, 4, 3)).astype(np.uint8))})
<del> self.assertAllClose(boxes, [[0.0, 0.0, 0.5, 0.5],
<del> [0.5, 0.5, 0.8, 0.8]])
<del> self.assertAllClose(scores, [[0.7, 0.6]])
<del> self.assertAllClose(classes, [[1, 2]])
<del> self.assertAllClose(masks, np.arange(32).reshape([2, 4, 4]))
<del> self.assertAllClose(num_detections, [2])
<add> (boxes_np, scores_np, classes_np, masks_np,
<add> num_detections_np) = sess.run(
<add> [boxes, scores, classes, masks, num_detections],
<add> feed_dict={tf_example: tf_example_np})
<add> self.assertAllClose(boxes_np, [[[0.0, 0.0, 0.5, 0.5],
<add> [0.5, 0.5, 0.8, 0.8]],
<add> [[0.5, 0.5, 1.0, 1.0],
<add> [0.0, 0.0, 0.0, 0.0]]])
<add> self.assertAllClose(scores_np, [[0.7, 0.6],
<add> [0.9, 0.0]])
<add> self.assertAllClose(classes_np, [[1, 2],
<add> [2, 1]])
<add> self.assertAllClose(masks_np, np.arange(64).reshape([2, 2, 4, 4]))
<add> self.assertAllClose(num_detections_np, [2, 1])
<ide>
<ide>
<ide> if __name__ == '__main__': | 3 |
Text | Text | fix typo in faq | 7b4e6ef50c5989bce69574e1487901ff5b381f58 | <ide><path>docs/sources/faq.md
<ide> You can build a Theano function that will return the output of a certain layer g
<ide> # with a Sequential model
<ide> get_3rd_layer_output = theano.function([model.layers[0].input],
<ide> model.layers[3].get_output(train=False))
<del>3rd_layer_output = get_3rd_layer_output(X)
<add>layer_output = get_3rd_layer_output(X)
<ide>
<ide> # with a Graph model
<ide> get_conv_layer_output = theano.function([model.inputs[i].input for i in model.input_order], | 1 |
Ruby | Ruby | clarify control flow | b367830af7fb75cd59863b3a1311d4a5bc4b37a8 | <ide><path>lib/active_job/parameters.rb
<ide>
<ide> module ActiveJob
<ide> class Parameters
<del> TYPE_WHITELIST = [NilClass, Fixnum, Float, String, TrueClass, FalseClass, Hash, Array, Bignum]
<add> TYPE_WHITELIST = [ NilClass, Fixnum, Float, String, TrueClass, FalseClass, Hash, Array, Bignum ]
<ide>
<ide> def self.serialize(params)
<ide> params.collect do |param|
<del> raise "Unsupported parameter type: #{param.class.name}" unless param.respond_to?(:global_id) || TYPE_WHITELIST.include?(param.class)
<del> param.try(:global_id) || param
<add> if param.respond_to?(:global_id)
<add> param.global_id
<add> elsif TYPE_WHITELIST.include?(param.class)
<add> param
<add> else
<add> raise "Unsupported parameter type: #{param.class.name}"
<add> end
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | fix cs error | 27a4ea25d3ae770664135f6e7f287b6221a47b47 | <ide><path>src/Mailer/Mailer.php
<ide> public function getTransport(): AbstractTransport
<ide> {
<ide> if ($this->transport === null) {
<ide> throw new BadMethodCallException(
<del> 'Transport was not defined. You must set on using setTransport() or set `transport` option in your mailer profile.'
<add> 'Transport was not defined. '
<add> . 'You must set on using setTransport() or set `transport` option in your mailer profile.'
<ide> );
<ide> }
<ide>
<ide><path>src/Mailer/Renderer.php
<ide> public function reset()
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Clone ViewBuilder instance when renderer is cloned.
<add> *
<add> * @return void
<add> */
<ide> public function __clone()
<ide> {
<ide> if ($this->_viewBuilder !== null) {
<ide><path>src/Mailer/Transport/SmtpTransport.php
<ide> protected function _sendData(Message $message): void
<ide> 'to',
<ide> 'cc',
<ide> 'subject',
<del> 'returnPath'
<add> 'returnPath',
<ide> ]);
<ide> $message = $this->_prepareMessage($message);
<ide> | 3 |
Text | Text | add code example to inspector.url() method | 411360150aff0ab2daaf00a0710822555d10e26a | <ide><path>doc/api/inspector.md
<ide> parameter usage.
<ide>
<ide> Return the URL of the active inspector, or `undefined` if there is none.
<ide>
<add>```console
<add>$ node --inspect -p 'inspector.url()'
<add>Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
<add>For help see https://nodejs.org/en/docs/inspector
<add>ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
<add>
<add>$ node --inspect=localhost:3000 -p 'inspector.url()'
<add>Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
<add>For help see https://nodejs.org/en/docs/inspector
<add>ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
<add>
<add>$ node -p 'inspector.url()'
<add>undefined
<add>```
<add>
<ide> ## inspector.waitForDebugger()
<ide> <!-- YAML
<ide> added: v12.7.0 | 1 |
Ruby | Ruby | add gcc 4.0 to compilerselector compiler queue | 6e3cb9f735165ecdda5bcc3d6cd656fa29872c5a | <ide><path>Library/Homebrew/compilers.rb
<ide> def initialize(f, old_compiler)
<ide> @f = f
<ide> @old_compiler = old_compiler
<ide> @compilers = CompilerQueue.new
<del> %w{clang llvm gcc}.map(&:to_sym).each do |cc|
<add> %w{clang llvm gcc gcc_4_0}.map(&:to_sym).each do |cc|
<ide> unless MacOS.send("#{cc}_build_version").nil?
<ide> @compilers << Compiler.new(cc, priority_for(cc))
<ide> end | 1 |
PHP | PHP | add response helper | b43ba4f4277f7a1fb9a2544e290b0b994ab9f57b | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function redirect($to = null, $status = 302)
<ide> }
<ide> }
<ide>
<add>if ( ! function_exists('response'))
<add>{
<add> /**
<add> * Return a new response from the application.
<add> *
<add> * @param string $content
<add> * @param int $status
<add> * @param array $headers
<add> * @return \Symfony\Component\HttpFoundation\Response
<add> */
<add> function response($content = '', $status = 200, array $headers = array())
<add> {
<add> return app('Illuminate\Contracts\Routing\ResponseFactory')->make($content, $status, $headers);
<add> }
<add>}
<add>
<ide> if ( ! function_exists('route'))
<ide> {
<ide> /** | 1 |
Python | Python | return subclasses from ediff1d | 9a90abf995d0d8d9e96992a083dc55a41a93254f | <ide><path>numpy/lib/arraysetops.py
<ide> def ediff1d(ary, to_end=None, to_begin=None):
<ide> if to_begin is None and to_end is None:
<ide> return ary[1:] - ary[:-1]
<ide>
<del> # get the length of the diff'd values
<del> l = len(ary) - 1
<del> if l < 0:
<del> # force length to be non negative, match previous API
<del> # should this be an warning or deprecated?
<del> l = 0
<del>
<ide> if to_begin is None:
<del> to_begin = np.array([])
<add> l_begin = 0
<ide> else:
<ide> to_begin = np.asanyarray(to_begin).ravel()
<add> l_begin = len(to_begin)
<ide>
<ide> if to_end is None:
<del> to_end = np.array([])
<add> l_end = 0
<ide> else:
<ide> to_end = np.asanyarray(to_end).ravel()
<add> l_end = len(to_end)
<ide>
<ide> # do the calculation in place and copy to_begin and to_end
<del> result = np.empty(l + len(to_begin) + len(to_end), dtype=ary.dtype)
<del> result[:len(to_begin)] = to_begin
<del> result[len(to_begin) + l:] = to_end
<del> np.subtract(ary[1:], ary[:-1], result[len(to_begin):len(to_begin) + l])
<add> l_diff = max(len(ary) - 1, 0)
<add> result = np.empty(l_diff + l_begin + l_end, dtype=ary.dtype)
<add> result = ary.__array_wrap__(result)
<add> if l_begin > 0:
<add> result[:l_begin] = to_begin
<add> if l_end > 0:
<add> result[l_begin + l_diff:] = to_end
<add> np.subtract(ary[1:], ary[:-1], result[l_begin:l_begin + l_diff])
<ide> return result
<ide>
<ide>
<ide><path>numpy/lib/tests/test_arraysetops.py
<ide> def test_ediff1d(self):
<ide> assert_array_equal([1,7,8], ediff1d(two_elem, to_end=[7,8]))
<ide> assert_array_equal([7,1], ediff1d(two_elem, to_begin=7))
<ide> assert_array_equal([5,6,1], ediff1d(two_elem, to_begin=[5,6]))
<add> assert(isinstance(ediff1d(np.matrix(1)), np.matrix))
<add> assert(isinstance(ediff1d(np.matrix(1), to_begin=1), np.matrix))
<ide>
<ide> def test_in1d(self):
<ide> # we use two different sizes for the b array here to test the | 2 |
Python | Python | add pause and unpause subcommands to cli | b7cfa3c6082b33be0d374a17a79a43416cf7c8cc | <ide><path>airflow/bin/cli.py
<ide> def trigger_dag(args):
<ide> session.commit()
<ide>
<ide>
<del>def dag_state(args):
<add>def pause(args):
<add> set_is_paused(True, args)
<add>
<add>
<add>def unpause(args):
<add> set_is_paused(False, args)
<add>
<add>
<add>def set_is_paused(is_paused, args):
<ide> dagbag = DagBag(process_subdir(args.subdir))
<ide> if args.dag_id not in dagbag.dags:
<ide> raise AirflowException('dag_id could not be found')
<ide> dag = dagbag.dags[args.dag_id]
<ide>
<del> if args.pause or args.un_pause is not None:
<del> session = settings.Session()
<del> dm = session.query(DagModel).filter(
<del> DagModel.dag_id == dag.dag_id).first()
<del> dm.is_paused = args.pause or args.un_pause
<del> session.commit()
<add> session = settings.Session()
<add> dm = session.query(DagModel).filter(
<add> DagModel.dag_id == dag.dag_id).first()
<add> dm.is_paused = is_paused
<add> session.commit()
<ide>
<ide> msg = "Dag: {}, paused: {}".format(dag, str(dag.is_paused))
<ide> print(msg)
<ide> def get_parser():
<ide> help="Helps to indentify this run")
<ide> parser_trigger_dag.set_defaults(func=trigger_dag)
<ide>
<del> ht = "Get or set the state of a DAG"
<del> parser_dag_state = subparsers.add_parser('dag_state', help=ht)
<del> parser_dag_state.add_argument("dag_id", help="The id of the dag to check")
<del> parser_dag_state.add_argument(
<add> ht = "Pause a DAG"
<add> parser_pause = subparsers.add_parser('pause', help=ht)
<add> parser_pause.add_argument("dag_id", help="The id of the dag to pause")
<add> parser_pause.add_argument(
<ide> "-sd", "--subdir", help=subdir_help,
<ide> default=DAGS_FOLDER)
<del> dag_state_pause_group = parser_dag_state.add_mutually_exclusive_group()
<del> dag_state_pause_group.add_argument(
<del> "-p", "--pause",
<del> help="Pause this dag",
<del> action="store_true")
<del> dag_state_pause_group.add_argument(
<del> "-u", "--un-pause",
<del> help="Unpause this dag",
<del> action="store_false")
<del> parser_dag_state.set_defaults(func=dag_state)
<add> parser_pause.set_defaults(func=pause)
<add>
<add> ht = "Unpause a DAG"
<add> parser_unpause = subparsers.add_parser('unpause', help=ht)
<add> parser_unpause.add_argument("dag_id", help="The id of the dag to unpause")
<add> parser_unpause.add_argument(
<add> "-sd", "--subdir", help=subdir_help,
<add> default=DAGS_FOLDER)
<add> parser_unpause.set_defaults(func=unpause)
<ide>
<ide> ht = "Run a single task instance"
<ide> parser_run = subparsers.add_parser('run', help=ht)
<ide><path>tests/core.py
<ide> def test_task_state(self):
<ide> 'task_state', 'example_bash_operator', 'runme_0',
<ide> DEFAULT_DATE.isoformat()]))
<ide>
<del> def test_dag_state(self):
<del> for dag_id in self.dagbag.dags.keys():
<del> args = self.parser.parse_args(['dag_state', dag_id])
<del> cli.dag_state(args)
<del>
<add> def test_pause(self):
<ide> args = self.parser.parse_args([
<del> 'dag_state', 'example_bash_operator', '--pause'])
<del> cli.dag_state(args)
<add> 'pause', 'example_bash_operator'])
<add> cli.pause(args)
<ide> assert self.dagbag.dags['example_bash_operator'].is_paused in [True, 1]
<ide>
<ide> args = self.parser.parse_args([
<del> 'dag_state', 'example_bash_operator', '--un-pause'])
<del> cli.dag_state(args)
<add> 'unpause', 'example_bash_operator'])
<add> cli.unpause(args)
<ide> assert self.dagbag.dags['example_bash_operator'].is_paused in [False, 0]
<ide>
<ide> def test_backfill(self): | 2 |
Ruby | Ruby | address changes from review | 15102a3234bae24a1aeeb458ccb0182f4685788d | <ide><path>Library/Homebrew/livecheck/strategy/electron_builder.rb
<del># typed: false
<add># typed: true
<ide> # frozen_string_literal: true
<ide>
<ide> module Homebrew
<ide> class ElectronBuilder
<ide> PRIORITY = 0
<ide>
<ide> # The `Regexp` used to determine if the strategy applies to the URL.
<del> URL_MATCH_REGEX = %r{^https?://.+?/.+?\.yml}i.freeze
<add> URL_MATCH_REGEX = %r{^https?://.+/.+\.ya?ml$}i.freeze
<ide>
<ide> # Whether the strategy can be applied to the provided URL.
<ide> #
<ide> def self.match?(url)
<ide> #
<ide> # @param content [String] the content to check
<ide> # @return [String]
<del> sig { params(content: String).returns(T.nilable(String)) }
<del> def self.version_from_content(content)
<add> sig {
<add> params(
<add> content: String,
<add> block: T.nilable(T.proc.params(arg0: Hash).returns(String)),
<add> ).returns(T.nilable(String))
<add> }
<add> def self.version_from_content(content, &block)
<ide> require "yaml"
<ide>
<del> return unless (item = YAML.safe_load(content))
<add> return unless (yaml = YAML.safe_load(content))
<ide>
<del> item["version"]
<add> if block
<add> value = block.call(yaml)
<add> return value if value.is_a?(String)
<add>
<add> raise TypeError, "Return value of `strategy :electron_builder` block must be a string."
<add> end
<add>
<add> yaml["version"]
<ide> end
<ide>
<ide> # Checks the content at the URL for new versions.
<ide> #
<ide> # @param url [String] the URL of the content to check
<ide> # @param regex [Regexp] a regex used for matching versions in content
<ide> # @return [Hash]
<del> sig { params(url: String, regex: T.nilable(Regexp)).returns(T::Hash[Symbol, T.untyped]) }
<add> sig {
<add> params(
<add> url: String,
<add> regex: T.nilable(Regexp),
<add> block: T.nilable(T.proc.params(arg0: Hash).returns(String)),
<add> ).returns(T::Hash[Symbol, T.untyped])
<add> }
<ide> def self.find_versions(url, regex = nil, &block)
<ide> raise ArgumentError, "The #{T.must(name).demodulize} strategy does not support a regex." if regex
<ide>
<ide> def self.find_versions(url, regex = nil, &block)
<ide> match_data.merge!(Strategy.page_content(url))
<ide> content = match_data.delete(:content)
<ide>
<del> if (item = version_from_content(content))
<del> match = if block
<del> block.call(item)&.to_s
<del> else
<del> item
<del> end
<del>
<del> match_data[:matches][match] = Version.new(match) if match
<del> end
<add> version = version_from_content(content, &block)
<add> match_data[:matches][version] = Version.new(version) if version
<ide>
<ide> match_data
<ide> end
<ide><path>Library/Homebrew/test/livecheck/strategy/electron_builder_spec.rb
<ide> subject(:electron_builder) { described_class }
<ide>
<ide> let(:valid_url) { "https://www.example.com/example/latest-mac.yml" }
<del> let(:invalid_url) { "https://www.example.com/example/example" }
<add> let(:invalid_url) { "https://brew.sh/test" }
<ide>
<ide> let(:electron_builder_yaml) {
<ide> <<~EOS
<ide> it "returns a version string when given YAML data" do
<ide> expect(version_from_electron_builder_yaml).to be_a(String)
<ide> end
<add>
<add> it "returns a version string when given YAML data and a block" do
<add> version = electron_builder.version_from_content(electron_builder_yaml) do |yaml|
<add> yaml["version"].sub("3", "4")
<add> end
<add>
<add> expect(version).to eq "1.2.4"
<add> end
<ide> end
<ide> end | 2 |
Ruby | Ruby | use binread to read the files | 0155bf4021e34c70b3b88eaf75ce41e1140fe474 | <ide><path>actionpack/lib/action_view/template/resolver.rb
<ide> require "pathname"
<ide> require "active_support/core_ext/class"
<add>require "active_support/core_ext/io"
<ide> require "action_view/template"
<ide>
<ide> module ActionView
<ide> def query(path, details, formats)
<ide> next if File.directory?(p) || !sanitizer[p].include?(p)
<ide>
<ide> handler, format = extract_handler_and_format(p, formats)
<del> contents = File.open(p, "rb") { |io| io.read }
<add> contents = File.binread p
<ide>
<ide> templates << Template.new(contents, File.expand_path(p), handler,
<ide> :virtual_path => path.virtual, :format => format, :updated_at => mtime(p)) | 1 |
Text | Text | fix animation example code | d8e9eb978b3b2bbee7bfaf94dccb25fc8a3fd8ec | <ide><path>docs/docs/09.1-animation.md
<ide> var TodoList = React.createClass({
<ide> render: function() {
<ide> var items = this.state.items.map(function(item, i) {
<ide> return (
<del> <div key={i} onClick={this.handleRemove.bind(this, i)}>
<add> <div key={item} onClick={this.handleRemove.bind(this, i)}>
<ide> {item}
<ide> </div>
<ide> ); | 1 |
Javascript | Javascript | remove two obsolete pummel tests | 8e1a8ffe24867192379cf92d329d9babc94a58f6 | <ide><path>test/pummel/test-buffer-big.js
<del>'use strict';
<del>var common = require('../common');
<del>var assert = require('assert');
<del>
<del>// The tests below should throw an error, not abort the process...
<del>assert.throws(function() { new Buffer(0x3fffffff + 1); }, RangeError);
<del>assert.throws(function() { new Int8Array(0x3fffffff + 1); }, RangeError);
<del>assert.throws(function() { new ArrayBuffer(0x3fffffff + 1); }, RangeError);
<del>assert.throws(function() { new Float64Array(0x7ffffff + 1); }, RangeError);
<ide><path>test/pummel/test-fs-readfile-large.js
<del>'use strict';
<del>var common = require('../common');
<del>var assert = require('assert');
<del>
<del>var path = require('path'),
<del> fs = require('fs'),
<del> filename = path.join(common.fixturesDir, 'large_file.txt');
<del>
<del>var filesize = 1024 * 1024 * 1024;
<del>
<del>function makeFile(done) {
<del> var buf = new Buffer(filesize / 1024);
<del> buf.fill('a');
<del>
<del> try { fs.unlinkSync(filename); } catch (e) {}
<del> var w = 1024;
<del> var ws = fs.createWriteStream(filename);
<del> ws.on('close', done);
<del> ws.on('drain', write);
<del> write();
<del> function write() {
<del> do {
<del> w--;
<del> } while (false !== ws.write(buf) && w > 0);
<del> if (w === 0)
<del> ws.end();
<del> }
<del>}
<del>
<del>makeFile(function() {
<del> fs.readFile(filename, function(err) {
<del> assert.ok(err, 'should get RangeError');
<del> assert.equal(err.name, 'RangeError', 'should get RangeError');
<del> try { fs.unlinkSync(filename); } catch (e) {}
<del> });
<del>});
<del>
<del>process.on('uncaughtException', function(err) {
<del> assert.ok(!err, 'should not throw uncaughtException');
<del>}); | 2 |
Go | Go | cap the amount of buffering done by bytespipe | 64f8ee444d23ae29a236f169f1d7faf7042b524a | <ide><path>daemon/container.go
<ide> func (streamConfig *streamConfig) StdinPipe() io.WriteCloser {
<ide> }
<ide>
<ide> func (streamConfig *streamConfig) StdoutPipe() io.ReadCloser {
<del> reader, writer := io.Pipe()
<del> streamConfig.stdout.Add(writer)
<del> return ioutils.NewBufReader(reader)
<add> bytesPipe := ioutils.NewBytesPipe(nil)
<add> streamConfig.stdout.Add(bytesPipe)
<add> return bytesPipe
<ide> }
<ide>
<ide> func (streamConfig *streamConfig) StderrPipe() io.ReadCloser {
<del> reader, writer := io.Pipe()
<del> streamConfig.stderr.Add(writer)
<del> return ioutils.NewBufReader(reader)
<add> bytesPipe := ioutils.NewBytesPipe(nil)
<add> streamConfig.stderr.Add(bytesPipe)
<add> return bytesPipe
<ide> }
<ide>
<ide> // ExitOnNext signals to the monitor that it should not restart the container
<ide><path>pkg/ioutils/bytespipe.go
<ide> package ioutils
<ide>
<add>import (
<add> "errors"
<add> "io"
<add> "sync"
<add>)
<add>
<add>// maxCap is the highest capacity to use in byte slices that buffer data.
<ide> const maxCap = 1e6
<ide>
<del>// BytesPipe is io.ReadWriter which works similarly to pipe(queue).
<del>// All written data could be read only once. Also BytesPipe is allocating
<del>// and releasing new byte slices to adjust to current needs, so there won't be
<del>// overgrown buffer after high load peak.
<del>// BytesPipe isn't goroutine-safe, caller must synchronize it if needed.
<add>// blockThreshold is the minimum number of bytes in the buffer which will cause
<add>// a write to BytesPipe to block when allocating a new slice.
<add>const blockThreshold = 1e6
<add>
<add>// ErrClosed is returned when Write is called on a closed BytesPipe.
<add>var ErrClosed = errors.New("write to closed BytesPipe")
<add>
<add>// BytesPipe is io.ReadWriteCloser which works similarly to pipe(queue).
<add>// All written data may be read at most once. Also, BytesPipe allocates
<add>// and releases new byte slices to adjust to current needs, so the buffer
<add>// won't be overgrown after peak loads.
<ide> type BytesPipe struct {
<add> mu sync.Mutex
<add> wait *sync.Cond
<ide> buf [][]byte // slice of byte-slices of buffered data
<ide> lastRead int // index in the first slice to a read point
<ide> bufLen int // length of data buffered over the slices
<add> closeErr error // error to return from next Read. set to nil if not closed.
<ide> }
<ide>
<ide> // NewBytesPipe creates new BytesPipe, initialized by specified slice.
<ide> func NewBytesPipe(buf []byte) *BytesPipe {
<ide> if cap(buf) == 0 {
<ide> buf = make([]byte, 0, 64)
<ide> }
<del> return &BytesPipe{
<add> bp := &BytesPipe{
<ide> buf: [][]byte{buf[:0]},
<ide> }
<add> bp.wait = sync.NewCond(&bp.mu)
<add> return bp
<ide> }
<ide>
<ide> // Write writes p to BytesPipe.
<ide> // It can allocate new []byte slices in a process of writing.
<del>func (bp *BytesPipe) Write(p []byte) (n int, err error) {
<add>func (bp *BytesPipe) Write(p []byte) (int, error) {
<add> bp.mu.Lock()
<add> defer bp.mu.Unlock()
<add> written := 0
<ide> for {
<add> if bp.closeErr != nil {
<add> return written, ErrClosed
<add> }
<ide> // write data to the last buffer
<ide> b := bp.buf[len(bp.buf)-1]
<ide> // copy data to the current empty allocated area
<ide> func (bp *BytesPipe) Write(p []byte) (n int, err error) {
<ide> // include written data in last buffer
<ide> bp.buf[len(bp.buf)-1] = b[:len(b)+n]
<ide>
<add> written += n
<add>
<ide> // if there was enough room to write all then break
<ide> if len(p) == n {
<ide> break
<ide> }
<ide>
<ide> // more data: write to the next slice
<ide> p = p[n:]
<add>
<add> // block if too much data is still in the buffer
<add> for bp.bufLen >= blockThreshold {
<add> bp.wait.Wait()
<add> }
<add>
<ide> // allocate slice that has twice the size of the last unless maximum reached
<ide> nextCap := 2 * cap(bp.buf[len(bp.buf)-1])
<del> if maxCap < nextCap {
<add> if nextCap > maxCap {
<ide> nextCap = maxCap
<ide> }
<ide> // add new byte slice to the buffers slice and continue writing
<ide> bp.buf = append(bp.buf, make([]byte, 0, nextCap))
<ide> }
<del> return
<add> bp.wait.Broadcast()
<add> return written, nil
<add>}
<add>
<add>// CloseWithError causes further reads from a BytesPipe to return immediately.
<add>func (bp *BytesPipe) CloseWithError(err error) error {
<add> bp.mu.Lock()
<add> if err != nil {
<add> bp.closeErr = err
<add> } else {
<add> bp.closeErr = io.EOF
<add> }
<add> bp.wait.Broadcast()
<add> bp.mu.Unlock()
<add> return nil
<add>}
<add>
<add>// Close causes further reads from a BytesPipe to return immediately.
<add>func (bp *BytesPipe) Close() error {
<add> return bp.CloseWithError(nil)
<ide> }
<ide>
<ide> func (bp *BytesPipe) len() int {
<ide> func (bp *BytesPipe) len() int {
<ide> // Read reads bytes from BytesPipe.
<ide> // Data could be read only once.
<ide> func (bp *BytesPipe) Read(p []byte) (n int, err error) {
<add> bp.mu.Lock()
<add> defer bp.mu.Unlock()
<add> if bp.len() == 0 {
<add> if bp.closeErr != nil {
<add> return 0, bp.closeErr
<add> }
<add> bp.wait.Wait()
<add> if bp.len() == 0 && bp.closeErr != nil {
<add> return 0, bp.closeErr
<add> }
<add> }
<ide> for {
<ide> read := copy(p, bp.buf[0][bp.lastRead:])
<ide> n += read
<ide> func (bp *BytesPipe) Read(p []byte) (n int, err error) {
<ide> bp.buf[0] = nil // throw away old slice
<ide> bp.buf = bp.buf[1:] // switch to next
<ide> }
<add> bp.wait.Broadcast()
<ide> return
<ide> }
<ide><path>pkg/ioutils/bytespipe_test.go
<ide> package ioutils
<ide> import (
<ide> "crypto/sha1"
<ide> "encoding/hex"
<add> "math/rand"
<ide> "testing"
<add> "time"
<ide> )
<ide>
<ide> func TestBytesPipeRead(t *testing.T) {
<ide> func TestBytesPipeWriteRandomChunks(t *testing.T) {
<ide> // write/read through buffer
<ide> buf := NewBytesPipe(nil)
<ide> hash.Reset()
<del> for i := 0; i < c.iterations; i++ {
<del> for w := 0; w < c.writesPerLoop; w++ {
<del> buf.Write(testMessage[:writeChunks[(i*c.writesPerLoop+w)%len(writeChunks)]])
<del> }
<del> for r := 0; r < c.readsPerLoop; r++ {
<del> p := make([]byte, readChunks[(i*c.readsPerLoop+r)%len(readChunks)])
<add>
<add> done := make(chan struct{})
<add>
<add> go func() {
<add> // random delay before read starts
<add> <-time.After(time.Duration(rand.Intn(10)) * time.Millisecond)
<add> for i := 0; ; i++ {
<add> p := make([]byte, readChunks[(c.iterations*c.readsPerLoop+i)%len(readChunks)])
<ide> n, _ := buf.Read(p)
<add> if n == 0 {
<add> break
<add> }
<ide> hash.Write(p[:n])
<ide> }
<del> }
<del> // read rest of the data from buffer
<del> for i := 0; ; i++ {
<del> p := make([]byte, readChunks[(c.iterations*c.readsPerLoop+i)%len(readChunks)])
<del> n, _ := buf.Read(p)
<del> if n == 0 {
<del> break
<add>
<add> close(done)
<add> }()
<add>
<add> for i := 0; i < c.iterations; i++ {
<add> for w := 0; w < c.writesPerLoop; w++ {
<add> buf.Write(testMessage[:writeChunks[(i*c.writesPerLoop+w)%len(writeChunks)]])
<ide> }
<del> hash.Write(p[:n])
<ide> }
<add> buf.Close()
<add> <-done
<add>
<ide> actual := hex.EncodeToString(hash.Sum(nil))
<ide>
<ide> if expected != actual {
<ide> func TestBytesPipeWriteRandomChunks(t *testing.T) {
<ide>
<ide> func BenchmarkBytesPipeWrite(b *testing.B) {
<ide> for i := 0; i < b.N; i++ {
<add> readBuf := make([]byte, 1024)
<ide> buf := NewBytesPipe(nil)
<add> go func() {
<add> var err error
<add> for err == nil {
<add> _, err = buf.Read(readBuf)
<add> }
<add> }()
<ide> for j := 0; j < 1000; j++ {
<ide> buf.Write([]byte("pretty short line, because why not?"))
<ide> }
<add> buf.Close()
<ide> }
<ide> }
<ide>
<ide> func BenchmarkBytesPipeRead(b *testing.B) {
<del> rd := make([]byte, 1024)
<add> rd := make([]byte, 512)
<ide> for i := 0; i < b.N; i++ {
<ide> b.StopTimer()
<ide> buf := NewBytesPipe(nil)
<del> for j := 0; j < 1000; j++ {
<add> for j := 0; j < 500; j++ {
<ide> buf.Write(make([]byte, 1024))
<ide> }
<ide> b.StartTimer()
<ide> for j := 0; j < 1000; j++ {
<del> if n, _ := buf.Read(rd); n != 1024 {
<add> if n, _ := buf.Read(rd); n != 512 {
<ide> b.Fatalf("Wrong number of bytes: %d", n)
<ide> }
<ide> }
<ide><path>pkg/ioutils/readers.go
<ide> import (
<ide> "crypto/sha256"
<ide> "encoding/hex"
<ide> "io"
<del> "sync"
<ide> )
<ide>
<ide> type readCloserWrapper struct {
<ide> func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader {
<ide> }
<ide> }
<ide>
<del>// bufReader allows the underlying reader to continue to produce
<del>// output by pre-emptively reading from the wrapped reader.
<del>// This is achieved by buffering this data in bufReader's
<del>// expanding buffer.
<del>type bufReader struct {
<del> sync.Mutex
<del> buf io.ReadWriter
<del> reader io.Reader
<del> err error
<del> wait sync.Cond
<del> drainBuf []byte
<del>}
<del>
<del>// NewBufReader returns a new bufReader.
<del>func NewBufReader(r io.Reader) io.ReadCloser {
<del> reader := &bufReader{
<del> buf: NewBytesPipe(nil),
<del> reader: r,
<del> drainBuf: make([]byte, 1024),
<del> }
<del> reader.wait.L = &reader.Mutex
<del> go reader.drain()
<del> return reader
<del>}
<del>
<del>// NewBufReaderWithDrainbufAndBuffer returns a BufReader with drainBuffer and buffer.
<del>func NewBufReaderWithDrainbufAndBuffer(r io.Reader, drainBuffer []byte, buffer io.ReadWriter) io.ReadCloser {
<del> reader := &bufReader{
<del> buf: buffer,
<del> drainBuf: drainBuffer,
<del> reader: r,
<del> }
<del> reader.wait.L = &reader.Mutex
<del> go reader.drain()
<del> return reader
<del>}
<del>
<del>func (r *bufReader) drain() {
<del> for {
<del> //Call to scheduler is made to yield from this goroutine.
<del> //This avoids goroutine looping here when n=0,err=nil, fixes code hangs when run with GCC Go.
<del> callSchedulerIfNecessary()
<del> n, err := r.reader.Read(r.drainBuf)
<del> r.Lock()
<del> if err != nil {
<del> r.err = err
<del> } else {
<del> if n == 0 {
<del> // nothing written, no need to signal
<del> r.Unlock()
<del> continue
<del> }
<del> r.buf.Write(r.drainBuf[:n])
<del> }
<del> r.wait.Signal()
<del> r.Unlock()
<del> if err != nil {
<del> break
<del> }
<del> }
<del>}
<del>
<del>func (r *bufReader) Read(p []byte) (n int, err error) {
<del> r.Lock()
<del> defer r.Unlock()
<del> for {
<del> n, err = r.buf.Read(p)
<del> if n > 0 {
<del> return n, err
<del> }
<del> if r.err != nil {
<del> return 0, r.err
<del> }
<del> r.wait.Wait()
<del> }
<del>}
<del>
<del>// Close closes the bufReader
<del>func (r *bufReader) Close() error {
<del> closer, ok := r.reader.(io.ReadCloser)
<del> if !ok {
<del> return nil
<del> }
<del> return closer.Close()
<del>}
<del>
<ide> // HashData returns the sha256 sum of src.
<ide> func HashData(src io.Reader) (string, error) {
<ide> h := sha256.New()
<ide><path>pkg/ioutils/readers_test.go
<ide> package ioutils
<ide>
<ide> import (
<del> "bytes"
<ide> "fmt"
<del> "io"
<del> "io/ioutil"
<ide> "strings"
<ide> "testing"
<del> "time"
<ide> )
<ide>
<ide> // Implement io.Reader
<ide> func TestReaderErrWrapperRead(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func TestNewBufReaderWithDrainbufAndBuffer(t *testing.T) {
<del> reader, writer := io.Pipe()
<del>
<del> drainBuffer := make([]byte, 1024)
<del> buffer := NewBytesPipe(nil)
<del> bufreader := NewBufReaderWithDrainbufAndBuffer(reader, drainBuffer, buffer)
<del>
<del> // Write everything down to a Pipe
<del> // Usually, a pipe should block but because of the buffered reader,
<del> // the writes will go through
<del> done := make(chan bool)
<del> go func() {
<del> writer.Write([]byte("hello world"))
<del> writer.Close()
<del> done <- true
<del> }()
<del>
<del> // Drain the reader *after* everything has been written, just to verify
<del> // it is indeed buffering
<del> select {
<del> case <-done:
<del> case <-time.After(1 * time.Second):
<del> t.Fatal("timeout")
<del> }
<del>
<del> output, err := ioutil.ReadAll(bufreader)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if !bytes.Equal(output, []byte("hello world")) {
<del> t.Error(string(output))
<del> }
<del>}
<del>
<del>func TestBufReader(t *testing.T) {
<del> reader, writer := io.Pipe()
<del> bufreader := NewBufReader(reader)
<del>
<del> // Write everything down to a Pipe
<del> // Usually, a pipe should block but because of the buffered reader,
<del> // the writes will go through
<del> done := make(chan bool)
<del> go func() {
<del> writer.Write([]byte("hello world"))
<del> writer.Close()
<del> done <- true
<del> }()
<del>
<del> // Drain the reader *after* everything has been written, just to verify
<del> // it is indeed buffering
<del> <-done
<del> output, err := ioutil.ReadAll(bufreader)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if !bytes.Equal(output, []byte("hello world")) {
<del> t.Error(string(output))
<del> }
<del>}
<del>
<del>func TestBufReaderCloseWithNonReaderCloser(t *testing.T) {
<del> reader := strings.NewReader("buffer")
<del> bufreader := NewBufReader(reader)
<del>
<del> if err := bufreader.Close(); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del>}
<del>
<del>// implements io.ReadCloser
<del>type simpleReaderCloser struct {
<del> err error
<del>}
<del>
<del>func (r *simpleReaderCloser) Read(p []byte) (n int, err error) {
<del> return 0, r.err
<del>}
<del>
<del>func (r *simpleReaderCloser) Close() error {
<del> r.err = io.EOF
<del> return nil
<del>}
<del>
<del>func TestBufReaderCloseWithReaderCloser(t *testing.T) {
<del> reader := &simpleReaderCloser{}
<del> bufreader := NewBufReader(reader)
<del>
<del> err := bufreader.Close()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del>}
<del>
<ide> func TestHashData(t *testing.T) {
<ide> reader := strings.NewReader("hash-me")
<ide> actual, err := HashData(reader)
<ide> func TestHashData(t *testing.T) {
<ide> t.Fatalf("Expecting %s, got %s", expected, actual)
<ide> }
<ide> }
<del>
<del>type repeatedReader struct {
<del> readCount int
<del> maxReads int
<del> data []byte
<del>}
<del>
<del>func newRepeatedReader(max int, data []byte) *repeatedReader {
<del> return &repeatedReader{0, max, data}
<del>}
<del>
<del>func (r *repeatedReader) Read(p []byte) (int, error) {
<del> if r.readCount >= r.maxReads {
<del> return 0, io.EOF
<del> }
<del> r.readCount++
<del> n := copy(p, r.data)
<del> return n, nil
<del>}
<del>
<del>func testWithData(data []byte, reads int) {
<del> reader := newRepeatedReader(reads, data)
<del> bufReader := NewBufReader(reader)
<del> io.Copy(ioutil.Discard, bufReader)
<del>}
<del>
<del>func Benchmark1M10BytesReads(b *testing.B) {
<del> reads := 1000000
<del> readSize := int64(10)
<del> data := make([]byte, readSize)
<del> b.SetBytes(readSize * int64(reads))
<del> b.ResetTimer()
<del> for i := 0; i < b.N; i++ {
<del> testWithData(data, reads)
<del> }
<del>}
<del>
<del>func Benchmark1M1024BytesReads(b *testing.B) {
<del> reads := 1000000
<del> readSize := int64(1024)
<del> data := make([]byte, readSize)
<del> b.SetBytes(readSize * int64(reads))
<del> b.ResetTimer()
<del> for i := 0; i < b.N; i++ {
<del> testWithData(data, reads)
<del> }
<del>}
<del>
<del>func Benchmark10k32KBytesReads(b *testing.B) {
<del> reads := 10000
<del> readSize := int64(32 * 1024)
<del> data := make([]byte, readSize)
<del> b.SetBytes(readSize * int64(reads))
<del> b.ResetTimer()
<del> for i := 0; i < b.N; i++ {
<del> testWithData(data, reads)
<del> }
<del>} | 5 |
Javascript | Javascript | add tests for casesensitivemoduleswarning | 23e57e5b9767869a7882c713bd6002aecb009576 | <ide><path>test/CaseSensitiveModulesWarning.test.js
<add>var should = require("should");
<add>var CaseSensitiveModulesWarning = require("../lib/CaseSensitiveModulesWarning");
<add>
<add>var createModule = function(identifier, numberOfReasons) {
<add> var reasons = new Array(numberOfReasons || 0).fill(null).map(function(value, index) {
<add> return {
<add> module: createModule(`${identifier}-reason-${index}`)
<add> };
<add> });
<add>
<add> return {
<add> identifier: () => identifier,
<add> reasons
<add> };
<add>};
<add>
<add>describe("CaseSensitiveModulesWarning", function() {
<add> var myCaseSensitiveModulesWarning, modules;
<add>
<add> beforeEach(function() {
<add> modules = [
<add> createModule('FooBar', 1),
<add> createModule('foobar', 2),
<add> createModule('FOOBAR')
<add> ];
<add> myCaseSensitiveModulesWarning = new CaseSensitiveModulesWarning(modules);
<add> });
<add>
<add> it('has the a name', function() {
<add> myCaseSensitiveModulesWarning.name.should.be.exactly('CaseSensitiveModulesWarning');
<add> });
<add>
<add> it('has the a message', function() {
<add> myCaseSensitiveModulesWarning.message.should.be.exactly(`
<add>There are multiple modules with names that only differ in casing.
<add>This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
<add>Use equal casing. Compare these module identifiers:
<add>* FOOBAR
<add>* FooBar
<add> Used by 1 module(s), i. e.
<add> FooBar-reason-0
<add>* foobar
<add> Used by 2 module(s), i. e.
<add> foobar-reason-0
<add>`.trim());
<add> });
<add>
<add> it('has the an origin', function() {
<add> myCaseSensitiveModulesWarning.origin.should.be.exactly(modules[0]);
<add> });
<add>
<add> it('has the a module', function() {
<add> myCaseSensitiveModulesWarning.module.should.be.exactly(modules[0]);
<add> });
<add>}); | 1 |
Python | Python | remove dup_select_related method | 389892aae595b86c4be28c43e3312d76a68a0173 | <ide><path>django/db/models/query.py
<ide> def prefetch_related(self, *lookups):
<ide> clone._prefetch_related_lookups.extend(lookups)
<ide> return clone
<ide>
<del> def dup_select_related(self, other):
<del> """
<del> Copies the related selection status from the QuerySet 'other' to the
<del> current QuerySet.
<del> """
<del> self.query.select_related = other.query.select_related
<del>
<ide> def annotate(self, *args, **kwargs):
<ide> """
<ide> Return a query set in which the returned objects have been annotated | 1 |
PHP | PHP | remove unneeded test inside conditional | 5da05d9216610dc2d7987ae2e908378d0bfaf09f | <ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> public function read(Model $model, $queryData = array(), $recursive = null) {
<ide> } else {
<ide> $db = ConnectionManager::getDataSource($linkModel->useDbConfig);
<ide> }
<del> } elseif ($model->recursive > 1 && ($type === 'belongsTo' || $type === 'hasOne')) {
<add> } elseif ($model->recursive > 1) {
<ide> $db = $this;
<ide> }
<ide> | 1 |
Javascript | Javascript | remove last call to `getdomnode` in tests | f3e6436bee20fde003fc5e36b6295c63d371c3d7 | <ide><path>src/browser/ui/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', function() {
<ide> expect(
<ide> ReactBrowserEventEmitter.getListener(rootNodeID, 'onClick')
<ide> ).toBe(callback);
<del> expect(rootNode).toBe(instance.getDOMNode());
<add> expect(rootNode).toBe(React.findDOMNode(instance));
<ide>
<ide> React.unmountComponentAtNode(container);
<ide> | 1 |
Javascript | Javascript | check memoryusage properties | 7d3a7ea0d7df9b6f11df723dec370f49f4f87e99 | <ide><path>test/parallel/test-memory-usage.js
<ide> require('../common');
<ide> var assert = require('assert');
<ide>
<ide> var r = process.memoryUsage();
<del>assert.equal(true, r['rss'] > 0);
<add>assert.ok(r.rss > 0);
<add>assert.ok(r.heapTotal > 0);
<add>assert.ok(r.heapUsed > 0); | 1 |
Javascript | Javascript | remove unused imports | 846227b17eeca2b4500508f92fd1c831ffcf7ba7 | <ide><path>packages/ember-glimmer/lib/component-managers/outlet.js
<ide> */
<ide> import { generateGuid, guidFor } from 'ember-utils';
<ide> import {
<del> ComponentDefinition,
<del> CompiledArgs
<add> ComponentDefinition
<ide> } from '@glimmer/runtime';
<ide> import { DEBUG } from 'ember-env-flags';
<ide> import { _instrumentStart } from 'ember-metal';
<ide><path>packages/ember-glimmer/lib/component-managers/root.js
<ide> import {
<ide> ComponentDefinition
<ide> } from '@glimmer/runtime';
<ide> import {
<del> get,
<ide> _instrumentStart
<ide> } from 'ember-metal';
<ide> import {
<ide> import { DEBUG } from 'ember-env-flags';
<ide> import ComponentStateBucket from '../utils/curly-component-state-bucket';
<ide> import CurlyComponentManager, {
<ide> initialRenderInstrumentDetails,
<del> rerenderInstrumentDetails,
<del> validatePositionalParameters,
<ide> processComponentInitializationAssertions
<ide> } from './curly';
<ide> | 2 |
Ruby | Ruby | remove dead code | 628a23cdd230f7f830ecbba137ab2430f69e8db5 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def nested_scope? #:nodoc:
<ide> @scope.nested?
<ide> end
<ide>
<del> def with_exclusive_scope
<del> begin
<del> @scope = @scope.new(:as => nil, :path => nil)
<del>
<del> with_scope_level(:exclusive) do
<del> yield
<del> end
<del> ensure
<del> @scope = @scope.parent
<del> end
<del> end
<del>
<ide> def with_scope_level(kind)
<ide> @scope = @scope.new_level(kind)
<ide> yield | 1 |
Ruby | Ruby | remove unnecessary test setup | 6a4606d3a64e60189ea4ba5243830dcd97e6de14 | <ide><path>actionpack/test/dispatch/show_exceptions_test.rb
<ide> class ShowExceptionsTest < ActionDispatch::IntegrationTest
<ide>
<ide> class Boomer
<del> def initialize(detailed = false)
<del> @detailed = detailed
<del> end
<del>
<ide> def call(env)
<del> env['action_dispatch.show_detailed_exceptions'] = @detailed
<ide> req = ActionDispatch::Request.new(env)
<ide> case req.path
<ide> when "/not_found"
<ide> def call(env)
<ide> end
<ide> end
<ide>
<del> ProductionApp = ActionDispatch::ShowExceptions.new((Boomer.new(false)))
<add> ProductionApp = ActionDispatch::ShowExceptions.new(Boomer.new)
<ide>
<ide> test 'skip diagnosis if not showing exceptions' do
<ide> @app = ProductionApp | 1 |
PHP | PHP | fix doc block | bf9f8f702f8f8847d95e7a6c79771ccf93370344 | <ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php
<ide> public function assertMissing($path)
<ide> }
<ide>
<ide> /**
<del> * Determine if a directory is empty.
<add> * Assert that the given directory is empty.
<ide> *
<ide> * @param string $path
<ide> * @return $this | 1 |
PHP | PHP | update factory count | 0a3faed03e24cb5d633abc6cd53781b395952fd7 | <ide><path>src/Illuminate/Database/Eloquent/Factories/HasFactory.php
<ide> trait HasFactory
<ide> public static function factory(...$parameters)
<ide> {
<ide> return Factory::factoryForModel(get_called_class())
<del> ->count(is_numeric($parameters[0] ?? null) ? $parameters[0] : 1)
<add> ->count(is_numeric($parameters[0] ?? null) ? $parameters[0] : null)
<ide> ->state(is_array($parameters[0] ?? null) ? $parameters[0] : ($parameters[1] ?? []));
<ide> }
<ide> } | 1 |
Python | Python | convert core tests to pytest | 7dd3d062ff59dfcb11cb1df05098e4a0b80abd64 | <ide><path>tests/keras/layers/test_core.py
<ide> import unittest
<add>import pytest
<ide> import numpy as np
<ide> from numpy.testing import assert_allclose
<ide>
<ide> from keras import backend as K
<ide> from keras.layers import core
<ide>
<ide>
<del>class TestLayerBase(unittest.TestCase):
<del> def test_input_output(self):
<del> nb_samples = 10
<del> input_dim = 5
<del> layer = core.Layer()
<del>
<del> # Once an input is provided, it should be reachable through the
<del> # appropriate getters
<del> input = np.ones((nb_samples, input_dim))
<del> layer.input = K.variable(input)
<del> for train in [True, False]:
<del> assert_allclose(K.eval(layer.get_input(train)), input)
<del> assert_allclose(K.eval(layer.get_output(train)), input)
<del>
<del> def test_connections(self):
<del> nb_samples = 10
<del> input_dim = 5
<del> layer1 = core.Layer()
<del> layer2 = core.Layer()
<del>
<del> input = np.ones((nb_samples, input_dim))
<del> layer1.input = K.variable(input)
<del>
<del> # After connecting, input of layer1 should be passed through
<del> layer2.set_previous(layer1)
<del> for train in [True, False]:
<del> assert_allclose(K.eval(layer2.get_input(train)), input)
<del> assert_allclose(K.eval(layer2.get_output(train)), input)
<del>
<del>
<del>class TestBuildConfigParams(unittest.TestCase):
<del> """
<del> Test the constructor, build, config and params functions of all layers in core.
<del> """
<del>
<del> def _runner(self, layer):
<del> assert isinstance(layer, core.Layer)
<del> layer.build()
<del> conf = layer.get_config()
<del> assert (type(conf) == dict)
<del>
<del> param = layer.get_params()
<del> # Typically a list or a tuple, but may be any iterable
<del> assert hasattr(param, '__iter__')
<del>
<del> #test the setter for the trainable attribute
<del> layer.trainable = True
<del> layer.trainable = False
<del>
<del> def test_base(self):
<del> layer = core.Layer()
<del> self._runner(layer)
<del>
<del> def test_masked(self):
<del> layer = core.MaskedLayer()
<del> self._runner(layer)
<del>
<del> def test_merge(self):
<del> layer_1 = core.Layer()
<del> layer_2 = core.Layer()
<del> layer_1.set_input_shape((None,))
<del> layer_2.set_input_shape((None,))
<del> layer = core.Merge([layer_1, layer_2])
<del> self._runner(layer)
<del>
<del> def test_dropout(self):
<del> layer = core.Dropout(0.5)
<del> self._runner(layer)
<del>
<del> def test_activation(self):
<del> layer = core.Activation('linear')
<del> self._runner(layer)
<del>
<del> def test_reshape(self):
<del> layer = core.Reshape(dims=(10, 10))
<del> self._runner(layer)
<del>
<del> def test_flatten(self):
<del> layer = core.Flatten()
<del> self._runner(layer)
<del>
<del> def test_repeat_vector(self):
<del> layer = core.RepeatVector(10)
<del> self._runner(layer)
<del>
<del> def test_dense(self):
<del> layer = core.Dense(10, input_shape=(10,))
<del> self._runner(layer)
<del>
<del> def test_act_reg(self):
<del> layer = core.ActivityRegularization(0.5, 0.5)
<del> self._runner(layer)
<del>
<del> def test_time_dist_dense(self):
<del> layer = core.TimeDistributedDense(10, input_shape=(None, 10))
<del> self._runner(layer)
<del>
<del> def test_time_dist_merge(self):
<del> layer = core.TimeDistributedMerge()
<del> self._runner(layer)
<del>
<del> def test_autoencoder(self):
<del> layer_1 = core.Layer()
<del> layer_2 = core.Layer()
<del>
<del> layer = core.AutoEncoder(layer_1, layer_2)
<del> self._runner(layer)
<del>
<del> def test_maxout_dense(self):
<del> layer = core.MaxoutDense(10, 10, input_shape=(20,))
<del> self._runner(layer)
<del>
<del>
<del>class TestMasking(unittest.TestCase):
<del> """Test the Masking class"""
<del>
<del> @pytest.mark.skipif(K._BACKEND=='tensorflow', reason="currently not working with TensorFlow")
<del> def test_sequences(self):
<del> """Test masking sequences with zeroes as padding"""
<del> # integer inputs, one per timestep, like embeddings
<del> layer = core.Masking()
<del> func = K.function([layer.input], [layer.get_output_mask()])
<del> input_data = np.array([[[1], [2], [3], [0]],
<del> [[0], [4], [5], [0]]], dtype=np.int32)
<del>
<del> # This is the expected output mask, one dimension less
<del> expected = np.array([[1, 1, 1, 0], [0, 1, 1, 0]])
<del>
<del> # get mask for this input
<del> output = func([input_data])[0]
<del> self.assertTrue(np.all(output == expected))
<del>
<del> @pytest.mark.skipif(K._BACKEND=='tensorflow', reason="currently not working with TensorFlow")
<del> def test_non_zero(self):
<del> """Test masking with non-zero mask value"""
<del> layer = core.Masking(5)
<del> func = K.function([layer.input], [layer.get_output_mask()])
<del> input_data = np.array([[[1, 1], [2, 1], [3, 1], [5, 5]],
<del> [[1, 5], [5, 0], [0, 0], [0, 0]]],
<del> dtype=np.int32)
<del> output = func([input_data])[0]
<del> expected = np.array([[1, 1, 1, 0], [1, 1, 1, 1]])
<del> self.assertTrue(np.all(output == expected))
<del>
<del> @pytest.mark.skipif(K._BACKEND=='tensorflow', reason="currently not working with TensorFlow")
<del> def test_non_zero_output(self):
<del> """Test output of masking layer with non-zero mask value"""
<del> layer = core.Masking(5)
<del> func = K.function([layer.input], [layer.get_output()])
<del>
<del> input_data = np.array([[[1, 1], [2, 1], [3, 1], [5, 5]],
<del> [[1, 5], [5, 0], [0, 0], [0, 0]]],
<del> dtype=np.int32)
<del> output = func([input_data])[0]
<del> expected = np.array([[[1, 1], [2, 1], [3, 1], [0, 0]],
<del> [[1, 5], [5, 0], [0, 0], [0, 0]]])
<del> self.assertTrue(np.all(output == expected))
<add>def test_input_output():
<add> nb_samples = 10
<add> input_dim = 5
<add> layer = core.Layer()
<add>
<add> # Once an input is provided, it should be reachable through the
<add> # appropriate getters
<add> input = np.ones((nb_samples, input_dim))
<add> layer.input = K.variable(input)
<add> for train in [True, False]:
<add> assert_allclose(K.eval(layer.get_input(train)), input)
<add> assert_allclose(K.eval(layer.get_output(train)), input)
<add>
<add>def test_connections():
<add> nb_samples = 10
<add> input_dim = 5
<add> layer1 = core.Layer()
<add> layer2 = core.Layer()
<add>
<add> input = np.ones((nb_samples, input_dim))
<add> layer1.input = K.variable(input)
<add>
<add> # After connecting, input of layer1 should be passed through
<add> layer2.set_previous(layer1)
<add> for train in [True, False]:
<add> assert_allclose(K.eval(layer2.get_input(train)), input)
<add> assert_allclose(K.eval(layer2.get_output(train)), input)
<add>
<add>
<add>def test_base():
<add> layer = core.Layer()
<add> _runner(layer)
<add>
<add>def test_masked():
<add> layer = core.MaskedLayer()
<add> _runner(layer)
<add>
<add>def test_merge():
<add> layer_1 = core.Layer()
<add> layer_2 = core.Layer()
<add> layer_1.set_input_shape((None,))
<add> layer_2.set_input_shape((None,))
<add> layer = core.Merge([layer_1, layer_2])
<add> _runner(layer)
<add>
<add>def test_dropout():
<add> layer = core.Dropout(0.5)
<add> _runner(layer)
<add>
<add>def test_activation():
<add> layer = core.Activation('linear')
<add> _runner(layer)
<add>
<add>def test_reshape():
<add> layer = core.Reshape(dims=(10, 10))
<add> _runner(layer)
<add>
<add>def test_flatten():
<add> layer = core.Flatten()
<add> _runner(layer)
<add>
<add>def test_repeat_vector():
<add> layer = core.RepeatVector(10)
<add> _runner(layer)
<add>
<add>def test_dense():
<add> layer = core.Dense(10, input_shape=(10,))
<add> _runner(layer)
<add>
<add>def test_act_reg():
<add> layer = core.ActivityRegularization(0.5, 0.5)
<add> _runner(layer)
<add>
<add>def test_time_dist_dense():
<add> layer = core.TimeDistributedDense(10, input_shape=(None, 10))
<add> _runner(layer)
<add>
<add>def test_time_dist_merge():
<add> layer = core.TimeDistributedMerge()
<add> _runner(layer)
<add>
<add>def test_autoencoder():
<add> layer_1 = core.Layer()
<add> layer_2 = core.Layer()
<add>
<add> layer = core.AutoEncoder(layer_1, layer_2)
<add> _runner(layer)
<add>
<add>def test_maxout_dense():
<add> layer = core.MaxoutDense(10, 10, input_shape=(20,))
<add> _runner(layer)
<add>
<add>
<add>@pytest.mark.skipif(K._BACKEND=='tensorflow', reason="currently not working with TensorFlow")
<add>def test_sequences():
<add> """Test masking sequences with zeroes as padding"""
<add> # integer inputs, one per timestep, like embeddings
<add> layer = core.Masking()
<add> func = K.function([layer.input], [layer.get_output_mask()])
<add> input_data = np.array([[[1], [2], [3], [0]],
<add> [[0], [4], [5], [0]]], dtype=np.int32)
<add>
<add> # This is the expected output mask, one dimension less
<add> expected = np.array([[1, 1, 1, 0], [0, 1, 1, 0]])
<add>
<add> # get mask for this input
<add> output = func([input_data])[0]
<add> assert np.all(output == expected) , "Output not as expected"
<add>
<add>@pytest.mark.skipif(K._BACKEND=='tensorflow', reason="currently not working with TensorFlow")
<add>def test_non_zero():
<add> """Test masking with non-zero mask value"""
<add> layer = core.Masking(5)
<add> func = K.function([layer.input], [layer.get_output_mask()])
<add> input_data = np.array([[[1, 1], [2, 1], [3, 1], [5, 5]],
<add> [[1, 5], [5, 0], [0, 0], [0, 0]]],
<add> dtype=np.int32)
<add> output = func([input_data])[0]
<add> expected = np.array([[1, 1, 1, 0], [1, 1, 1, 1]])
<add> assert np.all(output == expected) , "Output not as expected"
<add>
<add>@pytest.mark.skipif(K._BACKEND=='tensorflow', reason="currently not working with TensorFlow")
<add>def test_non_zero_output():
<add> """Test output of masking layer with non-zero mask value"""
<add> layer = core.Masking(5)
<add> func = K.function([layer.input], [layer.get_output()])
<add>
<add> input_data = np.array([[[1, 1], [2, 1], [3, 1], [5, 5]],
<add> [[1, 5], [5, 0], [0, 0], [0, 0]]],
<add> dtype=np.int32)
<add> output = func([input_data])[0]
<add> expected = np.array([[[1, 1], [2, 1], [3, 1], [0, 0]],
<add> [[1, 5], [5, 0], [0, 0], [0, 0]]])
<add> assert np.all(output == expected) , "Output not as expected"
<add>
<add>
<add>def _runner(layer):
<add> assert isinstance(layer, core.Layer)
<add> layer.build()
<add> conf = layer.get_config()
<add> assert (type(conf) == dict)
<add>
<add> param = layer.get_params()
<add> # Typically a list or a tuple, but may be any iterable
<add> assert hasattr(param, '__iter__')
<add>
<add> #test the setter for the trainable attribute
<add> layer.trainable = True
<add> layer.trainable = False
<ide>
<ide>
<ide> if __name__ == '__main__': | 1 |
Go | Go | update push to reflect the correct api | 08121c8f6b435779027d837c1e7fc8046bc1e165 | <ide><path>registry/registry.go
<ide> func (r *Registry) PushImageJsonIndex(remote string, imgList []*ImgData, validat
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del>
<del> utils.Debugf("json sent: %s\n", imgListJson)
<del>
<del> req, err := http.NewRequest("PUT", auth.IndexServerAddress()+"/repositories/"+remote+"/", bytes.NewReader(imgListJson))
<add> var suffix string
<add> if validate {
<add> suffix = "images"
<add> }
<add> req, err := http.NewRequest("PUT", auth.IndexServerAddress()+"/repositories/"+remote+"/"+suffix, bytes.NewReader(imgListJson))
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (r *Registry) PushImageJsonIndex(remote string, imgList []*ImgData, validat
<ide> defer res.Body.Close()
<ide> }
<ide>
<del> if res.StatusCode != 200 && res.StatusCode != 201 {
<del> errBody, err := ioutil.ReadAll(res.Body)
<del> if err != nil {
<del> return nil, err
<add> var tokens, endpoints []string
<add> if !validate {
<add> if res.StatusCode != 200 && res.StatusCode != 201 {
<add> errBody, err := ioutil.ReadAll(res.Body)
<add> if err != nil {
<add> return nil, err
<add> }
<add> return nil, fmt.Errorf("Error: Status %d trying to push repository %s: %s", res.StatusCode, remote, errBody)
<add> }
<add> if res.Header.Get("X-Docker-Token") != "" {
<add> tokens = res.Header["X-Docker-Token"]
<add> utils.Debugf("Auth token: %v", tokens)
<add> } else {
<add> return nil, fmt.Errorf("Index response didn't contain an access token")
<ide> }
<del> return nil, fmt.Errorf("Error: Status %d trying to push repository %s: %s", res.StatusCode, remote, errBody)
<del> }
<del>
<del> var tokens []string
<del> if res.Header.Get("X-Docker-Token") != "" {
<del> tokens = res.Header["X-Docker-Token"]
<del> utils.Debugf("Auth token: %v", tokens)
<del> } else {
<del> return nil, fmt.Errorf("Index response didn't contain an access token")
<del> }
<ide>
<del> var endpoints []string
<del> if res.Header.Get("X-Docker-Endpoints") != "" {
<del> endpoints = res.Header["X-Docker-Endpoints"]
<del> } else {
<del> return nil, fmt.Errorf("Index response didn't contain any endpoints")
<add> if res.Header.Get("X-Docker-Endpoints") != "" {
<add> endpoints = res.Header["X-Docker-Endpoints"]
<add> } else {
<add> return nil, fmt.Errorf("Index response didn't contain any endpoints")
<add> }
<ide> }
<del>
<ide> if validate {
<ide> if res.StatusCode != 204 {
<ide> if errBody, err := ioutil.ReadAll(res.Body); err != nil { | 1 |
Java | Java | add assert abstractstandardrequestupgradestrategy | 079fb2db737c830da62e57a02102bf0e9d70d6cb | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractStandardUpgradeStrategy.java
<ide> import org.springframework.http.server.ServerHttpRequest;
<ide> import org.springframework.http.server.ServerHttpResponse;
<ide> import org.springframework.http.server.ServletServerHttpRequest;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.web.socket.support.WebSocketExtension;
<ide> import org.springframework.web.socket.WebSocketHandler;
<ide> import org.springframework.web.socket.adapter.StandardWebSocketHandlerAdapter;
<ide> public List<WebSocketExtension> getSupportedExtensions(ServerHttpRequest request
<ide>
<ide> protected ServerContainer getContainer(HttpServletRequest request) {
<ide> ServletContext servletContext = request.getServletContext();
<del> return (ServerContainer) servletContext.getAttribute("javax.websocket.server.ServerContainer");
<add> String attrName = "javax.websocket.server.ServerContainer";
<add> ServerContainer container = (ServerContainer) servletContext.getAttribute(attrName);
<add> Assert.notNull(container, "No 'javax.websocket.server.ServerContainer' ServletContext attribute. " +
<add> "Are you running in a Servlet container that supports JSR-356?");
<add> return container;
<ide> }
<ide>
<ide> protected List<WebSocketExtension> getInstalledExtensions(WebSocketContainer container) { | 1 |
Javascript | Javascript | upgrade "suites" to be qunit 2 compat | cceca7ee192c8f034f6ddb09dcd2c8faf9de68bd | <ide><path>packages/ember-runtime/tests/suites/array.js
<ide> const ObserverClass = EnumerableTestsObserverClass.extend({
<ide> },
<ide>
<ide> arrayWillChange() {
<del> equal(this._before, null, 'should only call once');
<add> QUnit.config.current.assert.equal(this._before, null, 'should only call once');
<ide> this._before = Array.prototype.slice.call(arguments);
<ide> },
<ide>
<ide> arrayDidChange() {
<del> equal(this._after, null, 'should only call once');
<add> QUnit.config.current.assert.equal(this._after, null, 'should only call once');
<ide> this._after = Array.prototype.slice.call(arguments);
<ide> }
<ide> });
<ide><path>packages/ember-runtime/tests/suites/array/includes.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('includes');
<ide>
<del>suite.test('includes returns correct value if startAt is positive', function() {
<add>suite.test('includes returns correct value if startAt is positive', function(assert) {
<ide> let data = this.newFixture(3);
<ide> let obj = this.newObject(data);
<ide>
<del> equal(obj.includes(data[1], 1), true, 'should return true if included');
<del> equal(obj.includes(data[0], 1), false, 'should return false if not included');
<add> assert.equal(obj.includes(data[1], 1), true, 'should return true if included');
<add> assert.equal(obj.includes(data[0], 1), false, 'should return false if not included');
<ide> });
<ide>
<del>suite.test('includes returns correct value if startAt is negative', function() {
<add>suite.test('includes returns correct value if startAt is negative', function(assert) {
<ide> let data = this.newFixture(3);
<ide> let obj = this.newObject(data);
<ide>
<del> equal(obj.includes(data[1], -2), true, 'should return true if included');
<del> equal(obj.includes(data[0], -2), false, 'should return false if not included');
<add> assert.equal(obj.includes(data[1], -2), true, 'should return true if included');
<add> assert.equal(obj.includes(data[0], -2), false, 'should return false if not included');
<ide> });
<ide>
<del>suite.test('includes returns true if startAt + length is still negative', function() {
<add>suite.test('includes returns true if startAt + length is still negative', function(assert) {
<ide> let data = this.newFixture(1);
<ide> let obj = this.newObject(data);
<ide>
<del> equal(obj.includes(data[0], -2), true, 'should return true if included');
<del> equal(obj.includes(this.newFixture(1), -2), false, 'should return false if not included');
<add> assert.equal(obj.includes(data[0], -2), true, 'should return true if included');
<add> assert.equal(obj.includes(this.newFixture(1), -2), false, 'should return false if not included');
<ide> });
<ide>
<del>suite.test('includes returns false if startAt out of bounds', function() {
<add>suite.test('includes returns false if startAt out of bounds', function(assert) {
<ide> let data = this.newFixture(1);
<ide> let obj = this.newObject(data);
<ide>
<del> equal(obj.includes(data[0], 2), false, 'should return false if startAt >= length');
<del> equal(obj.includes(this.newFixture(1), 2), false, 'should return false if startAt >= length');
<add> assert.equal(obj.includes(data[0], 2), false, 'should return false if startAt >= length');
<add> assert.equal(obj.includes(this.newFixture(1), 2), false, 'should return false if startAt >= length');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/array/indexOf.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('indexOf');
<ide>
<del>suite.test('should return index of object', function() {
<add>suite.test('should return index of object', function(assert) {
<ide> let expected = this.newFixture(3);
<ide> let obj = this.newObject(expected);
<ide> let len = 3;
<ide>
<ide> for (let idx = 0; idx < len; idx++) {
<del> equal(obj.indexOf(expected[idx]), idx, `obj.indexOf(${expected[idx]}) should match idx`);
<add> assert.equal(obj.indexOf(expected[idx]), idx, `obj.indexOf(${expected[idx]}) should match idx`);
<ide> }
<ide> });
<ide>
<del>suite.test('should return -1 when requesting object not in index', function() {
<add>suite.test('should return -1 when requesting object not in index', function(assert) {
<ide> let obj = this.newObject(this.newFixture(3));
<ide> let foo = {};
<ide>
<del> equal(obj.indexOf(foo), -1, 'obj.indexOf(foo) should be < 0');
<add> assert.equal(obj.indexOf(foo), -1, 'obj.indexOf(foo) should be < 0');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/array/lastIndexOf.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('lastIndexOf');
<ide>
<del>suite.test('should return index of object\'s last occurrence', function() {
<add>suite.test('should return index of object\'s last occurrence', function(assert) {
<ide> let expected = this.newFixture(3);
<ide> let obj = this.newObject(expected);
<ide> let len = 3;
<ide>
<ide> for (let idx = 0; idx < len; idx++) {
<del> equal(obj.lastIndexOf(expected[idx]), idx, `obj.lastIndexOf(${expected[idx]}) should match idx`);
<add> assert.equal(obj.lastIndexOf(expected[idx]), idx, `obj.lastIndexOf(${expected[idx]}) should match idx`);
<ide> }
<ide> });
<ide>
<del>suite.test('should return index of object\'s last occurrence even startAt search location is equal to length', function() {
<add>suite.test('should return index of object\'s last occurrence even startAt search location is equal to length', function(assert) {
<ide> let expected = this.newFixture(3);
<ide> let obj = this.newObject(expected);
<ide> let len = 3;
<ide>
<ide> for (let idx = 0; idx < len; idx++) {
<del> equal(obj.lastIndexOf(expected[idx], len), idx, `obj.lastIndexOfs(${expected[idx]}) should match idx`);
<add> assert.equal(obj.lastIndexOf(expected[idx], len), idx, `obj.lastIndexOfs(${expected[idx]}) should match idx`);
<ide> }
<ide> });
<ide>
<del>suite.test('should return index of object\'s last occurrence even startAt search location is greater than length', function() {
<add>suite.test('should return index of object\'s last occurrence even startAt search location is greater than length', function(assert) {
<ide> let expected = this.newFixture(3);
<ide> let obj = this.newObject(expected);
<ide> let len = 3;
<ide>
<ide> for (let idx = 0; idx < len; idx++) {
<del> equal(obj.lastIndexOf(expected[idx], len + 1), idx, `obj.lastIndexOf(${expected[idx]}) should match idx`);
<add> assert.equal(obj.lastIndexOf(expected[idx], len + 1), idx, `obj.lastIndexOf(${expected[idx]}) should match idx`);
<ide> }
<ide> });
<ide>
<del>suite.test('should return -1 when no match is found', function() {
<add>suite.test('should return -1 when no match is found', function(assert) {
<ide> let obj = this.newObject(this.newFixture(3));
<ide> let foo = {};
<ide>
<del> equal(obj.lastIndexOf(foo), -1, 'obj.lastIndexOf(foo) should be -1');
<add> assert.equal(obj.lastIndexOf(foo), -1, 'obj.lastIndexOf(foo) should be -1');
<ide> });
<ide>
<del>suite.test('should return -1 when no match is found even startAt search location is equal to length', function() {
<add>suite.test('should return -1 when no match is found even startAt search location is equal to length', function(assert) {
<ide> let obj = this.newObject(this.newFixture(3));
<ide> let foo = {};
<ide>
<del> equal(obj.lastIndexOf(foo, get(obj, 'length')), -1, 'obj.lastIndexOf(foo) should be -1');
<add> assert.equal(obj.lastIndexOf(foo, get(obj, 'length')), -1, 'obj.lastIndexOf(foo) should be -1');
<ide> });
<ide>
<del>suite.test('should return -1 when no match is found even startAt search location is greater than length', function() {
<add>suite.test('should return -1 when no match is found even startAt search location is greater than length', function(assert) {
<ide> let obj = this.newObject(this.newFixture(3));
<ide> let foo = {};
<ide>
<del> equal(obj.lastIndexOf(foo, get(obj, 'length') + 1), -1, 'obj.lastIndexOf(foo) should be -1');
<add> assert.equal(obj.lastIndexOf(foo, get(obj, 'length') + 1), -1, 'obj.lastIndexOf(foo) should be -1');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/array/objectAt.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('objectAt');
<ide>
<del>suite.test('should return object at specified index', function() {
<add>suite.test('should return object at specified index', function(assert) {
<ide> let expected = this.newFixture(3);
<ide> let obj = this.newObject(expected);
<ide> let len = expected.length;
<ide>
<ide> for (let idx = 0; idx < len; idx++) {
<del> equal(objectAt(obj, idx), expected[idx], `obj.objectAt(${idx}) should match`);
<add> assert.equal(objectAt(obj, idx), expected[idx], `obj.objectAt(${idx}) should match`);
<ide> }
<ide> });
<ide>
<del>suite.test('should return undefined when requesting objects beyond index', function() {
<add>suite.test('should return undefined when requesting objects beyond index', function(assert) {
<ide> let obj;
<ide>
<ide> obj = this.newObject(this.newFixture(3));
<del> equal(objectAt(obj, 5), undefined, 'should return undefined for obj.objectAt(5) when len = 3');
<add> assert.equal(objectAt(obj, 5), undefined, 'should return undefined for obj.objectAt(5) when len = 3');
<ide>
<ide> obj = this.newObject([]);
<del> equal(objectAt(obj, 0), undefined, 'should return undefined for obj.objectAt(0) when len = 0');
<add> assert.equal(objectAt(obj, 0), undefined, 'should return undefined for obj.objectAt(0) when len = 0');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/copyable/copy.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('copy');
<ide>
<del>suite.test('should return an equivalent copy', function() {
<add>suite.test('should return an equivalent copy', function(assert) {
<ide> let obj = this.newObject();
<ide> let copy = obj.copy();
<del> ok(this.isEqual(obj, copy), 'old object and new object should be equivalent');
<add> assert.ok(this.isEqual(obj, copy), 'old object and new object should be equivalent');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable.js
<ide> const ObserverClass = EmberObject.extend({
<ide> },
<ide>
<ide> enumerableWillChange() {
<del> equal(this._before, null, 'should only call once');
<add> QUnit.config.current.assert.equal(this._before, null, 'should only call once');
<ide> this._before = Array.prototype.slice.call(arguments);
<ide> },
<ide>
<ide> enumerableDidChange() {
<del> equal(this._after, null, 'should only call once');
<add> QUnit.config.current.assert.equal(this._after, null, 'should only call once');
<ide> this._after = Array.prototype.slice.call(arguments);
<ide> }
<ide> });
<ide><path>packages/ember-runtime/tests/suites/enumerable/any.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('any');
<ide>
<del>suite.test('any should should invoke callback on each item as long as you return false', function() {
<add>suite.test('any should should invoke callback on each item as long as you return false', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let found = [];
<ide> suite.test('any should should invoke callback on each item as long as you return
<ide> found.push(i);
<ide> return false;
<ide> });
<del> equal(result, false, 'return value of obj.any');
<del> deepEqual(found, ary, 'items passed during any() should match');
<add> assert.equal(result, false, 'return value of obj.any');
<add> assert.deepEqual(found, ary, 'items passed during any() should match');
<ide> });
<ide>
<del>suite.test('any should stop invoking when you return true', function() {
<add>suite.test('any should stop invoking when you return true', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let cnt = ary.length - 2;
<ide> suite.test('any should stop invoking when you return true', function() {
<ide> found.push(i);
<ide> return --cnt <= 0;
<ide> });
<del> equal(result, true, 'return value of obj.any');
<del> equal(found.length, exp, 'should invoke proper number of times');
<del> deepEqual(found, ary.slice(0, -2), 'items passed during any() should match');
<add> assert.equal(result, true, 'return value of obj.any');
<add> assert.equal(found.length, exp, 'should invoke proper number of times');
<add> assert.deepEqual(found, ary.slice(0, -2), 'items passed during any() should match');
<ide> });
<ide>
<del>suite.test('any should return true if any object matches the callback', function() {
<add>suite.test('any should return true if any object matches the callback', function(assert) {
<ide> let obj = emberA([0, 1, 2]);
<ide> let result;
<ide>
<ide> result = obj.any(i => !!i);
<del> equal(result, true, 'return value of obj.any');
<add> assert.equal(result, true, 'return value of obj.any');
<ide> });
<ide>
<del>suite.test('any should return false if no object matches the callback', function() {
<add>suite.test('any should return false if no object matches the callback', function(assert) {
<ide> let obj = emberA([0, null, false]);
<ide> let result;
<ide>
<ide> result = obj.any(i => !!i);
<del> equal(result, false, 'return value of obj.any');
<add> assert.equal(result, false, 'return value of obj.any');
<ide> });
<ide>
<del>suite.test('any should produce correct results even if the matching element is undefined', function() {
<add>suite.test('any should produce correct results even if the matching element is undefined', function(assert) {
<ide> let obj = emberA([undefined]);
<ide> let result;
<ide>
<ide> result = obj.any(() => true);
<del> equal(result, true, 'return value of obj.any');
<add> assert.equal(result, true, 'return value of obj.any');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/compact.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('compact');
<ide>
<del>suite.test('removes null and undefined values from enumerable', function() {
<add>suite.test('removes null and undefined values from enumerable', function(assert) {
<ide> let obj = this.newObject([null, 1, false, '', undefined, 0, null]);
<ide> let ary = obj.compact();
<del> deepEqual(ary, [1, false, '', 0]);
<add> assert.deepEqual(ary, [1, false, '', 0]);
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/every.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('every');
<ide>
<del>suite.test('every should should invoke callback on each item as long as you return true', function() {
<add>suite.test('every should should invoke callback on each item as long as you return true', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let found = [];
<ide> suite.test('every should should invoke callback on each item as long as you retu
<ide> found.push(i);
<ide> return true;
<ide> });
<del> equal(result, true, 'return value of obj.every');
<del> deepEqual(found, ary, 'items passed during every() should match');
<add> assert.equal(result, true, 'return value of obj.every');
<add> assert.deepEqual(found, ary, 'items passed during every() should match');
<ide> });
<ide>
<del>suite.test('every should stop invoking when you return false', function() {
<add>suite.test('every should stop invoking when you return false', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let cnt = ary.length - 2;
<ide> suite.test('every should stop invoking when you return false', function() {
<ide> found.push(i);
<ide> return --cnt > 0;
<ide> });
<del> equal(result, false, 'return value of obj.every');
<del> equal(found.length, exp, 'should invoke proper number of times');
<del> deepEqual(found, ary.slice(0, -2), 'items passed during every() should match');
<add> assert.equal(result, false, 'return value of obj.every');
<add> assert.equal(found.length, exp, 'should invoke proper number of times');
<add> assert.deepEqual(found, ary.slice(0, -2), 'items passed during every() should match');
<ide> });
<ide>
<ide> // ..........................................................
<ide> suite.test('every should stop invoking when you return false', function() {
<ide>
<ide> suite.module('isEvery');
<ide>
<del>suite.test('should return true of every property matches', function() {
<add>suite.test('should return true of every property matches', function(assert) {
<ide> let obj = this.newObject([
<ide> { foo: 'foo', bar: 'BAZ' },
<ide> EmberObject.create({ foo: 'foo', bar: 'bar' })
<ide> ]);
<ide>
<del> equal(obj.isEvery('foo', 'foo'), true, 'isEvery(foo)');
<del> equal(obj.isEvery('bar', 'bar'), false, 'isEvery(bar)');
<add> assert.equal(obj.isEvery('foo', 'foo'), true, 'isEvery(foo)');
<add> assert.equal(obj.isEvery('bar', 'bar'), false, 'isEvery(bar)');
<ide> });
<ide>
<del>suite.test('should return true of every property is true', function() {
<add>suite.test('should return true of every property is true', function(assert) {
<ide> let obj = this.newObject([
<ide> { foo: 'foo', bar: true },
<ide> EmberObject.create({ foo: 'bar', bar: false })
<ide> ]);
<ide>
<ide> // different values - all eval to true
<del> equal(obj.isEvery('foo'), true, 'isEvery(foo)');
<del> equal(obj.isEvery('bar'), false, 'isEvery(bar)');
<add> assert.equal(obj.isEvery('foo'), true, 'isEvery(foo)');
<add> assert.equal(obj.isEvery('bar'), false, 'isEvery(bar)');
<ide> });
<ide>
<del>suite.test('should return true if every property matches null', function() {
<add>suite.test('should return true if every property matches null', function(assert) {
<ide> let obj = this.newObject([
<ide> { foo: null, bar: 'BAZ' },
<ide> EmberObject.create({ foo: null, bar: null })
<ide> ]);
<ide>
<del> equal(obj.isEvery('foo', null), true, 'isEvery(\'foo\', null)');
<del> equal(obj.isEvery('bar', null), false, 'isEvery(\'bar\', null)');
<add> assert.equal(obj.isEvery('foo', null), true, 'isEvery(\'foo\', null)');
<add> assert.equal(obj.isEvery('bar', null), false, 'isEvery(\'bar\', null)');
<ide> });
<ide>
<del>suite.test('should return true if every property is undefined', function() {
<add>suite.test('should return true if every property is undefined', function(assert) {
<ide> let obj = this.newObject([
<ide> { foo: undefined, bar: 'BAZ' },
<ide> EmberObject.create({ bar: undefined })
<ide> ]);
<ide>
<del> equal(obj.isEvery('foo', undefined), true, 'isEvery(\'foo\', undefined)');
<del> equal(obj.isEvery('bar', undefined), false, 'isEvery(\'bar\', undefined)');
<add> assert.equal(obj.isEvery('foo', undefined), true, 'isEvery(\'foo\', undefined)');
<add> assert.equal(obj.isEvery('bar', undefined), false, 'isEvery(\'bar\', undefined)');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/filter.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('filter');
<ide>
<del>suite.test('filter should invoke on each item', function() {
<add>suite.test('filter should invoke on each item', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let cnt = ary.length - 2;
<ide> suite.test('filter should invoke on each item', function() {
<ide> found.push(i);
<ide> return --cnt >= 0;
<ide> });
<del> deepEqual(found, ary, 'should have invoked on each item');
<del> deepEqual(result, ary.slice(0, -2), 'filtered array should exclude items');
<add> assert.deepEqual(found, ary, 'should have invoked on each item');
<add> assert.deepEqual(result, ary.slice(0, -2), 'filtered array should exclude items');
<ide> });
<ide>
<ide> // ..........................................................
<ide> suite.test('filter should invoke on each item', function() {
<ide>
<ide> suite.module('filterBy');
<ide>
<del>suite.test('should filter based on object', function() {
<add>suite.test('should filter based on object', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should filter based on object', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.filterBy('foo', 'foo'), ary, 'filterBy(foo)');
<del> deepEqual(obj.filterBy('bar', 'bar'), [ary[1]], 'filterBy(bar)');
<add> assert.deepEqual(obj.filterBy('foo', 'foo'), ary, 'filterBy(foo)');
<add> assert.deepEqual(obj.filterBy('bar', 'bar'), [ary[1]], 'filterBy(bar)');
<ide> });
<ide>
<del>suite.test('should include in result if property is true', function() {
<add>suite.test('should include in result if property is true', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should include in result if property is true', function() {
<ide> obj = this.newObject(ary);
<ide>
<ide> // different values - all eval to true
<del> deepEqual(obj.filterBy('foo'), ary, 'filterBy(foo)');
<del> deepEqual(obj.filterBy('bar'), [ary[0]], 'filterBy(bar)');
<add> assert.deepEqual(obj.filterBy('foo'), ary, 'filterBy(foo)');
<add> assert.deepEqual(obj.filterBy('bar'), [ary[0]], 'filterBy(bar)');
<ide> });
<ide>
<del>suite.test('should filter on second argument if provided', function() {
<add>suite.test('should filter on second argument if provided', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should filter on second argument if provided', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.filterBy('foo', 3), [ary[0], ary[3]], 'filterBy(\'foo\', 3)\')');
<add> assert.deepEqual(obj.filterBy('foo', 3), [ary[0], ary[3]], 'filterBy(\'foo\', 3)\')');
<ide> });
<ide>
<del>suite.test('should correctly filter null second argument', function() {
<add>suite.test('should correctly filter null second argument', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should correctly filter null second argument', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.filterBy('foo', null), [ary[1], ary[2]], 'filterBy(\'foo\', 3)\')');
<add> assert.deepEqual(obj.filterBy('foo', null), [ary[1], ary[2]], 'filterBy(\'foo\', 3)\')');
<ide> });
<ide>
<del>suite.test('should not return all objects on undefined second argument', function() {
<add>suite.test('should not return all objects on undefined second argument', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should not return all objects on undefined second argument', functio
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.filterBy('foo', undefined), [], 'filterBy(\'foo\', 3)\')');
<add> assert.deepEqual(obj.filterBy('foo', undefined), [], 'filterBy(\'foo\', 3)\')');
<ide> });
<ide>
<del>suite.test('should correctly filter explicit undefined second argument', function() {
<add>suite.test('should correctly filter explicit undefined second argument', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should correctly filter explicit undefined second argument', functio
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.filterBy('foo', undefined), ary.slice(2), 'filterBy(\'foo\', 3)\')');
<add> assert.deepEqual(obj.filterBy('foo', undefined), ary.slice(2), 'filterBy(\'foo\', 3)\')');
<ide> });
<ide>
<del>suite.test('should not match undefined properties without second argument', function() {
<add>suite.test('should not match undefined properties without second argument', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should not match undefined properties without second argument', func
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.filterBy('foo'), ary.slice(0, 2), 'filterBy(\'foo\', 3)\')');
<add> assert.deepEqual(obj.filterBy('foo'), ary.slice(0, 2), 'filterBy(\'foo\', 3)\')');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/find.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('find');
<ide>
<del>suite.test('find should invoke callback on each item as long as you return false', function() {
<add>suite.test('find should invoke callback on each item as long as you return false', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let found = [];
<ide> suite.test('find should invoke callback on each item as long as you return false
<ide> found.push(i);
<ide> return false;
<ide> });
<del> equal(result, undefined, 'return value of obj.find');
<del> deepEqual(found, ary, 'items passed during find() should match');
<add> assert.equal(result, undefined, 'return value of obj.find');
<add> assert.deepEqual(found, ary, 'items passed during find() should match');
<ide> });
<ide>
<del>suite.test('every should stop invoking when you return true', function() {
<add>suite.test('every should stop invoking when you return true', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let cnt = ary.length - 2;
<ide> suite.test('every should stop invoking when you return true', function() {
<ide> found.push(i);
<ide> return --cnt >= 0;
<ide> });
<del> equal(result, ary[exp - 1], 'return value of obj.find');
<del> equal(found.length, exp, 'should invoke proper number of times');
<del> deepEqual(found, ary.slice(0, -2), 'items passed during find() should match');
<add> assert.equal(result, ary[exp - 1], 'return value of obj.find');
<add> assert.equal(found.length, exp, 'should invoke proper number of times');
<add> assert.deepEqual(found, ary.slice(0, -2), 'items passed during find() should match');
<ide> });
<ide>
<ide> // ..........................................................
<ide> suite.test('every should stop invoking when you return true', function() {
<ide>
<ide> suite.module('findBy');
<ide>
<del>suite.test('should return first object of property matches', function() {
<add>suite.test('should return first object of property matches', function(assert) {
<ide> let ary, obj;
<ide>
<ide> ary = [
<ide> suite.test('should return first object of property matches', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> equal(obj.findBy('foo', 'foo'), ary[0], 'findBy(foo)');
<del> equal(obj.findBy('bar', 'bar'), ary[1], 'findBy(bar)');
<add> assert.equal(obj.findBy('foo', 'foo'), ary[0], 'findBy(foo)');
<add> assert.equal(obj.findBy('bar', 'bar'), ary[1], 'findBy(bar)');
<ide> });
<ide>
<del>suite.test('should return first object with truthy prop', function() {
<add>suite.test('should return first object with truthy prop', function(assert) {
<ide> let ary, obj;
<ide>
<ide> ary = [
<ide> suite.test('should return first object with truthy prop', function() {
<ide> obj = this.newObject(ary);
<ide>
<ide> // different values - all eval to true
<del> equal(obj.findBy('foo'), ary[0], 'findBy(foo)');
<del> equal(obj.findBy('bar'), ary[1], 'findBy(bar)');
<add> assert.equal(obj.findBy('foo'), ary[0], 'findBy(foo)');
<add> assert.equal(obj.findBy('bar'), ary[1], 'findBy(bar)');
<ide> });
<ide>
<del>suite.test('should return first null property match', function() {
<add>suite.test('should return first null property match', function(assert) {
<ide> let ary, obj;
<ide>
<ide> ary = [
<ide> suite.test('should return first null property match', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> equal(obj.findBy('foo', null), ary[0], 'findBy(\'foo\', null)');
<del> equal(obj.findBy('bar', null), ary[1], 'findBy(\'bar\', null)');
<add> assert.equal(obj.findBy('foo', null), ary[0], 'findBy(\'foo\', null)');
<add> assert.equal(obj.findBy('bar', null), ary[1], 'findBy(\'bar\', null)');
<ide> });
<ide>
<del>suite.test('should return first undefined property match', function() {
<add>suite.test('should return first undefined property match', function(assert) {
<ide> let ary, obj;
<ide>
<ide> ary = [
<ide> suite.test('should return first undefined property match', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> equal(obj.findBy('foo', undefined), ary[0], 'findBy(\'foo\', undefined)');
<del> equal(obj.findBy('bar', undefined), ary[1], 'findBy(\'bar\', undefined)');
<add> assert.equal(obj.findBy('foo', undefined), ary[0], 'findBy(\'foo\', undefined)');
<add> assert.equal(obj.findBy('bar', undefined), ary[1], 'findBy(\'bar\', undefined)');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/firstObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('firstObject');
<ide>
<del>suite.test('returns first item in enumerable', function() {
<add>suite.test('returns first item in enumerable', function(assert) {
<ide> let obj = this.newObject();
<del> equal(get(obj, 'firstObject'), this.toArray(obj)[0]);
<add> assert.equal(get(obj, 'firstObject'), this.toArray(obj)[0]);
<ide> });
<ide>
<del>suite.test('returns undefined if enumerable is empty', function() {
<add>suite.test('returns undefined if enumerable is empty', function(assert) {
<ide> let obj = this.newObject([]);
<del> equal(get(obj, 'firstObject'), undefined);
<add> assert.equal(get(obj, 'firstObject'), undefined);
<ide> });
<ide>
<del>suite.test('can not be set', function() {
<add>suite.test('can not be set', function(assert) {
<ide> let obj = this.newObject([]);
<ide>
<del> equal(get(obj, 'firstObject'), this.toArray(obj)[0]);
<add> assert.equal(get(obj, 'firstObject'), this.toArray(obj)[0]);
<ide>
<del> throws(() => {
<add> assert.throws(() => {
<ide> set(obj, 'firstObject', 'foo!');
<ide> }, /Cannot set read-only property "firstObject" on object/);
<ide> });
<ide><path>packages/ember-runtime/tests/suites/enumerable/forEach.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('forEach');
<ide>
<del>suite.test('forEach should iterate over list', function() {
<add>suite.test('forEach should iterate over list', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let found = [];
<ide>
<ide> obj.forEach(i => found.push(i));
<del> deepEqual(found, ary, 'items passed during forEach should match');
<add> assert.deepEqual(found, ary, 'items passed during forEach should match');
<ide> });
<ide>
<ide>
<del>suite.test('forEach should iterate over list after mutation', function() {
<add>suite.test('forEach should iterate over list after mutation', function(assert) {
<ide> if (get(this, 'canTestMutation')) {
<del> expect(0);
<add> assert.expect(0);
<ide> return;
<ide> }
<ide>
<ide> suite.test('forEach should iterate over list after mutation', function() {
<ide> let found = [];
<ide>
<ide> obj.forEach(i => found.push(i));
<del> deepEqual(found, ary, 'items passed during forEach should match');
<add> assert.deepEqual(found, ary, 'items passed during forEach should match');
<ide>
<ide> this.mutate(obj);
<ide> ary = this.toArray(obj);
<ide> found = [];
<ide>
<ide> obj.forEach(i => found.push(i));
<del> deepEqual(found, ary, 'items passed during forEach should match');
<add> assert.deepEqual(found, ary, 'items passed during forEach should match');
<ide> });
<ide>
<del>suite.test('2nd target parameter', function() {
<add>suite.test('2nd target parameter', function(assert) {
<ide> let obj = this.newObject();
<ide> let target = this;
<ide>
<ide> suite.test('2nd target parameter', function() {
<ide> });
<ide>
<ide> obj.forEach(() => {
<del> equal(guidFor(this), guidFor(target), 'should pass target as this if context');
<add> assert.equal(guidFor(this), guidFor(target), 'should pass target as this if context');
<ide> }, target);
<ide> });
<ide>
<ide>
<del>suite.test('callback params', function() {
<add>suite.test('callback params', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let loc = 0;
<ide>
<ide> obj.forEach((item, idx, enumerable) => {
<del> equal(item, ary[loc], 'item param');
<del> equal(idx, loc, 'idx param');
<del> equal(guidFor(enumerable), guidFor(obj), 'enumerable param');
<add> assert.equal(item, ary[loc], 'item param');
<add> assert.equal(idx, loc, 'idx param');
<add> assert.equal(guidFor(enumerable), guidFor(obj), 'enumerable param');
<ide> loc++;
<ide> });
<ide> });
<ide><path>packages/ember-runtime/tests/suites/enumerable/includes.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('includes');
<ide>
<del>suite.test('includes returns true if item is in enumerable', function() {
<add>suite.test('includes returns true if item is in enumerable', function(assert) {
<ide> let data = this.newFixture(1);
<ide> let obj = this.newObject([...data, NaN, undefined, null]);
<ide>
<del> equal(obj.includes(data[0]), true, 'should return true if included');
<del> equal(obj.includes(NaN), true, 'should return true if NaN included');
<del> equal(obj.includes(undefined), true, 'should return true if undefined included');
<del> equal(obj.includes(null), true, 'should return true if null included');
<add> assert.equal(obj.includes(data[0]), true, 'should return true if included');
<add> assert.equal(obj.includes(NaN), true, 'should return true if NaN included');
<add> assert.equal(obj.includes(undefined), true, 'should return true if undefined included');
<add> assert.equal(obj.includes(null), true, 'should return true if null included');
<ide> });
<ide>
<del>suite.test('includes returns false if item is not in enumerable', function() {
<add>suite.test('includes returns false if item is not in enumerable', function(assert) {
<ide> let data = this.newFixture(1);
<ide> let obj = this.newObject([...this.newFixture(3), null]);
<ide>
<del> equal(obj.includes(data[0]), false, 'should return false if not included');
<del> equal(obj.includes(undefined), false, 'should return false if undefined not included but null is included');
<add> assert.equal(obj.includes(data[0]), false, 'should return false if not included');
<add> assert.equal(obj.includes(undefined), false, 'should return false if undefined not included but null is included');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/invoke.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('invoke');
<ide>
<del>suite.test('invoke should call on each object that implements', function() {
<add>suite.test('invoke should call on each object that implements', function(assert) {
<ide> let cnt, ary, obj;
<ide>
<ide> function F(amt) {
<ide> suite.test('invoke should call on each object that implements', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide> obj.invoke('foo');
<del> equal(cnt, 3, 'should have invoked 3 times');
<add> assert.equal(cnt, 3, 'should have invoked 3 times');
<ide>
<ide> cnt = 0;
<ide> obj.invoke('foo', 2);
<del> equal(cnt, 6, 'should have invoked 3 times, passing param');
<add> assert.equal(cnt, 6, 'should have invoked 3 times, passing param');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/is_any.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('isAny');
<ide>
<del>suite.test('should return true of any property matches', function() {
<add>suite.test('should return true of any property matches', function(assert) {
<ide> let obj = this.newObject([
<ide> { foo: 'foo', bar: 'BAZ' },
<ide> EmberObject.create({ foo: 'foo', bar: 'bar' })
<ide> ]);
<ide>
<del> equal(obj.isAny('foo', 'foo'), true, 'isAny(foo)');
<del> equal(obj.isAny('bar', 'bar'), true, 'isAny(bar)');
<del> equal(obj.isAny('bar', 'BIFF'), false, 'isAny(BIFF)');
<add> assert.equal(obj.isAny('foo', 'foo'), true, 'isAny(foo)');
<add> assert.equal(obj.isAny('bar', 'bar'), true, 'isAny(bar)');
<add> assert.equal(obj.isAny('bar', 'BIFF'), false, 'isAny(BIFF)');
<ide> });
<ide>
<del>suite.test('should return true of any property is true', function() {
<add>suite.test('should return true of any property is true', function(assert) {
<ide> let obj = this.newObject([
<ide> { foo: 'foo', bar: true },
<ide> EmberObject.create({ foo: 'bar', bar: false })
<ide> ]);
<ide>
<ide> // different values - all eval to true
<del> equal(obj.isAny('foo'), true, 'isAny(foo)');
<del> equal(obj.isAny('bar'), true, 'isAny(bar)');
<del> equal(obj.isAny('BIFF'), false, 'isAny(biff)');
<add> assert.equal(obj.isAny('foo'), true, 'isAny(foo)');
<add> assert.equal(obj.isAny('bar'), true, 'isAny(bar)');
<add> assert.equal(obj.isAny('BIFF'), false, 'isAny(biff)');
<ide> });
<ide>
<del>suite.test('should return true if any property matches null', function() {
<add>suite.test('should return true if any property matches null', function(assert) {
<ide> let obj = this.newObject([
<ide> { foo: null, bar: 'bar' },
<ide> EmberObject.create({ foo: 'foo', bar: null })
<ide> ]);
<ide>
<del> equal(obj.isAny('foo', null), true, 'isAny(\'foo\', null)');
<del> equal(obj.isAny('bar', null), true, 'isAny(\'bar\', null)');
<add> assert.equal(obj.isAny('foo', null), true, 'isAny(\'foo\', null)');
<add> assert.equal(obj.isAny('bar', null), true, 'isAny(\'bar\', null)');
<ide> });
<ide>
<del>suite.test('should return true if any property is undefined', function() {
<add>suite.test('should return true if any property is undefined', function(assert) {
<ide> let obj = this.newObject([
<ide> { foo: undefined, bar: 'bar' },
<ide> EmberObject.create({ foo: 'foo' })
<ide> ]);
<ide>
<del> equal(obj.isAny('foo', undefined), true, 'isAny(\'foo\', undefined)');
<del> equal(obj.isAny('bar', undefined), true, 'isAny(\'bar\', undefined)');
<add> assert.equal(obj.isAny('foo', undefined), true, 'isAny(\'foo\', undefined)');
<add> assert.equal(obj.isAny('bar', undefined), true, 'isAny(\'bar\', undefined)');
<ide> });
<ide>
<del>suite.test('should not match undefined properties without second argument', function() {
<add>suite.test('should not match undefined properties without second argument', function(assert) {
<ide> let obj = this.newObject([
<ide> { foo: undefined },
<ide> EmberObject.create({ })
<ide> ]);
<ide>
<del> equal(obj.isAny('foo'), false, 'isAny(\'foo\', undefined)');
<add> assert.equal(obj.isAny('foo'), false, 'isAny(\'foo\', undefined)');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/lastObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('lastObject');
<ide>
<del>suite.test('returns last item in enumerable', function() {
<add>suite.test('returns last item in enumerable', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide>
<del> equal(get(obj, 'lastObject'), ary[ary.length - 1]);
<add> assert.equal(get(obj, 'lastObject'), ary[ary.length - 1]);
<ide> });
<ide>
<del>suite.test('returns undefined if enumerable is empty', function() {
<add>suite.test('returns undefined if enumerable is empty', function(assert) {
<ide> let obj = this.newObject([]);
<ide>
<del> equal(get(obj, 'lastObject'), undefined);
<add> assert.equal(get(obj, 'lastObject'), undefined);
<ide> });
<ide>
<del>suite.test('can not be set', function() {
<add>suite.test('can not be set', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide>
<del> equal(get(obj, 'lastObject'), ary[ary.length - 1]);
<add> assert.equal(get(obj, 'lastObject'), ary[ary.length - 1]);
<ide>
<del> throws(function() {
<add> assert.throws(function() {
<ide> set(obj, 'lastObject', 'foo!');
<ide> }, /Cannot set read-only property "lastObject" on object/);
<ide> });
<ide><path>packages/ember-runtime/tests/suites/enumerable/map.js
<ide> suite.module('map');
<ide>
<ide> const mapFunc = item => item ? item.toString() : null;
<ide>
<del>suite.test('map should iterate over list', function() {
<add>suite.test('map should iterate over list', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj).map(mapFunc);
<ide> let found = [];
<ide>
<ide> found = obj.map(mapFunc);
<del> deepEqual(found, ary, 'mapped arrays should match');
<add> assert.deepEqual(found, ary, 'mapped arrays should match');
<ide> });
<ide>
<ide>
<del>suite.test('map should iterate over list after mutation', function() {
<add>suite.test('map should iterate over list after mutation', function(assert) {
<ide> if (get(this, 'canTestMutation')) {
<del> expect(0);
<add> assert.expect(0);
<ide> return;
<ide> }
<ide>
<ide> suite.test('map should iterate over list after mutation', function() {
<ide> let found;
<ide>
<ide> found = obj.map(mapFunc);
<del> deepEqual(found, ary, 'items passed during forEach should match');
<add> assert.deepEqual(found, ary, 'items passed during forEach should match');
<ide>
<ide> this.mutate(obj);
<ide> ary = this.toArray(obj).map(mapFunc);
<ide> found = obj.map(mapFunc);
<del> deepEqual(found, ary, 'items passed during forEach should match');
<add> assert.deepEqual(found, ary, 'items passed during forEach should match');
<ide> });
<ide>
<del>suite.test('2nd target parameter', function() {
<add>suite.test('2nd target parameter', function(assert) {
<ide> let obj = this.newObject();
<ide> let target = this;
<ide>
<ide> suite.test('2nd target parameter', function() {
<ide> });
<ide>
<ide> obj.map(() => {
<del> equal(guidFor(this), guidFor(target), 'should pass target as this if context');
<add> assert.equal(guidFor(this), guidFor(target), 'should pass target as this if context');
<ide> }, target);
<ide> });
<ide>
<ide>
<del>suite.test('callback params', function() {
<add>suite.test('callback params', function(assert) {
<ide> let obj = this.newObject();
<ide> let ary = this.toArray(obj);
<ide> let loc = 0;
<ide>
<ide> obj.map((item, idx, enumerable) => {
<del> equal(item, ary[loc], 'item param');
<del> equal(idx, loc, 'idx param');
<del> equal(guidFor(enumerable), guidFor(obj), 'enumerable param');
<add> assert.equal(item, ary[loc], 'item param');
<add> assert.equal(idx, loc, 'idx param');
<add> assert.equal(guidFor(enumerable), guidFor(obj), 'enumerable param');
<ide> loc++;
<ide> });
<ide> });
<ide><path>packages/ember-runtime/tests/suites/enumerable/mapBy.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('mapBy');
<ide>
<del>suite.test('get value of each property', function() {
<add>suite.test('get value of each property', function(assert) {
<ide> let obj = this.newObject([{ a: 1 }, { a: 2 }]);
<del> equal(obj.mapBy('a').join(''), '12');
<add> assert.equal(obj.mapBy('a').join(''), '12');
<ide> });
<ide>
<del>suite.test('should work also through getEach alias', function() {
<add>suite.test('should work also through getEach alias', function(assert) {
<ide> let obj = this.newObject([{ a: 1 }, { a: 2 }]);
<del> equal(obj.getEach('a').join(''), '12');
<add> assert.equal(obj.getEach('a').join(''), '12');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/reduce.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('reduce');
<ide>
<del>suite.test('collects a summary value from an enumeration', function() {
<add>suite.test('collects a summary value from an enumeration', function(assert) {
<ide> let obj = this.newObject([1, 2, 3]);
<ide> let res = obj.reduce((previousValue, item) => previousValue + item, 0);
<del> equal(res, 6);
<add> assert.equal(res, 6);
<ide> });
<ide>
<del>suite.test('passes index of item to callback', function() {
<add>suite.test('passes index of item to callback', function(assert) {
<ide> let obj = this.newObject([1, 2, 3]);
<ide> let res = obj.reduce((previousValue, item, index) => previousValue + index, 0);
<del> equal(res, 3);
<add> assert.equal(res, 3);
<ide> });
<ide>
<del>suite.test('passes enumerable object to callback', function() {
<add>suite.test('passes enumerable object to callback', function(assert) {
<ide> let obj = this.newObject([1, 2, 3]);
<ide> let res = obj.reduce((previousValue, item, index, enumerable) => enumerable, 0);
<del> equal(res, obj);
<add> assert.equal(res, obj);
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/reject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('reject');
<ide>
<del>suite.test('should reject any item that does not meet the condition', function() {
<add>suite.test('should reject any item that does not meet the condition', function(assert) {
<ide> let obj = this.newObject([1, 2, 3, 4]);
<ide> let result;
<ide>
<ide> result = obj.reject(i => i < 3);
<del> deepEqual(result, [3, 4], 'reject the correct items');
<add> assert.deepEqual(result, [3, 4], 'reject the correct items');
<ide> });
<ide>
<del>suite.test('should be the inverse of filter', function() {
<add>suite.test('should be the inverse of filter', function(assert) {
<ide> let obj = this.newObject([1, 2, 3, 4]);
<ide> let isEven = i => i % 2 === 0;
<ide> let filtered, rejected;
<ide>
<ide> filtered = obj.filter(isEven);
<ide> rejected = obj.reject(isEven);
<ide>
<del> deepEqual(filtered, [2, 4], 'filtered evens');
<del> deepEqual(rejected, [1, 3], 'rejected evens');
<add> assert.deepEqual(filtered, [2, 4], 'filtered evens');
<add> assert.deepEqual(rejected, [1, 3], 'rejected evens');
<ide> });
<ide>
<ide> // ..........................................................
<ide> suite.test('should be the inverse of filter', function() {
<ide>
<ide> suite.module('rejectBy');
<ide>
<del>suite.test('should reject based on object', function() {
<add>suite.test('should reject based on object', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should reject based on object', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.rejectBy('foo', 'foo'), [], 'rejectBy(foo)');
<del> deepEqual(obj.rejectBy('bar', 'bar'), [ary[0]], 'rejectBy(bar)');
<add> assert.deepEqual(obj.rejectBy('foo', 'foo'), [], 'rejectBy(foo)');
<add> assert.deepEqual(obj.rejectBy('bar', 'bar'), [ary[0]], 'rejectBy(bar)');
<ide> });
<ide>
<del>suite.test('should include in result if property is false', function() {
<add>suite.test('should include in result if property is false', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should include in result if property is false', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.rejectBy('foo'), ary, 'rejectBy(foo)');
<del> deepEqual(obj.rejectBy('bar'), [ary[1]], 'rejectBy(bar)');
<add> assert.deepEqual(obj.rejectBy('foo'), ary, 'rejectBy(foo)');
<add> assert.deepEqual(obj.rejectBy('bar'), [ary[1]], 'rejectBy(bar)');
<ide> });
<ide>
<del>suite.test('should reject on second argument if provided', function() {
<add>suite.test('should reject on second argument if provided', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should reject on second argument if provided', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.rejectBy('foo', 3), [ary[1], ary[2]], 'rejectBy(\'foo\', 3)\')');
<add> assert.deepEqual(obj.rejectBy('foo', 3), [ary[1], ary[2]], 'rejectBy(\'foo\', 3)\')');
<ide> });
<ide>
<del>suite.test('should correctly reject null second argument', function() {
<add>suite.test('should correctly reject null second argument', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should correctly reject null second argument', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.rejectBy('foo', null), [ary[0], ary[3]], 'rejectBy(\'foo\', null)\')');
<add> assert.deepEqual(obj.rejectBy('foo', null), [ary[0], ary[3]], 'rejectBy(\'foo\', null)\')');
<ide> });
<ide>
<del>suite.test('should correctly reject undefined second argument', function() {
<add>suite.test('should correctly reject undefined second argument', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should correctly reject undefined second argument', function() {
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.rejectBy('bar', undefined), [], 'rejectBy(\'bar\', undefined)\')');
<add> assert.deepEqual(obj.rejectBy('bar', undefined), [], 'rejectBy(\'bar\', undefined)\')');
<ide> });
<ide>
<del>suite.test('should correctly reject explicit undefined second argument', function() {
<add>suite.test('should correctly reject explicit undefined second argument', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should correctly reject explicit undefined second argument', functio
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.rejectBy('foo', undefined), ary.slice(0, 2), 'rejectBy(\'foo\', undefined)\')');
<add> assert.deepEqual(obj.rejectBy('foo', undefined), ary.slice(0, 2), 'rejectBy(\'foo\', undefined)\')');
<ide> });
<ide>
<del>suite.test('should match undefined, null, or false properties without second argument', function() {
<add>suite.test('should match undefined, null, or false properties without second argument', function(assert) {
<ide> let obj, ary;
<ide>
<ide> ary = [
<ide> suite.test('should match undefined, null, or false properties without second arg
<ide>
<ide> obj = this.newObject(ary);
<ide>
<del> deepEqual(obj.rejectBy('foo'), ary.slice(2), 'rejectBy(\'foo\')\')');
<add> assert.deepEqual(obj.rejectBy('foo'), ary.slice(2), 'rejectBy(\'foo\')\')');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/sortBy.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('sortBy');
<ide>
<del>suite.test('sort by value of property', function() {
<add>suite.test('sort by value of property', function(assert) {
<ide> let obj = this.newObject([{ a: 2 }, { a: 1 }]);
<ide> let sorted = obj.sortBy('a');
<ide>
<del> equal(get(sorted[0], 'a'), 1);
<del> equal(get(sorted[1], 'a'), 2);
<add> assert.equal(get(sorted[0], 'a'), 1);
<add> assert.equal(get(sorted[1], 'a'), 2);
<ide> });
<ide>
<del>suite.test('supports multiple propertyNames', function() {
<add>suite.test('supports multiple propertyNames', function(assert) {
<ide> let obj = this.newObject([{ a: 1, b: 2 }, { a: 1, b: 1 }]);
<ide> let sorted = obj.sortBy('a', 'b');
<ide>
<del> equal(get(sorted[0], 'b'), 1);
<del> equal(get(sorted[1], 'b'), 2);
<add> assert.equal(get(sorted[0], 'b'), 1);
<add> assert.equal(get(sorted[1], 'b'), 2);
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/toArray.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('toArray');
<ide>
<del>suite.test('toArray should convert to an array', function() {
<add>suite.test('toArray should convert to an array', function(assert) {
<ide> let obj = this.newObject();
<del> deepEqual(obj.toArray(), this.toArray(obj));
<add> assert.deepEqual(obj.toArray(), this.toArray(obj));
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/uniq.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('uniq');
<ide>
<del>suite.test('should return new instance with duplicates removed', function() {
<add>suite.test('should return new instance with duplicates removed', function(assert) {
<ide> let before, after, obj, ret;
<ide>
<ide> after = this.newFixture(3);
<ide> suite.test('should return new instance with duplicates removed', function() {
<ide> before = obj.toArray(); // in case of set before will be different...
<ide>
<ide> ret = obj.uniq();
<del> deepEqual(this.toArray(ret), after, 'should have removed item');
<del> deepEqual(this.toArray(obj), before, 'should not have changed original');
<add> assert.deepEqual(this.toArray(ret), after, 'should have removed item');
<add> assert.deepEqual(this.toArray(obj), before, 'should not have changed original');
<ide> });
<ide>
<del>suite.test('should return duplicate of same content if no duplicates found', function() {
<add>suite.test('should return duplicate of same content if no duplicates found', function(assert) {
<ide> let item, obj, ret;
<ide> obj = this.newObject(this.newFixture(3));
<ide> ret = obj.uniq(item);
<del> ok(ret !== obj, 'should not be same object');
<del> deepEqual(this.toArray(ret), this.toArray(obj), 'should be the same content');
<add> assert.ok(ret !== obj, 'should not be same object');
<add> assert.deepEqual(this.toArray(ret), this.toArray(obj), 'should be the same content');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/enumerable/uniqBy.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('uniqBy');
<ide>
<del>suite.test('should return new instance with duplicates removed', function() {
<add>suite.test('should return new instance with duplicates removed', function(assert) {
<ide> let numbers = this.newObject([
<ide> { id: 1, value: 'one' },
<ide> { id: 2, value: 'two' },
<ide> { id: 1, value: 'one' }
<ide> ]);
<del> deepEqual(numbers.uniqBy('id'), [
<add> assert.deepEqual(numbers.uniqBy('id'), [
<ide> { id: 1, value: 'one' },
<ide> { id: 2, value: 'two' }
<ide> ]);
<ide><path>packages/ember-runtime/tests/suites/enumerable/without.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('without');
<ide>
<del>suite.test('should return new instance with item removed', function() {
<add>suite.test('should return new instance with item removed', function(assert) {
<ide> let before, after, obj, ret;
<ide>
<ide> before = this.newFixture(3);
<ide> after = [before[0], before[2]];
<ide> obj = this.newObject(before);
<ide>
<ide> ret = obj.without(before[1]);
<del> deepEqual(this.toArray(ret), after, 'should have removed item');
<del> deepEqual(this.toArray(obj), before, 'should not have changed original');
<add> assert.deepEqual(this.toArray(ret), after, 'should have removed item');
<add> assert.deepEqual(this.toArray(obj), before, 'should not have changed original');
<ide> });
<ide>
<del>suite.test('should remove NaN value', function() {
<add>suite.test('should remove NaN value', function(assert) {
<ide> let before, after, obj, ret;
<ide>
<ide> before = [...this.newFixture(2), NaN];
<ide> after = [before[0], before[1]];
<ide> obj = this.newObject(before);
<ide>
<ide> ret = obj.without(NaN);
<del> deepEqual(this.toArray(ret), after, 'should have removed item');
<add> assert.deepEqual(this.toArray(ret), after, 'should have removed item');
<ide> });
<ide>
<del>suite.test('should return same instance if object not found', function() {
<add>suite.test('should return same instance if object not found', function(assert) {
<ide> let item, obj, ret;
<ide>
<ide> item = this.newFixture(1)[0];
<ide> obj = this.newObject(this.newFixture(3));
<ide>
<ide> ret = obj.without(item);
<del> equal(ret, obj, 'should be same instance');
<add> assert.equal(ret, obj, 'should be same instance');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/addObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('addObject');
<ide>
<del>suite.test('should return receiver', function() {
<add>suite.test('should return receiver', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let obj = this.newObject(before);
<del> equal(obj.addObject(before[1]), obj, 'should return receiver');
<add> assert.equal(obj.addObject(before[1]), obj, 'should return receiver');
<ide> });
<ide>
<del>suite.test('[A,B].addObject(C) => [A,B,C] + notify', function() {
<add>suite.test('[A,B].addObject(C) => [A,B,C] + notify', function(assert) {
<ide> let before = this.newFixture(2);
<ide> let item = this.newFixture(1)[0];
<ide> let after = [before[0], before[1], item];
<ide> suite.test('[A,B].addObject(C) => [A,B,C] + notify', function() {
<ide>
<ide> obj.addObject(item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<ide> }
<ide> });
<ide>
<del>suite.test('[A,B,C].addObject(A) => [A,B,C] + NO notify', function() {
<add>suite.test('[A,B,C].addObject(A) => [A,B,C] + NO notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let after = before;
<ide> let item = before[0];
<ide> suite.test('[A,B,C].addObject(A) => [A,B,C] + NO notify', function() {
<ide>
<ide> obj.addObject(item); // note: item in set
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.validate('[]'), false, 'should NOT have notified []');
<del> equal(observer.validate('@each'), false, 'should NOT have notified @each');
<del> equal(observer.validate('length'), false, 'should NOT have notified length');
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('[]'), false, 'should NOT have notified []');
<add> assert.equal(observer.validate('@each'), false, 'should NOT have notified @each');
<add> assert.equal(observer.validate('length'), false, 'should NOT have notified length');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-runtime/tests/suites/mutable_array/clear.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('clear');
<ide>
<del>suite.test('[].clear() => [] + notify', function () {
<add>suite.test('[].clear() => [] + notify', function (assert) {
<ide> let before = [];
<ide> let after = [];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.clear(), obj, 'return self');
<add> assert.equal(obj.clear(), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.validate('[]'), false, 'should NOT have notified [] once');
<del> equal(observer.validate('@each'), false, 'should NOT have notified @each once');
<del> equal(observer.validate('length'), false, 'should NOT have notified length once');
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('[]'), false, 'should NOT have notified [] once');
<add> assert.equal(observer.validate('@each'), false, 'should NOT have notified @each once');
<add> assert.equal(observer.validate('length'), false, 'should NOT have notified length once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[X].clear() => [] + notify', function () {
<add>suite.test('[X].clear() => [] + notify', function (assert) {
<ide> var obj, before, after, observer;
<ide>
<ide> before = this.newFixture(1);
<ide> suite.test('[X].clear() => [] + notify', function () {
<ide> observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.clear(), obj, 'return self');
<add> assert.equal(obj.clear(), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/insertAt.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('insertAt');
<ide>
<del>suite.test('[].insertAt(0, X) => [X] + notify', function() {
<add>suite.test('[].insertAt(0, X) => [X] + notify', function(assert) {
<ide> let after = this.newFixture(1);
<ide> let obj = this.newObject([]);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide> suite.test('[].insertAt(0, X) => [X] + notify', function() {
<ide>
<ide> obj.insertAt(0, after[0]);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide>
<del> equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<del> equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<del> equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<del> equal(observer.timesCalledBefore('firstObject'), 1, 'should have notified firstObject will change once');
<del> equal(observer.timesCalledBefore('lastObject'), 1, 'should have notified lastObject will change once');
<add> assert.equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<add> assert.equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<add> assert.equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<add> assert.equal(observer.timesCalledBefore('firstObject'), 1, 'should have notified firstObject will change once');
<add> assert.equal(observer.timesCalledBefore('lastObject'), 1, 'should have notified lastObject will change once');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] did change once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each did change once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length did change once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject did change once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject did change once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] did change once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each did change once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length did change once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject did change once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject did change once');
<ide> });
<ide>
<del>suite.test('[].insertAt(200,X) => OUT_OF_RANGE_EXCEPTION exception', function() {
<add>suite.test('[].insertAt(200,X) => OUT_OF_RANGE_EXCEPTION exception', function(assert) {
<ide> let obj = this.newObject([]);
<ide> let that = this;
<ide>
<del> throws(() => obj.insertAt(200, that.newFixture(1)[0]), Error);
<add> assert.throws(() => obj.insertAt(200, that.newFixture(1)[0]), Error);
<ide> });
<ide>
<del>suite.test('[A].insertAt(0, X) => [X,A] + notify', function() {
<add>suite.test('[A].insertAt(0, X) => [X,A] + notify', function(assert) {
<ide> let item = this.newFixture(1)[0];
<ide> let before = this.newFixture(1);
<ide> let after = [item, before[0]];
<ide> suite.test('[A].insertAt(0, X) => [X,A] + notify', function() {
<ide>
<ide> obj.insertAt(0, item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<del> equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<del> equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<del> equal(observer.timesCalledBefore('firstObject'), 1, 'should have notified firstObject will change once');
<del> equal(observer.timesCalledBefore('lastObject'), 0, 'should NOT have notified lastObject will change once');
<add> assert.equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<add> assert.equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<add> assert.equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<add> assert.equal(observer.timesCalledBefore('firstObject'), 1, 'should have notified firstObject will change once');
<add> assert.equal(observer.timesCalledBefore('lastObject'), 0, 'should NOT have notified lastObject will change once');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<ide>
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> });
<ide>
<del>suite.test('[A].insertAt(1, X) => [A,X] + notify', function() {
<add>suite.test('[A].insertAt(1, X) => [A,X] + notify', function(assert) {
<ide> let item = this.newFixture(1)[0];
<ide> let before = this.newFixture(1);
<ide> let after = [before[0], item];
<ide> suite.test('[A].insertAt(1, X) => [A,X] + notify', function() {
<ide>
<ide> obj.insertAt(1, item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<del> equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<del> equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<del> equal(observer.timesCalledBefore('firstObject'), 0, 'should NOT have notified firstObject will change once');
<del> equal(observer.timesCalledBefore('lastObject'), 1, 'should have notified lastObject will change once');
<add> assert.equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<add> assert.equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<add> assert.equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<add> assert.equal(observer.timesCalledBefore('firstObject'), 0, 'should NOT have notified firstObject will change once');
<add> assert.equal(observer.timesCalledBefore('lastObject'), 1, 'should have notified lastObject will change once');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<ide> });
<ide>
<del>suite.test('[A].insertAt(200,X) => OUT_OF_RANGE exception', function() {
<add>suite.test('[A].insertAt(200,X) => OUT_OF_RANGE exception', function(assert) {
<ide> let obj = this.newObject(this.newFixture(1));
<ide> let that = this;
<ide>
<del> throws(() => obj.insertAt(200, that.newFixture(1)[0]), Error);
<add> assert.throws(() => obj.insertAt(200, that.newFixture(1)[0]), Error);
<ide> });
<ide>
<del>suite.test('[A,B,C].insertAt(0,X) => [X,A,B,C] + notify', function() {
<add>suite.test('[A,B,C].insertAt(0,X) => [X,A,B,C] + notify', function(assert) {
<ide> let item = this.newFixture(1)[0];
<ide> let before = this.newFixture(3);
<ide> let after = [item, before[0], before[1], before[2]];
<ide> suite.test('[A,B,C].insertAt(0,X) => [X,A,B,C] + notify', function() {
<ide>
<ide> obj.insertAt(0, item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<del> equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<del> equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<del> equal(observer.timesCalledBefore('firstObject'), 1, 'should have notified firstObject will change once');
<del> equal(observer.timesCalledBefore('lastObject'), 0, 'should NOT have notified lastObject will change once');
<add> assert.equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<add> assert.equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<add> assert.equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<add> assert.equal(observer.timesCalledBefore('firstObject'), 1, 'should have notified firstObject will change once');
<add> assert.equal(observer.timesCalledBefore('lastObject'), 0, 'should NOT have notified lastObject will change once');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<ide>
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> });
<ide>
<del>suite.test('[A,B,C].insertAt(1,X) => [A,X,B,C] + notify', function() {
<add>suite.test('[A,B,C].insertAt(1,X) => [A,X,B,C] + notify', function(assert) {
<ide> let item = this.newFixture(1)[0];
<ide> let before = this.newFixture(3);
<ide> let after = [before[0], item, before[1], before[2]];
<ide> suite.test('[A,B,C].insertAt(1,X) => [A,X,B,C] + notify', function() {
<ide> objectAtCalls.splice(0, objectAtCalls.length);
<ide>
<ide> obj.insertAt(1, item);
<del> deepEqual(objectAtCalls, [], 'objectAt is not called when only inserting items');
<add> assert.deepEqual(objectAtCalls, [], 'objectAt is not called when only inserting items');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<del> equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<del> equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<del> equal(observer.timesCalledBefore('firstObject'), 0, 'should NOT have notified firstObject will change once');
<del> equal(observer.timesCalledBefore('lastObject'), 0, 'should NOT have notified lastObject will change once');
<add> assert.equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<add> assert.equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<add> assert.equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<add> assert.equal(observer.timesCalledBefore('firstObject'), 0, 'should NOT have notified firstObject will change once');
<add> assert.equal(observer.timesCalledBefore('lastObject'), 0, 'should NOT have notified lastObject will change once');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> });
<ide>
<del>suite.test('[A,B,C].insertAt(3,X) => [A,B,C,X] + notify', function() {
<add>suite.test('[A,B,C].insertAt(3,X) => [A,B,C,X] + notify', function(assert) {
<ide> let item = this.newFixture(1)[0];
<ide> let before = this.newFixture(3);
<ide> let after = [before[0], before[1], before[2], item];
<ide> suite.test('[A,B,C].insertAt(3,X) => [A,B,C,X] + notify', function() {
<ide>
<ide> obj.insertAt(3, item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<del> equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<del> equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<del> equal(observer.timesCalledBefore('firstObject'), 0, 'should NOT have notified firstObject will change once');
<del> equal(observer.timesCalledBefore('lastObject'), 1, 'should have notified lastObject will change once');
<add> assert.equal(observer.timesCalledBefore('[]'), 1, 'should have notified [] will change once');
<add> assert.equal(observer.timesCalledBefore('@each'), 0, 'should not have notified @each will change once');
<add> assert.equal(observer.timesCalledBefore('length'), 1, 'should have notified length will change once');
<add> assert.equal(observer.timesCalledBefore('firstObject'), 0, 'should NOT have notified firstObject will change once');
<add> assert.equal(observer.timesCalledBefore('lastObject'), 1, 'should have notified lastObject will change once');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/popObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('popObject');
<ide>
<del>suite.test('[].popObject() => [] + returns undefined + NO notify', function() {
<add>suite.test('[].popObject() => [] + returns undefined + NO notify', function(assert) {
<ide> let obj = this.newObject([]);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.popObject(), undefined, 'popObject results');
<add> assert.equal(obj.popObject(), undefined, 'popObject results');
<ide>
<del> deepEqual(this.toArray(obj), [], 'post item results');
<add> assert.deepEqual(this.toArray(obj), [], 'post item results');
<ide>
<del> equal(observer.validate('[]'), false, 'should NOT have notified []');
<del> equal(observer.validate('@each'), false, 'should NOT have notified @each');
<del> equal(observer.validate('length'), false, 'should NOT have notified length');
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('[]'), false, 'should NOT have notified []');
<add> assert.equal(observer.validate('@each'), false, 'should NOT have notified @each');
<add> assert.equal(observer.validate('length'), false, 'should NOT have notified length');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> });
<ide>
<del>suite.test('[X].popObject() => [] + notify', function() {
<add>suite.test('[X].popObject() => [] + notify', function(assert) {
<ide> let before = this.newFixture(1);
<ide> let after = [];
<ide> let obj = this.newObject(before);
<ide> suite.test('[X].popObject() => [] + notify', function() {
<ide>
<ide> let ret = obj.popObject();
<ide>
<del> equal(ret, before[0], 'return object');
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.equal(ret, before[0], 'return object');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C].popObject() => [A,B] + notify', function() {
<add>suite.test('[A,B,C].popObject() => [A,B] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let after = [before[0], before[1]];
<ide> let obj = this.newObject(before);
<ide> suite.test('[A,B,C].popObject() => [A,B] + notify', function() {
<ide>
<ide> let ret = obj.popObject();
<ide>
<del> equal(ret, before[2], 'return object');
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.equal(ret, before[2], 'return object');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/pushObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('pushObject');
<ide>
<del>suite.test('returns pushed object', function() {
<add>suite.test('returns pushed object', function(assert) {
<ide> let exp = this.newFixture(1)[0];
<ide> let obj = this.newObject([]);
<ide>
<del> equal(obj.pushObject(exp), exp, 'should return pushed object');
<add> assert.equal(obj.pushObject(exp), exp, 'should return pushed object');
<ide> });
<ide>
<del>suite.test('[].pushObject(X) => [X] + notify', function() {
<add>suite.test('[].pushObject(X) => [X] + notify', function(assert) {
<ide> let before = [];
<ide> let after = this.newFixture(1);
<ide> let obj = this.newObject(before);
<ide> suite.test('[].pushObject(X) => [X] + notify', function() {
<ide>
<ide> obj.pushObject(after[0]);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C].pushObject(X) => [A,B,C,X] + notify', function() {
<add>suite.test('[A,B,C].pushObject(X) => [A,B,C,X] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let item = this.newFixture(1)[0];
<ide> let after = [before[0], before[1], before[2], item];
<ide> suite.test('[A,B,C].pushObject(X) => [A,B,C,X] + notify', function() {
<ide>
<ide> obj.pushObject(item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<ide> });
<ide>
<del>suite.test('[A,B,C,C].pushObject(A) => [A,B,C,C] + notify', function() {
<add>suite.test('[A,B,C,C].pushObject(A) => [A,B,C,C] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let item = before[2]; // note same object as current tail. should end up twice
<ide> let after = [before[0], before[1], before[2], item];
<ide> suite.test('[A,B,C,C].pushObject(A) => [A,B,C,C] + notify', function() {
<ide>
<ide> obj.pushObject(item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), true, 'should have notified lastObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), true, 'should have notified lastObject');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/pushObjects.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('pushObjects');
<ide>
<del>suite.test('should raise exception if not Ember.Enumerable is passed to pushObjects', function() {
<add>suite.test('should raise exception if not Ember.Enumerable is passed to pushObjects', function(assert) {
<ide> let obj = this.newObject([]);
<ide>
<del> throws(() => obj.pushObjects('string'));
<add> assert.throws(() => obj.pushObjects('string'));
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/removeAt.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('removeAt');
<ide>
<del>suite.test('removeAt([X], 0) => [] + notify', function() {
<add>suite.test('removeAt([X], 0) => [] + notify', function(assert) {
<ide> let before = this.newFixture(1);
<ide> let after = [];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(removeAt(obj, 0), obj, 'return self');
<add> assert.equal(removeAt(obj, 0), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<del>suite.test('removeAt([], 200) => OUT_OF_RANGE_EXCEPTION exception', function() {
<add>suite.test('removeAt([], 200) => OUT_OF_RANGE_EXCEPTION exception', function(assert) {
<ide> let obj = this.newObject([]);
<del> throws(() => removeAt(obj, 200), Error);
<add> assert.throws(() => removeAt(obj, 200), Error);
<ide> });
<ide>
<del>suite.test('removeAt([A,B], 0) => [B] + notify', function() {
<add>suite.test('removeAt([A,B], 0) => [B] + notify', function(assert) {
<ide> let before = this.newFixture(2);
<ide> let after = [before[1]];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(removeAt(obj, 0), obj, 'return self');
<add> assert.equal(removeAt(obj, 0), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<ide>
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> });
<ide>
<del>suite.test('removeAt([A,B], 1) => [A] + notify', function() {
<add>suite.test('removeAt([A,B], 1) => [A] + notify', function(assert) {
<ide> let before = this.newFixture(2);
<ide> let after = [before[0]];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(removeAt(obj, 1), obj, 'return self');
<add> assert.equal(removeAt(obj, 1), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<ide> });
<ide>
<del>suite.test('removeAt([A,B,C], 1) => [A,C] + notify', function() {
<add>suite.test('removeAt([A,B,C], 1) => [A,C] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let after = [before[0], before[2]];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(removeAt(obj, 1), obj, 'return self');
<add> assert.equal(removeAt(obj, 1), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<del>suite.test('removeAt([A,B,C,D], 1,2) => [A,D] + notify', function() {
<add>suite.test('removeAt([A,B,C,D], 1,2) => [A,D] + notify', function(assert) {
<ide> let before = this.newFixture(4);
<ide> let after = [before[0], before[3]];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(removeAt(obj, 1, 2), obj, 'return self');
<add> assert.equal(removeAt(obj, 1, 2), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C,D].removeAt(1,2) => [A,D] + notify', function() {
<add>suite.test('[A,B,C,D].removeAt(1,2) => [A,D] + notify', function(assert) {
<ide> var obj, before, after, observer;
<ide>
<ide> before = this.newFixture(4);
<ide> suite.test('[A,B,C,D].removeAt(1,2) => [A,D] + notify', function() {
<ide> observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.removeAt(1, 2), obj, 'return self');
<add> assert.equal(obj.removeAt(1, 2), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/removeObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('removeObject');
<ide>
<del>suite.test('should return receiver', function() {
<add>suite.test('should return receiver', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let obj = this.newObject(before);
<ide>
<del> equal(obj.removeObject(before[1]), obj, 'should return receiver');
<add> assert.equal(obj.removeObject(before[1]), obj, 'should return receiver');
<ide> });
<ide>
<del>suite.test('[A,B,C].removeObject(B) => [A,C] + notify', function() {
<add>suite.test('[A,B,C].removeObject(B) => [A,C] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let after = [before[0], before[2]];
<ide> let obj = this.newObject(before);
<ide> suite.test('[A,B,C].removeObject(B) => [A,C] + notify', function() {
<ide>
<ide> obj.removeObject(before[1]);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> }
<ide> });
<ide>
<del>suite.test('[A,B,C].removeObject(D) => [A,B,C]', function() {
<add>suite.test('[A,B,C].removeObject(D) => [A,B,C]', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let after = before;
<ide> let item = this.newFixture(1)[0];
<ide> suite.test('[A,B,C].removeObject(D) => [A,B,C]', function() {
<ide>
<ide> obj.removeObject(item); // note: item not in set
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.validate('[]'), false, 'should NOT have notified []');
<del> equal(observer.validate('@each'), false, 'should NOT have notified @each');
<del> equal(observer.validate('length'), false, 'should NOT have notified length');
<add> assert.equal(observer.validate('[]'), false, 'should NOT have notified []');
<add> assert.equal(observer.validate('@each'), false, 'should NOT have notified @each');
<add> assert.equal(observer.validate('length'), false, 'should NOT have notified length');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-runtime/tests/suites/mutable_array/replace.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('replace');
<ide>
<del>suite.test('[].replace(0,0,\'X\') => [\'X\'] + notify', function() {
<add>suite.test('[].replace(0,0,\'X\') => [\'X\'] + notify', function(assert) {
<ide> let exp = this.newFixture(1);
<ide> let obj = this.newObject([]);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide> suite.test('[].replace(0,0,\'X\') => [\'X\'] + notify', function() {
<ide>
<ide> obj.replace(0, 0, exp);
<ide>
<del> deepEqual(this.toArray(obj), exp, 'post item results');
<add> assert.deepEqual(this.toArray(obj), exp, 'post item results');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[].replace(0,0,"X") => ["X"] + avoid calling objectAt and notifying fistObject/lastObject when not in cache', function() {
<add>suite.test('[].replace(0,0,"X") => ["X"] + avoid calling objectAt and notifying fistObject/lastObject when not in cache', function(assert) {
<ide> var obj, exp, observer;
<ide> var called = 0;
<ide> exp = this.newFixture(1);
<ide> suite.test('[].replace(0,0,"X") => ["X"] + avoid calling objectAt and notifying
<ide>
<ide> obj.replace(0, 0, exp);
<ide>
<del> equal(called, 0, 'should NOT have called objectAt upon replace when firstObject/lastObject are not cached');
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject since not cached');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject since not cached');
<add> assert.equal(called, 0, 'should NOT have called objectAt upon replace when firstObject/lastObject are not cached');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject since not cached');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject since not cached');
<ide> });
<ide>
<del>suite.test('[A,B,C,D].replace(1,2,X) => [A,X,D] + notify', function() {
<add>suite.test('[A,B,C,D].replace(1,2,X) => [A,X,D] + notify', function(assert) {
<ide> let before = this.newFixture(4);
<ide> let replace = this.newFixture(1);
<ide> let after = [before[0], replace[0], before[3]];
<ide> suite.test('[A,B,C,D].replace(1,2,X) => [A,X,D] + notify', function() {
<ide>
<ide> obj.replace(1, 2, replace);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C,D].replace(1,2,[X,Y]) => [A,X,Y,D] + notify', function() {
<add>suite.test('[A,B,C,D].replace(1,2,[X,Y]) => [A,X,Y,D] + notify', function(assert) {
<ide> let before = this.newFixture(4);
<ide> let replace = this.newFixture(2);
<ide> let after = [before[0], replace[0], replace[1], before[3]];
<ide> suite.test('[A,B,C,D].replace(1,2,[X,Y]) => [A,X,Y,D] + notify', function() {
<ide>
<ide> obj.replace(1, 2, replace);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.validate('length'), false, 'should NOT have notified length');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.validate('length'), false, 'should NOT have notified length');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B].replace(1,0,[X,Y]) => [A,X,Y,B] + notify', function() {
<add>suite.test('[A,B].replace(1,0,[X,Y]) => [A,X,Y,B] + notify', function(assert) {
<ide> let before = this.newFixture(2);
<ide> let replace = this.newFixture(2);
<ide> let after = [before[0], replace[0], replace[1], before[1]];
<ide> suite.test('[A,B].replace(1,0,[X,Y]) => [A,X,Y,B] + notify', function() {
<ide>
<ide> obj.replace(1, 0, replace);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C,D].replace(2,2) => [A,B] + notify', function() {
<add>suite.test('[A,B,C,D].replace(2,2) => [A,B] + notify', function(assert) {
<ide> let before = this.newFixture(4);
<ide> let after = [before[0], before[1]];
<ide>
<ide> suite.test('[A,B,C,D].replace(2,2) => [A,B] + notify', function() {
<ide>
<ide> obj.replace(2, 2);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C,D].replace(-1,1) => [A,B,C] + notify', function() {
<add>suite.test('[A,B,C,D].replace(-1,1) => [A,B,C] + notify', function(assert) {
<ide> let before = this.newFixture(4);
<ide> let after = [before[0], before[1], before[2]];
<ide>
<ide> suite.test('[A,B,C,D].replace(-1,1) => [A,B,C] + notify', function() {
<ide>
<ide> obj.replace(-1, 1);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<ide> });
<ide>
<del>suite.test('Adding object should notify enumerable observer', function() {
<add>suite.test('Adding object should notify enumerable observer', function(assert) {
<ide> let fixtures = this.newFixture(4);
<ide> let obj = this.newObject(fixtures);
<ide> let observer = this.newObserver(obj).observeEnumerable(obj);
<ide> let item = this.newFixture(1)[0];
<ide>
<ide> obj.replace(2, 2, [item]);
<ide>
<del> deepEqual(observer._before, [obj, [fixtures[2], fixtures[3]], 1], 'before');
<del> deepEqual(observer._after, [obj, 2, [item]], 'after');
<add> assert.deepEqual(observer._before, [obj, [fixtures[2], fixtures[3]], 1], 'before');
<add> assert.deepEqual(observer._after, [obj, 2, [item]], 'after');
<ide> });
<ide>
<del>suite.test('Adding object should notify array observer', function() {
<add>suite.test('Adding object should notify array observer', function(assert) {
<ide> let fixtures = this.newFixture(4);
<ide> let obj = this.newObject(fixtures);
<ide> let observer = this.newObserver(obj).observeArray(obj);
<ide> let item = this.newFixture(1)[0];
<ide>
<ide> obj.replace(2, 2, [item]);
<ide>
<del> deepEqual(observer._before, [obj, 2, 2, 1], 'before');
<del> deepEqual(observer._after, [obj, 2, 2, 1], 'after');
<add> assert.deepEqual(observer._before, [obj, 2, 2, 1], 'before');
<add> assert.deepEqual(observer._after, [obj, 2, 2, 1], 'after');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/reverseObjects.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('reverseObjects');
<ide>
<del>suite.test('[A,B,C].reverseObjects() => [] + notify', function () {
<add>suite.test('[A,B,C].reverseObjects() => [] + notify', function (assert) {
<ide> let before = this.newFixture(3);
<ide> let after = [before[2], before[1], before[0]];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.reverseObjects(), obj, 'return self');
<add> assert.equal(obj.reverseObjects(), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 0, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 0, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/setObjects.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('setObjects');
<ide>
<del>suite.test('[A,B,C].setObjects([]) = > [] + notify', function() {
<add>suite.test('[A,B,C].setObjects([]) = > [] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let after = [];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.setObjects(after), obj, 'return self');
<add> assert.equal(obj.setObjects(after), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C].setObjects([D, E, F, G]) = > [D, E, F, G] + notify', function() {
<add>suite.test('[A,B,C].setObjects([D, E, F, G]) = > [D, E, F, G] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let after = this.newFixture(4);
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.setObjects(after), obj, 'return self');
<add> assert.equal(obj.setObjects(after), obj, 'return self');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/shiftObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('shiftObject');
<ide>
<del>suite.test('[].shiftObject() => [] + returns undefined + NO notify', function() {
<add>suite.test('[].shiftObject() => [] + returns undefined + NO notify', function(assert) {
<ide> let before = [];
<ide> let after = [];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.shiftObject(), undefined);
<add> assert.equal(obj.shiftObject(), undefined);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.validate('[]', undefined, 1), false, 'should NOT have notified [] once');
<del> equal(observer.validate('@each', undefined, 1), false, 'should NOT have notified @each once');
<del> equal(observer.validate('length', undefined, 1), false, 'should NOT have notified length once');
<add> assert.equal(observer.validate('[]', undefined, 1), false, 'should NOT have notified [] once');
<add> assert.equal(observer.validate('@each', undefined, 1), false, 'should NOT have notified @each once');
<add> assert.equal(observer.validate('length', undefined, 1), false, 'should NOT have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[X].shiftObject() => [] + notify', function() {
<add>suite.test('[X].shiftObject() => [] + notify', function(assert) {
<ide> let before = this.newFixture(1);
<ide> let after = [];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.shiftObject(), before[0], 'should return object');
<add> assert.equal(obj.shiftObject(), before[0], 'should return object');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C].shiftObject() => [B,C] + notify', function() {
<add>suite.test('[A,B,C].shiftObject() => [B,C] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let after = [before[1], before[2]];
<ide> let obj = this.newObject(before);
<ide> let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<ide>
<ide> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<ide>
<del> equal(obj.shiftObject(), before[0], 'should return object');
<add> assert.equal(obj.shiftObject(), before[0], 'should return object');
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<ide>
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/unshiftObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('unshiftObject');
<ide>
<del>suite.test('returns unshifted object', function() {
<add>suite.test('returns unshifted object', function(assert) {
<ide> let obj = this.newObject([]);
<ide> let item = this.newFixture(1)[0];
<ide>
<del> equal(obj.unshiftObject(item), item, 'should return unshifted object');
<add> assert.equal(obj.unshiftObject(item), item, 'should return unshifted object');
<ide> });
<ide>
<del>suite.test('[].unshiftObject(X) => [X] + notify', function() {
<add>suite.test('[].unshiftObject(X) => [X] + notify', function(assert) {
<ide> let before = [];
<ide> let item = this.newFixture(1)[0];
<ide> let after = [item];
<ide> suite.test('[].unshiftObject(X) => [X] + notify', function() {
<ide>
<ide> obj.unshiftObject(item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C].unshiftObject(X) => [X,A,B,C] + notify', function() {
<add>suite.test('[A,B,C].unshiftObject(X) => [X,A,B,C] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let item = this.newFixture(1)[0];
<ide> let after = [item, before[0], before[1], before[2]];
<ide> suite.test('[A,B,C].unshiftObject(X) => [X,A,B,C] + notify', function() {
<ide>
<ide> obj.unshiftObject(item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<ide>
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> });
<ide>
<del>suite.test('[A,B,C].unshiftObject(A) => [A,A,B,C] + notify', function() {
<add>suite.test('[A,B,C].unshiftObject(A) => [A,A,B,C] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let item = before[0]; // note same object as current head. should end up twice
<ide> let after = [item, before[0], before[1], before[2]];
<ide> suite.test('[A,B,C].unshiftObject(A) => [A,A,B,C] + notify', function() {
<ide>
<ide> obj.unshiftObject(item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), true, 'should have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('firstObject'), true, 'should have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_array/unshiftObjects.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('unshiftObjects');
<ide>
<del>suite.test('returns receiver', function() {
<add>suite.test('returns receiver', function(assert) {
<ide> let obj = this.newObject([]);
<ide> let items = this.newFixture(3);
<ide>
<del> equal(obj.unshiftObjects(items), obj, 'should return receiver');
<add> assert.equal(obj.unshiftObjects(items), obj, 'should return receiver');
<ide> });
<ide>
<del>suite.test('[].unshiftObjects([A,B,C]) => [A,B,C] + notify', function() {
<add>suite.test('[].unshiftObjects([A,B,C]) => [A,B,C] + notify', function(assert) {
<ide> let before = [];
<ide> let items = this.newFixture(3);
<ide> let obj = this.newObject(before);
<ide> suite.test('[].unshiftObjects([A,B,C]) => [A,B,C] + notify', function() {
<ide>
<ide> obj.unshiftObjects(items);
<ide>
<del> deepEqual(this.toArray(obj), items, 'post item results');
<del> equal(get(obj, 'length'), items.length, 'length');
<add> assert.deepEqual(this.toArray(obj), items, 'post item results');
<add> assert.equal(get(obj, 'length'), items.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<del>suite.test('[A,B,C].unshiftObjects([X,Y]) => [X,Y,A,B,C] + notify', function() {
<add>suite.test('[A,B,C].unshiftObjects([X,Y]) => [X,Y,A,B,C] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let items = this.newFixture(2);
<ide> let after = items.concat(before);
<ide> suite.test('[A,B,C].unshiftObjects([X,Y]) => [X,Y,A,B,C] + notify', function() {
<ide>
<ide> obj.unshiftObjects(items);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<ide>
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> });
<ide>
<del>suite.test('[A,B,C].unshiftObjects([A,B]) => [A,B,A,B,C] + notify', function() {
<add>suite.test('[A,B,C].unshiftObjects([A,B]) => [A,B,A,B,C] + notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let items = [before[0], before[1]]; // note same object as current head. should end up twice
<ide> let after = items.concat(before);
<ide> suite.test('[A,B,C].unshiftObjects([A,B]) => [A,B,A,B,C] + notify', function() {
<ide>
<ide> obj.unshiftObjects(items);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_enumerable/addObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('addObject');
<ide>
<del>suite.test('should return receiver', function() {
<add>suite.test('should return receiver', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let obj = this.newObject(before);
<ide>
<del> equal(obj.addObject(before[1]), obj, 'should return receiver');
<add> assert.equal(obj.addObject(before[1]), obj, 'should return receiver');
<ide> });
<ide>
<del>suite.test('[A,B].addObject(C) => [A,B,C] + notify', function() {
<add>suite.test('[A,B].addObject(C) => [A,B,C] + notify', function(assert) {
<ide> let before = this.newFixture(2);
<ide> let item = this.newFixture(1)[0];
<ide> let after = [before[0], before[1], item];
<ide> suite.test('[A,B].addObject(C) => [A,B,C] + notify', function() {
<ide>
<ide> obj.addObject(item);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> // This gets called since MutableEnumerable is naive about changes
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject once');
<ide> }
<ide> });
<ide>
<del>suite.test('[A,B,C].addObject(A) => [A,B,C] + NO notify', function() {
<add>suite.test('[A,B,C].addObject(A) => [A,B,C] + NO notify', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let after = before;
<ide> let item = before[0];
<ide> suite.test('[A,B,C].addObject(A) => [A,B,C] + NO notify', function() {
<ide>
<ide> obj.addObject(item); // note: item in set
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.validate('[]'), false, 'should NOT have notified []');
<del> equal(observer.validate('length'), false, 'should NOT have notified length');
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('[]'), false, 'should NOT have notified []');
<add> assert.equal(observer.validate('length'), false, 'should NOT have notified length');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('Adding object should notify enumerable observer', function() {
<add>suite.test('Adding object should notify enumerable observer', function(assert) {
<ide> let obj = this.newObject(this.newFixture(3));
<ide> let observer = this.newObserver(obj).observeEnumerable(obj);
<ide> let item = this.newFixture(1)[0];
<ide>
<ide> obj.addObject(item);
<ide>
<del> deepEqual(observer._before, [obj, null, [item]]);
<del> deepEqual(observer._after, [obj, null, [item]]);
<add> assert.deepEqual(observer._before, [obj, null, [item]]);
<add> assert.deepEqual(observer._after, [obj, null, [item]]);
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_enumerable/removeObject.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('removeObject');
<ide>
<del>suite.test('should return receiver', function() {
<add>suite.test('should return receiver', function(assert) {
<ide> let before = this.newFixture(3);
<ide> let obj = this.newObject(before);
<ide>
<del> equal(obj.removeObject(before[1]), obj, 'should return receiver');
<add> assert.equal(obj.removeObject(before[1]), obj, 'should return receiver');
<ide> });
<ide>
<del>suite.test('[A,B,C].removeObject(B) => [A,C] + notify', function() {
<add>suite.test('[A,B,C].removeObject(B) => [A,C] + notify', function(assert) {
<ide> let before = emberA(this.newFixture(3));
<ide> let after = [before[0], before[2]];
<ide> let obj = before;
<ide> suite.test('[A,B,C].removeObject(B) => [A,C] + notify', function() {
<ide>
<ide> obj.removeObject(before[1]);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('[A,B,C].removeObject(D) => [A,B,C]', function() {
<add>suite.test('[A,B,C].removeObject(D) => [A,B,C]', function(assert) {
<ide> let before = emberA(this.newFixture(3));
<ide> let after = before;
<ide> let item = this.newFixture(1)[0];
<ide> suite.test('[A,B,C].removeObject(D) => [A,B,C]', function() {
<ide>
<ide> obj.removeObject(item); // Note: item not in set
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.validate('[]'), false, 'should NOT have notified []');
<del> equal(observer.validate('length'), false, 'should NOT have notified length');
<add> assert.equal(observer.validate('[]'), false, 'should NOT have notified []');
<add> assert.equal(observer.validate('length'), false, 'should NOT have notified length');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('Removing object should notify enumerable observer', function() {
<add>suite.test('Removing object should notify enumerable observer', function(assert) {
<ide> let fixtures = this.newFixture(3);
<ide> let obj = this.newObject(fixtures);
<ide> let observer = this.newObserver(obj).observeEnumerable(obj);
<ide> let item = fixtures[1];
<ide>
<ide> obj.removeObject(item);
<ide>
<del> deepEqual(observer._before, [obj, [item], null]);
<del> deepEqual(observer._after, [obj, [item], null]);
<add> assert.deepEqual(observer._before, [obj, [item], null]);
<add> assert.deepEqual(observer._after, [obj, [item], null]);
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/mutable_enumerable/removeObjects.js
<ide> const suite = SuiteModuleBuilder.create();
<ide>
<ide> suite.module('removeObjects');
<ide>
<del>suite.test('should return receiver', function() {
<add>suite.test('should return receiver', function(assert) {
<ide> let before = emberA(this.newFixture(3));
<ide> let obj = before;
<ide>
<del> equal(obj.removeObjects(before[1]), obj, 'should return receiver');
<add> assert.equal(obj.removeObjects(before[1]), obj, 'should return receiver');
<ide> });
<ide>
<del>suite.test('[A,B,C].removeObjects([B]) => [A,C] + notify', function() {
<add>suite.test('[A,B,C].removeObjects([B]) => [A,C] + notify', function(assert) {
<ide> let before = emberA(this.newFixture(3));
<ide> let after = [before[0], before[2]];
<ide> let obj = before;
<ide> suite.test('[A,B,C].removeObjects([B]) => [A,C] + notify', function() {
<ide>
<ide> obj.removeObjects([before[1]]);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('[{A},{B},{C}].removeObjects([{B}]) => [{A},{C}] + notify', function() {
<add>suite.test('[{A},{B},{C}].removeObjects([{B}]) => [{A},{C}] + notify', function(assert) {
<ide> let before = emberA(this.newObjectsFixture(3));
<ide> let after = [before[0], before[2]];
<ide> let obj = before;
<ide> suite.test('[{A},{B},{C}].removeObjects([{B}]) => [{A},{C}] + notify', function(
<ide>
<ide> obj.removeObjects([before[1]]);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('[A,B,C].removeObjects([A,B]) => [C] + notify', function() {
<add>suite.test('[A,B,C].removeObjects([A,B]) => [C] + notify', function(assert) {
<ide> let before = emberA(this.newFixture(3));
<ide> let after = [before[2]];
<ide> let obj = before;
<ide> suite.test('[A,B,C].removeObjects([A,B]) => [C] + notify', function() {
<ide>
<ide> obj.removeObjects([before[0], before[1]]);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('[{A},{B},{C}].removeObjects([{A},{B}]) => [{C}] + notify', function() {
<add>suite.test('[{A},{B},{C}].removeObjects([{A},{B}]) => [{C}] + notify', function(assert) {
<ide> let before = emberA(this.newObjectsFixture(3));
<ide> let after = [before[2]];
<ide> let obj = before;
<ide> suite.test('[{A},{B},{C}].removeObjects([{A},{B}]) => [{C}] + notify', function(
<ide>
<ide> obj.removeObjects([before[0], before[1]]);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('[A,B,C].removeObjects([A,B,C]) => [] + notify', function() {
<add>suite.test('[A,B,C].removeObjects([A,B,C]) => [] + notify', function(assert) {
<ide> let before = emberA(this.newFixture(3));
<ide> let after = [];
<ide> let obj = before;
<ide> suite.test('[A,B,C].removeObjects([A,B,C]) => [] + notify', function() {
<ide>
<ide> obj.removeObjects([before[0], before[1], before[2]]);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject');
<del> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject');
<add> assert.equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('[{A},{B},{C}].removeObjects([{A},{B},{C}]) => [] + notify', function() {
<add>suite.test('[{A},{B},{C}].removeObjects([{A},{B},{C}]) => [] + notify', function(assert) {
<ide> let before = emberA(this.newObjectsFixture(3));
<ide> let after = [];
<ide> let obj = before;
<ide> suite.test('[{A},{B},{C}].removeObjects([{A},{B},{C}]) => [] + notify', function
<ide>
<ide> obj.removeObjects(before);
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<del> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add> assert.equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> assert.equal(observer.timesCalled('length'), 1, 'should have notified length once');
<ide>
<del> equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject');
<del> equal(observer.validate('lastObject'), 1, 'should have notified lastObject');
<add> assert.equal(observer.timesCalled('firstObject'), 1, 'should have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), 1, 'should have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('[A,B,C].removeObjects([D]) => [A,B,C]', function() {
<add>suite.test('[A,B,C].removeObjects([D]) => [A,B,C]', function(assert) {
<ide> let before = emberA(this.newFixture(3));
<ide> let after = before;
<ide> let item = this.newFixture(1)[0];
<ide> suite.test('[A,B,C].removeObjects([D]) => [A,B,C]', function() {
<ide>
<ide> obj.removeObjects([item]); // Note: item not in set
<ide>
<del> deepEqual(this.toArray(obj), after, 'post item results');
<del> equal(get(obj, 'length'), after.length, 'length');
<add> assert.deepEqual(this.toArray(obj), after, 'post item results');
<add> assert.equal(get(obj, 'length'), after.length, 'length');
<ide>
<ide> if (observer.isEnabled) {
<del> equal(observer.validate('[]'), false, 'should NOT have notified []');
<del> equal(observer.validate('length'), false, 'should NOT have notified length');
<add> assert.equal(observer.validate('[]'), false, 'should NOT have notified []');
<add> assert.equal(observer.validate('length'), false, 'should NOT have notified length');
<ide>
<del> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<del> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<add> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject');
<add> assert.equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject');
<ide> }
<ide> });
<ide>
<del>suite.test('Removing objects should notify enumerable observer', function() {
<add>suite.test('Removing objects should notify enumerable observer', function(assert) {
<ide> let fixtures = this.newFixture(3);
<ide> let obj = this.newObject(fixtures);
<ide> let observer = this.newObserver(obj).observeEnumerable(obj);
<ide> let item = fixtures[1];
<ide>
<ide> obj.removeObjects([item]);
<ide>
<del> deepEqual(observer._before, [obj, [item], null]);
<del> deepEqual(observer._after, [obj, [item], null]);
<add> assert.deepEqual(observer._before, [obj, [item], null]);
<add> assert.deepEqual(observer._after, [obj, [item], null]);
<ide> });
<ide>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/suites/suite.js
<ide> Suite.reopenClass({
<ide> let title = get(this, 'name') + ': ' + desc;
<ide> let ctx = this;
<ide> QUnit.module(title, {
<del> beforeEach() {
<add> beforeEach(assert) {
<ide> if (setup) {
<del> setup.call(ctx);
<add> setup.call(ctx, assert);
<ide> }
<ide> },
<ide>
<del> afterEach() {
<add> afterEach(assert) {
<ide> if (teardown) {
<del> teardown.call(ctx);
<add> teardown.call(ctx, assert);
<ide> }
<ide> }
<ide> }); | 45 |
Text | Text | add instructions on how to run bert with configs | eb674a1f7670762a12f9d36bc652b5156c43592a | <ide><path>official/nlp/MODEL_GARDEN.md
<add># TF-NLP Model Garden
<add>
<add>## Introduction
<add>
<add>This TF-NLP library provides a collection of scripts for the training and
<add>evaluation of transformer-based models, on various tasks such as sentence
<add>classification, question answering, and translation. Additionally, we provide
<add>checkpoints of pretrained models which can be finetuned on downstream tasks.
<add>
<add>### How to Train Models
<add>
<add>Model Garden can be easily installed using PIP
<add>(`pip install tf-models-nightly`). After installation, check out
<add>[this instruction](https://github.com/tensorflow/models/blob/master/official/nlp/docs/train.md)
<add>on how to train models with this codebase.
<add>
<add>## Available Tasks
<add>
<add>There are two available model configs (we will add more) under
<add>`configs/experiments/`:
<add>
<add>| Dataset | Task | Config | Example command |
<add>| ----------------- | ------------------------ | ------- | ---- |
<add>| GLUE/MNLI-matched | bert/sentence_prediction | [glue_mnli_matched.yaml](https://github.com/tensorflow/models/blob/master/official/nlp/configs/experiments/glue_mnli_matched.yaml) | <details> <summary>finetune BERT-base on this task</summary> PARAMS=runtime.distribution_strategy=mirrored<br/>PARAMS=${PARAMS},task.train_data.input_path=/path-to-your-training-data/<br/>PARAMS=${PARAMS},task.hub_module_url=https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4<br/><br/>python3 train.py \\<br/> --experiment=bert/sentence_prediction \\<br/> --mode=train \\<br/> --model_dir=/a-folder-to-hold-checkpoints-and-logs/ \\<br/> --config_file=configs/models/bert_en_uncased_base.yaml \\<br/> --config_file=configs/experiments/glue_mnli_matched.yaml \\<br/> --params_override=${PARAMS}</details> |
<add>| SQuAD v1.1 | bert/squad | [squad_v1.yaml](https://github.com/tensorflow/models/blob/master/official/nlp/configs/experiments/squad_v1.yaml) | <details> <summary>finetune BERT-base on this task</summary> PARAMS=runtime.distribution_strategy=mirrored<br/>PARAMS=${PARAMS},task.train_data.input_path=/path-to-your-training-data/<br/>PARAMS=${PARAMS},task.hub_module_url=https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4<br/><br/>python3 train.py \\<br/> --experiment=bert/squad \\<br/> --mode=train \\<br/> --model_dir=/a-folder-to-hold-checkpoints-and-logs/ \\<br/> --config_file=configs/models/bert_en_uncased_base.yaml \\<br/> --config_file=configs/experiments/squad_v1.yaml \\<br/> --params_override=${PARAMS}</details> |
<add>
<add>One example on how to use the config file: if you want to work on the SQuAD
<add>question answering task, set
<add>`--config_file=configs/experiments/squad_v1.yaml` and
<add>`--experiment=bert/squad`
<add>as arguments to `train.py`.
<add>
<add>## Available Model Configs
<add>
<add>There are two available model configs (we will add more) under
<add>`configs/models/`:
<add>
<add>| Model | Config | Pretrained checkpoint & Vocabulary | TF-HUB SavedModel | Example command |
<add>| ------------ | ------- | ---------------------------------- | ----------------- | --------------- |
<add>| BERT-base | [bert_en_uncased_base.yaml](https://github.com/tensorflow/models/blob/master/official/nlp/configs/models/bert_en_uncased_base.yaml) | [uncased_L-12_H-768_A-12](https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/uncased_L-12_H-768_A-12.tar.gz) | [uncased_L-12_H-768_A-12](https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/) | <details> <summary>finetune on SQuAD v1.1</summary> PARAMS=runtime.distribution_strategy=mirrored<br/>PARAMS=${PARAMS},task.train_data.input_path=/path-to-your-training-data/<br/>PARAMS=${PARAMS},task.hub_module_url=https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4<br/><br/>python3 train.py \\<br/> --experiment=bert/squad \\<br/> --mode=train \\<br/> --model_dir=/a-folder-to-hold-checkpoints-and-logs/ \\<br/> --config_file=configs/models/bert_en_uncased_base.yaml \\<br/> --config_file=configs/experiments/squad_v1.yaml \\<br/> --params_override=${PARAMS}</details> |
<add>| ALBERT-base | [albert_base.yaml](https://github.com/tensorflow/models/blob/master/official/nlp/configs/models/albert_base.yaml) | [albert_en_base](https://storage.googleapis.com/tf_model_garden/nlp/albert/albert_base.tar.gz) | [albert_en_base](https://tfhub.dev/tensorflow/albert_en_base/3) | <details> <summary>finetune on SQuAD v1.1</summary> PARAMS=runtime.distribution_strategy=mirrored<br/>PARAMS=${PARAMS},task.train_data.input_path=/path-to-your-training-data/<br/>PARAMS=${PARAMS},task.hub_module_url=https://tfhub.dev/tensorflow/albert_en_base/3<br/><br/>python3 train.py \\<br/> --experiment=bert/squad \\<br/> --mode=train \\<br/> --model_dir=/a-folder-to-hold-checkpoints-and-logs/ \\<br/> --config_file=configs/models/albert_base.yaml \\<br/> --config_file=configs/experiments/squad_v1.yaml \\<br/> --params_override=${PARAMS}</details> |
<add>
<add>One example on how to use the config file: if you want to train an ALBERT-base
<add>model, set `--config_file=configs/models/albert_base.yaml` as an argument to
<add>`train.py`.
<add>
<add>## Useful links
<add>
<add>[How to Train Models](https://github.com/tensorflow/models/blob/master/official/nlp/docs/train.md)
<add>
<add>[List of Pretrained Models](https://github.com/tensorflow/models/blob/master/official/nlp/docs/pretrained_models.md)
<add>
<add>[How to Publish Models](https://github.com/tensorflow/models/blob/master/official/nlp/docs/tfhub.md)
<add>
<add>[TensorFlow blog on Model Garden](https://blog.tensorflow.org/2020/03/introducing-model-garden-for-tensorflow-2.html).
<ide><path>official/nlp/docs/train.md
<ide> In addition, experiment configuration can be further overriden by
<ide> --params_override=task.train_data.input_path=/some/path,task.hub_module_url=/some/tfhub
<ide> ```
<ide>
<add>## Run locally on GPUs
<add>
<add>An example command for training a model on local GPUs is below. This command
<add>trains a BERT-base model on GLUE/MNLI-matched which is a sentence prediction
<add>task.
<add>
<add>```shell
<add>PARAMS=runtime.distribution_strategy=mirrored # Train no GPU
<add>PARAMS=${PARAMS},task.train_data.input_path=/path-to-your-training-data/
<add>
<add>python3 train.py \
<add> --experiment=bert/sentence_prediction \
<add> --mode=train \
<add> --model_dir=/a-folder-to-hold-checkpoints-and-logs/ \
<add> --config_file=configs/models/bert_en_uncased_base.yaml \
<add> --config_file=configs/experiments/glue_mnli_matched.yaml \
<add> --params_override=${PARAMS}
<add>```
<add>
<add>Note that you can specify any detailed configuration by appending
<add>to the `PARAMS` variable. For example, if you want to load from a pretrained
<add>checkpoint as initialization (instead of random initialization):
<add>
<add>```shell
<add>PARAMS=${PARAMS},task.hub_module_url=https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4
<add>```
<add>
<add>The configuration entry `task.hub_module_url` uses a URL to a TF-Hub model which
<add>is officially pretrained. See
<add>[List of Pretrained Models](https://github.com/tensorflow/models/blob/master/official/nlp/docs/pretrained_models.md)
<add>for the complete list of pretrained models on TF-Hub. When initializing from a
<add>pretrained model, the encoder architecture of the pretrained model will be used
<add>and the encoder architecture you set in the config
<add>(`configs/models/bert_en_uncased_base.yaml` in this case) will be ignored.
<add>
<add>You can change `--mode=train` to `--mode=train_and_eval` if you want to see
<add>evaluation results. But you need to specify the path to the evaluation data by
<add>setting `task.validation_data.input_path` in `PARAMS`.
<add>
<ide> ## Run on Cloud TPUs
<ide>
<ide> Next, we will describe how to run the [train.py](https://github.com/tensorflow/models/blob/master/official/nlp/train.py) on Cloud TPUs. | 2 |
Python | Python | consider the case where lambda is input layer | fb8e80daf456f00ac8b7404f49c551115cfca138 | <ide><path>keras/layers/core.py
<ide> def __init__(self, function, output_shape=None, ndim=2):
<ide> else:
<ide> self.function = marshal.dumps(function.func_code)
<ide> if output_shape is None:
<del> output_shape = self.previous.output_shape
<add> output_shape = input_shape
<ide> elif type(output_shape) in {tuple, list}:
<ide> self._output_shape = tuple(output_shape)
<ide> else: | 1 |
Mixed | Javascript | return http 431 on hpe_header_overflow error | bcf2886a84407028572fd1084242a1c789c056f8 | <ide><path>doc/api/http.md
<ide> changes:
<ide> description: The `rawPacket` is the current buffer that just parsed. Adding
<ide> this buffer to the error object of `'clientError'` event is to
<ide> make it possible that developers can log the broken packet.
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/25605
<add> description: The default behavior will return a 431 Request Header
<add> Fields Too Large if a HPE_HEADER_OVERFLOW error occurs.
<ide> -->
<ide>
<ide> * `exception` {Error}
<ide> Listener of this event is responsible for closing/destroying the underlying
<ide> socket. For example, one may wish to more gracefully close the socket with a
<ide> custom HTTP response instead of abruptly severing the connection.
<ide>
<del>Default behavior is to close the socket with an HTTP '400 Bad Request' response
<del>if possible, otherwise the socket is immediately destroyed.
<add>Default behavior is to try close the socket with a HTTP '400 Bad Request',
<add>or a HTTP '431 Request Header Fields Too Large' in the case of a
<add>[`HPE_HEADER_OVERFLOW`][] error. If the socket is not writable it is
<add>immediately destroyed.
<ide>
<ide> `socket` is the [`net.Socket`][] object that the error originated from.
<ide>
<ide> not abort the request or do anything besides add a `'timeout'` event.
<ide> [`url.parse()`]: url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
<ide> [Readable Stream]: stream.html#stream_class_stream_readable
<ide> [Stream]: stream.html#stream_stream
<add>[`HPE_HEADER_OVERFLOW`]: errors.html#errors_hpe_header_overflow
<ide><path>lib/_http_server.js
<ide> const noop = () => {};
<ide> const badRequestResponse = Buffer.from(
<ide> `HTTP/1.1 400 ${STATUS_CODES[400]}${CRLF}${CRLF}`, 'ascii'
<ide> );
<add>const requestHeaderFieldsTooLargeResponse = Buffer.from(
<add> `HTTP/1.1 431 ${STATUS_CODES[431]}${CRLF}${CRLF}`, 'ascii'
<add>);
<ide> function socketOnError(e) {
<ide> // Ignore further errors
<ide> this.removeListener('error', socketOnError);
<ide> this.on('error', noop);
<ide>
<ide> if (!this.server.emit('clientError', e, this)) {
<ide> if (this.writable) {
<del> this.write(badRequestResponse);
<add> const response = e.code === 'HPE_HEADER_OVERFLOW' ?
<add> requestHeaderFieldsTooLargeResponse : badRequestResponse;
<add> this.write(response);
<ide> }
<ide> this.destroy(e);
<ide> }
<ide><path>test/parallel/test-http-header-overflow.js
<add>'use strict';
<add>const assert = require('assert');
<add>const { createServer, maxHeaderSize } = require('http');
<add>const { createConnection } = require('net');
<add>const { expectsError, mustCall } = require('../common');
<add>
<add>const CRLF = '\r\n';
<add>const DUMMY_HEADER_NAME = 'Cookie: ';
<add>const DUMMY_HEADER_VALUE = 'a'.repeat(
<add> // plus one is to make it 1 byte too big
<add> maxHeaderSize - DUMMY_HEADER_NAME.length - (2 * CRLF.length) + 1
<add>);
<add>const PAYLOAD_GET = 'GET /blah HTTP/1.1';
<add>const PAYLOAD = PAYLOAD_GET + CRLF +
<add> DUMMY_HEADER_NAME + DUMMY_HEADER_VALUE + CRLF.repeat(2);
<add>
<add>const server = createServer();
<add>
<add>server.on('connection', mustCall((socket) => {
<add> socket.on('error', expectsError({
<add> type: Error,
<add> message: 'Parse Error',
<add> code: 'HPE_HEADER_OVERFLOW',
<add> bytesParsed: maxHeaderSize + PAYLOAD_GET.length,
<add> rawPacket: Buffer.from(PAYLOAD)
<add> }));
<add>}));
<add>
<add>server.listen(0, mustCall(() => {
<add> const c = createConnection(server.address().port);
<add> let received = '';
<add>
<add> c.on('connect', mustCall(() => {
<add> c.write(PAYLOAD);
<add> }));
<add> c.on('data', mustCall((data) => {
<add> received += data.toString();
<add> }));
<add> c.on('end', mustCall(() => {
<add> assert.strictEqual(
<add> received,
<add> 'HTTP/1.1 431 Request Header Fields Too Large\r\n\r\n'
<add> );
<add> c.end();
<add> }));
<add> c.on('close', mustCall(() => server.close()));
<add>})); | 3 |
Ruby | Ruby | show summary headings when appropriate | 1d606388b40e28defa86877b2b3976c2b2923c9b | <ide><path>Library/Homebrew/install.rb
<ide> def install f
<ide> opoo 'A top-level "man" folder was found.'
<ide> puts "Homebrew requires that man pages live under share."
<ide> puts 'This can often be fixed by passing "--mandir=#{man}" to configure.'
<add> show_summary_heading = true
<ide> end
<ide>
<ide> # Check for info pages that aren't in share/info
<ide> if (f.prefix+'info').exist?
<ide> opoo 'A top-level "info" folder was found.'
<ide> puts "Homebrew suggests that info pages live under share."
<ide> puts 'This can often be fixed by passing "--infodir=#{info}" to configure.'
<add> show_summary_heading = true
<ide> end
<ide>
<ide> # Check for Jars in lib
<ide> def install f
<ide> puts "For Java software, it is typically better for the formula to"
<ide> puts "install to \"libexec\" and then symlink or wrap binaries into \"bin\"."
<ide> puts "See \"activemq\", \"jruby\", etc. for examples."
<add> show_summary_heading = true
<ide> end
<ide> end
<ide>
<ide> def install f
<ide> puts "Homebrew does not append \"#{HOMEBREW_PREFIX}/share/aclocal\""
<ide> puts "to \"/usr/share/aclocal/dirlist\". If an autoconf script you use"
<ide> puts "requires these m4 macros, you'll need to add this path manually."
<add> show_summary_heading = true
<ide> end
<ide>
<ide> # link from Cellar to Prefix
<ide> def install f
<ide> onoe "The linking step did not complete successfully"
<ide> puts "The formula built, but is not symlinked into #{HOMEBREW_PREFIX}"
<ide> puts "You can try again using `brew link #{f.name}'"
<del> if ARGV.debug?
<del> ohai e, e.backtrace
<del> else
<del> onoe e
<del> end
<add> ohai e, e.backtrace if ARGV.debug?
<ide> show_summary_heading = true
<ide> end
<ide> | 1 |
Javascript | Javascript | ignore typescript bug | d7d9b9bfa3e981baa46bd919c893b05d041f12fa | <ide><path>bin/webpack.js
<ide> #!/usr/bin/env node
<ide>
<add>// @ts-ignore
<ide> process.exitCode = 0;
<ide>
<ide> /**
<ide> if (installedClis.length === 0) {
<ide> " and "
<ide> )} together. To work with the "webpack" command you need only one CLI package, please remove one of them or use them directly via their binary.`
<ide> );
<add>
<add> // @ts-ignore
<ide> process.exitCode = 1;
<ide> } | 1 |
Python | Python | add additional print and assert | 0b42b1c4f794259daac3de279b04213a18141cc9 | <ide><path>integration/storage/test_azure_blobs.py
<ide> def setUpClass(cls):
<ide> # to clean those up to ensure we dont hit any limits.
<ide> # To avoid deleting groups from concurrent runs, we only delete resources older than a
<ide> # couple (6) of hours
<add> print("Checking and cleaning up any old stray resource groups...")
<add>
<ide> resource_groups = resource_client.resource_groups.list()
<ide> now_ts = int(time.time())
<ide> delete_threshold_ts = now_ts - int(datetime.timedelta(hours=6).total_seconds())
<ide> def setUpClass(cls):
<ide> if resource_group.name.startswith(RESOURCE_GROUP_NAME_PREFIX) and \
<ide> resource_group.location.lower() == location.lower() and \
<ide> 'test' in resource_group.tags and resource_create_ts <= delete_threshold_ts:
<add> assert resource_group.name.startswith(RESOURCE_GROUP_NAME_PREFIX)
<ide> print("Deleting old stray resource group: %s..." % (resource_group.name))
<ide>
<ide> try: | 1 |
Javascript | Javascript | correct a typo with enumerable | 9b567c5a072202f5d7c1f33f41630c5602748c66 | <ide><path>server/server.js
<ide> if (!requireProto.hasOwnProperty('ensure')) {
<ide> callback(this);
<ide> },
<ide> writable: false,
<del> enumarble: false
<add> enumerable: false
<ide> }
<ide> }
<ide> ); | 1 |
Javascript | Javascript | add missing comments | 164fec6322f7fd0942cce670d2516eed808048d7 | <ide><path>src/config-schema.js
<ide> import path from 'path'
<ide> import fs from 'fs-plus'
<ide>
<add>// This is loaded by atom-environment.coffee. See
<add>// https://atom.io/docs/api/latest/Config for more information about config
<add>// schemas.
<ide> const configSchema = {
<ide> core: {
<ide> type: 'object',
<ide> const configSchema = {
<ide>
<ide> editor: {
<ide> type: 'object',
<del>
<add> // These settings are used in scoped fashion only. No defaults.
<ide> properties: {
<ide> commentStart: {
<ide> type: ['string', 'null']
<ide> const configSchema = {
<ide> type: ['string', 'null']
<ide> },
<ide>
<add> // These can be used as globals or scoped, thus defaults.
<ide> fontFamily: {
<ide> type: 'string',
<ide> default: '', | 1 |
Python | Python | add log message for max_processes | a8092685458d70d283f4721e341a4805ac494f0b | <ide><path>glances/core/glances_standalone.py
<ide> """Manage the Glances standalone session."""
<ide>
<ide> # Import Glances libs
<add>from glances.core.glances_globals import logger
<ide> from glances.core.glances_stats import GlancesStats
<ide> from glances.outputs.glances_curses import GlancesCurses
<ide> from glances.core.glances_globals import glances_processes
<ide> def __init__(self, config=None, args=None):
<ide> # If configured, set the maximum processes number to display
<ide> try:
<ide> max_processes = int(self.stats.get_plugin('processlist').get_conf_value('max_processes'))
<add> logger.debug(_("Limit maximum displayed processes to %s") % max_processes)
<ide> except:
<ide> max_processes = None
<add> logger.warning(_("Maximum displayed processes is not configured (high CPU consumption)"))
<ide> glances_processes.set_max_processes(max_processes)
<ide>
<ide> # Initial system informations update | 1 |
Python | Python | remove print statement | 6b325c2c1211325629eddbf7e853f8d51eeb18a7 | <ide><path>spacy/lemmatizer.py
<ide> def is_base_form(self, univ_pos, morphology=None):
<ide> morphology = {} if morphology is None else morphology
<ide> others = [key for key in morphology if key not in (POS, 'number', 'pos', 'verbform')]
<ide> true_morph_key = morphology.get('morph', 0)
<del> print(univ_pos, morphology)
<ide> if univ_pos == 'noun' and morphology.get('Number') == 'sing':
<ide> return True
<ide> elif univ_pos == 'verb' and morphology.get('VerbForm') == 'inf': | 1 |
PHP | PHP | use arguments to make sure they are being passed | 2696ff2eae8e28f6e721c8d8232d6cb4856dad91 | <ide><path>tests/TestCase/Mailer/MailerTest.php
<ide> public function testProxies()
<ide> $email = $this->getMockForEmail('setHeaders');
<ide> $email->expects($this->once())
<ide> ->method('setHeaders')
<del> ->with([]);
<del> $result = (new TestMailer($email))->setHeaders([]);
<add> ->with(['X-Something' => 'nice']);
<add> $result = (new TestMailer($email))->setHeaders(['X-Something' => 'nice']);
<ide> $this->assertInstanceOf('TestApp\Mailer\TestMailer', $result);
<ide>
<ide> $email = $this->getMockForEmail('addHeaders');
<ide> $email->expects($this->once())
<ide> ->method('addHeaders')
<del> ->with([]);
<del> $result = (new TestMailer($email))->addHeaders([]);
<add> ->with(['X-Something' => 'very nice', 'X-Other' => 'cool']);
<add> $result = (new TestMailer($email))->addHeaders(['X-Something' => 'very nice', 'X-Other' => 'cool']);
<ide> $this->assertInstanceOf('TestApp\Mailer\TestMailer', $result);
<ide>
<ide> $email = $this->getMockForEmail('attachments');
<ide> $email->expects($this->once())
<ide> ->method('attachments')
<del> ->with([]);
<del> $result = (new TestMailer($email))->attachments([]);
<add> ->with([
<add> ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain']
<add> ]);
<add> $result = (new TestMailer($email))->attachments([
<add> ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain']
<add> ]);
<ide> $this->assertInstanceOf('TestApp\Mailer\TestMailer', $result);
<ide> }
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 27e8438d7a781074a70bda7e4845716063ec56da | <ide><path>src/Illuminate/Routing/Middleware/ThrottleRequestsWithRedis.php
<ide> protected function tooManyAttempts($key, $maxAttempts, $decayMinutes)
<ide>
<ide> $this->remaining = $limiter->remaining;
<ide>
<del> return !$attempt;
<add> return ! $attempt;
<ide> }
<ide> }
<ide><path>tests/Integration/Http/ThrottleRequestsTest.php
<ide> public function setup()
<ide> public function test_lock_opens_immediately_after_decay()
<ide> {
<ide> Carbon::setTestNow(null);
<del>
<add>
<ide> Route::get('/', function () {
<ide> return 'yes';
<ide> })->middleware(ThrottleRequests::class.':2,1'); | 2 |
PHP | PHP | turn profiler off using runtime config | c1bcfec3d2da1c6ef27b3de685228622ef21aa51 | <ide><path>laravel/profiling/profiler.php
<ide> public static function render($response)
<ide> // We only want to send the profiler toolbar if the request is not an AJAX
<ide> // request, as sending it on AJAX requests could mess up JSON driven API
<ide> // type applications, so we will not send anything in those scenarios.
<del> if ( ! Request::ajax())
<add> if ( ! Request::ajax() and Config::get('application.profiler') )
<ide> {
<ide> static::$data['memory'] = get_file_size(memory_get_usage(true));
<ide> static::$data['memory_peak'] = get_file_size(memory_get_peak_usage(true)); | 1 |
Ruby | Ruby | fix `"dependencies"` being `nil` | be4e926b15ec58ff6273e6bf9377cfc8d11e57f9 | <ide><path>Library/Homebrew/formula_auditor.rb
<ide> def linux_only_gcc_dep?(formula)
<ide> # depends_on "gcc"
<ide> # end
<ide> # ```
<del> variations_deps = []
<del> variations.each_value do |data|
<del> variations_deps += data["dependencies"]
<del> end
<del> variations_deps.uniq!
<add> variations_deps = variations.values
<add> .flat_map { |data| data["dependencies"] }
<add> .compact
<add> .uniq
<ide>
<ide> variations_deps.exclude?("gcc")
<ide> end | 1 |
Javascript | Javascript | support gratuitous animation example on android | 0cc4306d6c46d7a11b29a0cf754faa127e01570b | <ide><path>RNTester/js/examples/Animated/AnimatedGratuitousApp/AnExApp.js
<ide> const {
<ide> Animated,
<ide> LayoutAnimation,
<ide> PanResponder,
<add> Platform,
<ide> StyleSheet,
<add> UIManager,
<ide> View,
<ide> } = require('react-native');
<ide>
<ide> class Circle extends React.Component<any, any> {
<ide> pan: new Animated.ValueXY(), // Vectors reduce boilerplate. (step1: uncomment)
<ide> pop: new Animated.Value(0), // Initial value. (step2a: uncomment)
<ide> };
<add>
<add> if (Platform.OS === 'android') {
<add> UIManager.setLayoutAnimationEnabledExperimental(true);
<add> }
<ide> }
<ide>
<ide> _onLongPress(): void {
<ide><path>RNTester/js/utils/RNTesterList.android.js
<ide> const APIExamples: Array<RNTesterExample> = [
<ide> key: 'AnimatedExample',
<ide> module: require('../examples/Animated/AnimatedExample'),
<ide> },
<add> {
<add> key: 'Animation - GratuitousAnimation',
<add> module: require('../examples/Animated/AnimatedGratuitousApp/AnExApp'),
<add> },
<ide> {
<ide> key: 'AppearanceExample',
<ide> module: require('../examples/Appearance/AppearanceExample'), | 2 |
Python | Python | fix typo when returning verticahook | 96cd211b77820981c739c2e07b710114b31bb196 | <ide><path>airflow/models.py
<ide> def get_hook(self):
<ide> elif self.conn_type == 'oracle':
<ide> return hooks.OracleHook(oracle_conn_id=self.conn_id)
<ide> elif self.conn_type == 'vertica':
<del> return hooks.VerticaHook(vertica_conn_id=self.conn_id)
<add> return contrib_hooks.VerticaHook(vertica_conn_id=self.conn_id)
<ide> except:
<ide> return None
<ide> | 1 |
Go | Go | implement build from git | 12c9b9b3c94d595ab155fc90dfc426eeada8bc75 | <ide><path>api.go
<ide> import (
<ide> "io/ioutil"
<ide> "log"
<ide> "net/http"
<add> "os"
<add> "os/exec"
<add> "path"
<ide> "strconv"
<ide> "strings"
<ide> )
<ide> func postBuild(srv *Server, version float64, w http.ResponseWriter, r *http.Requ
<ide> repoName = remoteParts[0]
<ide> }
<ide>
<del> var dockerfile, context io.ReadCloser
<add> var dockerfile, context io.Reader
<ide>
<ide> if remoteURL == "" {
<ide> d, _, err := r.FormFile("Dockerfile")
<ide> func postBuild(srv *Server, version float64, w http.ResponseWriter, r *http.Requ
<ide> }
<ide> } else {
<ide> if utils.IsGIT(remoteURL) {
<del> return fmt.Errorf("Builder from git is not yet supported")
<add> if !strings.HasPrefix(remoteURL, "git://") {
<add> remoteURL = "https://" + remoteURL
<add> }
<add> root, err := ioutil.TempDir("", "docker-build-git")
<add> if err != nil {
<add> return err
<add> }
<add> defer os.RemoveAll(root)
<add>
<add> if output, err := exec.Command("git", "clone", remoteURL, root).CombinedOutput(); err != nil {
<add> return fmt.Errorf("Error trying to use git: %s (%s)", err, output)
<add> }
<add>
<add> d, err := os.Open(path.Join(root, "Dockerfile"))
<add> if err != nil {
<add> if os.IsNotExist(err) {
<add> return fmt.Errorf("No Dockerfile found in the repository")
<add> }
<add> return err
<add> } else {
<add> dockerfile = d
<add> }
<add>
<add> c, err := Tar(root, Bzip2)
<add> if err != nil {
<add> return err
<add> } else {
<add> context = c
<add> }
<add>
<ide> } else if utils.IsURL(remoteURL) {
<ide> f, err := utils.Download(remoteURL, ioutil.Discard)
<ide> if err != nil {
<ide><path>commands.go
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> return err
<ide> }
<ide> io.Copy(wField, file)
<del> multipartBody = io.MultiReader(multipartBody, boundary)
<ide> }
<add> multipartBody = io.MultiReader(multipartBody, boundary)
<add>
<ide> v := &url.Values{}
<ide> v.Set("t", *tag)
<ide> if isRemote { | 2 |
Javascript | Javascript | improve fspromises readfile performance | e216d8f4a1277e77903e9c2c716fefa3b196761b | <ide><path>lib/internal/fs/promises.js
<ide> // See https://github.com/libuv/libuv/pull/1501.
<ide> const kIoMaxLength = 2 ** 31 - 1;
<ide>
<del>// Note: This is different from kReadFileBufferLength used for non-promisified
<del>// fs.readFile.
<del>const kReadFileMaxChunkSize = 2 ** 14;
<add>const kReadFileBufferLength = 512 * 1024;
<add>const kReadFileUnknownBufferLength = 64 * 1024;
<ide> const kWriteFileMaxChunkSize = 2 ** 14;
<ide>
<ide> const {
<ide> async function readFileHandle(filehandle, options) {
<ide> if (size > kIoMaxLength)
<ide> throw new ERR_FS_FILE_TOO_LARGE(size);
<ide>
<del> const chunks = [];
<del> let isFirstChunk = true;
<del> const firstChunkSize = size === 0 ? kReadFileMaxChunkSize : size;
<del> const chunkSize = MathMin(firstChunkSize, kReadFileMaxChunkSize);
<ide> let endOfFile = false;
<add> let totalRead = 0;
<add> const noSize = size === 0;
<add> const buffers = [];
<add> const fullBuffer = noSize ? undefined : Buffer.allocUnsafeSlow(size);
<ide> do {
<ide> if (signal?.aborted) {
<ide> throw lazyDOMException('The operation was aborted', 'AbortError');
<ide> }
<del> const buf = Buffer.alloc(isFirstChunk ? firstChunkSize : chunkSize);
<del> const { bytesRead, buffer } =
<del> await read(filehandle, buf, 0, buf.length, -1);
<del> endOfFile = bytesRead === 0;
<del> if (bytesRead > 0)
<del> ArrayPrototypePush(chunks, buffer.slice(0, bytesRead));
<del> isFirstChunk = false;
<add> let buffer;
<add> let offset;
<add> let length;
<add> if (noSize) {
<add> buffer = Buffer.allocUnsafeSlow(kReadFileUnknownBufferLength);
<add> offset = 0;
<add> length = kReadFileUnknownBufferLength;
<add> } else {
<add> buffer = fullBuffer;
<add> offset = totalRead;
<add> length = MathMin(size - totalRead, kReadFileBufferLength);
<add> }
<add>
<add> const bytesRead = (await binding.read(filehandle.fd, buffer, offset,
<add> length, -1, kUsePromises)) || 0;
<add> totalRead += bytesRead;
<add> endOfFile = bytesRead === 0 || totalRead === size;
<add> if (noSize && bytesRead > 0) {
<add> const isBufferFull = bytesRead === kReadFileUnknownBufferLength;
<add> const chunkBuffer = isBufferFull ? buffer : buffer.slice(0, bytesRead);
<add> ArrayPrototypePush(buffers, chunkBuffer);
<add> }
<ide> } while (!endOfFile);
<ide>
<del> const result = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
<add> let result;
<add> if (size > 0) {
<add> result = totalRead === size ? fullBuffer : fullBuffer.slice(0, totalRead);
<add> } else {
<add> result = buffers.length === 1 ? buffers[0] : Buffer.concat(buffers,
<add> totalRead);
<add> }
<ide>
<ide> return options.encoding ? result.toString(options.encoding) : result;
<ide> }
<ide><path>test/parallel/test-fs-promises-file-handle-readFile.js
<ide> const {
<ide> open,
<ide> readFile,
<ide> writeFile,
<del> truncate
<add> truncate,
<ide> } = fs.promises;
<ide> const path = require('path');
<ide> const tmpdir = require('../common/tmpdir');
<ide> async function doReadAndCancel() {
<ide> await assert.rejects(readFile(fileHandle, { signal }), {
<ide> name: 'AbortError'
<ide> });
<add> await fileHandle.close();
<ide> }
<ide>
<ide> // Signal aborted on first tick
<ide> async function doReadAndCancel() {
<ide> fs.writeFileSync(filePathForHandle, buffer);
<ide> const controller = new AbortController();
<ide> const { signal } = controller;
<del> tick(1, () => controller.abort());
<add> process.nextTick(() => controller.abort());
<ide> await assert.rejects(readFile(fileHandle, { signal }), {
<ide> name: 'AbortError'
<del> });
<add> }, 'tick-0');
<add> await fileHandle.close();
<ide> }
<ide>
<ide> // Signal aborted right before buffer read
<ide> async function doReadAndCancel() {
<ide>
<ide> const controller = new AbortController();
<ide> const { signal } = controller;
<del> tick(2, () => controller.abort());
<add> tick(1, () => controller.abort());
<ide> await assert.rejects(fileHandle.readFile({ signal, encoding: 'utf8' }), {
<ide> name: 'AbortError'
<del> });
<add> }, 'tick-1');
<add>
<add> await fileHandle.close();
<ide> }
<ide>
<ide> // Validate file size is within range for reading
<ide> async function doReadAndCancel() {
<ide> name: 'RangeError',
<ide> code: 'ERR_FS_FILE_TOO_LARGE'
<ide> });
<add> await fileHandle.close();
<ide> }
<ide> }
<ide> | 2 |
Javascript | Javascript | fix no-redeclare in code | eebc5ceaf60b101e9ccc65ae5bd07967ca9e803e | <ide><path>bin/convert-argv.js
<ide> module.exports = function(optimist, argv, convertOptions) {
<ide> return a.concat(i);
<ide> }, []);
<ide>
<add> var i;
<ide> if(argv.config) {
<ide> configPath = path.resolve(argv.config);
<del> for(var i = extensions.length - 1; i >= 0; i--) {
<add> for(i = extensions.length - 1; i >= 0; i--) {
<ide> var tmpExt = extensions[i];
<ide> if(configPath.indexOf(tmpExt, configPath.length - tmpExt.length) > -1) {
<ide> ext = tmpExt;
<ide> module.exports = function(optimist, argv, convertOptions) {
<ide> ext = path.extname(configPath);
<ide> }
<ide> } else {
<del> for(var i = 0; i < configFiles.length; i++) {
<add> for(i = 0; i < configFiles.length; i++) {
<ide> var webpackConfig = configFiles[i].path;
<ide> if(fs.existsSync(webpackConfig)) {
<ide> ext = configFiles[i].ext;
<ide><path>lib/HotModuleReplacement.runtime.js
<ide> module.exports = function() {
<ide> if(hotStatus !== "ready") throw new Error("apply() is only allowed in ready status");
<ide> options = options || {};
<ide>
<add> var cb;
<add> var i;
<add> var j;
<add> var module;
<add> var moduleId;
<add>
<ide> function getAffectedStuff(module) {
<ide> var outdatedModules = [module];
<ide> var outdatedDependencies = {};
<ide>
<ide> var queue = outdatedModules.slice();
<ide> while(queue.length > 0) {
<ide> var moduleId = queue.pop();
<del> var module = installedModules[moduleId];
<add> module = installedModules[moduleId];
<ide> if(!module || module.hot._selfAccepted)
<ide> continue;
<ide> if(module.hot._selfDeclined) {
<ide> module.exports = function() {
<ide> var appliedUpdate = {};
<ide> for(var id in hotUpdate) {
<ide> if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
<del> var moduleId = toModuleId(id);
<add> moduleId = toModuleId(id);
<ide> var result = getAffectedStuff(moduleId);
<ide> if(!result) {
<ide> if(options.ignoreUnaccepted)
<ide> module.exports = function() {
<ide> }
<ide> appliedUpdate[moduleId] = hotUpdate[moduleId];
<ide> addAllToSet(outdatedModules, result[0]);
<del> for(var moduleId in result[1]) {
<add> for(moduleId in result[1]) {
<ide> if(Object.prototype.hasOwnProperty.call(result[1], moduleId)) {
<ide> if(!outdatedDependencies[moduleId])
<ide> outdatedDependencies[moduleId] = [];
<ide> module.exports = function() {
<ide>
<ide> // Store self accepted outdated modules to require them later by the module system
<ide> var outdatedSelfAcceptedModules = [];
<del> for(var i = 0; i < outdatedModules.length; i++) {
<del> var moduleId = outdatedModules[i];
<add> for(i = 0; i < outdatedModules.length; i++) {
<add> moduleId = outdatedModules[i];
<ide> if(installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted)
<ide> outdatedSelfAcceptedModules.push({
<ide> module: moduleId,
<ide> module.exports = function() {
<ide>
<ide> // Now in "dispose" phase
<ide> hotSetStatus("dispose");
<add> var idx;
<ide> var queue = outdatedModules.slice();
<ide> while(queue.length > 0) {
<del> var moduleId = queue.pop();
<del> var module = installedModules[moduleId];
<add> moduleId = queue.pop();
<add> module = installedModules[moduleId];
<ide> if(!module) continue;
<ide>
<ide> var data = {};
<ide>
<ide> // Call dispose handlers
<ide> var disposeHandlers = module.hot._disposeHandlers;
<del> for(var j = 0; j < disposeHandlers.length; j++) {
<del> var cb = disposeHandlers[j];
<add> for(j = 0; j < disposeHandlers.length; j++) {
<add> cb = disposeHandlers[j];
<ide> cb(data);
<ide> }
<ide> hotCurrentModuleData[moduleId] = data;
<ide> module.exports = function() {
<ide> delete installedModules[moduleId];
<ide>
<ide> // remove "parents" references from all children
<del> for(var j = 0; j < module.children.length; j++) {
<add> for(j = 0; j < module.children.length; j++) {
<ide> var child = installedModules[module.children[j]];
<ide> if(!child) continue;
<del> var idx = child.parents.indexOf(moduleId);
<add> idx = child.parents.indexOf(moduleId);
<ide> if(idx >= 0) {
<ide> child.parents.splice(idx, 1);
<ide> }
<ide> }
<ide> }
<ide>
<ide> // remove outdated dependency from module children
<del> for(var moduleId in outdatedDependencies) {
<add> var dependency;
<add> var moduleOutdatedDependencies;
<add> for(moduleId in outdatedDependencies) {
<ide> if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
<del> var module = installedModules[moduleId];
<del> var moduleOutdatedDependencies = outdatedDependencies[moduleId];
<del> for(var j = 0; j < moduleOutdatedDependencies.length; j++) {
<del> var dependency = moduleOutdatedDependencies[j];
<del> var idx = module.children.indexOf(dependency);
<add> module = installedModules[moduleId];
<add> moduleOutdatedDependencies = outdatedDependencies[moduleId];
<add> for(j = 0; j < moduleOutdatedDependencies.length; j++) {
<add> dependency = moduleOutdatedDependencies[j];
<add> idx = module.children.indexOf(dependency);
<ide> if(idx >= 0) module.children.splice(idx, 1);
<ide> }
<ide> }
<ide> module.exports = function() {
<ide> hotCurrentHash = hotUpdateNewHash;
<ide>
<ide> // insert new code
<del> for(var moduleId in appliedUpdate) {
<add> for(moduleId in appliedUpdate) {
<ide> if(Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) {
<ide> modules[moduleId] = appliedUpdate[moduleId];
<ide> }
<ide> }
<ide>
<ide> // call accept handlers
<ide> var error = null;
<del> for(var moduleId in outdatedDependencies) {
<add> for(moduleId in outdatedDependencies) {
<ide> if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
<del> var module = installedModules[moduleId];
<del> var moduleOutdatedDependencies = outdatedDependencies[moduleId];
<add> module = installedModules[moduleId];
<add> moduleOutdatedDependencies = outdatedDependencies[moduleId];
<ide> var callbacks = [];
<del> for(var i = 0; i < moduleOutdatedDependencies.length; i++) {
<del> var dependency = moduleOutdatedDependencies[i];
<del> var cb = module.hot._acceptedDependencies[dependency];
<add> for(i = 0; i < moduleOutdatedDependencies.length; i++) {
<add> dependency = moduleOutdatedDependencies[i];
<add> cb = module.hot._acceptedDependencies[dependency];
<ide> if(callbacks.indexOf(cb) >= 0) continue;
<ide> callbacks.push(cb);
<ide> }
<del> for(var i = 0; i < callbacks.length; i++) {
<del> var cb = callbacks[i];
<add> for(i = 0; i < callbacks.length; i++) {
<add> cb = callbacks[i];
<ide> try {
<ide> cb(outdatedDependencies);
<ide> } catch(err) {
<ide> module.exports = function() {
<ide> }
<ide>
<ide> // Load self accepted modules
<del> for(var i = 0; i < outdatedSelfAcceptedModules.length; i++) {
<add> for(i = 0; i < outdatedSelfAcceptedModules.length; i++) {
<ide> var item = outdatedSelfAcceptedModules[i];
<del> var moduleId = item.module;
<add> moduleId = item.module;
<ide> hotCurrentParents = [moduleId];
<ide> try {
<ide> $require$(moduleId);
<ide><path>lib/ModuleFilenameHelpers.js
<ide> function asRegExp(test) {
<ide> }
<ide>
<ide> ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFilenameTemplate, requestShortener) {
<add> var absoluteResourcePath;
<add> var hash;
<add> var identifier;
<add> var moduleId;
<add> var shortIdentifier;
<ide> if(!module) module = "";
<ide> if(typeof module === "string") {
<del> var shortIdentifier = requestShortener.shorten(module);
<del> var identifier = shortIdentifier;
<del> var moduleId = "";
<del> var absoluteResourcePath = module.split("!").pop();
<del> var hash = getHash(identifier);
<add> shortIdentifier = requestShortener.shorten(module);
<add> identifier = shortIdentifier;
<add> moduleId = "";
<add> absoluteResourcePath = module.split("!").pop();
<add> hash = getHash(identifier);
<ide> } else {
<del> var shortIdentifier = module.readableIdentifier(requestShortener);
<del> var identifier = requestShortener.shorten(module.identifier());
<del> var moduleId = module.id;
<del> var absoluteResourcePath = module.resourcePath || module.identifier().split("!").pop();
<del> var hash = getHash(identifier);
<add> shortIdentifier = module.readableIdentifier(requestShortener);
<add> identifier = requestShortener.shorten(module.identifier());
<add> moduleId = module.id;
<add> absoluteResourcePath = module.resourcePath || module.identifier().split("!").pop();
<add> hash = getHash(identifier);
<ide> }
<ide> var resource = shortIdentifier.split("!").pop();
<ide> var loaders = getBefore(shortIdentifier, "!");
<ide><path>lib/Parser.js
<ide> Parser.prototype.initializeEvaluating = function() {
<ide> return new BasicEvaluatedExpression().setRegExp(expr.value).setRange(expr.range);
<ide> });
<ide> this.plugin("evaluate LogicalExpression", function(expr) {
<add> var left;
<add> var leftAsBool;
<add> var right;
<ide> if(expr.operator === "&&") {
<del> var left = this.evaluateExpression(expr.left);
<del> var leftAsBool = left && left.asBool();
<add> left = this.evaluateExpression(expr.left);
<add> leftAsBool = left && left.asBool();
<ide> if(leftAsBool === false) return left.setRange(expr.range);
<ide> if(leftAsBool !== true) return;
<del> var right = this.evaluateExpression(expr.right);
<add> right = this.evaluateExpression(expr.right);
<ide> return right.setRange(expr.range);
<ide> } else if(expr.operator === "||") {
<del> var left = this.evaluateExpression(expr.left);
<del> var leftAsBool = left && left.asBool();
<add> left = this.evaluateExpression(expr.left);
<add> leftAsBool = left && left.asBool();
<ide> if(leftAsBool === true) return left.setRange(expr.range);
<ide> if(leftAsBool !== false) return;
<del> var right = this.evaluateExpression(expr.right);
<add> right = this.evaluateExpression(expr.right);
<ide> return right.setRange(expr.range);
<ide> }
<ide> });
<ide> this.plugin("evaluate BinaryExpression", function(expr) {
<add> var left;
<add> var right;
<add> var res;
<ide> if(expr.operator === "+") {
<del> var left = this.evaluateExpression(expr.left);
<del> var right = this.evaluateExpression(expr.right);
<add> left = this.evaluateExpression(expr.left);
<add> right = this.evaluateExpression(expr.right);
<ide> if(!left || !right) return;
<del> var res = new BasicEvaluatedExpression();
<add> res = new BasicEvaluatedExpression();
<ide> if(left.isString()) {
<ide> if(right.isString()) {
<ide> res.setString(left.string + right.string);
<ide> Parser.prototype.initializeEvaluating = function() {
<ide> res.setRange(expr.range);
<ide> return res;
<ide> } else if(expr.operator === "-") {
<del> var left = this.evaluateExpression(expr.left);
<del> var right = this.evaluateExpression(expr.right);
<add> left = this.evaluateExpression(expr.left);
<add> right = this.evaluateExpression(expr.right);
<ide> if(!left || !right) return;
<ide> if(!left.isNumber() || !right.isNumber()) return;
<del> var res = new BasicEvaluatedExpression();
<add> res = new BasicEvaluatedExpression();
<ide> res.setNumber(left.number - right.number);
<ide> res.setRange(expr.range);
<ide> return res;
<ide> } else if(expr.operator === "*") {
<del> var left = this.evaluateExpression(expr.left);
<del> var right = this.evaluateExpression(expr.right);
<add> left = this.evaluateExpression(expr.left);
<add> right = this.evaluateExpression(expr.right);
<ide> if(!left || !right) return;
<ide> if(!left.isNumber() || !right.isNumber()) return;
<del> var res = new BasicEvaluatedExpression();
<add> res = new BasicEvaluatedExpression();
<ide> res.setNumber(left.number * right.number);
<ide> res.setRange(expr.range);
<ide> return res;
<ide> } else if(expr.operator === "/") {
<del> var left = this.evaluateExpression(expr.left);
<del> var right = this.evaluateExpression(expr.right);
<add> left = this.evaluateExpression(expr.left);
<add> right = this.evaluateExpression(expr.right);
<ide> if(!left || !right) return;
<ide> if(!left.isNumber() || !right.isNumber()) return;
<del> var res = new BasicEvaluatedExpression();
<add> res = new BasicEvaluatedExpression();
<ide> res.setNumber(left.number / right.number);
<ide> res.setRange(expr.range);
<ide> return res;
<ide> } else if(expr.operator === "==" || expr.operator === "===") {
<del> var left = this.evaluateExpression(expr.left);
<del> var right = this.evaluateExpression(expr.right);
<add> left = this.evaluateExpression(expr.left);
<add> right = this.evaluateExpression(expr.right);
<ide> if(!left || !right) return;
<del> var res = new BasicEvaluatedExpression();
<add> res = new BasicEvaluatedExpression();
<ide> res.setRange(expr.range);
<ide> if(left.isString() && right.isString()) {
<ide> return res.setBoolean(left.string === right.string);
<ide> Parser.prototype.initializeEvaluating = function() {
<ide> return res.setBoolean(left.bool === right.bool);
<ide> }
<ide> } else if(expr.operator === "!=" || expr.operator === "!==") {
<del> var left = this.evaluateExpression(expr.left);
<del> var right = this.evaluateExpression(expr.right);
<add> left = this.evaluateExpression(expr.left);
<add> right = this.evaluateExpression(expr.right);
<ide> if(!left || !right) return;
<del> var res = new BasicEvaluatedExpression();
<add> res = new BasicEvaluatedExpression();
<ide> res.setRange(expr.range);
<ide> if(left.isString() && right.isString()) {
<ide> return res.setBoolean(left.string !== right.string);
<ide> Parser.prototype.initializeEvaluating = function() {
<ide> });
<ide> this.plugin("evaluate UnaryExpression", function(expr) {
<ide> if(expr.operator === "typeof") {
<add> var res;
<ide> if(expr.argument.type === "Identifier") {
<ide> var name = this.scope.renames["$" + expr.argument.name] || expr.argument.name;
<ide> if(this.scope.definitions.indexOf(name) === -1) {
<del> var res = this.applyPluginsBailResult("evaluate typeof " + name, expr);
<add> res = this.applyPluginsBailResult("evaluate typeof " + name, expr);
<ide> if(res !== undefined) return res;
<ide> }
<ide> }
<ide> Parser.prototype.initializeEvaluating = function() {
<ide> exprName.unshift(this.scope.renames["$" + expression.name] || expression.name);
<ide> if(this.scope.definitions.indexOf(name) === -1) {
<ide> exprName = exprName.join(".");
<del> var res = this.applyPluginsBailResult("evaluate typeof " + exprName, expr);
<add> res = this.applyPluginsBailResult("evaluate typeof " + exprName, expr);
<ide> if(res !== undefined) return res;
<ide> }
<ide> }
<ide> Parser.prototype.initializeEvaluating = function() {
<ide> ["substr", "substring"].forEach(function(fn) {
<ide> this.plugin("evaluate CallExpression ." + fn, function(expr, param) {
<ide> if(!param.isString()) return;
<add> var arg1;
<ide> var result, str = param.string;
<ide> switch(expr.arguments.length) {
<ide> case 1:
<del> var arg1 = this.evaluateExpression(expr.arguments[0]);
<add> arg1 = this.evaluateExpression(expr.arguments[0]);
<ide> if(!arg1.isNumber()) return;
<ide> result = str[fn](arg1.number);
<ide> break;
<ide> case 2:
<del> var arg1 = this.evaluateExpression(expr.arguments[0]);
<add> arg1 = this.evaluateExpression(expr.arguments[0]);
<ide> var arg2 = this.evaluateExpression(expr.arguments[1]);
<ide> if(!arg1.isNumber()) return;
<ide> if(!arg2.isNumber()) return;
<ide> Parser.prototype.initializeEvaluating = function() {
<ide> this.plugin("evaluate ConditionalExpression", function(expr) {
<ide> var condition = this.evaluateExpression(expr.test);
<ide> var conditionValue = condition.asBool();
<add> var res;
<ide> if(conditionValue === undefined) {
<ide> var consequent = this.evaluateExpression(expr.consequent);
<ide> var alternate = this.evaluateExpression(expr.alternate);
<ide> if(!consequent || !alternate) return;
<del> var res = new BasicEvaluatedExpression();
<add> res = new BasicEvaluatedExpression();
<ide> if(consequent.isConditional())
<ide> res.setOptions(consequent.options);
<ide> else
<ide> Parser.prototype.initializeEvaluating = function() {
<ide> else
<ide> res.addOptions([alternate]);
<ide> } else {
<del> var res = this.evaluateExpression(conditionValue ? expr.consequent : expr.alternate);
<add> res = this.evaluateExpression(conditionValue ? expr.consequent : expr.alternate);
<ide> }
<ide> res.setRange(expr.range);
<ide> return res;
<ide> Parser.prototype.walkClassExpression = function walkClassExpression(expression)
<ide> Parser.prototype.walkCallExpression = function walkCallExpression(expression) {
<ide> function walkIIFE(functionExpression, args) {
<ide> var params = functionExpression.params;
<del> var args = args.map(function(arg) {
<add> args = args.map(function(arg) {
<ide> var renameIdentifier = this.getRenameIdentifier(arg);
<ide> if(renameIdentifier && this.applyPluginsBailResult("can-rename " + renameIdentifier, arg)) {
<ide> if(!this.applyPluginsBailResult("rename " + renameIdentifier, arg))
<ide><path>lib/SourceMapDevToolPlugin.js
<ide> SourceMapDevToolPlugin.prototype.apply = function(compiler) {
<ide> }
<ide> return;
<ide> }
<add> var source;
<add> var sourceMap;
<ide> if(asset.sourceAndMap) {
<ide> var sourceAndMap = asset.sourceAndMap(options);
<del> var sourceMap = sourceAndMap.map;
<del> var source = sourceAndMap.source;
<add> sourceMap = sourceAndMap.map;
<add> source = sourceAndMap.source;
<ide> } else {
<del> var sourceMap = asset.map(options);
<del> var source = asset.source();
<add> sourceMap = asset.map(options);
<add> source = asset.source();
<ide> }
<ide> if(sourceMap) {
<ide> return {
<ide><path>lib/Stats.js
<ide> Stats.jsonToString = function jsonToString(obj, useColors) {
<ide> }
<ide>
<ide> function table(array, formats, align, splitter) {
<add> var row;
<ide> var rows = array.length;
<add> var col;
<ide> var cols = array[0].length;
<ide> var colSizes = new Array(cols);
<del> for(var col = 0; col < cols; col++)
<add> var value;
<add> for(col = 0; col < cols; col++)
<ide> colSizes[col] = 3;
<del> for(var row = 0; row < rows; row++) {
<del> for(var col = 0; col < cols; col++) {
<del> var value = array[row][col] + "";
<add> for(row = 0; row < rows; row++) {
<add> for(col = 0; col < cols; col++) {
<add> value = array[row][col] + "";
<ide> if(value.length > colSizes[col]) {
<ide> colSizes[col] = value.length;
<ide> }
<ide> }
<ide> }
<del> for(var row = 0; row < rows; row++) {
<del> for(var col = 0; col < cols; col++) {
<add> for(row = 0; row < rows; row++) {
<add> for(col = 0; col < cols; col++) {
<ide> var format = row === 0 ? colors.bold : formats[col];
<del> var value = array[row][col] + "";
<add> value = array[row][col] + "";
<ide> var l = value.length;
<ide> if(align[col] === "l")
<ide> format(value);
<ide><path>lib/UmdMainTemplatePlugin.js
<ide> UmdMainTemplatePlugin.prototype.apply = function(compilation) {
<ide>
<ide> function externalsRequireArray(type) {
<ide> return replaceKeys(externals.map(function(m) {
<add> var expr;
<ide> var request = m.request;
<ide> if(typeof request === "object") request = request[type];
<ide> if(Array.isArray(request)) {
<del> var expr = "require(" + JSON.stringify(request[0]) + ")" + accessorToObjectAccess(request.slice(1));
<add> expr = "require(" + JSON.stringify(request[0]) + ")" + accessorToObjectAccess(request.slice(1));
<ide> } else
<del> var expr = "require(" + JSON.stringify(request) + ")";
<add> expr = "require(" + JSON.stringify(request) + ")";
<ide> if(m.optional) {
<ide> expr = "(function webpackLoadOptionalExternalModule() { try { return " + expr + "; } catch(e) {} }())";
<ide> }
<ide> UmdMainTemplatePlugin.prototype.apply = function(compilation) {
<ide> return JSON.stringify(replaceKeys([].concat(library).pop()));
<ide> }
<ide>
<add> var amdFactory;
<ide> if(optionalExternals.length > 0) {
<del> var amdFactory = "function webpackLoadOptionalExternalModuleAmd(" + externalsArguments(requiredExternals) + ") {\n" +
<add> amdFactory = "function webpackLoadOptionalExternalModuleAmd(" + externalsArguments(requiredExternals) + ") {\n" +
<ide> " return factory(" + (
<ide> requiredExternals.length > 0 ?
<ide> externalsArguments(requiredExternals) + ", " + externalsRootArray(optionalExternals) :
<ide> externalsRootArray(optionalExternals)
<ide> ) + ");\n" +
<ide> " }";
<ide> } else {
<del> var amdFactory = "factory";
<add> amdFactory = "factory";
<ide> }
<ide>
<ide> return new ConcatSource(new OriginalSource(
<ide><path>lib/WebpackOptionsApply.js
<ide> module.exports = WebpackOptionsApply;
<ide>
<ide> WebpackOptionsApply.prototype = Object.create(OptionsApply.prototype);
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<add> var ExternalsPlugin;
<ide> compiler.context = options.context;
<ide> if(options.plugins && Array.isArray(options.plugins)) {
<ide> compiler.apply.apply(compiler, options.plugins);
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> compiler.recordsOutputPath = options.recordsOutputPath || options.recordsPath;
<ide> compiler.name = options.name;
<ide> if(typeof options.target === "string") {
<add> var JsonpTemplatePlugin;
<add> var NodeSourcePlugin;
<add> var NodeTargetPlugin;
<add> var NodeTemplatePlugin;
<ide> switch(options.target) {
<ide> case "web":
<del> var JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
<del> var NodeSourcePlugin = require("./node/NodeSourcePlugin");
<add> JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
<add> NodeSourcePlugin = require("./node/NodeSourcePlugin");
<ide> compiler.apply(
<ide> new JsonpTemplatePlugin(options.output),
<ide> new FunctionModulePlugin(options.output),
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> break;
<ide> case "webworker":
<ide> var WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin");
<del> var NodeSourcePlugin = require("./node/NodeSourcePlugin");
<add> NodeSourcePlugin = require("./node/NodeSourcePlugin");
<ide> compiler.apply(
<ide> new WebWorkerTemplatePlugin(options.output),
<ide> new FunctionModulePlugin(options.output),
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> break;
<ide> case "node":
<ide> case "async-node":
<del> var NodeTemplatePlugin = require("./node/NodeTemplatePlugin");
<del> var NodeTargetPlugin = require("./node/NodeTargetPlugin");
<add> NodeTemplatePlugin = require("./node/NodeTemplatePlugin");
<add> NodeTargetPlugin = require("./node/NodeTargetPlugin");
<ide> compiler.apply(
<ide> new NodeTemplatePlugin({
<ide> asyncChunkLoading: options.target === "async-node"
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> );
<ide> break;
<ide> case "node-webkit":
<del> var JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
<del> var NodeTargetPlugin = require("./node/NodeTargetPlugin");
<del> var ExternalsPlugin = require("./ExternalsPlugin");
<add> JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
<add> NodeTargetPlugin = require("./node/NodeTargetPlugin");
<add> ExternalsPlugin = require("./ExternalsPlugin");
<ide> compiler.apply(
<ide> new JsonpTemplatePlugin(options.output),
<ide> new FunctionModulePlugin(options.output),
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> case "atom":
<ide> case "electron":
<ide> case "electron-main":
<del> var NodeTemplatePlugin = require("./node/NodeTemplatePlugin");
<del> var NodeTargetPlugin = require("./node/NodeTargetPlugin");
<del> var ExternalsPlugin = require("./ExternalsPlugin");
<add> NodeTemplatePlugin = require("./node/NodeTemplatePlugin");
<add> NodeTargetPlugin = require("./node/NodeTargetPlugin");
<add> ExternalsPlugin = require("./ExternalsPlugin");
<ide> compiler.apply(
<ide> new NodeTemplatePlugin({
<ide> asyncChunkLoading: true
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> );
<ide> break;
<ide> case "electron-renderer":
<del> var JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
<del> var NodeTargetPlugin = require("./node/NodeTargetPlugin");
<del> var ExternalsPlugin = require("./ExternalsPlugin");
<add> JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
<add> NodeTargetPlugin = require("./node/NodeTargetPlugin");
<add> ExternalsPlugin = require("./ExternalsPlugin");
<ide> compiler.apply(
<ide> new JsonpTemplatePlugin(options.output),
<ide> new FunctionModulePlugin(options.output),
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> compiler.apply(new LibraryTemplatePlugin(options.output.library, options.output.libraryTarget, options.output.umdNamedDefine));
<ide> }
<ide> if(options.externals) {
<del> var ExternalsPlugin = require("./ExternalsPlugin");
<add> ExternalsPlugin = require("./ExternalsPlugin");
<ide> compiler.apply(new ExternalsPlugin(options.output.libraryTarget, options.externals));
<ide> }
<del>
<add> var legacy;
<add> var modern;
<add> var comment;
<ide> if(options.devtool && (options.devtool.indexOf("sourcemap") >= 0 || options.devtool.indexOf("source-map") >= 0)) {
<ide> var hidden = options.devtool.indexOf("hidden") >= 0;
<ide> var inline = options.devtool.indexOf("inline") >= 0;
<ide> var evalWrapped = options.devtool.indexOf("eval") >= 0;
<ide> var cheap = options.devtool.indexOf("cheap") >= 0;
<ide> var moduleMaps = options.devtool.indexOf("module") >= 0;
<del> var legacy = options.devtool.indexOf("@") >= 0;
<del> var modern = options.devtool.indexOf("#") >= 0;
<del> var comment = legacy && modern ? "\n/*\n//@ sourceMappingURL=[url]\n//# sourceMappingURL=[url]\n*/" :
<add> legacy = options.devtool.indexOf("@") >= 0;
<add> modern = options.devtool.indexOf("#") >= 0;
<add> comment = legacy && modern ? "\n/*\n//@ sourceMappingURL=[url]\n//# sourceMappingURL=[url]\n*/" :
<ide> legacy ? "\n/*\n//@ sourceMappingURL=[url]\n*/" :
<ide> modern ? "\n//# sourceMappingURL=[url]" :
<ide> null;
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> lineToLine: options.output.devtoolLineToLine
<ide> }));
<ide> } else if(options.devtool && options.devtool.indexOf("eval") >= 0) {
<del> var legacy = options.devtool.indexOf("@") >= 0;
<del> var modern = options.devtool.indexOf("#") >= 0;
<del> var comment = legacy && modern ? "\n//@ sourceURL=[url]\n//# sourceURL=[url]" :
<add> legacy = options.devtool.indexOf("@") >= 0;
<add> modern = options.devtool.indexOf("#") >= 0;
<add> comment = legacy && modern ? "\n//@ sourceURL=[url]\n//# sourceURL=[url]" :
<ide> legacy ? "\n//@ sourceURL=[url]" :
<ide> modern ? "\n//# sourceURL=[url]" :
<ide> null;
<ide><path>lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js
<ide> module.exports = AMDRequireDependenciesBlockParserPlugin;
<ide> AMDRequireDependenciesBlockParserPlugin.prototype.apply = function(parser) {
<ide> var options = this.options;
<ide> parser.plugin("call require", function(expr) {
<add> var param;
<add> var dep;
<add> var old;
<add> var result;
<ide> switch(expr.arguments.length) {
<ide> case 1:
<del> var param = this.evaluateExpression(expr.arguments[0]);
<del> var result;
<del> var dep = new AMDRequireDependenciesBlock(expr, param.range, null, this.state.module, expr.loc);
<del> var old = this.state.current;
<add> param = this.evaluateExpression(expr.arguments[0]);
<add> dep = new AMDRequireDependenciesBlock(expr, param.range, null, this.state.module, expr.loc);
<add> old = this.state.current;
<ide> this.state.current = dep;
<ide> this.inScope([], function() {
<ide> result = this.applyPluginsBailResult("call require:amd:array", expr, param);
<ide> AMDRequireDependenciesBlockParserPlugin.prototype.apply = function(parser) {
<ide> this.state.current.addBlock(dep);
<ide> return true;
<ide> case 2:
<del> var param = this.evaluateExpression(expr.arguments[0]);
<del> var dep = new AMDRequireDependenciesBlock(expr, param.range, expr.arguments[1].range, this.state.module, expr.loc);
<add> param = this.evaluateExpression(expr.arguments[0]);
<add> dep = new AMDRequireDependenciesBlock(expr, param.range, expr.arguments[1].range, this.state.module, expr.loc);
<ide> dep.loc = expr.loc;
<del> var old = this.state.current;
<add> old = this.state.current;
<ide> this.state.current = dep;
<ide> try {
<del> var result;
<ide> this.inScope([], function() {
<ide> result = this.applyPluginsBailResult("call require:amd:array", expr, param);
<ide> }.bind(this));
<ide><path>lib/dependencies/ContextDependencyHelpers.js
<ide> var ContextDependencyHelpers = exports;
<ide>
<ide> ContextDependencyHelpers.create = function(Dep, range, param, expr, options) {
<add> var dep;
<ide> if(param.isWrapped() && (param.prefix && param.prefix.isString() || param.postfix && param.postfix.isString())) {
<ide> var prefix = param.prefix && param.prefix.isString() ? param.prefix.string : "";
<ide> var postfix = param.postfix && param.postfix.isString() ? param.postfix.string : "";
<ide> ContextDependencyHelpers.create = function(Dep, range, param, expr, options) {
<ide> prefix.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") +
<ide> options.wrappedContextRegExp.source +
<ide> postfix.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "$");
<del> var dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange);
<add> dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange);
<ide> dep.loc = expr.loc;
<ide> dep.prepend = param.prefix && param.prefix.isString() ? prefix : null;
<ide> dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression";
<ide> return dep;
<ide> } else {
<del> var dep = new Dep(options.exprContextRequest, options.exprContextRecursive, options.exprContextRegExp, range, param.range);
<add> dep = new Dep(options.exprContextRequest, options.exprContextRecursive, options.exprContextRegExp, range, param.range);
<ide> dep.loc = expr.loc;
<ide> dep.critical = options.exprContextCritical && "the request of a dependency is an expression";
<ide> return dep;
<ide><path>lib/dependencies/LabeledModuleDependencyParserPlugin.js
<ide> module.exports = AbstractPlugin.create({
<ide> }
<ide> },
<ide> "label exports": function(stmt) {
<add> var name;
<add> var dep;
<ide> switch(stmt.body.type) {
<ide> case "VariableDeclaration":
<ide> stmt.body.declarations.forEach(function(decl) {
<ide> module.exports = AbstractPlugin.create({
<ide> }, this);
<ide> return true;
<ide> case "FunctionDeclaration":
<del> var name = stmt.body.id.name;
<del> var dep = new LabeledExportsDependency(name, stmt.body.range[0]);
<add> name = stmt.body.id.name;
<add> dep = new LabeledExportsDependency(name, stmt.body.range[0]);
<ide> dep.loc = stmt.loc;
<ide> this.state.current.addDependency(dep);
<ide> if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
<ide> this.state.module.meta.exports.push(name);
<ide> return true;
<ide> case "ExpressionStatement":
<ide> if(stmt.body.expression.type === "Identifier") {
<del> var name = stmt.body.expression.name;
<del> var dep = new LabeledExportsDependency(name, stmt.body.expression.range[0]);
<add> name = stmt.body.expression.name;
<add> dep = new LabeledExportsDependency(name, stmt.body.expression.range[0]);
<ide> dep.loc = stmt.loc;
<ide> this.state.current.addDependency(dep);
<ide> if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
<ide> module.exports = AbstractPlugin.create({
<ide> } else if(stmt.body.expression.type === "SequenceExpression") {
<ide> stmt.body.expression.expressions.forEach(function(e) {
<ide> if(e.type !== "Identifier") return;
<del> var name = e.name;
<del> var dep = new LabeledExportsDependency(name, e.range[0]);
<add> name = e.name;
<add> dep = new LabeledExportsDependency(name, e.range[0]);
<ide> dep.loc = stmt.loc;
<ide> this.state.current.addDependency(dep);
<ide> if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
<ide><path>lib/dependencies/ModuleDependencyTemplateAsId.js
<ide> ModuleDependencyTemplateAsId.prototype.apply = function(dep, source, outputOptio
<ide> if(!dep.range) return;
<ide> var comment = "";
<ide> if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ ";
<add> var content;
<ide> if(dep.module)
<del> var content = comment + JSON.stringify(dep.module.id);
<add> content = comment + JSON.stringify(dep.module.id);
<ide> else
<del> var content = require("./WebpackMissingModule").module(dep.request);
<add> content = require("./WebpackMissingModule").module(dep.request);
<ide> source.replace(dep.range[0], dep.range[1] - 1, content);
<ide> };
<ide>
<ide><path>lib/dependencies/ModuleDependencyTemplateAsRequireId.js
<ide> ModuleDependencyTemplateAsRequireId.prototype.apply = function(dep, source, outp
<ide> if(!dep.range) return;
<ide> var comment = "";
<ide> if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ ";
<add> var content;
<ide> if(dep.module)
<del> var content = "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")";
<add> content = "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")";
<ide> else
<del> var content = require("./WebpackMissingModule").module(dep.request);
<add> content = require("./WebpackMissingModule").module(dep.request);
<ide> source.replace(dep.range[0], dep.range[1] - 1, content);
<ide> };
<ide>
<ide><path>lib/optimize/AggressiveMergingPlugin.js
<ide> AggressiveMergingPlugin.prototype.apply = function(compiler) {
<ide> b: b,
<ide> ab: ab
<ide> });
<add> var newSize;
<ide> if(ab === false) {
<ide> pair.unshift(false);
<ide> } else if(options.moveToParents) {
<ide> var aOnly = ab - b;
<ide> var bOnly = ab - a;
<ide> var common = a + b - ab;
<del> var newSize = common + getParentsWeight(pair[0]) * aOnly + getParentsWeight(pair[1]) * bOnly;
<add> newSize = common + getParentsWeight(pair[0]) * aOnly + getParentsWeight(pair[1]) * bOnly;
<ide> pair.push({
<ide> aOnly: aOnly,
<ide> bOnly: bOnly,
<ide> common: common,
<ide> newSize: newSize
<ide> });
<ide> } else {
<del> var newSize = ab;
<add> newSize = ab;
<ide> }
<ide>
<ide> pair.unshift((a + b) / newSize);
<ide><path>lib/optimize/DedupePlugin.js
<ide> DedupePlugin.prototype.apply = function(compiler) {
<ide> var chunkIndex = module.rootDuplicatesChunks.indexOf(chunk);
<ide> if(!module.rootDuplicates || !module.rootDuplicates[chunkIndex]) return moduleSource;
<ide> var rootDuplicates = module.rootDuplicates[chunkIndex];
<add> var source;
<ide> if(rootDuplicates.template) {
<ide> rootDuplicates.template.addReason(module, {
<ide> type: "template",
<ide> DedupePlugin.prototype.apply = function(compiler) {
<ide> return "(function webpackMissingModule() { throw new Error(" + JSON.stringify("Cannot find module") + "); }())";
<ide> return JSON.stringify(module.id);
<ide> }));
<del> var source = new ConcatSource("[" + array.join(", ") + "]");
<add> source = new ConcatSource("[" + array.join(", ") + "]");
<ide> return source;
<ide> } else {
<ide> rootDuplicates.sort(function(a, b) {
<ide> return a.id - b.id;
<ide> });
<ide> if(module === rootDuplicates[0]) return moduleSource;
<del> var source = new ConcatSource("" + JSON.stringify(rootDuplicates[0].id));
<add> source = new ConcatSource("" + JSON.stringify(rootDuplicates[0].id));
<ide> return source;
<ide> }
<ide> });
<ide><path>lib/optimize/UglifyJsPlugin.js
<ide> UglifyJsPlugin.prototype.apply = function(compiler) {
<ide> compilation.assets[file] = asset.__UglifyJsPlugin;
<ide> return;
<ide> }
<add> var input;
<ide> if(options.sourceMap !== false) {
<add> var inputSourceMap;
<ide> if(asset.sourceAndMap) {
<ide> var sourceAndMap = asset.sourceAndMap();
<del> var inputSourceMap = sourceAndMap.map;
<del> var input = sourceAndMap.source;
<add> inputSourceMap = sourceAndMap.map;
<add> input = sourceAndMap.source;
<ide> } else {
<del> var inputSourceMap = asset.map();
<del> var input = asset.source();
<add> inputSourceMap = asset.map();
<add> input = asset.source();
<ide> }
<ide> var sourceMap = new SourceMapConsumer(inputSourceMap);
<ide> uglify.AST_Node.warn_function = function(warning) { // eslint-disable-line camelcase
<ide> UglifyJsPlugin.prototype.apply = function(compiler) {
<ide> "[" + requestShortener.shorten(original.source) + ":" + original.line + "," + original.column + "]");
<ide> };
<ide> } else {
<del> var input = asset.source();
<add> input = asset.source();
<ide> uglify.AST_Node.warn_function = function(warning) { // eslint-disable-line camelcase
<ide> warnings.push(warning);
<ide> }; | 16 |
Java | Java | append unique number to log prefix for undertow | bad8954e65b5c27d40d19fe98a0e12f8986114d6 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.net.URI;
<ide> import java.net.URISyntaxException;
<ide> import java.nio.ByteBuffer;
<add>import java.util.concurrent.atomic.AtomicLong;
<ide>
<ide> import javax.net.ssl.SSLSession;
<ide>
<ide> */
<ide> class UndertowServerHttpRequest extends AbstractServerHttpRequest {
<ide>
<add> private static final AtomicLong logPrefixIndex = new AtomicLong();
<add>
<add>
<ide> private final HttpServerExchange exchange;
<ide>
<ide> private final RequestBodyPublisher body;
<ide> public <T> T getNativeRequest() {
<ide>
<ide> @Override
<ide> protected String initId() {
<del> return ObjectUtils.getIdentityHexString(this.exchange.getConnection());
<add> return ObjectUtils.getIdentityHexString(this.exchange.getConnection()) +
<add> "-" + logPrefixIndex.incrementAndGet();
<ide> }
<ide>
<ide> | 1 |
Text | Text | fix typo in doc | d13ce702a8346b72bf6461cb1da52d08d39a2d4a | <ide><path>docs/docs/07.1-more-about-refs.md
<ide> Consider the case when you wish to tell an `<input />` element (that exists with
<ide> ```
<ide>
<ide>
<del>Notice how, in this example, we want to "tell" the input something - something that it cannot infer from its props over time. In this case we want to "tell" it that it should now become focused. However, there are some challenges. What is returned from `render()`` is not your actual composition of "child" components, it is merely a *description* of the children at a particular instance in time - a snapshot, if you will.
<add>Notice how, in this example, we want to "tell" the input something - something that it cannot infer from its props over time. In this case we want to "tell" it that it should now become focused. However, there are some challenges. What is returned from `render()` is not your actual composition of "child" components, it is merely a *description* of the children at a particular instance in time - a snapshot, if you will.
<ide>
<ide> > Note:
<ide> > | 1 |
Python | Python | add date to index, unbreak object push | 5bf7069053d33276e770341079e6a907613903de | <ide><path>glances/exports/glances_elasticsearch.py
<ide> def init(self):
<ide> if not self.export_enable:
<ide> return None
<ide>
<add> self.index='{}-{}'.format(self.index, datetime.today().strftime("%Y.%m.%d"))
<ide> try:
<ide> es = Elasticsearch(hosts=['{}:{}'.format(self.host, self.port)])
<ide> except Exception as e:
<ide> def export(self, name, columns, points):
<ide> for c, p in zip(columns, points):
<ide> action = {
<ide> "_index": self.index,
<del> "_type": name,
<ide> "_id": c,
<add> "_type": "glances",
<ide> "_source": {
<add> "name": name,
<ide> "value": str(p),
<add> "type": "keyword",
<ide> "timestamp": datetime.now()
<ide> }
<ide> }
<add> logger.debug("Exporting the following object to elasticsearch: {}".format(action))
<ide> actions.append(action)
<ide>
<ide> # Write input to the ES index | 1 |
Text | Text | fix a small typo | c8a9c856c25a1a360a91d2c7bc11e0dacfb9c3a4 | <ide><path>docs/api-guide/renderers.md
<ide> The TemplateHTMLRenderer will create a `RequestContext`, using the `response.dat
<ide>
<ide> ---
<ide>
<del>**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionay and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
<add>**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
<ide>
<ide> ```
<ide> response.data = {'results': response.data} | 1 |
Mixed | Python | add slim image to docs/docker-stack/readme.md | cd9d935c350f33e194e46bab3d8150ef303e1181 | <ide><path>docs/docker-stack/README.md
<ide> You can find the following images there (Assuming Airflow version `2.4.0.dev0`):
<ide> * `apache/airflow:2.4.0.dev0` - the versioned Airflow image with default Python version (3.7 currently)
<ide> * `apache/airflow:2.4.0.dev0-pythonX.Y` - the versioned Airflow image with specific Python version
<ide>
<del>Those are "reference" images. They contain the most common set of extras, dependencies and providers that are
<add>Those are "reference" regular images. They contain the most common set of extras, dependencies and providers that are
<ide> often used by the users and they are good to "try-things-out" when you want to just take Airflow for a spin,
<ide>
<add>You can also use "slim" images that contain only core airflow and are about half the size of the "regular" images
<add>but you need to add all the [Reference for package extras](https://airflow.apache.org/docs/apache-airflow/stable/extra-packages-ref.html) and providers that you need separately
<add>via [Building the image](https://airflow.apache.org/docs/docker-stack/build.html#build-build-image).
<add>
<add>* `apache/airflow:slim-latest` - the latest released Airflow image with default Python version (3.7 currently)
<add>* `apache/airflow:slim-latest-pythonX.Y` - the latest released Airflow image with specific Python version
<add>* `apache/airflow:slim-2.4.0.dev0` - the versioned Airflow image with default Python version (3.7 currently)
<add>* `apache/airflow:slim-2.4.0.dev0-pythonX.Y` - the versioned Airflow image with specific Python version
<add>
<ide> The Apache Airflow image provided as convenience package is optimized for size, and
<ide> it provides just a bare minimal set of the extras and dependencies installed and in most cases
<ide> you want to either extend or customize the image. You can see all possible extras in [Reference for package extras](https://airflow.apache.org/docs/apache-airflow/stable/extra-packages-ref.html).
<ide><path>scripts/ci/pre_commit/pre_commit_update_versions.py
<ide> def update_version(pattern: re.Pattern, v: str, file_path: str):
<ide> REPLACEMENTS = {
<ide> r'^(FROM apache\/airflow:).*($)': "docs/docker-stack/docker-examples/extending/*/Dockerfile",
<ide> r'(apache\/airflow:)[^-]*(\-)': "docs/docker-stack/entrypoint.rst",
<del> r'(`apache/airflow:)[0-9].*?((?:-pythonX.Y)?`)': "docs/docker-stack/README.md",
<add> r'(`apache/airflow:(?:slim-)?)[0-9].*?((?:-pythonX.Y)?`)': "docs/docker-stack/README.md",
<ide> r'(\(Assuming Airflow version `).*(`\))': "docs/docker-stack/README.md",
<ide> }
<ide> | 2 |
Python | Python | add option to generate panoptic masks | e46a24972c6220d8d0800dddfebda8f6d3256366 | <ide><path>official/vision/beta/projects/panoptic_maskrcnn/modeling/factory.py
<ide> def build_panoptic_deeplab(
<ide> norm_epsilon=norm_activation_config.norm_epsilon,
<ide> kernel_regularizer=l2_regularizer)
<ide>
<del> post_processing_config = model_config.post_processor
<del> post_processor = panoptic_deeplab_merge.PostProcessor(
<del> center_score_threshold=post_processing_config.center_score_threshold,
<del> thing_class_ids=post_processing_config.thing_class_ids,
<del> label_divisor=post_processing_config.label_divisor,
<del> stuff_area_limit=post_processing_config.stuff_area_limit,
<del> ignore_label=post_processing_config.ignore_label,
<del> nms_kernel=post_processing_config.nms_kernel,
<del> keep_k_centers=post_processing_config.keep_k_centers)
<add> if model_config.generate_panoptic_masks:
<add> post_processing_config = model_config.post_processor
<add> post_processor = panoptic_deeplab_merge.PostProcessor(
<add> output_size=post_processing_config.output_size,
<add> center_score_threshold=post_processing_config.center_score_threshold,
<add> thing_class_ids=post_processing_config.thing_class_ids,
<add> label_divisor=post_processing_config.label_divisor,
<add> stuff_area_limit=post_processing_config.stuff_area_limit,
<add> ignore_label=post_processing_config.ignore_label,
<add> nms_kernel=post_processing_config.nms_kernel,
<add> keep_k_centers=post_processing_config.keep_k_centers,
<add> rescale_predictions=post_processing_config.rescale_predictions)
<add> else:
<add> post_processor = None
<ide>
<ide> model = panoptic_deeplab_model.PanopticDeeplabModel(
<ide> backbone=backbone,
<ide><path>official/vision/beta/projects/panoptic_maskrcnn/modeling/factory_test.py
<ide> class PanopticDeeplabBuilderTest(parameterized.TestCase, tf.test.TestCase):
<ide> decoder_type=['aspp', 'fpn'],
<ide> level=[2, 3, 4],
<ide> low_level=[(4, 3), (3, 2)],
<del> shared_decoder=[True, False]))
<del> def test_builder(self, input_size, backbone_type, level,
<del> low_level, decoder_type, shared_decoder):
<add> shared_decoder=[True, False],
<add> generate_panoptic_masks=[True, False]))
<add> def test_builder(self, input_size, backbone_type,
<add> level, low_level, decoder_type,
<add> shared_decoder, generate_panoptic_masks):
<ide> num_classes = 10
<ide> input_specs = tf.keras.layers.InputSpec(
<ide> shape=[None, input_size[0], input_size[1], 3])
<ide> def test_builder(self, input_size, backbone_type, level,
<ide> kernel_size=5,
<ide> prediction_kernel_size=1,
<ide> low_level=low_level),
<del> shared_decoder=shared_decoder)
<add> shared_decoder=shared_decoder,
<add> generate_panoptic_masks=generate_panoptic_masks)
<ide>
<ide> l2_regularizer = tf.keras.regularizers.l2(5e-5)
<ide> _ = factory.build_panoptic_deeplab(
<ide><path>official/vision/beta/projects/panoptic_maskrcnn/modeling/panoptic_deeplab_model.py
<ide> def __init__(
<ide> self.instance_head = instance_head
<ide> self.post_processor = post_processor
<ide>
<del> def call(self, inputs: tf.Tensor, training: bool = None) -> tf.Tensor:
<add> def call(
<add> self, inputs: tf.Tensor,
<add> image_info: tf.Tensor,
<add> training: bool = None) -> tf.Tensor:
<ide> if training is None:
<ide> training = tf.keras.backend.learning_phase()
<ide>
<ide> def call(self, inputs: tf.Tensor, training: bool = None) -> tf.Tensor:
<ide>
<ide> outputs = {
<ide> 'segmentation_outputs': segmentation_outputs,
<del> 'instance_center_prediction':
<del> instance_outputs['instance_center_prediction'],
<del> 'instance_center_regression':
<del> instance_outputs['instance_center_regression'],
<add> 'instance_centers_heatmap':
<add> instance_outputs['instance_centers_heatmap'],
<add> 'instance_centers_offset':
<add> instance_outputs['instance_centers_offset'],
<ide> }
<ide> if training:
<ide> return outputs
<ide>
<del> outputs = self.post_processor(outputs)
<add> if self.post_processor is not None:
<add> panoptic_masks = self.post_processor(outputs, image_info)
<add> outputs.update(panoptic_masks)
<add>
<ide> return outputs
<ide>
<ide> @property | 3 |
PHP | PHP | fix white line | 86aea2615e57b4ac02db238dcca4fcb73ac98b45 | <ide><path>tests/TestCase/I18n/Parser/MoFileParserTest.php
<ide> * @since 3.0.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>
<ide> namespace Cake\Test\TestCase\I18n\Parser;
<ide>
<ide> use Cake\I18n\Parser\MoFileParser; | 1 |
Go | Go | fix profiler http serving | 3bea892d5458fc627f2ebe26f44a09df018d1fcc | <ide><path>api/server/profiler.go
<ide> import (
<ide> "github.com/gorilla/mux"
<ide> )
<ide>
<del>func NewProfiler() http.Handler {
<del> var (
<del> p = &Profiler{}
<del> r = mux.NewRouter()
<del> )
<del> r.HandleFunc("/vars", p.expVars)
<add>func ProfilerSetup(mainRouter *mux.Router, path string) {
<add> var r = mainRouter.PathPrefix(path).Subrouter()
<add> r.HandleFunc("/vars", expVars)
<ide> r.HandleFunc("/pprof/", pprof.Index)
<ide> r.HandleFunc("/pprof/cmdline", pprof.Cmdline)
<ide> r.HandleFunc("/pprof/profile", pprof.Profile)
<ide> func NewProfiler() http.Handler {
<ide> r.HandleFunc("/pprof/heap", pprof.Handler("heap").ServeHTTP)
<ide> r.HandleFunc("/pprof/goroutine", pprof.Handler("goroutine").ServeHTTP)
<ide> r.HandleFunc("/pprof/threadcreate", pprof.Handler("threadcreate").ServeHTTP)
<del> p.r = r
<del> return p
<del>}
<del>
<del>// Profiler enables pprof and expvar support via a HTTP API.
<del>type Profiler struct {
<del> r *mux.Router
<del>}
<del>
<del>func (p *Profiler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
<del> p.r.ServeHTTP(w, r)
<ide> }
<ide>
<ide> // Replicated from expvar.go as not public.
<del>func (p *Profiler) expVars(w http.ResponseWriter, r *http.Request) {
<add>func expVars(w http.ResponseWriter, r *http.Request) {
<ide> first := true
<ide> w.Header().Set("Content-Type", "application/json; charset=utf-8")
<ide> fmt.Fprintf(w, "{\n")
<ide><path>api/server/server.go
<ide> func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, local
<ide> func createRouter(eng *engine.Engine, logging, enableCors bool, corsHeaders string, dockerVersion string) *mux.Router {
<ide> r := mux.NewRouter()
<ide> if os.Getenv("DEBUG") != "" {
<del> r.Handle("/debug", NewProfiler())
<add> ProfilerSetup(r, "/debug/")
<ide> }
<ide> m := map[string]map[string]HttpApiFunc{
<ide> "GET": { | 2 |
Ruby | Ruby | add missing deprecation requires | fef31be2bceba083744c856f29dabdc3fb03402b | <ide><path>railties/lib/rails/application/configuration.rb
<add>require 'active_support/deprecation'
<ide> require 'rails/engine/configuration'
<ide>
<ide> module Rails
<ide><path>railties/lib/rails/configuration.rb
<add>require 'active_support/deprecation'
<ide> require 'active_support/ordered_options'
<ide> require 'rails/paths'
<ide> require 'rails/rack'
<ide><path>railties/lib/rails/railtie.rb
<ide> require 'rails/initializable'
<ide> require 'rails/configuration'
<ide> require 'active_support/inflector'
<add>require 'active_support/deprecation'
<ide>
<ide> module Rails
<ide> # Railtie is the core of the Rails Framework and provides several hooks to extend | 3 |
Javascript | Javascript | add error for number constructor, too | 2f63b0d6c9f16e4820d969532e8f9ae00ab66bdd | <ide><path>eslint-rules/no-primitive-constructors.js
<ide> module.exports = function(context) {
<ide> '\'\' + value'
<ide> );
<ide> break;
<add> case 'Number':
<add> report(
<add> node,
<add> name,
<add> 'To cast a value to a number, use the plus operator: +value'
<add> );
<add> break;
<ide> }
<ide> }
<ide> | 1 |
Text | Text | add django api client to the third party packages | 327cbef29977bb999f292d3c8b7b3efc2491691d | <ide><path>docs/community/third-party-packages.md
<ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque
<ide> * [drf-viewset-profiler][drf-viewset-profiler] - Lib to profile all methods from a viewset line by line.
<ide> * [djangorestframework-features][djangorestframework-features] - Advanced schema generation and more based on named features.
<ide> * [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons.
<add>* [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models..
<ide>
<ide> [cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html
<ide> [cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
<ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque
<ide> [drf-viewset-profiler]: https://github.com/fvlima/drf-viewset-profiler
<ide> [djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/
<ide> [django-elasticsearch-dsl-drf]: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf
<add>[django-api-client]: https://github.com/rhenter/django-api-client | 1 |
PHP | PHP | fix some failing tests related to routing | 836fa834b428aa77657802051a7424ff5347a222 | <ide><path>lib/Cake/Test/TestCase/TestSuite/ControllerTestCaseTest.php
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\Test\TestCase\TestSuite;
<add>
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Configure;
<ide> public function setUp() {
<ide> 'Model' => array(CAKE . 'Test' . DS . 'TestApp' . DS . 'Model' . DS),
<ide> 'View' => array(CAKE . 'Test' . DS . 'TestApp' . DS . 'View' . DS)
<ide> ), App::RESET);
<del> $this->_ns = Configure::read('App.namespace');
<ide> Configure::write('App.namespace', 'TestApp');
<ide> Plugin::load(array('TestPlugin', 'TestPluginTwo'));
<ide> $this->Case = $this->getMockForAbstractClass('Cake\TestSuite\ControllerTestCase');
<ide> public function setUp() {
<ide> */
<ide> public function tearDown() {
<ide> parent::tearDown();
<del> Configure::write('App.namespace', $this->_ns);
<ide> Plugin::unload();
<ide> $this->Case->controller = null;
<ide> }
<ide> public function tearDown() {
<ide> public function testGenerate() {
<ide> $Posts = $this->Case->generate(__NAMESPACE__ . '\PostsController');
<ide> $this->assertEquals('Posts', $Posts->name);
<del> $this->assertEquals('Post', $Posts->modelClass);
<add> $this->assertEquals('ControllerPost', $Posts->modelClass);
<ide> $this->assertNull($Posts->response->send());
<ide>
<del> $Posts = $this->Case->generate('Posts', array(
<add> $Posts = $this->Case->generate(__NAMESPACE__ . '\PostsController', array(
<ide> 'methods' => array(
<ide> 'render'
<ide> )
<ide> ));
<ide> $this->assertNull($Posts->render('index'));
<ide>
<del> $Posts = $this->Case->generate('Posts', array(
<add> $Posts = $this->Case->generate(__NAMESPACE__ . '\PostsController', array(
<ide> 'models' => array('Post'),
<ide> 'components' => array('RequestHandler')
<ide> ));
<ide>
<del> $this->assertInstanceOf('Post', $Posts->Post);
<add> $this->assertInstanceOf(__NAMESPACE__ . '\ControllerPost', $Posts->Post);
<ide> $this->assertNull($Posts->Post->save(array()));
<ide> $this->assertNull($Posts->Post->find('all'));
<ide> $this->assertEquals('posts', $Posts->Post->useTable);
<ide> $this->assertNull($Posts->RequestHandler->isAjax());
<ide>
<del> $Posts = $this->Case->generate('Posts', array(
<add> $Posts = $this->Case->generate(__NAMESPACE__ . '\PostsController', array(
<ide> 'models' => array(
<ide> 'Post' => true
<ide> )
<ide> public function testGenerateWithPlugin() {
<ide>
<ide> $result = ClassRegistry::init('TestPlugin.TestPluginComment');
<ide> $this->assertInstanceOf('TestPlugin\Model\TestPluginComment', $result);
<del>
<del> $Tests = $this->Case->generate(__NAMESPACE__ . '\ControllerTestCaseTestController', array(
<del> 'models' => array(
<del> 'TestPlugin.TestPluginComment' => array('save')
<del> )
<del> ));
<del> $this->assertInstanceOf('TestPlugin\Model\TestPluginComment', $Tests->TestPluginComment);
<del> $Tests->TestPluginComment->expects($this->at(0))
<del> ->method('save')
<del> ->will($this->returnValue(true));
<del> $Tests->TestPluginComment->expects($this->at(1))
<del> ->method('save')
<del> ->will($this->returnValue(false));
<del> $this->assertTrue($Tests->TestPluginComment->save(array()));
<del> $this->assertFalse($Tests->TestPluginComment->save(array()));
<ide> }
<ide>
<ide> /**
<ide> public function testTestActionPostData() {
<ide> $this->assertEquals($this->Case->controller->viewVars['data'], $data);
<ide> $this->assertEquals($this->Case->controller->data, $data);
<ide>
<del> $this->Case->testAction('/tests_apps_posts/post_var/named:param', array(
<del> 'data' => $data
<del> ));
<del> $expected = array(
<del> 'named' => 'param'
<del> );
<del> $this->assertEquals($expected, $this->Case->controller->request->named);
<del> $this->assertEquals($this->Case->controller->data, $data);
<del>
<ide> $result = $this->Case->testAction('/tests_apps_posts/post_var', array(
<ide> 'return' => 'vars',
<ide> 'method' => 'post',
<ide> public function testTestActionGetData() {
<ide> $this->assertEquals('var', $this->Case->controller->request->query['some']);
<ide> $this->assertEquals('creativity', $this->Case->controller->request->query['lackof']);
<ide>
<del> $result = $this->Case->testAction('/tests_apps_posts/url_var/var1:value1/var2:val2', array(
<del> 'return' => 'vars',
<del> 'method' => 'get',
<del> ));
<del> $this->assertEquals(array('var1', 'var2'), array_keys($result['params']['named']));
<del>
<ide> $result = $this->Case->testAction('/tests_apps_posts/url_var/gogo/val2', array(
<ide> 'return' => 'vars',
<ide> 'method' => 'get',
<ide><path>lib/Cake/TestSuite/ControllerTestCase.php
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\TestSuite;
<add>
<ide> use Cake\Core\App;
<ide> use Cake\Error;
<ide> use Cake\Event\Event;
<ide> public function __call($name, $arguments) {
<ide> *
<ide> * ### Options:
<ide> *
<del> * - `data` Will be used as the request data. If the `method` is GET,
<del> * data will be used a GET params. If the `method` is POST, it will be used
<del> * as POST data. By setting `$options['data']` to a string, you can simulate XML or JSON
<del> * payloads to your controllers allowing you to test REST webservices.
<add> * - `data` The data to use for POST or PUT requests. If `method` is GET
<add> * and `query` is empty, the data key will be used as GET parameters. By setting
<add> * `data to a string you can simulate XML or JSON payloads allowing you to test
<add> * REST webservices.
<add> * - `query` The query string parameters to set.
<add> * - `cookies` The cookie data to use for the request.
<ide> * - `method` POST or GET. Defaults to POST.
<ide> * - `return` Specify the return type you want. Choose from:
<ide> * - `vars` Get the set view variables.
<ide> protected function _testAction($url = '', $options = array()) {
<ide> $this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
<ide>
<ide> $options = array_merge(array(
<add> 'query' => array(),
<ide> 'data' => array(),
<add> 'cookies' => array(),
<ide> 'method' => 'POST',
<ide> 'return' => 'result'
<ide> ), $options);
<ide>
<del> $restore = array('get' => $_GET, 'post' => $_POST);
<add> $method = strtoupper($options['method']);
<add> $_SERVER['REQUEST_METHOD'] = $method;
<ide>
<del> $_SERVER['REQUEST_METHOD'] = strtoupper($options['method']);
<add> if ($method === 'GET' && is_array($options['data']) && empty($options['query'])) {
<add> $options['query'] = $options['data'];
<add> $options['data'] = array();
<add> }
<add> $requestData = array(
<add> 'url' => $url,
<add> 'cookies' => $options['cookies'],
<add> 'query' => $options['query'],
<add> );
<ide> if (is_array($options['data'])) {
<del> if (strtoupper($options['method']) == 'GET') {
<del> $_GET = $options['data'];
<del> $_POST = array();
<del> } else {
<del> $_POST = $options['data'];
<del> $_GET = array();
<del> }
<add> $requestData['post'] = $options['data'];
<ide> }
<del> $request = $this->getMock('Cake\Network\Request', array('_readInput'), array($url));
<add>
<add> $request = $this->getMock(
<add> 'Cake\Network\Request',
<add> array('_readInput'),
<add> array($requestData)
<add> );
<ide>
<ide> if (is_string($options['data'])) {
<ide> $request->expects($this->any())
<ide> protected function _testAction($url = '', $options = array()) {
<ide> }
<ide>
<ide> $Dispatch = new ControllerTestDispatcher();
<del> foreach (Router::$routes as $route) {
<del> if ($route instanceof RedirectRoute) {
<del> $route->response = $this->getMock('Cake\Network\Response', array('send'));
<del> }
<del> }
<ide> $Dispatch->loadRoutes = $this->loadRoutes;
<ide> $Dispatch->parseParams(new Event('ControllerTestCase', $Dispatch, array('request' => $request)));
<add>
<ide> if (!isset($request->params['controller'])) {
<del> $this->headers = Router::currentRoute()->response->header();
<add> // TODO fix this somehow.
<add> // $this->headers = Router::currentRoute()->response->header();
<ide> return;
<ide> }
<ide> if ($this->__dirtyController) {
<ide> protected function _testAction($url = '', $options = array()) {
<ide> $this->__dirtyController = true;
<ide> $this->headers = $Dispatch->response->header();
<ide>
<del> $_GET = $restore['get'];
<del> $_POST = $restore['post'];
<del>
<ide> return $this->{$options['return']};
<ide> }
<ide>
<ide> public function generate($controller, $mocks = array()) {
<ide> 'components' => array()
<ide> ), (array)$mocks);
<ide>
<del> $_controller = $this->getMock($classname, $mocks['methods'], array(), '', false);
<del> list(, $controllerName) = namespaceSplit($classname);
<del> $_controller->name = substr($controllerName, 0, -10);
<ide> $request = $this->getMock('Cake\Network\Request');
<ide> $response = $this->getMock('Cake\Network\Response', array('_sendHeader'));
<del> $_controller->__construct($request, $response);
<add> $controller = $this->getMock(
<add> $classname,
<add> $mocks['methods'],
<add> array($request, $response)
<add> );
<add> list(, $controllerName) = namespaceSplit($classname);
<add> $controller->name = substr($controllerName, 0, -10);
<ide>
<ide> $config = ClassRegistry::config('Model');
<ide> foreach ($mocks['models'] as $model => $methods) {
<ide> public function generate($controller, $mocks = array()) {
<ide> if ($methods === true) {
<ide> $methods = array();
<ide> }
<del> ;
<ide> $modelClass = get_class(ClassRegistry::init($model));
<ide> list(, $modelName) = namespaceSplit($modelClass);
<ide> $config = array_merge((array)$config, array('name' => $model));
<del> $_model = $this->getMock($modelClass, $methods, array($config));
<add> $model = $this->getMock($modelClass, $methods, array($config));
<ide> ClassRegistry::removeObject($modelName);
<del> ClassRegistry::addObject($modelName, $_model);
<add> ClassRegistry::addObject($modelName, $model);
<ide> }
<ide>
<ide> foreach ($mocks['components'] as $component => $methods) {
<ide> public function generate($controller, $mocks = array()) {
<ide> 'class' => $name . 'Component'
<ide> ));
<ide> }
<del> $_component = $this->getMock($componentClass, $methods, array(), '', false);
<del> $_controller->Components->set($name, $_component);
<add> $component = $this->getMock($componentClass, $methods, array(), '', false);
<add> $controller->Components->set($name, $component);
<ide> }
<ide>
<del> $_controller->constructClasses();
<add> $controller->constructClasses();
<ide> $this->__dirtyController = false;
<ide>
<del> $this->controller = $_controller;
<add> $this->controller = $controller;
<ide> return $this->controller;
<ide> }
<ide> | 2 |
PHP | PHP | escape urls to avoid xss | 0c88f6365f85e0659ff6cf571a3b709077fc11e9 | <ide><path>src/View/Helper/HtmlHelper.php
<ide> protected function _prepareCrumbs($startText, $escape = true)
<ide> * - `fullBase` If true the src attribute will get a full address for the image file.
<ide> * - `plugin` False value will prevent parsing path as a plugin
<ide> *
<del> * @param string $path Path to the image file, relative to the app/webroot/img/ directory.
<add> * @param string|array $path Path to the image file, relative to the app/webroot/img/ directory.
<ide> * @param array $options Array of HTML attributes. See above for special options.
<ide> * @return string completed img tag
<ide> * @link https://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-images
<ide><path>src/View/Helper/UrlHelper.php
<ide> public function assetUrl($path, array $options = [])
<ide> return $this->build($path, !empty($options['fullBase']));
<ide> }
<ide> if (strpos($path, '://') !== false || preg_match('/^[a-z]+:/i', $path)) {
<del> return $path;
<add> return ltrim($this->build($path), '/');
<ide> }
<ide> if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
<ide> list($plugin, $path) = $this->_View->pluginSplit($path, false);
<ide><path>src/View/StringTemplate.php
<ide> protected function _formatAttribute($key, $value, $escape = true)
<ide> }
<ide> $truthy = [1, '1', true, 'true', $key];
<ide> $isMinimized = isset($this->_compactAttributes[$key]);
<add> if (!preg_match('/\A(\w|[.-])+\z/', $key)) {
<add> $key = h($key);
<add> }
<ide> if ($isMinimized && in_array($value, $truthy, true)) {
<ide> return "$key=\"$key\"";
<ide> }
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testImageTag()
<ide> $result = $this->Html->image('cid:cakephp_logo');
<ide> $expected = ['img' => ['src' => 'cid:cakephp_logo', 'alt' => '']];
<ide> $this->assertHtml($expected, $result);
<add>
<add> $result = $this->Html->image('x:"><script>alert(1)</script>');
<add> $expected = ['img' => ['src' => 'x:"><script>alert(1)</script>', 'alt' => '']];
<add>
<add> $this->assertHtml($expected, $result);
<ide> }
<ide>
<ide> /**
<ide> public function testCssLink()
<ide> $expected['link']['href'] = 'css/screen.css?with=param&other=param';
<ide> $this->assertHtml($expected, $result);
<ide>
<add> $result = $this->Html->css('x:"><script>alert(1)</script>');
<add> $expected['link']['href'] = 'x:"><script>alert(1)</script>';
<add> $this->assertHtml($expected, $result);
<add>
<ide> $result = $this->Html->css('http://whatever.com/screen.css?1234');
<ide> $expected['link']['href'] = 'preg:/http:\/\/.*\/screen\.css\?1234/';
<ide> $this->assertHtml($expected, $result);
<ide> public function testScript()
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<add> $result = $this->Html->script('x:"><script>alert(1)</script>');
<add> $expected = [
<add> 'script' => ['src' => 'x:"><script>alert(1)</script>']
<add> ];
<add> $this->assertHtml($expected, $result);
<add>
<ide> $result = $this->Html->script('foo2', ['pathPrefix' => '/my/custom/path/']);
<ide> $expected = [
<ide> 'script' => ['src' => '/my/custom/path/foo2.js']
<ide> public function testMetaIcon()
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<add> $result = $this->Html->meta('icon', 'x:"><script>alert(1)</script>');
<add> $url = 'x:"><script>alert(1)</script>';
<add> $expected = [
<add> 'link' => [
<add> 'href' => $url,
<add> 'type' => 'image/x-icon',
<add> 'rel' => 'icon'
<add> ],
<add> [
<add> 'link' => [
<add> 'href' => $url,
<add> 'type' => 'image/x-icon',
<add> 'rel' => 'shortcut icon'
<add> ]
<add> ]
<add> ];
<add> $this->assertHtml($expected, $result);
<add>
<ide> $this->Html->request->webroot = '/testing/';
<ide> $result = $this->Html->meta('icon');
<ide> $expected = [
<ide> public function testDiv()
<ide> $result = $this->Html->div('class-name', '<text>', ['escape' => true]);
<ide> $expected = ['div' => ['class' => 'class-name'], '<text>', '/div'];
<ide> $this->assertHtml($expected, $result);
<add>
<add> $evilKey = "><script>alert(1)</script>";
<add> $options = [$evilKey => 'some value'];
<add> $result = $this->Html->div('class-name', '', $options);
<add> $expected = '<div ><script>alert(1)</script>="some value" class="class-name"></div>';
<add> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Helper/UrlHelperTest.php
<ide> public function testAssetUrl()
<ide> $result = $this->Helper->assetUrl('foo.jpg?one=two&three=four');
<ide> $this->assertEquals('foo.jpg?one=two&three=four', $result);
<ide>
<add> $result = $this->Helper->assetUrl('x:"><script>alert(1)</script>');
<add> $this->assertEquals('x:"><script>alert(1)</script>', $result);
<add>
<ide> $result = $this->Helper->assetUrl('dir/big+tall/image', ['ext' => '.jpg']);
<ide> $this->assertEquals('dir/big%2Btall/image.jpg', $result);
<ide> }
<ide><path>tests/TestCase/View/StringTemplateTest.php
<ide> public function testFormatAttributes()
<ide> ' data-hero="<batman>"',
<ide> $result
<ide> );
<add>
<add> $evilKey = "><script>alert(1)</script>";
<add> $attrs = [$evilKey => 'some value'];
<add>
<add> $result = $this->template->formatAttributes($attrs);
<add> $this->assertEquals(
<add> ' ><script>alert(1)</script>="some value"',
<add> $result
<add> );
<ide> }
<ide>
<ide> /** | 6 |
Javascript | Javascript | move events to the jsstreamsocket | 6abb7e594417ce8bf539fcfc896b3ab3b2c6b5d5 | <ide><path>lib/internal/http2/core.js
<ide> function connect(authority, options, listener) {
<ide> }
<ide> }
<ide>
<del> socket.on('error', socketOnError);
<del> socket.on('close', socketOnClose);
<del>
<ide> const session = new ClientHttp2Session(options, socket);
<ide>
<add> // ClientHttp2Session may create a new socket object
<add> // when socket is a JSSocket (socket != kSocket)
<add> // https://github.com/nodejs/node/issues/35695
<add> session[kSocket].on('error', socketOnError);
<add> session[kSocket].on('close', socketOnClose);
<add>
<ide> session[kAuthority] = `${options.servername || host}:${port}`;
<ide> session[kProtocol] = protocol;
<ide>
<ide><path>test/parallel/test-http2-client-jsstream-destroy.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>const h2 = require('http2');
<add>const tls = require('tls');
<add>const fixtures = require('../common/fixtures');
<add>const { Duplex } = require('stream');
<add>
<add>const server = h2.createSecureServer({
<add> key: fixtures.readKey('agent1-key.pem'),
<add> cert: fixtures.readKey('agent1-cert.pem')
<add>});
<add>
<add>class JSSocket extends Duplex {
<add> constructor(socket) {
<add> super({ emitClose: true });
<add> socket.on('close', () => this.destroy());
<add> socket.on('data', (data) => this.push(data));
<add> this.socket = socket;
<add> }
<add>
<add> _write(data, encoding, callback) {
<add> this.socket.write(data, encoding, callback);
<add> }
<add>
<add> _read(size) {
<add> }
<add>
<add> _final(cb) {
<add> cb();
<add> }
<add>}
<add>
<add>server.listen(0, common.mustCall(function() {
<add> const socket = tls.connect({
<add> rejectUnauthorized: false,
<add> host: 'localhost',
<add> port: this.address().port,
<add> ALPNProtocols: ['h2']
<add> }, () => {
<add> const proxy = new JSSocket(socket);
<add> const client = h2.connect(`https://localhost:${this.address().port}`, {
<add> createConnection: () => proxy
<add> });
<add> const req = client.request();
<add>
<add> setTimeout(() => socket.destroy(), 200);
<add> setTimeout(() => client.close(), 400);
<add> setTimeout(() => server.close(), 600);
<add>
<add> req.on('close', common.mustCall(() => { }));
<add> });
<add>})); | 2 |
Go | Go | add progress bar on docker push | 1fc9405537a1c528a59356ec36189a61db146701 | <ide><path>registry.go
<ide> func (graph *Graph) PushImage(stdout io.Writer, imgOrig *Image, authConfig *auth
<ide> // FIXME: Don't do this :D. Check the S3 requierement and implement chunks of 5MB
<ide> // FIXME2: I won't stress it enough, DON'T DO THIS! very high priority
<ide> layerData2, err := Tar(path.Join(graph.Root, img.Id, "layer"), Gzip)
<del> layerData, err := Tar(path.Join(graph.Root, img.Id, "layer"), Gzip)
<add> tmp, err := ioutil.ReadAll(layerData2)
<ide> if err != nil {
<del> return fmt.Errorf("Failed to generate layer archive: %s", err)
<add> return err
<ide> }
<del> req3, err := http.NewRequest("PUT", url.String(), layerData)
<add> layerLength := len(tmp)
<add>
<add> layerData, err := Tar(path.Join(graph.Root, img.Id, "layer"), Gzip)
<ide> if err != nil {
<del> return err
<add> return fmt.Errorf("Failed to generate layer archive: %s", err)
<ide> }
<del> tmp, err := ioutil.ReadAll(layerData2)
<add> req3, err := http.NewRequest("PUT", url.String(), ProgressReader(layerData.(io.ReadCloser), layerLength, stdout))
<ide> if err != nil {
<ide> return err
<ide> }
<del> req3.ContentLength = int64(len(tmp))
<add> req3.ContentLength = int64(layerLength)
<ide>
<ide> req3.TransferEncoding = []string{"none"}
<ide> res3, err := client.Do(req3) | 1 |
Python | Python | avoid comparison to none in tok2vec | 78301b2d29fe0c37fb05d98b3cf141cc3d6b060a | <ide><path>spacy/_ml.py
<ide> def drop_layer_fwd(X, drop=0.):
<ide>
<ide>
<ide> def Tok2Vec(width, embed_size, pretrained_dims=0):
<add> if pretrained_dims is None:
<add> pretrained_dims = 0
<ide> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE, ORTH]
<ide> with Model.define_operators({'>>': chain, '|': concatenate, '**': clone, '+': add}):
<ide> norm = HashEmbed(width, embed_size, column=cols.index(NORM), name='embed_norm') | 1 |
Mixed | Go | modify options for the command plugin install | d08886618eac804e879cc2953a3a07863e90e5e6 | <ide><path>api/client/plugin/install.go
<ide> func newInstallCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> }
<ide>
<ide> flags := cmd.Flags()
<del> flags.BoolVar(&options.grantPerms, "grant-all-permissions", false, "grant all permissions necessary to run the plugin")
<del> flags.BoolVar(&options.disable, "disable", false, "do not enable the plugin on install")
<add> flags.BoolVar(&options.grantPerms, "grant-all-permissions", false, "Grant all permissions necessary to run the plugin")
<add> flags.BoolVar(&options.disable, "disable", false, "Do not enable the plugin on install")
<ide>
<ide> return cmd
<ide> }
<ide><path>docs/reference/commandline/plugin_install.md
<ide> Usage: docker plugin install [OPTIONS] PLUGIN
<ide> Install a plugin
<ide>
<ide> Options:
<del> --disable do not enable the plugin on install
<del> --grant-all-permissions grant all permissions necessary to run the plugin
<add> --disable Do not enable the plugin on install
<add> --grant-all-permissions Grant all permissions necessary to run the plugin
<ide> --help Print usage
<ide> ```
<ide> | 2 |
Text | Text | remove link to sign in crypto.md | 00b200fc34193e9c7a40b803e28c76ef067d0b93 | <ide><path>doc/api/crypto.md
<ide> console.log(sign.sign(private_key, 'hex'));
<ide> // Prints the calculated signature
<ide> ```
<ide>
<del>A [`sign`][] instance can also be created by just passing in the digest
<add>A `Sign` instance can also be created by just passing in the digest
<ide> algorithm name, in which case OpenSSL will infer the full signature algorithm
<ide> from the type of the PEM-formatted private key, including algorithms that
<ide> do not have directly exposed name constants, e.g. 'ecdsa-with-SHA256'. | 1 |
Javascript | Javascript | introduce default config | c6c97cbd9d00c89aeb47677cb571205c830f025b | <ide><path>local-cli/cli.js
<ide> var bundle = require('../private-cli/src/bundle/bundle');
<ide> var childProcess = require('child_process');
<ide> var Config = require('../private-cli/src/util/Config');
<add>var defaultConfig = require('./default.config');
<ide> var fs = require('fs');
<ide> var generate = require('../private-cli/src/generate/generate');
<ide> var library = require('../private-cli/src/library/library');
<ide> function run() {
<ide> return;
<ide> }
<ide>
<del> command[0](args, Config.get(__dirname)).done();
<add> command[0](args, Config.get(__dirname, defaultConfig)).done();
<ide> }
<ide>
<ide> function generateWrapper(args, config) {
<ide><path>local-cli/default.config.js
<add>'use strict';
<add>
<add>var blacklist = require('../packager/blacklist');
<add>var path = require('path');
<add>
<add>/**
<add> * Default configuration for the CLI.
<add> *
<add> * If you need to override any of this functions do so by defining the file
<add> * `rn-cli.config.js` on the root of your project with the functions you need
<add> * to tweak.
<add> */
<add>var config = {
<add> getProjectRoots() {
<add> if (__dirname.match(/node_modules[\/\\]react-native[\/\\]local-cli$/)) {
<add> // packager is running from node_modules of another project
<add> return [path.resolve(__dirname, '../../..')];
<add> } else if (__dirname.match(/Pods[\/\\]React[\/\\]packager$/)) {
<add> // packager is running from node_modules of another project
<add> return [path.resolve(__dirname, '../../..')];
<add> } else {
<add> return [path.resolve(__dirname, '..')];
<add> }
<add> },
<add>
<add> /**
<add> * Specify where to look for assets that are referenced using
<add> * `image!<image_name>`. Asset directories for images referenced using
<add> * `./<image.extension>` don't require any entry in here.
<add> */
<add> getAssetRoots() {
<add> return [];
<add> },
<add>
<add> /**
<add> * Returns a regular expression for modules that should be ignored by the
<add> * packager on a given platform.
<add> */
<add> getBlacklistRE(platform) {
<add> return blacklist(platform);
<add> }
<add>};
<add>
<add>module.exports = config;
<ide><path>local-cli/generator/index.js
<ide> module.exports = yeoman.generators.NamedBase.extend({
<ide> { 'Libraries\/react-native\/react-native-interface.js' : 'node_modules/react-native/Libraries/react-native/react-native-interface.js' }
<ide> );
<ide>
<del> this.fs.copy(
<del> this.templatePath('rn-cli.config.js'),
<del> this.destinationPath('rn-cli.config.js')
<del> );
<ide> this.fs.copy(
<ide> this.templatePath('_gitignore'),
<ide> this.destinationPath('.gitignore')
<ide><path>local-cli/generator/templates/rn-cli.config.js
<del>'use strict';
<del>
<del>var blacklist = require('./node_modules/react-native/packager/blacklist');
<del>
<del>var config = {
<del> getProjectRoots() {
<del> return [__dirname];
<del> },
<del>
<del> getAssetRoots() {
<del> // speficy where to look for assets
<del> return [];
<del> },
<del>
<del> getBlacklistRE(platform) {
<del> return blacklist(platform);
<del> }
<del>};
<del>
<del>module.exports = config;
<ide><path>private-cli/src/util/Config.js
<ide> let cachedConfig = null;
<ide>
<ide> /**
<ide> * Module capable of getting the configuration that should be used for
<del> * the `rn-cli`. The configuration file is a JS file named `rn-cli.conf.js`.
<add> * the `rn-cli`. The configuration file is a JS file named `rn-cli.config.js`.
<ide> * It has to be on any parent directory of the cli.
<add> *
<add> * The function will return all the default configuration functions overriden
<add> * by those found on `rn-cli.config.js`, if any. If no default config is
<add> * provided and no configuration can be found in the directory hierarchy an
<add> * error will be thrown.
<ide> */
<ide> const Config = {
<del> get(pwd) {
<add> get(pwd, defaultConfig) {
<ide> if (cachedConfig) {
<ide> return cachedConfig;
<ide> }
<ide>
<ide> const parentDir = findParentDirectory(pwd, RN_CLI_CONFIG);
<del>
<del> if (!parentDir) {
<add> if (!parentDir && !defaultConfig) {
<ide> throw new Error(
<ide> 'Can\'t find "rn-cli.config.js" file in any parent folder of "' +
<ide> __dirname + '"'
<ide> );
<ide> }
<ide>
<del> cachedConfig = require(path.join(parentDir, RN_CLI_CONFIG));
<add> const config = parentDir
<add> ? require(path.join(parentDir, RN_CLI_CONFIG))
<add> : {};
<add>
<add> cachedConfig = Object.assign({}, defaultConfig, config);
<ide> return cachedConfig;
<ide> }
<ide> }; | 5 |
Ruby | Ruby | use sub instead of gsub | d27dd860c7f4f9b9e5aebe7d0c6e9b6108d8717c | <ide><path>actionpack/lib/action_view/renderable_partial.rb
<ide> module RenderablePartial
<ide> # So you can not set or modify any instance variables
<ide>
<ide> def variable_name
<del> @variable_name ||= name.gsub(/^_/, '').to_sym
<add> @variable_name ||= name.sub(/\A_/, '').to_sym
<ide> end
<ide>
<ide> def counter_name | 1 |
Python | Python | add check on connect | fd29d2157d031cda430005456669763c4014f8b4 | <ide><path>libcloud/container/drivers/docker.py
<ide> import shlex
<ide> import re
<ide> import os
<add>import socket
<ide>
<ide> try:
<ide> import simplejson as json
<ide> def __init__(self, key='', secret='', secure=False, host='localhost',
<ide> if host.startswith(prefix):
<ide> host = host.strip(prefix)
<ide>
<add> try:
<add> socket.setdefaulttimeout(15)
<add> so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
<add> so.connect((host, int(port)))
<add> so.close()
<add> except:
<add> raise Exception("Make sure host is accessible "
<add> "and docker port is specified")
<add>
<ide> super(DockerContainerDriver, self).__init__(key=key,
<ide> secret=secret,
<ide> secure=secure, host=host,
<ide> def __init__(self, key='', secret='', secure=False, host='localhost',
<ide> self.connection.host = host
<ide> self.connection.port = port
<ide>
<add>
<ide> # set API version
<ide> self.version = self._get_api_version()
<ide>
<ide> def ts_to_str(timestamp):
<ide>
<ide>
<ide> def is_private(hostname):
<del> import socket
<ide> from libcloud.utils.networking import is_private_subnet, is_public_subnet
<ide> hostname = socket.gethostbyname(hostname)
<ide> if is_private_subnet(hostname): | 1 |
PHP | PHP | update doc blocks based on feedback | 4d9e65ea1651de2004e117def5261eb0cc9021e4 | <ide><path>src/Routing/ScopedRouteCollection.php
<ide> public function params() {
<ide> }
<ide>
<ide> /**
<del> * Get the explicity named routes in the collectio.
<add> * Get the explicity named routes in the collection.
<ide> *
<ide> * @return array An array of named routes indexed by their name.
<ide> */
<ide> public function named() {
<ide> /**
<ide> * Get all the routes in this collection.
<ide> *
<del> * @return array
<ide> * @return array An array of routes.
<ide> */
<ide> public function routes() {
<ide> public function get($name) {
<ide> * Connect resource routes for an app controller:
<ide> *
<ide> * {{{
<del> * Router::mapResources('Posts');
<add> * $routes->resources('Posts');
<ide> * }}}
<ide> *
<del> * Connect resource routes for the Comment controller in the
<add> * Connect resource routes for the Comments controller in the
<ide> * Comments plugin:
<ide> *
<ide> * {{{
<del> * Router::mapResources('Comments.Comment');
<add> * Router::plugin('Comments', function ($routes) {
<add> * $routes->resource('Comments');
<add> * });
<ide> * }}}
<ide> *
<ide> * Plugins will create lower_case underscored resource routes. e.g
<del> * `/comments/comment`
<add> * `/comments/comments`
<ide> *
<del> * Connect resource routes for the Posts controller in the
<add> * Connect resource routes for the Articles controller in the
<ide> * Admin prefix:
<ide> *
<ide> * {{{
<del> * Router::mapResources('Posts', ['prefix' => 'admin']);
<add> * Router::prefix('admin', function ($routes) {
<add> * $routes->resource('Articles');
<add> * });
<ide> * }}}
<ide> *
<ide> * Prefixes will create lower_case underscored resource routes. e.g
<ide> * `/admin/posts`
<ide> *
<add> * You can create nested resources by passing a callback in:
<add> *
<add> * {{{
<add> * $routes->resource('Articles', function($routes) {
<add> * $routes->resource('Comments');
<add> * });
<add> * }}}
<add> *
<add> * The above would generate both resource routes for `/articles`, and `/articles/:article_id/comments`.
<add> *
<ide> * ### Options:
<ide> *
<ide> * - 'id' - The regular expression fragment to use when matching IDs. By default, matches
<ide> * integer values and UUIDs.
<del> * - 'prefix' - Routing prefix to use for the generated routes. Defaults to ''.
<del> * Using this option will create prefixed routes, similar to using Routing.prefixes.
<ide> *
<ide> * @param string|array $controller A controller name or array of controller names (i.e. "Posts" or "ListItems")
<ide> * @param array $options Options to use when generating REST routes
<ide> public function resource($name, $options = [], $callback = null) {
<ide> '[method]' => $params['method'],
<ide> '_ext' => $ext
<ide> );
<del> $routeOptions = array_merge(array(
<add> $routeOptions = $connectOptions + [
<ide> 'id' => $options['id'],
<del> 'pass' => array('id')
<del> ), $connectOptions);
<add> 'pass' => ['id']
<add> ];
<ide> $this->connect($url, $params, $routeOptions);
<ide> }
<ide>
<ide> public function resource($name, $options = [], $callback = null) {
<ide> * it will match requests like `/posts/index` as well as requests
<ide> * like `/posts/edit/1/foo/bar`.
<ide> *
<del> * `$routes->connect('/home-page', ['controller' => 'pages', 'action' => 'display', 'home']);`
<add> * `$routes->connect('/home-page', ['controller' => 'Pages', 'action' => 'display', 'home']);`
<ide> *
<ide> * The above shows the use of route parameter defaults. And providing routing
<ide> * parameters for a static route.
<ide> public function resource($name, $options = [], $callback = null) {
<ide> * reverse routing lookups. If undefined a name will be generated for each
<ide> * connected route.
<ide> * - `_ext` is an array of filename extensions that will be parsed out of the url if present.
<del> * See {@link Route::parseExtensions()}.
<add> * See {@link ScopedRouteCollection::extensions()}.
<ide> *
<ide> * You can also add additional conditions for matching routes to the $defaults array.
<ide> * The following conditions can be used:
<ide> public function resource($name, $options = [], $callback = null) {
<ide> *
<ide> * Example of using the `[method]` condition:
<ide> *
<del> * `$routes->connect('/tasks', array('controller' => 'tasks', 'action' => 'index', '[method]' => 'GET'));`
<add> * `$routes->connect('/tasks', array('controller' => 'Tasks', 'action' => 'index', '[method]' => 'GET'));`
<ide> *
<ide> * The above route will only be matched for GET requests. POST requests will fail to match this route.
<ide> *
<ide> public function resource($name, $options = [], $callback = null) {
<ide> * element should match. Also contains additional parameters such as which routed parameters should be
<ide> * shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a
<ide> * custom routing class.
<del> * @see routes
<ide> * @return void
<ide> * @throws \Cake\Error\Exception
<ide> */
<ide> public function connect($route, array $defaults = [], $options = []) {
<ide> }
<ide>
<ide> /**
<del> * Validates that the passed route class exists and is a subclass of Cake Route
<add> * Validates that the passed route class exists and is a subclass of Cake\Routing\Route\Route
<ide> *
<ide> * @param string $routeClass Route class name
<ide> * @return string
<ide> * @throws \Cake\Error\Exception
<ide> */
<ide> protected function _validateRouteClass($routeClass) {
<ide> if (
<del> $routeClass != 'Cake\Routing\Route\Route' &&
<add> $routeClass !== 'Cake\Routing\Route\Route' &&
<ide> (!class_exists($routeClass) || !is_subclass_of($routeClass, 'Cake\Routing\Route\Route'))
<ide> ) {
<ide> throw new Error\Exception('Route class not found, or route class is not a subclass of Cake\Routing\Route\Route');
<ide> protected function _validateRouteClass($routeClass) {
<ide> * @param array $options An array matching the named elements in the route to regular expressions which that
<ide> * element should match. Also contains additional parameters such as which routed parameters should be
<ide> * shifted into the passed arguments. As well as supplying patterns for routing parameters.
<del> * @see routes
<ide> * @return array Array of routes
<ide> */
<ide> public function redirect($route, $url, $options = []) { | 1 |
Python | Python | add warning if initial vectors are empty | 7944761ba7335048b6d81784cfdcedecf87b3cac | <ide><path>spacy/errors.py
<ide> class Warnings:
<ide> "`spacy.load()` to ensure that the model is loaded on the correct "
<ide> "device. More information: "
<ide> "http://spacy.io/usage/v3#jupyter-notebook-gpu")
<add> W112 = ("The model specified to use for initial vectors ({name}) has no "
<add> "vectors. This is almost certainly a mistake.")
<ide>
<ide>
<ide> @add_codes
<ide><path>spacy/training/initialize.py
<ide> def load_vectors_into_model(
<ide> )
<ide> err = ConfigValidationError.from_error(e, title=title, desc=desc)
<ide> raise err from None
<add>
<add> if len(vectors_nlp.vocab.vectors.keys()) == 0:
<add> logger.warning(Warnings.W112.format(name=name))
<add>
<ide> nlp.vocab.vectors = vectors_nlp.vocab.vectors
<ide> if add_strings:
<ide> # I guess we should add the strings from the vectors_nlp model? | 2 |
Ruby | Ruby | use database agnostic function/quoting in test | 4a5b3ca972e867d9b9276dcd98b0a6b9b6fb7583 | <ide><path>activerecord/test/cases/unsafe_raw_sql_test.rb
<ide> class UnsafeRawSqlTest < ActiveRecord::TestCase
<ide> end
<ide>
<ide> test "order: allows Arel.sql with binds" do
<del> ids_expected = Post.order(Arel.sql('INSTR(title, "comments"), id')).pluck(:id)
<add> ids_expected = Post.order(Arel.sql("REPLACE(title, 'misc', 'zzzz'), id")).pluck(:id)
<ide>
<del> ids_depr = with_unsafe_raw_sql_deprecated { Post.order([Arel.sql("INSTR(title, ?), id"), "comments"]).pluck(:id) }
<del> ids_disabled = with_unsafe_raw_sql_disabled { Post.order([Arel.sql("INSTR(title, ?), id"), "comments"]).pluck(:id) }
<add> ids_depr = with_unsafe_raw_sql_deprecated { Post.order([Arel.sql("REPLACE(title, ?, ?), id"), "misc", "zzzz"]).pluck(:id) }
<add> ids_disabled = with_unsafe_raw_sql_disabled { Post.order([Arel.sql("REPLACE(title, ?, ?), id"), "misc", "zzzz"]).pluck(:id) }
<ide>
<ide> assert_equal ids_expected, ids_depr
<ide> assert_equal ids_expected, ids_disabled
<ide> class UnsafeRawSqlTest < ActiveRecord::TestCase
<ide> test "order: disallows invalid bind statement" do
<ide> with_unsafe_raw_sql_disabled do
<ide> assert_raises(ActiveRecord::UnknownAttributeReference) do
<del> Post.order(["INSTR(title, ?), id", "comments"]).pluck(:id)
<add> Post.order(["REPLACE(title, ?, ?), id", "misc", "zzzz"]).pluck(:id)
<ide> end
<ide> end
<ide> end | 1 |
Ruby | Ruby | destroy rich text dependents | a79fa9d2233be0ac968dbec6c00e8eca5b1d0117 | <ide><path>lib/action_text/attribute.rb
<ide> def #{name}=(body)
<ide> end
<ide> CODE
<ide>
<del> has_one :"rich_text_#{name}", -> { where(name: name) }, class_name: "ActionText::RichText", as: :record, inverse_of: :record, dependent: false
<add> has_one :"rich_text_#{name}", -> { where(name: name) }, class_name: "ActionText::RichText", as: :record, inverse_of: :record, dependent: :destroy
<ide>
<ide> scope :"with_rich_text_#{name}", -> { includes("rich_text_#{name}") }
<ide> | 1 |
Text | Text | add intermediate solution to guide | ae5e2398aa1444124d0d29c898952dbf4c5b0579 | <ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number/index.md
<ide> Got it?  Code Solution:
<add>##  Basic Code Solution:
<ide>
<ide> function factorialize(num) {
<ide> if (num === 0) { return 1; }
<ide> Notice at the first line we have the terminal condition, i.e a condition to chec
<ide> * <a href='https://en.wikipedia.org/wiki/Factorial' target='_blank' rel='nofollow'>Factorialization</a>
<ide> * <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators' target='_blank' rel='nofollow'>Arithmetic Operators</a>
<ide>
<add>##  Intermediate Code Solution:
<add>
<add> function factorialize(num, factorial = 1) {
<add> if (num == 0) {
<add> return factorial;
<add> } else {
<add> return factorialize(num - 1, factorial * num);
<add> }
<add> }
<add>
<add> factorialize(5);
<add>
<add> <a href='https://repl.it/repls/CrimsonVerifiableDownload' target='_blank' rel='nofollow'>Run Code</a>
<add>
<add>## Code Explanation:
<add>
<add>In this solution, we use <a href='https://stackoverflow.com/questions/33923/what-is-tail-recursion' target='_blank' rel='nofollow'>Tail Recursion</a> to optimize the the memory use.
<add>
<add>In traditional head recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don't get the result of your calculation until you have returned from every recursive call.
<add>
<add>In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params)).
<add>
<add>In this solution, with each evaluation of the recursive call, the factorial is updated. This is different from the head-recursive solution where all evaluation calculations are stored on the stack until the base case is reached.
<add>
<add>### Relevant Links
<add>
<add>* <a href='https://www.geeksforgeeks.org/tail-recursion/' target='_blank' rel='nofollow'>Tail Recursion</a>
<add>
<ide> ##  NOTES FOR CONTRIBUTIONS:
<ide>
<ide> *  **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution. | 1 |
Text | Text | add javascript context to docs | 893ec223654f1eddedf42f2092de6cfcfd633e6c | <ide><path>guide/english/typescript/index.md
<ide> title: TypeScript
<ide>
<ide> So as you are most likely aware, JavaScript is expanding its footprint everyday and it is both overwhelming and amazing what you can do with the language nowadays.
<ide>
<del>However, as more large-scale projects start to use JavaScript, the process of making the code easier to write and more maintainable becomes more and more difficult.
<add>However, as more large-scale projects start to use JavaScript, the process of making the code easier to write and more maintainable becomes more and more difficult. One reason for this is that, unlike some other programming languages, JavaScript is not a strongly-typed language. This means there can be confusion, especially in large code bases, about when different types (numbers, strings, booleans, arrays, etc) should be used and sometimes the problems only surface in production.
<ide>
<ide> This is a problem Microsoft recognized early on and they came up with the solution of TypeScript and released the first version approximately on October 1st, 2012.
<ide> | 1 |
Text | Text | fix typos in `test.md` | f0639eb8bad739b27b7cdefef4fac8e48c889f16 | <ide><path>doc/api/test.md
<ide> changes:
<ide> * `only` {boolean} If truthy, and the test context is configured to run
<ide> `only` tests, then this test will be run. Otherwise, the test is skipped.
<ide> **Default:** `false`.
<del> * `signal` {AbortSignal} Allows aborting an in-progress test
<add> * `signal` {AbortSignal} Allows aborting an in-progress test.
<ide> * `skip` {boolean|string} If truthy, the test is skipped. If a string is
<ide> provided, that string is displayed in the test results as the reason for
<ide> skipping the test. **Default:** `false`.
<ide> test('top level test', (t) => {
<ide> added: REPLACEME
<ide> -->
<ide>
<del>* <AbortSignal> Can be used to abort test subtasks when the test has been aborted.
<add>* {AbortSignal} Can be used to abort test subtasks when the test has been
<add> aborted.
<ide>
<ide> ```js
<ide> test('top level test', async (t) => {
<ide> changes:
<ide> * `only` {boolean} If truthy, and the test context is configured to run
<ide> `only` tests, then this test will be run. Otherwise, the test is skipped.
<ide> **Default:** `false`.
<del> * `signal` {AbortSignal} Allows aborting an in-progress test
<add> * `signal` {AbortSignal} Allows aborting an in-progress test.
<ide> * `skip` {boolean|string} If truthy, the test is skipped. If a string is
<ide> provided, that string is displayed in the test results as the reason for
<ide> skipping the test. **Default:** `false`.
<ide> exposed as part of the API.
<ide> added: REPLACEME
<ide> -->
<ide>
<del>* <AbortSignal> Can be used to abort test subtasks when the test has been aborted.
<add>* {AbortSignal} Can be used to abort test subtasks when the test has been
<add> aborted.
<ide>
<ide> [TAP]: https://testanything.org/
<ide> [`--test-only`]: cli.md#--test-only | 1 |
PHP | PHP | add authenticatesession middleware | fc302a6667f9dcce53395d01d8e6ba752ea62955 | <ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> class Kernel implements KernelContract
<ide> \Illuminate\Session\Middleware\StartSession::class,
<ide> \Illuminate\View\Middleware\ShareErrorsFromSession::class,
<ide> \Illuminate\Auth\Middleware\Authenticate::class,
<add> \Illuminate\Session\Middleware\AuthenticateSession::class,
<ide> \Illuminate\Routing\Middleware\SubstituteBindings::class,
<ide> \Illuminate\Auth\Middleware\Authorize::class,
<ide> ];
<ide><path>src/Illuminate/Session/Middleware/AuthenticateSession.php
<add><?php
<add>
<add>namespace Illuminate\Session\Middleware;
<add>
<add>use Closure;
<add>use Illuminate\Auth\AuthenticationException;
<add>use Illuminate\Contracts\Auth\Factory as AuthFactory;
<add>
<add>class AuthenticateSession
<add>{
<add> /**
<add> * The authentication factory implementation.
<add> *
<add> * @var \Illuminate\Contracts\Auth\Factory
<add> */
<add> protected $auth;
<add>
<add> /**
<add> * Create a new middleware instance.
<add> *
<add> * @param \Illuminate\Contracts\Auth\Factory $auth
<add> * @return void
<add> */
<add> public function __construct(AuthFactory $auth)
<add> {
<add> $this->auth = $auth;
<add> }
<add>
<add> /**
<add> * Handle an incoming request.
<add> *
<add> * @param \Illuminate\Http\Request $request
<add> * @param \Closure $next
<add> * @return mixed
<add> */
<add> public function handle($request, Closure $next)
<add> {
<add> if (! $request->user() || ! $request->session()) {
<add> return $next($request);
<add> }
<add>
<add> if (! $request->session()->has('password_hash') && $this->auth->viaRemember()) {
<add> $this->logout($request);
<add> }
<add>
<add> if (! $request->session()->has('password_hash')) {
<add> $this->storePasswordHashInSession($request);
<add> }
<add>
<add> if ($request->session()->get('password_hash') !== $request->user()->password) {
<add> $this->logout($request);
<add> }
<add>
<add> return tap($next($request), function () use ($request) {
<add> $this->storePasswordHashInSession($request);
<add> });
<add> }
<add>
<add> /**
<add> * Store the user's current password hash in the session.
<add> *
<add> * @param \Illuminate\Http\Request $request
<add> * @return void
<add> */
<add> protected function storePasswordHashInSession($request)
<add> {
<add> $request->session()->put([
<add> 'password_hash' => $request->user()->password,
<add> ]);
<add> }
<add>
<add> /**
<add> * Log the user out of the application.
<add> *
<add> * @param \Illuminate\Http\Request $request
<add> * @return void
<add> *
<add> * @throws \Illuminate\Auth\AuthenticationException
<add> */
<add> protected function logout($request)
<add> {
<add> $this->auth->logout();
<add>
<add> $request->session()->flush();
<add>
<add> throw new AuthenticationException;
<add> }
<add>} | 2 |
Python | Python | add support for runtime selected ufunc simd loops | 0a2276a66f7bfbce4c3cf6aa1f0f820a24342bf5 | <ide><path>numpy/core/code_generators/generate_umath.py
<ide> class TypeDescription(object):
<ide> astype : dict or None, optional
<ide> If astype['x'] is 'y', uses PyUFunc_x_x_As_y_y/PyUFunc_xx_x_As_yy_y
<ide> instead of PyUFunc_x_x/PyUFunc_xx_x.
<add> simd: list
<add> Available SIMD ufunc loops, dispatched at runtime in specified order
<add> Currently only supported for simples types (see make_arrays)
<ide> """
<del> def __init__(self, type, f=None, in_=None, out=None, astype=None):
<add> def __init__(self, type, f=None, in_=None, out=None, astype=None, simd=None):
<ide> self.type = type
<ide> self.func_data = f
<ide> if astype is None:
<ide> def __init__(self, type, f=None, in_=None, out=None, astype=None):
<ide> if out is not None:
<ide> out = out.replace('P', type)
<ide> self.out = out
<add> self.simd = simd
<ide>
<ide> def finish_signature(self, nin, nout):
<ide> if self.in_ is None:
<ide> def build_func_data(types, f):
<ide> func_data.append(d)
<ide> return func_data
<ide>
<del>def TD(types, f=None, astype=None, in_=None, out=None):
<add>def TD(types, f=None, astype=None, in_=None, out=None, simd=None):
<ide> if f is not None:
<ide> if isinstance(f, str):
<ide> func_data = build_func_data(types, f)
<ide> def TD(types, f=None, astype=None, in_=None, out=None):
<ide> out = (None,) * len(types)
<ide> tds = []
<ide> for t, fd, i, o in zip(types, func_data, in_, out):
<del> tds.append(TypeDescription(t, f=fd, in_=i, out=o, astype=astype))
<add> # [(simd-name, list of types)]
<add> if simd is not None:
<add> simdt = [k for k, v in simd if t in v]
<add> else:
<add> simdt = []
<add> tds.append(TypeDescription(t, f=fd, in_=i, out=o, astype=astype, simd=simdt))
<ide> return tds
<ide>
<ide> class Ufunc(object):
<ide> def make_arrays(funcdict):
<ide> datalist.append('(void *)NULL')
<ide> tname = english_upper(chartoname[t.type])
<ide> funclist.append('%s_%s' % (tname, name))
<add> if t.simd is not None:
<add> for vt in t.simd:
<add> code2list.append("""\
<add>#ifdef HAVE_ATTRIBUTE_TARGET_{ISA}
<add>if (NPY_CPU_SUPPORTS_{ISA}) {{
<add> {fname}_functions[{idx}] = {type}_{fname}_{isa};
<add>}}
<add>#endif
<add>""".format(ISA=vt.upper(), isa=vt, fname=name, type=tname, idx=k))
<ide>
<ide> for x in t.in_ + t.out:
<ide> siglist.append('NPY_%s' % (english_upper(chartoname[x]),)) | 1 |
PHP | PHP | add more test on view | 73e7b702b19c0039cda702c6f17b4ef9a767e29f | <ide><path>tests/View/ViewFlowTest.php
<ide>
<ide> use Mockery as m;
<ide> use Illuminate\View\Factory;
<add>use Illuminate\Filesystem\Filesystem;
<add>use Illuminate\View\Engines\CompilerEngine;
<ide> use Illuminate\View\Compilers\BladeCompiler;
<ide>
<ide> class ViewFlowTest extends PHPUnit_Framework_TestCase
<ide> {
<add> public function setUp()
<add> {
<add> parent::setUp();
<add>
<add> $files = new Filesystem;
<add> $this->tempDir = __DIR__.'/tmp';
<add>
<add> if (!$files->exists($this->tempDir)) {
<add> $files->makeDirectory($this->tempDir);
<add> }
<add> }
<add>
<ide> public function tearDown()
<ide> {
<add> $files = new Filesystem;
<add> $files->deleteDirectory($this->tempDir);
<add>
<ide> m::close();
<ide> }
<ide>
<ide> public function testPushWithExtend()
<ide> {
<del> $files = new Illuminate\Filesystem\Filesystem;
<del>
<add> $files = new Filesystem;
<ide> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<ide>
<del> $files->put(__DIR__.'/fixtures/child.php', $compiler->compileString('
<add> $files->put($this->tempDir.'/child.php', $compiler->compileString('
<ide> @extends("layout")
<ide>
<ide> @push("content")
<ide> World
<ide> @endpush'));
<del> $files->put(__DIR__.'/fixtures/layout.php', $compiler->compileString('
<add> $files->put($this->tempDir.'/layout.php', $compiler->compileString('
<ide> @push("content")
<ide> Hello
<ide> @endpush
<ide> @stack("content")'));
<ide>
<del> $engine = new Illuminate\View\Engines\CompilerEngine(m::mock('Illuminate\View\Compilers\CompilerInterface'));
<del> $engine->getCompiler()->shouldReceive('getCompiledPath')->andReturnUsing(function ($path) { return $path; });
<del> $engine->getCompiler()->shouldReceive('isExpired')->times(2)->andReturn(false);
<del>
<del> $factory = $this->getFactory();
<del> $factory->getEngineResolver()->shouldReceive('resolve')->times(2)->andReturn($engine);
<del> $factory->getFinder()->shouldReceive('find')->once()->with('child')->andReturn(__DIR__.'/fixtures/child.php');
<del> $factory->getFinder()->shouldReceive('find')->once()->with('layout')->andReturn(__DIR__.'/fixtures/layout.php');
<del> $factory->getDispatcher()->shouldReceive('fire')->times(4);
<del>
<add> $factory = $this->prepareCommonFactory();
<ide> $this->assertEquals("Hello\nWorld\n", $factory->make('child')->render());
<del>
<del> $files->delete(__DIR__.'/fixtures/layout.php');
<del> $files->delete(__DIR__.'/fixtures/child.php');
<ide> }
<ide>
<ide> public function testPushWithMultipleExtends()
<ide> {
<del> $files = new Illuminate\Filesystem\Filesystem;
<del>
<add> $files = new Filesystem;
<ide> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<ide>
<del> $files->put(__DIR__.'/fixtures/a.php', $compiler->compileString('
<add> $files->put($this->tempDir.'/a.php', $compiler->compileString('
<ide> a
<ide> @stack("me")'));
<ide>
<del> $files->put(__DIR__.'/fixtures/b.php', $compiler->compileString('
<add> $files->put($this->tempDir.'/b.php', $compiler->compileString('
<ide> @extends("a")
<ide> @push("me")
<ide> b
<del>@endpush("me")'));
<add>@endpush'));
<ide>
<del> $files->put(__DIR__.'/fixtures/c.php', $compiler->compileString('
<add> $files->put($this->tempDir.'/c.php', $compiler->compileString('
<ide> @extends("b")
<ide> @push("me")
<ide> c
<del>@endpush("me")'));
<del>
<del> $engine = new Illuminate\View\Engines\CompilerEngine(m::mock('Illuminate\View\Compilers\CompilerInterface'));
<del> $engine->getCompiler()->shouldReceive('getCompiledPath')->andReturnUsing(function ($path) { return $path; });
<del> $engine->getCompiler()->shouldReceive('isExpired')->andReturn(false);
<del>
<del> $factory = $this->getFactory();
<del> $factory->getEngineResolver()->shouldReceive('resolve')->andReturn($engine);
<del> $factory->getFinder()->shouldReceive('find')->andReturnUsing(function ($path) {
<del> return __DIR__.'/fixtures/'.$path.'.php';
<del> });
<del> $factory->getDispatcher()->shouldReceive('fire');
<add>@endpush'));
<ide>
<add> $factory = $this->prepareCommonFactory();
<ide> $this->assertEquals("a\nb\nc\n", $factory->make('c')->render());
<del>
<del> $files->delete(__DIR__.'/fixtures/a.php');
<del> $files->delete(__DIR__.'/fixtures/b.php');
<del> $files->delete(__DIR__.'/fixtures/c.php');
<ide> }
<ide>
<ide> public function testPushWithInputAndExtend()
<ide> {
<del> $files = new Illuminate\Filesystem\Filesystem;
<del>
<add> $files = new Filesystem;
<ide> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<ide>
<del> $files->put(__DIR__.'/fixtures/aa.php', $compiler->compileString('
<add> $files->put($this->tempDir.'/aa.php', $compiler->compileString('
<ide> a
<ide> @stack("me")'));
<ide>
<del> $files->put(__DIR__.'/fixtures/bb.php', $compiler->compileString('
<add> $files->put($this->tempDir.'/bb.php', $compiler->compileString('
<ide> @push("me")
<ide> b
<del>@endpush("me")'));
<add>@endpush'));
<ide>
<del> $files->put(__DIR__.'/fixtures/cc.php', $compiler->compileString('
<add> $files->put($this->tempDir.'/cc.php', $compiler->compileString('
<ide> @extends("aa")
<ide> @include("bb")
<ide> @push("me")
<ide> c
<del>@endpush("me")'));
<add>@endpush'));
<add>
<add> $factory = $this->prepareCommonFactory();
<add> $this->assertEquals("a\nc\nb\n", $factory->make('cc')->render());
<add> }
<add>
<add> public function testExtends()
<add> {
<add> $files = new Filesystem;
<add> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<add>
<add> $files->put($this->tempDir.'/extends-a.php', $compiler->compileString('
<add>yield:
<add>@yield("me")'));
<add>
<add> $files->put($this->tempDir.'/extends-b.php', $compiler->compileString('
<add>@extends("extends-a")
<add>@section("me")
<add>b
<add>@endsection'));
<add>
<add> $files->put($this->tempDir.'/extends-c.php', $compiler->compileString('
<add>@extends("extends-b")
<add>@section("me")
<add>c
<add>@endsection'));
<add>
<add> $factory = $this->prepareCommonFactory();
<add> $this->assertEquals("yield:\nb\n", $factory->make('extends-b')->render());
<add> $this->assertEquals("yield:\nc\n", $factory->make('extends-c')->render());
<add> }
<ide>
<del> $engine = new Illuminate\View\Engines\CompilerEngine(m::mock('Illuminate\View\Compilers\CompilerInterface'));
<del> $engine->getCompiler()->shouldReceive('getCompiledPath')->andReturnUsing(function ($path) { return $path; });
<add> public function testExtendsWithParent()
<add> {
<add> $files = new Filesystem;
<add> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<add>
<add> $files->put($this->tempDir.'/extends-layout.php', $compiler->compileString('
<add>yield:
<add>@yield("me")'));
<add>
<add> $files->put($this->tempDir.'/extends-dad.php', $compiler->compileString('
<add>@extends("extends-layout")
<add>@section("me")
<add>dad
<add>@endsection'));
<add>
<add> $files->put($this->tempDir.'/extends-child.php', $compiler->compileString('
<add>@extends("extends-dad")
<add>@section("me")
<add>@parent
<add>child
<add>@endsection'));
<add>
<add> $factory = $this->prepareCommonFactory();
<add> $this->assertEquals("yield:\ndad\n\nchild\n", $factory->make('extends-child')->render());
<add> }
<add>
<add> public function testExtendsWithVariable()
<add> {
<add> $files = new Filesystem;
<add> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<add>
<add> $files->put($this->tempDir.'/extends-variable-layout.php', $compiler->compileString('
<add>yield:
<add>@yield("me")'));
<add>
<add> $files->put($this->tempDir.'/extends-variable-dad.php', $compiler->compileString('
<add>@extends("extends-variable-layout")
<add>@section("me")
<add>dad
<add>@endsection'));
<add>
<add> $files->put($this->tempDir.'/extends-variable-child-a.php', $compiler->compileString('
<add>@extends("extends-variable-dad")
<add>@section("me")
<add>{{ $title }}
<add>@endsection'));
<add>
<add> $files->put($this->tempDir.'/extends-variable-child-b.php', $compiler->compileString('
<add>@extends("extends-variable-dad")
<add>@section("me")
<add>{{ $title }}
<add>@endsection'));
<add>
<add> $factory = $this->prepareCommonFactory();
<add> $this->assertEquals("yield:\ntitle\n", $factory->make('extends-variable-child-a', ['title' => 'title'])->render());
<add> $this->assertEquals("yield:\ndad\n\n", $factory->make('extends-variable-child-b', ['title' => '@parent'])->render());
<add> }
<add>
<add> protected function prepareCommonFactory()
<add> {
<add> $engine = new CompilerEngine(m::mock('Illuminate\View\Compilers\CompilerInterface'));
<add> $engine->getCompiler()->shouldReceive('getCompiledPath')
<add> ->andReturnUsing(function ($path) { return $path; });
<ide> $engine->getCompiler()->shouldReceive('isExpired')->andReturn(false);
<ide>
<ide> $factory = $this->getFactory();
<ide> $factory->getEngineResolver()->shouldReceive('resolve')->andReturn($engine);
<ide> $factory->getFinder()->shouldReceive('find')->andReturnUsing(function ($path) {
<del> return __DIR__.'/fixtures/'.$path.'.php';
<add> return $this->tempDir.'/'.$path.'.php';
<ide> });
<ide> $factory->getDispatcher()->shouldReceive('fire');
<ide>
<del> $this->assertEquals("a\nc\nb\n", $factory->make('cc')->render());
<del>
<del> $files->delete(__DIR__.'/fixtures/aa.php');
<del> $files->delete(__DIR__.'/fixtures/bb.php');
<del> $files->delete(__DIR__.'/fixtures/cc.php');
<add> return $factory;
<ide> }
<ide>
<ide> protected function getFactory() | 1 |
Javascript | Javascript | improve format performance | faaefa8082033809246d004a9c46b0a612c3bb99 | <ide><path>benchmark/util/format.js
<ide>
<ide> const util = require('util');
<ide> const common = require('../common');
<del>const types = [
<del> 'string',
<del> 'number',
<del> 'object',
<del> 'unknown',
<del> 'no-replace'
<del>];
<del>const bench = common.createBenchmark(main, {
<del> n: [2e6],
<del> type: types
<del>});
<ide>
<ide> const inputs = {
<del> 'string': ['Hello, my name is %s', 'fred'],
<del> 'number': ['Hi, I was born in %d', 1942],
<del> 'object': ['An error occurred %j', { msg: 'This is an error', code: 'ERR' }],
<add> 'string': ['Hello, my name is %s', 'Fred'],
<add> 'string-2': ['Hello, %s is my name', 'Fred'],
<add> 'number': ['Hi, I was born in %d', 1989],
<add> 'replace-object': ['An error occurred %j', { msg: 'This is an error' }],
<ide> 'unknown': ['hello %a', 'test'],
<del> 'no-replace': [1, 2]
<add> 'no-replace': [1, 2],
<add> 'no-replace-2': ['foobar', 'yeah', 'mensch', 5],
<add> 'only-objects': [{ msg: 'This is an error' }, { msg: 'This is an error' }],
<add> 'many-%': ['replace%%%%s%%%%many%s%s%s', 'percent'],
<ide> };
<ide>
<del>function main(conf) {
<del> const n = conf.n | 0;
<del> const type = conf.type;
<add>const bench = common.createBenchmark(main, {
<add> n: [4e6],
<add> type: Object.keys(inputs)
<add>});
<ide>
<del> const input = inputs[type];
<add>function main({ n, type }) {
<add> const [first, second] = inputs[type];
<ide>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<del> util.format(input[0], input[1]);
<add> util.format(first, second);
<ide> }
<ide> bench.end(n);
<ide> }
<ide><path>lib/util.js
<ide> function tryStringify(arg) {
<ide> }
<ide>
<ide> function format(f) {
<add> var i, tempStr;
<ide> if (typeof f !== 'string') {
<del> const objects = new Array(arguments.length);
<del> for (var index = 0; index < arguments.length; index++) {
<del> objects[index] = inspect(arguments[index]);
<add> if (arguments.length === 0) return '';
<add> var res = '';
<add> for (i = 0; i < arguments.length - 1; i++) {
<add> res += inspect(arguments[i]);
<add> res += ' ';
<ide> }
<del> return objects.join(' ');
<add> res += inspect(arguments[i]);
<add> return res;
<ide> }
<ide>
<ide> if (arguments.length === 1) return f;
<ide>
<ide> var str = '';
<ide> var a = 1;
<ide> var lastPos = 0;
<del> for (var i = 0; i < f.length;) {
<del> if (f.charCodeAt(i) === 37/*'%'*/ && i + 1 < f.length) {
<del> if (f.charCodeAt(i + 1) !== 37/*'%'*/ && a >= arguments.length) {
<del> ++i;
<del> continue;
<del> }
<del> if (lastPos < i)
<add> for (i = 0; i < f.length - 1; i++) {
<add> if (f.charCodeAt(i) === 37) { // '%'
<add> const nextChar = f.charCodeAt(++i);
<add> if (a !== arguments.length) {
<add> switch (nextChar) {
<add> case 115: // 's'
<add> tempStr = String(arguments[a++]);
<add> break;
<add> case 106: // 'j'
<add> tempStr = tryStringify(arguments[a++]);
<add> break;
<add> case 100: // 'd'
<add> tempStr = `${Number(arguments[a++])}`;
<add> break;
<add> case 79: // 'O'
<add> tempStr = inspect(arguments[a++]);
<add> break;
<add> case 111: // 'o'
<add> tempStr = inspect(arguments[a++],
<add> { showHidden: true, depth: 4, showProxy: true });
<add> break;
<add> case 105: // 'i'
<add> tempStr = `${parseInt(arguments[a++])}`;
<add> break;
<add> case 102: // 'f'
<add> tempStr = `${parseFloat(arguments[a++])}`;
<add> break;
<add> case 37: // '%'
<add> str += f.slice(lastPos, i);
<add> lastPos = i + 1;
<add> continue;
<add> default: // any other character is not a correct placeholder
<add> continue;
<add> }
<add> if (lastPos !== i - 1)
<add> str += f.slice(lastPos, i - 1);
<add> str += tempStr;
<add> lastPos = i + 1;
<add> } else if (nextChar === 37) {
<ide> str += f.slice(lastPos, i);
<del> switch (f.charCodeAt(i + 1)) {
<del> case 100: // 'd'
<del> str += Number(arguments[a++]);
<del> break;
<del> case 105: // 'i'
<del> str += parseInt(arguments[a++]);
<del> break;
<del> case 102: // 'f'
<del> str += parseFloat(arguments[a++]);
<del> break;
<del> case 106: // 'j'
<del> str += tryStringify(arguments[a++]);
<del> break;
<del> case 115: // 's'
<del> str += String(arguments[a++]);
<del> break;
<del> case 79: // 'O'
<del> str += inspect(arguments[a++]);
<del> break;
<del> case 111: // 'o'
<del> str += inspect(arguments[a++],
<del> { showHidden: true, depth: 4, showProxy: true });
<del> break;
<del> case 37: // '%'
<del> str += '%';
<del> break;
<del> default: // any other character is not a correct placeholder
<del> str += '%';
<del> lastPos = i = i + 1;
<del> continue;
<add> lastPos = i + 1;
<ide> }
<del> lastPos = i = i + 2;
<del> continue;
<ide> }
<del> ++i;
<ide> }
<ide> if (lastPos === 0)
<ide> str = f;
<ide> else if (lastPos < f.length)
<ide> str += f.slice(lastPos);
<ide> while (a < arguments.length) {
<ide> const x = arguments[a++];
<del> if (x === null || (typeof x !== 'object' && typeof x !== 'symbol')) {
<add> if ((typeof x !== 'object' && typeof x !== 'symbol') || x === null) {
<ide> str += ` ${x}`;
<ide> } else {
<ide> str += ` ${inspect(x)}`; | 2 |
Javascript | Javascript | remove empty block | 73a75c2ee63ea65709f63b71ade3b81a02b519fc | <ide><path>lib/internal/webstreams/readablestream.js
<ide> function readableStreamPipeTo(
<ide>
<ide> async function run() {
<ide> // Run until step resolves as true
<del> while (!await step()) {}
<add> while (!await step());
<ide> }
<ide>
<ide> if (signal !== undefined) { | 1 |
Javascript | Javascript | add util functions to pdfjs | 04c8d1454d9fa30c376b08b667184c6bf449819e | <ide><path>src/util.js
<ide> function stringToBytes(str) {
<ide>
<ide> var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
<ide>
<del>var Util = (function UtilClosure() {
<add>var Util = PDFJS.Util = (function UtilClosure() {
<ide> function Util() {}
<ide>
<ide> Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
<ide><path>web/viewer.js
<ide> var PageView = function pageView(container, pdfPage, id, scale,
<ide> }
<ide> function createElementWithStyle(tagName, item) {
<ide> var rect = viewport.convertToViewportRectangle(item.rect);
<del> rect = Util.normalizeRect(rect);
<add> rect = PDFJS.Util.normalizeRect(rect);
<ide> var element = document.createElement(tagName);
<ide> element.style.left = Math.floor(rect[0]) + 'px';
<ide> element.style.top = Math.floor(rect[1]) + 'px'; | 2 |
PHP | PHP | fix vendor publish command | bcf9ed1d415fc11b4ba7d956b44284938d2ce467 | <ide><path>src/Illuminate/Foundation/Console/VendorPublishCommand.php
<ide> use Illuminate\Foundation\Events\VendorTagPublished;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\ServiceProvider;
<add>use Illuminate\Support\Str;
<ide> use League\Flysystem\Filesystem as Flysystem;
<ide> use League\Flysystem\Local\LocalFilesystemAdapter as LocalAdapter;
<ide> use League\Flysystem\MountManager;
<ide> protected function publishDirectory($from, $to)
<ide> protected function moveManagedFiles($manager)
<ide> {
<ide> foreach ($manager->listContents('from://', true) as $file) {
<del> if ($file['type'] === 'file' && (! $manager->fileExists('to://'.$file['path']) || $this->option('force'))) {
<del> $manager->write('to://'.$file['path'], $manager->read('from://'.$file['path']));
<add> $path = Str::after($file['path'], 'from://');
<add>
<add> if ($file['type'] === 'file' && (! $manager->fileExists('to://'.$path) || $this->option('force'))) {
<add> $manager->write('to://'.$path, $manager->read($file['path']));
<ide> }
<ide> }
<ide> } | 1 |
Text | Text | fix links to beginner friendly issues | c355a34de107befd26bc495272b91c11957f3fd0 | <ide><path>CONTRIBUTING.md
<ide> Working on your first Pull Request? You can learn how from this free video serie
<ide>
<ide> [**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
<ide>
<del>We have a list of [beginner friendly issues](https://github.com/facebook/react-native/labels/Good%20First%20Task) to help you get your feet wet in the React Native codebase and familiar with our contribution process. This is a great place to get started.
<add>We have a list of [beginner friendly issues](https://github.com/facebook/react-native/labels/Good%20first%20issue) to help you get your feet wet in the React Native codebase and familiar with our contribution process. This is a great place to get started.
<ide>
<ide> ### Proposing a change
<ide>
<ide><path>README.md
<ide> Read our [contributing guide](https://facebook.github.io/react-native/docs/contr
<ide>
<ide> ### Beginner Friendly Bugs
<ide>
<del>We have a list of [beginner friendly issues](https://github.com/facebook/react-native/labels/Good%20First%20Issue) to help you get your feet wet in the React Native codebase and familiar with our contribution process. This is a great place to get started.
<add>We have a list of [beginner friendly issues](https://github.com/facebook/react-native/labels/Good%20first%20issue) to help you get your feet wet in the React Native codebase and familiar with our contribution process. This is a great place to get started.
<ide>
<ide> ---
<ide> | 2 |
Java | Java | disallow empty @propertysource(value = {}) | 80dd32e95ccb6e7c4836a751b1414f4be741a1fe | <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
<ide> protected AnnotationMetadata doProcessConfigurationClass(
<ide> String name = propertySource.getString("name");
<ide> String[] locations = propertySource.getStringArray("value");
<ide> int nLocations = locations.length;
<add> if (nLocations == 0) {
<add> throw new IllegalArgumentException("At least one @PropertySource(value) location is required");
<add> }
<ide> for (int i = 0; i < nLocations; i++) {
<ide> locations[0] = this.environment.resolveRequiredPlaceholders(locations[0]);
<ide> }
<ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java
<ide> public void withNameAndMultipleResourceLocations() {
<ide> assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true));
<ide> }
<ide>
<del>
<del> @Configuration
<del> @PropertySource(
<del> name = "psName",
<del> value = {
<del> "classpath:org/springframework/context/annotation/p1.properties",
<del> "classpath:org/springframework/context/annotation/p2.properties"
<del> })
<del> static class ConfigWithNameAndMultipleResourceValues {
<add> @Test(expected=IllegalArgumentException.class)
<add> public void withEmptyResourceLocations() {
<add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
<add> ctx.register(ConfigWithEmptyResourceLocations.class);
<add> ctx.refresh();
<ide> }
<ide>
<ide>
<ide> static class P2Config {
<ide> })
<ide> static class ConfigWithNameAndMultipleResourceLocations {
<ide> }
<add>
<add>
<add> @Configuration
<add> @PropertySource(value = {})
<add> static class ConfigWithEmptyResourceLocations {
<add> }
<ide> } | 2 |
Java | Java | avoid use of stream api in controlleradvicebean | 2759b4b909ab254ca2d6e3eb55a5b2374901c91b | <ide><path>spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java
<ide>
<ide> package org.springframework.web.method;
<ide>
<del>import java.util.Arrays;
<add>import java.util.ArrayList;
<ide> import java.util.List;
<del>import java.util.stream.Collectors;
<ide>
<ide> import org.springframework.beans.factory.BeanFactory;
<ide> import org.springframework.beans.factory.BeanFactoryUtils;
<ide> * @author Rossen Stoyanchev
<ide> * @author Brian Clozel
<ide> * @author Juergen Hoeller
<add> * @author Sam Brannen
<ide> * @since 3.2
<ide> */
<ide> public class ControllerAdviceBean implements Ordered {
<ide> public String toString() {
<ide> * instances.
<ide> */
<ide> public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext context) {
<del> return Arrays.stream(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, Object.class))
<del> .filter(name -> context.findAnnotationOnBean(name, ControllerAdvice.class) != null)
<del> .map(name -> new ControllerAdviceBean(name, context))
<del> .collect(Collectors.toList());
<add> List<ControllerAdviceBean> adviceBeans = new ArrayList<>();
<add> for (String name : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, Object.class)) {
<add> if (context.findAnnotationOnBean(name, ControllerAdvice.class) != null) {
<add> adviceBeans.add(new ControllerAdviceBean(name, context));
<add> }
<add> }
<add> return adviceBeans;
<ide> }
<ide>
<ide> private static int initOrderFromBean(Object bean) { | 1 |
Ruby | Ruby | remove unnecessary string casts | dca786176e250843c3d27d562675e62c86d9d47a | <ide><path>Library/Homebrew/formula.rb
<ide> def system cmd, *args
<ide> @exec_count ||= 0
<ide> @exec_count += 1
<ide> logd = HOMEBREW_LOGS/name
<del> logfn = "#{logd}/%02d.%s" % [@exec_count, File.basename(cmd.to_s).split(' ').first]
<add> logfn = "#{logd}/%02d.%s" % [@exec_count, File.basename(cmd).split(' ').first]
<ide> mkdir_p(logd)
<ide>
<ide> rd, wr = IO.pipe
<ide> def system cmd, *args
<ide> $stdout.reopen wr
<ide> $stderr.reopen wr
<ide> args.collect!{|arg| arg.to_s}
<del> exec(cmd.to_s, *args) rescue nil
<add> exec(cmd, *args) rescue nil
<ide> puts "Failed to execute: #{cmd}"
<ide> exit! 1 # never gets here unless exec threw or failed
<ide> end | 1 |
Java | Java | fix javadoc reference | d3b051a9330de8bdd00ccff69d75a613d16f2cf5 | <ide><path>spring-core/src/main/java/org/springframework/util/backoff/BackOff.java
<ide> * BackOffExecution exec = backOff.start();
<ide> *
<ide> * // In the operation recovery/retry loop:
<del> * long waitInterval = exec.nextBackOffMillis();
<add> * long waitInterval = exec.nextBackOff();
<ide> * if (waitInterval == BackOffExecution.STOP) {
<ide> * // do not retry operation
<ide> * } | 1 |
Python | Python | add chinese punctuation | 188b439b25dbe020977761cc719efaf452e79423 | <ide><path>spacy/language_data/punctuation.py
<ide>
<ide> _PUNCT = r"""
<ide> … , : ; \! \? ¿ ¡ \( \) \[ \] \{ \} < > _ # \* &
<del>。? ! , 、 ; : ~
<add>。 ? ! , 、 ; : ~
<ide> """
<ide>
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.