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
Python
Python
adapt scheduler to use dagrun table for triggering
566da59ecf1fb5be443bab79a9dd6710ac65f3d2
<ide><path>airflow/jobs.py <ide> import sys <ide> from time import sleep <ide> <del>from sqlalchemy import Column, Integer, String, DateTime, func, Index <add>from sqlalchemy import Column, Integer, String, DateTime, func, Index, and_ <ide> from sqlalchemy.orm.session import make_transient <ide> <ide> from airflow import executors, models, settings, utils <ide> def import_errors(self, dagbag): <ide> filename=filename, stacktrace=stacktrace)) <ide> session.commit() <ide> <add> <add> def schedule_dag(self, dag): <add> """ <add> This method checks whether a new DagRun needs to be created <add> for a DAG based on scheduling interval <add> """ <add> DagRun = models.DagRun <add> session = settings.Session() <add> qry = session.query(func.max(DagRun.execution_date)).filter(and_( <add> DagRun.dag_id == dag.dag_id, <add> DagRun.external_trigger == False <add> )) <add> last_scheduled_run = qry.scalar() <add> if not last_scheduled_run or last_scheduled_run <= datetime.now(): <add> if last_scheduled_run: <add> next_run_date = last_scheduled_run + dag.schedule_interval <add> else: <add> next_run_date = dag.default_args['start_date'] <add> if not next_run_date: <add> raise Exception('no next_run_date defined!') <add> next_run = DagRun( <add> dag_id=dag.dag_id, <add> run_id='scheduled', <add> execution_date=next_run_date, <add> external_trigger=False <add> ) <add> session.add(next_run) <add> session.commit() <add> <add> <add> <ide> def process_dag(self, dag, executor): <ide> """ <ide> This method schedules a single DAG by looking at the latest <ide> def process_dag(self, dag, executor): <ide> if task.adhoc: <ide> continue <ide> if task.task_id not in ti_dict: <add> # TODO: Needs this be changed with DagRun refactoring <ide> # Brand new task, let's get started <ide> ti = TI(task, task.start_date) <ide> ti.refresh_from_db() <ide> def process_dag(self, dag, executor): <ide> # in self.prioritize_queued <ide> continue <ide> else: <del> # Trying to run the next schedule <del> next_schedule = ( <del> ti.execution_date + task.schedule_interval) <del> if ( <del> ti.task.end_date and <del> next_schedule > ti.task.end_date): <add> # Checking whether there is a dag for which no task exists <add> # up to now <add> qry = session.query(func.min(models.DagRun.execution_date)).filter( <add> and_(models.DagRun.dag_id == dag.dag_id, <add> models.DagRun.execution_date > ti.execution_date)) <add> next_schedule = qry.scalar() <add> if not next_schedule: <ide> continue <add> <ide> ti = TI( <ide> task=task, <ide> execution_date=next_schedule, <ide> def signal_handler(signum, frame): <ide> if not dag or (dag.dag_id in paused_dag_ids): <ide> continue <ide> try: <add> self.schedule_dag(dag) <ide> self.process_dag(dag, executor) <ide> self.manage_slas(dag) <ide> except Exception as e: <ide><path>airflow/migrations/versions/19054f4ff36_add_dagrun.py <ide> def upgrade(): <ide> 'dag_run', <ide> sa.Column('dag_id', sa.String(length=250), nullable=False), <ide> sa.Column('execution_date', sa.DateTime(), nullable=False), <del> sa.Column('run_id', sa.String(length=250), nullable=False), <add> sa.Column('run_id', sa.String(length=250), nullable=True), <add> sa.Column('external_trigger', sa.Boolean(), nullable=True), <ide> sa.PrimaryKeyConstraint('dag_id', 'execution_date') <ide> ) <ide> <ide><path>airflow/models.py <ide> def is_queueable(self, flag_upstream_failed=False): <ide> path to add the feature <ide> :type flag_upstream_failed: boolean <ide> """ <del> if self.execution_date > datetime.now() - self.task.schedule_interval: <add> if self.execution_date > datetime.now(): <ide> return False <ide> elif self.state == State.UP_FOR_RETRY and not self.ready_for_retry(): <ide> return False <ide> class DagRun(Base): <ide> dag_id = Column(String(ID_LEN), primary_key=True) <ide> execution_date = Column(DateTime, primary_key=True) <ide> run_id = Column(String(ID_LEN)) <del> timestamp = Column(DateTime) <del> description = Column(Text) <add> external_trigger = Column(Boolean, default=False) <ide> <ide> def __repr__(self): <add> return '<DagRun {dag_id} @ {execution_date}: {run_id}, \ <add> externally triggered: {external_trigger}>'.format( <add> task_id=self.task_id, <add> execution_date=self.execution_date, <add> run_id=self.run_id, <add> external_trigger=self.external_trigger) <ide> return str(( <ide> self.dag_id, self.run_id, self.execution_date.isoformat())) <ide>
3
Mixed
Ruby
fix with_routing when testing api only controllers
f28d073a394c0575dac5505e2c1c8cafc66034c4
<ide><path>actionpack/CHANGELOG.md <add>* Make `with_routing` test helper work when testing controllers inheriting from `ActionController::API` <add> <add> *Julia López* <add> <ide> * Use accept header in integration tests with `as: :json` <ide> <ide> Instead of appending the `format` to the request path, Rails will figure <ide><path>actionpack/lib/action_dispatch/testing/assertions/routing.rb <ide> def with_routing <ide> _routes = @routes <ide> <ide> @controller.singleton_class.include(_routes.url_helpers) <del> @controller.view_context_class = Class.new(@controller.view_context_class) do <del> include _routes.url_helpers <add> <add> if @controller.respond_to? :view_context_class <add> @controller.view_context_class = Class.new(@controller.view_context_class) do <add> include _routes.url_helpers <add> end <ide> end <ide> end <ide> yield @routes <ide><path>actionpack/test/controller/action_pack_assertions_test.rb <ide> def redirect_to_top_level_named_route <ide> end <ide> end <ide> <add>class ApiOnlyController < ActionController::API <add> def nothing <add> head :ok <add> end <add> <add> def redirect_to_new_route <add> redirect_to new_route_url <add> end <add>end <add> <ide> class ActionPackAssertionsControllerTest < ActionController::TestCase <ide> def test_render_file_absolute_path <ide> get :render_file_absolute_path <ide> def test_string_constraint <ide> end <ide> end <ide> <add> def test_with_routing_works_with_api_only_controllers <add> @controller = ApiOnlyController.new <add> <add> with_routing do |set| <add> set.draw do <add> get "new_route", to: "api_only#nothing" <add> get "redirect_to_new_route", to: "api_only#redirect_to_new_route" <add> end <add> <add> process :redirect_to_new_route <add> assert_redirected_to "http://test.host/new_route" <add> end <add> end <add> <ide> def test_assert_redirect_to_named_route_failure <ide> with_routing do |set| <ide> set.draw do
3
PHP
PHP
apply fixes from styleci
621ca8a3fd8fe9ea35ed97d80ae7d2a0de79d08a
<ide><path>tests/View/ViewBladeCompilerTest.php <ide> public function testCompileCompilesFileAndReturnsContents() <ide> { <ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); <ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); <del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World"); <add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); <ide> $compiler->compile('foo'); <ide> } <ide> <ide> public function testCompileCompilesAndGetThePath() <ide> { <ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); <ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); <del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World"); <add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); <ide> $compiler->compile('foo'); <ide> $this->assertEquals('foo', $compiler->getPath()); <ide> } <ide> public function testCompileWithPathSetBefore() <ide> { <ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); <ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); <del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World"); <add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); <ide> // set path before compilation <ide> $compiler->setPath('foo'); <ide> // trigger compilation with null $path <ide> public function testIncludePathToTemplate() <ide> { <ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); <ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); <del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World"); <add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); <ide> $compiler->compile('foo'); <ide> } <ide>
1
PHP
PHP
return instance from sethidden
f19151762b38e7386a5d85d4bbc948de6d123cd8
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function getHidden() <ide> * Set the hidden attributes for the model. <ide> * <ide> * @param array $hidden <del> * @return void <add> * @return $this <ide> */ <ide> public function setHidden(array $hidden) <ide> { <ide> $this->hidden = $hidden; <add> <add> return $this; <ide> } <ide> <ide> /**
1
Text
Text
fix 'persons' to 'people' and add some whitespace
204d3afb2ad33dbc8ae1e7a3c94adc41effe7907
<ide><path>guides/source/action_view_overview.md <ide> Action View Overview <ide> <ide> In this guide you will learn: <ide> <del>* What Action View is, and how to use it with Rails <add>* What Action View is and how to use it with Rails <ide> * How best to use templates, partials, and layouts <ide> * What helpers are provided by Action View and how to make your own <ide> * How to use localized views <ide> The core method of this helper, form_for, gives you the ability to create a form <ide> The HTML generated for this would be: <ide> <ide> ```html <del><form action="/persons/create" method="post"> <add><form action="/people/create" method="post"> <ide> <input id="person_first_name" name="person[first_name]" type="text" /> <ide> <input id="person_last_name" name="person[last_name]" type="text" /> <ide> <input name="commit" type="submit" value="Create" /> <ide> The HTML generated for this would be: <ide> The params object created when this form is submitted would look like: <ide> <ide> ```ruby <del>{"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}} <add>{"action" => "create", "controller" => "people", "person" => {"first_name" => "William", "last_name" => "Smith"}} <ide> ``` <ide> <ide> The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller.
1
Text
Text
use relative urls for intra-guide links [ci-skip]
9ac01c6a818108e019d15a782fbaeca8ae9cc1bb
<ide><path>guides/source/action_controller_overview.md <ide> WARNING: Some method names are reserved by Action Controller. Accidentally redef <ide> NOTE: If you must use a reserved method as an action name, one workaround is to use a custom route to map the reserved method name to your non-reserved action method. <ide> <ide> [`ActionController::Base`]: https://api.rubyonrails.org/classes/ActionController/Base.html <del>[Resource Routing]: https://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default <add>[Resource Routing]: routing.html#resource-routing-the-rails-default <ide> <ide> Parameters <ide> ---------- <ide><path>guides/source/active_record_encryption.md <ide> end <ide> <ide> ### Filtering Params Named as Encrypted Columns <ide> <del>By default, encrypted columns are configured to be [automatically filtered in Rails logs](https://guides.rubyonrails.org/action_controller_overview.html#parameters-filtering). You can disable this behavior by adding the following to your `application.rb`: <add>By default, encrypted columns are configured to be [automatically filtered in Rails logs](action_controller_overview.html#parameters-filtering). You can disable this behavior by adding the following to your `application.rb`: <ide> <ide> When generating the filter parameter, it will use the model name as a prefix. E.g: For `Person#name` the filter parameter will be `person.name`. <ide> <ide><path>guides/source/active_storage_overview.md <ide> the purge job is executed immediately rather at an unknown time in the future. <ide> config.active_job.queue_adapter = :inline <ide> ``` <ide> <del>[parallel tests]: https://guides.rubyonrails.org/testing.html#parallel-testing <add>[parallel tests]: testing.html#parallel-testing <ide> <ide> #### Integration tests <ide> <ide> class ActionDispatch::IntegrationTest <ide> end <ide> ``` <ide> <del>[parallel tests]: https://guides.rubyonrails.org/testing.html#parallel-testing <add>[parallel tests]: testing.html#parallel-testing <ide> <ide> ### Adding attachments to fixtures <ide> <ide> Minitest.after_run do <ide> end <ide> ``` <ide> <del>[fixtures]: https://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures <add>[fixtures]: testing.html#the-low-down-on-fixtures <ide> [`ActiveStorage::FixtureSet`]: https://api.rubyonrails.org/classes/ActiveStorage/FixtureSet.html <ide> <ide> Implementing Support for Other Cloud Services <ide><path>guides/source/command_line.md <ide> about code. In unit testing, we take a little part of code, say a method of a mo <ide> and test its inputs and outputs. Unit tests are your friend. The sooner you make <ide> peace with the fact that your quality of life will drastically increase when you unit <ide> test your code, the better. Seriously. Please visit <del>[the testing guide](https://guides.rubyonrails.org/testing.html) for an in-depth <add>[the testing guide](testing.html) for an in-depth <ide> look at unit testing. <ide> <ide> Let's see the interface Rails created for us. <ide><path>guides/source/contributing_to_ruby_on_rails.md <ide> Reporting an Issue <ide> <ide> Ruby on Rails uses [GitHub Issue Tracking](https://github.com/rails/rails/issues) to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) GitHub account to submit an issue, comment on issues, or create pull requests. <ide> <del>NOTE: Bugs in the most recent released version of Ruby on Rails will likely get the most attention. Additionally, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide, you'll find out how to get edge Rails for testing. See our [maintenance policy](https://guides.rubyonrails.org/maintenance_policy.html) for information on which versions are supported. Never report a security issue on the GitHub issues tracker. <add>NOTE: Bugs in the most recent released version of Ruby on Rails will likely get the most attention. Additionally, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide, you'll find out how to get edge Rails for testing. See our [maintenance policy](maintenance_policy.html) for information on which versions are supported. Never report a security issue on the GitHub issues tracker. <ide> <ide> ### Creating a Bug Report <ide> <ide><path>guides/source/development_dependencies_install.md <ide> After reading this guide, you will know: <ide> Other Ways to Set Up Your Environment <ide> ------------------------------------- <ide> <del>If you don't want to set up Rails for development on your local machine, you can use Codespaces, the VS Code Remote Plugin, or rails-dev-box. Learn more about these options [here](https://guides.rubyonrails.org/contributing_to_ruby_on_rails.html#setting-up-a-development-environment). <add>If you don't want to set up Rails for development on your local machine, you can use Codespaces, the VS Code Remote Plugin, or rails-dev-box. Learn more about these options [here](contributing_to_ruby_on_rails.html#setting-up-a-development-environment). <ide> <ide> Local Development <ide> ----------------- <ide><path>guides/source/getting_started.md <ide> You may have noticed that `ArticlesController` inherits from `ApplicationControl <ide> require "application_controller" # DON'T DO THIS. <ide> ``` <ide> <del>Application classes and modules are available everywhere, you do not need and **should not** load anything under `app` with `require`. This feature is called _autoloading_, and you can learn more about it in [_Autoloading and Reloading Constants_](https://guides.rubyonrails.org/autoloading_and_reloading_constants.html). <add>Application classes and modules are available everywhere, you do not need and **should not** load anything under `app` with `require`. This feature is called _autoloading_, and you can learn more about it in [_Autoloading and Reloading Constants_](autoloading_and_reloading_constants.html). <ide> <ide> You only need `require` calls for two use cases: <ide>
7
Ruby
Ruby
simplify integration tests
0e080eba97095d0212c605390ec59df2d52d23b0
<ide><path>Library/Homebrew/test/dev-cmd/extract_spec.rb <ide> describe "brew extract", :integration_test do <del> it "retrieves the most recent formula version without version argument" do <add> it "retrieves the specified version of formula, defaulting to most recent" do <ide> path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" <ide> (path/"Formula").mkpath <ide> target = Tap.from_path(path) <ide> expect(path/"Formula/[email protected]").to exist <ide> <ide> expect(Formulary.factory(path/"Formula/[email protected]").version).to be == "0.2" <del> end <del> <del> it "does not overwrite existing files, except when running with --force" do <del> path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" <del> (path/"Formula").mkpath <del> target = Tap.from_path(path) <del> core_tap = CoreTap.new <del> core_tap.path.cd do <del> system "git", "init" <del> formula_file = setup_test_formula "testball" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.1" <del> contents = File.read(formula_file) <del> contents.gsub!("testball-0.1", "testball-0.2") <del> File.write(formula_file, contents) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.2" <del> end <del> expect { brew "extract", "testball", target.name } <del> .to be_a_success <del> <del> expect(path/"Formula/[email protected]").to exist <del> <del> expect { brew "extract", "testball", target.name } <del> .to be_a_failure <del> <del> expect { brew "extract", "testball", target.name, "--force" } <del> .to be_a_success <del> <del> expect { brew "extract", "testball", target.name, "--version=0.1" } <del> .to be_a_success <del> <del> expect(path/"Formula/[email protected]").to exist <del> <del> expect { brew "extract", "testball", "--version=0.1", target.name } <del> .to be_a_failure <del> <del> expect { brew "extract", "testball", target.name, "--version=0.1", "--force" } <del> .to be_a_success <del> end <del> <del> it "retrieves the specified formula version when given argument" do <del> path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" <del> (path/"Formula").mkpath <del> target = Tap.from_path(path) <del> core_tap = CoreTap.new <del> core_tap.path.cd do <del> system "git", "init" <del> formula_file = setup_test_formula "testball" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.1" <del> contents = File.read(formula_file) <del> contents.gsub!("testball-0.1", "testball-0.2") <del> File.write(formula_file, contents) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.2" <del> end <del> expect { brew "extract", "testball", target.name, "--version=0.1" } <del> .to be_a_success <del> <del> expect { brew "extract", "testball", target.name, "--version=0.1", "--force" } <del> .to be_a_success <del> <del> expect(Formulary.factory(path/"Formula/[email protected]").version).to be == "0.1" <del> end <del> <del> it "retrieves most recent deleted formula when no argument is given" do <del> path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" <del> (path/"Formula").mkpath <del> target = Tap.from_path(path) <del> core_tap = CoreTap.new <del> core_tap.path.cd do <del> system "git", "init" <del> formula_file = setup_test_formula "testball" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.1" <del> contents = File.read(formula_file) <del> contents.gsub!("testball-0.1", "testball-0.2") <del> File.write(formula_file, contents) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.2" <del> File.delete(formula_file) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "Remove testball" <del> end <del> <del> expect { brew "extract", "testball", target.name } <del> .to be_a_success <del> <del> expect(path/"Formula/[email protected]").to exist <del> <del> expect(Formulary.factory(path/"Formula/[email protected]").version).to be == "0.2" <del> end <del> <del> it "retrieves old version of deleted formula when argument is given" do <del> path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" <del> (path/"Formula").mkpath <del> target = Tap.from_path(path) <del> core_tap = CoreTap.new <del> core_tap.path.cd do <del> system "git", "init" <del> formula_file = setup_test_formula "testball" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.1" <del> contents = File.read(formula_file) <del> contents.gsub!("testball-0.1", "testball-0.2") <del> File.write(formula_file, contents) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.2" <del> File.delete(formula_file) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "Remove testball" <del> end <ide> <ide> expect { brew "extract", "testball", target.name, "--version=0.1" } <ide> .to be_a_success <ide> <ide> expect(Formulary.factory(path/"Formula/[email protected]").version).to be == "0.1" <ide> end <del> <del> it "retrieves old formulae that use outdated/missing blocks" do <del> path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" <del> (path/"Formula").mkpath <del> target = Tap.from_path(path) <del> core_tap = CoreTap.new <del> core_tap.path.cd do <del> system "git", "init" <del> contents = <<~EOF <del> require 'brewkit' <del> class Testball < Formula <del> @url="file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" <del> @md5='80a8aa0c5a8310392abf3b69f0319204' <del> <del> def install <del> prefix.install "bin" <del> prefix.install "libexec" <del> Dir.chdir "doc" <del> end <del> end <del> EOF <del> formula_file = core_tap.path/"Formula/testball.rb" <del> File.write(formula_file, contents) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.1" <del> contents = File.read(formula_file) <del> contents.gsub!("testball-0.1", "testball-0.2") <del> File.write(formula_file, contents) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.2" <del> File.delete(formula_file) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "Remove testball" <del> end <del> <del> expect { brew "extract", "testball", target.name, "--version=0.1" } <del> .to be_a_success <del> <del> expect(path/"Formula/[email protected]").to exist <del> end <del> <del> it "fails when formula does not exist" do <del> path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" <del> (path/"Formula").mkpath <del> target = Tap.from_path(path) <del> core_tap = CoreTap.new <del> core_tap.path.cd do <del> system "git", "init" <del> formula_file = setup_test_formula "testball" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.1" <del> contents = File.read(formula_file) <del> contents.gsub!("testball-0.1", "testball-0.2") <del> File.write(formula_file, contents) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.2" <del> File.delete(formula_file) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "Remove testball" <del> end <del> expect { brew "extract", "foo", target.name } <del> .to be_a_failure <del> expect(Dir.entries(path/"Formula").size).to be == 2 <del> end <del> <del> it "fails when formula does not have the specified version" do <del> path = Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" <del> (path/"Formula").mkpath <del> target = Tap.from_path(path) <del> core_tap = CoreTap.new <del> core_tap.path.cd do <del> system "git", "init" <del> formula_file = setup_test_formula "testball" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.1" <del> contents = File.read(formula_file) <del> contents.gsub!("testball-0.1", "testball-0.2") <del> File.write(formula_file, contents) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "testball 0.2" <del> File.delete(formula_file) <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "Remove testball" <del> end <del> <del> expect { brew "extract", "testball", target.name, "--version=0.3" } <del> .to be_a_failure <del> <del> expect(path/"Formula/[email protected]").not_to exist <del> end <ide> end
1
Python
Python
fix big bird gpu test
7772ddb473a079e10f4635bb00703c8011754120
<ide><path>tests/test_modeling_big_bird.py <ide> def test_model_various_attn_type(self): <ide> config_and_inputs[0].attention_type = type <ide> self.model_tester.create_and_check_model(*config_and_inputs) <ide> <del> @unittest.skipIf(torch_device == "cpu", "Fast integration only compatible on GPU") <ide> def test_fast_integration(self): <del> torch.manual_seed(0) <del> <del> input_ids = torch.randint( <del> self.model_tester.vocab_size, <del> (self.model_tester.batch_size, self.model_tester.seq_length), <add> # fmt: off <add> input_ids = torch.tensor( <add> [[6, 117, 33, 36, 70, 22, 63, 31, 71, 72, 88, 58, 109, 49, 48, 116, 92, 6, 19, 95, 118, 100, 80, 111, 93, 2, 31, 84, 26, 5, 6, 82, 46, 96, 109, 4, 39, 19, 109, 13, 92, 31, 36, 90, 111, 18, 75, 6, 56, 74, 16, 42, 56, 92, 69, 108, 127, 81, 82, 41, 106, 19, 44, 24, 82, 121, 120, 65, 36, 26, 72, 13, 36, 98, 43, 64, 8, 53, 100, 92, 51, 122, 66, 17, 61, 50, 104, 127, 26, 35, 94, 23, 110, 71, 80, 67, 109, 111, 44, 19, 51, 41, 86, 71, 76, 44, 18, 68, 44, 77, 107, 81, 98, 126, 100, 2, 49, 98, 84, 39, 23, 98, 52, 46, 10, 82, 121, 73],[6, 117, 33, 36, 70, 22, 63, 31, 71, 72, 88, 58, 109, 49, 48, 116, 92, 6, 19, 95, 118, 100, 80, 111, 93, 2, 31, 84, 26, 5, 6, 82, 46, 96, 109, 4, 39, 19, 109, 13, 92, 31, 36, 90, 111, 18, 75, 6, 56, 74, 16, 42, 56, 92, 69, 108, 127, 81, 82, 41, 106, 19, 44, 24, 82, 121, 120, 65, 36, 26, 72, 13, 36, 98, 43, 64, 8, 53, 100, 92, 51, 12, 66, 17, 61, 50, 104, 127, 26, 35, 94, 23, 110, 71, 80, 67, 109, 111, 44, 19, 51, 41, 86, 71, 76, 28, 18, 68, 44, 77, 107, 81, 98, 126, 100, 2, 49, 18, 84, 39, 23, 98, 52, 46, 10, 82, 121, 73]], # noqa: E231 <add> dtype=torch.long, <ide> device=torch_device, <ide> ) <del> attention_mask = torch.ones((self.model_tester.batch_size, self.model_tester.seq_length), device=torch_device) <add> # fmt: on <add> input_ids = input_ids % self.model_tester.vocab_size <add> input_ids[1] = input_ids[1] - 1 <add> <add> attention_mask = torch.ones((input_ids.shape), device=torch_device) <ide> attention_mask[:, :-10] = 0 <del> token_type_ids = torch.randint( <del> self.model_tester.type_vocab_size, <del> (self.model_tester.batch_size, self.model_tester.seq_length), <del> device=torch_device, <del> ) <ide> <ide> config, _, _, _, _, _, _ = self.model_tester.prepare_config_and_inputs() <del> model = BigBirdModel(config).to(torch_device).eval() <add> torch.manual_seed(0) <add> model = BigBirdModel(config).eval().to(torch_device) <ide> <ide> with torch.no_grad(): <del> hidden_states = model( <del> input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask <del> ).last_hidden_state <add> hidden_states = model(input_ids, attention_mask=attention_mask).last_hidden_state <ide> self.assertTrue( <ide> torch.allclose( <ide> hidden_states[0, 0, :5], <del> torch.tensor([-0.6326, 0.6124, -0.0844, 0.6698, -1.7155], device=torch_device), <add> torch.tensor([1.4943, 0.0928, 0.8254, -0.2816, -0.9788], device=torch_device), <ide> atol=1e-3, <ide> ) <ide> )
1
Javascript
Javascript
fix typo in comments of text-editor-registry.js
11c06d44b8e6c1ab5992997d1fcee351f62f825d
<ide><path>src/text-editor-registry.js <ide> export default class TextEditorRegistry { <ide> } <ide> <ide> // Set a {TextEditor}'s grammar based on its path and content, and continue <del> // to update its grammar as gramamrs are added or updated, or the editor's <add> // to update its grammar as grammars are added or updated, or the editor's <ide> // file path changes. <ide> // <ide> // * `editor` The editor whose grammar will be maintained.
1
Python
Python
fix a bug
d7ea34fcc87159ec7d3b5a802b34629f756dd923
<ide><path>examples/variational_autoencoder.py <ide> def plot_results(models, <ide> <ide> plt.figure(figsize=(10, 10)) <ide> start_range = digit_size // 2 <del> end_range = n * digit_size + start_range + 1 <add> end_range = (n - 1) * digit_size + start_range + 1 <ide> pixel_range = np.arange(start_range, end_range, digit_size) <ide> sample_range_x = np.round(grid_x, 1) <ide> sample_range_y = np.round(grid_y, 1)
1
Javascript
Javascript
fix csp setup
ea2518fceac22f2ee2a9ce688e9608f776c207f1
<ide><path>test/ng/parseSpec.js <ide> describe('parser', function() { <ide> <ide> beforeEach(module(function($provide) { <ide> $provide.decorator('$sniffer', function($delegate) { <del> $delegate.csp = cspEnabled; <del> return $delegate; <add> expect($delegate.csp.noUnsafeEval === true || <add> $delegate.csp.noUnsafeEval === false).toEqual(true); <add> $delegate.csp.noUnsafeEval = cspEnabled; <ide> }); <ide> }, provideLog)); <ide> <ide> describe('parser', function() { <ide> <ide> expect(scope.$eval('items[1] = "abc"')).toEqual("abc"); <ide> expect(scope.$eval('items[1]')).toEqual("abc"); <del> // Dont know how to make this work.... <del> // expect(scope.$eval('books[1] = "moby"')).toEqual("moby"); <del> // expect(scope.$eval('books[1]')).toEqual("moby"); <add> expect(scope.$eval('books[1] = "moby"')).toEqual("moby"); <add> expect(scope.$eval('books[1]')).toEqual("moby"); <ide> }); <ide> <ide> it('should evaluate grouped filters', function() {
1
Go
Go
use state as embedded to container
e0339d4b88989a31b72be02582eee72433d2f0ec
<ide><path>builder/internals.go <ide> func (b *Builder) run(c *daemon.Container) error { <ide> } <ide> <ide> // Wait for it to finish <del> if ret, _ := c.State.WaitStop(-1 * time.Second); ret != 0 { <add> if ret, _ := c.WaitStop(-1 * time.Second); ret != 0 { <ide> err := &utils.JSONError{ <ide> Message: fmt.Sprintf("The command %v returned a non-zero code: %d", b.Config.Cmd, ret), <ide> Code: ret, <ide><path>daemon/attach.go <ide> func (daemon *Daemon) ContainerAttach(job *engine.Job) engine.Status { <ide> // If we are in stdinonce mode, wait for the process to end <ide> // otherwise, simply return <ide> if container.Config.StdinOnce && !container.Config.Tty { <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> } <ide> } <ide> return engine.StatusOK <ide><path>daemon/container.go <ide> func (container *Container) Start() (err error) { <ide> container.Lock() <ide> defer container.Unlock() <ide> <del> if container.State.Running { <add> if container.Running { <ide> return nil <ide> } <ide> <ide> func (container *Container) Run() error { <ide> if err := container.Start(); err != nil { <ide> return err <ide> } <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> return nil <ide> } <ide> <ide> func (container *Container) Output() (output []byte, err error) { <ide> return nil, err <ide> } <ide> output, err = ioutil.ReadAll(pipe) <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> return output, err <ide> } <ide> <ide> func (container *Container) KillSig(sig int) error { <ide> defer container.Unlock() <ide> <ide> // We could unpause the container for them rather than returning this error <del> if container.State.Paused { <add> if container.Paused { <ide> return fmt.Errorf("Container %s is paused. Unpause the container before stopping", container.ID) <ide> } <ide> <del> if !container.State.Running { <add> if !container.Running { <ide> return nil <ide> } <ide> <ide> func (container *Container) KillSig(sig int) error { <ide> // if the container is currently restarting we do not need to send the signal <ide> // to the process. Telling the monitor that it should exit on it's next event <ide> // loop is enough <del> if container.State.Restarting { <add> if container.Restarting { <ide> return nil <ide> } <ide> <ide> return container.daemon.Kill(container, sig) <ide> } <ide> <ide> func (container *Container) Pause() error { <del> if container.State.IsPaused() { <add> if container.IsPaused() { <ide> return fmt.Errorf("Container %s is already paused", container.ID) <ide> } <del> if !container.State.IsRunning() { <add> if !container.IsRunning() { <ide> return fmt.Errorf("Container %s is not running", container.ID) <ide> } <ide> return container.daemon.Pause(container) <ide> } <ide> <ide> func (container *Container) Unpause() error { <del> if !container.State.IsPaused() { <add> if !container.IsPaused() { <ide> return fmt.Errorf("Container %s is not paused", container.ID) <ide> } <del> if !container.State.IsRunning() { <add> if !container.IsRunning() { <ide> return fmt.Errorf("Container %s is not running", container.ID) <ide> } <ide> return container.daemon.Unpause(container) <ide> } <ide> <ide> func (container *Container) Kill() error { <del> if !container.State.IsRunning() { <add> if !container.IsRunning() { <ide> return nil <ide> } <ide> <ide> func (container *Container) Kill() error { <ide> } <ide> <ide> // 2. Wait for the process to die, in last resort, try to kill the process directly <del> if _, err := container.State.WaitStop(10 * time.Second); err != nil { <add> if _, err := container.WaitStop(10 * time.Second); err != nil { <ide> // Ensure that we don't kill ourselves <del> if pid := container.State.GetPid(); pid != 0 { <add> if pid := container.GetPid(); pid != 0 { <ide> log.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", utils.TruncateID(container.ID)) <ide> if err := syscall.Kill(pid, 9); err != nil { <ide> return err <ide> } <ide> } <ide> } <ide> <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> return nil <ide> } <ide> <ide> func (container *Container) Stop(seconds int) error { <del> if !container.State.IsRunning() { <add> if !container.IsRunning() { <ide> return nil <ide> } <ide> <ide> func (container *Container) Stop(seconds int) error { <ide> } <ide> <ide> // 2. Wait for the process to exit on its own <del> if _, err := container.State.WaitStop(time.Duration(seconds) * time.Second); err != nil { <add> if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil { <ide> log.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds) <ide> // 3. If it doesn't, then send SIGKILL <ide> if err := container.Kill(); err != nil { <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> return err <ide> } <ide> } <ide> func (container *Container) setupLinkedContainers() ([]string, error) { <ide> } <ide> <ide> for linkAlias, child := range children { <del> if !child.State.IsRunning() { <add> if !child.IsRunning() { <ide> return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias) <ide> } <ide> <ide> func (container *Container) getNetworkedContainer() (*Container, error) { <ide> if nc == nil { <ide> return nil, fmt.Errorf("no such container to join network: %s", parts[1]) <ide> } <del> if !nc.State.IsRunning() { <add> if !nc.IsRunning() { <ide> return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1]) <ide> } <ide> return nc, nil <ide><path>daemon/daemon.go <ide> func (daemon *Daemon) register(container *Container, updateSuffixarray bool) err <ide> // FIXME: if the container is supposed to be running but is not, auto restart it? <ide> // if so, then we need to restart monitor and init a new lock <ide> // If the container is supposed to be running, make sure of it <del> if container.State.IsRunning() { <add> if container.IsRunning() { <ide> log.Debugf("killing old running container %s", container.ID) <ide> <del> existingPid := container.State.Pid <del> container.State.SetStopped(0) <add> existingPid := container.Pid <add> container.SetStopped(0) <ide> <ide> // We only have to handle this for lxc because the other drivers will ensure that <ide> // no processes are left when docker dies <ide> func (daemon *Daemon) register(container *Container, updateSuffixarray bool) err <ide> <ide> log.Debugf("Marking as stopped") <ide> <del> container.State.SetStopped(-127) <add> container.SetStopped(-127) <ide> if err := container.ToDisk(); err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) restore() error { <ide> <ide> for _, container := range registeredContainers { <ide> if container.hostConfig.RestartPolicy.Name == "always" || <del> (container.hostConfig.RestartPolicy.Name == "on-failure" && container.State.ExitCode != 0) { <add> (container.hostConfig.RestartPolicy.Name == "on-failure" && container.ExitCode != 0) { <ide> log.Debugf("Starting container %s", container.ID) <ide> <ide> if err := container.Start(); err != nil { <ide> func (daemon *Daemon) shutdown() error { <ide> log.Debugf("starting clean shutdown of all containers...") <ide> for _, container := range daemon.List() { <ide> c := container <del> if c.State.IsRunning() { <add> if c.IsRunning() { <ide> log.Debugf("stopping %s", c.ID) <ide> group.Add(1) <ide> <ide> func (daemon *Daemon) shutdown() error { <ide> if err := c.KillSig(15); err != nil { <ide> log.Debugf("kill 15 error for %s - %s", c.ID, err) <ide> } <del> c.State.WaitStop(-1 * time.Second) <add> c.WaitStop(-1 * time.Second) <ide> log.Debugf("container stopped %s", c.ID) <ide> }() <ide> } <ide> func (daemon *Daemon) Pause(c *Container) error { <ide> if err := daemon.execDriver.Pause(c.command); err != nil { <ide> return err <ide> } <del> c.State.SetPaused() <add> c.SetPaused() <ide> return nil <ide> } <ide> <ide> func (daemon *Daemon) Unpause(c *Container) error { <ide> if err := daemon.execDriver.Unpause(c.command); err != nil { <ide> return err <ide> } <del> c.State.SetUnpaused() <add> c.SetUnpaused() <ide> return nil <ide> } <ide> <ide><path>daemon/delete.go <ide> func (daemon *Daemon) ContainerRm(job *engine.Job) engine.Status { <ide> } <ide> <ide> if container != nil { <del> if container.State.IsRunning() { <add> if container.IsRunning() { <ide> if forceRemove { <ide> if err := container.Kill(); err != nil { <ide> return job.Errorf("Could not kill running container, cannot remove - %v", err) <ide><path>daemon/image_delete.go <ide> func (daemon *Daemon) canDeleteImage(imgID string, force, untagged bool) error { <ide> <ide> if err := parent.WalkHistory(func(p *image.Image) error { <ide> if imgID == p.ID { <del> if container.State.IsRunning() { <add> if container.IsRunning() { <ide> if force { <ide> return fmt.Errorf("Conflict, cannot force delete %s because the running container %s is using it%s, stop it and retry", utils.TruncateID(imgID), utils.TruncateID(container.ID), message) <ide> } <ide><path>daemon/list.go <ide> func (daemon *Daemon) Containers(job *engine.Job) engine.Status { <ide> writeCont := func(container *Container) error { <ide> container.Lock() <ide> defer container.Unlock() <del> if !container.State.Running && !all && n <= 0 && since == "" && before == "" { <add> if !container.Running && !all && n <= 0 && since == "" && before == "" { <ide> return nil <ide> } <ide> if before != "" && !foundBefore { <ide> func (daemon *Daemon) Containers(job *engine.Job) engine.Status { <ide> return errLast <ide> } <ide> } <del> if len(filt_exited) > 0 && !container.State.Running { <add> if len(filt_exited) > 0 && !container.Running { <ide> should_skip := true <ide> for _, code := range filt_exited { <del> if code == container.State.GetExitCode() { <add> if code == container.GetExitCode() { <ide> should_skip = false <ide> break <ide> } <ide><path>daemon/logs.go <ide> func (daemon *Daemon) ContainerLogs(job *engine.Job) engine.Status { <ide> } <ide> } <ide> } <del> if follow && container.State.IsRunning() { <add> if follow && container.IsRunning() { <ide> errors := make(chan error, 2) <ide> if stdout { <ide> stdoutPipe := container.StdoutLogPipe() <ide><path>daemon/monitor.go <ide> func (m *containerMonitor) Start() error { <ide> defer func() { <ide> if afterRun { <ide> m.container.Lock() <del> m.container.State.setStopped(exitStatus) <add> m.container.setStopped(exitStatus) <ide> defer m.container.Unlock() <ide> } <ide> m.Close() <ide> func (m *containerMonitor) Start() error { <ide> m.resetMonitor(err == nil && exitStatus == 0) <ide> <ide> if m.shouldRestart(exitStatus) { <del> m.container.State.SetRestarting(exitStatus) <add> m.container.SetRestarting(exitStatus) <ide> m.container.LogEvent("die") <ide> m.resetContainer(true) <ide> <ide> func (m *containerMonitor) callback(processConfig *execdriver.ProcessConfig, pid <ide> } <ide> } <ide> <del> m.container.State.setRunning(pid) <add> m.container.setRunning(pid) <ide> <ide> // signal that the process has started <ide> // close channel only if not closed <ide><path>daemon/start.go <ide> func (daemon *Daemon) ContainerStart(job *engine.Job) engine.Status { <ide> return job.Errorf("No such container: %s", name) <ide> } <ide> <del> if container.State.IsRunning() { <add> if container.IsRunning() { <ide> return job.Errorf("Container already started") <ide> } <ide> <ide><path>daemon/stop.go <ide> func (daemon *Daemon) ContainerStop(job *engine.Job) engine.Status { <ide> t = job.GetenvInt("t") <ide> } <ide> if container := daemon.Get(name); container != nil { <del> if !container.State.IsRunning() { <add> if !container.IsRunning() { <ide> return job.Errorf("Container already stopped") <ide> } <ide> if err := container.Stop(int(t)); err != nil { <ide><path>daemon/top.go <ide> func (daemon *Daemon) ContainerTop(job *engine.Job) engine.Status { <ide> } <ide> <ide> if container := daemon.Get(name); container != nil { <del> if !container.State.IsRunning() { <add> if !container.IsRunning() { <ide> return job.Errorf("Container %s is not running", name) <ide> } <ide> pids, err := daemon.ExecutionDriver().GetPidsForContainer(container.ID) <ide><path>daemon/wait.go <ide> func (daemon *Daemon) ContainerWait(job *engine.Job) engine.Status { <ide> } <ide> name := job.Args[0] <ide> if container := daemon.Get(name); container != nil { <del> status, _ := container.State.WaitStop(-1 * time.Second) <add> status, _ := container.WaitStop(-1 * time.Second) <ide> job.Printf("%d\n", status) <ide> return engine.StatusOK <ide> } <ide><path>integration/commands_test.go <ide> func waitContainerStart(t *testing.T, timeout time.Duration) *daemon.Container { <ide> setTimeout(t, "Waiting for the container to be started timed out", timeout, func() { <ide> for { <ide> l := globalDaemon.List() <del> if len(l) == 1 && l[0].State.IsRunning() { <add> if len(l) == 1 && l[0].IsRunning() { <ide> container = l[0] <ide> break <ide> } <ide> func TestRunDisconnect(t *testing.T) { <ide> // cause /bin/cat to exit. <ide> setTimeout(t, "Waiting for /bin/cat to exit timed out", 2*time.Second, func() { <ide> container := globalDaemon.List()[0] <del> container.State.WaitStop(-1 * time.Second) <del> if container.State.IsRunning() { <add> container.WaitStop(-1 * time.Second) <add> if container.IsRunning() { <ide> t.Fatalf("/bin/cat is still running after closing stdin") <ide> } <ide> }) <ide> func TestRunDisconnectTty(t *testing.T) { <ide> // In tty mode, we expect the process to stay alive even after client's stdin closes. <ide> <ide> // Give some time to monitor to do his thing <del> container.State.WaitStop(500 * time.Millisecond) <del> if !container.State.IsRunning() { <add> container.WaitStop(500 * time.Millisecond) <add> if !container.IsRunning() { <ide> t.Fatalf("/bin/cat should still be running after closing stdin (tty mode)") <ide> } <ide> } <ide> func TestRunDetach(t *testing.T) { <ide> closeWrap(stdin, stdinPipe, stdout, stdoutPipe) <ide> <ide> time.Sleep(500 * time.Millisecond) <del> if !container.State.IsRunning() { <add> if !container.IsRunning() { <ide> t.Fatal("The detached container should be still running") <ide> } <ide> <ide> func TestAttachDetach(t *testing.T) { <ide> closeWrap(stdin, stdinPipe, stdout, stdoutPipe) <ide> <ide> time.Sleep(500 * time.Millisecond) <del> if !container.State.IsRunning() { <add> if !container.IsRunning() { <ide> t.Fatal("The detached container should be still running") <ide> } <ide> <ide> func TestAttachDetachTruncatedID(t *testing.T) { <ide> closeWrap(stdin, stdinPipe, stdout, stdoutPipe) <ide> <ide> time.Sleep(500 * time.Millisecond) <del> if !container.State.IsRunning() { <add> if !container.IsRunning() { <ide> t.Fatal("The detached container should be still running") <ide> } <ide> <ide> func TestAttachDisconnect(t *testing.T) { <ide> setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() { <ide> for { <ide> l := globalDaemon.List() <del> if len(l) == 1 && l[0].State.IsRunning() { <add> if len(l) == 1 && l[0].IsRunning() { <ide> break <ide> } <ide> time.Sleep(10 * time.Millisecond) <ide> func TestAttachDisconnect(t *testing.T) { <ide> <ide> // We closed stdin, expect /bin/cat to still be running <ide> // Wait a little bit to make sure container.monitor() did his thing <del> _, err := container.State.WaitStop(500 * time.Millisecond) <del> if err == nil || !container.State.IsRunning() { <add> _, err := container.WaitStop(500 * time.Millisecond) <add> if err == nil || !container.IsRunning() { <ide> t.Fatalf("/bin/cat is not running after closing stdin") <ide> } <ide> <ide> // Try to avoid the timeout in destroy. Best effort, don't check error <ide> cStdin, _ := container.StdinPipe() <ide> cStdin.Close() <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> } <ide> <ide> // Expected behaviour: container gets deleted automatically after exit <ide><path>integration/container_test.go <ide> func TestRestartStdin(t *testing.T) { <ide> if err := stdin.Close(); err != nil { <ide> t.Fatal(err) <ide> } <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> output, err := ioutil.ReadAll(stdout) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestRestartStdin(t *testing.T) { <ide> if err := stdin.Close(); err != nil { <ide> t.Fatal(err) <ide> } <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> output, err = ioutil.ReadAll(stdout) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestStdin(t *testing.T) { <ide> if err := stdin.Close(); err != nil { <ide> t.Fatal(err) <ide> } <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> output, err := ioutil.ReadAll(stdout) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestTty(t *testing.T) { <ide> if err := stdin.Close(); err != nil { <ide> t.Fatal(err) <ide> } <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> output, err := ioutil.ReadAll(stdout) <ide> if err != nil { <ide> t.Fatal(err) <ide> func BenchmarkRunParallel(b *testing.B) { <ide> complete <- err <ide> return <ide> } <del> if _, err := container.State.WaitStop(15 * time.Second); err != nil { <add> if _, err := container.WaitStop(15 * time.Second); err != nil { <ide> complete <- err <ide> return <ide> } <ide><path>integration/runtime_test.go <ide> func startEchoServerContainer(t *testing.T, proto string) (*daemon.Daemon, *daem <ide> } <ide> <ide> setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() { <del> for !container.State.IsRunning() { <add> for !container.IsRunning() { <ide> time.Sleep(10 * time.Millisecond) <ide> } <ide> }) <ide> <ide> // Even if the state is running, lets give some time to lxc to spawn the process <del> container.State.WaitStop(500 * time.Millisecond) <add> container.WaitStop(500 * time.Millisecond) <ide> <ide> strPort = container.NetworkSettings.Ports[p][0].HostPort <ide> return daemon, container, strPort <ide> func TestRestore(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> if !container2.State.IsRunning() { <add> if !container2.IsRunning() { <ide> t.Fatalf("Container %v should appear as running but isn't", container2.ID) <ide> } <ide> <ide> // Simulate a crash/manual quit of dockerd: process dies, states stays 'Running' <ide> cStdin, _ := container2.StdinPipe() <ide> cStdin.Close() <del> if _, err := container2.State.WaitStop(2 * time.Second); err != nil { <add> if _, err := container2.WaitStop(2 * time.Second); err != nil { <ide> t.Fatal(err) <ide> } <del> container2.State.SetRunning(42) <add> container2.SetRunning(42) <ide> container2.ToDisk() <ide> <ide> if len(daemon1.List()) != 2 { <ide> func TestRestore(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> if !container2.State.IsRunning() { <add> if !container2.IsRunning() { <ide> t.Fatalf("Container %v should appear as running but isn't", container2.ID) <ide> } <ide> <ide> func TestRestore(t *testing.T) { <ide> } <ide> runningCount := 0 <ide> for _, c := range daemon2.List() { <del> if c.State.IsRunning() { <add> if c.IsRunning() { <ide> t.Errorf("Running container found: %v (%v)", c.ID, c.Path) <ide> runningCount++ <ide> } <ide> func TestRestore(t *testing.T) { <ide> if err := container3.Run(); err != nil { <ide> t.Fatal(err) <ide> } <del> container2.State.SetStopped(0) <add> container2.SetStopped(0) <ide> } <ide> <ide> func TestDefaultContainerName(t *testing.T) { <ide><path>integration/utils_test.go <ide> func containerAttach(eng *engine.Engine, id string, t log.Fataler) (io.WriteClos <ide> } <ide> <ide> func containerWait(eng *engine.Engine, id string, t log.Fataler) int { <del> ex, _ := getContainer(eng, id, t).State.WaitStop(-1 * time.Second) <add> ex, _ := getContainer(eng, id, t).WaitStop(-1 * time.Second) <ide> return ex <ide> } <ide> <ide> func containerWaitTimeout(eng *engine.Engine, id string, t log.Fataler) error { <del> _, err := getContainer(eng, id, t).State.WaitStop(500 * time.Millisecond) <add> _, err := getContainer(eng, id, t).WaitStop(500 * time.Millisecond) <ide> return err <ide> } <ide> <ide> func containerKill(eng *engine.Engine, id string, t log.Fataler) { <ide> } <ide> <ide> func containerRunning(eng *engine.Engine, id string, t log.Fataler) bool { <del> return getContainer(eng, id, t).State.IsRunning() <add> return getContainer(eng, id, t).IsRunning() <ide> } <ide> <ide> func containerAssertExists(eng *engine.Engine, id string, t log.Fataler) { <ide> func runContainer(eng *engine.Engine, r *daemon.Daemon, args []string, t *testin <ide> return "", err <ide> } <ide> <del> container.State.WaitStop(-1 * time.Second) <add> container.WaitStop(-1 * time.Second) <ide> data, err := ioutil.ReadAll(stdout) <ide> if err != nil { <ide> return "", err
17
Text
Text
update the documentation for fix
c9ca5c4dd3a90332cc40d25175e3b54aca1212a8
<ide><path>docs/sources/reference/commandline/cli.md <ide> The `docker exec` command runs a new command in a running container. <ide> The command started using `docker exec` will only run while the container's primary <ide> process (`PID 1`) is running, and will not be restarted if the container is restarted. <ide> <del>If the container is paused, then the `docker exec` command will wait until the <del>container is unpaused, and then run. <add>If the container is paused, then the `docker exec` command will fail with an error: <add> <add> $ docker pause test <add> test <add> $ docker ps <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 1ae3b36715d2 ubuntu:latest "bash" 17 seconds ago Up 16 seconds (Paused) test <add> $ docker exec test ls <add> FATA[0000] Error response from daemon: Container test is paused, unpause the container before exec <add> $ echo $? <add> 1 <ide> <ide> #### Examples <ide>
1
Go
Go
initialize config with platform-specific defaults
b28e66cf4fd2fb7c7f14d889614f57f3457f585e
<ide><path>cmd/dockerd/config.go <ide> const defaultTrustKeyFile = "key.json" <ide> <ide> // installCommonConfigFlags adds flags to the pflag.FlagSet to configure the daemon <ide> func installCommonConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <del> var err error <del> conf.Pidfile, err = getDefaultPidFile() <del> if err != nil { <del> return err <del> } <del> conf.Root, err = getDefaultDataRoot() <del> if err != nil { <del> return err <del> } <del> conf.ExecRoot, err = getDefaultExecRoot() <del> if err != nil { <del> return err <del> } <del> <ide> var ( <ide> allowNonDistributable = opts.NewNamedListOptsRef("allow-nondistributable-artifacts", &conf.AllowNondistributableArtifacts, registry.ValidateIndexName) <ide> registryMirrors = opts.NewNamedListOptsRef("registry-mirrors", &conf.Mirrors, registry.ValidateMirror) <ide><path>cmd/dockerd/config_unix.go <ide> package main <ide> <ide> import ( <ide> "net" <del> "os/exec" <ide> "path/filepath" <ide> <del> "github.com/containerd/cgroups" <del> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/homedir" <ide> "github.com/docker/docker/registry" <ide> "github.com/docker/docker/rootless" <del> units "github.com/docker/go-units" <del> "github.com/pkg/errors" <ide> "github.com/spf13/pflag" <ide> ) <ide> <ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> return err <ide> } <ide> <del> conf.Ulimits = make(map[string]*units.Ulimit) <del> <del> // Set default value for `--default-shm-size` <del> conf.ShmSize = opts.MemBytes(config.DefaultShmSize) <del> conf.Runtimes = make(map[string]types.Runtime) <del> <ide> // Then platform-specific install flags <ide> flags.Var(opts.NewNamedRuntimeOpt("runtimes", &conf.Runtimes, config.StockRuntimeName), "add-runtime", "Register an additional OCI compatible runtime") <ide> flags.StringVarP(&conf.SocketGroup, "group", "G", "docker", "Group for the unix socket") <ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> flags.BoolVar(&conf.BridgeConfig.InterContainerCommunication, "icc", true, "Enable inter-container communication") <ide> flags.IPVar(&conf.BridgeConfig.DefaultIP, "ip", net.IPv4zero, "Default IP when binding container ports") <ide> flags.BoolVar(&conf.BridgeConfig.EnableUserlandProxy, "userland-proxy", true, "Use userland proxy for loopback traffic") <del> defaultUserlandProxyPath := "" <del> if rootless.RunningWithRootlessKit() { <del> var err error <del> // use rootlesskit-docker-proxy for exposing the ports in RootlessKit netns to the initial namespace. <del> defaultUserlandProxyPath, err = exec.LookPath(rootless.RootlessKitDockerProxyBinary) <del> if err != nil { <del> return errors.Wrapf(err, "running with RootlessKit, but %s not installed", rootless.RootlessKitDockerProxyBinary) <del> } <del> } <del> flags.StringVar(&conf.BridgeConfig.UserlandProxyPath, "userland-proxy-path", defaultUserlandProxyPath, "Path to the userland proxy binary") <add> flags.StringVar(&conf.BridgeConfig.UserlandProxyPath, "userland-proxy-path", conf.BridgeConfig.UserlandProxyPath, "Path to the userland proxy binary") <ide> flags.StringVar(&conf.CgroupParent, "cgroup-parent", "", "Set parent cgroup for all containers") <ide> flags.StringVar(&conf.RemappedRoot, "userns-remap", "", "User/Group setting for user namespaces") <ide> flags.BoolVar(&conf.LiveRestoreEnabled, "live-restore", false, "Enable live restore of docker when containers are still running") <ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> flags.StringVar(&conf.InitPath, "init-path", "", "Path to the docker-init binary") <ide> flags.Int64Var(&conf.CPURealtimePeriod, "cpu-rt-period", 0, "Limit the CPU real-time period in microseconds for the parent cgroup for all containers (not supported with cgroups v2)") <ide> flags.Int64Var(&conf.CPURealtimeRuntime, "cpu-rt-runtime", 0, "Limit the CPU real-time runtime in microseconds for the parent cgroup for all containers (not supported with cgroups v2)") <del> flags.StringVar(&conf.SeccompProfile, "seccomp-profile", config.SeccompProfileDefault, `Path to seccomp profile. Use "unconfined" to disable the default seccomp profile`) <add> flags.StringVar(&conf.SeccompProfile, "seccomp-profile", conf.SeccompProfile, `Path to seccomp profile. Use "unconfined" to disable the default seccomp profile`) <ide> flags.Var(&conf.ShmSize, "default-shm-size", "Default shm size for containers") <ide> flags.BoolVar(&conf.NoNewPrivileges, "no-new-privileges", false, "Set no-new-privileges by default for new containers") <del> flags.StringVar(&conf.IpcMode, "default-ipc-mode", string(config.DefaultIpcMode), `Default mode for containers ipc ("shareable" | "private")`) <add> flags.StringVar(&conf.IpcMode, "default-ipc-mode", conf.IpcMode, `Default mode for containers ipc ("shareable" | "private")`) <ide> flags.Var(&conf.NetworkConfig.DefaultAddressPools, "default-address-pool", "Default address pools for node specific local networks") <ide> // rootless needs to be explicitly specified for running "rootful" dockerd in rootless dockerd (#38702) <del> // Note that defaultUserlandProxyPath and honorXDG are configured according to the value of rootless.RunningWithRootlessKit, not the value of --rootless. <del> flags.BoolVar(&conf.Rootless, "rootless", rootless.RunningWithRootlessKit(), "Enable rootless mode; typically used with RootlessKit") <del> defaultCgroupNamespaceMode := config.DefaultCgroupNamespaceMode <del> if cgroups.Mode() != cgroups.Unified { <del> defaultCgroupNamespaceMode = config.DefaultCgroupV1NamespaceMode <del> } <del> flags.StringVar(&conf.CgroupNamespaceMode, "default-cgroupns-mode", string(defaultCgroupNamespaceMode), `Default mode for containers cgroup namespace ("host" | "private")`) <add> // Note that conf.BridgeConfig.UserlandProxyPath and honorXDG are configured according to the value of rootless.RunningWithRootlessKit, not the value of --rootless. <add> flags.BoolVar(&conf.Rootless, "rootless", conf.Rootless, "Enable rootless mode; typically used with RootlessKit") <add> flags.StringVar(&conf.CgroupNamespaceMode, "default-cgroupns-mode", conf.CgroupNamespaceMode, `Default mode for containers cgroup namespace ("host" | "private")`) <ide> return nil <ide> } <ide> <ide> func configureCertsDir() { <ide> } <ide> } <ide> } <del> <del>func getDefaultPidFile() (string, error) { <del> if !honorXDG { <del> return "/var/run/docker.pid", nil <del> } <del> runtimeDir, err := homedir.GetRuntimeDir() <del> if err != nil { <del> return "", err <del> } <del> return filepath.Join(runtimeDir, "docker.pid"), nil <del>} <del> <del>func getDefaultDataRoot() (string, error) { <del> if !honorXDG { <del> return "/var/lib/docker", nil <del> } <del> dataHome, err := homedir.GetDataHome() <del> if err != nil { <del> return "", err <del> } <del> return filepath.Join(dataHome, "docker"), nil <del>} <del> <del>func getDefaultExecRoot() (string, error) { <del> if !honorXDG { <del> return "/var/run/docker", nil <del> } <del> runtimeDir, err := homedir.GetRuntimeDir() <del> if err != nil { <del> return "", err <del> } <del> return filepath.Join(runtimeDir, "docker"), nil <del>} <ide><path>cmd/dockerd/config_unix_test.go <ide> import ( <ide> func TestDaemonParseShmSize(t *testing.T) { <ide> flags := pflag.NewFlagSet("test", pflag.ContinueOnError) <ide> <del> conf := &config.Config{} <del> err := installConfigFlags(conf, flags) <add> conf, err := config.New() <add> assert.NilError(t, err) <add> err = installConfigFlags(conf, flags) <ide> assert.NilError(t, err) <ide> // By default `--default-shm-size=64M` <ide> assert.Check(t, is.Equal(int64(64*1024*1024), conf.ShmSize.Value())) <ide><path>cmd/dockerd/config_windows.go <ide> package main <ide> <ide> import ( <del> "os" <del> "path/filepath" <del> <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/spf13/pflag" <ide> ) <ide> <del>func getDefaultPidFile() (string, error) { <del> return "", nil <del>} <del> <del>func getDefaultDataRoot() (string, error) { <del> return filepath.Join(os.Getenv("programdata"), "docker"), nil <del>} <del> <del>func getDefaultExecRoot() (string, error) { <del> return filepath.Join(os.Getenv("programdata"), "docker", "exec-root"), nil <del>} <del> <ide> // installConfigFlags adds flags to the pflag.FlagSet to configure the daemon <ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> // First handle install flags which are consistent cross-platform <ide><path>cmd/dockerd/docker.go <ide> var ( <ide> ) <ide> <ide> func newDaemonCommand() (*cobra.Command, error) { <del> opts := newDaemonOptions(config.New()) <add> cfg, err := config.New() <add> if err != nil { <add> return nil, err <add> } <add> opts := newDaemonOptions(cfg) <ide> <ide> cmd := &cobra.Command{ <ide> Use: "dockerd [OPTIONS]", <ide><path>daemon/config/config.go <ide> func (conf *Config) IsValueSet(name string) bool { <ide> return ok <ide> } <ide> <del>// New returns a new fully initialized Config struct <del>func New() *Config { <del> return &Config{ <add>// New returns a new fully initialized Config struct with default values set. <add>func New() (*Config, error) { <add> // platform-agnostic default values for the Config. <add> cfg := &Config{ <ide> CommonConfig: CommonConfig{ <ide> ShutdownTimeout: DefaultShutdownTimeout, <ide> LogConfig: LogConfig{ <ide> func New() *Config { <ide> DefaultRuntime: StockRuntimeName, <ide> }, <ide> } <add> <add> if err := setPlatformDefaults(cfg); err != nil { <add> return nil, err <add> } <add> <add> return cfg, nil <ide> } <ide> <ide> // GetConflictFreeLabels validates Labels for conflict <ide> func Reload(configFile string, flags *pflag.FlagSet, reload func(*Config)) error <ide> if flags.Changed("config-file") || !os.IsNotExist(err) { <ide> return errors.Wrapf(err, "unable to configure the Docker daemon with file %s", configFile) <ide> } <del> newConfig = New() <add> newConfig, err = New() <add> if err != nil { <add> return err <add> } <ide> } <ide> <ide> // Check if duplicate label-keys with different values are found <ide><path>daemon/config/config_linux.go <ide> package config // import "github.com/docker/docker/daemon/config" <ide> import ( <ide> "fmt" <ide> "net" <add> "os/exec" <add> "path/filepath" <ide> <add> "github.com/containerd/cgroups" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/opts" <add> "github.com/docker/docker/pkg/homedir" <add> "github.com/docker/docker/rootless" <ide> units "github.com/docker/go-units" <add> "github.com/pkg/errors" <ide> ) <ide> <ide> const ( <ide> func (conf *Config) ValidatePlatformConfig() error { <ide> func (conf *Config) IsRootless() bool { <ide> return conf.Rootless <ide> } <add> <add>func setPlatformDefaults(cfg *Config) error { <add> cfg.Ulimits = make(map[string]*units.Ulimit) <add> cfg.ShmSize = opts.MemBytes(DefaultShmSize) <add> cfg.SeccompProfile = SeccompProfileDefault <add> cfg.IpcMode = string(DefaultIpcMode) <add> cfg.Runtimes = make(map[string]types.Runtime) <add> <add> if cgroups.Mode() != cgroups.Unified { <add> cfg.CgroupNamespaceMode = string(DefaultCgroupV1NamespaceMode) <add> } else { <add> cfg.CgroupNamespaceMode = string(DefaultCgroupNamespaceMode) <add> } <add> <add> if rootless.RunningWithRootlessKit() { <add> cfg.Rootless = true <add> <add> var err error <add> // use rootlesskit-docker-proxy for exposing the ports in RootlessKit netns to the initial namespace. <add> cfg.BridgeConfig.UserlandProxyPath, err = exec.LookPath(rootless.RootlessKitDockerProxyBinary) <add> if err != nil { <add> return errors.Wrapf(err, "running with RootlessKit, but %s not installed", rootless.RootlessKitDockerProxyBinary) <add> } <add> <add> dataHome, err := homedir.GetDataHome() <add> if err != nil { <add> return err <add> } <add> runtimeDir, err := homedir.GetRuntimeDir() <add> if err != nil { <add> return err <add> } <add> <add> cfg.Root = filepath.Join(dataHome, "docker") <add> cfg.ExecRoot = filepath.Join(runtimeDir, "docker") <add> cfg.Pidfile = filepath.Join(runtimeDir, "docker.pid") <add> } else { <add> cfg.Root = "/var/lib/docker" <add> cfg.ExecRoot = "/var/run/docker" <add> cfg.Pidfile = "/var/run/docker.pid" <add> } <add> <add> return nil <add>} <ide><path>daemon/config/config_linux_test.go <ide> func TestDaemonConfigurationMerge(t *testing.T) { <ide> file := fs.NewFile(t, "docker-config", fs.WithContent(configFileData)) <ide> defer file.Remove() <ide> <del> conf := New() <add> conf, err := New() <add> assert.NilError(t, err) <ide> <ide> flags := pflag.NewFlagSet("test", pflag.ContinueOnError) <ide> flags.BoolVarP(&conf.Debug, "debug", "D", false, "") <ide><path>daemon/config/config_test.go <ide> func TestValidateConfigurationErrors(t *testing.T) { <ide> } <ide> for _, tc := range testCases { <ide> t.Run(tc.name, func(t *testing.T) { <del> cfg := New() <add> cfg, err := New() <add> assert.NilError(t, err) <ide> if tc.field != "" { <ide> assert.Check(t, mergo.Merge(cfg, tc.config, mergo.WithOverride, withForceOverwrite(tc.field))) <ide> } else { <ide> assert.Check(t, mergo.Merge(cfg, tc.config, mergo.WithOverride)) <ide> } <del> err := Validate(cfg) <add> err = Validate(cfg) <ide> assert.Error(t, err, tc.expectedErr) <ide> }) <ide> } <ide> func TestValidateConfiguration(t *testing.T) { <ide> for _, tc := range testCases { <ide> t.Run(tc.name, func(t *testing.T) { <ide> // Start with a config with all defaults set, so that we only <del> cfg := New() <add> cfg, err := New() <add> assert.NilError(t, err) <ide> assert.Check(t, mergo.Merge(cfg, tc.config, mergo.WithOverride)) <ide> <ide> // Check that the override happened :) <ide> assert.Check(t, is.DeepEqual(cfg, tc.config, field(tc.field))) <del> err := Validate(cfg) <add> err = Validate(cfg) <ide> assert.NilError(t, err) <ide> }) <ide> } <ide><path>daemon/config/config_windows.go <ide> package config // import "github.com/docker/docker/daemon/config" <ide> <ide> import ( <add> "os" <add> "path/filepath" <add> <ide> "github.com/docker/docker/api/types" <ide> ) <ide> <ide> func (conf *Config) ValidatePlatformConfig() error { <ide> func (conf *Config) IsRootless() bool { <ide> return false <ide> } <add> <add>func setPlatformDefaults(cfg *Config) error { <add> cfg.Root = filepath.Join(os.Getenv("programdata"), "docker") <add> cfg.ExecRoot = filepath.Join(os.Getenv("programdata"), "docker", "exec-root") <add> cfg.Pidfile = filepath.Join(cfg.Root, "docker.pid") <add> return nil <add>} <ide><path>daemon/config/config_windows_test.go <ide> func TestDaemonConfigurationMerge(t *testing.T) { <ide> <ide> f.Close() <ide> <del> conf := New() <add> conf, err := New() <add> assert.NilError(t, err) <ide> <ide> flags := pflag.NewFlagSet("test", pflag.ContinueOnError) <ide> flags.BoolVarP(&conf.Debug, "debug", "D", false, "") <ide><path>daemon/runtime_unix_test.go <ide> func TestGetRuntime(t *testing.T) { <ide> const configuredRtName = "my/custom.shim.v1" <ide> configuredRuntime := types.Runtime{Path: "/bin/true"} <ide> <del> d := &Daemon{configStore: config.New()} <add> cfg, err := config.New() <add> assert.NilError(t, err) <add> <add> d := &Daemon{configStore: cfg} <ide> d.configStore.Root = t.TempDir() <ide> assert.Assert(t, os.Mkdir(filepath.Join(d.configStore.Root, "runtimes"), 0700)) <ide> d.configStore.Runtimes = map[string]types.Runtime{
12
Javascript
Javascript
drop module.hot from production bundles
662dfd42716ae2c2a4043321f2552f0166a7c2be
<ide><path>packages/next/client/page-loader.js <ide> function supportsPreload (list) { <ide> } <ide> <ide> const hasPreload = supportsPreload(document.createElement('link').relList) <del>const webpackModule = module <ide> <ide> export default class PageLoader { <ide> constructor (buildId, assetPrefix) { <ide> export default class PageLoader { <ide> } <ide> } <ide> <del> // Wait for webpack to become idle if it's not. <del> // More info: https://github.com/zeit/next.js/pull/1511 <del> if (webpackModule && webpackModule.hot && webpackModule.hot.status() !== 'idle') { <del> console.log(`Waiting for webpack to become "idle" to initialize the page: "${route}"`) <del> <del> const check = (status) => { <del> if (status === 'idle') { <del> webpackModule.hot.removeStatusHandler(check) <del> register() <add> if (process.env.NODE_ENV !== 'production') { <add> // Wait for webpack to become idle if it's not. <add> // More info: https://github.com/zeit/next.js/pull/1511 <add> if (module.hot && module.hot.status() !== 'idle') { <add> console.log(`Waiting for webpack to become "idle" to initialize the page: "${route}"`) <add> <add> const check = (status) => { <add> if (status === 'idle') { <add> module.hot.removeStatusHandler(check) <add> register() <add> } <ide> } <add> module.hot.status(check) <add> return <ide> } <del> webpackModule.hot.status(check) <del> } else { <del> register() <ide> } <add> <add> register() <ide> } <ide> <ide> async prefetch (route) {
1
Python
Python
remove lines causing a keyerror
adb8c93134f02fd0eac2b52189364af21977004c
<ide><path>examples/run_tf_glue.py <ide> inputs_1 = tokenizer.encode_plus(sentence_0, sentence_1, add_special_tokens=True, return_tensors="pt") <ide> inputs_2 = tokenizer.encode_plus(sentence_0, sentence_2, add_special_tokens=True, return_tensors="pt") <ide> <del> del inputs_1["special_tokens_mask"] <del> del inputs_2["special_tokens_mask"] <del> <ide> pred_1 = pytorch_model(**inputs_1)[0].argmax().item() <ide> pred_2 = pytorch_model(**inputs_2)[0].argmax().item() <ide> print("sentence_1 is", "a paraphrase" if pred_1 else "not a paraphrase", "of sentence_0")
1
Javascript
Javascript
increase usage of assert.iferror()
746a46ebddf594370137042b9b3a0af80daff903
<ide><path>test/disabled/test-dgram-send-error.js <ide> function onMessage(message, info) { <ide> } <ide> <ide> function afterSend(err) { <del> if (err) throw err; <add> assert.ifError(err); <ide> packetsSent++; <ide> } <ide> <ide><path>test/gc/node_modules/nan/tools/1to2.js <ide> groups.push([1, ['(', [ <ide> /* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */ <ide> groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']); <ide> <del>/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ <add>/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ <ide> groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); <ide> <ide> /* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */ <ide><path>test/internet/test-dgram-broadcast-multi-process.js <ide> if (process.argv[2] !== 'child') { <ide> common.PORT, <ide> LOCAL_BROADCAST_HOST, <ide> function(err) { <del> if (err) throw err; <add> assert.ifError(err); <ide> console.error('[PARENT] sent %s to %s:%s', <ide> util.inspect(buf.toString()), <ide> LOCAL_BROADCAST_HOST, common.PORT); <ide><path>test/internet/test-dgram-multicast-multi-process.js <ide> if (process.argv[2] !== 'child') { <ide> common.PORT, <ide> LOCAL_BROADCAST_HOST, <ide> function(err) { <del> if (err) throw err; <add> assert.ifError(err); <ide> console.error('[PARENT] sent "%s" to %s:%s', <ide> buf.toString(), <ide> LOCAL_BROADCAST_HOST, common.PORT); <ide><path>test/internet/test-dns-ipv6.js <ide> TEST(function test_lookup_ipv6_explicit(done) { <ide> /* This ends up just being too problematic to test <ide> TEST(function test_lookup_ipv6_implicit(done) { <ide> var req = dns.lookup('ipv6.google.com', function(err, ip, family) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.ok(net.isIPv6(ip)); <ide> assert.strictEqual(family, 6); <ide> <ide> TEST(function test_lookupservice_ip_ipv6(done) { <ide> /* Disabled because it appears to be not working on linux. */ <ide> /* TEST(function test_lookup_localhost_ipv6(done) { <ide> var req = dns.lookup('localhost', 6, function(err, ip, family) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.ok(net.isIPv6(ip)); <ide> assert.strictEqual(family, 6); <ide> <ide><path>test/internet/test-dns.js <ide> TEST(function test_resolve6_ttl(done) { <ide> <ide> TEST(function test_resolveMx(done) { <ide> var req = dns.resolveMx('gmail.com', function(err, result) { <del> if (err) throw err; <del> <add> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> for (var i = 0; i < result.length; i++) { <ide> TEST(function test_resolveMx_failure(done) { <ide> <ide> TEST(function test_resolveNs(done) { <ide> var req = dns.resolveNs('rackspace.com', function(err, names) { <del> if (err) throw err; <del> <add> assert.ifError(err); <ide> assert.ok(names.length > 0); <ide> <ide> for (var i = 0; i < names.length; i++) { <ide> TEST(function test_resolveNs_failure(done) { <ide> <ide> TEST(function test_resolveSrv(done) { <ide> var req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { <del> if (err) throw err; <del> <add> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> for (var i = 0; i < result.length; i++) { <ide> TEST(function test_resolveSrv_failure(done) { <ide> <ide> TEST(function test_resolvePtr(done) { <ide> var req = dns.resolvePtr('8.8.8.8.in-addr.arpa', function(err, result) { <del> if (err) throw err; <del> <add> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> for (var i = 0; i < result.length; i++) { <ide> TEST(function test_resolvePtr_failure(done) { <ide> <ide> TEST(function test_resolveNaptr(done) { <ide> var req = dns.resolveNaptr('sip2sip.info', function(err, result) { <del> if (err) throw err; <del> <add> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> for (var i = 0; i < result.length; i++) { <ide> TEST(function test_resolveNaptr_failure(done) { <ide> <ide> TEST(function test_resolveSoa(done) { <ide> var req = dns.resolveSoa('nodejs.org', function(err, result) { <del> if (err) throw err; <del> <add> assert.ifError(err); <ide> assert.ok(result); <ide> assert.strictEqual(typeof result, 'object'); <ide> <ide> TEST(function test_resolveSoa_failure(done) { <ide> <ide> TEST(function test_resolveCname(done) { <ide> var req = dns.resolveCname('www.microsoft.com', function(err, names) { <del> if (err) throw err; <del> <add> assert.ifError(err); <ide> assert.ok(names.length > 0); <ide> <ide> for (var i = 0; i < names.length; i++) { <ide> TEST(function test_resolveCname_failure(done) { <ide> <ide> TEST(function test_resolveTxt(done) { <ide> var req = dns.resolveTxt('google.com', function(err, records) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.strictEqual(records.length, 1); <ide> assert.ok(util.isArray(records[0])); <ide> assert.strictEqual(records[0][0].indexOf('v=spf1'), 0); <ide> TEST(function test_lookup_failure(done) { <ide> <ide> TEST(function test_lookup_null(done) { <ide> var req = dns.lookup(null, function(err, ip, family) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.strictEqual(ip, null); <ide> assert.strictEqual(family, 4); <ide> <ide> TEST(function test_lookup_null(done) { <ide> <ide> TEST(function test_lookup_ip_all(done) { <ide> var req = dns.lookup('127.0.0.1', {all: true}, function(err, ips, family) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.ok(Array.isArray(ips)); <ide> assert.ok(ips.length > 0); <ide> assert.strictEqual(ips[0].address, '127.0.0.1'); <ide> TEST(function test_lookup_ip_all(done) { <ide> <ide> TEST(function test_lookup_null_all(done) { <ide> var req = dns.lookup(null, {all: true}, function(err, ips, family) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.ok(Array.isArray(ips)); <ide> assert.strictEqual(ips.length, 0); <ide> <ide> TEST(function test_lookup_null_all(done) { <ide> <ide> TEST(function test_lookup_all_mixed(done) { <ide> var req = dns.lookup('www.google.com', {all: true}, function(err, ips) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.ok(Array.isArray(ips)); <ide> assert.ok(ips.length > 0); <ide> <ide><path>test/parallel/test-child-process-fork-dgram.js <ide> if (process.argv[2] === 'child') { <ide> serverPort, <ide> '127.0.0.1', <ide> function(err) { <del> if (err) throw err; <add> assert.ifError(err); <ide> } <ide> ); <ide> } <ide><path>test/parallel/test-domain-implicit-fs.js <ide> d.run(function() { <ide> var fs = require('fs'); <ide> fs.readdir(__dirname, function() { <ide> fs.open('this file does not exist', 'r', function(er) { <del> if (er) throw er; <add> assert.ifError(er); <ide> throw new Error('should not get here!'); <ide> }); <ide> }); <ide><path>test/parallel/test-fs-buffer.js <ide> common.refreshTmpDir(); <ide> <ide> assert.doesNotThrow(() => { <ide> fs.access(Buffer.from(common.tmpDir), common.mustCall((err) => { <del> if (err) throw err; <add> assert.ifError(err); <ide> })); <ide> }); <ide> <ide> assert.doesNotThrow(() => { <ide> const buf = Buffer.from(path.join(common.tmpDir, 'a.txt')); <ide> fs.open(buf, 'w+', common.mustCall((err, fd) => { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert(fd); <ide> fs.close(fd, common.mustCall(() => { <ide> fs.unlinkSync(buf); <ide> assert.throws(() => { <ide> <ide> const dir = Buffer.from(common.fixturesDir); <ide> fs.readdir(dir, 'hex', common.mustCall((err, list) => { <del> if (err) throw err; <add> assert.ifError(err); <ide> list = list.map((i) => { <ide> return Buffer.from(i, 'hex').toString(); <ide> }); <ide> fs.readdir(dir, common.mustCall((err, list2) => { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.deepStrictEqual(list, list2); <ide> })); <ide> })); <ide><path>test/parallel/test-fs-link.js <ide> const dstPath = path.join(common.tmpDir, 'link1.js'); <ide> fs.writeFileSync(srcPath, 'hello world'); <ide> <ide> const callback = function(err) { <del> if (err) throw err; <add> assert.ifError(err); <ide> const dstContent = fs.readFileSync(dstPath, 'utf8'); <ide> assert.strictEqual('hello world', dstContent); <ide> }; <ide><path>test/parallel/test-fs-readdir-ucs2.js <ide> const fullpath = Buffer.concat([root, filebuff]); <ide> fs.closeSync(fs.openSync(fullpath, 'w+')); <ide> <ide> fs.readdir(common.tmpDir, 'ucs2', (err, list) => { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.equal(1, list.length); <ide> const fn = list[0]; <ide> assert.deepStrictEqual(filebuff, Buffer.from(fn, 'ucs2')); <ide><path>test/parallel/test-fs-readfile-fd.js <ide> tempFdSync(function(fd) { <ide> <ide> function tempFd(callback) { <ide> fs.open(fn, 'r', function(err, fd) { <del> if (err) throw err; <del> <add> assert.ifError(err); <ide> callback(fd, function() { <ide> fs.close(fd, function(err) { <del> if (err) throw err; <add> assert.ifError(err); <ide> }); <ide> }); <ide> }); <ide><path>test/parallel/test-fs-readfile-pipe-large.js <ide> const fs = require('fs'); <ide> <ide> if (process.argv[2] === 'child') { <ide> fs.readFile('/dev/stdin', function(er, data) { <del> if (er) throw er; <add> assert.ifError(er); <ide> process.stdout.write(data); <ide> }); <ide> return; <ide> const f = JSON.stringify(__filename); <ide> const node = JSON.stringify(process.execPath); <ide> const cmd = `cat ${filename} | ${node} ${f} child`; <ide> exec(cmd, { maxBuffer: 1000000 }, function(err, stdout, stderr) { <del> if (err) console.error(err); <del> assert(!err, 'it exits normally'); <add> assert.ifError(err); <ide> assert.strictEqual(stdout, dataExpected, 'it reads the file and outputs it'); <ide> assert.strictEqual(stderr, '', 'it does not write to stderr'); <ide> console.log('ok'); <ide><path>test/parallel/test-fs-readfile-pipe.js <ide> const f = JSON.stringify(__filename); <ide> const node = JSON.stringify(process.execPath); <ide> const cmd = `cat ${f} | ${node} ${f} child`; <ide> exec(cmd, function(err, stdout, stderr) { <del> if (err) console.error(err); <del> assert(!err, 'it exits normally'); <add> assert.ifError(err); <ide> assert.strictEqual(stdout, dataExpected, 'it reads the file and outputs it'); <ide> assert.strictEqual(stderr, '', 'it does not write to stderr'); <ide> console.log('ok'); <ide><path>test/parallel/test-fs-readfilesync-pipe-large.js <ide> const f = JSON.stringify(__filename); <ide> const node = JSON.stringify(process.execPath); <ide> const cmd = `cat ${filename} | ${node} ${f} child`; <ide> exec(cmd, { maxBuffer: 1000000 }, function(err, stdout, stderr) { <del> if (err) console.error(err); <del> assert(!err, 'it exits normally'); <add> assert.ifError(err); <ide> assert.strictEqual(stdout, dataExpected, 'it reads the file and outputs it'); <ide> assert.strictEqual(stderr, '', 'it does not write to stderr'); <ide> console.log('ok'); <ide><path>test/parallel/test-fs-realpath-buffer-encoding.js <ide> for (encoding in expected) { <ide> const expected_value = expected[encoding]; <ide> <ide> fs.realpath(string_dir, {encoding: encoding}, common.mustCall((err, res) => { <del> assert(!err); <add> assert.ifError(err); <ide> assert.strictEqual(res, expected_value); <ide> })); <ide> fs.realpath(string_dir, encoding, common.mustCall((err, res) => { <del> assert(!err); <add> assert.ifError(err); <ide> assert.strictEqual(res, expected_value); <ide> })); <ide> fs.realpath(buffer_dir, {encoding: encoding}, common.mustCall((err, res) => { <del> assert(!err); <add> assert.ifError(err); <ide> assert.strictEqual(res, expected_value); <ide> })); <ide> fs.realpath(buffer_dir, encoding, common.mustCall((err, res) => { <del> assert(!err); <add> assert.ifError(err); <ide> assert.strictEqual(res, expected_value); <ide> })); <ide> } <ide> <ide> fs.realpath(string_dir, {encoding: 'buffer'}, common.mustCall((err, res) => { <del> assert(!err); <add> assert.ifError(err); <ide> assert.deepStrictEqual(res, buffer_dir); <ide> })); <ide> <ide> fs.realpath(string_dir, 'buffer', common.mustCall((err, res) => { <del> assert(!err); <add> assert.ifError(err); <ide> assert.deepStrictEqual(res, buffer_dir); <ide> })); <ide> <ide> fs.realpath(buffer_dir, {encoding: 'buffer'}, common.mustCall((err, res) => { <del> assert(!err); <add> assert.ifError(err); <ide> assert.deepStrictEqual(res, buffer_dir); <ide> })); <ide> <ide> fs.realpath(buffer_dir, 'buffer', common.mustCall((err, res) => { <del> assert(!err); <add> assert.ifError(err); <ide> assert.deepStrictEqual(res, buffer_dir); <ide> })); <ide><path>test/parallel/test-fs-realpath-on-substed-drive.js <ide> assert(Buffer.isBuffer(result)); <ide> assert(result.equals(filenameBuffer)); <ide> <ide> fs.realpath(filename, common.mustCall(function(err, result) { <del> assert(!err); <add> assert.ifError(err); <ide> assert.strictEqual(result, filename); <ide> })); <ide> <ide> fs.realpath(filename, 'buffer', common.mustCall(function(err, result) { <del> assert(!err); <add> assert.ifError(err); <ide> assert(Buffer.isBuffer(result)); <ide> assert(result.equals(filenameBuffer)); <ide> })); <ide><path>test/parallel/test-fs-realpath.js <ide> function test_up_multiple(cb) { <ide> assertEqualPath(fs.realpathSync(abedabeda), abedabeda_real); <ide> assertEqualPath(fs.realpathSync(abedabed), abedabed_real); <ide> fs.realpath(abedabeda, function(er, real) { <del> if (er) throw er; <add> assert.ifError(er); <ide> assertEqualPath(abedabeda_real, real); <ide> fs.realpath(abedabed, function(er, real) { <del> if (er) throw er; <add> assert.ifError(er); <ide> assertEqualPath(abedabed_real, real); <ide> cb(); <ide> cleanup(); <ide> const tests = [ <ide> const numtests = tests.length; <ide> var testsRun = 0; <ide> function runNextTest(err) { <del> if (err) throw err; <add> assert.ifError(err); <ide> const test = tests.shift(); <ide> if (!test) { <ide> return console.log(numtests + <ide><path>test/parallel/test-fs-truncate.js <ide> fs.closeSync(fd); <ide> <ide> // async tests <ide> testTruncate(common.mustCall(function(er) { <del> if (er) throw er; <add> assert.ifError(er); <ide> testFtruncate(common.mustCall(function(er) { <del> if (er) throw er; <add> assert.ifError(er); <ide> })); <ide> })); <ide> <ide><path>test/parallel/test-fs-write-stream-autoclose-option.js <ide> function next() { <ide> function next2() { <ide> // This will test if after reusing the fd data is written properly <ide> fs.readFile(file, function(err, data) { <del> assert(!err); <add> assert.ifError(err); <ide> assert.strictEqual(data.toString(), 'Test2'); <ide> process.nextTick(common.mustCall(next3)); <ide> }); <ide><path>test/parallel/test-fs-write-string-coerce.js <ide> var data = true; <ide> var expected = data + ''; <ide> <ide> fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { <del> if (err) throw err; <add> assert.ifError(err); <ide> console.log('open done'); <ide> fs.write(fd, data, 0, 'utf8', common.mustCall(function(err, written) { <ide> console.log('write done'); <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.equal(Buffer.byteLength(expected), written); <ide> fs.closeSync(fd); <ide> const found = fs.readFileSync(fn, 'utf8'); <ide><path>test/parallel/test-fs-write.js <ide> const constants = fs.constants; <ide> common.refreshTmpDir(); <ide> <ide> fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { <del> if (err) throw err; <add> assert.ifError(err); <ide> console.log('open done'); <ide> fs.write(fd, '', 0, 'utf8', function(err, written) { <ide> assert.strictEqual(0, written); <ide> }); <ide> fs.write(fd, expected, 0, 'utf8', common.mustCall(function(err, written) { <ide> console.log('write done'); <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.strictEqual(Buffer.byteLength(expected), written); <ide> fs.closeSync(fd); <ide> const found = fs.readFileSync(fn, 'utf8'); <ide> fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { <ide> <ide> fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0o644, <ide> common.mustCall((err, fd) => { <del> if (err) throw err; <add> assert.ifError(err); <ide> console.log('open done'); <ide> fs.write(fd, '', 0, 'utf8', (err, written) => { <ide> assert.strictEqual(0, written); <ide> }); <ide> fs.write(fd, expected, 0, 'utf8', common.mustCall((err, written) => { <ide> console.log('write done'); <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.strictEqual(Buffer.byteLength(expected), written); <ide> fs.closeSync(fd); <ide> const found = fs.readFileSync(fn2, 'utf8'); <ide><path>test/parallel/test-http-chunk-problem.js <ide> function executeRequest(cb) { <ide> __filename, <ide> 'shasum' ].join(' '), <ide> (err, stdout, stderr) => { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a', <ide> stdout.slice(0, 40)); <ide> cb(); <ide> common.refreshTmpDir(); <ide> const ddcmd = common.ddCommand(filename, 10240); <ide> <ide> cp.exec(ddcmd, function(err, stdout, stderr) { <del> if (err) throw err; <add> assert.ifError(err); <ide> server = http.createServer(function(req, res) { <ide> res.writeHead(200); <ide> <ide><path>test/parallel/test-http-host-headers.js <ide> function testHttp() { <ide> <ide> httpServer.listen(0, function(er) { <ide> console.error(`test http server listening on ${this.address().port}`); <del> <del> if (er) throw er; <del> <add> assert.ifError(er); <ide> http.get({ <ide> method: 'GET', <ide> path: '/' + (counter++), <ide><path>test/parallel/test-https-host-headers.js <ide> function testHttps() { <ide> <ide> httpsServer.listen(0, function(er) { <ide> console.log(`test https server listening on port ${this.address().port}`); <del> <del> if (er) throw er; <del> <add> assert.ifError(er); <ide> https.get({ <ide> method: 'GET', <ide> path: '/' + (counter++), <ide><path>test/parallel/test-pipe-file-to-http.js <ide> server.on('listening', function() { <ide> const cmd = common.ddCommand(filename, 10240); <ide> <ide> cp.exec(cmd, function(err) { <del> if (err) throw err; <add> assert.ifError(err); <ide> makeRequest(); <ide> }); <ide> }); <ide><path>test/parallel/test-preload.js <ide> childProcess.exec(nodeBinary + ' ' + <ide> preloadOption([fixtureA]) + ' ' + <ide> fixtureB, <ide> function(err, stdout, stderr) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.strictEqual(stdout, 'A\nB\n'); <ide> }); <ide> <ide> childProcess.exec(nodeBinary + ' ' + <ide> preloadOption([fixtureA, fixtureB]) + ' ' + <ide> fixtureC, <ide> function(err, stdout, stderr) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.strictEqual(stdout, 'A\nB\nC\n'); <ide> }); <ide> <ide> childProcess.exec(nodeBinary + ' ' + <ide> preloadOption([fixtureA]) + <ide> '-e "console.log(\'hello\');"', <ide> function(err, stdout, stderr) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.strictEqual(stdout, 'A\nhello\n'); <ide> }); <ide> <ide> childProcess.exec(nodeBinary + ' ' + <ide> '-e "console.log(\'hello\');" ' + <ide> preloadOption([fixtureA, fixtureB]), <ide> function(err, stdout, stderr) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.strictEqual(stdout, 'A\nB\nhello\n'); <ide> }); <ide> <ide> childProcess.exec(nodeBinary + ' ' + <ide> '--require ' + fixture('cluster-preload.js') + ' ' + <ide> fixture('cluster-preload-test.js'), <ide> function(err, stdout, stderr) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.ok(/worker terminated with code 43/.test(stdout)); <ide> }); <ide> <ide> childProcess.exec(nodeBinary + ' ' + <ide> '--require ' + fixture('cluster-preload.js') + ' ' + <ide> 'cluster-preload-test.js', <ide> function(err, stdout, stderr) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert.ok(/worker terminated with code 43/.test(stdout)); <ide> }); <ide><path>test/parallel/test-process-getgroups.js <ide> if (typeof process.getgroups === 'function') { <ide> assert(Array.isArray(groups)); <ide> assert(groups.length > 0); <ide> exec('id -G', function(err, stdout) { <del> if (err) throw err; <add> assert.ifError(err); <ide> var real_groups = stdout.match(/\d+/g).map(Number); <ide> assert.equal(groups.length, real_groups.length); <ide> check(groups, real_groups); <ide><path>test/parallel/test-regress-GH-3739.js <ide> assert(common.fileExists(dir), 'Directory is not accessible'); <ide> <ide> // Test if file exists asynchronously <ide> fs.access(dir, function(err) { <del> assert(!err, 'Directory is not accessible'); <add> assert.ifError(err); <ide> }); <ide><path>test/parallel/test-repl-envvars.js <ide> function run(test) { <ide> }; <ide> <ide> REPL.createInternalRepl(env, opts, function(err, repl) { <del> if (err) throw err; <add> assert.ifError(err); <ide> <ide> // The REPL registers 'module' and 'require' globals <ide> common.allowGlobals(repl.context.module, repl.context.require); <ide><path>test/parallel/test-repl-history-perm.js <ide> common.refreshTmpDir(); <ide> const replHistoryPath = path.join(common.tmpDir, '.node_repl_history'); <ide> <ide> const checkResults = common.mustCall(function(err, r) { <del> if (err) <del> throw err; <add> assert.ifError(err); <ide> <ide> // The REPL registers 'module' and 'require' globals <ide> common.allowGlobals(r.context.module, r.context.require); <ide><path>test/parallel/test-stdout-to-file.js <ide> function test(size, useBuffer, cb) { <ide> console.log(`${size} chars to ${tmpFile}...`); <ide> <ide> childProcess.exec(cmd, common.mustCall(function(err) { <del> if (err) throw err; <del> <add> assert.ifError(err); <ide> console.log('done!'); <ide> <ide> var stat = fs.statSync(tmpFile); <ide><path>test/parallel/test-stream-writev.js <ide> function test(decode, uncork, multi, next) { <ide> expectCount++; <ide> var expect = expectCount; <ide> return function(er) { <del> if (er) <del> throw er; <add> assert.ifError(er); <ide> counter++; <ide> assert.equal(counter, expect); <ide> }; <ide><path>test/parallel/test-tls-client-getephemeralkeyinfo.js <ide> function test(size, type, name, next) { <ide> }); <ide> <ide> server.on('close', common.mustCall(function(err) { <del> assert(!err); <add> assert.ifError(err); <ide> if (next) next(); <ide> })); <ide> <ide><path>test/parallel/test-tls-dhe.js <ide> function test(keylen, expectedCipher, cb) { <ide> }); <ide> <ide> server.on('close', function(err) { <del> assert(!err); <add> assert.ifError(err); <ide> if (cb) cb(); <ide> }); <ide> <ide><path>test/parallel/test-tls-ecdh.js <ide> server.listen(0, '127.0.0.1', common.mustCall(function() { <ide> cmd += ' -no_rand_screen'; <ide> <ide> exec(cmd, common.mustCall(function(err, stdout, stderr) { <del> if (err) throw err; <add> assert.ifError(err); <ide> assert(stdout.includes(reply)); <ide> server.close(); <ide> })); <ide><path>test/parallel/test-tls-server-verify.js <ide> function runTest(port, testIndex) { <ide> requestCert: true, <ide> rejectUnauthorized: false <ide> }, function(err) { <del> assert(!err); <add> assert.ifError(err); <ide> c.write('\n_renegotiated\n'); <ide> handleConnection(c); <ide> }); <ide><path>test/parallel/test-tls-set-ciphers.js <ide> server.listen(0, '127.0.0.1', function() { <ide> cmd += ' -no_rand_screen'; <ide> <ide> exec(cmd, function(err, stdout, stderr) { <del> if (err) throw err; <add> assert.ifError(err); <ide> response = stdout; <ide> server.close(); <ide> }); <ide><path>test/parallel/test-zlib-truncated.js <ide> const inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing eli' <ide> { comp: 'deflateRaw', decomp: 'inflateRaw', decompSync: 'inflateRawSync' } <ide> ].forEach(function(methods) { <ide> zlib[methods.comp](inputString, function(err, compressed) { <del> assert(!err); <add> assert.ifError(err); <ide> const truncated = compressed.slice(0, compressed.length / 2); <ide> const toUTF8 = (buffer) => buffer.toString('utf-8'); <ide>
39
PHP
PHP
remove another unused method
5cc2aad07b0fee6459139f24c0f2d711433c643c
<ide><path>Cake/Controller/Controller.php <ide> public function redirect($url, $status = null, $exit = true) { <ide> } <ide> } <ide> <del>/** <del> * Parse beforeRedirect Response <del> * <del> * @param mixed $response Response from beforeRedirect callback <del> * @param string|array $url The same value of beforeRedirect <del> * @param integer $status The same value of beforeRedirect <del> * @param boolean $exit The same value of beforeRedirect <del> * @return array Array with keys url, status and exit <del> */ <del> protected function _parseBeforeRedirect($response, $url, $status, $exit) { <del> if (is_array($response) && array_key_exists(0, $response)) { <del> foreach ($response as $resp) { <del> if (is_array($resp) && isset($resp['url'])) { <del> extract($resp, EXTR_OVERWRITE); <del> } elseif ($resp !== null) { <del> $url = $resp; <del> } <del> } <del> } elseif (is_array($response)) { <del> extract($response, EXTR_OVERWRITE); <del> } <del> return compact('url', 'status', 'exit'); <del> } <del> <ide> /** <ide> * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect() <ide> *
1
PHP
PHP
update docblock with correct spacing
4dd5ff245b9c7ac93816adb1e6e577cb9cac0204
<ide><path>src/Illuminate/Validation/Concerns/ReplacesAttributes.php <ide> protected function replaceDimensions($message, $attribute, $rule, $parameters) <ide> /** <ide> * Replace all place-holders for the starts_with rule. <ide> * <del> * @param string $message <del> * @param string $attribute <del> * @param string $rule <del> * @param array $parameters <add> * @param string $message <add> * @param string $attribute <add> * @param string $rule <add> * @param array $parameters <ide> * @return string <ide> */ <ide> protected function replaceStartsWith($message, $attribute, $rule, $parameters)
1
Python
Python
fix exception causes in four .py files
ddf0191ea43d763c784dcb5f7ab937d8ef1ae0b0
<ide><path>numpy/lib/histograms.py <ide> def _get_bin_edges(a, bins, range, weights): <ide> elif np.ndim(bins) == 0: <ide> try: <ide> n_equal_bins = operator.index(bins) <del> except TypeError: <add> except TypeError as e: <ide> raise TypeError( <del> '`bins` must be an integer, a string, or an array') <add> '`bins` must be an integer, a string, or an array') from e <ide> if n_equal_bins < 1: <ide> raise ValueError('`bins` must be positive, when an integer') <ide> <ide><path>numpy/lib/index_tricks.py <ide> def __getitem__(self, key): <ide> if len(vec) == 3: <ide> trans1d = int(vec[2]) <ide> continue <del> except Exception: <del> raise ValueError("unknown special directive") <add> except Exception as e: <add> raise ValueError("unknown special directive {!r}".format(item)) from e <ide> try: <ide> axis = int(item) <ide> continue <ide><path>numpy/lib/shape_base.py <ide> def apply_along_axis(func1d, axis, arr, *args, **kwargs): <ide> # invoke the function on the first item <ide> try: <ide> ind0 = next(inds) <del> except StopIteration: <del> raise ValueError('Cannot apply_along_axis when any iteration dimensions are 0') <add> except StopIteration as e: <add> raise ValueError('Cannot apply_along_axis when any iteration dimensions are 0') from None <ide> res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs)) <ide> <ide> # build a buffer for storing evaluations of func1d. <ide><path>numpy/lib/ufunclike.py <ide> def isposinf(x, out=None): <ide> is_inf = nx.isinf(x) <ide> try: <ide> signbit = ~nx.signbit(x) <del> except TypeError: <add> except TypeError as e: <ide> raise TypeError('This operation is not supported for complex values ' <del> 'because it would be ambiguous.') <add> 'because it would be ambiguous.') from e <ide> else: <ide> return nx.logical_and(is_inf, signbit, out) <ide> <ide> def isneginf(x, out=None): <ide> is_inf = nx.isinf(x) <ide> try: <ide> signbit = nx.signbit(x) <del> except TypeError: <add> except TypeError as e: <ide> raise TypeError('This operation is not supported for complex values ' <del> 'because it would be ambiguous.') <add> 'because it would be ambiguous.') from e <ide> else: <ide> return nx.logical_and(is_inf, signbit, out)
4
Ruby
Ruby
change param name to improve documentation
629bc03bf885f8d1450a28972c5bea630a079e85
<ide><path>activemodel/lib/active_model/errors.rb <ide> def clear <ide> end <ide> <ide> # Do the error messages include an error with key +error+? <del> def include?(error) <del> (v = messages[error]) && v.any? <add> def include?(attribute) <add> (v = messages[attribute]) && v.any? <ide> end <ide> alias :has_key? :include? <ide>
1
Python
Python
add missing space to error message
0b1d504ba21cf917a4f42055aba6bdf91fa5e5d6
<ide><path>keras/engine/input_spec.py <ide> def assert_input_compatibility(input_spec, inputs, layer_name): <ide> if value is not None and shape_as_list[int(axis)] not in {value, None}: <ide> raise ValueError( <ide> f'Input {input_index} of layer "{layer_name}" is ' <del> f'incompatible with the layer: expected axis {axis}' <add> f'incompatible with the layer: expected axis {axis} ' <ide> f'of input shape to have value {value}, ' <ide> f'but received input with shape {display_shape(x.shape)}') <ide> # Check shape.
1
Text
Text
add missing periods to elements in roadmap.md
59aa3b27cad988dc21cafb04504191f94938be58
<ide><path>ROADMAP.md <ide> definitive move, we temporarily won't accept more patches to the Dockerfile synt <ide> reasons: <ide> <ide> - Long term impact of syntax changes is a sensitive matter that require an amount of attention <del>the volume of Engine codebase and activity today doesn't allow us to provide <add>the volume of Engine codebase and activity today doesn't allow us to provide. <ide> - Allowing the Builder to be implemented as a separate utility consuming the Engine's API will <ide> open the door for many possibilities, such as offering alternate syntaxes or DSL for existing <del>languages without cluttering the Engine's codebase <add>languages without cluttering the Engine's codebase. <ide> - A standalone Builder will also offer the opportunity for a better dedicated group of maintainers <del>to own the Dockerfile syntax and decide collectively on the direction to give it <add>to own the Dockerfile syntax and decide collectively on the direction to give it. <ide> - Our experience with official images tend to show that no new instruction or syntax expansion is <ide> *strictly* necessary for the majority of use cases, and although we are aware many things are still <ide> lacking for many, we cannot make it a priority yet for the above reasons.
1
Go
Go
add error checking and error messages
31b883b07641bfab721a05f0a68629c79b74a058
<ide><path>devmapper/deviceset_devmapper.go <ide> package devmapper <ide> <ide> import ( <del> "time" <ide> "encoding/json" <ide> "fmt" <ide> "github.com/dotcloud/docker/utils" <ide> import ( <ide> "strconv" <ide> "sync" <ide> "syscall" <add> "time" <ide> ) <ide> <ide> var ( <ide> func (devices *DeviceSetDM) initDevmapper() error { <ide> // "reg-" stands for "regular file". <ide> // In the future we might use "dev-" for "device file", etc. <ide> devices.devicePrefix = fmt.Sprintf("docker-reg-%d-%d", sysSt.Dev, sysSt.Ino) <del> <add> utils.Debugf("Generated prefix: %s", devices.devicePrefix) <ide> <ide> // Check for the existence of the device <prefix>-pool <ide> utils.Debugf("Checking for existence of the pool '%s'", devices.getPoolName()) <ide> func (devices *DeviceSetDM) initDevmapper() error { <ide> // If the pool doesn't exist, create it <ide> if info.Exists == 0 { <ide> utils.Debugf("Pool doesn't exist. Creating it.") <add> <ide> dataFile, err := AttachLoopDevice(data) <ide> if err != nil { <ide> utils.Debugf("\n--->Err: %s\n", err) <ide> func (devices *DeviceSetDM) waitRemove(hash string) error { <ide> return err <ide> } <ide> i := 0 <del> for ; i<1000; i+=1 { <add> for ; i < 1000; i += 1 { <ide> devinfo, err := getInfo(devname) <ide> if err != nil { <ide> // If there is an error we assume the device doesn't exist. <ide> func (devices *DeviceSetDM) waitClose(hash string) error { <ide> return err <ide> } <ide> i := 0 <del> for ; i<1000; i+=1 { <add> for ; i < 1000; i += 1 { <ide> devinfo, err := getInfo(devname) <ide> if err != nil { <ide> return err <ide> func (devices *DeviceSetDM) byHash(hash string) (devname string, err error) { <ide> return info.Name(), nil <ide> } <ide> <del> <ide> func (devices *DeviceSetDM) Shutdown() error { <ide> utils.Debugf("[deviceset %s] shutdown()", devices.devicePrefix) <ide> defer utils.Debugf("[deviceset %s] shutdown END", devices.devicePrefix) <ide><path>devmapper/devmapper.go <ide> char* attach_loop_device(const char *filename, int *loop_fd_out) <ide> int i, loop_fd, fd, start_index; <ide> char* loopname; <ide> <add> <ide> *loop_fd_out = -1; <ide> <ide> start_index = 0; <ide> char* attach_loop_device(const char *filename, int *loop_fd_out) <ide> loop_fd = -1; <ide> for (i = start_index ; loop_fd < 0 ; i++ ) { <ide> if (sprintf(buf, "/dev/loop%d", i) < 0) { <del> close(fd); <del> perror("sprintf"); <del> return NULL; <add> close(fd); <add> return NULL; <ide> } <ide> <del> if (stat(buf, &st) || !S_ISBLK(st.st_mode)) { <add> if (stat(buf, &st)) { <add> if (!S_ISBLK(st.st_mode)) { <add> fprintf(stderr, "[error] Loopback device %s is not a block device.\n", buf); <add> } else if (errno == ENOENT) { <add> fprintf(stderr, "[error] There are no more loopback device available.\n"); <add> } else { <add> fprintf(stderr, "[error] Unkown error trying to stat the loopback device %s (errno: %d).\n", buf, errno); <add> } <ide> close(fd); <ide> return NULL; <ide> } <ide> <ide> loop_fd = open(buf, O_RDWR); <ide> if (loop_fd < 0 && errno == ENOENT) { <add> fprintf(stderr, "[error] The loopback device %s does not exists.\n", buf); <ide> close(fd); <del> fprintf (stderr, "no available loopback device!"); <ide> return NULL; <del> } else if (loop_fd < 0) <del> continue; <add> } else if (loop_fd < 0) { <add> fprintf(stderr, "[error] Unkown error openning the loopback device %s. (errno: %d)\n", buf, errno); <add> continue; <add> } <ide> <del> if (ioctl (loop_fd, LOOP_SET_FD, (void *)(size_t)fd) < 0) { <add> if (ioctl(loop_fd, LOOP_SET_FD, (void *)(size_t)fd) < 0) { <ide> int errsv = errno; <ide> close(loop_fd); <ide> loop_fd = -1; <ide> if (errsv != EBUSY) { <del> close (fd); <del> fprintf (stderr, "cannot set up loopback device %s: %s", buf, strerror(errsv)); <add> close(fd); <add> fprintf(stderr, "cannot set up loopback device %s: %s", buf, strerror(errsv)); <ide> return NULL; <ide> } <ide> continue; <ide> } <ide> <del> close (fd); <add> close(fd); <ide> <ide> strncpy((char*)loopinfo.lo_file_name, buf, LO_NAME_SIZE); <ide> loopinfo.lo_offset = 0; <ide> loopinfo.lo_flags = LO_FLAGS_AUTOCLEAR; <ide> <ide> if (ioctl(loop_fd, LOOP_SET_STATUS64, &loopinfo) < 0) { <del> perror("ioctl1"); <add> perror("ioctl LOOP_SET_STATUS64"); <ide> if (ioctl(loop_fd, LOOP_CLR_FD, 0) < 0) { <del> perror("ioctl2"); <add> perror("ioctl LOOP_CLR_FD"); <ide> } <ide> close(loop_fd); <ide> fprintf (stderr, "cannot set up loopback device info"); <del> return NULL; <add> return (NULL); <ide> } <ide> <ide> loopname = strdup(buf); <ide> if (loopname == NULL) { <ide> close(loop_fd); <del> return NULL; <add> return (NULL); <ide> } <ide> <ide> *loop_fd_out = loop_fd; <del> return loopname; <add> return (loopname); <ide> } <del> return NULL; <add> <add> return (NULL); <ide> } <ide> <del>static int64_t <del>get_block_size(int fd) <add>static int64_t get_block_size(int fd) <ide> { <del> uint64_t size; <add> uint64_t size; <add> <ide> if (ioctl(fd, BLKGETSIZE64, &size) == -1) <ide> return -1; <del> return (int64_t)size; <add> return ((int64_t)size); <ide> } <ide> <ide> extern void DevmapperLogCallback(int level, char *file, int line, int dm_errno_or_class, char *str); <ide> import ( <ide> "unsafe" <ide> ) <ide> <del>type DevmapperLogger interface { <add>type DevmapperLogger interface { <ide> log(level int, file string, line int, dmError int, message string) <ide> } <ide> <ide> type ( <ide> ReadOnly int <ide> TargetCount int32 <ide> } <del> TaskType int <add> TaskType int <ide> AddNodeType int <ide> ) <ide> <ide> func (t *Task) SetCookie(cookie *uint32, flags uint16) error { <ide> } <ide> <ide> func (t *Task) SetAddNode(add_node AddNodeType) error { <del> if res := C.dm_task_set_add_node(t.unmanaged, C.dm_add_node_t (add_node)); res != 1 { <add> if res := C.dm_task_set_add_node(t.unmanaged, C.dm_add_node_t(add_node)); res != 1 { <ide> return ErrTaskSetAddNode <ide> } <ide> return nil <ide> func AttachLoopDevice(filename string) (*os.File, error) { <ide> res := C.attach_loop_device(c_filename, &fd) <ide> if res == nil { <ide> if os.Getenv("DEBUG") != "" { <del> C.perror(C.CString(fmt.Sprintf("[debug] Error attach_loop_device(%s, $#v)", c_filename, &fd))) <add> C.perror(C.CString(fmt.Sprintf("[debug] Error attach_loop_device(%s, %d)", filename, int(fd)))) <ide> } <ide> return nil, ErrAttachLoopbackDevice <ide> } <ide><path>runtime_test.go <ide> package docker <ide> <ide> import ( <del> "path" <ide> "bytes" <ide> "fmt" <ide> "github.com/dotcloud/docker/devmapper" <ide> import ( <ide> "log" <ide> "net" <ide> "os" <add> "path" <ide> "path/filepath" <ide> "runtime" <ide> "strconv" <ide> import ( <ide> ) <ide> <ide> const ( <del> unitTestImageName = "docker-test-image" <del> unitTestImageID = "83599e29c455eb719f77d799bc7c51521b9551972f5a850d7ad265bc1b5292f6" // 1.0 <del> unitTestNetworkBridge = "testdockbr0" <del> unitTestStoreBase = "/var/lib/docker/unit-tests" <del> testDaemonAddr = "127.0.0.1:4270" <del> testDaemonProto = "tcp" <add> unitTestImageName = "docker-test-image" <add> unitTestImageID = "83599e29c455eb719f77d799bc7c51521b9551972f5a850d7ad265bc1b5292f6" // 1.0 <add> unitTestNetworkBridge = "testdockbr0" <add> unitTestStoreBase = "/var/lib/docker/unit-tests" <add> testDaemonAddr = "127.0.0.1:4270" <add> testDaemonProto = "tcp" <ide> <ide> unitTestDMDataLoopbackSize = 209715200 // 200MB <ide> unitTestDMMetaDataLoopbackSize = 104857600 // 100MB <ide> func cleanupDevMapper() error { <ide> } <ide> pools := []string{} <ide> for _, info := range infos { <del> if name := info.Name(); strings.HasPrefix(name, filter + "-") { <add> if name := info.Name(); strings.HasPrefix(name, filter+"-") { <ide> if strings.HasSuffix(name, "-pool") { <ide> pools = append(pools, name) <ide> } else { <ide> func init() { <ide> startFds, startGoroutines = utils.GetTotalUsedFds(), runtime.NumGoroutine() <ide> } <ide> <del> <ide> func setupBaseImage() { <ide> runtime, err := NewRuntimeFromDirectory(unitTestStoreBase, false) <ide> if err != nil { <ide> func setupBaseImage() { <ide> // Create a device, which triggers the initiation of the base FS <ide> // This avoids other tests doing this and timing out <ide> deviceset := devmapper.NewDeviceSetDM(unitTestStoreBase) <del> deviceset.AddDevice("init", "") <add> if err := deviceset.AddDevice("init", ""); err != nil { <add> log.Fatalf("Unable to setup the base image: %s", err) <add> } <ide> <ide> // Create the "Server" <ide> srv := &Server{ <ide> func setupBaseImage() { <ide> } <ide> } <ide> <del> <ide> func spawnGlobalDaemon() { <ide> if globalRuntime != nil { <ide> utils.Debugf("Global runtime already exists. Skipping.")
3
Go
Go
fix api with old version
e43236c78ae8a466a36c323aa679ea581b42cdc5
<ide><path>api/api.go <ide> func getImagesJSON(eng *engine.Engine, version float64, w http.ResponseWriter, r <ide> job.Setenv("filter", r.Form.Get("filter")) <ide> job.Setenv("all", r.Form.Get("all")) <ide> <del> if version > 1.8 { <add> if version >= 1.7 { <ide> job.Stdout.Add(w) <ide> } else if outs, err = job.Stdout.AddListTable(); err != nil { <ide> return err <ide> func getImagesJSON(eng *engine.Engine, version float64, w http.ResponseWriter, r <ide> return err <ide> } <ide> <del> if version < 1.8 && outs != nil { // Convert to legacy format <add> if version < 1.7 && outs != nil { // Convert to legacy format <ide> outsLegacy := engine.NewTable("Created", 0) <ide> for _, out := range outs.Data { <ide> for _, repoTag := range out.GetList("RepoTags") { <ide> func getContainersJSON(eng *engine.Engine, version float64, w http.ResponseWrite <ide> job.Setenv("before", r.Form.Get("before")) <ide> job.Setenv("limit", r.Form.Get("limit")) <ide> <del> if version > 1.5 { <add> if version >= 1.5 { <ide> job.Stdout.Add(w) <ide> } else if outs, err = job.Stdout.AddTable(); err != nil { <ide> return err
1
Ruby
Ruby
use travis ci environment variables
e39cd2e9b2581924596998d918f6e19fedd74328
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> # --tap=<tap>: Use the git repository of the given tap <ide> # --dry-run: Just print commands, don't run them. <ide> # --fail-fast: Immediately exit on a failing step. <add># --verbose: Print out all logs in realtime <ide> # <ide> # --ci-master: Shortcut for Homebrew master branch CI options. <ide> # --ci-pr: Shortcut for Homebrew pull request CI options. <ide> def failed? <ide> <ide> def puts_command <ide> cmd = @command.join(" ") <del> print "#{Tty.blue}==>#{Tty.white} #{cmd}#{Tty.reset}" <add> cmd_line = "#{Tty.blue}==>#{Tty.white} #{cmd}#{Tty.reset}" <add> if ENV["TRAVIS"] <add> @travis_timer_id = rand(2**32).to_s(16) <add> puts "travis_fold:start:#{@command.join(".")}" <add> puts "travis_time:start:#{@travis_timer_id}" <add> puts cmd_line <add> return <add> end <add> print cmd_line <ide> tabs = (80 - "PASSED".length + 1 - cmd.length) / 8 <ide> tabs.times { print "\t" } <ide> $stdout.flush <ide> end <ide> <ide> def puts_result <add> if ENV["TRAVIS"] <add> cmd = @command.join(" ") <add> puts "#{Tty.send status_colour}==> #{cmd}: #{status_upcase}#{Tty.reset}" <add> travis_start_time = @start_time.to_i*1000000000 <add> travis_end_time = @end_time.to_i*1000000000 <add> travis_duration = travis_end_time - travis_start_time <add> puts "travis_fold:end:#{@command.join(".")}" <add> puts "travis_time:end:#{@travis_timer_id},start=#{travis_start_time},finish=#{travis_end_time},duration=#{travis_duration}" <add> return <add> end <ide> puts " #{Tty.send status_colour}#{status_upcase}#{Tty.reset}" <ide> end <ide> <ide> def has_output? <ide> @output && [email protected]? <ide> end <ide> <add> def time <add> @end_time - @start_time <add> end <add> <ide> def run <add> @start_time = Time.now <add> <ide> puts_command <ide> if ARGV.include? "--dry-run" <del> puts <add> @end_time = Time.now <ide> @status = :passed <add> puts_result <ide> return <ide> end <ide> <ide> verbose = ARGV.verbose? <del> puts if verbose <add> puts if verbose && !ENV["TRAVIS"] <ide> @output = "" <ide> working_dir = Pathname.new(@command.first == "git" ? @repository : Dir.pwd) <del> start_time = Time.now <ide> read, write = IO.pipe <ide> <ide> begin <ide> def run <ide> end <ide> <ide> Process.wait(pid) <del> @time = Time.now - start_time <add> @end_time = Time.now <ide> @status = $?.success? ? :passed : :failed <ide> puts_result <ide> <ide> def brew_update <ide> @category = __method__ <ide> @start_branch = current_branch <ide> <add> travis_pr = ENV["TRAVIS_PULL_REQUEST"] && ENV["TRAVIS_PULL_REQUEST"] != "false" <add> <ide> # Use Jenkins environment variables if present. <ide> if no_args? && ENV["GIT_PREVIOUS_COMMIT"] && ENV["GIT_COMMIT"] \ <ide> && !ENV["ghprbPullLink"] <ide> diff_start_sha1 = shorten_revision ENV["GIT_PREVIOUS_COMMIT"] <ide> diff_end_sha1 = shorten_revision ENV["GIT_COMMIT"] <ide> brew_update <add> elsif ENV["TRAVIS_COMMIT_RANGE"] <add> diff_start_sha1, diff_end_sha1 = ENV["TRAVIS_COMMIT_RANGE"].split "..." <add> diff_end_sha1 = ENV["TRAVIS_COMMIT"] if travis_pr <ide> elsif @hash <ide> diff_start_sha1 = current_sha1 <ide> brew_update <ide> def brew_update <ide> if ENV["ghprbPullLink"] <ide> @url = ENV["ghprbPullLink"] <ide> @hash = nil <add> elsif travis_pr <add> @url = "https://github.com/#{ENV["TRAVIS_REPO_SLUG"]}/pull/#{ENV["TRAVIS_PULL_REQUEST"]}" <add> @hash = nil <ide> end <ide> <ide> if no_args? <ide> def brew_update <ide> diff_start_sha1 = "#{@hash}^" <ide> diff_end_sha1 = @hash <ide> @name = @hash <add> elsif ENV["TRAVIS_PULL_REQUEST"] && ENV["TRAVIS_PULL_REQUEST"] != "false" <add> @short_url = @url.gsub("https://github.com/", "") <add> @name = "#{@short_url}-#{diff_end_sha1}" <ide> elsif @url <ide> diff_start_sha1 = current_sha1 <ide> test "git", "checkout", diff_start_sha1 <ide> def brew_update <ide> FileUtils.mkdir_p @log_root <ide> <ide> return unless diff_start_sha1 != diff_end_sha1 <del> return if @url && !steps.last.passed? <add> return if @url && steps.last && !steps.last.passed? <ide> <ide> if @tap <ide> formula_path = %w[Formula HomebrewFormula].find { |dir| (@repository/dir).directory? } || "" <ide> def satisfied_requirements?(formula, spec, dependency = nil) <ide> def setup <ide> @category = __method__ <ide> return if ARGV.include? "--skip-setup" <del> test "brew", "doctor" <add> test "brew", "doctor" unless ENV["TRAVIS"] <ide> test "brew", "--env" <ide> test "brew", "config" <ide> end <ide> def cleanup_after <ide> <ide> checkout_args << @start_branch <ide> <del> if ARGV.include?("--cleanup") || @url || @hash <add> if @start_branch && !@start_branch.empty? && \ <add> (ARGV.include?("--cleanup") || @url || @hash) <ide> test "git", "checkout", *checkout_args <ide> end <ide> <ide> def test_bot <ide> ENV["HOMEBREW_DEVELOPER"] = "1" <ide> ENV["HOMEBREW_SANDBOX"] = "1" <ide> ENV["HOMEBREW_NO_EMOJI"] = "1" <add> ARGV << "--verbose" if ENV["TRAVIS"] <add> <ide> if ARGV.include?("--ci-master") || ARGV.include?("--ci-pr") \ <ide> || ARGV.include?("--ci-testing") <del> ARGV << "--cleanup" if ENV["JENKINS_HOME"] || ENV["TRAVIS_COMMIT"] <add> ARGV << "--cleanup" if ENV["JENKINS_HOME"] || ENV["TRAVIS"] <ide> ARGV << "--junit" << "--local" <ide> end <ide> if ARGV.include? "--ci-master" <ide> def test_bot <ide> end <ide> end <ide> <del> if ARGV.include? "--email" <del> failed_steps = [] <del> tests.each do |test| <del> test.steps.each do |step| <del> next if step.passed? <del> failed_steps << step.command_short <del> end <add> failed_steps = [] <add> tests.each do |test| <add> test.steps.each do |step| <add> next if step.passed? <add> failed_steps << step.command_short <ide> end <add> end <ide> <add> if ENV["TRAVIS"] && !failed_steps.empty? <add> puts "#{Tty.red}==> #{cmd}: FAILED: #{MacOS.version}: #{failed_steps.join ", "}#{Tty.reset}" <add> end <add> <add> if ARGV.include? "--email" <ide> if failed_steps.empty? <ide> email_subject = "" <ide> else
1
Python
Python
improve decorator typing
9b44bf2818d8e3cde422ad7f43fb33dfc6737289
<ide><path>src/flask/app.py <ide> from .testing import FlaskClient <ide> from .testing import FlaskCliRunner <ide> <add>T_before_first_request = t.TypeVar( <add> "T_before_first_request", bound=ft.BeforeFirstRequestCallable <add>) <add>T_shell_context_processor = t.TypeVar( <add> "T_shell_context_processor", bound=ft.ShellContextProcessorCallable <add>) <add>T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) <add>T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable) <add>T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable) <add>T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable) <add> <ide> if sys.version_info >= (3, 8): <ide> iscoroutinefunction = inspect.iscoroutinefunction <ide> else: <ide> def __init__( <ide> #: when a shell context is created. <ide> #: <ide> #: .. versionadded:: 0.11 <del> self.shell_context_processors: t.List[t.Callable[[], t.Dict[str, t.Any]]] = [] <add> self.shell_context_processors: t.List[ft.ShellContextProcessorCallable] = [] <ide> <ide> #: Maps registered blueprint names to blueprint objects. The <ide> #: dict retains the order the blueprints were registered in. <ide> def add_url_rule( <ide> self, <ide> rule: str, <ide> endpoint: t.Optional[str] = None, <del> view_func: t.Optional[ft.ViewCallable] = None, <add> view_func: t.Optional[ft.RouteCallable] = None, <ide> provide_automatic_options: t.Optional[bool] = None, <ide> **options: t.Any, <ide> ) -> None: <ide> def add_url_rule( <ide> @setupmethod <ide> def template_filter( <ide> self, name: t.Optional[str] = None <del> ) -> t.Callable[[ft.TemplateFilterCallable], ft.TemplateFilterCallable]: <add> ) -> t.Callable[[T_template_filter], T_template_filter]: <ide> """A decorator that is used to register custom template filter. <ide> You can specify a name for the filter, otherwise the function <ide> name will be used. Example:: <ide> def reverse(s): <ide> function name will be used. <ide> """ <ide> <del> def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable: <add> def decorator(f: T_template_filter) -> T_template_filter: <ide> self.add_template_filter(f, name=name) <ide> return f <ide> <ide> def add_template_filter( <ide> @setupmethod <ide> def template_test( <ide> self, name: t.Optional[str] = None <del> ) -> t.Callable[[ft.TemplateTestCallable], ft.TemplateTestCallable]: <add> ) -> t.Callable[[T_template_test], T_template_test]: <ide> """A decorator that is used to register custom template test. <ide> You can specify a name for the test, otherwise the function <ide> name will be used. Example:: <ide> def is_prime(n): <ide> function name will be used. <ide> """ <ide> <del> def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable: <add> def decorator(f: T_template_test) -> T_template_test: <ide> self.add_template_test(f, name=name) <ide> return f <ide> <ide> def add_template_test( <ide> @setupmethod <ide> def template_global( <ide> self, name: t.Optional[str] = None <del> ) -> t.Callable[[ft.TemplateGlobalCallable], ft.TemplateGlobalCallable]: <add> ) -> t.Callable[[T_template_global], T_template_global]: <ide> """A decorator that is used to register a custom template global function. <ide> You can specify a name for the global function, otherwise the function <ide> name will be used. Example:: <ide> def double(n): <ide> function name will be used. <ide> """ <ide> <del> def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable: <add> def decorator(f: T_template_global) -> T_template_global: <ide> self.add_template_global(f, name=name) <ide> return f <ide> <ide> def add_template_global( <ide> self.jinja_env.globals[name or f.__name__] = f <ide> <ide> @setupmethod <del> def before_first_request( <del> self, f: ft.BeforeFirstRequestCallable <del> ) -> ft.BeforeFirstRequestCallable: <add> def before_first_request(self, f: T_before_first_request) -> T_before_first_request: <ide> """Registers a function to be run before the first request to this <ide> instance of the application. <ide> <ide> def before_first_request( <ide> return f <ide> <ide> @setupmethod <del> def teardown_appcontext(self, f: ft.TeardownCallable) -> ft.TeardownCallable: <add> def teardown_appcontext(self, f: T_teardown) -> T_teardown: <ide> """Registers a function to be called when the application context <ide> ends. These functions are typically also called when the request <ide> context is popped. <ide> def teardown_appcontext(self, f: ft.TeardownCallable) -> ft.TeardownCallable: <ide> return f <ide> <ide> @setupmethod <del> def shell_context_processor(self, f: t.Callable) -> t.Callable: <add> def shell_context_processor( <add> self, f: T_shell_context_processor <add> ) -> T_shell_context_processor: <ide> """Registers a shell context processor function. <ide> <ide> .. versionadded:: 0.11 <ide><path>src/flask/blueprints.py <ide> from .app import Flask <ide> <ide> DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable] <add>T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable) <add>T_before_first_request = t.TypeVar( <add> "T_before_first_request", bound=ft.BeforeFirstRequestCallable <add>) <add>T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable) <add>T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable) <add>T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) <add>T_template_context_processor = t.TypeVar( <add> "T_template_context_processor", bound=ft.TemplateContextProcessorCallable <add>) <add>T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable) <add>T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable) <add>T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable) <add>T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable) <add>T_url_value_preprocessor = t.TypeVar( <add> "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable <add>) <ide> <ide> <ide> class BlueprintSetupState: <ide> def wrapper(state: BlueprintSetupState) -> None: <ide> if state.first_registration: <ide> func(state) <ide> <del> return self.record(update_wrapper(wrapper, func)) <add> self.record(update_wrapper(wrapper, func)) <ide> <ide> def make_setup_state( <ide> self, app: "Flask", options: dict, first_registration: bool = False <ide> def add_url_rule( <ide> self, <ide> rule: str, <ide> endpoint: t.Optional[str] = None, <del> view_func: t.Optional[ft.ViewCallable] = None, <add> view_func: t.Optional[ft.RouteCallable] = None, <ide> provide_automatic_options: t.Optional[bool] = None, <ide> **options: t.Any, <ide> ) -> None: <ide> def add_url_rule( <ide> @setupmethod <ide> def app_template_filter( <ide> self, name: t.Optional[str] = None <del> ) -> t.Callable[[ft.TemplateFilterCallable], ft.TemplateFilterCallable]: <add> ) -> t.Callable[[T_template_filter], T_template_filter]: <ide> """Register a custom template filter, available application wide. Like <ide> :meth:`Flask.template_filter` but for a blueprint. <ide> <ide> :param name: the optional name of the filter, otherwise the <ide> function name will be used. <ide> """ <ide> <del> def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable: <add> def decorator(f: T_template_filter) -> T_template_filter: <ide> self.add_app_template_filter(f, name=name) <ide> return f <ide> <ide> def register_template(state: BlueprintSetupState) -> None: <ide> @setupmethod <ide> def app_template_test( <ide> self, name: t.Optional[str] = None <del> ) -> t.Callable[[ft.TemplateTestCallable], ft.TemplateTestCallable]: <add> ) -> t.Callable[[T_template_test], T_template_test]: <ide> """Register a custom template test, available application wide. Like <ide> :meth:`Flask.template_test` but for a blueprint. <ide> <ide> def app_template_test( <ide> function name will be used. <ide> """ <ide> <del> def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable: <add> def decorator(f: T_template_test) -> T_template_test: <ide> self.add_app_template_test(f, name=name) <ide> return f <ide> <ide> def register_template(state: BlueprintSetupState) -> None: <ide> @setupmethod <ide> def app_template_global( <ide> self, name: t.Optional[str] = None <del> ) -> t.Callable[[ft.TemplateGlobalCallable], ft.TemplateGlobalCallable]: <add> ) -> t.Callable[[T_template_global], T_template_global]: <ide> """Register a custom template global, available application wide. Like <ide> :meth:`Flask.template_global` but for a blueprint. <ide> <ide> def app_template_global( <ide> function name will be used. <ide> """ <ide> <del> def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable: <add> def decorator(f: T_template_global) -> T_template_global: <ide> self.add_app_template_global(f, name=name) <ide> return f <ide> <ide> def register_template(state: BlueprintSetupState) -> None: <ide> self.record_once(register_template) <ide> <ide> @setupmethod <del> def before_app_request( <del> self, f: ft.BeforeRequestCallable <del> ) -> ft.BeforeRequestCallable: <add> def before_app_request(self, f: T_before_request) -> T_before_request: <ide> """Like :meth:`Flask.before_request`. Such a function is executed <ide> before each request, even if outside of a blueprint. <ide> """ <ide> def before_app_request( <ide> <ide> @setupmethod <ide> def before_app_first_request( <del> self, f: ft.BeforeFirstRequestCallable <del> ) -> ft.BeforeFirstRequestCallable: <add> self, f: T_before_first_request <add> ) -> T_before_first_request: <ide> """Like :meth:`Flask.before_first_request`. Such a function is <ide> executed before the first request to the application. <ide> <ide> def before_app_first_request( <ide> self.record_once(lambda s: s.app.before_first_request_funcs.append(f)) <ide> return f <ide> <del> def after_app_request(self, f: ft.AfterRequestCallable) -> ft.AfterRequestCallable: <add> @setupmethod <add> def after_app_request(self, f: T_after_request) -> T_after_request: <ide> """Like :meth:`Flask.after_request` but for a blueprint. Such a function <ide> is executed after each request, even if outside of the blueprint. <ide> """ <ide> def after_app_request(self, f: ft.AfterRequestCallable) -> ft.AfterRequestCallab <ide> return f <ide> <ide> @setupmethod <del> def teardown_app_request(self, f: ft.TeardownCallable) -> ft.TeardownCallable: <add> def teardown_app_request(self, f: T_teardown) -> T_teardown: <ide> """Like :meth:`Flask.teardown_request` but for a blueprint. Such a <ide> function is executed when tearing down each request, even if outside of <ide> the blueprint. <ide> def teardown_app_request(self, f: ft.TeardownCallable) -> ft.TeardownCallable: <ide> <ide> @setupmethod <ide> def app_context_processor( <del> self, f: ft.TemplateContextProcessorCallable <del> ) -> ft.TemplateContextProcessorCallable: <add> self, f: T_template_context_processor <add> ) -> T_template_context_processor: <ide> """Like :meth:`Flask.context_processor` but for a blueprint. Such a <ide> function is executed each request, even if outside of the blueprint. <ide> """ <ide> def app_context_processor( <ide> @setupmethod <ide> def app_errorhandler( <ide> self, code: t.Union[t.Type[Exception], int] <del> ) -> t.Callable[[ft.ErrorHandlerDecorator], ft.ErrorHandlerDecorator]: <add> ) -> t.Callable[[T_error_handler], T_error_handler]: <ide> """Like :meth:`Flask.errorhandler` but for a blueprint. This <ide> handler is used for all requests, even if outside of the blueprint. <ide> """ <ide> <del> def decorator(f: ft.ErrorHandlerDecorator) -> ft.ErrorHandlerDecorator: <add> def decorator(f: T_error_handler) -> T_error_handler: <ide> self.record_once(lambda s: s.app.errorhandler(code)(f)) <ide> return f <ide> <ide> return decorator <ide> <ide> @setupmethod <ide> def app_url_value_preprocessor( <del> self, f: ft.URLValuePreprocessorCallable <del> ) -> ft.URLValuePreprocessorCallable: <add> self, f: T_url_value_preprocessor <add> ) -> T_url_value_preprocessor: <ide> """Same as :meth:`url_value_preprocessor` but application wide.""" <ide> self.record_once( <ide> lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f) <ide> ) <ide> return f <ide> <ide> @setupmethod <del> def app_url_defaults(self, f: ft.URLDefaultCallable) -> ft.URLDefaultCallable: <add> def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults: <ide> """Same as :meth:`url_defaults` but application wide.""" <ide> self.record_once( <ide> lambda s: s.app.url_default_functions.setdefault(None, []).append(f) <ide><path>src/flask/scaffold.py <ide> _sentinel = object() <ide> <ide> F = t.TypeVar("F", bound=t.Callable[..., t.Any]) <add>T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable) <add>T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable) <add>T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable) <add>T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) <add>T_template_context_processor = t.TypeVar( <add> "T_template_context_processor", bound=ft.TemplateContextProcessorCallable <add>) <add>T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable) <add>T_url_value_preprocessor = t.TypeVar( <add> "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable <add>) <add>T_route = t.TypeVar("T_route", bound=ft.RouteCallable) <ide> <ide> <ide> def setupmethod(f: F) -> F: <ide> def _method_route( <ide> method: str, <ide> rule: str, <ide> options: dict, <del> ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]: <add> ) -> t.Callable[[T_route], T_route]: <ide> if "methods" in options: <ide> raise TypeError("Use the 'route' decorator to use the 'methods' argument.") <ide> <ide> return self.route(rule, methods=[method], **options) <ide> <ide> @setupmethod <del> def get( <del> self, rule: str, **options: t.Any <del> ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]: <add> def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: <ide> """Shortcut for :meth:`route` with ``methods=["GET"]``. <ide> <ide> .. versionadded:: 2.0 <ide> """ <ide> return self._method_route("GET", rule, options) <ide> <ide> @setupmethod <del> def post( <del> self, rule: str, **options: t.Any <del> ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]: <add> def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: <ide> """Shortcut for :meth:`route` with ``methods=["POST"]``. <ide> <ide> .. versionadded:: 2.0 <ide> """ <ide> return self._method_route("POST", rule, options) <ide> <ide> @setupmethod <del> def put( <del> self, rule: str, **options: t.Any <del> ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]: <add> def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: <ide> """Shortcut for :meth:`route` with ``methods=["PUT"]``. <ide> <ide> .. versionadded:: 2.0 <ide> """ <ide> return self._method_route("PUT", rule, options) <ide> <ide> @setupmethod <del> def delete( <del> self, rule: str, **options: t.Any <del> ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]: <add> def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: <ide> """Shortcut for :meth:`route` with ``methods=["DELETE"]``. <ide> <ide> .. versionadded:: 2.0 <ide> """ <ide> return self._method_route("DELETE", rule, options) <ide> <ide> @setupmethod <del> def patch( <del> self, rule: str, **options: t.Any <del> ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]: <add> def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: <ide> """Shortcut for :meth:`route` with ``methods=["PATCH"]``. <ide> <ide> .. versionadded:: 2.0 <ide> """ <ide> return self._method_route("PATCH", rule, options) <ide> <ide> @setupmethod <del> def route( <del> self, rule: str, **options: t.Any <del> ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]: <add> def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: <ide> """Decorate a view function to register it with the given URL <ide> rule and options. Calls :meth:`add_url_rule`, which has more <ide> details about the implementation. <ide> def index(): <ide> :class:`~werkzeug.routing.Rule` object. <ide> """ <ide> <del> def decorator(f: ft.RouteDecorator) -> ft.RouteDecorator: <add> def decorator(f: T_route) -> T_route: <ide> endpoint = options.pop("endpoint", None) <ide> self.add_url_rule(rule, endpoint, f, **options) <ide> return f <ide> def add_url_rule( <ide> self, <ide> rule: str, <ide> endpoint: t.Optional[str] = None, <del> view_func: t.Optional[ft.ViewCallable] = None, <add> view_func: t.Optional[ft.RouteCallable] = None, <ide> provide_automatic_options: t.Optional[bool] = None, <ide> **options: t.Any, <ide> ) -> None: <ide> def index(): <ide> raise NotImplementedError <ide> <ide> @setupmethod <del> def endpoint(self, endpoint: str) -> t.Callable: <add> def endpoint(self, endpoint: str) -> t.Callable[[F], F]: <ide> """Decorate a view function to register it for the given <ide> endpoint. Used if a rule is added without a ``view_func`` with <ide> :meth:`add_url_rule`. <ide> def example(): <ide> function. <ide> """ <ide> <del> def decorator(f): <add> def decorator(f: F) -> F: <ide> self.view_functions[endpoint] = f <ide> return f <ide> <ide> return decorator <ide> <ide> @setupmethod <del> def before_request(self, f: ft.BeforeRequestCallable) -> ft.BeforeRequestCallable: <add> def before_request(self, f: T_before_request) -> T_before_request: <ide> """Register a function to run before each request. <ide> <ide> For example, this can be used to open a database connection, or <ide> def load_user(): <ide> return f <ide> <ide> @setupmethod <del> def after_request(self, f: ft.AfterRequestCallable) -> ft.AfterRequestCallable: <add> def after_request(self, f: T_after_request) -> T_after_request: <ide> """Register a function to run after each request to this object. <ide> <ide> The function is called with the response object, and must return <ide> def after_request(self, f: ft.AfterRequestCallable) -> ft.AfterRequestCallable: <ide> return f <ide> <ide> @setupmethod <del> def teardown_request(self, f: ft.TeardownCallable) -> ft.TeardownCallable: <add> def teardown_request(self, f: T_teardown) -> T_teardown: <ide> """Register a function to be run at the end of each request, <ide> regardless of whether there was an exception or not. These functions <ide> are executed when the request context is popped, even if not an <ide> def teardown_request(self, f: ft.TeardownCallable) -> ft.TeardownCallable: <ide> <ide> @setupmethod <ide> def context_processor( <del> self, f: ft.TemplateContextProcessorCallable <del> ) -> ft.TemplateContextProcessorCallable: <add> self, <add> f: T_template_context_processor, <add> ) -> T_template_context_processor: <ide> """Registers a template context processor function.""" <ide> self.template_context_processors[None].append(f) <ide> return f <ide> <ide> @setupmethod <ide> def url_value_preprocessor( <del> self, f: ft.URLValuePreprocessorCallable <del> ) -> ft.URLValuePreprocessorCallable: <add> self, <add> f: T_url_value_preprocessor, <add> ) -> T_url_value_preprocessor: <ide> """Register a URL value preprocessor function for all view <ide> functions in the application. These functions will be called before the <ide> :meth:`before_request` functions. <ide> def url_value_preprocessor( <ide> return f <ide> <ide> @setupmethod <del> def url_defaults(self, f: ft.URLDefaultCallable) -> ft.URLDefaultCallable: <add> def url_defaults(self, f: T_url_defaults) -> T_url_defaults: <ide> """Callback function for URL defaults for all view functions of the <ide> application. It's called with the endpoint and values and should <ide> update the values passed in place. <ide> def url_defaults(self, f: ft.URLDefaultCallable) -> ft.URLDefaultCallable: <ide> @setupmethod <ide> def errorhandler( <ide> self, code_or_exception: t.Union[t.Type[Exception], int] <del> ) -> t.Callable[[ft.ErrorHandlerDecorator], ft.ErrorHandlerDecorator]: <add> ) -> t.Callable[[T_error_handler], T_error_handler]: <ide> """Register a function to handle errors by code or exception class. <ide> <ide> A decorator that is used to register a function given an <ide> def special_exception_handler(error): <ide> an arbitrary exception <ide> """ <ide> <del> def decorator(f: ft.ErrorHandlerDecorator) -> ft.ErrorHandlerDecorator: <add> def decorator(f: T_error_handler) -> T_error_handler: <ide> self.register_error_handler(code_or_exception, f) <ide> return f <ide> <ide><path>src/flask/typing.py <ide> ResponseClass = t.TypeVar("ResponseClass", bound="Response") <ide> <ide> AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named <del>AfterRequestCallable = t.Callable[[ResponseClass], ResponseClass] <del>BeforeFirstRequestCallable = t.Callable[[], None] <del>BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]] <del>TeardownCallable = t.Callable[[t.Optional[BaseException]], None] <add>AfterRequestCallable = t.Union[ <add> t.Callable[[ResponseClass], ResponseClass], <add> t.Callable[[ResponseClass], t.Awaitable[ResponseClass]], <add>] <add>BeforeFirstRequestCallable = t.Union[ <add> t.Callable[[], None], t.Callable[[], t.Awaitable[None]] <add>] <add>BeforeRequestCallable = t.Union[ <add> t.Callable[[], t.Optional[ResponseReturnValue]], <add> t.Callable[[], t.Awaitable[t.Optional[ResponseReturnValue]]], <add>] <add>ShellContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]] <add>TeardownCallable = t.Union[ <add> t.Callable[[t.Optional[BaseException]], None], <add> t.Callable[[t.Optional[BaseException]], t.Awaitable[None]], <add>] <ide> TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]] <ide> TemplateFilterCallable = t.Callable[..., t.Any] <ide> TemplateGlobalCallable = t.Callable[..., t.Any] <ide> # https://github.com/pallets/flask/issues/4295 <ide> # https://github.com/pallets/flask/issues/4297 <ide> ErrorHandlerCallable = t.Callable[[t.Any], ResponseReturnValue] <del>ErrorHandlerDecorator = t.TypeVar("ErrorHandlerDecorator", bound=ErrorHandlerCallable) <ide> <del>ViewCallable = t.Callable[..., ResponseReturnValue] <del>RouteDecorator = t.TypeVar("RouteDecorator", bound=ViewCallable) <add>RouteCallable = t.Union[ <add> t.Callable[..., ResponseReturnValue], <add> t.Callable[..., t.Awaitable[ResponseReturnValue]], <add>] <ide><path>src/flask/views.py <ide> def dispatch_request(self) -> ft.ResponseReturnValue: <ide> @classmethod <ide> def as_view( <ide> cls, name: str, *class_args: t.Any, **class_kwargs: t.Any <del> ) -> ft.ViewCallable: <add> ) -> ft.RouteCallable: <ide> """Convert the class into a view function that can be registered <ide> for a route. <ide> <ide><path>tests/typing/typing_route.py <ide> def return_template_stream() -> t.Iterator[str]: <ide> return stream_template("index.html", name="Hello") <ide> <ide> <add>@app.route("/async") <add>async def async_route() -> str: <add> return "Hello" <add> <add> <ide> class RenderTemplateView(View): <ide> def __init__(self: RenderTemplateView, template_name: str) -> None: <ide> self.template_name = template_name
6
Go
Go
fix composite literal uses unkeyed fields warnings
0275b007c6a0d21e33d52af376d7f7d99f8f17b9
<ide><path>libnetwork/drivers/overlay/ostweaks_linux.go <ide> import ( <ide> ) <ide> <ide> var ovConfig = map[string]*kernel.OSValue{ <del> "net.ipv4.neigh.default.gc_thresh1": {"8192", checkHigher}, <del> "net.ipv4.neigh.default.gc_thresh2": {"49152", checkHigher}, <del> "net.ipv4.neigh.default.gc_thresh3": {"65536", checkHigher}, <add> "net.ipv4.neigh.default.gc_thresh1": {Value: "8192", CheckFn: checkHigher}, <add> "net.ipv4.neigh.default.gc_thresh2": {Value: "49152", CheckFn: checkHigher}, <add> "net.ipv4.neigh.default.gc_thresh3": {Value: "65536", CheckFn: checkHigher}, <ide> } <ide> <ide> func checkHigher(val1, val2 string) bool { <ide><path>libnetwork/osl/namespace_linux.go <ide> var ( <ide> loadBalancerConfig = map[string]*kernel.OSValue{ <ide> // expires connection from the IPVS connection table when the backend is not available <ide> // more info: https://github.com/torvalds/linux/blob/master/Documentation/networking/ipvs-sysctl.txt#L126:1 <del> "net.ipv4.vs.expire_nodest_conn": {"1", nil}, <add> "net.ipv4.vs.expire_nodest_conn": {Value: "1", CheckFn: nil}, <ide> } <ide> ) <ide>
2
Javascript
Javascript
check result for primitive exports
0cfaadc63f3a34c6cfac9282236c9433474c02a4
<ide><path>test/cases/parsing/issue-4940/index.js <ide> it("should create dependency when require is called with 'new' (object export)", <ide> it("should create dependency when require is called with 'new' (non-object export)", function() { <ide> const sideEffect = require("./sideEffect"); <ide> const result = new require("./non-object-export"); <add> result.should.instanceof(__webpack_require__); <ide> sideEffect.foo.should.equal("bar"); <ide> });
1
Ruby
Ruby
remove missing default helper warnings
cefea3c677f90b2c095b377f1ba36a3ff157f5b0
<ide><path>actionpack/lib/action_controller/helpers.rb <ide> def default_helper_module! <ide> end <ide> rescue MissingSourceFile => e <ide> raise unless e.is_missing? module_path <del> logger.debug("#{name}: missing default helper path #{module_path}") if logger <ide> rescue NameError => e <ide> raise unless e.missing_name? module_name <del> logger.debug("#{name}: missing default helper module #{module_name}") if logger <ide> end <ide> <ide> def inherited_with_helper(child)
1
PHP
PHP
add test case
b862e5f521e77cd47ba120ecd0c6ee62f277fe58
<ide><path>tests/TestCase/Console/CommandTest.php <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\Stub\ConsoleOutput; <ide> use Cake\TestSuite\TestCase; <add>use TestApp\Command\AutoLoadModelCommand; <ide> use TestApp\Command\DemoCommand; <ide> <ide> /** <ide> public function testConstructorLoadModel() <ide> $this->assertInstanceOf(Table::class, $command->Comments); <ide> } <ide> <add> /** <add> * test loadModel is configured properly <add> * <add> * @return void <add> */ <add> public function testConstructorAutoLoadModel() <add> { <add> $command = new AutoLoadModelCommand(); <add> $this->assertInstanceOf(Table::class, $command->Posts); <add> } <add> <ide> /** <ide> * Test name <ide> * <ide><path>tests/test_app/TestApp/Command/AutoLoadModelCommand.php <add><?php <add>namespace TestApp\Command; <add> <add>use Cake\Console\Command; <add> <add>class AutoLoadModelCommand extends Command <add>{ <add> public $modelClass = 'Posts'; <add>}
2
Javascript
Javascript
rewrite stack layout for flexibility
3018f873c147bc885b2e999e81ad0a286281e7ec
<ide><path>d3.layout.js <ide> d3.layout.pie = function() { <ide> return pie; <ide> }; <ide> // data is two-dimensional array of x,y; we populate y0 <del>// TODO perhaps make the `x`, `y` and `y0` structure customizable <ide> d3.layout.stack = function() { <del> var order = "default", <del> offset = "zero"; <add> var values = Object, <add> order = d3_layout_stackOrders["default"], <add> offset = d3_layout_stackOffsets["zero"], <add> out = d3_layout_stackOut, <add> x = d3_layout_stackX, <add> y = d3_layout_stackY; <add> <add> function stack(data, index) { <add> <add> // Convert series to canonical two-dimensional representation. <add> var series = data.map(function(d, i) { <add> return values.call(stack, d, i); <add> }); <ide> <del> function stack(data) { <del> var n = data.length, <del> m = data[0].length, <del> i, <del> j, <del> y0; <add> // Convert each series to canonical [[x,y]] representation. <add> var points = series.map(function(d, i) { <add> return d.map(function(v, i) { <add> return [x.call(stack, v, i), y.call(stack, v, i)]; <add> }); <add> }); <ide> <del> // compute the order of series <del> var index = d3_layout_stackOrders[order](data); <add> // Compute the order of series, and permute them. <add> var orders = order.call(stack, points, index); <add> series = d3.permute(series, orders); <add> points = d3.permute(points, orders); <ide> <del> // set y0 on the baseline <del> d3_layout_stackOffsets[offset](data, index); <add> // Compute the baseline… <add> var offsets = offset.call(stack, points, index); <ide> <del> // propagate offset to other series <add> // And propagate it to other series. <add> var n = series.length, <add> m = series[0].length, <add> i, <add> j, <add> o; <ide> for (j = 0; j < m; ++j) { <del> for (i = 1, y0 = data[index[0]][j].y0; i < n; ++i) { <del> data[index[i]][j].y0 = y0 += data[index[i - 1]][j].y; <add> out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); <add> for (i = 1; i < n; ++i) { <add> out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); <ide> } <ide> } <ide> <ide> return data; <ide> } <ide> <add> stack.values = function(x) { <add> if (!arguments.length) return values; <add> values = x; <add> return stack; <add> }; <add> <ide> stack.order = function(x) { <ide> if (!arguments.length) return order; <del> order = x; <add> order = typeof x === "function" ? x : d3_layout_stackOrders[x]; <ide> return stack; <ide> }; <ide> <ide> stack.offset = function(x) { <ide> if (!arguments.length) return offset; <del> offset = x; <add> offset = typeof x === "function" ? x : d3_layout_stackOffsets[x]; <add> return stack; <add> }; <add> <add> stack.x = function(z) { <add> if (!arguments.length) return x; <add> x = z; <add> return stack; <add> }; <add> <add> stack.y = function(z) { <add> if (!arguments.length) return y; <add> y = z; <add> return stack; <add> }; <add> <add> stack.out = function(z) { <add> if (!arguments.length) return out; <add> out = z; <ide> return stack; <ide> }; <ide> <ide> return stack; <ide> } <ide> <add>function d3_layout_stackX(d) { <add> return d.x; <add>} <add> <add>function d3_layout_stackY(d) { <add> return d.y; <add>} <add> <add>function d3_layout_stackOut(d, y0, y) { <add> d.y0 = y0; <add> d.y = y; <add>} <add> <ide> var d3_layout_stackOrders = { <ide> <ide> "inside-out": function(data) { <ide> var d3_layout_stackOrders = { <ide> bottom = 0, <ide> tops = [], <ide> bottoms = []; <del> for (i = 0; i < n; i++) { <add> for (i = 0; i < n; ++i) { <ide> j = index[i]; <ide> if (top < bottom) { <ide> top += sums[j]; <ide> var d3_layout_stackOrders = { <ide> <ide> var d3_layout_stackOffsets = { <ide> <del> "silhouette": function(data, index) { <add> "silhouette": function(data) { <ide> var n = data.length, <ide> m = data[0].length, <ide> sums = [], <ide> max = 0, <ide> i, <ide> j, <del> o; <add> o, <add> y0 = []; <ide> for (j = 0; j < m; ++j) { <del> for (i = 0, o = 0; i < n; i++) o += data[i][j].y; <add> for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; <ide> if (o > max) max = o; <ide> sums.push(o); <ide> } <del> for (j = 0, i = index[0]; j < m; ++j) { <del> data[i][j].y0 = (max - sums[j]) / 2; <add> for (j = 0; j < m; ++j) { <add> y0[j] = (max - sums[j]) / 2; <ide> } <add> return y0; <ide> }, <ide> <del> "wiggle": function(data, index) { <add> "wiggle": function(data) { <ide> var n = data.length, <ide> x = data[0], <ide> m = x.length, <ide> max = 0, <ide> i, <ide> j, <ide> k, <del> ii, <del> ik, <del> i0 = index[0], <ide> s1, <ide> s2, <ide> s3, <ide> dx, <ide> o, <del> o0; <del> data[i0][0].y0 = o = o0 = 0; <add> o0, <add> y0 = []; <add> y0[0] = o = o0 = 0; <ide> for (j = 1; j < m; ++j) { <del> for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j].y; <del> for (i = 0, s2 = 0, dx = x[j].x - x[j - 1].x; i < n; ++i) { <del> for (k = 0, ii = index[i], s3 = (data[ii][j].y - data[ii][j - 1].y) / (2 * dx); k < i; ++k) { <del> s3 += (data[ik = index[k]][j].y - data[ik][j - 1].y) / dx; <add> for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; <add> for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { <add> for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { <add> s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; <ide> } <del> s2 += s3 * data[ii][j].y; <add> s2 += s3 * data[i][j][1]; <ide> } <del> data[i0][j].y0 = o -= s1 ? s2 / s1 * dx : 0; <add> y0[j] = o -= s1 ? s2 / s1 * dx : 0; <ide> if (o < o0) o0 = o; <ide> } <del> for (j = 0; j < m; ++j) data[i0][j].y0 -= o0; <add> for (j = 0; j < m; ++j) y0[j] -= o0; <add> return y0; <ide> }, <ide> <del> "expand": function(data, index) { <add> "expand": function(data) { <ide> var n = data.length, <ide> m = data[0].length, <ide> k = 1 / n, <ide> i, <ide> j, <del> o; <add> o, <add> y0 = []; <ide> for (j = 0; j < m; ++j) { <del> for (i = 0, o = 0; i < n; i++) o += data[i][j].y; <del> if (o) for (i = 0; i < n; i++) data[i][j].y /= o; <del> else for (i = 0; i < n; i++) data[i][j].y = k; <add> for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; <add> if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; <add> else for (i = 0; i < n; i++) data[i][j][1] = k; <ide> } <del> for (i = index[0], j = 0; j < m; ++j) data[i][j].y0 = 0; <add> for (j = 0; j < m; ++j) y0[j] = 0; <add> return y0; <ide> }, <ide> <del> "zero": function(data, index) { <del> var j = 0, <add> "zero": function(data) { <add> var j = -1, <ide> m = data[0].length, <del> i0 = index[0]; <del> for (; j < m; ++j) data[i0][j].y0 = 0; <add> y0 = []; <add> while (++j < m) y0[j] = 0; <add> return y0; <ide> } <ide> <ide> }; <ide> <del>function d3_layout_stackReduceSum(d) { <del> return d.reduce(d3_layout_stackSum, 0); <del>} <del> <ide> function d3_layout_stackMaxIndex(array) { <ide> var i = 1, <ide> j = 0, <del> v = array[0].y, <add> v = array[0][1], <ide> k, <ide> n = array.length; <ide> for (; i < n; ++i) { <del> if ((k = array[i].y) > v) { <add> if ((k = array[i][1]) > v) { <ide> j = i; <ide> v = k; <ide> } <ide> } <ide> return j; <ide> } <ide> <add>function d3_layout_stackReduceSum(d) { <add> return d.reduce(d3_layout_stackSum, 0); <add>} <add> <ide> function d3_layout_stackSum(p, d) { <del> return p + d.y; <add> return p + d[1]; <ide> } <ide> d3.layout.hierarchy = function() { <ide> var sort = d3_layout_hierarchySort, <ide><path>d3.layout.min.js <del>(function(){function S(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function R(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function Q(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function P(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function O(a,b){return a.depth-b.depth}function N(a,b){return b.x-a.x}function M(a,b){return a.x-b.x}function L(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=L(c[f],b),a)>0&&(a=d)}return a}function K(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function J(a){return a.children?a.children[0]:a._tree.thread}function I(a,b){return a.parent==b.parent?1:2}function H(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function G(a){var b=a.children;return b?G(b[b.length-1]):a}function F(a){var b=a.children;return b?F(b[0]):a}function E(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function D(a){return 1+d3.max(a,function(a){return a.y})}function C(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function B(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)B(e[f],b,c,d)}}function A(a){var b=a.children;b?(b.forEach(A),a.r=x(b)):a.r=Math.sqrt(a.value)}function z(a){delete a._pack_next,delete a._pack_prev}function y(a){a._pack_next=a._pack_prev=a}function x(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(y),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],C(g,h,i),l(i),u(g,i),g._pack_prev=i,u(i,h),h=g._pack_next;for(var m=3;m<f;m++){C(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(w(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(w(k,i)){p<o&&(n=-1,j=k);break}n==0?(u(g,i),h=i,l(i)):n>0?(v(g,j),h=j,m--):(v(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(z);return s}function w(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function v(a,b){a._pack_next=b,b._pack_prev=a}function u(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function t(a,b){return a.value-b.value}function s(a,b){return b.value-a.value}function r(a){return a.value}function q(a){return a.children}function p(a,b){return a+b.y}function o(a){var b=1,c=0,d=a[0].y,e,f=a.length;for(;b<f;++b)(e=a[b].y)>d&&(c=b,d=e);return c}function n(a){return a.reduce(p,0)}function k(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){k(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){d3.event.stopPropagation(),d3.event.preventDefault()}function i(){c&&(j(),c=!1)}function h(c,d){(a=c).fixed=!0,b=!1,e=this,j()}function g(b){b!==a&&(b.fixed=!1)}function f(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function A(){!a||(b&&(c=!0,j()),z(),a.fixed=!1,a=e=null)}function z(){if(!!a){var c=e.parentNode;if(!c){a.fixed=!1,a=e=null;return}var f=d3.svg.mouse(c);b=!0,a.px=f[0],a.py=f[1],d.resume()}}function y(){var a=u.length,b=v.length,c=d3.geom.quadtree(u),d,e,f,g,h,i,j;for(d=0;d<b;++d){e=v[d],f=e.source,g=e.target,i=g.x-f.x,j=g.y-f.y;if(h=i*i+j*j)h=n*((h=Math.sqrt(h))-p)/h,i*=h,j*=h,g.x-=i,g.y-=j,f.x+=i,f.y+=j}var s=n*r;i=m[0]/2,j=m[1]/2,d=-1;while(++d<a)e=u[d],e.x+=(i-e.x)*s,e.y+=(j-e.y)*s;k(c);var t=n*q;d=-1;while(++d<a)c.visit(x(u[d],t));d=-1;while(++d<a)e=u[d],e.fixed?(e.x=e.px,e.y=e.py):(e.x-=(e.px-(e.px=e.x))*o,e.y-=(e.py-(e.py=e.y))*o);l.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function x(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<s){var k=b*c.count*j*j;a.x+=h*k,a.y+=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.x+=h*k,a.y+=i*k}}}}var d={},l=d3.dispatch("tick"),m=[1,1],n,o=.9,p=20,q=-30,r=.1,s=.8,t,u,v,w;d.on=function(a,b){l[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return u;u=a;return d},d.links=function(a){if(!arguments.length)return v;v=a;return d},d.size=function(a){if(!arguments.length)return m;m=a;return d},d.distance=function(a){if(!arguments.length)return p;p=a;return d},d.drag=function(a){if(!arguments.length)return o;o=a;return d},d.charge=function(a){if(!arguments.length)return q;q=a;return d},d.gravity=function(a){if(!arguments.length)return r;r=a;return d},d.theta=function(a){if(!arguments.length)return s;s=a;return d},d.start=function(){function k(){if(!h){h=[];for(b=0;b<c;++b)h[b]=[];for(b=0;b<e;++b){var d=v[b];h[d.source.index].push(d.target),h[d.target.index].push(d.source)}}return h[a]}function j(b,c){var d=k(a),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][b]))return g;return Math.random()*c}var a,b,c=u.length,e=v.length,f=m[0],g=m[1],h,i;for(a=0;a<c;++a)(i=u[a]).index=a;for(a=0;a<e;++a)i=v[a],typeof i.source=="number"&&(i.source=u[i.source]),typeof i.target=="number"&&(i.target=u[i.target]);for(a=0;a<c;++a)i=u[a],isNaN(i.x)&&(i.x=j("x",f)),isNaN(i.y)&&(i.y=j("y",g)),isNaN(i.px)&&(i.px=i.x),isNaN(i.py)&&(i.py=i.y);return d.resume()},d.resume=function(){n=.1,d3.timer(y);return d},d.stop=function(){n=0;return d},d.drag=function(){this.on("mouseover.force",f).on("mouseout.force",g).on("mousedown.force",h),d3.select(window).on("mousemove.force",z).on("mouseup.force",A,!0).on("click.force",i,!0);return d};return d};var a,b,c,e;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function c(c){var d=c.length,e=c[0].length,f,g,h,i=l[a](c);m[b](c,i);for(g=0;g<e;++g)for(f=1,h=c[i[0]][g].y0;f<d;++f)c[i[f]][g].y0=h+=c[i[f-1]][g].y;return c}var a="default",b="zero";c.order=function(b){if(!arguments.length)return a;a=b;return c},c.offset=function(a){if(!arguments.length)return b;b=a;return c};return c};var l={"inside-out":function(a){var b=a.length,c,d,e=a.map(o),f=a.map(n),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;c++)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},m={silhouette:function(a,b){var c=a.length,d=a[0].length,e=[],f=0,g,h,i;for(h=0;h<d;++h){for(g=0,i=0;g<c;g++)i+=a[g][h].y;i>f&&(f=i),e.push(i)}for(h=0,g=b[0];h<d;++h)a[g][h].y0=(f-e[h])/2},wiggle:function(a,b){var c=a.length,d=a[0],e=d.length,f=0,g,h,i,j,k,l=b[0],m,n,o,p,q,r;a[l][0].y0=q=r=0;for(h=1;h<e;++h){for(g=0,m=0;g<c;++g)m+=a[g][h].y;for(g=0,n=0,p=d[h].x-d[h-1].x;g<c;++g){for(i=0,j=b[g],o=(a[j][h].y-a[j][h-1].y)/(2*p);i<g;++i)o+=(a[k=b[i]][h].y-a[k][h-1].y)/p;n+=o*a[j][h].y}a[l][h].y0=q-=m?n/m*p:0,q<r&&(r=q)}for(h=0;h<e;++h)a[l][h].y0-=r},expand:function(a,b){var c=a.length,d=a[0].length,e=1/c,f,g,h;for(g=0;g<d;++g){for(f=0,h=0;f<c;f++)h+=a[f][g].y;if(h)for(f=0;f<c;f++)a[f][g].y/=h;else for(f=0;f<c;f++)a[f][g].y=e}for(f=b[0],g=0;g<d;++g)a[f][g].y0=0},zero:function(a,b){var c=0,d=a[0].length,e=b[0];for(;c<d;++c)a[e][c].y0=0}};d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=s,b=q,c=r;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,A(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);B(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(t)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;P(g,function(a){a.children?(a.x=E(a.children),a.y=D(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=F(g),m=G(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;P(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=I,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=H,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=K(g),e=J(e),g&&e)h=J(h),f=K(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(R(S(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!K(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!J(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;Q(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];P(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=L(g,N),l=L(g,M),m=L(g,O),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;P(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=I,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=H,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})() <ide>\ No newline at end of file <add>(function(){function V(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function U(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function T(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function S(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function R(a,b){return a.depth-b.depth}function Q(a,b){return b.x-a.x}function P(a,b){return a.x-b.x}function O(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=O(c[f],b),a)>0&&(a=d)}return a}function N(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function M(a){return a.children?a.children[0]:a._tree.thread}function L(a,b){return a.parent==b.parent?1:2}function K(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function J(a){var b=a.children;return b?J(b[b.length-1]):a}function I(a){var b=a.children;return b?I(b[0]):a}function H(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function G(a){return 1+d3.max(a,function(a){return a.y})}function F(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function E(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)E(e[f],b,c,d)}}function D(a){var b=a.children;b?(b.forEach(D),a.r=A(b)):a.r=Math.sqrt(a.value)}function C(a){delete a._pack_next,delete a._pack_prev}function B(a){a._pack_next=a._pack_prev=a}function A(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(B),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],F(g,h,i),l(i),x(g,i),g._pack_prev=i,x(i,h),h=g._pack_next;for(var m=3;m<f;m++){F(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(z(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(z(k,i)){p<o&&(n=-1,j=k);break}n==0?(x(g,i),h=i,l(i)):n>0?(y(g,j),h=j,m--):(y(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(C);return s}function z(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function y(a,b){a._pack_next=b,b._pack_prev=a}function x(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function w(a,b){return a.value-b.value}function v(a,b){return b.value-a.value}function u(a){return a.value}function t(a){return a.children}function s(a,b){return a+b[1]}function r(a){return a.reduce(s,0)}function q(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function n(a,b,c){a.y0=b,a.y=c}function m(a){return a.y}function l(a){return a.x}function k(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){k(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){d3.event.stopPropagation(),d3.event.preventDefault()}function i(){c&&(j(),c=!1)}function h(c,d){(a=c).fixed=!0,b=!1,e=this,j()}function g(b){b!==a&&(b.fixed=!1)}function f(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function A(){!a||(b&&(c=!0,j()),z(),a.fixed=!1,a=e=null)}function z(){if(!!a){var c=e.parentNode;if(!c){a.fixed=!1,a=e=null;return}var f=d3.svg.mouse(c);b=!0,a.px=f[0],a.py=f[1],d.resume()}}function y(){var a=u.length,b=v.length,c=d3.geom.quadtree(u),d,e,f,g,h,i,j;for(d=0;d<b;++d){e=v[d],f=e.source,g=e.target,i=g.x-f.x,j=g.y-f.y;if(h=i*i+j*j)h=n*((h=Math.sqrt(h))-p)/h,i*=h,j*=h,g.x-=i,g.y-=j,f.x+=i,f.y+=j}var s=n*r;i=m[0]/2,j=m[1]/2,d=-1;while(++d<a)e=u[d],e.x+=(i-e.x)*s,e.y+=(j-e.y)*s;k(c);var t=n*q;d=-1;while(++d<a)c.visit(x(u[d],t));d=-1;while(++d<a)e=u[d],e.fixed?(e.x=e.px,e.y=e.py):(e.x-=(e.px-(e.px=e.x))*o,e.y-=(e.py-(e.py=e.y))*o);l.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function x(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<s){var k=b*c.count*j*j;a.x+=h*k,a.y+=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.x+=h*k,a.y+=i*k}}}}var d={},l=d3.dispatch("tick"),m=[1,1],n,o=.9,p=20,q=-30,r=.1,s=.8,t,u,v,w;d.on=function(a,b){l[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return u;u=a;return d},d.links=function(a){if(!arguments.length)return v;v=a;return d},d.size=function(a){if(!arguments.length)return m;m=a;return d},d.distance=function(a){if(!arguments.length)return p;p=a;return d},d.drag=function(a){if(!arguments.length)return o;o=a;return d},d.charge=function(a){if(!arguments.length)return q;q=a;return d},d.gravity=function(a){if(!arguments.length)return r;r=a;return d},d.theta=function(a){if(!arguments.length)return s;s=a;return d},d.start=function(){function k(){if(!h){h=[];for(b=0;b<c;++b)h[b]=[];for(b=0;b<e;++b){var d=v[b];h[d.source.index].push(d.target),h[d.target.index].push(d.source)}}return h[a]}function j(b,c){var d=k(a),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][b]))return g;return Math.random()*c}var a,b,c=u.length,e=v.length,f=m[0],g=m[1],h,i;for(a=0;a<c;++a)(i=u[a]).index=a;for(a=0;a<e;++a)i=v[a],typeof i.source=="number"&&(i.source=u[i.source]),typeof i.target=="number"&&(i.target=u[i.target]);for(a=0;a<c;++a)i=u[a],isNaN(i.x)&&(i.x=j("x",f)),isNaN(i.y)&&(i.y=j("y",g)),isNaN(i.px)&&(i.px=i.x),isNaN(i.py)&&(i.py=i.y);return d.resume()},d.resume=function(){n=.1,d3.timer(y);return d},d.stop=function(){n=0;return d},d.drag=function(){this.on("mouseover.force",f).on("mouseout.force",g).on("mousedown.force",h),d3.select(window).on("mousemove.force",z).on("mouseup.force",A,!0).on("click.force",i,!0);return d};return d};var a,b,c,e;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=o["default"],c=p.zero,d=n,e=l,f=m;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:o[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:p[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var o={"inside-out":function(a){var b=a.length,c,d,e=a.map(q),f=a.map(r),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},p={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=v,b=t,c=u;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,D(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);E(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(w)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;S(g,function(a){a.children?(a.x=H(a.children),a.y=G(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=I(g),m=J(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;S(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=L,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=K,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=N(g),e=M(e),g&&e)h=M(h),f=N(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(U(V(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!N(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!M(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;T(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];S(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=O(g,Q),l=O(g,P),m=O(g,R),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;S(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=L,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=K,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})() <ide>\ No newline at end of file <ide><path>src/layout/stack.js <ide> // data is two-dimensional array of x,y; we populate y0 <del>// TODO perhaps make the `x`, `y` and `y0` structure customizable <ide> d3.layout.stack = function() { <del> var order = "default", <del> offset = "zero"; <del> <del> function stack(data) { <del> var n = data.length, <del> m = data[0].length, <add> var values = Object, <add> order = d3_layout_stackOrders["default"], <add> offset = d3_layout_stackOffsets["zero"], <add> out = d3_layout_stackOut, <add> x = d3_layout_stackX, <add> y = d3_layout_stackY; <add> <add> function stack(data, index) { <add> <add> // Convert series to canonical two-dimensional representation. <add> var series = data.map(function(d, i) { <add> return values.call(stack, d, i); <add> }); <add> <add> // Convert each series to canonical [[x,y]] representation. <add> var points = series.map(function(d, i) { <add> return d.map(function(v, i) { <add> return [x.call(stack, v, i), y.call(stack, v, i)]; <add> }); <add> }); <add> <add> // Compute the order of series, and permute them. <add> var orders = order.call(stack, points, index); <add> series = d3.permute(series, orders); <add> points = d3.permute(points, orders); <add> <add> // Compute the baseline… <add> var offsets = offset.call(stack, points, index); <add> <add> // And propagate it to other series. <add> var n = series.length, <add> m = series[0].length, <ide> i, <ide> j, <del> y0; <del> <del> // compute the order of series <del> var index = d3_layout_stackOrders[order](data); <del> <del> // set y0 on the baseline <del> d3_layout_stackOffsets[offset](data, index); <del> <del> // propagate offset to other series <add> o; <ide> for (j = 0; j < m; ++j) { <del> for (i = 1, y0 = data[index[0]][j].y0; i < n; ++i) { <del> data[index[i]][j].y0 = y0 += data[index[i - 1]][j].y; <add> out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); <add> for (i = 1; i < n; ++i) { <add> out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); <ide> } <ide> } <ide> <ide> return data; <ide> } <ide> <add> stack.values = function(x) { <add> if (!arguments.length) return values; <add> values = x; <add> return stack; <add> }; <add> <ide> stack.order = function(x) { <ide> if (!arguments.length) return order; <del> order = x; <add> order = typeof x === "function" ? x : d3_layout_stackOrders[x]; <ide> return stack; <ide> }; <ide> <ide> stack.offset = function(x) { <ide> if (!arguments.length) return offset; <del> offset = x; <add> offset = typeof x === "function" ? x : d3_layout_stackOffsets[x]; <add> return stack; <add> }; <add> <add> stack.x = function(z) { <add> if (!arguments.length) return x; <add> x = z; <add> return stack; <add> }; <add> <add> stack.y = function(z) { <add> if (!arguments.length) return y; <add> y = z; <add> return stack; <add> }; <add> <add> stack.out = function(z) { <add> if (!arguments.length) return out; <add> out = z; <ide> return stack; <ide> }; <ide> <ide> return stack; <ide> } <ide> <add>function d3_layout_stackX(d) { <add> return d.x; <add>} <add> <add>function d3_layout_stackY(d) { <add> return d.y; <add>} <add> <add>function d3_layout_stackOut(d, y0, y) { <add> d.y0 = y0; <add> d.y = y; <add>} <add> <ide> var d3_layout_stackOrders = { <ide> <ide> "inside-out": function(data) { <ide> var d3_layout_stackOrders = { <ide> bottom = 0, <ide> tops = [], <ide> bottoms = []; <del> for (i = 0; i < n; i++) { <add> for (i = 0; i < n; ++i) { <ide> j = index[i]; <ide> if (top < bottom) { <ide> top += sums[j]; <ide> var d3_layout_stackOrders = { <ide> <ide> var d3_layout_stackOffsets = { <ide> <del> "silhouette": function(data, index) { <add> "silhouette": function(data) { <ide> var n = data.length, <ide> m = data[0].length, <ide> sums = [], <ide> max = 0, <ide> i, <ide> j, <del> o; <add> o, <add> y0 = []; <ide> for (j = 0; j < m; ++j) { <del> for (i = 0, o = 0; i < n; i++) o += data[i][j].y; <add> for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; <ide> if (o > max) max = o; <ide> sums.push(o); <ide> } <del> for (j = 0, i = index[0]; j < m; ++j) { <del> data[i][j].y0 = (max - sums[j]) / 2; <add> for (j = 0; j < m; ++j) { <add> y0[j] = (max - sums[j]) / 2; <ide> } <add> return y0; <ide> }, <ide> <del> "wiggle": function(data, index) { <add> "wiggle": function(data) { <ide> var n = data.length, <ide> x = data[0], <ide> m = x.length, <ide> max = 0, <ide> i, <ide> j, <ide> k, <del> ii, <del> ik, <del> i0 = index[0], <ide> s1, <ide> s2, <ide> s3, <ide> dx, <ide> o, <del> o0; <del> data[i0][0].y0 = o = o0 = 0; <add> o0, <add> y0 = []; <add> y0[0] = o = o0 = 0; <ide> for (j = 1; j < m; ++j) { <del> for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j].y; <del> for (i = 0, s2 = 0, dx = x[j].x - x[j - 1].x; i < n; ++i) { <del> for (k = 0, ii = index[i], s3 = (data[ii][j].y - data[ii][j - 1].y) / (2 * dx); k < i; ++k) { <del> s3 += (data[ik = index[k]][j].y - data[ik][j - 1].y) / dx; <add> for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; <add> for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { <add> for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { <add> s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; <ide> } <del> s2 += s3 * data[ii][j].y; <add> s2 += s3 * data[i][j][1]; <ide> } <del> data[i0][j].y0 = o -= s1 ? s2 / s1 * dx : 0; <add> y0[j] = o -= s1 ? s2 / s1 * dx : 0; <ide> if (o < o0) o0 = o; <ide> } <del> for (j = 0; j < m; ++j) data[i0][j].y0 -= o0; <add> for (j = 0; j < m; ++j) y0[j] -= o0; <add> return y0; <ide> }, <ide> <del> "expand": function(data, index) { <add> "expand": function(data) { <ide> var n = data.length, <ide> m = data[0].length, <ide> k = 1 / n, <ide> i, <ide> j, <del> o; <add> o, <add> y0 = []; <ide> for (j = 0; j < m; ++j) { <del> for (i = 0, o = 0; i < n; i++) o += data[i][j].y; <del> if (o) for (i = 0; i < n; i++) data[i][j].y /= o; <del> else for (i = 0; i < n; i++) data[i][j].y = k; <add> for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; <add> if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; <add> else for (i = 0; i < n; i++) data[i][j][1] = k; <ide> } <del> for (i = index[0], j = 0; j < m; ++j) data[i][j].y0 = 0; <add> for (j = 0; j < m; ++j) y0[j] = 0; <add> return y0; <ide> }, <ide> <del> "zero": function(data, index) { <del> var j = 0, <add> "zero": function(data) { <add> var j = -1, <ide> m = data[0].length, <del> i0 = index[0]; <del> for (; j < m; ++j) data[i0][j].y0 = 0; <add> y0 = []; <add> while (++j < m) y0[j] = 0; <add> return y0; <ide> } <ide> <ide> }; <ide> <del>function d3_layout_stackReduceSum(d) { <del> return d.reduce(d3_layout_stackSum, 0); <del>} <del> <ide> function d3_layout_stackMaxIndex(array) { <ide> var i = 1, <ide> j = 0, <del> v = array[0].y, <add> v = array[0][1], <ide> k, <ide> n = array.length; <ide> for (; i < n; ++i) { <del> if ((k = array[i].y) > v) { <add> if ((k = array[i][1]) > v) { <ide> j = i; <ide> v = k; <ide> } <ide> } <ide> return j; <ide> } <ide> <add>function d3_layout_stackReduceSum(d) { <add> return d.reduce(d3_layout_stackSum, 0); <add>} <add> <ide> function d3_layout_stackSum(p, d) { <del> return p + d.y; <add> return p + d[1]; <ide> }
3
Javascript
Javascript
remove obsolete test
b5406d276d73bcb0319eb451fa1cf2aec1e67946
<ide><path>test/ng/directive/ngBindSpec.js <ide> describe('ngBind*', function() { <ide> $rootScope.$digest(); <ide> expect(element.text()).toEqual('-0false'); <ide> })); <del> <del> <del> it('should render object as JSON ignore $$', inject(function($rootScope, $compile) { <del> element = $compile('<div>{{ {key:"value", $$key:"hide"} }}</div>')($rootScope); <del> $rootScope.$digest(); <del> expect(fromJson(element.text())).toEqual({key:'value'}); <del> })); <ide> }); <ide> <ide>
1
Ruby
Ruby
add saved changes helpers for store accessors
b574d283e57930105d505c2d34f6d4777dc21069
<ide><path>activerecord/lib/active_record/store.rb <ide> module ActiveRecord <ide> # of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's <ide> # already built around just accessing attributes on the model. <ide> # <del> # Every accessor comes with dirty tracking methods (+key_changed?+, +key_was+ and +key_change+). <add> # Every accessor comes with dirty tracking methods (+key_changed?+, +key_was+ and +key_change+) and <add> # methods to access the changes made during the last save (+saved_change_to_key?+, +saved_change_to_key+ and <add> # +key_before_last_save+). <ide> # <ide> # NOTE: There is no +key_will_change!+ method for accessors, use +store_will_change!+ instead. <ide> # <ide> def store_accessor(store_attribute, *keys, prefix: nil, suffix: nil) <ide> prev_store, _new_store = changes[store_attribute] <ide> prev_store&.dig(key) <ide> end <add> <add> define_method("saved_change_to_#{accessor_key}?") do <add> return false unless saved_change_to_attribute?(store_attribute) <add> prev_store, new_store = saved_change_to_attribute(store_attribute) <add> prev_store&.dig(key) != new_store&.dig(key) <add> end <add> <add> define_method("saved_change_to_#{accessor_key}") do <add> return unless saved_change_to_attribute?(store_attribute) <add> prev_store, new_store = saved_change_to_attribute(store_attribute) <add> [prev_store&.dig(key), new_store&.dig(key)] <add> end <add> <add> define_method("#{accessor_key}_before_last_save") do <add> return unless saved_change_to_attribute?(store_attribute) <add> prev_store, _new_store = saved_change_to_attribute(store_attribute) <add> prev_store&.dig(key) <add> end <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/store_test.rb <ide> class StoreTest < ActiveRecord::TestCase <ide> assert_equal ["Dallas", "Lena"], @john.partner_name_change <ide> end <ide> <add> test "saved changes tracking for accessors" do <add> @john.spouse[:name] = "Lena" <add> assert @john.partner_name_changed? <add> <add> @john.save! <add> assert_not @john.partner_name_change <add> assert @john.saved_change_to_partner_name? <add> assert_equal ["Dallas", "Lena"], @john.saved_change_to_partner_name <add> assert_equal "Dallas", @john.partner_name_before_last_save <add> end <add> <ide> test "object initialization with not nullable column" do <ide> assert_equal true, @john.remember_login <ide> end
2
Javascript
Javascript
replace fixturesdir with fixtures module
ca12ae6015e6936ecc8cea89222eee42911d1bf1
<ide><path>test/parallel/test-module-children.js <ide> // Flags: --no-deprecation <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <add>const fixtures = require('../common/fixtures'); <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> <del>const dir = path.join(common.fixturesDir, 'GH-7131'); <add>const dir = fixtures.path('GH-7131'); <ide> const b = require(path.join(dir, 'b')); <ide> const a = require(path.join(dir, 'a')); <ide>
1
Ruby
Ruby
add flags for printing only formulae or casks
11fbf9d035033467009ae0252b4496b34923c425
<ide><path>Library/Homebrew/cmd/--cache.rb <ide> module Homebrew <ide> def __cache_args <ide> Homebrew::CLI::Parser.new do <ide> usage_banner <<~EOS <del> `--cache` [<options>] [<formula>] <add> `--cache` [<options>] [<formula/cask>] <ide> <ide> Display Homebrew's download cache. See also `HOMEBREW_CACHE`. <ide> <del> If <formula> is provided, display the file or directory used to cache <formula>. <add> If <formula/cask> is provided, display the file or directory used to cache <formula/cask>. <ide> EOS <ide> switch "-s", "--build-from-source", <ide> description: "Show the cache file used when building from source." <ide> switch "--force-bottle", <ide> description: "Show the cache file used when pouring a bottle." <add> switch "--formula", <add> description: "Show cache files for only formulae" <add> switch "--cask", <add> description: "Show cache files for only casks" <ide> conflicts "--build-from-source", "--force-bottle" <add> conflicts "--formula", "--cask" <ide> end <ide> end <ide> <ide> def __cache <ide> <ide> if args.no_named? <ide> puts HOMEBREW_CACHE <add> elsif args.formula? <add> args.named.each do |name| <add> print_formula_cache name <add> end <add> elsif args.cask? <add> args.named.each do |name| <add> print_cask_cache name <add> end <ide> else <ide> args.named.each do |name| <del> formula = Formulary.factory name <del> if Fetch.fetch_bottle?(formula) <del> puts formula.bottle.cached_download <del> else <del> puts formula.cached_download <del> end <add> print_formula_cache name <ide> rescue FormulaUnavailableError => e <del> formula_error_message = e.message <ide> begin <del> cask = Cask::CaskLoader.load name <del> puts "cask: #{Cask::Cmd::Cache.cached_location(cask)}" <add> print_cask_cache name <ide> rescue Cask::CaskUnavailableError => e <del> cask_error_message = e.message <del> odie "No available formula or cask with the name \"#{name}\"\n" \ <del> "#{formula_error_message}\n" \ <del> "#{cask_error_message}\n" <add> odie "No available formula or cask with the name \"#{name}\"" <ide> end <ide> end <ide> end <ide> end <add> <add> def print_formula_cache(name) <add> formula = Formulary.factory name <add> if Fetch.fetch_bottle?(formula) <add> puts formula.bottle.cached_download <add> else <add> puts formula.cached_download <add> end <add> end <add> <add> def print_cask_cache(name) <add> cask = Cask::CaskLoader.load name <add> puts Cask::Cmd::Cache.cached_location(cask) <add> end <add> <ide> end
1
Python
Python
update arraypad to use np.pad in examples
ce1a3b7898484d244806fccc7c52840c11ac98f2
<ide><path>numpy/lib/arraypad.py <ide> def pad(array, pad_width, mode, **kwargs): <ide> Examples <ide> -------- <ide> >>> a = [1, 2, 3, 4, 5] <del> >>> np.lib.pad(a, (2,3), 'constant', constant_values=(4, 6)) <add> >>> np.pad(a, (2,3), 'constant', constant_values=(4, 6)) <ide> array([4, 4, 1, 2, 3, 4, 5, 6, 6, 6]) <ide> <del> >>> np.lib.pad(a, (2, 3), 'edge') <add> >>> np.pad(a, (2, 3), 'edge') <ide> array([1, 1, 1, 2, 3, 4, 5, 5, 5, 5]) <ide> <del> >>> np.lib.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4)) <add> >>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4)) <ide> array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4]) <ide> <del> >>> np.lib.pad(a, (2,), 'maximum') <add> >>> np.pad(a, (2,), 'maximum') <ide> array([5, 5, 1, 2, 3, 4, 5, 5, 5]) <ide> <del> >>> np.lib.pad(a, (2,), 'mean') <add> >>> np.pad(a, (2,), 'mean') <ide> array([3, 3, 1, 2, 3, 4, 5, 3, 3]) <ide> <del> >>> np.lib.pad(a, (2,), 'median') <add> >>> np.pad(a, (2,), 'median') <ide> array([3, 3, 1, 2, 3, 4, 5, 3, 3]) <ide> <ide> >>> a = [[1, 2], [3, 4]] <del> >>> np.lib.pad(a, ((3, 2), (2, 3)), 'minimum') <add> >>> np.pad(a, ((3, 2), (2, 3)), 'minimum') <ide> array([[1, 1, 1, 2, 1, 1, 1], <ide> [1, 1, 1, 2, 1, 1, 1], <ide> [1, 1, 1, 2, 1, 1, 1], <ide> def pad(array, pad_width, mode, **kwargs): <ide> [1, 1, 1, 2, 1, 1, 1]]) <ide> <ide> >>> a = [1, 2, 3, 4, 5] <del> >>> np.lib.pad(a, (2, 3), 'reflect') <add> >>> np.pad(a, (2, 3), 'reflect') <ide> array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2]) <ide> <del> >>> np.lib.pad(a, (2, 3), 'reflect', reflect_type='odd') <add> >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd') <ide> array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) <ide> <del> >>> np.lib.pad(a, (2, 3), 'symmetric') <add> >>> np.pad(a, (2, 3), 'symmetric') <ide> array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3]) <ide> <del> >>> np.lib.pad(a, (2, 3), 'symmetric', reflect_type='odd') <add> >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd') <ide> array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7]) <ide> <del> >>> np.lib.pad(a, (2, 3), 'wrap') <add> >>> np.pad(a, (2, 3), 'wrap') <ide> array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3]) <ide> <ide> >>> def pad_with(vector, pad_width, iaxis, kwargs): <ide> def pad(array, pad_width, mode, **kwargs): <ide> ... return vector <ide> >>> a = np.arange(6) <ide> >>> a = a.reshape((2, 3)) <del> >>> np.lib.pad(a, 2, pad_with) <add> >>> np.pad(a, 2, pad_with) <ide> array([[10, 10, 10, 10, 10, 10, 10], <ide> [10, 10, 10, 10, 10, 10, 10], <ide> [10, 10, 0, 1, 2, 10, 10], <ide> [10, 10, 3, 4, 5, 10, 10], <ide> [10, 10, 10, 10, 10, 10, 10], <ide> [10, 10, 10, 10, 10, 10, 10]]) <del> >>> np.lib.pad(a, 2, pad_with, padder=100) <add> >>> np.pad(a, 2, pad_with, padder=100) <ide> array([[100, 100, 100, 100, 100, 100, 100], <ide> [100, 100, 100, 100, 100, 100, 100], <ide> [100, 100, 0, 1, 2, 100, 100],
1
Ruby
Ruby
unify version.create usage
3fb5d70a729472a7d7f2a5d0d7b84248921fb583
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_specs <ide> case stable && stable.url <ide> when %r{download\.gnome\.org/sources}, %r{ftp\.gnome\.org/pub/GNOME/sources}i <ide> version = Version.parse(stable.url) <del> if version >= Version.new("1.0") <add> if version >= Version.create("1.0") <ide> minor_version = version.to_s.split(".", 3)[1].to_i <ide> if minor_version.odd? <ide> problem "#{stable.version} is a development release" <ide><path>Library/Homebrew/cmd/create.rb <ide> def url=(url) <ide> end <ide> update_path <ide> if @version <del> @version = Version.new(@version) <add> @version = Version.create(@version) <ide> else <ide> @version = Pathname.new(url).version <ide> end <ide><path>Library/Homebrew/cmd/pull.rb <ide> def any_bottle_tag <ide> <ide> def version(spec_type) <ide> version_str = info["versions"][spec_type.to_s] <del> version_str && Version.new(version_str) <add> version_str && Version.create(version_str) <ide> end <ide> <ide> def pkg_version(spec_type = :stable) <ide><path>Library/Homebrew/diagnostic.rb <ide> def check_filesystem_case_sensitive <ide> def check_git_version <ide> # https://help.github.com/articles/https-cloning-errors <ide> return unless Utils.git_available? <del> return unless Version.new(Utils.git_version) < Version.new("1.7.10") <add> return unless Version.create(Utils.git_version) < Version.create("1.7.10") <ide> <ide> git = Formula["git"] <ide> git_upgrade_cmd = git.any_version_installed? ? "upgrade" : "install" <ide><path>Library/Homebrew/extend/ENV/shared.rb <ide> def check_for_compiler_universal_support <ide> <ide> def gcc_with_cxx11_support?(cc) <ide> version = cc[/^gcc-(\d+(?:\.\d+)?)$/, 1] <del> version && Version.new(version) >= Version.new("4.8") <add> version && Version.create(version) >= Version.create("4.8") <ide> end <ide> end <ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb <ide> def check_for_latest_xquartz <ide> return unless MacOS::XQuartz.version <ide> return if MacOS::XQuartz.provided_by_apple? <ide> <del> installed_version = Version.new(MacOS::XQuartz.version) <del> latest_version = Version.new(MacOS::XQuartz.latest_version) <add> installed_version = Version.create(MacOS::XQuartz.version) <add> latest_version = Version.create(MacOS::XQuartz.latest_version) <ide> return if installed_version >= latest_version <ide> <ide> <<-EOS.undent <ide><path>Library/Homebrew/formula.rb <ide> def to_hash <ide> } <ide> end <ide> <del> hsh["installed"] = hsh["installed"].sort_by { |i| Version.new(i["version"]) } <add> hsh["installed"] = hsh["installed"].sort_by { |i| Version.create(i["version"]) } <ide> <ide> hsh <ide> end <ide><path>Library/Homebrew/language/python.rb <ide> module Python <ide> def self.major_minor_version(python) <ide> version = /\d\.\d/.match `#{python} --version 2>&1` <ide> return unless version <del> Version.new(version.to_s) <add> Version.create(version.to_s) <ide> end <ide> <ide> def self.homebrew_site_packages(version = "2.7") <ide><path>Library/Homebrew/requirements/emacs_requirement.rb <ide> def initialize(tags) <ide> next false unless which "emacs" <ide> next true unless @version <ide> emacs_version = Utils.popen_read("emacs", "--batch", "--eval", "(princ emacs-version)") <del> Version.new(emacs_version) >= Version.new(@version) <add> Version.create(emacs_version) >= Version.create(@version) <ide> end <ide> <ide> env do <ide><path>Library/Homebrew/requirements/perl_requirement.rb <ide> def initialize(tags) <ide> which_all("perl").detect do |perl| <ide> perl_version = Utils.popen_read(perl, "--version")[/\(v(\d+\.\d+)(?:\.\d+)?\)/, 1] <ide> next unless perl_version <del> Version.new(perl_version.to_s) >= Version.new(@version) <add> Version.create(perl_version.to_s) >= Version.create(@version) <ide> end <ide> end <ide> <ide><path>Library/Homebrew/requirements/python_requirement.rb <ide> class PythonRequirement < Requirement <ide> version = python_short_version <ide> next unless version <ide> # Always use Python 2.7 for consistency on older versions of OSX. <del> version == Version.new("2.7") <add> version == Version.create("2.7") <ide> end <ide> <ide> env do <ide> short_version = python_short_version <ide> <del> if !system_python? && short_version == Version.new("2.7") <add> if !system_python? && short_version == Version.create("2.7") <ide> ENV.prepend_path "PATH", which_python.dirname <ide> # Homebrew Python should take precedence over older Pythons in the PATH <del> elsif short_version != Version.new("2.7") <add> elsif short_version != Version.create("2.7") <ide> ENV.prepend_path "PATH", Formula["python"].opt_bin <ide> end <ide> <ide><path>Library/Homebrew/requirements/ruby_requirement.rb <ide> def initialize(tags) <ide> which_all("ruby").detect do |ruby| <ide> version = /\d\.\d/.match Utils.popen_read(ruby, "--version") <ide> next unless version <del> Version.new(version.to_s) >= Version.new(@version) <add> Version.create(version.to_s) >= Version.create(@version) <ide> end <ide> end <ide> <ide><path>Library/Homebrew/requirements/x11_requirement.rb <ide> class X11Requirement < Requirement <ide> def initialize(name = "x11", tags = []) <ide> @name = name <ide> if /(\d\.)+\d/ === tags.first <del> @min_version = Version.new(tags.shift) <add> @min_version = Version.create(tags.shift) <ide> @min_version_string = " #{@min_version}" <ide> else <del> @min_version = Version.new("0.0.0") <add> @min_version = Version.create("0.0.0") <ide> @min_version_string = "" <ide> end <ide> super(tags) <ide> end <ide> <ide> satisfy :build_env => false do <del> MacOS::XQuartz.installed? && min_version <= Version.new(MacOS::XQuartz.version) <add> MacOS::XQuartz.installed? && min_version <= Version.create(MacOS::XQuartz.version) <ide> end <ide> <ide> def message <ide><path>Library/Homebrew/software_spec.rb <ide> def add_dep_option(dep) <ide> class HeadSoftwareSpec < SoftwareSpec <ide> def initialize <ide> super <del> @resource.version = HeadVersion.new("HEAD") <add> @resource.version = Version.create("HEAD") <ide> end <ide> <ide> def verify_download_integrity(_fn) <ide><path>Library/Homebrew/test/test_pkg_version.rb <ide> def v(version) <ide> end <ide> <ide> def test_parse <del> assert_equal PkgVersion.new(Version.new("1.0"), 1), PkgVersion.parse("1.0_1") <del> assert_equal PkgVersion.new(Version.new("1.0"), 1), PkgVersion.parse("1.0_1") <del> assert_equal PkgVersion.new(Version.new("1.0"), 0), PkgVersion.parse("1.0") <del> assert_equal PkgVersion.new(Version.new("1.0"), 0), PkgVersion.parse("1.0_0") <del> assert_equal PkgVersion.new(Version.new("2.1.4"), 0), PkgVersion.parse("2.1.4_0") <del> assert_equal PkgVersion.new(Version.new("1.0.1e"), 1), PkgVersion.parse("1.0.1e_1") <add> assert_equal PkgVersion.new(Version.create("1.0"), 1), PkgVersion.parse("1.0_1") <add> assert_equal PkgVersion.new(Version.create("1.0"), 1), PkgVersion.parse("1.0_1") <add> assert_equal PkgVersion.new(Version.create("1.0"), 0), PkgVersion.parse("1.0") <add> assert_equal PkgVersion.new(Version.create("1.0"), 0), PkgVersion.parse("1.0_0") <add> assert_equal PkgVersion.new(Version.create("2.1.4"), 0), PkgVersion.parse("2.1.4_0") <add> assert_equal PkgVersion.new(Version.create("1.0.1e"), 1), PkgVersion.parse("1.0.1e_1") <ide> end <ide> <ide> def test_comparison <ide> def test_comparison <ide> assert_operator v("HEAD"), :>, v("1.0") <ide> assert_operator v("1.0"), :<, v("HEAD") <ide> <del> v = PkgVersion.new(Version.new("1.0"), 0) <add> v = PkgVersion.new(Version.create("1.0"), 0) <ide> assert_nil v <=> Object.new <ide> assert_raises(ArgumentError) { v > Object.new } <del> assert_raises(ArgumentError) { v > Version.new("1.0") } <add> assert_raises(ArgumentError) { v > Version.create("1.0") } <ide> end <ide> <ide> def test_to_s <del> assert_equal "1.0", PkgVersion.new(Version.new("1.0"), 0).to_s <del> assert_equal "1.0_1", PkgVersion.new(Version.new("1.0"), 1).to_s <del> assert_equal "1.0", PkgVersion.new(Version.new("1.0"), 0).to_s <del> assert_equal "1.0", PkgVersion.new(Version.new("1.0"), 0).to_s <add> assert_equal "1.0", PkgVersion.new(Version.create("1.0"), 0).to_s <add> assert_equal "1.0_1", PkgVersion.new(Version.create("1.0"), 1).to_s <add> assert_equal "1.0", PkgVersion.new(Version.create("1.0"), 0).to_s <add> assert_equal "1.0", PkgVersion.new(Version.create("1.0"), 0).to_s <ide> assert_equal "HEAD_1", PkgVersion.new(Version.create("HEAD"), 1).to_s <ide> assert_equal "HEAD-ffffff_1", PkgVersion.new(Version.create("HEAD-ffffff"), 1).to_s <ide> end <ide> <ide> def test_hash <del> p1 = PkgVersion.new(Version.new("1.0"), 1) <del> p2 = PkgVersion.new(Version.new("1.0"), 1) <del> p3 = PkgVersion.new(Version.new("1.1"), 1) <del> p4 = PkgVersion.new(Version.new("1.0"), 0) <add> p1 = PkgVersion.new(Version.create("1.0"), 1) <add> p2 = PkgVersion.new(Version.create("1.0"), 1) <add> p3 = PkgVersion.new(Version.create("1.1"), 1) <add> p4 = PkgVersion.new(Version.create("1.0"), 0) <ide> assert_equal p1.hash, p2.hash <ide> refute_equal p1.hash, p3.hash <ide> refute_equal p1.hash, p4.hash <ide><path>Library/Homebrew/test/test_version_subclasses.rb <ide> def test_compare_with_string <ide> end <ide> <ide> def test_compare_with_version <del> assert_operator @v, :>, Version.new("10.6") <del> assert_operator @v, :==, Version.new("10.7") <del> assert_operator @v, :===, Version.new("10.7") <del> assert_operator @v, :<, Version.new("10.8") <add> assert_operator @v, :>, Version.create("10.6") <add> assert_operator @v, :==, Version.create("10.7") <add> assert_operator @v, :===, Version.create("10.7") <add> assert_operator @v, :<, Version.create("10.8") <ide> end <ide> <ide> def test_from_symbol <ide><path>Library/Homebrew/test/test_versions.rb <ide> class VersionTests < Homebrew::TestCase <ide> def test_accepts_objects_responding_to_to_str <ide> value = stub(:to_str => "0.1") <del> assert_equal "0.1", Version.new(value).to_s <add> assert_equal "0.1", Version.create(value).to_s <ide> end <ide> <ide> def test_raises_for_non_string_objects <del> assert_raises(TypeError) { Version.new(1.1) } <del> assert_raises(TypeError) { Version.new(1) } <del> assert_raises(TypeError) { Version.new(:symbol) } <add> assert_raises(TypeError) { Version.create(1.1) } <add> assert_raises(TypeError) { Version.create(1) } <add> assert_raises(TypeError) { Version.create(:symbol) } <ide> end <ide> <ide> def test_detected_from_url? <del> refute Version.new("1.0").detected_from_url? <add> refute Version.create("1.0").detected_from_url? <ide> assert Version::FromURL.new("1.0").detected_from_url? <ide> end <ide> end <ide> def test_create_head <ide> end <ide> <ide> def test_commit_assigned <del> v = HeadVersion.new("HEAD-abcdef") <add> v = Version.create("HEAD-abcdef") <ide> assert_equal "abcdef", v.commit <ide> assert_equal "HEAD-abcdef", v.to_str <ide> end <ide> <ide> def test_no_commit <del> v = HeadVersion.new("HEAD") <add> v = Version.create("HEAD") <ide> assert_nil v.commit <ide> assert_equal "HEAD", v.to_str <ide> end <ide> <ide> def test_update_commit <del> v1 = HeadVersion.new("HEAD-abcdef") <del> v2 = HeadVersion.new("HEAD") <add> v1 = Version.create("HEAD-abcdef") <add> v2 = Version.create("HEAD") <ide> <ide> v1.update_commit("ffffff") <ide> assert_equal "ffffff", v1.commit <ide><path>Library/Homebrew/test/testing_env.rb <ide> def version(v) <ide> end <ide> <ide> def assert_version_equal(expected, actual) <del> assert_equal Version.new(expected), actual <add> assert_equal Version.create(expected), actual <ide> end <ide> <ide> def assert_version_detected(expected, url, specs={})
18
Mixed
Javascript
support abortsignal in writefile
d9dadacb35d7b2f88b0a89b4828e639e8441fc45
<ide><path>doc/api/fs.md <ide> details. <ide> <!-- YAML <ide> added: v0.1.29 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/35993 <add> description: The options argument may include an AbortSignal to abort an <add> ongoing writeFile request. <ide> - version: v14.12.0 <ide> pr-url: https://github.com/nodejs/node/pull/34993 <ide> description: The `data` parameter will stringify an object with an <ide> changes: <ide> * `encoding` {string|null} **Default:** `'utf8'` <ide> * `mode` {integer} **Default:** `0o666` <ide> * `flag` {string} See [support of file system `flags`][]. **Default:** `'w'`. <add> * `signal` {AbortSignal} allows aborting an in-progress writeFile <ide> * `callback` {Function} <ide> * `err` {Error} <ide> <ide> It is unsafe to use `fs.writeFile()` multiple times on the same file without <ide> waiting for the callback. For this scenario, [`fs.createWriteStream()`][] is <ide> recommended. <ide> <add>Similarly to `fs.readFile` - `fs.writeFile` is a convenience method that <add>performs multiple `write` calls internally to write the buffer passed to it. <add>For performance sensitive code consider using [`fs.createWriteStream()`][]. <add> <add>It is possible to use an {AbortSignal} to cancel an `fs.writeFile()`. <add>Cancelation is "best effort", and some amount of data is likely still <add>to be written. <add> <add>```js <add>const controller = new AbortController(); <add>const { signal } = controller; <add>const data = new Uint8Array(Buffer.from('Hello Node.js')); <add>fs.writeFile('message.txt', data, { signal }, (err) => { <add> // When a request is aborted - the callback is called with an AbortError <add>}); <add>// When the request should be aborted <add>controller.abort(); <add>``` <add> <add>Aborting an ongoing request does not abort individual operating <add>system requests but rather the internal buffering `fs.writeFile` performs. <add> <ide> ### Using `fs.writeFile()` with file descriptors <ide> <ide> When `file` is a file descriptor, the behavior is almost identical to directly <ide> The `atime` and `mtime` arguments follow these rules: <ide> <!-- YAML <ide> added: v10.0.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/35993 <add> description: The options argument may include an AbortSignal to abort an <add> ongoing writeFile request. <ide> - version: v14.12.0 <ide> pr-url: https://github.com/nodejs/node/pull/34993 <ide> description: The `data` parameter will stringify an object with an <ide> changes: <ide> * `encoding` {string|null} **Default:** `'utf8'` <ide> * `mode` {integer} **Default:** `0o666` <ide> * `flag` {string} See [support of file system `flags`][]. **Default:** `'w'`. <add> * `signal` {AbortSignal} allows aborting an in-progress writeFile <ide> * Returns: {Promise} <ide> <ide> Asynchronously writes data to a file, replacing the file if it already exists. <ide> If `options` is a string, then it specifies the encoding. <ide> Any specified `FileHandle` has to support writing. <ide> <ide> It is unsafe to use `fsPromises.writeFile()` multiple times on the same file <del>without waiting for the `Promise` to be resolved (or rejected). <add>without waiting for the `Promise` to be fulfilled (or rejected). <add> <add>Similarly to `fsPromises.readFile` - `fsPromises.writeFile` is a convenience <add>method that performs multiple `write` calls internally to write the buffer <add>passed to it. For performance sensitive code consider using <add>[`fs.createWriteStream()`][]. <add> <add>It is possible to use an {AbortSignal} to cancel an `fsPromises.writeFile()`. <add>Cancelation is "best effort", and some amount of data is likely still <add>to be written. <add> <add>```js <add>const controller = new AbortController(); <add>const { signal } = controller; <add>const data = new Uint8Array(Buffer.from('Hello Node.js')); <add>(async () => { <add> try { <add> await fs.writeFile('message.txt', data, { signal }); <add> } catch (err) { <add> // When a request is aborted - err is an AbortError <add> } <add>})(); <add>// When the request should be aborted <add>controller.abort(); <add>``` <add> <add>Aborting an ongoing request does not abort individual operating <add>system requests but rather the internal buffering `fs.writeFile` performs. <ide> <ide> ## FS constants <ide> <ide><path>lib/fs.js <ide> const { <ide> ERR_INVALID_CALLBACK, <ide> ERR_FEATURE_UNAVAILABLE_ON_PLATFORM <ide> }, <add> hideStackFrames, <ide> uvException <ide> } = require('internal/errors'); <ide> <ide> let ReadStream; <ide> let WriteStream; <ide> let rimraf; <ide> let rimrafSync; <add>let DOMException; <add> <add>const lazyDOMException = hideStackFrames((message, name) => { <add> if (DOMException === undefined) <add> DOMException = internalBinding('messaging').DOMException; <add> return new DOMException(message, name); <add>}); <ide> <ide> // These have to be separate because of how graceful-fs happens to do it's <ide> // monkeypatching. <ide> function lutimesSync(path, atime, mtime) { <ide> handleErrorFromBinding(ctx); <ide> } <ide> <del>function writeAll(fd, isUserFd, buffer, offset, length, callback) { <add>function writeAll(fd, isUserFd, buffer, offset, length, signal, callback) { <add> if (signal?.aborted) { <add> callback(lazyDOMException('The operation was aborted', 'AbortError')); <add> return; <add> } <ide> // write(fd, buffer, offset, length, position, callback) <ide> fs.write(fd, buffer, offset, length, null, (writeErr, written) => { <ide> if (writeErr) { <ide> function writeAll(fd, isUserFd, buffer, offset, length, callback) { <ide> } else { <ide> offset += written; <ide> length -= written; <del> writeAll(fd, isUserFd, buffer, offset, length, callback); <add> writeAll(fd, isUserFd, buffer, offset, length, signal, callback); <ide> } <ide> }); <ide> } <ide> function writeFile(path, data, options, callback) { <ide> <ide> if (isFd(path)) { <ide> const isUserFd = true; <del> writeAll(path, isUserFd, data, 0, data.byteLength, callback); <add> const signal = options.signal; <add> writeAll(path, isUserFd, data, 0, data.byteLength, signal, callback); <ide> return; <ide> } <ide> <add> if (options.signal?.aborted) { <add> callback(lazyDOMException('The operation was aborted', 'AbortError')); <add> return; <add> } <ide> fs.open(path, flag, options.mode, (openErr, fd) => { <ide> if (openErr) { <ide> callback(openErr); <ide> } else { <ide> const isUserFd = false; <del> writeAll(fd, isUserFd, data, 0, data.byteLength, callback); <add> const signal = options.signal; <add> writeAll(fd, isUserFd, data, 0, data.byteLength, signal, callback); <ide> } <ide> }); <ide> } <ide><path>lib/internal/fs/promises.js <ide> async function fsCall(fn, handle, ...args) { <ide> } <ide> } <ide> <del>async function writeFileHandle(filehandle, data) { <add>async function writeFileHandle(filehandle, data, signal) { <ide> // `data` could be any kind of typed array. <ide> data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); <ide> let remaining = data.length; <ide> if (remaining === 0) return; <ide> do { <add> if (signal?.aborted) { <add> throw new lazyDOMException('The operation was aborted', 'AbortError'); <add> } <ide> const { bytesWritten } = <ide> await write(filehandle, data, 0, <ide> MathMin(kWriteFileMaxChunkSize, data.length)); <ide> async function writeFile(path, data, options) { <ide> } <ide> <ide> if (path instanceof FileHandle) <del> return writeFileHandle(path, data); <add> return writeFileHandle(path, data, options.signal); <ide> <ide> const fd = await open(path, flag, options.mode); <add> if (options.signal?.aborted) { <add> throw new lazyDOMException('The operation was aborted', 'AbortError'); <add> } <ide> return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close); <ide> } <ide> <ide><path>test/parallel/test-fs-promises-writefile.js <ide> const tmpDir = tmpdir.path; <ide> tmpdir.refresh(); <ide> <ide> const dest = path.resolve(tmpDir, 'tmp.txt'); <add>const otherDest = path.resolve(tmpDir, 'tmp-2.txt'); <ide> const buffer = Buffer.from('abc'.repeat(1000)); <ide> const buffer2 = Buffer.from('xyz'.repeat(1000)); <ide> <ide> async function doWrite() { <ide> assert.deepStrictEqual(data, buffer); <ide> } <ide> <add>async function doWriteWithCancel() { <add> const controller = new AbortController(); <add> const { signal } = controller; <add> process.nextTick(() => controller.abort()); <add> assert.rejects(fsPromises.writeFile(otherDest, buffer, { signal }), { <add> name: 'AbortError' <add> }); <add>} <add> <ide> async function doAppend() { <ide> await fsPromises.appendFile(dest, buffer2); <ide> const data = fs.readFileSync(dest); <ide> async function doReadWithEncoding() { <ide> } <ide> <ide> doWrite() <add> .then(doWriteWithCancel) <ide> .then(doAppend) <ide> .then(doRead) <ide> .then(doReadWithEncoding) <ide><path>test/parallel/test-fs-write-file.js <ide> fs.open(filename4, 'w+', common.mustSucceed((fd) => { <ide> })); <ide> })); <ide> })); <add> <add> <add>{ <add> // Test that writeFile is cancellable with an AbortSignal. <add> // Before the operation has started <add> const controller = new AbortController(); <add> const signal = controller.signal; <add> const filename3 = join(tmpdir.path, 'test3.txt'); <add> <add> fs.writeFile(filename3, s, { signal }, common.mustCall((err) => { <add> assert.strictEqual(err.name, 'AbortError'); <add> })); <add> <add> controller.abort(); <add>} <add> <add>{ <add> // Test that writeFile is cancellable with an AbortSignal. <add> // After the operation has started <add> const controller = new AbortController(); <add> const signal = controller.signal; <add> const filename4 = join(tmpdir.path, 'test4.txt'); <add> <add> fs.writeFile(filename4, s, { signal }, common.mustCall((err) => { <add> assert.strictEqual(err.name, 'AbortError'); <add> })); <add> <add> process.nextTick(() => controller.abort()); <add>}
5
PHP
PHP
update hasmany to avoid ambigous columns
54d8e7683243f62e8ce55c53906e3c9ea4bd6b04
<ide><path>src/ORM/Association/HasMany.php <ide> namespace Cake\ORM\Association; <ide> <ide> use Cake\Collection\Collection; <add>use Cake\Database\Expression\FieldInterface; <add>use Cake\Database\Expression\QueryExpression; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\ORM\Association; <ide> use Cake\ORM\Table; <ide> protected function _unlink(array $foreignKey, Table $target, array $conditions = <ide> <ide> if ($mustBeDependent) { <ide> if ($this->_cascadeCallbacks) { <add> $conditions = new QueryExpression($conditions); <add> $conditions->traverse(function ($entry) use ($target) { <add> if ($entry instanceof FieldInterface) { <add> $entry->setField($target->aliasField($entry->getField())); <add> } <add> }); <ide> $query = $this->find('all')->where($conditions); <ide> $ok = true; <ide> foreach ($query as $assoc) {
1
PHP
PHP
fix eloquent->delete bug
75f63847673f241463c00f42134277039b0e38c2
<ide><path>laravel/database/eloquent/model.php <ide> public function save() <ide> return $result; <ide> } <ide> <add> /** <add> * Delete the model from the database. <add> * <add> * @return int <add> */ <add> public function delete() <add> { <add> if ($this->exists) <add> { <add> return $this->query()->where(static::$key, '=', $this->get_key())->delete(); <add> } <add> } <add> <ide> /** <ide> * Set the update and creation timestamps on the model. <ide> * <ide><path>laravel/database/eloquent/relationships/has_many_and_belongs_to.php <ide> public function insert($attributes, $joining = array()) <ide> */ <ide> public function delete() <ide> { <del> $id = $this->base->get_key(); <del> <del> return $this->joining_table()->where($this->foreign_key(), '=', $id)->delete(); <add> return $this->pivot()->delete(); <ide> } <ide> <ide> /**
2
Ruby
Ruby
use new hash style in doc examples [ci skip]
d9ac2afc8fc49c2d8b0cf2ddbea374ffbb48c0f4
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def rename_column(table_name, column_name, new_column_name) <ide> # <ide> # ====== Creating an index with a specific method <ide> # <del> # add_index(:developers, :name, :using => 'btree') <add> # add_index(:developers, :name, using: 'btree') <ide> # <ide> # generates <ide> # <ide> def rename_column(table_name, column_name, new_column_name) <ide> # <ide> # ====== Creating an index with a specific type <ide> # <del> # add_index(:developers, :name, :type => :fulltext) <add> # add_index(:developers, :name, type: :fulltext) <ide> # <ide> # generates <ide> #
1
Ruby
Ruby
rename a variable name for consistency
22bfd8b09804db28e05e598e062d58fd2ab36485
<ide><path>activerecord/lib/active_record/relation.rb <ide> class Relation <ide> <ide> attr_reader :relation, :klass <ide> attr_writer :readonly, :table <del> attr_accessor :preload_associations, :eager_load_associations, :include_associations <add> attr_accessor :preload_associations, :eager_load_associations, :includes_associations <ide> <ide> def initialize(klass, relation) <ide> @klass, @relation = klass, relation <ide> @preload_associations = [] <ide> @eager_load_associations = [] <del> @include_associations = [] <add> @includes_associations = [] <ide> @loaded, @readonly = false <ide> end <ide> <ide> def to_a <ide> :offset => @relation.skipped, <ide> :from => (@relation.send(:from_clauses) if @relation.send(:sources).present?) <ide> }, <del> ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, @eager_load_associations + @include_associations, nil)) <add> ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, @eager_load_associations + @includes_associations, nil)) <ide> rescue ThrowResult <ide> [] <ide> end <ide> def to_a <ide> end <ide> <ide> preload = @preload_associations <del> preload += @include_associations unless find_with_associations <add> preload += @includes_associations unless find_with_associations <ide> preload.each {|associations| @klass.send(:preload_associations, @records, associations) } <ide> <ide> @records.each { |record| record.readonly! } if @readonly <ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def preload(*associations) <ide> end <ide> <ide> def includes(*associations) <del> spawn.tap {|r| r.include_associations += Array.wrap(associations) } <add> spawn.tap {|r| r.includes_associations += Array.wrap(associations) } <ide> end <ide> <ide> def eager_load(*associations) <ide><path>activerecord/lib/active_record/relation/spawn_methods.rb <ide> def spawn(relation = @relation) <ide> relation.readonly = @readonly <ide> relation.preload_associations = @preload_associations <ide> relation.eager_load_associations = @eager_load_associations <del> relation.include_associations = @include_associations <add> relation.includes_associations = @includes_associations <ide> relation.table = table <ide> relation <ide> end <ide> <ide> def merge(r) <ide> raise ArgumentError, "Cannot merge a #{r.klass.name} relation with #{@klass.name} relation" if r.klass != @klass <ide> <del> merged_relation = spawn(table).eager_load(r.eager_load_associations).preload(r.preload_associations).includes(r.include_associations) <add> merged_relation = spawn(table).eager_load(r.eager_load_associations).preload(r.preload_associations).includes(r.includes_associations) <ide> merged_relation.readonly = r.readonly <ide> <ide> [self.relation, r.relation].each do |arel|
3
Mixed
Text
fix spelling of "harmony"
a59672a5e1102f7c1f5774a7336c003510f44b2e
<ide><path>examples/code-splitted-require.context-amd/README.md <ide> getTemplate("b", function(b) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/code-splitted-require.context/README.md <ide> getTemplate("b", function(b) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/code-splitting-bundle-loader/README.md <ide> module.exports = "It works"; <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/code-splitting-harmony/README.md <ide> Promise.all([loadC("1"), loadC("2")]).then(function(arr) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/code-splitting/README.md <ide> require.ensure(["c"], function(require) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/coffee-script/README.md <ide> module.exports = 42 <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> chunk {0} output.js (main) 206 bytes [entry] [rendered] <ide> [1] ./cup1.coffee 118 bytes {0} [built] <ide> cjs require ./cup1 [2] ./example.js 1:12-29 <ide> [2] ./example.js 31 bytes {0} [built] <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/common-chunk-and-vendor-chunk/README.md <ide> module.exports = { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/commonjs/README.md <ide> exports.add = function() { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> chunk {0} output.js (main) 318 bytes [entry] [rendered] <ide> [1] ./math.js 156 bytes {0} [built] <ide> cjs require ./math [0] ./increment.js 1:10-27 <ide> [2] ./example.js 67 bytes {0} [built] <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/css-bundle/README.md <ide> module.exports = { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> Child extract-text-webpack-plugin: <ide> [1] ./image.png 82 bytes {0} [built] <ide> cjs require ./image.png [2] (webpack)/~/css-loader!./style.css 6:50-72 <ide> [2] (webpack)/~/css-loader!./style.css 211 bytes {0} [built] <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/dll-user/README.md <ide> console.log(require("module")); <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> chunk {0} output.js (main) 541 bytes [entry] [rendered] <ide> > main [8] ./example.js <ide> [8] ./example.js 205 bytes {0} [built] <ide> + 8 hidden modules <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/dll/README.md <ide> var alpha_282e8826843b2bb4eeb1 = <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> chunk {1} MyDll.alpha.js (alpha) 84 bytes [entry] [rendered] <ide> [5] ../~/module.js 26 bytes {1} [built] <ide> single entry module [6] dll alpha <ide> [6] dll alpha 12 bytes {1} [built] <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/explicit-vendor-chunk/README.md <ide> var vendor_32199746b38d6e93b44b = <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> module.exports = __webpack_require__; <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/externals/README.md <ide> return /******/ (function(modules) { // webpackBootstrap <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> chunk {0} output.js (main) 194 bytes [entry] [rendered] <ide> > main [2] ./example.js <ide> [2] ./example.js 110 bytes {0} [built] <ide> + 2 hidden modules <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/extra-async-chunk-advanced/README.md <ide> module.exports = { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/extra-async-chunk/README.md <ide> module.exports = { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/harmony-interop/README.md <ide> export var named = "named"; <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> chunk {0} output.js (main) 1.16 kB [entry] [rendered] <ide> [exports: default, named] <ide> cjs require ./harmony [1] ./example2.js 4:13-33 <ide> [4] ./example.js 373 bytes {0} [built] <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/harmony-unused/README.md <ide> export { add as reexportedAdd, multiply as reexportedMultiply } from "./math"; <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/harmony/README.md <ide> export function increment(val) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> chunk {1} output.js (main) 407 bytes [entry] [rendered] <ide> [only some exports used: add] <ide> harmony import ./math [0] ./increment.js 1:0-29 <ide> [3] ./example.js 182 bytes {1} [built] <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/hybrid-routing/README.md <ide> window.onLinkToPage = function onLinkToPage(name) { // name is "a" or "b" <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/i18n/README.md <ide> module.exports = Object.keys(languages).map(function(language) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> console.log("Missing Text"); <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> Child de: <ide> <ide> WARNING in ./example.js <ide> Missing localization: Missing Text <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/loader/README.md <ide> module.exports = function(content) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/mixed/README.md <ide> require( <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/multi-compiler/README.md <ide> module.exports = [ <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> console.log("Running " + "desktop" + " build"); <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> Child desktop: <ide> chunk {0} desktop.js (main) 94 bytes [entry] [rendered] <ide> > main [0] ./example.js <ide> [0] ./example.js 94 bytes {0} [built] <del>``` <ide>\ No newline at end of file <add>``` <ide><path>examples/multi-part-library/README.md <ide> return /******/ (function(modules) { // webpackBootstrap <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> return /******/ (function(modules) { // webpackBootstrap <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/multiple-commons-chunks/README.md <ide> module.exports = { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/multiple-entry-points/README.md <ide> module.exports = { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/named-chunks/README.md <ide> require.ensure(["b"], function(require) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/require.context/README.md <ide> module.exports = function() { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/require.resolve/README.md <ide> module.exports = Math.random(); <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/two-explicit-vendor-chunks/README.md <ide> module.exports = { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>examples/web-worker/README.md <ide> onmessage = function(event) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide> worker.onmessage = function(event) { <ide> /******/ // expose the module cache <ide> /******/ __webpack_require__.c = installedModules; <ide> <del>/******/ // identity function for calling harmory imports with the correct context <add>/******/ // identity function for calling harmony imports with the correct context <ide> /******/ __webpack_require__.i = function(value) { return value; }; <ide> <del>/******/ // define getter function for harmory exports <add>/******/ // define getter function for harmony exports <ide> /******/ __webpack_require__.d = function(exports, name, getter) { <ide> /******/ Object.defineProperty(exports, name, { <ide> /******/ configurable: false, <ide><path>lib/MainTemplate.js <ide> function MainTemplate(outputOptions) { <ide> buf.push(this.requireFn + ".c = installedModules;"); <ide> <ide> buf.push(""); <del> buf.push("// identity function for calling harmory imports with the correct context"); <add> buf.push("// identity function for calling harmony imports with the correct context"); <ide> buf.push(this.requireFn + ".i = function(value) { return value; };"); <ide> <ide> buf.push(""); <del> buf.push("// define getter function for harmory exports"); <add> buf.push("// define getter function for harmony exports"); <ide> buf.push(this.requireFn + ".d = function(exports, name, getter) {"); <ide> buf.push(this.indent([ <ide> "if(!" + this.requireFn + ".o(exports, name)) {", <ide><path>lib/dependencies/HarmonyModulesHelpers.js <ide> HarmonyModulesHelpers.checkModuleVar = function(state, request) { <ide> return HarmonyModulesHelpers.getModuleVar(state, request); <ide> }; <ide> <del>// checks if an harmory dependency is active in a module according to <add>// checks if an harmony dependency is active in a module according to <ide> // precedence rules. <ide> HarmonyModulesHelpers.isActive = function(module, depInQuestion) { <ide> var desc = depInQuestion.describeHarmonyExport();
33
Javascript
Javascript
add promises metadata to postmortem test
cf5624c4d8f16397c6d12aaf13bcc3ecfe10b8fe
<ide><path>test/v8-updates/test-postmortem-metadata.js <ide> function getExpectedSymbols() { <ide> 'v8dbg_type_JSFunction__JS_FUNCTION_TYPE', <ide> 'v8dbg_type_JSGlobalObject__JS_GLOBAL_OBJECT_TYPE', <ide> 'v8dbg_type_JSGlobalProxy__JS_GLOBAL_PROXY_TYPE', <add> 'v8dbg_type_JSMessageObject__JS_MESSAGE_OBJECT_TYPE', <ide> 'v8dbg_type_JSObject__JS_OBJECT_TYPE', <add> 'v8dbg_type_JSPromise__JS_PROMISE_TYPE', <ide> 'v8dbg_type_JSRegExp__JS_REG_EXP_TYPE', <ide> 'v8dbg_type_JSTypedArray__JS_TYPED_ARRAY_TYPE', <ide> 'v8dbg_type_Map__MAP_TYPE',
1
Python
Python
add letter spacing to arrow label
82154a1861170538e4afe705baa285440ab30476
<ide><path>spacy/displacy/templates.py <ide> TPL_DEP_ARCS = """ <ide> <g class="displacy-arrow"> <ide> <path class="displacy-arc" id="arrow-{id}-{i}" stroke-width="{stroke}px" d="{arc}" fill="none" stroke="currentColor"/> <del> <text dy="1.25em" style="font-size: 0.8em"> <add> <text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px"> <ide> <textPath xlink:href="#arrow-{id}-{i}" class="displacy-label" startOffset="50%" fill="currentColor" text-anchor="middle">{label}</textPath> <ide> </text> <ide> <path class="displacy-arrowhead" d="{head}" fill="currentColor"/>
1
Ruby
Ruby
use media_type instead of content_type internally
7cf445d3bdc466f26b4a1929822ccd34daac19a7
<ide><path>actionpack/lib/action_controller/metal/renderers.rb <ide> def _render_to_body_with_renderer(options) <ide> <ide> "/**/#{options[:callback]}(#{json})" <ide> else <del> self.content_type ||= Mime[:json] <add> self.content_type = Mime[:json] if media_type.nil? <ide> json <ide> end <ide> end <ide> <ide> add :js do |js, options| <del> self.content_type ||= Mime[:js] <add> self.content_type = Mime[:js] if media_type.nil? <ide> js.respond_to?(:to_js) ? js.to_js(options) : js <ide> end <ide> <ide> add :xml do |xml, options| <del> self.content_type ||= Mime[:xml] <add> self.content_type = Mime[:xml] if media_type.nil? <ide> xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml <ide> end <ide> end <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb <ide> def marked_for_same_origin_verification? # :doc: <ide> <ide> # Check for cross-origin JavaScript responses. <ide> def non_xhr_javascript_response? # :doc: <del> %r(\A(?:text|application)/javascript).match?(content_type) && !request.xhr? <add> %r(\A(?:text|application)/javascript).match?(media_type) && !request.xhr? <ide> end <ide> <ide> AUTHENTICITY_TOKEN_LENGTH = 32 <ide><path>actionpack/test/controller/render_js_test.rb <ide> def test_should_render_js_partial <ide> get :show_partial, format: "js", xhr: true <ide> assert_equal "partial js", @response.body <ide> end <add> <add> def test_should_not_trigger_content_type_deprecation <add> original = ActionDispatch::Response.return_only_media_type_on_content_type <add> ActionDispatch::Response.return_only_media_type_on_content_type = true <add> <add> assert_not_deprecated { get :render_vanilla_js_hello, xhr: true } <add> ensure <add> ActionDispatch::Response.return_only_media_type_on_content_type = original <add> end <ide> end <ide><path>actionpack/test/controller/render_json_test.rb <ide> def test_render_json_calls_to_json_from_object <ide> get :render_json_without_options <ide> assert_equal '{"a":"b"}', @response.body <ide> end <add> <add> def test_should_not_trigger_content_type_deprecation <add> original = ActionDispatch::Response.return_only_media_type_on_content_type <add> ActionDispatch::Response.return_only_media_type_on_content_type = true <add> <add> assert_not_deprecated { get :render_json_hello_world } <add> ensure <add> ActionDispatch::Response.return_only_media_type_on_content_type = original <add> end <add> <add> def test_should_not_trigger_content_type_deprecation_with_callback <add> original = ActionDispatch::Response.return_only_media_type_on_content_type <add> ActionDispatch::Response.return_only_media_type_on_content_type = true <add> <add> assert_not_deprecated { get :render_json_hello_world_with_callback, xhr: true } <add> ensure <add> ActionDispatch::Response.return_only_media_type_on_content_type = original <add> end <ide> end <ide><path>actionpack/test/controller/render_xml_test.rb <ide> def test_should_use_implicit_content_type <ide> get :implicit_content_type, format: "atom" <ide> assert_equal Mime[:atom], @response.media_type <ide> end <add> <add> def test_should_not_trigger_content_type_deprecation <add> original = ActionDispatch::Response.return_only_media_type_on_content_type <add> ActionDispatch::Response.return_only_media_type_on_content_type = true <add> <add> assert_not_deprecated { get :render_with_to_xml } <add> ensure <add> ActionDispatch::Response.return_only_media_type_on_content_type = original <add> end <ide> end <ide><path>actionpack/test/controller/request_forgery_protection_test.rb <ide> def test_should_only_allow_cross_origin_js_get_without_xhr_header_if_protection_ <ide> end <ide> end <ide> <add> def test_should_not_trigger_content_type_deprecation <add> original = ActionDispatch::Response.return_only_media_type_on_content_type <add> ActionDispatch::Response.return_only_media_type_on_content_type = true <add> <add> assert_not_deprecated { get :same_origin_js, xhr: true } <add> ensure <add> ActionDispatch::Response.return_only_media_type_on_content_type = original <add> end <add> <ide> def test_should_not_raise_error_if_token_is_not_a_string <ide> assert_blocked do <ide> patch :index, params: { custom_authenticity_token: { foo: "bar" } }
6
Java
Java
fix border-rendering in apis < 18 cont
ca7fe72c31fd7c7cbe4734118019f5808235560e
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java <ide> public void setBorderColor(int position, float rgb, float alpha) { <ide> } <ide> <ide> public void setBorderRadius(float borderRadius) { <del> getOrCreateReactViewBackground().setRadius(borderRadius); <add> ReactViewBackgroundDrawable backgroundDrawable = getOrCreateReactViewBackground(); <add> backgroundDrawable.setRadius(borderRadius); <add> <add> if (Build.VERSION_CODES.HONEYCOMB < Build.VERSION.SDK_INT <add> && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { <add> final int UPDATED_LAYER_TYPE = <add> backgroundDrawable.hasRoundedBorders() <add> ? View.LAYER_TYPE_SOFTWARE <add> : View.LAYER_TYPE_HARDWARE; <add> <add> if (UPDATED_LAYER_TYPE != getLayerType()) { <add> setLayerType(UPDATED_LAYER_TYPE, null); <add> } <add> } <ide> } <ide> <ide> public void setBorderRadius(float borderRadius, int position) {
1
PHP
PHP
remove duplicated code backup
990fbcdea01d25c30bde0d8a37c004568a8cbcb4
<ide><path>lib/Cake/Test/Case/Error/ErrorHandlerTest.php <ide> public function setUp() { <ide> $request = new CakeRequest(null, false); <ide> $request->base = ''; <ide> Router::setRequestInfo($request); <del> $this->_debug = Configure::read('debug'); <del> $this->_error = Configure::read('Error'); <ide> Configure::write('debug', 2); <ide> } <ide> <ide> public function setUp() { <ide> * @return void <ide> */ <ide> public function tearDown() { <del> Configure::write('debug', $this->_debug); <del> Configure::write('Error', $this->_error); <del> App::build(); <ide> if ($this->_restoreError) { <ide> restore_error_handler(); <ide> } <ide><path>lib/Cake/Test/Case/Error/ExceptionRendererTest.php <ide> public function setUp() { <ide> $request = new CakeRequest(null, false); <ide> $request->base = ''; <ide> Router::setRequestInfo($request); <del> $this->_debug = Configure::read('debug'); <del> $this->_error = Configure::read('Error'); <ide> Configure::write('debug', 2); <ide> } <ide> <ide> public function setUp() { <ide> * @return void <ide> */ <ide> public function tearDown() { <del> Configure::write('debug', $this->_debug); <del> Configure::write('Error', $this->_error); <del> App::build(); <ide> if ($this->_restoreError) { <ide> restore_error_handler(); <ide> }
2
PHP
PHP
fix failing tests in 5.3 and 5.4
d8b1be22968f4929d1b02ab89b07f1762c78c7ff
<ide><path>tests/Queue/RedisQueueIntegrationTest.php <ide> <?php <ide> <add>use Carbon\Carbon; <ide> use Mockery as m; <ide> use Illuminate\Redis\Database; <ide> use Illuminate\Queue\RedisQueue; <ide> class RedisQueueIntegrationTest extends PHPUnit_Framework_TestCase <ide> <ide> public function setUp() <ide> { <add> Carbon::setTestNow(); <ide> parent::setUp(); <ide> <ide> $host = getenv('REDIS_HOST') ?: '127.0.0.1'; <ide> public function setUp() <ide> <ide> public function tearDown() <ide> { <add> Carbon::setTestNow(Carbon::now()); <ide> parent::tearDown(); <ide> m::close(); <ide> if ($this->redis) {
1
PHP
PHP
move toarrayresponse() method to http\response
f46432f920a37463aa0c51ae45fcf94d19ec835f
<ide><path>src/Http/Response.php <ide> use Cake\Filesystem\File; <ide> use Cake\Http\Cookie\Cookie; <ide> use Cake\Http\Cookie\CookieCollection; <add>use Cake\Http\Cookie\CookieInterface; <ide> use Cake\Log\Log; <ide> use Cake\Network\CorsBuilder; <ide> use Cake\Network\Exception\NotFoundException; <ide> public function cookie($options = null) <ide> return null; <ide> } <ide> <del> return $this->_cookies->get($options)->toArrayResponse(); <add> $cookie = $this->_cookies->get($options); <add> <add> return $this->toArrayResponse($cookie); <ide> } <ide> <ide> $options += [ <ide> public function getCookie($name) <ide> return null; <ide> } <ide> <del> return $this->_cookies->get($name)->toArrayResponse(); <add> $cookie = $this->_cookies->get($name); <add> <add> return $this->toArrayResponse($cookie); <ide> } <ide> <ide> /** <ide> public function getCookies() <ide> { <ide> $out = []; <ide> foreach ($this->_cookies as $cookie) { <del> $out[$cookie->getName()] = $cookie->toArrayResponse(); <add> $out[$cookie->getName()] = $this->toArrayResponse($cookie); <ide> } <ide> <ide> return $out; <ide> } <ide> <add> /** <add> * Convert the cookie into an array of its properties. <add> * <add> * This method is compatible with the historical behavior of Cake\Http\Response, <add> * where `httponly` is `httpOnly` and `expires` is `expire` <add> * <add> * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie object. <add> * @return array <add> */ <add> protected function toArrayResponse(CookieInterface $cookie) <add> { <add> if ($cookie instanceof Cookie) { <add> return $cookie->toArrayResponse(); <add> } elseif ($cookie->getExpiry()) { <add> $expires = $cookie->getExpiry()->format('U'); <add> } else { <add> $expires = ''; <add> } <add> <add> return [ <add> 'name' => $cookie->getName(), <add> 'value' => $cookie->getValue(), <add> 'path' => $cookie->getPath(), <add> 'domain' => $cookie->getDomain(), <add> 'secure' => $cookie->isSecure(), <add> 'httpOnly' => $cookie->isHttpOnly(), <add> 'expire' => $expires <add> ]; <add> } <add> <ide> /** <ide> * Get the CookieCollection from the response <ide> *
1
Ruby
Ruby
fix stream tests
df5a32dfbc94723d847aa8d8034041a2bd8751e2
<ide><path>test/channel/stream_test.rb <ide> def subscribed <ide> <ide> test "streaming start and stop" do <ide> run_in_eventmachine do <del> @connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("test_room_1") } <add> @connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("test_room_1").returns stub_everything(:pubsub) } <ide> channel = ChatChannel.new @connection, "{id: 1}", { id: 1 } <ide> <ide> @connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe_proc) } <ide> def subscribed <ide> test "stream_for" do <ide> run_in_eventmachine do <ide> EM.next_tick do <del> @connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("action_cable:channel:stream_test:chat:Room#1-Campfire") } <add> @connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("action_cable:channel:stream_test:chat:Room#1-Campfire").returns stub_everything(:pubsub) } <ide> end <ide> <ide> channel = ChatChannel.new @connection, ""
1
Ruby
Ruby
fix method names
bf6429c438bcc74e5b1248c4293bcf6bbbce228e
<ide><path>activesupport/lib/active_support/callbacks.rb <ide> def apply(code) <ide> <ide> private <ide> <add> def invert_lambda(l) <add> lambda { |*args, &blk| !l.call(*args, &blk) } <add> end <add> <add> def make_lambda(filter) <add> case filter <add> when Array <add> filter.map {|f| _compile_options(f)} <add> when Symbol <add> lambda { |target, value, &blk| <add> target.send filter, &blk <add> } <add> when String <add> l = eval "lambda { |value| #{filter} }" <add> lambda { |target,value| target.instance_exec(value, &l) } <add> when ::Proc <add> if filter.arity <= 0 <add> return lambda { |target, _| target.instance_exec(&filter) } <add> end <add> <add> if filter.arity == 1 <add> lambda { |target, _| <add> target.instance_exec(target, &filter) <add> } <add> else <add> lambda { |target, _| <add> target.instance_exec target, ::Proc.new, &filter <add> } <add> end <add> else <add> scopes = Array(chain.config[:scope]) <add> method_to_call = scopes.map{ |s| public_send(s) }.join("_") <add> <add> lambda { |target, _, &blk| <add> filter.public_send method_to_call, target, &blk <add> } <add> end <add> end <add> <ide> def compute_identifier(filter) <ide> case filter <ide> when String, ::Proc <ide> def recompile_options! <ide> conditions = [] <ide> <ide> unless options[:if].empty? <del> conditions.concat Array(_compile_options(options[:if])) <add> lambdas = Array(options[:if]).map { |c| make_lambda c } <add> conditions.concat lambdas <ide> end <ide> <ide> unless options[:unless].empty? <del> conditions.concat Array(_compile_options(options[:unless])).map { |f| <del> lambda { |*args,&blk| !f.call(*args, &blk) } <del> } <add> lambdas = Array(options[:unless]).map { |c| make_lambda c } <add> conditions.concat lambdas.map { |l| invert_lambda l } <ide> end <ide> <ide> method_name = "_callback_#{@kind}_#{next_id}" <ide> def _method_name_for_object_filter(kind, filter, append_next_id = true) <ide> # a method is created that calls the before_foo method <ide> # on the object. <ide> def _compile_source(filter) <del> l = _compile_options filter <add> l = make_lambda filter <ide> <ide> method_name = "_callback_#{@kind}_#{next_id}" <ide> @klass.send(:define_method, method_name) do |*args,&block| <ide> def _compile_source(filter) <ide> method_name <ide> end <ide> <del> def _compile_options(filter) <del> case filter <del> when Array <del> filter.map {|f| _compile_options(f)} <del> when Symbol <del> lambda { |target, value, &blk| <del> target.send filter, &blk <del> } <del> when String <del> l = eval "lambda { |value| #{filter} }", __FILE__, __LINE__ <del> lambda { |target,value| target.instance_exec(value, &l) } <del> when ::Proc <del> if filter.arity <= 0 <del> return lambda { |target, _| target.instance_exec(&filter) } <del> end <del> <del> if filter.arity == 1 <del> lambda { |target, _| <del> target.instance_exec(target, &filter) <del> } <del> else <del> lambda { |target, _| <del> target.instance_exec target, ::Proc.new, &filter <del> } <del> end <del> else <del> scopes = Array(chain.config[:scope]) <del> method_to_call = scopes.map{ |s| public_send(s) }.join("_") <del> <del> lambda { |target, _, &blk| <del> filter.public_send method_to_call, target, &blk <del> } <del> end <del> end <del> <ide> def _normalize_legacy_filter(kind, filter) <ide> if !filter.respond_to?(kind) && filter.respond_to?(:filter) <ide> message = "Filter object with #filter method is deprecated. Define method corresponding " \
1
Python
Python
fix formatting and remove unused imports
b13e7f79b4ceb9dffd0fd1b568c63c2dcfdc5b48
<ide><path>spacy/__init__.py <del>import pathlib <del> <ide> from .util import set_lang_class, get_lang_class <del>from .about import __version__ <ide> <ide> from . import en <ide> from . import de <ide> from . import fi <ide> from . import bn <ide> <add> <ide> try: <ide> basestring <ide> except NameError:
1
Python
Python
handle groupresults for non-pickle serializers
5a7ebe2f998cb93b7988eac479a8bde54e0393f8
<ide><path>celery/backends/base.py <ide> from celery.app import current_task <ide> from celery.datastructures import LRUCache <ide> from celery.exceptions import TimeoutError, TaskRevokedError <del>from celery.result import from_serializable <add>from celery.result import from_serializable, GroupResult <ide> from celery.utils import timeutils <ide> from celery.utils.serialization import ( <ide> get_pickled_exception, <ide> def exception_to_python(self, exc): <ide> <ide> def prepare_value(self, result): <ide> """Prepare value for storage.""" <add> if isinstance(result, GroupResult): <add> return result.serializable() <ide> return result <ide> <ide> def forget(self, task_id):
1
Javascript
Javascript
fix broken build due to unstubbed query params
8c4c8cbfb11f554cd568d7f55c82b6da4732d315
<ide><path>packages_es6/ember-routing/tests/system/route_test.js <ide> test("default store utilizes the container to acquire the model factory", functi <ide> }; <ide> <ide> route.container = container; <add> route.set('_qp', null); <ide> <ide> equal(route.model({ post_id: 1}), post); <ide> equal(route.findModel('post', 1), post, '#findModel returns the correct post');
1
PHP
PHP
use newfrombuilder instance of newinstance
3f7ac061c24ba3e81f9492425ebffe003254a99e
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function lists($column, $key = null) <ide> { <ide> $fill = array($column => $value); <ide> <del> $value = $this->model->newInstance($fill)->$column; <add> $value = $this->model->newFromBuilder($fill)->$column; <ide> } <ide> } <ide>
1
Java
Java
add jackons decoder tests related list vs flux
4fd80bbb67d24d1ff26d8fe1583a5dda5e4c178f
<ide><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/JacksonJsonDecoderTests.java <ide> <ide> package org.springframework.core.codec.support; <ide> <add>import java.lang.reflect.Method; <add>import java.util.Arrays; <add>import java.util.List; <add> <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.test.TestSubscriber; <ide> import static org.junit.Assert.assertTrue; <ide> <ide> /** <add> * Unit tests for {@link JacksonJsonDecoder}. <ide> * @author Sebastien Deleuze <add> * @author Rossen Stoyanchev <ide> */ <ide> public class JacksonJsonDecoderTests extends AbstractDataBufferAllocatingTestCase { <ide> <del> private final JacksonJsonDecoder decoder = new JacksonJsonDecoder(); <del> <ide> @Test <ide> public void canDecode() { <del> assertTrue(this.decoder.canDecode(null, MediaType.APPLICATION_JSON)); <del> assertFalse(this.decoder.canDecode(null, MediaType.APPLICATION_XML)); <add> JacksonJsonDecoder decoder = new JacksonJsonDecoder(); <add> <add> assertTrue(decoder.canDecode(null, MediaType.APPLICATION_JSON)); <add> assertFalse(decoder.canDecode(null, MediaType.APPLICATION_XML)); <add> } <add> <add> @Test <add> public void decodePojo() { <add> Flux<DataBuffer> source = Flux.just(stringBuffer("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}")); <add> ResolvableType elementType = ResolvableType.forClass(Pojo.class); <add> Flux<Object> flux = new JacksonJsonDecoder().decode(source, elementType, null); <add> <add> TestSubscriber.subscribe(flux).assertNoError().assertComplete(). <add> assertValues(new Pojo("foofoo", "barbar")); <ide> } <ide> <ide> @Test <del> public void decode() { <del> Flux<DataBuffer> source = <del> Flux.just(stringBuffer("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}")); <del> Flux<Object> output = <del> this.decoder.decode(source, ResolvableType.forClass(Pojo.class), null); <del> TestSubscriber <del> .subscribe(output) <del> .assertValues(new Pojo("foofoo", "barbar")); <add> @Ignore // Issues 112 (no generic type), otherwise works <add> public void decodeToListWithoutObjectDecoder() throws Exception { <add> Flux<DataBuffer> source = Flux.just(stringBuffer( <add> "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]")); <add> <add> Method method = getClass().getDeclaredMethod("handle", List.class); <add> ResolvableType elementType = ResolvableType.forMethodParameter(method, 0); <add> Flux<Object> flux = new JacksonJsonDecoder().decode(source, elementType, null); <add> <add> TestSubscriber.subscribe(flux).assertNoError().assertComplete(). <add> assertValues(Arrays.asList(new Pojo("f1", "b1"), new Pojo("f2", "b2"))); <add> } <add> <add> @Test <add> @Ignore // Issue 109 <add> public void decodeToFluxWithoutObjectDecoder() throws Exception { <add> Flux<DataBuffer> source = Flux.just(stringBuffer( <add> "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]")); <add> <add> ResolvableType elementType = ResolvableType.forClass(Pojo.class); <add> Flux<Object> flux = new JacksonJsonDecoder().decode(source, elementType, null); <add> <add> TestSubscriber.subscribe(flux).assertNoError().assertComplete(). <add> assertValues(new Pojo("f1", "b1"), new Pojo("f2", "b2")); <ide> } <ide> <add> @Test <add> @Ignore // Issue 109 <add> public void decodeToListWithObjectDecoder() throws Exception { <add> Flux<DataBuffer> source = Flux.just(stringBuffer( <add> "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]")); <add> <add> Method method = getClass().getDeclaredMethod("handle", List.class); <add> ResolvableType elementType = ResolvableType.forMethodParameter(method, 0); <add> Flux<Object> flux = new JacksonJsonDecoder(new JsonObjectDecoder()).decode(source, elementType, null); <add> <add> TestSubscriber.subscribe(flux).assertNoError().assertComplete(). <add> assertValues(Arrays.asList(new Pojo("f1", "b1"), new Pojo("f2", "b2"))); <add> } <add> <add> @Test <add> public void decodeToFluxWithObjectDecoder() throws Exception { <add> Flux<DataBuffer> source = Flux.just(stringBuffer( <add> "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]")); <add> <add> ResolvableType elementType = ResolvableType.forClass(Pojo.class); <add> Flux<Object> flux = new JacksonJsonDecoder(new JsonObjectDecoder()).decode(source, elementType, null); <add> <add> TestSubscriber.subscribe(flux).assertNoError().assertComplete(). <add> assertValues(new Pojo("f1", "b1"), new Pojo("f2", "b2")); <add> } <add> <add> @SuppressWarnings("unused") <add> void handle(List<Pojo> list) { <add> } <add> <add> <ide> }
1
PHP
PHP
improve http\request test coverage
4dfd0b7a3a82d21abd7d2cd1d7a2eb7ec2ac6d65
<ide><path>tests/Http/HttpRequestTest.php <ide> public function tearDown() <ide> { <ide> m::close(); <ide> } <add> <add> <add> public function testInstanceMethod() <add> { <add> $request = Request::create('', 'GET'); <add> $this->assertTrue($request === $request->instance()); <add> } <add> <add> <add> public function testRootMethod() <add> { <add> $request = Request::create('http://example.com/foo/bar/script.php?test'); <add> $this->assertEquals('http://example.com', $request->root()); <add> } <ide> <ide> <ide> public function testPathMethod() <ide> public function testPathMethod() <ide> $request = Request::create('/foo/bar', 'GET'); <ide> $this->assertEquals('foo/bar', $request->path()); <ide> } <add> <add> <add> public function testDecodedPathMethod() <add> { <add> $request = Request::create('/foo%20bar'); <add> $this->assertEquals('foo bar', $request->decodedPath()); <add> } <ide> <ide> <ide> public function testSegmentMethod() <ide> public function testIsMethod() <ide> $this->assertTrue($request->is('foo*')); <ide> $this->assertFalse($request->is('bar*')); <ide> $this->assertTrue($request->is('*bar*')); <add> $this->assertTrue($request->is('bar*', 'foo*', 'baz')); <ide> <ide> $request = Request::create('/', 'GET'); <ide> <ide> $this->assertTrue($request->is('/')); <ide> } <add> <add> <add> public function testAjaxMethod() <add> { <add> $request = Request::create('/', 'GET'); <add> $this->assertFalse($request->ajax()); <add> $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'), '{}'); <add> $this->assertTrue($request->ajax()); <add> } <add> <add> <add> public function testSecureMethod() <add> { <add> $request = Request::create('http://example.com', 'GET'); <add> $this->assertFalse($request->secure()); <add> $request = Request::create('https://example.com', 'GET'); <add> $this->assertTrue($request->secure()); <add> } <ide> <ide> <ide> public function testHasMethod() <ide> public function testQueryMethod() <ide> $request = Request::create('/', 'GET', array('name' => 'Taylor')); <ide> $this->assertEquals('Taylor', $request->query('name')); <ide> $this->assertEquals('Bob', $request->query('foo', 'Bob')); <add> $all = $request->query(null); <add> $this->assertEquals('Taylor', $all['name']); <ide> } <ide> <ide> <ide> public function testCookieMethod() <ide> $request = Request::create('/', 'GET', array(), array('name' => 'Taylor')); <ide> $this->assertEquals('Taylor', $request->cookie('name')); <ide> $this->assertEquals('Bob', $request->cookie('foo', 'Bob')); <add> $all = $request->cookie(null); <add> $this->assertEquals('Taylor', $all['name']); <add> } <add> <add> <add> public function testHasCookieMethod() <add> { <add> $request = Request::create('/', 'GET', array(), array('foo' => 'bar')); <add> $this->assertTrue($request->hasCookie('foo')); <add> $this->assertFalse($request->hasCookie('qu')); <ide> } <ide> <ide> <ide> public function testServerMethod() <ide> $request = Request::create('/', 'GET', array(), array(), array(), array('foo' => 'bar')); <ide> $this->assertEquals('bar', $request->server('foo')); <ide> $this->assertEquals('bar', $request->server('foo.doesnt.exist', 'bar')); <add> $all = $request->server(null); <add> $this->assertEquals('bar', $all['foo']); <ide> } <ide> <ide> <ide> public function testHeaderMethod() <ide> { <ide> $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_DO_THIS' => 'foo')); <ide> $this->assertEquals('foo', $request->header('do-this')); <add> $all = $request->header(null); <add> $this->assertEquals('foo', $all['do-this'][0]); <ide> } <ide> <ide> <ide> public function testFormatReturnsAcceptableFormat() <ide> { <ide> $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_ACCEPT' => 'application/json')); <ide> $this->assertEquals('json', $request->format()); <add> $this->assertTrue($request->wantsJson()); <ide> <ide> $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_ACCEPT' => 'application/atom+xml')); <ide> $this->assertEquals('atom', $request->format()); <add> $this->assertFalse($request->wantsJson()); <add> <add> $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_ACCEPT' => 'is/not/known')); <add> $this->assertEquals('html', $request->format()); <add> $this->assertEquals('foo', $request->format('foo')); <add> } <add> <add> <add> public function testSessionMethod() <add> { <add> $this->setExpectedException('RuntimeException'); <add> $request = Request::create('/', 'GET'); <add> $request->session(); <ide> } <ide> <ide> }
1
Go
Go
remove unused "testutils" imports
427ad30c0545c1fc5e9448b6f9a12ef255e03f8d
<ide><path>cmd/docker-proxy/network_proxy_test.go <ide> import ( <ide> <ide> "github.com/ishidawataru/sctp" <ide> "gotest.tools/v3/skip" <del> <del> // this takes care of the incontainer flag <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> var testBuf = []byte("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo") <ide><path>libnetwork/bitseq/sequence_test.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/docker/libnetwork/datastore" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/libkv/store" <ide> "github.com/docker/libkv/store/boltdb" <ide> ) <ide><path>libnetwork/config/config_test.go <ide> import ( <ide> <ide> "github.com/docker/docker/libnetwork/datastore" <ide> "github.com/docker/docker/libnetwork/netlabel" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> func TestInvalidConfig(t *testing.T) { <ide><path>libnetwork/datastore/datastore_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/libnetwork/options" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "gotest.tools/v3/assert" <ide> ) <ide> <ide><path>libnetwork/driverapi/driverapi_test.go <ide> import ( <ide> "net" <ide> "testing" <ide> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/libnetwork/types" <ide> ) <ide> <ide><path>libnetwork/drivers/host/host_test.go <ide> package host <ide> import ( <ide> "testing" <ide> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/libnetwork/types" <ide> ) <ide> <ide><path>libnetwork/drivers/ipvlan/ipvlan_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/libnetwork/driverapi" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/pkg/plugingetter" <ide> ) <ide> <ide><path>libnetwork/drivers/macvlan/macvlan_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/libnetwork/driverapi" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/pkg/plugingetter" <ide> ) <ide> <ide><path>libnetwork/drivers/null/null_test.go <ide> package null <ide> import ( <ide> "testing" <ide> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/libnetwork/types" <ide> ) <ide> <ide><path>libnetwork/drivers/overlay/overlay_test.go <ide> import ( <ide> "github.com/docker/docker/libnetwork/discoverapi" <ide> "github.com/docker/docker/libnetwork/driverapi" <ide> "github.com/docker/docker/libnetwork/netlabel" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/libkv/store/consul" <ide> "github.com/vishvananda/netlink/nl" <ide><path>libnetwork/drivers/overlay/ovmanager/ovmanager_test.go <ide> import ( <ide> "github.com/docker/docker/libnetwork/driverapi" <ide> "github.com/docker/docker/libnetwork/idm" <ide> "github.com/docker/docker/libnetwork/netlabel" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/libnetwork/types" <ide> "gotest.tools/v3/assert" <ide> is "gotest.tools/v3/assert/cmp" <ide><path>libnetwork/drivers/overlay/peerdb_test.go <ide> package overlay <ide> import ( <ide> "net" <ide> "testing" <del> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> func TestPeerMarshal(t *testing.T) { <ide><path>libnetwork/drivers/remote/driver_test.go <ide> import ( <ide> "github.com/docker/docker/libnetwork/datastore" <ide> "github.com/docker/docker/libnetwork/discoverapi" <ide> "github.com/docker/docker/libnetwork/driverapi" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/libnetwork/types" <ide> "github.com/docker/docker/pkg/plugins" <ide> ) <ide><path>libnetwork/drvregistry/drvregistry_test.go <ide> import ( <ide> remoteIpam "github.com/docker/docker/libnetwork/ipams/remote" <ide> "gotest.tools/v3/assert" <ide> is "gotest.tools/v3/assert/cmp" <del> <del> // this takes care of the incontainer flag <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> const mockDriverName = "mock-driver" <ide><path>libnetwork/etchosts/etchosts_test.go <ide> import ( <ide> "os" <ide> "testing" <ide> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "golang.org/x/sync/errgroup" <ide> ) <ide> <ide><path>libnetwork/hostdiscovery/hostdiscovery_test.go <ide> import ( <ide> "testing" <ide> <ide> mapset "github.com/deckarep/golang-set" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> <ide> "github.com/docker/docker/pkg/discovery" <ide> ) <ide><path>libnetwork/idm/idm_test.go <ide> package idm <ide> <ide> import ( <ide> "testing" <del> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> func TestNew(t *testing.T) { <ide><path>libnetwork/internal/caller/caller_test.go <ide> package caller <ide> <ide> import ( <ide> "testing" <del> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> func fun1() string { <ide><path>libnetwork/internal/setmatrix/setmatrix_test.go <ide> import ( <ide> "strings" <ide> "testing" <ide> "time" <del> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> func TestSetSerialInsertDelete(t *testing.T) { <ide><path>libnetwork/ipam/allocator_test.go <ide> import ( <ide> "github.com/docker/docker/libnetwork/bitseq" <ide> "github.com/docker/docker/libnetwork/datastore" <ide> "github.com/docker/docker/libnetwork/ipamapi" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/libnetwork/types" <ide> "github.com/docker/libkv/store" <ide> "github.com/docker/libkv/store/boltdb" <ide><path>libnetwork/ipams/null/null_test.go <ide> package null <ide> import ( <ide> "testing" <ide> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/libnetwork/types" <ide> ) <ide> <ide><path>libnetwork/ipams/remote/remote_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/libnetwork/ipamapi" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/pkg/plugins" <ide> ) <ide> <ide><path>libnetwork/ipams/windowsipam/windowsipam_test.go <ide> import ( <ide> <ide> "github.com/docker/docker/libnetwork/ipamapi" <ide> "github.com/docker/docker/libnetwork/netlabel" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/libnetwork/types" <ide> ) <ide> <ide><path>libnetwork/ipamutils/utils_test.go <ide> import ( <ide> "net" <ide> "testing" <ide> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "gotest.tools/v3/assert" <ide> is "gotest.tools/v3/assert/cmp" <ide> ) <ide><path>libnetwork/iptables/iptables_test.go <ide> import ( <ide> "strings" <ide> "testing" <ide> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "golang.org/x/sync/errgroup" <ide> ) <ide> <ide><path>libnetwork/netlabel/labels_test.go <ide> package netlabel <ide> <ide> import ( <ide> "testing" <del> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> var input = []struct { <ide><path>libnetwork/networkdb/networkdb_test.go <ide> import ( <ide> "gotest.tools/v3/assert" <ide> is "gotest.tools/v3/assert/cmp" <ide> "gotest.tools/v3/poll" <del> <del> // this takes care of the incontainer flag <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> var dbPort int32 = 10000 <ide><path>libnetwork/options/options_test.go <ide> import ( <ide> "reflect" <ide> "strings" <ide> "testing" <del> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> func TestGenerate(t *testing.T) { <ide><path>libnetwork/osl/kernel/knobs_linux_test.go <ide> import ( <ide> "github.com/sirupsen/logrus" <ide> "gotest.tools/v3/assert" <ide> is "gotest.tools/v3/assert/cmp" <del> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> func TestReadWriteKnobs(t *testing.T) { <ide><path>libnetwork/portallocator/portallocator_test.go <ide> import ( <ide> "fmt" <ide> "net" <ide> "testing" <del> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> func resetPortAllocator() { <ide><path>libnetwork/portmapper/mapper_linux_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/libnetwork/iptables" <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> ) <ide> <ide> func init() { <ide><path>libnetwork/resolvconf/resolvconf_linux_test.go <ide> import ( <ide> "os" <ide> "testing" <ide> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "github.com/docker/docker/libnetwork/types" <ide> "github.com/docker/docker/pkg/ioutils" <ide> ) <ide><path>libnetwork/types/types_test.go <ide> import ( <ide> "net" <ide> "testing" <ide> <del> _ "github.com/docker/docker/libnetwork/testutils" <ide> "gotest.tools/v3/assert" <ide> is "gotest.tools/v3/assert/cmp" <ide> )
33
PHP
PHP
expand documentation on placeholder binding
1d388ea82387ba2500ae8892544d2fd32f82d2b6
<ide><path>src/Database/Query.php <ide> public function traverseExpressions(callable $callback) <ide> * <ide> * If type is expressed as "atype[]" (note braces) then it will cause the <ide> * placeholder to be re-written dynamically so if the value is an array, it <del> * will create as many placeholders as values are in it. For example "string[]" <del> * will create several placeholders of type string. <add> * will create as many placeholders as values are in it. For example: <add> * <add> * ``` <add> * $query->bind(':id', [1, 2, 3], 'int[]'); <add> * ``` <add> * <add> * Will create 3 int placeholders. When using named placeholders, this method <add> * requires that the placeholders include `:` e.g. `:value`. <ide> * <ide> * @param string|int $param placeholder to be replaced with quoted version <ide> * of $value
1
Javascript
Javascript
add meta matchers for testing tests
3bbf6ce1a53358d2a3030050c88901b06e507460
<ide><path>src/modern/class/__tests__/ReactClassEquivalence-test.js <add>/** <add> * Copyright 2015, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @emails react-core <add> */ <add> <add>var MetaMatchers = require('MetaMatchers'); <add> <add>describe('ReactClassEquivalence', function() { <add> <add> beforeEach(function() { <add> this.addMatchers(MetaMatchers); <add> }); <add> <add> var es6 = () => require('./ReactES6Class-test.js'); <add> var coffee = () => require('./ReactCoffeeScriptClass-test.coffee'); <add> <add> it('tests the same thing for es6 classes and coffee script', function() { <add> expect(coffee).toEqualSpecsIn(es6); <add> }); <add> <add>}); <ide><path>src/test/MetaMatchers.js <add>/** <add> * Copyright 2015, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @providesModule MetaMatchers <add> */ <add> <add>'use strict'; <add> <add>/** <add> * This modules adds a jasmine matcher toEqualSpecsIn that can be used to <add> * compare the specs in two different "describe" functions and their result. <add> * It can be used to test a test. <add> */ <add> <add>function getRunnerWithResults(describeFunction) { <add> if (describeFunction._cachedRunner) { <add> // Cached result of execution. This is a convenience way to test against <add> // the same authorative function multiple times. <add> return describeFunction._cachedRunner; <add> } <add> // Patch the current global environment. <add> var env = new jasmine.Env(); <add> // Execute the tests synchronously. <add> env.updateInterval = 0; <add> var outerGetEnv = jasmine.getEnv; <add> jasmine.getEnv = function() { return env; }; <add> // TODO: Bring over matchers from the existing environment. <add> var runner = env.currentRunner(); <add> try { <add> env.describe('', describeFunction); <add> env.execute(); <add> } finally { <add> // Restore the environment. <add> jasmine.getEnv = outerGetEnv; <add> } <add> describeFunction._cachedRunner = runner; <add> return runner; <add>} <add> <add>function compareSpec(actual, expected) { <add> if (actual.results().totalCount !== expected.results().totalCount) { <add> return ( <add> 'Expected ' + expected.results().totalCount + ' expects, ' + <add> 'but got ' + actual.results().totalCount + ':' + <add> actual.getFullName() <add> ); <add> } <add> return null; <add>} <add> <add>function includesDescription(specs, description, startIndex) { <add> for (var i = startIndex; i < specs.length; i++) { <add> if (specs[i].description === description) { <add> return true; <add> } <add> } <add> return false; <add>} <add> <add>function compareSpecs(actualSpecs, expectedSpecs) { <add> for (var i = 0; i < actualSpecs.length && i < expectedSpecs.length; i++) { <add> var actual = actualSpecs[i]; <add> var expected = expectedSpecs[i]; <add> if (actual.description === expected.description) { <add> var errorMessage = compareSpec(actual, expected); <add> if (errorMessage) { <add> return errorMessage; <add> } <add> continue; <add> } else if (includesDescription(actualSpecs, expected.description, i)) { <add> return 'Did not expect the spec:' + actualSpecs[i].getFullName(); <add> } else { <add> return 'Expected an equivalent to:' + expectedSpecs[i].getFullName(); <add> } <add> } <add> if (i < actualSpecs.length) { <add> return 'Did not expect the spec:' + actualSpecs[i].getFullName(); <add> } <add> if (i < expectedSpecs.length) { <add> return 'Expected an equivalent to:' + expectedSpecs[i].getFullName(); <add> } <add> return null; <add>} <add> <add>function compareDescription(a, b) { <add> if (a.description === b.description) { <add> return 0; <add> } <add> return a.description < b.description ? -1 : 1; <add>} <add> <add>function compareRunners(actual, expected) { <add> return compareSpecs( <add> actual.specs().sort(compareDescription), <add> expected.specs().sort(compareDescription) <add> ); <add>} <add> <add>var MetaMatchers = { <add> toEqualSpecsIn: function(expectedDescribeFunction) { <add> var actualDescribeFunction = this.actual; <add> if (typeof actualDescribeFunction !== 'function') { <add> throw Error('toEqualSpecsIn() should be used on a describe function'); <add> } <add> if (typeof expectedDescribeFunction !== 'function') { <add> throw Error('toEqualSpecsIn() should be passed a describe function'); <add> } <add> var actual = getRunnerWithResults(actualDescribeFunction); <add> var expected = getRunnerWithResults(expectedDescribeFunction); <add> var errorMessage = compareRunners(actual, expected); <add> this.message = function() { <add> return [ <add> errorMessage, <add> 'The specs are equal. Expected them to be different.' <add> ]; <add> }; <add> return !errorMessage; <add> } <add>}; <add> <add>module.exports = MetaMatchers; <ide><path>src/test/__tests__/MetaMatchers-test.js <add>/** <add> * Copyright 2015, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @emails react-core <add> */ <add> <add>var MetaMatchers = require('MetaMatchers'); <add> <add>describe('meta-matchers', function() { <add> <add> beforeEach(function() { <add> this.addMatchers(MetaMatchers); <add> }); <add> <add> function a() { <add> it('should add 1 and 2', function() { <add> expect(1 + 2).toBe(3); <add> }); <add> } <add> <add> function b() { <add> it('should add 1 and 2', function() { <add> expect(1 + 2).toBe(3); <add> }); <add> } <add> <add> function c() { <add> it('should add 1 and 2', function() { <add> expect(1 + 2).toBe(3); <add> }); <add> it('should mutiply 1 and 2', function() { <add> expect(1 * 2).toBe(2); <add> }); <add> } <add> <add> function d() { <add> it('should add 1 and 2', function() { <add> expect(1 + 2).toBe(3); <add> }); <add> it('should mutiply 1 and 2', function() { <add> expect(1 * 2).toBe(2); <add> expect(2 * 1).toBe(2); <add> }); <add> } <add> <add> it('tests equality of specs', function() { <add> expect(a).toEqualSpecsIn(b); <add> }); <add> <add> it('tests inequality of specs and expects', function() { <add> expect(b).not.toEqualSpecsIn(c); <add> expect(c).not.toEqualSpecsIn(d); <add> }); <add> <add>});
3
Javascript
Javascript
use common.mustcall in http test
f81bb7b527bb58ee68ddd26c9eee56a133547c01
<ide><path>test/parallel/test-http-pipeline-regr-2639.js <ide> 'use strict'; <del>require('../common'); <del>const assert = require('assert'); <add>const common = require('../common'); <ide> const http = require('http'); <ide> const net = require('net'); <ide> <ide> const COUNT = 10; <ide> <del>let received = 0; <del> <del>const server = http.createServer(function(req, res) { <add>const server = http.createServer(common.mustCall((req, res) => { <ide> // Close the server, we have only one TCP connection anyway <del> if (received++ === 0) <del> server.close(); <del> <add> server.close(); <ide> res.writeHead(200); <ide> res.write('data'); <ide> <ide> setTimeout(function() { <ide> res.end(); <ide> }, (Math.random() * 100) | 0); <del>}).listen(0, function() { <add>}, COUNT)).listen(0, function() { <ide> const s = net.connect(this.address().port); <ide> <ide> const big = 'GET / HTTP/1.0\r\n\r\n'.repeat(COUNT); <ide> <ide> s.write(big); <ide> s.resume(); <ide> }); <del> <del>process.on('exit', function() { <del> assert.strictEqual(received, COUNT); <del>});
1
Javascript
Javascript
add better labels to tests, reorder
6db588073bbe1997480f6740f081b8b81cafbcd0
<ide><path>packages/ember-runtime/tests/core/compare_test.js <ide> test('comparables should return values in the range of -1, 0, 1', function() { <ide> var zero = Comp.create({ val: 0 }); <ide> var one = Comp.create({ val: 1 }); <ide> <del> equal(compare('a', negOne), 1, 'Second item comparable - Should return valid range -1, 0, 1'); <del> equal(compare('b', zero), 0, 'Second item comparable - Should return valid range -1, 0, 1'); <del> equal(compare('c', one), -1, 'Second item comparable - Should return valid range -1, 0, 1'); <add> equal(compare(negOne, 'a'), -1, 'First item comparable - returns -1 (not negated)'); <add> equal(compare(zero, 'b'), 0, 'First item comparable - returns 0 (not negated)'); <add> equal(compare(one, 'c'), 1, 'First item comparable - returns 1 (not negated)'); <ide> <del> equal(compare(negOne, 'a'), -1, 'First itam comparable - Should return valid range -1, 0, 1'); <del> equal(compare(zero, 'b'), 0, 'First itam comparable - Should return valid range -1, 0, 1'); <del> equal(compare(one, 'c'), 1, 'First itam comparable - Should return valid range -1, 0, 1'); <add> equal(compare('a', negOne), 1, 'Second item comparable - returns -1 (negated)'); <add> equal(compare('b', zero), 0, 'Second item comparable - returns 0 (negated)'); <add> equal(compare('c', one), -1, 'Second item comparable - returns 1 (negated)'); <ide> });
1
Javascript
Javascript
change wording for donate buttons
2e90ba4754152ee3eb57477f37914c02bf045137
<ide><path>client/src/components/Donation/DonateForm.js <ide> class DonateForm extends Component { <ide> id='confirm-donation-btn' <ide> onClick={this.handleStripeCheckoutRedirect} <ide> > <del> <span>Pay with Apple Pay</span> <add> <span>Donate with Apple Pay</span> <ide> <ide> <ApplePay className='apple-pay-logo' /> <ide> </Button> <ide> class DonateForm extends Component { <ide> id='confirm-donation-btn' <ide> onClick={this.handleStripeCheckoutRedirect} <ide> > <del> <span>Pay with Google Pay</span> <add> <span>Donate with Google Pay</span> <ide> <GooglePay className='google-pay-logo' /> <ide> </Button> <ide> <Spacer /> <ide> class DonateForm extends Component { <ide> id='confirm-donation-btn' <ide> onClick={this.handleStripeCheckoutRedirect} <ide> > <del> <span>Pay with Card</span> <add> <span>Donate with Card</span> <ide> <ide> <img <ide> alt='accepted cards'
1
Javascript
Javascript
improve error handling
b38c81cb449a822ab45e6caa210d070b91a59836
<ide><path>lib/_http_client.js <ide> function ClientRequest(options, cb) { <ide> // Explicitly pass through this statement as agent will not be used <ide> // when createConnection is provided. <ide> } else if (typeof agent.addRequest !== 'function') { <del> throw new ERR_INVALID_ARG_TYPE('Agent option', <del> ['Agent-like Object', 'undefined', 'false']); <add> throw new ERR_INVALID_ARG_TYPE('options.agent', <add> ['Agent-like Object', 'undefined', 'false'], <add> agent); <ide> } <ide> this.agent = agent; <ide> <ide><path>lib/_http_outgoing.js <ide> OutgoingMessage.prototype.end = function end(chunk, encoding, callback) { <ide> var uncork; <ide> if (chunk) { <ide> if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) { <del> throw new ERR_INVALID_ARG_TYPE('first argument', ['string', 'Buffer']); <add> throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); <ide> } <ide> if (!this._header) { <ide> if (typeof chunk === 'string') <ide><path>lib/_tls_wrap.js <ide> function Server(options, listener) { <ide> this[kSNICallback] = options.SNICallback; <ide> <ide> if (typeof this[kHandshakeTimeout] !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('timeout', 'number'); <add> throw new ERR_INVALID_ARG_TYPE( <add> 'options.handshakeTimeout', 'number', options.handshakeTimeout); <ide> } <ide> <ide> if (this.sessionTimeout) { <ide><path>lib/buffer.js <ide> Buffer.concat = function concat(list, length) { <ide> for (i = 0; i < list.length; i++) { <ide> var buf = list[i]; <ide> if (!isUint8Array(buf)) { <del> throw new ERR_INVALID_ARG_TYPE('list', ['Array', 'Buffer', 'Uint8Array']); <add> // TODO(BridgeAR): This should not be of type ERR_INVALID_ARG_TYPE. <add> // Instead, find the proper error code for this. <add> throw new ERR_INVALID_ARG_TYPE( <add> `list[${i}]`, ['Array', 'Buffer', 'Uint8Array'], list[i]); <ide> } <ide> _copy(buf, buffer, pos); <ide> pos += buf.length; <ide><path>lib/internal/http2/compat.js <ide> const { <ide> ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED, <ide> ERR_HTTP2_STATUS_INVALID, <ide> ERR_INVALID_ARG_TYPE, <add> ERR_INVALID_ARG_VALUE, <ide> ERR_INVALID_CALLBACK, <ide> ERR_INVALID_HTTP_TOKEN <ide> } = require('internal/errors').codes; <ide> class Http2ServerRequest extends Readable { <ide> } <ide> <ide> set method(method) { <del> if (typeof method !== 'string' || method.trim() === '') <del> throw new ERR_INVALID_ARG_TYPE('method', 'string'); <add> if (typeof method !== 'string') <add> throw new ERR_INVALID_ARG_TYPE('method', 'string', method); <add> if (method.trim() === '') <add> throw new ERR_INVALID_ARG_VALUE('method', method); <ide> <ide> this[kHeaders][HTTP2_HEADER_METHOD] = method; <ide> } <ide><path>test/parallel/test-buffer-concat.js <ide> assert.strictEqual(flatLongLen.toString(), check); <ide> }); <ide> }); <ide> <add>[[42], ['hello', Buffer.from('world')]].forEach((value) => { <add> assert.throws(() => { <add> Buffer.concat(value); <add> }, { <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: 'The "list[0]" argument must be one of type Array, Buffer, ' + <add> `or Uint8Array. Received type ${typeof value[0]}` <add> }); <add>}); <add> <add>assert.throws(() => { <add> Buffer.concat([Buffer.from('hello'), 3]); <add>}, { <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: 'The "list[1]" argument must be one of type Array, Buffer, ' + <add> 'or Uint8Array. Received type number' <add>}); <add> <ide> // eslint-disable-next-line node-core/crypto-check <ide> const random10 = common.hasCrypto ? <ide> require('crypto').randomBytes(10) : <ide><path>test/parallel/test-http-client-reject-unexpected-agent.js <ide> server.listen(0, baseOptions.host, common.mustCall(function() { <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <del> message: 'The "Agent option" argument must be one of type ' + <del> 'Agent-like Object, undefined, or false' <add> message: 'The "options.agent" property must be one of type Agent-like' + <add> ` Object, undefined, or false. Received type ${typeof agent}` <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-http2-compat-serverrequest-headers.js <ide> server.listen(0, common.mustCall(function() { <ide> // change the request method <ide> request.method = 'POST'; <ide> assert.strictEqual(request.method, 'POST'); <del> common.expectsError( <add> assert.throws( <ide> () => request.method = ' ', <ide> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "method" argument must be of type string' <add> code: 'ERR_INVALID_ARG_VALUE', <add> name: 'TypeError [ERR_INVALID_ARG_VALUE]', <add> message: "The argument 'method' is invalid. Received ' '" <ide> } <ide> ); <ide> assert.throws( <ide> () => request.method = true, <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <del> message: 'The "method" argument must be of type string' <add> message: 'The "method" argument must be of type string. ' + <add> 'Received type boolean' <ide> } <ide> ); <ide> <ide><path>test/parallel/test-tls-basic-validations.js <ide> common.expectsError(() => tls.createServer({ handshakeTimeout: 'abcd' }), <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <del> message: 'The "timeout" argument must ' + <del> 'be of type number' <add> message: 'The "options.handshakeTimeout" property must ' + <add> 'be of type number. Received type string' <ide> } <ide> ); <ide>
9
Javascript
Javascript
use indices instead of indicies
f65a3ef8f5081d24ea826e82ab2b441defc78fc2
<ide><path>test/configCases/chunk-index/order-multiple-entries/webpack.config.js <ide> module.exports = { <ide> asyncIndex: "0: ./async.js", <ide> asyncIndex2: "0: ./async.js" <ide> }); <del> const indicies = Array.from(compilation.modules) <add> const indices = Array.from(compilation.modules) <ide> .map(m => [moduleGraph.getPreOrderIndex(m), m]) <ide> .filter(p => typeof p[0] === "number") <ide> .sort((a, b) => a[0] - b[0]) <ide> module.exports = { <ide> `${i}: ${m.readableIdentifier(compilation.requestShortener)}` <ide> ) <ide> .join(", "); <del> expect(indicies).toEqual( <add> expect(indices).toEqual( <ide> "0: ./entry1.js, 1: ./a.js, 2: ./shared.js, 3: ./b.js, 4: ./c.js, 5: ./entry2.js, 6: ./async.js" <ide> ); <ide> expect(indicies2).toEqual(
1
Ruby
Ruby
split missing formula help into its own method
9438dc94e3724bcf2456c1d550e3386ae0bc9d94
<ide><path>Library/Homebrew/cmd/search.rb <ide> def search_names(query, string_or_regex, args) <ide> <ide> count = all_formulae.count + all_casks.count <ide> <del> if $stdout.tty? && (reason = MissingFormula.reason(query, silent: true)) && local_casks.exclude?(query) <del> if count.positive? <del> puts <del> puts "If you meant #{query.inspect} specifically:" <del> end <del> puts reason <del> end <add> print_missing_formula_help(query, count.positive?) if local_casks.exclude?(query) <ide> <ide> odie "No formulae or casks found for #{query.inspect}." if count.zero? <ide> end <add> <add> def print_missing_formula_help(query, found_matches) <add> return unless $stdout.tty? <add> <add> reason = MissingFormula.reason(query, silent: true) <add> return if reason.nil? <add> <add> if found_matches <add> puts <add> puts "If you meant #{query.inspect} specifically:" <add> end <add> puts reason <add> end <ide> end
1
Javascript
Javascript
replace fs.accesssync with fs.existssync
bf26d92c267323feef93b084018e7ab1e1237c01
<ide><path>test/parallel/test-npm-install.js <ide> function handleExit(error, stdout, stderr) { <ide> <ide> assert.strictEqual(code, 0, `npm install got error code ${code}`); <ide> assert.strictEqual(signalCode, null, `unexpected signal: ${signalCode}`); <del> assert.doesNotThrow(function() { <del> fs.accessSync(`${installDir}/node_modules/package-name`); <del> }); <add> assert(fs.existsSync(`${installDir}/node_modules/package-name`)); <ide> }
1
Ruby
Ruby
check minimumsystemversion for compatibility
823dc28c2164c6db8842ebdf0fce51443c83baec
<ide><path>Library/Homebrew/livecheck/strategy/sparkle.rb <ide> def self.item_from_content(content) <ide> <ide> next if os && os != "osx" <ide> <add> if OS.mac? && (minimum_system_version = (item > "minimumSystemVersion").first&.text&.strip) <add> macos_minimum_system_version = begin <add> MacOS::Version.new(minimum_system_version).strip_patch <add> rescue MacOSVersionError <add> nil <add> end <add> <add> next if MacOS.version < macos_minimum_system_version <add> end <add> <ide> data = { <ide> title: title, <ide> pub_date: pub_date || Time.new(0),
1
Ruby
Ruby
handle invalid names in download strategies
57560c03e64cb11a33287b3194b0c35cbea6e159
<ide><path>Library/Homebrew/download_strategy.rb <ide> require 'open-uri' <ide> require 'utils/json' <add>require 'erb' <ide> <ide> class AbstractDownloadStrategy <ide> attr_reader :name, :resource <ide> def quiet_safe_system *args <ide> safe_system(*expand_safe_system_args(args)) <ide> end <ide> <add> def checkout_name(tag) <add> if name.empty? || name == '__UNKNOWN__' <add> "#{ERB::Util.url_encode(@url)}--#{tag}" <add> else <add> "#{name}--#{tag}" <add> end <add> end <add> <ide> # All download strategies are expected to implement these methods <ide> def fetch; end <ide> def stage; end <ide> def initialize name, resource <ide> super <ide> @@svn ||= 'svn' <ide> <del> if name.to_s.empty? || name == '__UNKNOWN__' <del> raise NotImplementedError, "strategy requires a name parameter" <add> if ARGV.build_head? <add> @co = Pathname.new("#{HOMEBREW_CACHE}/#{checkout_name("svn-HEAD")}") <ide> else <del> @co = Pathname.new("#{HOMEBREW_CACHE}/#{name}--svn") <add> @co = Pathname.new("#{HOMEBREW_CACHE}/#{checkout_name("svn")}") <ide> end <del> <del> @co = Pathname.new(@co.to_s + '-HEAD') if ARGV.build_head? <ide> end <ide> <ide> def cached_location <ide> class GitDownloadStrategy < AbstractDownloadStrategy <ide> def initialize name, resource <ide> super <ide> @@git ||= 'git' <del> <del> if name.to_s.empty? || name == '__UNKNOWN__' <del> raise NotImplementedError, "strategy requires a name parameter" <del> else <del> @clone = Pathname.new("#{HOMEBREW_CACHE}/#{name}--git") <del> end <add> @clone = Pathname.new("#{HOMEBREW_CACHE}/#{checkout_name("git")}") <ide> end <ide> <ide> def cached_location <ide> def checkout_submodules(dst) <ide> class CVSDownloadStrategy < AbstractDownloadStrategy <ide> def initialize name, resource <ide> super <del> <del> if name.to_s.empty? || name == '__UNKNOWN__' <del> raise NotImplementedError, "strategy requires a name parameter" <del> else <del> @unique_token = "#{name}--cvs" <del> @co = Pathname.new("#{HOMEBREW_CACHE}/#{@unique_token}") <del> end <add> @co = Pathname.new("#{HOMEBREW_CACHE}/#{checkout_name("cvs")}") <ide> end <ide> <ide> def cached_location; @co; end <ide> def fetch <ide> unless @co.exist? <ide> Dir.chdir HOMEBREW_CACHE do <ide> safe_system '/usr/bin/cvs', '-d', url, 'login' <del> safe_system '/usr/bin/cvs', '-d', url, 'checkout', '-d', @unique_token, mod <add> safe_system '/usr/bin/cvs', '-d', url, 'checkout', '-d', checkout_name("cvs"), mod <ide> end <ide> else <ide> puts "Updating #{@co}" <ide> def split_url(in_url) <ide> class MercurialDownloadStrategy < AbstractDownloadStrategy <ide> def initialize name, resource <ide> super <del> <del> if name.to_s.empty? || name == '__UNKNOWN__' <del> raise NotImplementedError, "strategy requires a name parameter" <del> else <del> @clone = Pathname.new("#{HOMEBREW_CACHE}/#{name}--hg") <del> end <add> @clone = Pathname.new("#{HOMEBREW_CACHE}/#{checkout_name("hg")}") <ide> end <ide> <ide> def cached_location; @clone; end <ide> def stage <ide> class BazaarDownloadStrategy < AbstractDownloadStrategy <ide> def initialize name, resource <ide> super <del> <del> if name.to_s.empty? || name == '__UNKNOWN__' <del> raise NotImplementedError, "strategy requires a name parameter" <del> else <del> @clone = Pathname.new("#{HOMEBREW_CACHE}/#{name}--bzr") <del> end <add> @clone = Pathname.new("#{HOMEBREW_CACHE}/#{checkout_name("bzr")}") <ide> end <ide> <ide> def cached_location; @clone; end <ide> def stage <ide> class FossilDownloadStrategy < AbstractDownloadStrategy <ide> def initialize name, resource <ide> super <del> if name.to_s.empty? || name == '__UNKNOWN__' <del> raise NotImplementedError, "strategy requires a name parameter" <del> else <del> @clone = Pathname.new("#{HOMEBREW_CACHE}/#{name}--fossil") <del> end <add> @clone = Pathname.new("#{HOMEBREW_CACHE}/#{checkout_name("fossil")}") <ide> end <ide> <ide> def cached_location; @clone; end <ide><path>Library/Homebrew/test/test_download_strategies.rb <ide> require 'download_strategy' <ide> require 'bottles' # XXX: hoist these regexps into constants in Pathname? <ide> <del>class SoftwareSpecDouble <add>class ResourceDouble <ide> attr_reader :url, :specs <ide> <ide> def initialize(url="http://foo.com/bar.tar.gz", specs={}) <ide> def initialize(url="http://foo.com/bar.tar.gz", specs={}) <ide> class AbstractDownloadStrategyTests < Test::Unit::TestCase <ide> def setup <ide> @name = "foo" <del> @package = SoftwareSpecDouble.new <del> @strategy = AbstractDownloadStrategy.new(@name, @package) <add> @resource = ResourceDouble.new <add> @strategy = AbstractDownloadStrategy.new(@name, @resource) <ide> @args = %w{foo bar baz} <ide> end <ide> <ide> def test_expand_safe_system_args_does_not_mutate_argument <ide> end <ide> end <ide> <add>class DownloadStrategyCheckoutNameTests < Test::Unit::TestCase <add> def setup <add> @resource = ResourceDouble.new("http://foo.com/bar") <add> @strategy = AbstractDownloadStrategy <add> end <add> <add> def escaped(tag) <add> "#{ERB::Util.url_encode(@resource.url)}--#{tag}" <add> end <add> <add> def test_explicit_name <add> downloader = @strategy.new("baz", @resource) <add> assert_equal "baz--foo", downloader.checkout_name("foo") <add> end <add> <add> def test_empty_name <add> downloader = @strategy.new("", @resource) <add> assert_equal escaped("foo"), downloader.checkout_name("foo") <add> end <add> <add> def test_unknown_name <add> downloader = @strategy.new("__UNKNOWN__", @resource) <add> assert_equal escaped("foo"), downloader.checkout_name("foo") <add> end <add>end <add> <ide> class DownloadStrategyDetectorTests < Test::Unit::TestCase <ide> def setup <ide> @d = DownloadStrategyDetector.new
2
Javascript
Javascript
simplify enabletrace logic
b233d028b3b48bc16d6f9ccbe4e00941e65920e3
<ide><path>lib/_tls_wrap.js <ide> function Server(options, listener) { <ide> } <ide> <ide> const enableTrace = options.enableTrace; <del> if (enableTrace === true) <del> this[kEnableTrace] = true; <del> else if (enableTrace === false || enableTrace == null) <del> ; // Tracing explicitly disabled, or defaulting to disabled. <del> else <add> if (typeof enableTrace === 'boolean') { <add> this[kEnableTrace] = enableTrace; <add> } else if (enableTrace != null) { <ide> throw new ERR_INVALID_ARG_TYPE( <ide> 'options.enableTrace', 'boolean', enableTrace); <add> } <ide> } <ide> <ide> Object.setPrototypeOf(Server.prototype, net.Server.prototype);
1
Mixed
Python
fix callbacks doc
1f224de9b1c23e18995b6e651adde6ca06033cac
<ide><path>docs/sources/callbacks.md <ide> class LossHistory(keras.callbacks.Callback): <ide> <ide> ```python <ide> class LossHistory(keras.callbacks.Callback): <del> def on_train_begin(self): <add> def on_train_begin(self, logs={}): <ide> self.losses = [] <ide> <ide> def on_batch_end(self, batch, logs={}): <ide><path>keras/callbacks.py <ide> def on_epoch_end(self, epoch, logs={}): <ide> if self.params['show_accuracy']: <ide> self.validation_accuracy.append(val_acc) <ide> <add> <ide> class ModelCheckpoint(Callback): <ide> def __init__(self, filepath, verbose=0, save_best_only=False): <ide> super(Callback, self).__init__()
2
Go
Go
eliminate redundant parameters
58028a2919f1ee794a058fb3451a5145a6382b4d
<ide><path>container/container.go <ide> func (container *Container) CheckpointDir() string { <ide> } <ide> <ide> // StartLogger starts a new logger driver for the container. <del>func (container *Container) StartLogger(cfg containertypes.LogConfig) (logger.Logger, error) { <add>func (container *Container) StartLogger() (logger.Logger, error) { <add> cfg := container.HostConfig.LogConfig <ide> c, err := logger.GetLogDriver(cfg.Type) <ide> if err != nil { <del> return nil, fmt.Errorf("Failed to get logging factory: %v", err) <add> return nil, fmt.Errorf("failed to get logging factory: %v", err) <ide> } <ide> ctx := logger.Context{ <ide> Config: cfg.Config, <ide> func (container *Container) startLogging() error { <ide> return nil // do not start logging routines <ide> } <ide> <del> l, err := container.StartLogger(container.HostConfig.LogConfig) <add> l, err := container.StartLogger() <ide> if err != nil { <del> return fmt.Errorf("Failed to initialize logging driver: %v", err) <add> return fmt.Errorf("failed to initialize logging driver: %v", err) <ide> } <ide> <ide> copier := logger.NewCopier(map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l) <ide><path>daemon/logs.go <ide> func (daemon *Daemon) getLogger(container *container.Container) (logger.Logger, <ide> if container.LogDriver != nil && container.IsRunning() { <ide> return container.LogDriver, nil <ide> } <del> return container.StartLogger(container.HostConfig.LogConfig) <add> return container.StartLogger() <ide> } <ide> <ide> // mergeLogConfig merges the daemon log config to the container's log config if the container's log driver is not specified. <ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunStoppedLoggingDriverNoLeak(c *check.C) { <ide> <ide> out, _, err := dockerCmdWithError("run", "--name=fail", "--log-driver=splunk", "busybox", "true") <ide> c.Assert(err, checker.NotNil) <del> c.Assert(out, checker.Contains, "Failed to initialize logging driver", check.Commentf("error should be about logging driver, got output %s", out)) <add> c.Assert(out, checker.Contains, "failed to initialize logging driver", check.Commentf("error should be about logging driver, got output %s", out)) <ide> <ide> // NGoroutines is not updated right away, so we need to wait before failing <ide> c.Assert(waitForGoroutines(nroutines), checker.IsNil)
3
Javascript
Javascript
improve coverage for util.inspect() with classes
75afb6c7a6a7143d8e9f6f8e914f78a4814b2827
<ide><path>test/parallel/test-util-inspect.js <ide> assert.strictEqual(util.inspect('"\'${a}'), "'\"\\'${a}'"); <ide> rest[rest.length - 1] = rest[rest.length - 1].slice(0, -1); <ide> rest.length = 1; <ide> } <add> Object.setPrototypeOf(clazz, Map.prototype); <add> assert.strictEqual( <add> util.inspect(clazz), <add> ['[class', name, '[Map]', ...rest].join(' ') + ']' <add> ); <ide> Object.setPrototypeOf(clazz, null); <ide> assert.strictEqual( <ide> util.inspect(clazz),
1
Text
Text
add private beta docs
7ace46d81fba0b0f5523179bedb30e6d2a93498c
<ide><path>docs/private-beta/README.md <add>## Proposed Timeline <add> <add>1. **October 30st** - Internal launch - persuade as many githubers to switch as <add>possible. <add> <add>1. Triage bugs and identify what needs to be fixed before private alpha. Maybe <add>talk to @chrissiebrodigan about doing a UX study. <add> <add>1. **November 22st** - Private alpha launch <add> <add>1. Trickle out invites as people ask/we need more testers. <add> <add>1. If our usage metrics/engagement metrics decrease, stop, identify the issue <add>and fix it before continuing. <add> <add>1. Launch <ide><path>docs/private-beta/tasks.md <add>**Polish the user experience** <add> <add>First and foremost, Atom is a **product**. Atom needs to feel familiar and <add>inviting. This includes a solid introductory experience and parity with the most <add>important features of Sublime Text. <add> <add> * First launch UI and flow (actions below should be easily discoverable) <add> * Create a new file <add> * Open a project and edit an existing file <add> * Install a package <add> * Change settings (adjust theme, change key bindings, set config options) <add> * How to use command P <add> * Use collaboration internally <add> * How and where to edit keyBinding should be obvious to new users <add> * Finish find and replace in buffer/project <add> * Atom should start < 300ms <add> * Match Sublime's multiple selection functionality (#523) <add> * Fix softwrap bugs <add> * Menus & Context menus <add> * Track usage/engagement of our users (make this opted in?) <add> * Windows support <add> * Reliably and securely auto-update and list what's new <add> * Secure access to the keychain (don't give every package access to the keychain) <add> * Secure access to GitHub (each package can ask to have it's own oauth token) <add> * Don't crash when opening/editing large (> 10Mb) files <add> * Send js and native crash reports to a remote server <add> <add>**Lay solid groundwork for a package and theme ecosystem** <add> <add>Extensibility is one of Atom's key value propositions, so a smooth experience <add>for creating and maintaining packages is just as important as the user <add>experience. The package development, dependency and publishing workflow needs to <add>be solid. We also want to have a mechanism for clearly communicating with <add>package authors about breaking API changes. <add> <add> * Finish APM backend (integrate with GitHub Releases) <add> * Streamline Dev workflow <add> * `api create` - create package scaffolding <add> * `apm test` - so users can run focused package tests <add> * `apm publish` - should integrate release best practices (ie npm version) <add> * Determine which classes and methods should be included in the public API <add> * Users can find/install/update/fork existing packages and themes <add> <add>**Tighten up the view layer** <add>Our current approach to the view layer need some improvement. We want to <add>actively promote the use of the M-V-VM design pattern, provide some declarative <add>event binding mechanisms in the view layer, and improve the performance of the <add>typical package specs. We don't want the current approach to be used as an <add>example in a bunch of new packages, so it's important to improve it now. <add> <add> * Add marker view API <add> <add>**Get atom.io online with some exciting articles and documentation** <add>We'd love to send our private alpha candidates to a nice site with information <add>about what Atom is, the philosophies and technologies behind it, and guidance <add>for how to get started. <add> <add> * Design and create www.atom.io <add> * Guides <add> * Theme & Package creation guide <add> * Full API per release tag <add> * Changelog per release <add> * Explanation of features <add> * Explain Semver and general plans for the future (reassure developers we care about them) <add> * General Values/Goals <add> * Make docs accessible from Atom <add> * Community/contribution guidelines <add> * Is all communication to be done through issues? <add> * When should you publish a plugin? <add> * Do we need to vet plugins from a security perspective?
2
Javascript
Javascript
add test for progress plugin
140cbaad2137da7934f87a2d59ba1e46c2175ed5
<ide><path>test/configCases/plugins/progress-plugin/data.js <add>module.exports = []; <ide><path>test/configCases/plugins/progress-plugin/index.js <add>it("should contain the custom progres messages", function() { <add> var data = require(__dirname + "/data"); <add> data.should.containEql("optimizing"); <add> data.should.containEql("optimizing|CustomPlugin"); <add> data.should.containEql("optimizing|CustomPlugin|custom category|custom message"); <add>}); <ide><path>test/configCases/plugins/progress-plugin/webpack.config.js <add>var webpack = require("../../../../"); <add>var data = require("./data"); <add>module.exports = { <add> externals: { <add> [__dirname + "/data"]: "commonjs " + __dirname + "/data" <add> }, <add> plugins: [ <add> new webpack.ProgressPlugin((value, ...messages) => { <add> data.push(messages.join("|")); <add> }), <add> { <add> apply: (compiler) => { <add> compiler.hooks.compilation.tap("CustomPlugin", compilation => { <add> compilation.hooks.optimize.tap({ <add> name: "CustomPlugin", <add> context: true <add> }, (context) => { <add> context.reportProgress(0, "custom category", "custom message"); <add> }); <add> }); <add> } <add> } <add> ] <add>};
3
Python
Python
expose only process_str
7b9ac412223fbb7e94511cc338818f3832cf4aea
<ide><path>scipy_distutils/from_template.py <ide> # Note that all <..> forms in a block must have the same number of <ide> # comma-separated entries. <ide> <add>__all__ = ['process_str'] <ide> <ide> import string,os,sys <ide> if sys.version[:3]>='2.3': <ide> def expand_sub(substr): <ide> <ide> """ <ide> <del>def process_filestr(allstr): <add>def process_str(allstr): <ide> newstr = allstr.lower() <ide> writestr = _head <ide>
1
Text
Text
fix confusing reference in net.md
14749f9eaffaa18eb2acfccfaa691329ae7d8ff4
<ide><path>doc/api/net.md <ide> Additional options: <ide> [`socket.setTimeout(timeout)`][] after the socket is created, but before <ide> it starts the connection. <ide> <del>Here is an example of a client of the previously described echo server: <add>Following is an example of a client of the echo server described <add>in the [`net.createServer()`][] section: <ide> <ide> ```js <ide> const net = require('net');
1
Text
Text
remove extra space in repl example
81903590948eb69e89b6984bd49efde6147cea3c
<ide><path>doc/api/repl.md <ide> dropped into the REPL. It has simplistic emacs line-editing. <ide> ``` <ide> $ node <ide> Type '.help' for options. <del>> a = [ 1, 2, 3]; <add>> a = [1, 2, 3]; <ide> [ 1, 2, 3 ] <ide> > a.forEach((v) => { <ide> ... console.log(v);
1
Text
Text
add method, solution, and reference.
d50b4970dc41b418a9e3efa2e6c6dcbe28e033df
<ide><path>guide/english/certifications/coding-interview-prep/data-structures/reverse-a-doubly-linked-list/index.md <ide> --- <ide> title: Reverse a Doubly Linked List <ide> --- <add> <ide> ## Reverse a Doubly Linked List <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/reverse-a-doubly-linked-list/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>### Method: <add>- Reverse the doubly linked list, and update previous and next variables for each member node accordingly. <add>- Define privileged methods add() and reverse(). <add>- add() will find the end of the list and append new entries at this location. <add>- reverse() will swap entries one pair at a time using a temporary variable. <add> <add>### Solution: <add> <add>```js <add>var Node = function(data, prev) { <add> this.data = data; <add> this.prev = prev; <add> this.next = null; <add>}; <add>var DoublyLinkedList = function() { <add> this.head = null; <add> this.tail = null; <add> // change code below this line <add> this.add = function(element) { <add> let node = new Node(element, this.tail); <add> let currentNode = this.head; <add> let previousNode; <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add> if (this.head === null) { <add> this.head = node; <add> this.tail = node; <add> } else { <add> while (currentNode.next) { <add> previousNode = currentNode; <add> currentNode = currentNode.next; <add> } <add> node.prev = currentNode; <add> currentNode.next = node; <add> this.tail = node; <add> } <add> }; <add> this.reverse = function() { <add> let temp = null; <add> let currentNode = this.head; <add> <add> if (this.head === null) { <add> return null; <add> } <add> <add> this.tail = currentNode; <add> <add> while (currentNode) { <add> temp = currentNode.prev; <add> currentNode.prev = currentNode.next; <add> currentNode.next = temp; <add> currentNode = currentNode.prev; <add> } <add> <add> if (temp != null) { <add> this.head = temp.prev; <add> } <add> }; <add> // change code above this line <add>}; <add>``` <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>### Reference: <add>- [Wikipedia](https://en.wikipedia.org/wiki/Doubly_linked_list)
1
Text
Text
specify location for engine-specific commands
2ffc80ab8afe72e77524e8ed08b253ea388473e1
<ide><path>guides/source/engines.md <ide> The engine that this guide covers provides submitting articles and commenting <ide> functionality and follows a similar thread to the [Getting Started <ide> Guide](getting_started.html), with some new twists. <ide> <add>NOTE: For this section, make sure to run the commands in the root of the <add>`blorgh` engine's directory. <add> <ide> ### Generating an Article Resource <ide> <ide> The first thing to generate for a blog engine is the `Article` model and related
1
Go
Go
update nsinit to be nicer to work with and test
1a3d43c23ec7bbb1aa206581acd0497c47e29a2f
<ide><path>pkg/libcontainer/nsinit/exec.go <add>package main <add> <add>import ( <add> "fmt" <add> "log" <add> "os" <add> "os/exec" <add> "os/signal" <add> <add> "github.com/codegangsta/cli" <add> "github.com/dotcloud/docker/pkg/libcontainer" <add> "github.com/dotcloud/docker/pkg/libcontainer/namespaces" <add>) <add> <add>var execCommand = cli.Command{ <add> Name: "exec", <add> Usage: "execute a new command inside a container", <add> Action: execAction, <add>} <add> <add>func execAction(context *cli.Context) { <add> var ( <add> err error <add> nspid, exitCode int <add> ) <add> <add> if nspid, err = readPid(); err != nil && !os.IsNotExist(err) { <add> log.Fatalf("unable to read pid: %s", err) <add> } <add> <add> if nspid > 0 { <add> exitCode, err = namespaces.ExecIn(container, nspid, []string(context.Args())) <add> } else { <add> term := namespaces.NewTerminal(os.Stdin, os.Stdout, os.Stderr, container.Tty) <add> exitCode, err = startContainer(container, term, dataPath, []string(context.Args())) <add> } <add> <add> if err != nil { <add> log.Fatalf("failed to exec: %s", err) <add> } <add> <add> os.Exit(exitCode) <add>} <add> <add>// startContainer starts the container. Returns the exit status or -1 and an <add>// error. <add>// <add>// Signals sent to the current process will be forwarded to container. <add>func startContainer(container *libcontainer.Container, term namespaces.Terminal, dataPath string, args []string) (int, error) { <add> var ( <add> cmd *exec.Cmd <add> sigc = make(chan os.Signal, 10) <add> ) <add> <add> signal.Notify(sigc) <add> <add> createCommand := func(container *libcontainer.Container, console, rootfs, dataPath, init string, pipe *os.File, args []string) *exec.Cmd { <add> cmd = namespaces.DefaultCreateCommand(container, console, rootfs, dataPath, init, pipe, args) <add> if logPath != "" { <add> cmd.Env = append(cmd.Env, fmt.Sprintf("log=%s", logPath)) <add> } <add> return cmd <add> } <add> <add> startCallback := func() { <add> go func() { <add> for sig := range sigc { <add> cmd.Process.Signal(sig) <add> } <add> }() <add> } <add> <add> return namespaces.Exec(container, term, "", dataPath, args, createCommand, startCallback) <add>} <ide><path>pkg/libcontainer/nsinit/init.go <add>package main <add> <add>import ( <add> "log" <add> "os" <add> "strconv" <add> <add> "github.com/codegangsta/cli" <add> "github.com/dotcloud/docker/pkg/libcontainer/namespaces" <add>) <add> <add>var ( <add> dataPath = os.Getenv("data_path") <add> console = os.Getenv("console") <add> rawPipeFd = os.Getenv("pipe") <add> <add> initCommand = cli.Command{ <add> Name: "init", <add> Usage: "runs the init process inside the namespace", <add> Action: initAction, <add> } <add>) <add> <add>func initAction(context *cli.Context) { <add> rootfs, err := os.Getwd() <add> if err != nil { <add> log.Fatal(err) <add> } <add> <add> pipeFd, err := strconv.Atoi(rawPipeFd) <add> if err != nil { <add> log.Fatal(err) <add> } <add> <add> syncPipe, err := namespaces.NewSyncPipeFromFd(0, uintptr(pipeFd)) <add> if err != nil { <add> log.Fatalf("unable to create sync pipe: %s", err) <add> } <add> <add> if err := namespaces.Init(container, rootfs, console, syncPipe, []string(context.Args())); err != nil { <add> log.Fatalf("unable to initialize for container: %s", err) <add> } <add>} <ide><path>pkg/libcontainer/nsinit/main.go <ide> package main <ide> <ide> import ( <del> "encoding/json" <del> "fmt" <del> "io/ioutil" <ide> "log" <ide> "os" <del> "os/exec" <del> "os/signal" <del> "path/filepath" <del> "strconv" <ide> <add> "github.com/codegangsta/cli" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <del> "github.com/dotcloud/docker/pkg/libcontainer/cgroups/fs" <del> "github.com/dotcloud/docker/pkg/libcontainer/namespaces" <ide> ) <ide> <ide> var ( <del> dataPath = os.Getenv("data_path") <del> console = os.Getenv("console") <del> rawPipeFd = os.Getenv("pipe") <add> container *libcontainer.Container <add> logPath = os.Getenv("log") <ide> ) <ide> <del>func main() { <del> if len(os.Args) < 2 { <del> log.Fatalf("invalid number of arguments %d", len(os.Args)) <del> } <del> <del> switch os.Args[1] { <del> case "exec": // this is executed outside of the namespace in the cwd <del> container, err := loadContainer() <del> if err != nil { <del> log.Fatalf("unable to load container: %s", err) <del> } <del> <del> var nspid, exitCode int <del> if nspid, err = readPid(); err != nil && !os.IsNotExist(err) { <del> log.Fatalf("unable to read pid: %s", err) <del> } <del> <del> if nspid > 0 { <del> err = namespaces.ExecIn(container, nspid, os.Args[2:]) <del> } else { <del> term := namespaces.NewTerminal(os.Stdin, os.Stdout, os.Stderr, container.Tty) <del> exitCode, err = startContainer(container, term, dataPath, os.Args[2:]) <del> } <del> <del> if err != nil { <del> log.Fatalf("failed to exec: %s", err) <del> } <del> os.Exit(exitCode) <del> case "nsenter": // this is executed inside the namespace. <del> // nsinit nsenter <pid> <process label> <container JSON> <cmd>... <del> if len(os.Args) < 6 { <del> log.Fatalf("incorrect usage: nsinit nsenter <pid> <process label> <container JSON> <cmd>...") <del> } <del> <del> container, err := loadContainerFromJson(os.Args[4]) <del> if err != nil { <del> log.Fatalf("unable to load container: %s", err) <del> } <del> <del> nspid, err := strconv.Atoi(os.Args[2]) <del> if err != nil { <del> log.Fatalf("unable to read pid: %s from %q", err, os.Args[2]) <del> } <del> <del> if nspid <= 0 { <del> log.Fatalf("cannot enter into namespaces without valid pid: %q", nspid) <del> } <del> <del> err = namespaces.NsEnter(container, os.Args[3], nspid, os.Args[5:]) <del> if err != nil { <del> log.Fatalf("failed to nsenter: %s", err) <del> } <del> case "init": // this is executed inside of the namespace to setup the container <del> container, err := loadContainer() <del> if err != nil { <del> log.Fatalf("unable to load container: %s", err) <del> } <del> <del> // by default our current dir is always our rootfs <del> rootfs, err := os.Getwd() <del> if err != nil { <del> log.Fatal(err) <del> } <del> <del> pipeFd, err := strconv.Atoi(rawPipeFd) <del> if err != nil { <del> log.Fatal(err) <del> } <del> syncPipe, err := namespaces.NewSyncPipeFromFd(0, uintptr(pipeFd)) <del> if err != nil { <del> log.Fatalf("unable to create sync pipe: %s", err) <del> } <del> <del> if err := namespaces.Init(container, rootfs, console, syncPipe, os.Args[2:]); err != nil { <del> log.Fatalf("unable to initialize for container: %s", err) <del> } <del> case "stats": <del> container, err := loadContainer() <del> if err != nil { <del> log.Fatalf("unable to load container: %s", err) <del> } <del> <del> // returns the stats of the current container. <del> stats, err := getContainerStats(container) <del> if err != nil { <del> log.Printf("Failed to get stats - %v\n", err) <del> os.Exit(1) <del> } <del> fmt.Printf("Stats:\n%v\n", stats) <del> os.Exit(0) <del> <del> case "spec": <del> container, err := loadContainer() <del> if err != nil { <del> log.Fatalf("unable to load container: %s", err) <del> } <del> <del> // returns the spec of the current container. <del> spec, err := getContainerSpec(container) <del> if err != nil { <del> log.Printf("Failed to get spec - %v\n", err) <del> os.Exit(1) <del> } <del> fmt.Printf("Spec:\n%v\n", spec) <del> os.Exit(0) <del> <del> default: <del> log.Fatalf("command not supported for nsinit %s", os.Args[1]) <del> } <del>} <del> <del>func loadContainer() (*libcontainer.Container, error) { <del> f, err := os.Open(filepath.Join(dataPath, "container.json")) <add>func preload(context *cli.Context) (err error) { <add> container, err = loadContainer() <ide> if err != nil { <del> log.Printf("Path: %q", filepath.Join(dataPath, "container.json")) <del> return nil, err <del> } <del> defer f.Close() <del> <del> var container *libcontainer.Container <del> if err := json.NewDecoder(f).Decode(&container); err != nil { <del> return nil, err <add> return err <ide> } <del> return container, nil <del>} <ide> <del>func loadContainerFromJson(rawData string) (*libcontainer.Container, error) { <del> container := &libcontainer.Container{} <del> err := json.Unmarshal([]byte(rawData), container) <del> if err != nil { <del> return nil, err <add> if logPath != "" { <ide> } <del> return container, nil <del>} <ide> <del>func readPid() (int, error) { <del> data, err := ioutil.ReadFile(filepath.Join(dataPath, "pid")) <del> if err != nil { <del> return -1, err <del> } <del> pid, err := strconv.Atoi(string(data)) <del> if err != nil { <del> return -1, err <del> } <del> return pid, nil <add> return nil <ide> } <ide> <del>// startContainer starts the container. Returns the exit status or -1 and an <del>// error. <del>// <del>// Signals sent to the current process will be forwarded to container. <del>func startContainer(container *libcontainer.Container, term namespaces.Terminal, dataPath string, args []string) (int, error) { <del> var ( <del> cmd *exec.Cmd <del> sigc = make(chan os.Signal, 10) <del> ) <del> <del> signal.Notify(sigc) <del> <del> createCommand := func(container *libcontainer.Container, console, rootfs, dataPath, init string, pipe *os.File, args []string) *exec.Cmd { <del> cmd = namespaces.DefaultCreateCommand(container, console, rootfs, dataPath, init, pipe, args) <del> return cmd <del> } <del> <del> startCallback := func() { <del> go func() { <del> for sig := range sigc { <del> cmd.Process.Signal(sig) <del> } <del> }() <del> } <del> <del> return namespaces.Exec(container, term, "", dataPath, args, createCommand, startCallback) <del>} <add>func main() { <add> app := cli.NewApp() <add> app.Name = "nsinit" <add> app.Version = "0.1" <add> app.Author = "libcontainer maintainers" <ide> <del>// returns the container stats in json format. <del>func getContainerStats(container *libcontainer.Container) (string, error) { <del> stats, err := fs.GetStats(container.Cgroups) <del> if err != nil { <del> return "", err <del> } <del> out, err := json.MarshalIndent(stats, "", "\t") <del> if err != nil { <del> return "", err <add> app.Before = preload <add> app.Commands = []cli.Command{ <add> execCommand, <add> initCommand, <add> statsCommand, <add> specCommand, <ide> } <del> return string(out), nil <del>} <ide> <del>// returns the container spec in json format. <del>func getContainerSpec(container *libcontainer.Container) (string, error) { <del> spec, err := json.MarshalIndent(container, "", "\t") <del> if err != nil { <del> return "", err <add> if err := app.Run(os.Args); err != nil { <add> log.Fatal(err) <ide> } <del> return string(spec), nil <ide> } <ide><path>pkg/libcontainer/nsinit/spec.go <add>package main <add> <add>import ( <add> "encoding/json" <add> "fmt" <add> "log" <add> "os" <add> <add> "github.com/codegangsta/cli" <add> "github.com/dotcloud/docker/pkg/libcontainer" <add>) <add> <add>var specCommand = cli.Command{ <add> Name: "spec", <add> Usage: "display the container specification", <add> Action: specAction, <add>} <add> <add>func specAction(context *cli.Context) { <add> // returns the spec of the current container. <add> spec, err := getContainerSpec(container) <add> if err != nil { <add> log.Printf("Failed to get spec - %v\n", err) <add> os.Exit(1) <add> } <add> fmt.Printf("Spec:\n%v\n", spec) <add> os.Exit(0) <add> <add>} <add> <add>// returns the container spec in json format. <add>func getContainerSpec(container *libcontainer.Container) (string, error) { <add> spec, err := json.MarshalIndent(container, "", "\t") <add> if err != nil { <add> return "", err <add> } <add> return string(spec), nil <add>} <ide><path>pkg/libcontainer/nsinit/stats.go <add>package main <add> <add>import ( <add> "encoding/json" <add> "fmt" <add> "log" <add> "os" <add> <add> "github.com/codegangsta/cli" <add> "github.com/dotcloud/docker/pkg/libcontainer" <add> "github.com/dotcloud/docker/pkg/libcontainer/cgroups/fs" <add>) <add> <add>var statsCommand = cli.Command{ <add> Name: "stats", <add> Usage: "display statistics for the container", <add> Action: statsAction, <add>} <add> <add>func statsAction(context *cli.Context) { <add> // returns the stats of the current container. <add> stats, err := getContainerStats(container) <add> if err != nil { <add> log.Printf("Failed to get stats - %v\n", err) <add> os.Exit(1) <add> } <add> fmt.Printf("Stats:\n%v\n", stats) <add> os.Exit(0) <add>} <add> <add>// returns the container stats in json format. <add>func getContainerStats(container *libcontainer.Container) (string, error) { <add> stats, err := fs.GetStats(container.Cgroups) <add> if err != nil { <add> return "", err <add> } <add> out, err := json.MarshalIndent(stats, "", "\t") <add> if err != nil { <add> return "", err <add> } <add> return string(out), nil <add>} <ide><path>pkg/libcontainer/nsinit/utils.go <add>package main <add> <add>import ( <add> "encoding/json" <add> "io/ioutil" <add> "log" <add> "os" <add> "path/filepath" <add> "strconv" <add> <add> "github.com/dotcloud/docker/pkg/libcontainer" <add>) <add> <add>func loadContainer() (*libcontainer.Container, error) { <add> f, err := os.Open(filepath.Join(dataPath, "container.json")) <add> if err != nil { <add> return nil, err <add> } <add> defer f.Close() <add> <add> var container *libcontainer.Container <add> if err := json.NewDecoder(f).Decode(&container); err != nil { <add> return nil, err <add> } <add> <add> return container, nil <add>} <add> <add>func readPid() (int, error) { <add> data, err := ioutil.ReadFile(filepath.Join(dataPath, "pid")) <add> if err != nil { <add> return -1, err <add> } <add> <add> pid, err := strconv.Atoi(string(data)) <add> if err != nil { <add> return -1, err <add> } <add> <add> return pid, nil <add>} <add> <add>func openLog(name string) error { <add> f, err := os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0755) <add> if err != nil { <add> return err <add> } <add> <add> log.SetOutput(f) <add> <add> return nil <add>}
6
Text
Text
use "long term support" in technical values doc
0ba7da6f0f1c5f0f49f10830c890ad67d5ddfd35
<ide><path>doc/guides/technical-values.md <ide> Some key elements of this include: <ide> * Stable releases on a predictable schedule <ide> * A strong safety net, including testing how changes <ide> in Node.js affect popular packages <del>* Careful consideration of what goes into long term support (LTS) releases <add>* Careful consideration of what goes into Long Term Support (LTS) releases <ide> <ide> ### 3 - Operational qualities <ide> We value keeping Node.js safe, performant, and lightweight.
1
Javascript
Javascript
expose info about selection state in controller
6fc0f02ad24a6ac8bef517210e6d7e679c3988fd
<ide><path>src/ng/directive/select.js <ide> function setOptionSelectedStatus(optionEl, value) { <ide> /** <ide> * @ngdoc type <ide> * @name select.SelectController <add> * <ide> * @description <del> * The controller for the `<select>` directive. This provides support for reading <del> * and writing the selected value(s) of the control and also coordinates dynamically <del> * added `<option>` elements, perhaps by an `ngRepeat` directive. <add> * The controller for the {@link ng.select select} directive. The controller exposes <add> * a few utility methods that can be used to augment the behavior of a regular or an <add> * {@link ng.ngOptions ngOptions} select element. <add> * <add> * @example <add> * ### Set a custom error when the unknown option is selected <add> * <add> * This example sets a custom error "unknownValue" on the ngModelController <add> * when the select element's unknown option is selected, i.e. when the model is set to a value <add> * that is not matched by any option. <add> * <add> * <example name="select-unknown-value-error" module="staticSelect"> <add> * <file name="index.html"> <add> * <div ng-controller="ExampleController"> <add> * <form name="myForm"> <add> * <label for="testSelect"> Single select: </label><br> <add> * <select name="testSelect" ng-model="selected" unknown-value-error> <add> * <option value="option-1">Option 1</option> <add> * <option value="option-2">Option 2</option> <add> * </select><br> <add> * <span ng-if="myForm.testSelect.$error.unknownValue">Error: The current model doesn't match any option</span> <add> * <add> * <button ng-click="forceUnknownOption()">Force unknown option</button><br> <add> * </form> <add> * </div> <add> * </file> <add> * <file name="app.js"> <add> * angular.module('staticSelect', []) <add> * .controller('ExampleController', ['$scope', function($scope) { <add> * $scope.selected = null; <add> * <add> * $scope.forceUnknownOption = function() { <add> * $scope.selected = 'nonsense'; <add> * }; <add> * }]) <add> * .directive('unknownValueError', function() { <add> * return { <add> * require: ['ngModel', 'select'], <add> * link: function(scope, element, attrs, ctrls) { <add> * var ngModelCtrl = ctrls[0]; <add> * var selectCtrl = ctrls[1]; <add> * <add> * ngModelCtrl.$validators.unknownValue = function(modelValue, viewValue) { <add> * if (selectCtrl.$isUnknownOptionSelected()) { <add> * return false; <add> * } <add> * <add> * return true; <add> * }; <add> * } <add> * <add> * }; <add> * }); <add> * </file> <add> *</example> <add> * <add> * <add> * @example <add> * ### Set the "required" error when the unknown option is selected. <add> * <add> * By default, the "required" error on the ngModelController is only set on a required select <add> * when the empty option is selected. This example adds a custom directive that also sets the <add> * error when the unknown option is selected. <add> * <add> * <example name="select-unknown-value-required" module="staticSelect"> <add> * <file name="index.html"> <add> * <div ng-controller="ExampleController"> <add> * <form name="myForm"> <add> * <label for="testSelect"> Select: </label><br> <add> * <select name="testSelect" ng-model="selected" unknown-value-required> <add> * <option value="option-1">Option 1</option> <add> * <option value="option-2">Option 2</option> <add> * </select><br> <add> * <span ng-if="myForm.testSelect.$error.required">Error: Please select a value</span><br> <add> * <add> * <button ng-click="forceUnknownOption()">Force unknown option</button><br> <add> * </form> <add> * </div> <add> * </file> <add> * <file name="app.js"> <add> * angular.module('staticSelect', []) <add> * .controller('ExampleController', ['$scope', function($scope) { <add> * $scope.selected = null; <add> * <add> * $scope.forceUnknownOption = function() { <add> * $scope.selected = 'nonsense'; <add> * }; <add> * }]) <add> * .directive('unknownValueRequired', function() { <add> * return { <add> * priority: 1, // This directive must run after the required directive has added its validator <add> * require: ['ngModel', 'select'], <add> * link: function(scope, element, attrs, ctrls) { <add> * var ngModelCtrl = ctrls[0]; <add> * var selectCtrl = ctrls[1]; <add> * <add> * var originalRequiredValidator = ngModelCtrl.$validators.required; <add> * <add> * ngModelCtrl.$validators.required = function() { <add> * if (attrs.required && selectCtrl.$isUnknownOptionSelected()) { <add> * return false; <add> * } <add> * <add> * return originalRequiredValidator.apply(this, arguments); <add> * }; <add> * } <add> * }; <add> * }); <add> * </file> <add> *</example> <add> * <add> * <ide> */ <ide> var SelectController = <ide> ['$element', '$scope', /** @this */ function($element, $scope) { <ide> var SelectController = <ide> return !!optionsMap.get(value); <ide> }; <ide> <add> /** <add> * @ngdoc method <add> * @name select.SelectController#$hasEmptyOption <add> * <add> * @description <add> * <add> * Returns `true` if the select element currently has an empty option <add> * element, i.e. an option that signifies that the select is empty / the selection is null. <add> * <add> */ <add> self.$hasEmptyOption = function() { <add> return self.hasEmptyOption; <add> }; <add> <add> /** <add> * @ngdoc method <add> * @name select.SelectController#$isUnknownOptionSelected <add> * <add> * @description <add> * <add> * Returns `true` if the select element's unknown option is selected. The unknown option is added <add> * and automatically selected whenever the select model doesn't match any option. <add> * <add> */ <add> self.$isUnknownOptionSelected = function() { <add> // Presence of the unknown option means it is selected <add> return $element[0].options[0] === self.unknownOption[0]; <add> }; <add> <add> /** <add> * @ngdoc method <add> * @name select.SelectController#$isEmptyOptionSelected <add> * <add> * @description <add> * <add> * Returns `true` if the select element has an empty option and this empty option is currently <add> * selected. Returns `false` if the select element has no empty option or it is not selected. <add> * <add> */ <add> self.$isEmptyOptionSelected = function() { <add> return self.hasEmptyOption && $element[0].options[$element[0].selectedIndex] === self.emptyOption[0]; <add> }; <add> <ide> self.selectUnknownOrEmptyOption = function(value) { <ide> if (value == null && self.emptyOption) { <ide> self.removeUnknownOption(); <ide> var SelectController = <ide> * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing. <ide> * Value and textContent can be interpolated. <ide> * <add> * The {@link select.selectController select controller} exposes utility functions that can be used <add> * to manipulate the select's behavior. <add> * <ide> * ## Matching model and option values <ide> * <ide> * In general, the match between the model and an option is evaluated by strictly comparing the model <ide><path>test/ng/directive/ngOptionsSpec.js <ide> describe('ngOptions', function() { <ide> expect(scope.form.select.$pristine).toBe(true); <ide> }); <ide> }); <add> <add> describe('selectCtrl api', function() { <add> <add> it('should reflect the status of empty and unknown option', function() { <add> createSingleSelect('<option ng-if="isBlank" value="">blank</option>'); <add> <add> var selectCtrl = element.controller('select'); <add> <add> scope.$apply(function() { <add> scope.values = [{name: 'A'}, {name: 'B'}]; <add> scope.isBlank = true; <add> }); <add> <add> expect(element).toEqualSelect([''], 'object:4', 'object:5'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(true); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // empty -> selection <add> scope.$apply(function() { <add> scope.selected = scope.values[0]; <add> }); <add> <add> expect(element).toEqualSelect('', ['object:4'], 'object:5'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // remove empty <add> scope.$apply('isBlank = false'); <add> <add> expect(element).toEqualSelect(['object:4'], 'object:5'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(false); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // selection -> unknown <add> scope.$apply('selected = "unmatched"'); <add> <add> expect(element).toEqualSelect(['?'], 'object:4', 'object:5'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(false); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(true); <add> <add> // add empty <add> scope.$apply('isBlank = true'); <add> <add> expect(element).toEqualSelect(['?'], '', 'object:4', 'object:5'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(true); <add> <add> // unknown -> empty <add> scope.$apply(function() { <add> scope.selected = null; <add> }); <add> <add> expect(element).toEqualSelect([''], 'object:4', 'object:5'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(true); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // empty -> unknown <add> scope.$apply('selected = "unmatched"'); <add> <add> expect(element).toEqualSelect(['?'], '', 'object:4', 'object:5'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(true); <add> <add> // unknown -> selection <add> scope.$apply(function() { <add> scope.selected = scope.values[1]; <add> }); <add> <add> expect(element).toEqualSelect('', 'object:4', ['object:5']); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // selection -> empty <add> scope.$apply('selected = null'); <add> <add> expect(element).toEqualSelect([''], 'object:4', 'object:5'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(true); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> }); <add> }); <add> <ide> }); <ide><path>test/ng/directive/selectSpec.js <ide> describe('select', function() { <ide> describe('empty option', function() { <ide> <ide> it('should allow empty option to be added and removed dynamically', function() { <del> <ide> scope.dynamicOptions = []; <ide> scope.robot = ''; <ide> compile('<select ng-model="robot">' + <ide> '<option ng-repeat="opt in dynamicOptions" value="{{opt.val}}">{{opt.display}}</option>' + <ide> '</select>'); <del> expect(element).toEqualSelect(['? string: ?']); <ide> <add> expect(element).toEqualSelect(['? string: ?']); <ide> <ide> scope.dynamicOptions = [ <del> { val: '', display: '--select--' }, <add> { val: '', display: '--empty--'}, <ide> { val: 'x', display: 'robot x' }, <ide> { val: 'y', display: 'robot y' } <ide> ]; <ide> scope.$digest(); <ide> expect(element).toEqualSelect([''], 'x', 'y'); <ide> <del> <ide> scope.robot = 'x'; <ide> scope.$digest(); <ide> expect(element).toEqualSelect('', ['x'], 'y'); <ide> <del> <ide> scope.dynamicOptions.shift(); <ide> scope.$digest(); <ide> expect(element).toEqualSelect(['x'], 'y'); <ide> <del> <ide> scope.robot = undefined; <ide> scope.$digest(); <ide> expect(element).toEqualSelect([unknownValue(undefined)], 'x', 'y'); <ide> describe('select', function() { <ide> }); <ide> }); <ide> <add> describe('selectController', function() { <add> <add> it('should expose .$hasEmptyOption(), .$isEmptyOptionSelected(), ' + <add> 'and .$isUnknownOptionSelected()', function() { <add> compile('<select ng-model="mySelect"></select>'); <add> <add> var selectCtrl = element.controller('select'); <add> <add> expect(selectCtrl.$hasEmptyOption).toEqual(jasmine.any(Function)); <add> expect(selectCtrl.$isEmptyOptionSelected).toEqual(jasmine.any(Function)); <add> expect(selectCtrl.$isUnknownOptionSelected).toEqual(jasmine.any(Function)); <add> } <add> ); <add> <add> <add> it('should reflect the status of empty and unknown option', function() { <add> scope.dynamicOptions = []; <add> scope.selected = ''; <add> compile('<select ng-model="selected">' + <add> '<option ng-if="empty" value="">--no selection--</option>' + <add> '<option ng-repeat="opt in dynamicOptions" value="{{opt.val}}">{{opt.display}}</option>' + <add> '</select>'); <add> <add> var selectCtrl = element.controller('select'); <add> <add> expect(element).toEqualSelect(['? string: ?']); <add> expect(selectCtrl.$hasEmptyOption()).toBe(false); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> <add> scope.dynamicOptions = [ <add> { val: 'x', display: 'robot x' }, <add> { val: 'y', display: 'robot y' } <add> ]; <add> scope.empty = true; <add> <add> scope.$digest(); <add> expect(element).toEqualSelect([''], 'x', 'y'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(true); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // empty -> selection <add> scope.$apply('selected = "x"'); <add> expect(element).toEqualSelect('', ['x'], 'y'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // remove empty <add> scope.$apply('empty = false'); <add> expect(element).toEqualSelect(['x'], 'y'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(false); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // selection -> unknown <add> scope.$apply('selected = "unmatched"'); <add> expect(element).toEqualSelect([unknownValue('unmatched')], 'x', 'y'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(false); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(true); <add> <add> // add empty <add> scope.$apply('empty = true'); <add> expect(element).toEqualSelect([unknownValue('unmatched')], '', 'x', 'y'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(true); <add> <add> // unknown -> empty <add> scope.$apply('selected = null'); <add> <add> expect(element).toEqualSelect([''], 'x', 'y'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(true); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // empty -> unknown <add> scope.$apply('selected = "unmatched"'); <add> <add> expect(element).toEqualSelect([unknownValue('unmatched')], '', 'x', 'y'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(true); <add> <add> // unknown -> selection <add> scope.$apply('selected = "y"'); <add> <add> expect(element).toEqualSelect('', 'x', ['y']); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(false); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> <add> // selection -> empty <add> scope.$apply('selected = null'); <add> <add> expect(element).toEqualSelect([''], 'x', 'y'); <add> expect(selectCtrl.$hasEmptyOption()).toBe(true); <add> expect(selectCtrl.$isEmptyOptionSelected()).toBe(true); <add> expect(selectCtrl.$isUnknownOptionSelected()).toBe(false); <add> }); <add> <add> }); <ide> <ide> describe('selectController.hasOption', function() { <ide>
3
Javascript
Javascript
log all errors to console.error by default
0853aab74dc8285401e62d1e490551ba3c96fd64
<ide><path>packages/react-client/src/__tests__/ReactFlight-test.js <ide> describe('ReactFlight', () => { <ide> return <div ref={ref} />; <ide> } <ide> <del> const event = ReactNoopFlightServer.render(<EventHandlerProp />); <del> const fn = ReactNoopFlightServer.render(<FunctionProp />); <del> const symbol = ReactNoopFlightServer.render(<SymbolProp />); <del> const refs = ReactNoopFlightServer.render(<RefProp />); <add> const options = { <add> onError() { <add> // ignore <add> }, <add> }; <add> const event = ReactNoopFlightServer.render(<EventHandlerProp />, options); <add> const fn = ReactNoopFlightServer.render(<FunctionProp />, options); <add> const symbol = ReactNoopFlightServer.render(<SymbolProp />, options); <add> const refs = ReactNoopFlightServer.render(<RefProp />, options); <ide> <ide> function Client({transport}) { <ide> return ReactNoopFlightClient.read(transport); <ide> describe('ReactFlight', () => { <ide> ); <ide> } <ide> <del> const data = ReactNoopFlightServer.render(<Server />); <add> const data = ReactNoopFlightServer.render(<Server />, { <add> onError(x) { <add> // ignore <add> }, <add> }); <ide> <ide> function Client({transport}) { <ide> return ReactNoopFlightClient.read(transport); <ide><path>packages/react-server/src/ReactFizzServer.js <ide> type Request = { <ide> // 500 * 1024 / 8 * .8 * 0.5 / 2 <ide> const DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800; <ide> <add>function defaultErrorHandler(error: mixed) { <add> console['error'](error); // Don't transform to our wrapper <add>} <add> <ide> export function createRequest( <ide> children: ReactNodeList, <ide> destination: Destination, <ide> responseState: ResponseState, <ide> rootContext: FormatContext, <ide> progressiveChunkSize: number = DEFAULT_PROGRESSIVE_CHUNK_SIZE, <del> onError: (error: mixed) => void = noop, <add> onError: (error: mixed) => void = defaultErrorHandler, <ide> onCompleteAll: () => void = noop, <ide> onReadyToStream: () => void = noop, <ide> ): Request { <ide><path>packages/react-server/src/ReactFlightServer.js <ide> export type Request = { <ide> <ide> const ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; <ide> <del>function defaultErrorHandler() {} <add>function defaultErrorHandler(error: mixed) { <add> console['error'](error); // Don't transform to our wrapper <add>} <ide> <ide> export function createRequest( <ide> model: ReactModel,
3
Javascript
Javascript
call minification post-processing hook
5ee4e63abf944e8b0bae34ba69637803bd84f8b0
<ide><path>packager/src/ModuleGraph/worker/__tests__/optimize-module-test.js <ide> const optimizeModule = require('../optimize-module'); <ide> const transformModule = require('../transform-module'); <ide> const transformer = require('../../../../transformer.js'); <ide> const {SourceMapConsumer} = require('source-map'); <add>const {fn} = require('../../test-helpers'); <ide> <ide> const {objectContaining} = jasmine; <ide> <ide> describe('optimizing JS modules', () => { <ide> const optimizationOptions = { <ide> dev: false, <ide> platform: 'android', <add> postMinifyProcess: x => x, <ide> }; <ide> const originalCode = <ide> `if (Platform.OS !== 'android') { <ide> describe('optimizing JS modules', () => { <ide> }); <ide> }); <ide> <add> describe('post-processing', () => { <add> let postMinifyProcess, optimize; <add> beforeEach(() => { <add> postMinifyProcess = fn(); <add> optimize = () => <add> optimizeModule(transformResult, {...optimizationOptions, postMinifyProcess}); <add> }); <add> <add> it('passes the result to the provided postprocessing function', () => { <add> postMinifyProcess.stub.callsFake(x => x); <add> const result = optimize(); <add> const {code, map} = result.details.transformed.default; <add> expect(postMinifyProcess).toBeCalledWith({code, map}); <add> }); <add> <add> it('uses the result of the provided postprocessing function for the result', () => { <add> const code = 'var postprocessed = "code";'; <add> const map = {version: 3, mappings: 'postprocessed'}; <add> postMinifyProcess.stub.returns({code, map}); <add> expect(optimize().details.transformed.default) <add> .toEqual(objectContaining({code, map})); <add> }); <add> }); <add> <ide> it('passes through non-code data unmodified', () => { <ide> const data = {type: 'asset', details: {arbitrary: 'data'}}; <ide> expect(optimizeModule(JSON.stringify(data), {dev: true, platform: ''})) <ide><path>packager/src/ModuleGraph/worker/optimize-module.js <ide> const sourceMap = require('source-map'); <ide> <ide> import type {TransformedSourceFile, TransformResult} from '../types.flow'; <ide> import type {MappingsMap, SourceMap} from '../../lib/SourceMap'; <add>import type {PostMinifyProcess} from '../../Bundler/index.js'; <add> <ide> <ide> export type OptimizationOptions = {| <ide> dev: boolean, <ide> isPolyfill?: boolean, <ide> platform: string, <add> postMinifyProcess: PostMinifyProcess, <ide> |}; <ide> <ide> function optimizeModule( <ide> function optimizeModule( <ide> const {details} = data; <ide> const {code, file, transformed} = details; <ide> const result = {...details, transformed: {}}; <add> const {postMinifyProcess} = optimizationOptions; <ide> <ide> //$FlowIssue #14545724 <ide> Object.entries(transformed).forEach(([k, t: TransformResult]: [*, TransformResult]) => { <del> result.transformed[k] = optimize(t, file, code, optimizationOptions); <add> const optimized = optimize(t, file, code, optimizationOptions); <add> const processed = postMinifyProcess({code: optimized.code, map: optimized.map}); <add> optimized.code = processed.code; <add> optimized.map = processed.map; <add> result.transformed[k] = optimized; <ide> }); <ide> <ide> return {type: 'code', details: result}; <ide> } <ide> <del>function optimize(transformed, file, originalCode, options): TransformResult { <add>function optimize(transformed, file, originalCode, options) { <ide> const {code, dependencyMapName, map} = transformed; <ide> const optimized = optimizeCode(code, map, file, options); <ide>
2
Javascript
Javascript
fix failing tests for non-blocking assertions
6867a0b14a1bbee72e81b4245628f0a5f78803df
<ide><path>packages/ember-handlebars/lib/main.js <del>require("ember-handlebars-compiler"); <ide> require("ember-runtime"); <add>require("ember-handlebars-compiler"); <ide> require("ember-views"); <ide> require("ember-handlebars/ext"); <ide> require("ember-handlebars/string"); <ide><path>packages/ember-old-router/tests/routable_test.js <ide> test("if a leaf state has a redirectsTo, it automatically transitions into that <ide> }); <ide> <ide> test("you cannot define connectOutlets AND redirectsTo", function() { <del> raises(function() { <add> expectAssertion(function() { <ide> Ember.Router.create({ <ide> location: 'none', <ide> root: Ember.Route.create({ <ide> test("you cannot define connectOutlets AND redirectsTo", function() { <ide> }); <ide> <ide> test("you cannot have a redirectsTo in a non-leaf state", function () { <del> raises(function() { <add> expectAssertion(function() { <ide> Ember.Router.create({ <ide> location: 'none', <ide> root: Ember.Route.create({ <ide> test("urlFor raises an error when route property is not defined", function() { <ide> }) <ide> }); <ide> <del> raises(function (){ <add> expectAssertion(function (){ <ide> router.urlFor('root.dashboard'); <ide> }); <ide> });
2
Python
Python
fix a bug that ignores max_seq_len in preprocess
2b8599b2df6a09f83bd8b19086f691a648af74cb
<ide><path>src/transformers/pipelines/question_answering.py <ide> def _sanitize_parameters( <ide> preprocess_params["doc_stride"] = doc_stride <ide> if max_question_len is not None: <ide> preprocess_params["max_question_len"] = max_question_len <add> if max_seq_len is not None: <add> preprocess_params["max_seq_len"] = max_seq_len <ide> <ide> postprocess_params = {} <ide> if topk is not None and top_k is None:
1
Go
Go
detect defaultnetworkmtu from default route
4d0a026c98721da874a03f5b6993045bae95842a
<ide><path>config.go <ide> package docker <ide> <ide> import ( <del> "github.com/dotcloud/docker/engine" <ide> "net" <add> <add> "github.com/dotcloud/docker/engine" <add> "github.com/dotcloud/docker/networkdriver" <ide> ) <ide> <ide> const ( <del> DefaultNetworkMtu = 1500 <add> defaultNetworkMtu = 1500 <ide> DisableNetworkBridge = "none" <ide> ) <ide> <ide> func DaemonConfigFromJob(job *engine.Job) *DaemonConfig { <ide> <ide> return config <ide> } <add> <add>func GetDefaultNetworkMtu() int { <add> if iface, err := networkdriver.GetDefaultRouteIface(); err == nil { <add> return iface.MTU <add> } <add> return defaultNetworkMtu <add>} <ide><path>docker/docker.go <ide> package main <ide> <ide> import ( <ide> "fmt" <add> "log" <add> "os" <add> "strings" <add> <ide> "github.com/dotcloud/docker" <ide> "github.com/dotcloud/docker/api" <ide> "github.com/dotcloud/docker/engine" <ide> flag "github.com/dotcloud/docker/pkg/mflag" <ide> "github.com/dotcloud/docker/sysinit" <ide> "github.com/dotcloud/docker/utils" <del> "log" <del> "os" <del> "strings" <ide> ) <ide> <ide> var ( <ide> func main() { <ide> flInterContainerComm = flag.Bool([]string{"#icc", "-icc"}, true, "Enable inter-container communication") <ide> flGraphDriver = flag.String([]string{"s", "-storage-driver"}, "", "Force the docker runtime to use a specific storage driver") <ide> flHosts = docker.NewListOpts(docker.ValidateHost) <del> flMtu = flag.Int([]string{"#mtu", "-mtu"}, docker.DefaultNetworkMtu, "Set the containers network mtu") <add> flMtu = flag.Int([]string{"#mtu", "-mtu"}, docker.GetDefaultNetworkMtu(), "Set the containers network mtu") <ide> ) <ide> flag.Var(&flDns, []string{"#dns", "-dns"}, "Force docker to use specific DNS servers") <ide> flag.Var(&flHosts, []string{"H", "-host"}, "tcp://host:port, unix://path/to/socket, fd://* or fd://socketfd to use in daemon mode. Multiple sockets can be specified") <ide><path>networkdriver/utils.go <ide> package networkdriver <ide> import ( <ide> "encoding/binary" <ide> "fmt" <del> "github.com/dotcloud/docker/pkg/netlink" <ide> "net" <add> <add> "github.com/dotcloud/docker/pkg/netlink" <ide> ) <ide> <ide> var ( <ide> func GetIfaceAddr(name string) (net.Addr, error) { <ide> } <ide> return addrs4[0], nil <ide> } <add> <add>func GetDefaultRouteIface() (*net.Interface, error) { <add> rs, err := netlink.NetworkGetRoutes() <add> if err != nil { <add> return nil, fmt.Errorf("unable to get routes: %v", err) <add> } <add> for _, r := range rs { <add> if r.Default { <add> return r.Iface, nil <add> } <add> } <add> return nil, fmt.Errorf("no default route") <add>}
3
Javascript
Javascript
remove common.port from test-cluster-basic
c05e5bfa7b32ad6e527c6cb801ce96883ce274e3
<ide><path>test/parallel/test-cluster-basic.js <ide> function forEach(obj, fn) { <ide> <ide> <ide> if (cluster.isWorker) { <del> const http = require('http'); <del> http.Server(function() { <del> <del> }).listen(common.PORT, '127.0.0.1'); <add> require('http').Server(common.noop).listen(0, '127.0.0.1'); <ide> } else if (cluster.isMaster) { <ide> <ide> const checks = { <ide> if (cluster.isWorker) { <ide> <ide> case 'listening': <ide> assert.strictEqual(arguments.length, 1); <del> const expect = { address: '127.0.0.1', <del> port: common.PORT, <del> addressType: 4, <del> fd: undefined }; <del> assert.deepStrictEqual(arguments[0], expect); <add> assert.strictEqual(Object.keys(arguments[0]).length, 4); <add> assert.strictEqual(arguments[0].address, '127.0.0.1'); <add> assert.strictEqual(arguments[0].addressType, 4); <add> assert(arguments[0].hasOwnProperty('fd')); <add> assert.strictEqual(arguments[0].fd, undefined); <add> const port = arguments[0].port; <add> assert(Number.isInteger(port)); <add> assert(port >= 1); <add> assert(port <= 65535); <ide> break; <ide> <ide> default:
1
Python
Python
remove unused import
a89a6000e5b4170d3f7c871088885159c98912ae
<ide><path>spacy/it/__init__.py <ide> # encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <del>from os import path <del> <ide> from ..language import Language <ide> from ..attrs import LANG <ide> <ide><path>spacy/nl/__init__.py <ide> # encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <del>from os import path <del> <ide> from ..language import Language <ide> from ..attrs import LANG <ide> from .language_data import * <ide><path>spacy/pt/__init__.py <ide> # encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <del>from os import path <del> <ide> from ..language import Language <ide> from ..attrs import LANG <ide> <ide><path>spacy/sv/__init__.py <ide> # encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <del>from os import path <del> <ide> from ..language import Language <ide> from ..attrs import LANG <ide> from .language_data import *
4
Python
Python
fix mypy issues in ``airflow/macros``
72eb0d3a5500210a8e2a83121bef6ea686f0af53
<ide><path>airflow/macros/__init__.py <ide> from typing import Any, Optional <ide> <ide> import dateutil # noqa <add>from pendulum import DateTime <ide> <ide> from airflow.macros import hive # noqa <ide> <ide> def ds_format(ds: str, input_format: str, output_format: str) -> str: <ide> return datetime.strptime(str(ds), input_format).strftime(output_format) <ide> <ide> <del>def datetime_diff_for_humans(dt: Any, since: Optional[datetime] = None) -> str: <add>def datetime_diff_for_humans(dt: Any, since: Optional[DateTime] = None) -> str: <ide> """ <ide> Return a human-readable/approximate difference between two datetimes, or <ide> one and now. <ide> def datetime_diff_for_humans(dt: Any, since: Optional[datetime] = None) -> str: <ide> :type dt: datetime.datetime <ide> :param since: When to display the date from. If ``None`` then the diff is <ide> between ``dt`` and now. <del> :type since: None or datetime.datetime <add> :type since: None or DateTime <ide> :rtype: str <ide> """ <ide> import pendulum
1
Javascript
Javascript
improve unicode support
8fb5fe28a45cc884567cd39e3b2f6b4272917af6
<ide><path>lib/internal/cli_table.js <ide> const { <ide> ObjectPrototypeHasOwnProperty, <ide> } = primordials; <ide> <del>const { getStringWidth } = require('internal/readline/utils'); <add>const { getStringWidth } = require('internal/util/inspect'); <ide> <ide> // The use of Unicode characters below is the only non-comment use of non-ASCII <ide> // Unicode characters in Node.js built-in modules. If they are ever removed or <ide><path>lib/internal/readline/utils.js <ide> 'use strict'; <ide> <ide> const { <del> RegExp, <ide> Symbol, <ide> } = primordials; <ide> <del>// Regex used for ansi escape code splitting <del>// Adopted from https://github.com/chalk/ansi-regex/blob/master/index.js <del>// License: MIT, authors: @sindresorhus, Qix-, arjunmehta and LitoMore <del>// Matches all ansi escape code sequences in a string <del>const ansiPattern = '[\\u001B\\u009B][[\\]()#;?]*' + <del> '(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' + <del> '|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'; <del>const ansi = new RegExp(ansiPattern, 'g'); <del> <ide> const kUTF16SurrogateThreshold = 0x10000; // 2 ** 16 <ide> const kEscape = '\x1b'; <ide> const kSubstringSearch = Symbol('kSubstringSearch'); <ide> <del>let getStringWidth; <del> <ide> function CSI(strings, ...args) { <ide> let ret = `${kEscape}[`; <ide> for (let n = 0; n < strings.length; n++) { <ide> function charLengthAt(str, i) { <ide> return str.codePointAt(i) >= kUTF16SurrogateThreshold ? 2 : 1; <ide> } <ide> <del>if (internalBinding('config').hasIntl) { <del> const icu = internalBinding('icu'); <del> // icu.getStringWidth(string, ambiguousAsFullWidth, expandEmojiSequence) <del> // Defaults: ambiguousAsFullWidth = false; expandEmojiSequence = true; <del> // TODO(BridgeAR): Expose the options to the user. That is probably the <del> // best thing possible at the moment, since it's difficult to know what <del> // the receiving end supports. <del> getStringWidth = function getStringWidth(str) { <del> let width = 0; <del> str = stripVTControlCharacters(str); <del> for (let i = 0; i < str.length; i++) { <del> // Try to avoid calling into C++ by first handling the ASCII portion of <del> // the string. If it is fully ASCII, we skip the C++ part. <del> const code = str.charCodeAt(i); <del> if (code >= 127) { <del> width += icu.getStringWidth(str.slice(i)); <del> break; <del> } <del> width += code >= 32 ? 1 : 0; <del> } <del> return width; <del> }; <del>} else { <del> /** <del> * Returns the number of columns required to display the given string. <del> */ <del> getStringWidth = function getStringWidth(str) { <del> let width = 0; <del> <del> str = stripVTControlCharacters(str); <del> <del> for (const char of str) { <del> const code = char.codePointAt(0); <del> if (isFullWidthCodePoint(code)) { <del> width += 2; <del> } else if (!isZeroWidthCodePoint(code)) { <del> width++; <del> } <del> } <del> <del> return width; <del> }; <del> <del> /** <del> * Returns true if the character represented by a given <del> * Unicode code point is full-width. Otherwise returns false. <del> */ <del> const isFullWidthCodePoint = (code) => { <del> // Code points are partially derived from: <del> // http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt <del> return code >= 0x1100 && ( <del> code <= 0x115f || // Hangul Jamo <del> code === 0x2329 || // LEFT-POINTING ANGLE BRACKET <del> code === 0x232a || // RIGHT-POINTING ANGLE BRACKET <del> // CJK Radicals Supplement .. Enclosed CJK Letters and Months <del> (code >= 0x2e80 && code <= 0x3247 && code !== 0x303f) || <del> // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A <del> (code >= 0x3250 && code <= 0x4dbf) || <del> // CJK Unified Ideographs .. Yi Radicals <del> (code >= 0x4e00 && code <= 0xa4c6) || <del> // Hangul Jamo Extended-A <del> (code >= 0xa960 && code <= 0xa97c) || <del> // Hangul Syllables <del> (code >= 0xac00 && code <= 0xd7a3) || <del> // CJK Compatibility Ideographs <del> (code >= 0xf900 && code <= 0xfaff) || <del> // Vertical Forms <del> (code >= 0xfe10 && code <= 0xfe19) || <del> // CJK Compatibility Forms .. Small Form Variants <del> (code >= 0xfe30 && code <= 0xfe6b) || <del> // Halfwidth and Fullwidth Forms <del> (code >= 0xff01 && code <= 0xff60) || <del> (code >= 0xffe0 && code <= 0xffe6) || <del> // Kana Supplement <del> (code >= 0x1b000 && code <= 0x1b001) || <del> // Enclosed Ideographic Supplement <del> (code >= 0x1f200 && code <= 0x1f251) || <del> // Miscellaneous Symbols and Pictographs .. Emoticons <del> (code >= 0x1f300 && code <= 0x1f64f) || <del> // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane <del> (code >= 0x20000 && code <= 0x3fffd) <del> ); <del> }; <del> <del> const isZeroWidthCodePoint = (code) => { <del> return code <= 0x1F || // C0 control codes <del> (code > 0x7F && code <= 0x9F) || // C1 control codes <del> (code >= 0x0300 && code <= 0x036F) || // Combining Diacritical Marks <del> (code >= 0x200B && code <= 0x200F) || // Modifying Invisible Characters <del> (code >= 0xFE00 && code <= 0xFE0F) || // Variation Selectors <del> (code >= 0xFE20 && code <= 0xFE2F) || // Combining Half Marks <del> (code >= 0xE0100 && code <= 0xE01EF); // Variation Selectors <del> }; <del>} <del> <del>/** <del> * Tries to remove all VT control characters. Use to estimate displayed <del> * string width. May be buggy due to not running a real state machine <del> */ <del>function stripVTControlCharacters(str) { <del> return str.replace(ansi, ''); <del>} <del> <ide> /* <ide> Some patterns seen in terminal key escape codes, derived from combos seen <ide> at http://www.midnight-commander.org/browser/lib/tty/key.c <ide> module.exports = { <ide> charLengthLeft, <ide> commonPrefix, <ide> emitKeys, <del> getStringWidth, <ide> kSubstringSearch, <del> stripVTControlCharacters, <ide> CSI <ide> }; <ide><path>lib/internal/repl/utils.js <ide> const { <ide> <ide> const { <ide> commonPrefix, <del> getStringWidth, <ide> kSubstringSearch, <ide> } = require('internal/readline/utils'); <ide> <del>const { inspect } = require('util'); <add>const { <add> getStringWidth, <add> inspect, <add>} = require('internal/util/inspect'); <ide> <ide> const debug = require('internal/util/debuglog').debuglog('repl'); <ide> <ide><path>lib/internal/util/inspect.js <ide> const meta = [ <ide> '\\x98', '\\x99', '\\x9A', '\\x9B', '\\x9C', '\\x9D', '\\x9E', '\\x9F', // x9F <ide> ]; <ide> <add>// Regex used for ansi escape code splitting <add>// Adopted from https://github.com/chalk/ansi-regex/blob/master/index.js <add>// License: MIT, authors: @sindresorhus, Qix-, arjunmehta and LitoMore <add>// Matches all ansi escape code sequences in a string <add>const ansiPattern = '[\\u001B\\u009B][[\\]()#;?]*' + <add> '(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' + <add> '|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'; <add>const ansi = new RegExp(ansiPattern, 'g'); <add> <add>let getStringWidth; <add> <ide> function getUserOptions(ctx) { <ide> return { <ide> stylize: ctx.stylize, <ide> function groupArrayElements(ctx, output, value) { <ide> // entries length of all output entries. We have to remove colors first, <ide> // otherwise the length would not be calculated properly. <ide> for (; i < outputLength; i++) { <del> const len = ctx.colors ? removeColors(output[i]).length : output[i].length; <add> const len = getStringWidth(output[i], ctx.colors); <ide> dataLen[i] = len; <ide> totalLength += len + separatorSpace; <ide> if (maxLength < len) <ide> function groupArrayElements(ctx, output, value) { <ide> if (columns <= 1) { <ide> return output; <ide> } <del> // TODO(BridgeAR): Add unicode support. Use the readline getStringWidth <del> // function. <ide> const tmp = []; <ide> const maxLineLength = []; <ide> for (let i = 0; i < columns; i++) { <ide> function formatProperty(ctx, value, recurseTimes, key, type, desc) { <ide> const diff = (ctx.compact !== true || type !== kObjectType) ? 2 : 3; <ide> ctx.indentationLvl += diff; <ide> str = formatValue(ctx, desc.value, recurseTimes); <del> if (diff === 3) { <del> const len = ctx.colors ? removeColors(str).length : str.length; <del> if (ctx.breakLength < len) { <del> extra = `\n${' '.repeat(ctx.indentationLvl)}`; <del> } <add> if (diff === 3 && ctx.breakLength < getStringWidth(str, ctx.colors)) { <add> extra = `\n${' '.repeat(ctx.indentationLvl)}`; <ide> } <ide> ctx.indentationLvl -= diff; <ide> } else if (desc.get !== undefined) { <ide> function formatWithOptionsInternal(inspectOptions, ...args) { <ide> return str; <ide> } <ide> <add>if (internalBinding('config').hasIntl) { <add> const icu = internalBinding('icu'); <add> // icu.getStringWidth(string, ambiguousAsFullWidth, expandEmojiSequence) <add> // Defaults: ambiguousAsFullWidth = false; expandEmojiSequence = true; <add> // TODO(BridgeAR): Expose the options to the user. That is probably the <add> // best thing possible at the moment, since it's difficult to know what <add> // the receiving end supports. <add> getStringWidth = function getStringWidth(str, removeControlChars = true) { <add> let width = 0; <add> if (removeControlChars) <add> str = stripVTControlCharacters(str); <add> for (let i = 0; i < str.length; i++) { <add> // Try to avoid calling into C++ by first handling the ASCII portion of <add> // the string. If it is fully ASCII, we skip the C++ part. <add> const code = str.charCodeAt(i); <add> if (code >= 127) { <add> width += icu.getStringWidth(str.slice(i)); <add> break; <add> } <add> width += code >= 32 ? 1 : 0; <add> } <add> return width; <add> }; <add>} else { <add> /** <add> * Returns the number of columns required to display the given string. <add> */ <add> getStringWidth = function getStringWidth(str, removeControlChars = true) { <add> let width = 0; <add> <add> if (removeControlChars) <add> str = stripVTControlCharacters(str); <add> <add> for (const char of str) { <add> const code = char.codePointAt(0); <add> if (isFullWidthCodePoint(code)) { <add> width += 2; <add> } else if (!isZeroWidthCodePoint(code)) { <add> width++; <add> } <add> } <add> <add> return width; <add> }; <add> <add> /** <add> * Returns true if the character represented by a given <add> * Unicode code point is full-width. Otherwise returns false. <add> */ <add> const isFullWidthCodePoint = (code) => { <add> // Code points are partially derived from: <add> // http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt <add> return code >= 0x1100 && ( <add> code <= 0x115f || // Hangul Jamo <add> code === 0x2329 || // LEFT-POINTING ANGLE BRACKET <add> code === 0x232a || // RIGHT-POINTING ANGLE BRACKET <add> // CJK Radicals Supplement .. Enclosed CJK Letters and Months <add> (code >= 0x2e80 && code <= 0x3247 && code !== 0x303f) || <add> // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A <add> (code >= 0x3250 && code <= 0x4dbf) || <add> // CJK Unified Ideographs .. Yi Radicals <add> (code >= 0x4e00 && code <= 0xa4c6) || <add> // Hangul Jamo Extended-A <add> (code >= 0xa960 && code <= 0xa97c) || <add> // Hangul Syllables <add> (code >= 0xac00 && code <= 0xd7a3) || <add> // CJK Compatibility Ideographs <add> (code >= 0xf900 && code <= 0xfaff) || <add> // Vertical Forms <add> (code >= 0xfe10 && code <= 0xfe19) || <add> // CJK Compatibility Forms .. Small Form Variants <add> (code >= 0xfe30 && code <= 0xfe6b) || <add> // Halfwidth and Fullwidth Forms <add> (code >= 0xff01 && code <= 0xff60) || <add> (code >= 0xffe0 && code <= 0xffe6) || <add> // Kana Supplement <add> (code >= 0x1b000 && code <= 0x1b001) || <add> // Enclosed Ideographic Supplement <add> (code >= 0x1f200 && code <= 0x1f251) || <add> // Miscellaneous Symbols and Pictographs 0x1f300 - 0x1f5ff <add> // Emoticons 0x1f600 - 0x1f64f <add> (code >= 0x1f300 && code <= 0x1f64f) || <add> // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane <add> (code >= 0x20000 && code <= 0x3fffd) <add> ); <add> }; <add> <add> const isZeroWidthCodePoint = (code) => { <add> return code <= 0x1F || // C0 control codes <add> (code > 0x7F && code <= 0x9F) || // C1 control codes <add> (code >= 0x300 && code <= 0x36F) || // Combining Diacritical Marks <add> (code >= 0x200B && code <= 0x200F) || // Modifying Invisible Characters <add> (code >= 0xFE00 && code <= 0xFE0F) || // Variation Selectors <add> (code >= 0xFE20 && code <= 0xFE2F) || // Combining Half Marks <add> (code >= 0xE0100 && code <= 0xE01EF); // Variation Selectors <add> }; <add>} <add> <add>/** <add> * Remove all VT control characters. Use to estimate displayed string width. <add> */ <add>function stripVTControlCharacters(str) { <add> return str.replace(ansi, ''); <add>} <add> <ide> module.exports = { <ide> inspect, <ide> format, <ide> formatWithOptions, <del> inspectDefaultOptions <add> getStringWidth, <add> inspectDefaultOptions, <add> stripVTControlCharacters <ide> }; <ide><path>lib/readline.js <ide> const { <ide> ERR_INVALID_OPT_VALUE <ide> } = require('internal/errors').codes; <ide> const { validateString } = require('internal/validators'); <del>const { inspect } = require('internal/util/inspect'); <add>const { <add> inspect, <add> getStringWidth, <add> stripVTControlCharacters, <add>} = require('internal/util/inspect'); <ide> const EventEmitter = require('events'); <ide> const { <ide> charLengthAt, <ide> charLengthLeft, <ide> commonPrefix, <ide> CSI, <ide> emitKeys, <del> getStringWidth, <ide> kSubstringSearch, <del> stripVTControlCharacters <ide> } = require('internal/readline/utils'); <ide> <ide> const { clearTimeout, setTimeout } = require('timers'); <ide><path>test/parallel/test-icu-stringwidth.js <ide> if (!common.hasIntl) <ide> common.skip('missing Intl'); <ide> <ide> const assert = require('assert'); <del>const readline = require('internal/readline/utils'); <add>const { getStringWidth } = require('internal/util/inspect'); <ide> <ide> // Test column width <ide> <ide> // Ll (Lowercase Letter): LATIN SMALL LETTER A <del>assert.strictEqual(readline.getStringWidth('a'), 1); <del>assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x0061)), 1); <add>assert.strictEqual(getStringWidth('a'), 1); <add>assert.strictEqual(getStringWidth(String.fromCharCode(0x0061)), 1); <ide> // Lo (Other Letter) <del>assert.strictEqual(readline.getStringWidth('丁'), 2); <del>assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x4E01)), 2); <add>assert.strictEqual(getStringWidth('丁'), 2); <add>assert.strictEqual(getStringWidth(String.fromCharCode(0x4E01)), 2); <ide> // Surrogate pairs <del>assert.strictEqual(readline.getStringWidth('\ud83d\udc78\ud83c\udfff'), 4); <del>assert.strictEqual(readline.getStringWidth('👅'), 2); <add>assert.strictEqual(getStringWidth('\ud83d\udc78\ud83c\udfff'), 4); <add>assert.strictEqual(getStringWidth('👅'), 2); <ide> // Cs (Surrogate): High Surrogate <del>assert.strictEqual(readline.getStringWidth('\ud83d'), 1); <add>assert.strictEqual(getStringWidth('\ud83d'), 1); <ide> // Cs (Surrogate): Low Surrogate <del>assert.strictEqual(readline.getStringWidth('\udc78'), 1); <add>assert.strictEqual(getStringWidth('\udc78'), 1); <ide> // Cc (Control): NULL <del>assert.strictEqual(readline.getStringWidth('\u0000'), 0); <add>assert.strictEqual(getStringWidth('\u0000'), 0); <ide> // Cc (Control): BELL <del>assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x0007)), 0); <add>assert.strictEqual(getStringWidth(String.fromCharCode(0x0007)), 0); <ide> // Cc (Control): LINE FEED <del>assert.strictEqual(readline.getStringWidth('\n'), 0); <add>assert.strictEqual(getStringWidth('\n'), 0); <ide> // Cf (Format): SOFT HYPHEN <del>assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x00AD)), 1); <add>assert.strictEqual(getStringWidth(String.fromCharCode(0x00AD)), 1); <ide> // Cf (Format): LEFT-TO-RIGHT MARK <ide> // Cf (Format): RIGHT-TO-LEFT MARK <del>assert.strictEqual(readline.getStringWidth('\u200Ef\u200F'), 1); <add>assert.strictEqual(getStringWidth('\u200Ef\u200F'), 1); <ide> // Cn (Unassigned): Not a character <del>assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x10FFEF)), 1); <add>assert.strictEqual(getStringWidth(String.fromCharCode(0x10FFEF)), 1); <ide> // Cn (Unassigned): Not a character (but in a CJK range) <del>assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x3FFEF)), 1); <add>assert.strictEqual(getStringWidth(String.fromCharCode(0x3FFEF)), 1); <ide> // Mn (Nonspacing Mark): COMBINING ACUTE ACCENT <del>assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x0301)), 0); <add>assert.strictEqual(getStringWidth(String.fromCharCode(0x0301)), 0); <ide> // Mc (Spacing Mark): BALINESE ADEG ADEG <ide> // Chosen as its Canonical_Combining_Class is not 0, but is not a 0-width <ide> // character. <del>assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x1B44)), 1); <add>assert.strictEqual(getStringWidth(String.fromCharCode(0x1B44)), 1); <ide> // Me (Enclosing Mark): COMBINING ENCLOSING CIRCLE <del>assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x20DD)), 0); <add>assert.strictEqual(getStringWidth(String.fromCharCode(0x20DD)), 0); <ide> <ide> // The following is an emoji sequence with ZWJ (zero-width-joiner). In some <ide> // implementations, it is represented as a single glyph, in other <ide> // implementations as a sequence of individual glyphs. By default, each <ide> // component will be counted individually, since not a lot of systems support <ide> // these fully. <ide> // See https://www.unicode.org/reports/tr51/tr51-16.html#Emoji_ZWJ_Sequences <del>assert.strictEqual(readline.getStringWidth('👩‍👩‍👧‍👧'), 8); <add>assert.strictEqual(getStringWidth('👩‍👩‍👧‍👧'), 8); <ide> // TODO(BridgeAR): This should have a width of two and six. The heart contains <ide> // the \uFE0F variation selector that indicates that it should be displayed as <ide> // emoji instead of as text. Emojis are all full width characters when not being <ide> // rendered as text. <ide> // https://en.wikipedia.org/wiki/Variation_Selectors_(Unicode_block) <del>assert.strictEqual(readline.getStringWidth('❤️'), 1); <del>assert.strictEqual(readline.getStringWidth('👩‍❤️‍👩'), 5); <add>assert.strictEqual(getStringWidth('❤️'), 1); <add>assert.strictEqual(getStringWidth('👩‍❤️‍👩'), 5); <ide> // The length of one is correct. It is an emoji treated as text. <del>assert.strictEqual(readline.getStringWidth('❤'), 1); <add>assert.strictEqual(getStringWidth('❤'), 1); <ide> <ide> // By default, unicode characters whose width is considered ambiguous will <ide> // be considered half-width. For these characters, getStringWidth will return <ide> // 1. In some contexts, however, it is more appropriate to consider them full <ide> // width. By default, the algorithm will assume half width. <del>assert.strictEqual(readline.getStringWidth('\u01d4'), 1); <add>assert.strictEqual(getStringWidth('\u01d4'), 1); <ide> <ide> // Control chars and combining chars are zero <del>assert.strictEqual(readline.getStringWidth('\u200E\n\u220A\u20D2'), 1); <add>assert.strictEqual(getStringWidth('\u200E\n\u220A\u20D2'), 1); <ide> <ide> // Test that the fast path for ASCII characters yields results consistent <ide> // with the 'slow' path. <ide> for (let i = 0; i < 256; i++) { <ide> const char = String.fromCharCode(i); <ide> assert.strictEqual( <del> readline.getStringWidth(char + '🎉'), <del> readline.getStringWidth(char) + 2); <add> getStringWidth(char + '🎉'), <add> getStringWidth(char) + 2); <ide> <ide> if (i < 32 || (i >= 127 && i < 160)) { // Control character <del> assert.strictEqual(readline.getStringWidth(char), 0); <add> assert.strictEqual(getStringWidth(char), 0); <ide> } else { // Regular ASCII character <del> assert.strictEqual(readline.getStringWidth(char), 1); <add> assert.strictEqual(getStringWidth(char), 1); <ide> } <ide> } <ide><path>test/parallel/test-readline-interface.js <ide> const common = require('../common'); <ide> <ide> const assert = require('assert'); <ide> const readline = require('readline'); <del>const internalReadline = require('internal/readline/utils'); <add>const { <add> getStringWidth, <add> stripVTControlCharacters <add>} = require('internal/util/inspect'); <ide> const EventEmitter = require('events').EventEmitter; <ide> const { Writable, Readable } = require('stream'); <ide> <ide> function isWarned(emitter) { <ide> } <ide> <ide> // Wide characters should be treated as two columns. <del> assert.strictEqual(internalReadline.getStringWidth('a'), 1); <del> assert.strictEqual(internalReadline.getStringWidth('あ'), 2); <del> assert.strictEqual(internalReadline.getStringWidth('谢'), 2); <del> assert.strictEqual(internalReadline.getStringWidth('고'), 2); <del> assert.strictEqual( <del> internalReadline.getStringWidth(String.fromCodePoint(0x1f251)), 2); <del> assert.strictEqual(internalReadline.getStringWidth('abcde'), 5); <del> assert.strictEqual(internalReadline.getStringWidth('古池や'), 6); <del> assert.strictEqual(internalReadline.getStringWidth('ノード.js'), 9); <del> assert.strictEqual(internalReadline.getStringWidth('你好'), 4); <del> assert.strictEqual(internalReadline.getStringWidth('안녕하세요'), 10); <del> assert.strictEqual(internalReadline.getStringWidth('A\ud83c\ude00BC'), 5); <del> assert.strictEqual(internalReadline.getStringWidth('👨‍👩‍👦‍👦'), 8); <del> assert.strictEqual(internalReadline.getStringWidth('🐕𐐷あ💻😀'), 9); <add> assert.strictEqual(getStringWidth('a'), 1); <add> assert.strictEqual(getStringWidth('あ'), 2); <add> assert.strictEqual(getStringWidth('谢'), 2); <add> assert.strictEqual(getStringWidth('고'), 2); <add> assert.strictEqual(getStringWidth(String.fromCodePoint(0x1f251)), 2); <add> assert.strictEqual(getStringWidth('abcde'), 5); <add> assert.strictEqual(getStringWidth('古池や'), 6); <add> assert.strictEqual(getStringWidth('ノード.js'), 9); <add> assert.strictEqual(getStringWidth('你好'), 4); <add> assert.strictEqual(getStringWidth('안녕하세요'), 10); <add> assert.strictEqual(getStringWidth('A\ud83c\ude00BC'), 5); <add> assert.strictEqual(getStringWidth('👨‍👩‍👦‍👦'), 8); <add> assert.strictEqual(getStringWidth('🐕𐐷あ💻😀'), 9); <ide> // TODO(BridgeAR): This should have a width of 4. <del> assert.strictEqual(internalReadline.getStringWidth('⓬⓪'), 2); <del> assert.strictEqual(internalReadline.getStringWidth('\u0301\u200D\u200E'), 0); <add> assert.strictEqual(getStringWidth('⓬⓪'), 2); <add> assert.strictEqual(getStringWidth('\u0301\u200D\u200E'), 0); <ide> <ide> // Check if vt control chars are stripped <ide> assert.strictEqual( <del> internalReadline.stripVTControlCharacters('\u001b[31m> \u001b[39m'), <add> stripVTControlCharacters('\u001b[31m> \u001b[39m'), <ide> '> ' <ide> ); <ide> assert.strictEqual( <del> internalReadline.stripVTControlCharacters('\u001b[31m> \u001b[39m> '), <add> stripVTControlCharacters('\u001b[31m> \u001b[39m> '), <ide> '> > ' <ide> ); <ide> assert.strictEqual( <del> internalReadline.stripVTControlCharacters('\u001b[31m\u001b[39m'), <add> stripVTControlCharacters('\u001b[31m\u001b[39m'), <ide> '' <ide> ); <ide> assert.strictEqual( <del> internalReadline.stripVTControlCharacters('> '), <add> stripVTControlCharacters('> '), <ide> '> ' <ide> ); <del> assert.strictEqual(internalReadline <del> .getStringWidth('\u001b[31m> \u001b[39m'), 2); <del> assert.strictEqual(internalReadline <del> .getStringWidth('\u001b[31m> \u001b[39m> '), 4); <del> assert.strictEqual(internalReadline <del> .getStringWidth('\u001b[31m\u001b[39m'), 0); <del> assert.strictEqual(internalReadline.getStringWidth('> '), 2); <add> assert.strictEqual(getStringWidth('\u001b[31m> \u001b[39m'), 2); <add> assert.strictEqual(getStringWidth('\u001b[31m> \u001b[39m> '), 4); <add> assert.strictEqual(getStringWidth('\u001b[31m\u001b[39m'), 0); <add> assert.strictEqual(getStringWidth('> '), 2); <ide> <ide> { <ide> const fi = new FakeInput(); <ide><path>test/parallel/test-readline-tab-complete.js <ide> const common = require('../common'); <ide> const readline = require('readline'); <ide> const assert = require('assert'); <ide> const EventEmitter = require('events').EventEmitter; <del>const { getStringWidth } = require('internal/readline/utils'); <add>const { getStringWidth } = require('internal/util/inspect'); <ide> <ide> // This test verifies that the tab completion supports unicode and the writes <ide> // are limited to the minimum. <ide><path>test/parallel/test-repl-history-navigation.js <ide> const tests = [ <ide> env: { NODE_REPL_HISTORY: defaultHistoryPath }, <ide> skip: !process.features.inspector, <ide> test: [ <del> // あ is a fill width character with a length of one. <add> // あ is a full width character with a length of one. <ide> // 🐕 is a full width character with a length of two. <ide> // 𐐷 is a half width character with the length of two. <ide> // '\u0301', '0x200D', '\u200E' are zero width characters. <ide><path>test/parallel/test-repl-top-level-await.js <ide> const common = require('../common'); <ide> const ArrayStream = require('../common/arraystream'); <ide> const assert = require('assert'); <del>const { stripVTControlCharacters } = require('internal/readline/utils'); <add>const { stripVTControlCharacters } = require('internal/util/inspect'); <ide> const repl = require('repl'); <ide> <ide> common.skipIfInspectorDisabled(); <ide><path>test/parallel/test-util-inspect.js <ide> assert.strictEqual( <ide> <ide> assert.strictEqual(out, expected); <ide> <add> // Unicode support. あ has a length of one and a width of two. <add> obj = [ <add> '123', '123', '123', '123', 'あああ', <add> '123', '123', '123', '123', 'あああ' <add> ]; <add> <add> out = util.inspect(obj, { compact: 3 }); <add> <add> expected = [ <add> '[', <add> " '123', '123',", <add> " '123', '123',", <add> " 'あああ', '123',", <add> " '123', '123',", <add> " '123', 'あああ'", <add> ']', <add> ].join('\n'); <add> <add> assert.strictEqual(out, expected); <add> <ide> // Verify that array grouping and line consolidation does not happen together. <ide> obj = { <ide> a: {
11
Javascript
Javascript
add currentheight constant to status bar docs
a609d1c2b78fb2493935b065afa52413313ea199
<ide><path>Examples/UIExplorer/js/StatusBarExample.js <ide> const examples = [{ <ide> render() { <ide> return ( <ide> <View> <del> <Text>Height: {StatusBar.currentHeight} pts</Text> <add> <Text>Height (Android only): {StatusBar.currentHeight} pts</Text> <ide> </View> <ide> ); <ide> }, <ide><path>Libraries/Components/StatusBar/StatusBar.js <ide> function createStackEntry(props: any): any { <ide> * to use the static API and the component for the same prop because any value <ide> * set by the static API will get overriden by the one set by the component in <ide> * the next render. <add> * <add> * ### Constants <add> * <add> * `currentHeight` (Android only) The height of the status bar. <ide> */ <ide> class StatusBar extends React.Component { <ide> props: {
2
PHP
PHP
apply fixes from styleci
6d9a3523f47f7f73553ceee93495f960846cd41a
<ide><path>src/Illuminate/Session/Middleware/StartSession.php <ide> namespace Illuminate\Session\Middleware; <ide> <ide> use Closure; <del>use Illuminate\Contracts\Cache\Factory as CacheFactory; <ide> use Illuminate\Contracts\Session\Session; <ide> use Illuminate\Http\Request; <ide> use Illuminate\Session\SessionManager;
1
Javascript
Javascript
prepare test-hash-seed for ci
f2e3a4ed8edf4675e3ec409a8430f6547660960a
<ide><path>test/pummel/test-hash-seed.js <ide> <ide> // Check that spawn child doesn't create duplicated entries <ide> require('../common'); <add>const Countdown = require('../common/countdown'); <ide> const REPETITIONS = 2; <ide> const assert = require('assert'); <ide> const fixtures = require('../common/fixtures'); <del>const { spawnSync } = require('child_process'); <add>const { spawn } = require('child_process'); <ide> const targetScript = fixtures.path('guess-hash-seed.js'); <ide> const seeds = []; <ide> <add>const requiredCallback = () => { <add> console.log(`Seeds: ${seeds}`); <add> assert.strictEqual(new Set(seeds).size, seeds.length); <add> assert.strictEqual(seeds.length, REPETITIONS); <add>}; <add> <add>const countdown = new Countdown(REPETITIONS, requiredCallback); <add> <ide> for (let i = 0; i < REPETITIONS; ++i) { <del> const seed = spawnSync(process.execPath, [targetScript], { <del> encoding: 'utf8' <del> }).stdout.trim(); <del> seeds.push(seed); <del>} <add> let result = ''; <add> const subprocess = spawn(process.execPath, [targetScript]); <add> subprocess.stdout.setEncoding('utf8'); <add> subprocess.stdout.on('data', (data) => { result += data; }); <ide> <del>console.log(`Seeds: ${seeds}`); <del>assert.strictEqual(new Set(seeds).size, seeds.length); <add> subprocess.on('exit', () => { <add> seeds.push(result.trim()); <add> countdown.dec(); <add> }); <add>}
1
Ruby
Ruby
read formula text in binmode
62e79c8d09d978f0f9106ebc7694d4fc55fc3241
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def text <ide> <ide> class FormulaText <ide> def initialize path <del> @text = path.open('r') { |f| f.read } <add> @text = path.open("rb", &:read) <ide> end <ide> <ide> def without_patch
1
Javascript
Javascript
remove the fundamental internals
4ecf11977c46966d3deedcdc71f1280a34607d1d
<ide><path>packages/react-art/src/ReactARTHostConfig.js <ide> export function clearContainer(container) { <ide> // TODO Implement this <ide> } <ide> <del>export function getFundamentalComponentInstance(fundamentalInstance) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function mountFundamentalComponent(fundamentalInstance) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function shouldUpdateFundamentalComponent(fundamentalInstance) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function updateFundamentalComponent(fundamentalInstance) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function unmountFundamentalComponent(fundamentalInstance) { <del> throw new Error('Not yet implemented.'); <del>} <del> <ide> export function getInstanceFromNode(node) { <ide> throw new Error('Not yet implemented.'); <ide> } <ide><path>packages/react-devtools-shared/src/backend/ReactSymbols.js <ide> export const FORWARD_REF_SYMBOL_STRING = 'Symbol(react.forward_ref)'; <ide> export const FRAGMENT_NUMBER = 0xeacb; <ide> export const FRAGMENT_SYMBOL_STRING = 'Symbol(react.fragment)'; <ide> <del>export const FUNDAMENTAL_NUMBER = 0xead5; <del>export const FUNDAMENTAL_SYMBOL_STRING = 'Symbol(react.fundamental)'; <del> <ide> export const LAZY_NUMBER = 0xead4; <ide> export const LAZY_SYMBOL_STRING = 'Symbol(react.lazy)'; <ide> <ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js <ide> import type { <ide> } from 'react-reconciler/src/ReactTestSelectors'; <ide> import type {RootType} from './ReactDOMRoot'; <ide> import type {ReactScopeInstance} from 'shared/ReactTypes'; <del>import type {ReactDOMFundamentalComponentInstance} from '../shared/ReactDOMTypes'; <ide> <ide> import { <ide> precacheFiberNode, <ide> import {retryIfBlockedOn} from '../events/ReactDOMEventReplaying'; <ide> <ide> import { <ide> enableSuspenseServerRenderer, <del> enableFundamentalAPI, <ide> enableCreateEventHandleAPI, <ide> enableScopeAPI, <ide> } from 'shared/ReactFeatureFlags'; <ide> export function didNotFindHydratableSuspenseInstance( <ide> } <ide> } <ide> <del>export function getFundamentalComponentInstance( <del> fundamentalInstance: ReactDOMFundamentalComponentInstance, <del>): Instance { <del> if (enableFundamentalAPI) { <del> const {currentFiber, impl, props, state} = fundamentalInstance; <del> const instance = impl.getInstance(null, props, state); <del> precacheFiberNode(currentFiber, instance); <del> return instance; <del> } <del> // Because of the flag above, this gets around the Flow error; <del> return (null: any); <del>} <del> <del>export function mountFundamentalComponent( <del> fundamentalInstance: ReactDOMFundamentalComponentInstance, <del>): void { <del> if (enableFundamentalAPI) { <del> const {impl, instance, props, state} = fundamentalInstance; <del> const onMount = impl.onMount; <del> if (onMount !== undefined) { <del> onMount(null, instance, props, state); <del> } <del> } <del>} <del> <del>export function shouldUpdateFundamentalComponent( <del> fundamentalInstance: ReactDOMFundamentalComponentInstance, <del>): boolean { <del> if (enableFundamentalAPI) { <del> const {impl, prevProps, props, state} = fundamentalInstance; <del> const shouldUpdate = impl.shouldUpdate; <del> if (shouldUpdate !== undefined) { <del> return shouldUpdate(null, prevProps, props, state); <del> } <del> } <del> return true; <del>} <del> <del>export function updateFundamentalComponent( <del> fundamentalInstance: ReactDOMFundamentalComponentInstance, <del>): void { <del> if (enableFundamentalAPI) { <del> const {impl, instance, prevProps, props, state} = fundamentalInstance; <del> const onUpdate = impl.onUpdate; <del> if (onUpdate !== undefined) { <del> onUpdate(null, instance, prevProps, props, state); <del> } <del> } <del>} <del> <del>export function unmountFundamentalComponent( <del> fundamentalInstance: ReactDOMFundamentalComponentInstance, <del>): void { <del> if (enableFundamentalAPI) { <del> const {impl, instance, props, state} = fundamentalInstance; <del> const onUnmount = impl.onUnmount; <del> if (onUnmount !== undefined) { <del> onUnmount(null, instance, props, state); <del> } <del> } <del>} <del> <ide> export function getInstanceFromNode(node: HTMLElement): null | Object { <ide> return getClosestInstanceFromNode(node) || null; <ide> } <ide><path>packages/react-dom/src/server/ReactPartialRenderer.js <ide> import { <ide> disableLegacyContext, <ide> disableModulePatternComponents, <ide> enableSuspenseServerRenderer, <del> enableFundamentalAPI, <ide> enableScopeAPI, <ide> } from 'shared/ReactFeatureFlags'; <ide> <ide> import { <ide> REACT_CONTEXT_TYPE, <ide> REACT_LAZY_TYPE, <ide> REACT_MEMO_TYPE, <del> REACT_FUNDAMENTAL_TYPE, <ide> REACT_SCOPE_TYPE, <ide> REACT_LEGACY_HIDDEN_TYPE, <ide> } from 'shared/ReactSymbols'; <ide> class ReactDOMServerRenderer { <ide> return ''; <ide> } <ide> // eslint-disable-next-line-no-fallthrough <del> case REACT_FUNDAMENTAL_TYPE: { <del> if (enableFundamentalAPI) { <del> const fundamentalImpl = elementType.impl; <del> const open = fundamentalImpl.getServerSideString( <del> null, <del> nextElement.props, <del> ); <del> const getServerSideStringClose = <del> fundamentalImpl.getServerSideStringClose; <del> const close = <del> getServerSideStringClose !== undefined <del> ? getServerSideStringClose(null, nextElement.props) <del> : ''; <del> const nextChildren = <del> fundamentalImpl.reconcileChildren !== false <del> ? toArray(((nextChild: any): ReactElement).props.children) <del> : []; <del> const frame: Frame = { <del> type: null, <del> domNamespace: parentNamespace, <del> children: nextChildren, <del> childIndex: 0, <del> context: context, <del> footer: close, <del> }; <del> if (__DEV__) { <del> ((frame: any): FrameDev).debugElementStack = []; <del> } <del> this.stack.push(frame); <del> return open; <del> } <del> invariant( <del> false, <del> 'ReactDOMServer does not yet support the fundamental API.', <del> ); <del> } <del> // eslint-disable-next-line-no-fallthrough <ide> case REACT_LAZY_TYPE: { <ide> const element: ReactElement = (nextChild: any); <ide> const lazyComponent: LazyComponent<any, any> = (nextChild: any) <ide><path>packages/react-dom/src/shared/ReactDOMTypes.js <ide> * @flow <ide> */ <ide> <del>import type { <del> ReactFundamentalComponentInstance, <del> ReactScopeInstance, <del>} from 'shared/ReactTypes'; <add>import type {ReactScopeInstance} from 'shared/ReactTypes'; <ide> import type {DOMEventName} from '../events/DOMEventNames'; <ide> <del>export type ReactDOMFundamentalComponentInstance = ReactFundamentalComponentInstance< <del> any, <del> any, <del>>; <del> <ide> export type ReactDOMEventHandle = ( <ide> target: EventTarget | ReactScopeInstance, <ide> callback: (SyntheticEvent<EventTarget>) => void, <ide><path>packages/react-native-renderer/src/ReactFabricHostConfig.js <ide> export function replaceContainerChildren( <ide> newChildren: ChildSet, <ide> ): void {} <ide> <del>export function getFundamentalComponentInstance(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function mountFundamentalComponent(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function shouldUpdateFundamentalComponent(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function updateFundamentalComponent(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function unmountFundamentalComponent(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function cloneFundamentalInstance(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <ide> export function getInstanceFromNode(node: any) { <ide> throw new Error('Not yet implemented.'); <ide> } <ide><path>packages/react-native-renderer/src/ReactNativeHostConfig.js <ide> export function unhideTextInstance( <ide> throw new Error('Not yet implemented.'); <ide> } <ide> <del>export function getFundamentalComponentInstance(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function mountFundamentalComponent(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function shouldUpdateFundamentalComponent(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function updateFundamentalComponent(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <del>export function unmountFundamentalComponent(fundamentalInstance: any) { <del> throw new Error('Not yet implemented.'); <del>} <del> <ide> export function getInstanceFromNode(node: any) { <ide> throw new Error('Not yet implemented.'); <ide> } <ide><path>packages/react-noop-renderer/src/createReactNoop.js <ide> function createReactNoop(reconciler: Function, useMutation: boolean) { <ide> warnsIfNotActing: true, <ide> supportsHydration: false, <ide> <del> getFundamentalComponentInstance(fundamentalInstance): Instance { <del> const {impl, props, state} = fundamentalInstance; <del> return impl.getInstance(null, props, state); <del> }, <del> <del> mountFundamentalComponent(fundamentalInstance): void { <del> const {impl, instance, props, state} = fundamentalInstance; <del> const onMount = impl.onUpdate; <del> if (onMount !== undefined) { <del> onMount(null, instance, props, state); <del> } <del> }, <del> <del> shouldUpdateFundamentalComponent(fundamentalInstance): boolean { <del> const {impl, instance, prevProps, props, state} = fundamentalInstance; <del> const shouldUpdate = impl.shouldUpdate; <del> if (shouldUpdate !== undefined) { <del> return shouldUpdate(null, instance, prevProps, props, state); <del> } <del> return true; <del> }, <del> <del> updateFundamentalComponent(fundamentalInstance): void { <del> const {impl, instance, prevProps, props, state} = fundamentalInstance; <del> const onUpdate = impl.onUpdate; <del> if (onUpdate !== undefined) { <del> onUpdate(null, instance, prevProps, props, state); <del> } <del> }, <del> <del> unmountFundamentalComponent(fundamentalInstance): void { <del> const {impl, instance, props, state} = fundamentalInstance; <del> const onUnmount = impl.onUnmount; <del> if (onUnmount !== undefined) { <del> onUnmount(null, instance, props, state); <del> } <del> }, <del> <del> cloneFundamentalInstance(fundamentalInstance): Instance { <del> const instance = fundamentalInstance.instance; <del> return { <del> children: [], <del> text: instance.text, <del> type: instance.type, <del> prop: instance.prop, <del> id: instance.id, <del> context: instance.context, <del> hidden: instance.hidden, <del> }; <del> }, <del> <ide> getInstanceFromNode() { <ide> throw new Error('Not yet implemented.'); <ide> }, <ide><path>packages/react-reconciler/src/ReactFiber.new.js <ide> */ <ide> <ide> import type {ReactElement} from 'shared/ReactElementType'; <del>import type { <del> ReactFragment, <del> ReactPortal, <del> ReactFundamentalComponent, <del> ReactScope, <del>} from 'shared/ReactTypes'; <add>import type {ReactFragment, ReactPortal, ReactScope} from 'shared/ReactTypes'; <ide> import type {Fiber} from './ReactInternalTypes'; <ide> import type {RootTag} from './ReactRootTags'; <ide> import type {WorkTag} from './ReactWorkTags'; <ide> import type {OffscreenProps} from './ReactFiberOffscreenComponent'; <ide> import invariant from 'shared/invariant'; <ide> import { <ide> enableProfilerTimer, <del> enableFundamentalAPI, <ide> enableScopeAPI, <ide> enableCache, <ide> } from 'shared/ReactFeatureFlags'; <ide> import { <ide> MemoComponent, <ide> SimpleMemoComponent, <ide> LazyComponent, <del> FundamentalComponent, <ide> ScopeComponent, <ide> OffscreenComponent, <ide> LegacyHiddenComponent, <ide> import { <ide> REACT_SUSPENSE_LIST_TYPE, <ide> REACT_MEMO_TYPE, <ide> REACT_LAZY_TYPE, <del> REACT_FUNDAMENTAL_TYPE, <ide> REACT_SCOPE_TYPE, <ide> REACT_OFFSCREEN_TYPE, <ide> REACT_LEGACY_HIDDEN_TYPE, <ide> export function createFiberFromTypeAndProps( <ide> fiberTag = LazyComponent; <ide> resolvedType = null; <ide> break getTag; <del> case REACT_FUNDAMENTAL_TYPE: <del> if (enableFundamentalAPI) { <del> return createFiberFromFundamental( <del> type, <del> pendingProps, <del> mode, <del> lanes, <del> key, <del> ); <del> } <del> break; <ide> } <ide> } <ide> let info = ''; <ide> export function createFiberFromFragment( <ide> return fiber; <ide> } <ide> <del>export function createFiberFromFundamental( <del> fundamentalComponent: ReactFundamentalComponent<any, any>, <del> pendingProps: any, <del> mode: TypeOfMode, <del> lanes: Lanes, <del> key: null | string, <del>): Fiber { <del> const fiber = createFiber(FundamentalComponent, pendingProps, key, mode); <del> fiber.elementType = fundamentalComponent; <del> fiber.type = fundamentalComponent; <del> fiber.lanes = lanes; <del> return fiber; <del>} <del> <ide> function createFiberFromScope( <ide> scope: ReactScope, <ide> pendingProps: any, <ide><path>packages/react-reconciler/src/ReactFiber.old.js <ide> */ <ide> <ide> import type {ReactElement} from 'shared/ReactElementType'; <del>import type { <del> ReactFragment, <del> ReactPortal, <del> ReactFundamentalComponent, <del> ReactScope, <del>} from 'shared/ReactTypes'; <add>import type {ReactFragment, ReactPortal, ReactScope} from 'shared/ReactTypes'; <ide> import type {Fiber} from './ReactInternalTypes'; <ide> import type {RootTag} from './ReactRootTags'; <ide> import type {WorkTag} from './ReactWorkTags'; <ide> import type {OffscreenProps} from './ReactFiberOffscreenComponent'; <ide> import invariant from 'shared/invariant'; <ide> import { <ide> enableProfilerTimer, <del> enableFundamentalAPI, <ide> enableScopeAPI, <ide> enableCache, <ide> } from 'shared/ReactFeatureFlags'; <ide> import { <ide> MemoComponent, <ide> SimpleMemoComponent, <ide> LazyComponent, <del> FundamentalComponent, <ide> ScopeComponent, <ide> OffscreenComponent, <ide> LegacyHiddenComponent, <ide> import { <ide> REACT_SUSPENSE_LIST_TYPE, <ide> REACT_MEMO_TYPE, <ide> REACT_LAZY_TYPE, <del> REACT_FUNDAMENTAL_TYPE, <ide> REACT_SCOPE_TYPE, <ide> REACT_OFFSCREEN_TYPE, <ide> REACT_LEGACY_HIDDEN_TYPE, <ide> export function createFiberFromTypeAndProps( <ide> fiberTag = LazyComponent; <ide> resolvedType = null; <ide> break getTag; <del> case REACT_FUNDAMENTAL_TYPE: <del> if (enableFundamentalAPI) { <del> return createFiberFromFundamental( <del> type, <del> pendingProps, <del> mode, <del> lanes, <del> key, <del> ); <del> } <del> break; <ide> } <ide> } <ide> let info = ''; <ide> export function createFiberFromFragment( <ide> return fiber; <ide> } <ide> <del>export function createFiberFromFundamental( <del> fundamentalComponent: ReactFundamentalComponent<any, any>, <del> pendingProps: any, <del> mode: TypeOfMode, <del> lanes: Lanes, <del> key: null | string, <del>): Fiber { <del> const fiber = createFiber(FundamentalComponent, pendingProps, key, mode); <del> fiber.elementType = fundamentalComponent; <del> fiber.type = fundamentalComponent; <del> fiber.lanes = lanes; <del> return fiber; <del>} <del> <ide> function createFiberFromScope( <ide> scope: ReactScope, <ide> pendingProps: any, <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.new.js <ide> import { <ide> SimpleMemoComponent, <ide> LazyComponent, <ide> IncompleteClassComponent, <del> FundamentalComponent, <ide> ScopeComponent, <ide> OffscreenComponent, <ide> LegacyHiddenComponent, <ide> import { <ide> enableProfilerTimer, <ide> enableSchedulerTracing, <ide> enableSuspenseServerRenderer, <del> enableFundamentalAPI, <ide> warnAboutDefaultPropsOnFunctionComponents, <ide> enableScopeAPI, <ide> enableCache, <ide> function updateContextConsumer( <ide> return workInProgress.child; <ide> } <ide> <del>function updateFundamentalComponent(current, workInProgress, renderLanes) { <del> const fundamentalImpl = workInProgress.type.impl; <del> if (fundamentalImpl.reconcileChildren === false) { <del> return null; <del> } <del> const nextProps = workInProgress.pendingProps; <del> const nextChildren = nextProps.children; <del> <del> reconcileChildren(current, workInProgress, nextChildren, renderLanes); <del> return workInProgress.child; <del>} <del> <ide> function updateScopeComponent(current, workInProgress, renderLanes) { <ide> const nextProps = workInProgress.pendingProps; <ide> const nextChildren = nextProps.children; <ide> function beginWork( <ide> case SuspenseListComponent: { <ide> return updateSuspenseListComponent(current, workInProgress, renderLanes); <ide> } <del> case FundamentalComponent: { <del> if (enableFundamentalAPI) { <del> return updateFundamentalComponent(current, workInProgress, renderLanes); <del> } <del> break; <del> } <ide> case ScopeComponent: { <ide> if (enableScopeAPI) { <ide> return updateScopeComponent(current, workInProgress, renderLanes); <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.old.js <ide> import { <ide> SimpleMemoComponent, <ide> LazyComponent, <ide> IncompleteClassComponent, <del> FundamentalComponent, <ide> ScopeComponent, <ide> OffscreenComponent, <ide> LegacyHiddenComponent, <ide> import { <ide> enableProfilerTimer, <ide> enableSchedulerTracing, <ide> enableSuspenseServerRenderer, <del> enableFundamentalAPI, <ide> warnAboutDefaultPropsOnFunctionComponents, <ide> enableScopeAPI, <ide> enableCache, <ide> function updateContextConsumer( <ide> return workInProgress.child; <ide> } <ide> <del>function updateFundamentalComponent(current, workInProgress, renderLanes) { <del> const fundamentalImpl = workInProgress.type.impl; <del> if (fundamentalImpl.reconcileChildren === false) { <del> return null; <del> } <del> const nextProps = workInProgress.pendingProps; <del> const nextChildren = nextProps.children; <del> <del> reconcileChildren(current, workInProgress, nextChildren, renderLanes); <del> return workInProgress.child; <del>} <del> <ide> function updateScopeComponent(current, workInProgress, renderLanes) { <ide> const nextProps = workInProgress.pendingProps; <ide> const nextChildren = nextProps.children; <ide> function beginWork( <ide> case SuspenseListComponent: { <ide> return updateSuspenseListComponent(current, workInProgress, renderLanes); <ide> } <del> case FundamentalComponent: { <del> if (enableFundamentalAPI) { <del> return updateFundamentalComponent(current, workInProgress, renderLanes); <del> } <del> break; <del> } <ide> case ScopeComponent: { <ide> if (enableScopeAPI) { <ide> return updateScopeComponent(current, workInProgress, renderLanes); <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js <ide> import { <ide> enableProfilerCommitHooks, <ide> enableProfilerNestedUpdatePhase, <ide> enableSuspenseServerRenderer, <del> enableFundamentalAPI, <ide> enableSuspenseCallback, <ide> enableScopeAPI, <ide> enableDoubleInvokingEffects, <ide> import { <ide> MemoComponent, <ide> SimpleMemoComponent, <ide> SuspenseListComponent, <del> FundamentalComponent, <ide> ScopeComponent, <ide> OffscreenComponent, <ide> LegacyHiddenComponent, <ide> import { <ide> hideTextInstance, <ide> unhideInstance, <ide> unhideTextInstance, <del> unmountFundamentalComponent, <del> updateFundamentalComponent, <ide> commitHydratedContainer, <ide> commitHydratedSuspenseInstance, <ide> clearContainer, <ide> function commitLayoutEffectOnFiber( <ide> } <ide> case SuspenseListComponent: <ide> case IncompleteClassComponent: <del> case FundamentalComponent: <ide> case ScopeComponent: <ide> case OffscreenComponent: <ide> case LegacyHiddenComponent: <ide> function commitUnmount( <ide> } <ide> return; <ide> } <del> case FundamentalComponent: { <del> if (enableFundamentalAPI) { <del> const fundamentalInstance = current.stateNode; <del> if (fundamentalInstance !== null) { <del> unmountFundamentalComponent(fundamentalInstance); <del> current.stateNode = null; <del> } <del> } <del> return; <del> } <ide> case DehydratedFragment: { <ide> if (enableSuspenseCallback) { <ide> const hydrationCallbacks = finishedRoot.hydrationCallbacks; <ide> function commitContainer(finishedWork: Fiber) { <ide> switch (finishedWork.tag) { <ide> case ClassComponent: <ide> case HostComponent: <del> case HostText: <del> case FundamentalComponent: { <add> case HostText: { <ide> return; <ide> } <ide> case HostRoot: <ide> function commitPlacement(finishedWork: Fiber): void { <ide> parent = parentStateNode.containerInfo; <ide> isContainer = true; <ide> break; <del> case FundamentalComponent: <del> if (enableFundamentalAPI) { <del> parent = parentStateNode.instance; <del> isContainer = false; <del> } <ide> // eslint-disable-next-line-no-fallthrough <ide> default: <ide> invariant( <ide> function insertOrAppendPlacementNodeIntoContainer( <ide> ): void { <ide> const {tag} = node; <ide> const isHost = tag === HostComponent || tag === HostText; <del> if (isHost || (enableFundamentalAPI && tag === FundamentalComponent)) { <add> if (isHost) { <ide> const stateNode = isHost ? node.stateNode : node.stateNode.instance; <ide> if (before) { <ide> insertInContainerBefore(parent, stateNode, before); <ide> function insertOrAppendPlacementNode( <ide> ): void { <ide> const {tag} = node; <ide> const isHost = tag === HostComponent || tag === HostText; <del> if (isHost || (enableFundamentalAPI && tag === FundamentalComponent)) { <add> if (isHost) { <ide> const stateNode = isHost ? node.stateNode : node.stateNode.instance; <ide> if (before) { <ide> insertBefore(parent, stateNode, before); <ide> function unmountHostComponents( <ide> currentParent = parentStateNode.containerInfo; <ide> currentParentIsContainer = true; <ide> break findParent; <del> case FundamentalComponent: <del> if (enableFundamentalAPI) { <del> currentParent = parentStateNode.instance; <del> currentParentIsContainer = false; <del> } <ide> } <ide> parent = parent.return; <ide> } <ide> function unmountHostComponents( <ide> ); <ide> } <ide> // Don't visit children because we already visited them. <del> } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { <del> const fundamentalNode = node.stateNode.instance; <del> commitNestedUnmounts( <del> finishedRoot, <del> node, <del> nearestMountedAncestor, <del> renderPriorityLevel, <del> ); <del> // After all the children have unmounted, it is now safe to remove the <del> // node from the tree. <del> if (currentParentIsContainer) { <del> removeChildFromContainer( <del> ((currentParent: any): Container), <del> (fundamentalNode: Instance), <del> ); <del> } else { <del> removeChild( <del> ((currentParent: any): Instance), <del> (fundamentalNode: Instance), <del> ); <del> } <ide> } else if ( <ide> enableSuspenseServerRenderer && <ide> node.tag === DehydratedFragment <ide> function commitWork(current: Fiber | null, finishedWork: Fiber): void { <ide> case IncompleteClassComponent: { <ide> return; <ide> } <del> case FundamentalComponent: { <del> if (enableFundamentalAPI) { <del> const fundamentalInstance = finishedWork.stateNode; <del> updateFundamentalComponent(fundamentalInstance); <del> return; <del> } <del> break; <del> } <ide> case ScopeComponent: { <ide> if (enableScopeAPI) { <ide> const scopeInstance = finishedWork.stateNode; <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js <ide> import { <ide> enableProfilerCommitHooks, <ide> enableProfilerNestedUpdatePhase, <ide> enableSuspenseServerRenderer, <del> enableFundamentalAPI, <ide> enableSuspenseCallback, <ide> enableScopeAPI, <ide> enableDoubleInvokingEffects, <ide> import { <ide> MemoComponent, <ide> SimpleMemoComponent, <ide> SuspenseListComponent, <del> FundamentalComponent, <ide> ScopeComponent, <ide> OffscreenComponent, <ide> LegacyHiddenComponent, <ide> import { <ide> hideTextInstance, <ide> unhideInstance, <ide> unhideTextInstance, <del> unmountFundamentalComponent, <del> updateFundamentalComponent, <ide> commitHydratedContainer, <ide> commitHydratedSuspenseInstance, <ide> clearContainer, <ide> function commitLayoutEffectOnFiber( <ide> } <ide> case SuspenseListComponent: <ide> case IncompleteClassComponent: <del> case FundamentalComponent: <ide> case ScopeComponent: <ide> case OffscreenComponent: <ide> case LegacyHiddenComponent: <ide> function commitUnmount( <ide> } <ide> return; <ide> } <del> case FundamentalComponent: { <del> if (enableFundamentalAPI) { <del> const fundamentalInstance = current.stateNode; <del> if (fundamentalInstance !== null) { <del> unmountFundamentalComponent(fundamentalInstance); <del> current.stateNode = null; <del> } <del> } <del> return; <del> } <ide> case DehydratedFragment: { <ide> if (enableSuspenseCallback) { <ide> const hydrationCallbacks = finishedRoot.hydrationCallbacks; <ide> function commitContainer(finishedWork: Fiber) { <ide> switch (finishedWork.tag) { <ide> case ClassComponent: <ide> case HostComponent: <del> case HostText: <del> case FundamentalComponent: { <add> case HostText: { <ide> return; <ide> } <ide> case HostRoot: <ide> function commitPlacement(finishedWork: Fiber): void { <ide> parent = parentStateNode.containerInfo; <ide> isContainer = true; <ide> break; <del> case FundamentalComponent: <del> if (enableFundamentalAPI) { <del> parent = parentStateNode.instance; <del> isContainer = false; <del> } <ide> // eslint-disable-next-line-no-fallthrough <ide> default: <ide> invariant( <ide> function insertOrAppendPlacementNodeIntoContainer( <ide> ): void { <ide> const {tag} = node; <ide> const isHost = tag === HostComponent || tag === HostText; <del> if (isHost || (enableFundamentalAPI && tag === FundamentalComponent)) { <add> if (isHost) { <ide> const stateNode = isHost ? node.stateNode : node.stateNode.instance; <ide> if (before) { <ide> insertInContainerBefore(parent, stateNode, before); <ide> function insertOrAppendPlacementNode( <ide> ): void { <ide> const {tag} = node; <ide> const isHost = tag === HostComponent || tag === HostText; <del> if (isHost || (enableFundamentalAPI && tag === FundamentalComponent)) { <add> if (isHost) { <ide> const stateNode = isHost ? node.stateNode : node.stateNode.instance; <ide> if (before) { <ide> insertBefore(parent, stateNode, before); <ide> function unmountHostComponents( <ide> currentParent = parentStateNode.containerInfo; <ide> currentParentIsContainer = true; <ide> break findParent; <del> case FundamentalComponent: <del> if (enableFundamentalAPI) { <del> currentParent = parentStateNode.instance; <del> currentParentIsContainer = false; <del> } <ide> } <ide> parent = parent.return; <ide> } <ide> function unmountHostComponents( <ide> ); <ide> } <ide> // Don't visit children because we already visited them. <del> } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { <del> const fundamentalNode = node.stateNode.instance; <del> commitNestedUnmounts( <del> finishedRoot, <del> node, <del> nearestMountedAncestor, <del> renderPriorityLevel, <del> ); <del> // After all the children have unmounted, it is now safe to remove the <del> // node from the tree. <del> if (currentParentIsContainer) { <del> removeChildFromContainer( <del> ((currentParent: any): Container), <del> (fundamentalNode: Instance), <del> ); <del> } else { <del> removeChild( <del> ((currentParent: any): Instance), <del> (fundamentalNode: Instance), <del> ); <del> } <ide> } else if ( <ide> enableSuspenseServerRenderer && <ide> node.tag === DehydratedFragment <ide> function commitWork(current: Fiber | null, finishedWork: Fiber): void { <ide> case IncompleteClassComponent: { <ide> return; <ide> } <del> case FundamentalComponent: { <del> if (enableFundamentalAPI) { <del> const fundamentalInstance = finishedWork.stateNode; <del> updateFundamentalComponent(fundamentalInstance); <del> return; <del> } <del> break; <del> } <ide> case ScopeComponent: { <ide> if (enableScopeAPI) { <ide> const scopeInstance = finishedWork.stateNode; <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.new.js <ide> <ide> import type {Fiber} from './ReactInternalTypes'; <ide> import type {Lanes, Lane} from './ReactFiberLane.new'; <del>import type { <del> ReactFundamentalComponentInstance, <del> ReactScopeInstance, <del> ReactContext, <del>} from 'shared/ReactTypes'; <add>import type {ReactScopeInstance, ReactContext} from 'shared/ReactTypes'; <ide> import type {FiberRoot} from './ReactInternalTypes'; <ide> import type { <ide> Instance, <ide> import { <ide> SimpleMemoComponent, <ide> LazyComponent, <ide> IncompleteClassComponent, <del> FundamentalComponent, <ide> ScopeComponent, <ide> OffscreenComponent, <ide> LegacyHiddenComponent, <ide> import { <ide> createContainerChildSet, <ide> appendChildToContainerChildSet, <ide> finalizeContainerChildren, <del> getFundamentalComponentInstance, <del> mountFundamentalComponent, <del> cloneFundamentalInstance, <del> shouldUpdateFundamentalComponent, <ide> preparePortalMount, <ide> prepareScopeUpdate, <ide> } from './ReactFiberHostConfig'; <ide> import { <ide> enableSchedulerTracing, <ide> enableSuspenseCallback, <ide> enableSuspenseServerRenderer, <del> enableFundamentalAPI, <ide> enableScopeAPI, <ide> enableProfilerTimer, <ide> enableCache, <ide> import { <ide> getRenderTargetTime, <ide> subtreeRenderLanes, <ide> } from './ReactFiberWorkLoop.new'; <del>import {createFundamentalStateInstance} from './ReactFiberFundamental.new'; <ide> import { <ide> OffscreenLane, <ide> SomeRetryLane, <ide> if (supportsMutation) { <ide> while (node !== null) { <ide> if (node.tag === HostComponent || node.tag === HostText) { <ide> appendInitialChild(parent, node.stateNode); <del> } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { <del> appendInitialChild(parent, node.stateNode.instance); <ide> } else if (node.tag === HostPortal) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> if (supportsMutation) { <ide> instance = cloneHiddenTextInstance(instance, text, node); <ide> } <ide> appendInitialChild(parent, instance); <del> } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { <del> let instance = node.stateNode.instance; <del> if (needsVisibilityToggle && isHidden) { <del> // This child is inside a timed out tree. Hide it. <del> const props = node.memoizedProps; <del> const type = node.type; <del> instance = cloneHiddenInstance(instance, type, props, node); <del> } <del> appendInitialChild(parent, instance); <ide> } else if (node.tag === HostPortal) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> if (supportsMutation) { <ide> instance = cloneHiddenTextInstance(instance, text, node); <ide> } <ide> appendChildToContainerChildSet(containerChildSet, instance); <del> } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { <del> let instance = node.stateNode.instance; <del> if (needsVisibilityToggle && isHidden) { <del> // This child is inside a timed out tree. Hide it. <del> const props = node.memoizedProps; <del> const type = node.type; <del> instance = cloneHiddenInstance(instance, type, props, node); <del> } <del> appendChildToContainerChildSet(containerChildSet, instance); <ide> } else if (node.tag === HostPortal) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> function completeWork( <ide> bubbleProperties(workInProgress); <ide> return null; <ide> } <del> case FundamentalComponent: { <del> if (enableFundamentalAPI) { <del> const fundamentalImpl = workInProgress.type.impl; <del> let fundamentalInstance: ReactFundamentalComponentInstance< <del> any, <del> any, <del> > | null = workInProgress.stateNode; <del> <del> if (fundamentalInstance === null) { <del> const getInitialState = fundamentalImpl.getInitialState; <del> let fundamentalState; <del> if (getInitialState !== undefined) { <del> fundamentalState = getInitialState(newProps); <del> } <del> fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance( <del> workInProgress, <del> newProps, <del> fundamentalImpl, <del> fundamentalState || {}, <del> ); <del> const instance = ((getFundamentalComponentInstance( <del> fundamentalInstance, <del> ): any): Instance); <del> fundamentalInstance.instance = instance; <del> if (fundamentalImpl.reconcileChildren === false) { <del> bubbleProperties(workInProgress); <del> return null; <del> } <del> appendAllChildren(instance, workInProgress, false, false); <del> mountFundamentalComponent(fundamentalInstance); <del> } else { <del> // We fire update in commit phase <del> const prevProps = fundamentalInstance.props; <del> fundamentalInstance.prevProps = prevProps; <del> fundamentalInstance.props = newProps; <del> fundamentalInstance.currentFiber = workInProgress; <del> if (supportsPersistence) { <del> const instance = cloneFundamentalInstance(fundamentalInstance); <del> fundamentalInstance.instance = instance; <del> appendAllChildren(instance, workInProgress, false, false); <del> } <del> const shouldUpdate = shouldUpdateFundamentalComponent( <del> fundamentalInstance, <del> ); <del> if (shouldUpdate) { <del> markUpdate(workInProgress); <del> } <del> } <del> bubbleProperties(workInProgress); <del> return null; <del> } <del> break; <del> } <ide> case ScopeComponent: { <ide> if (enableScopeAPI) { <ide> if (current === null) { <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.old.js <ide> <ide> import type {Fiber} from './ReactInternalTypes'; <ide> import type {Lanes, Lane} from './ReactFiberLane.old'; <del>import type { <del> ReactFundamentalComponentInstance, <del> ReactScopeInstance, <del> ReactContext, <del>} from 'shared/ReactTypes'; <add>import type {ReactScopeInstance, ReactContext} from 'shared/ReactTypes'; <ide> import type {FiberRoot} from './ReactInternalTypes'; <ide> import type { <ide> Instance, <ide> import { <ide> SimpleMemoComponent, <ide> LazyComponent, <ide> IncompleteClassComponent, <del> FundamentalComponent, <ide> ScopeComponent, <ide> OffscreenComponent, <ide> LegacyHiddenComponent, <ide> import { <ide> createContainerChildSet, <ide> appendChildToContainerChildSet, <ide> finalizeContainerChildren, <del> getFundamentalComponentInstance, <del> mountFundamentalComponent, <del> cloneFundamentalInstance, <del> shouldUpdateFundamentalComponent, <ide> preparePortalMount, <ide> prepareScopeUpdate, <ide> } from './ReactFiberHostConfig'; <ide> import { <ide> enableSchedulerTracing, <ide> enableSuspenseCallback, <ide> enableSuspenseServerRenderer, <del> enableFundamentalAPI, <ide> enableScopeAPI, <ide> enableProfilerTimer, <ide> enableCache, <ide> import { <ide> getRenderTargetTime, <ide> subtreeRenderLanes, <ide> } from './ReactFiberWorkLoop.old'; <del>import {createFundamentalStateInstance} from './ReactFiberFundamental.old'; <ide> import { <ide> OffscreenLane, <ide> SomeRetryLane, <ide> if (supportsMutation) { <ide> while (node !== null) { <ide> if (node.tag === HostComponent || node.tag === HostText) { <ide> appendInitialChild(parent, node.stateNode); <del> } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { <del> appendInitialChild(parent, node.stateNode.instance); <ide> } else if (node.tag === HostPortal) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> if (supportsMutation) { <ide> instance = cloneHiddenTextInstance(instance, text, node); <ide> } <ide> appendInitialChild(parent, instance); <del> } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { <del> let instance = node.stateNode.instance; <del> if (needsVisibilityToggle && isHidden) { <del> // This child is inside a timed out tree. Hide it. <del> const props = node.memoizedProps; <del> const type = node.type; <del> instance = cloneHiddenInstance(instance, type, props, node); <del> } <del> appendInitialChild(parent, instance); <ide> } else if (node.tag === HostPortal) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> if (supportsMutation) { <ide> instance = cloneHiddenTextInstance(instance, text, node); <ide> } <ide> appendChildToContainerChildSet(containerChildSet, instance); <del> } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { <del> let instance = node.stateNode.instance; <del> if (needsVisibilityToggle && isHidden) { <del> // This child is inside a timed out tree. Hide it. <del> const props = node.memoizedProps; <del> const type = node.type; <del> instance = cloneHiddenInstance(instance, type, props, node); <del> } <del> appendChildToContainerChildSet(containerChildSet, instance); <ide> } else if (node.tag === HostPortal) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> function completeWork( <ide> bubbleProperties(workInProgress); <ide> return null; <ide> } <del> case FundamentalComponent: { <del> if (enableFundamentalAPI) { <del> const fundamentalImpl = workInProgress.type.impl; <del> let fundamentalInstance: ReactFundamentalComponentInstance< <del> any, <del> any, <del> > | null = workInProgress.stateNode; <del> <del> if (fundamentalInstance === null) { <del> const getInitialState = fundamentalImpl.getInitialState; <del> let fundamentalState; <del> if (getInitialState !== undefined) { <del> fundamentalState = getInitialState(newProps); <del> } <del> fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance( <del> workInProgress, <del> newProps, <del> fundamentalImpl, <del> fundamentalState || {}, <del> ); <del> const instance = ((getFundamentalComponentInstance( <del> fundamentalInstance, <del> ): any): Instance); <del> fundamentalInstance.instance = instance; <del> if (fundamentalImpl.reconcileChildren === false) { <del> bubbleProperties(workInProgress); <del> return null; <del> } <del> appendAllChildren(instance, workInProgress, false, false); <del> mountFundamentalComponent(fundamentalInstance); <del> } else { <del> // We fire update in commit phase <del> const prevProps = fundamentalInstance.props; <del> fundamentalInstance.prevProps = prevProps; <del> fundamentalInstance.props = newProps; <del> fundamentalInstance.currentFiber = workInProgress; <del> if (supportsPersistence) { <del> const instance = cloneFundamentalInstance(fundamentalInstance); <del> fundamentalInstance.instance = instance; <del> appendAllChildren(instance, workInProgress, false, false); <del> } <del> const shouldUpdate = shouldUpdateFundamentalComponent( <del> fundamentalInstance, <del> ); <del> if (shouldUpdate) { <del> markUpdate(workInProgress); <del> } <del> } <del> bubbleProperties(workInProgress); <del> return null; <del> } <del> break; <del> } <ide> case ScopeComponent: { <ide> if (enableScopeAPI) { <ide> if (current === null) { <ide><path>packages/react-reconciler/src/ReactFiberFundamental.new.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @flow <del> */ <del> <del>import type {Fiber} from './ReactInternalTypes'; <del>import type { <del> ReactFundamentalImpl, <del> ReactFundamentalComponentInstance, <del>} from 'shared/ReactTypes'; <del> <del>export function createFundamentalStateInstance<C, H>( <del> currentFiber: Fiber, <del> props: Object, <del> impl: ReactFundamentalImpl<C, H>, <del> state: Object, <del>): ReactFundamentalComponentInstance<C, H> { <del> return { <del> currentFiber, <del> impl, <del> instance: null, <del> prevProps: null, <del> props, <del> state, <del> }; <del>} <ide><path>packages/react-reconciler/src/ReactFiberFundamental.old.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @flow <del> */ <del> <del>import type {Fiber} from './ReactInternalTypes'; <del>import type { <del> ReactFundamentalImpl, <del> ReactFundamentalComponentInstance, <del>} from 'shared/ReactTypes'; <del> <del>export function createFundamentalStateInstance<C, H>( <del> currentFiber: Fiber, <del> props: Object, <del> impl: ReactFundamentalImpl<C, H>, <del> state: Object, <del>): ReactFundamentalComponentInstance<C, H> { <del> return { <del> currentFiber, <del> impl, <del> instance: null, <del> prevProps: null, <del> props, <del> state, <del> }; <del>} <ide><path>packages/react-reconciler/src/ReactFiberHostConfigWithNoPersistence.js <ide> function shim(...args: any) { <ide> // Persistence (when unsupported) <ide> export const supportsPersistence = false; <ide> export const cloneInstance = shim; <del>export const cloneFundamentalInstance = shim; <ide> export const createContainerChildSet = shim; <ide> export const appendChildToContainerChildSet = shim; <ide> export const finalizeContainerChildren = shim; <ide><path>packages/react-reconciler/src/ReactFiberReconciler.new.js <ide> import type { <ide> PublicInstance, <ide> } from './ReactFiberHostConfig'; <ide> import type {RendererInspectionConfig} from './ReactFiberHostConfig'; <del>import {FundamentalComponent} from './ReactWorkTags'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> import type {Lane, LanePriority} from './ReactFiberLane.new'; <ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.new'; <ide> export function findHostInstanceWithNoPortals( <ide> if (hostFiber === null) { <ide> return null; <ide> } <del> if (hostFiber.tag === FundamentalComponent) { <del> return hostFiber.stateNode.instance; <del> } <ide> return hostFiber.stateNode; <ide> } <ide> <ide><path>packages/react-reconciler/src/ReactFiberReconciler.old.js <ide> import type { <ide> PublicInstance, <ide> } from './ReactFiberHostConfig'; <ide> import type {RendererInspectionConfig} from './ReactFiberHostConfig'; <del>import {FundamentalComponent} from './ReactWorkTags'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> import type {Lane, LanePriority} from './ReactFiberLane.old'; <ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.old'; <ide> export function findHostInstanceWithNoPortals( <ide> if (hostFiber === null) { <ide> return null; <ide> } <del> if (hostFiber.tag === FundamentalComponent) { <del> return hostFiber.stateNode.instance; <del> } <ide> return hostFiber.stateNode; <ide> } <ide> <ide><path>packages/react-reconciler/src/ReactFiberTreeReflection.js <ide> import { <ide> HostRoot, <ide> HostPortal, <ide> HostText, <del> FundamentalComponent, <ide> SuspenseComponent, <ide> } from './ReactWorkTags'; <ide> import {NoFlags, Placement, Hydrating} from './ReactFiberFlags'; <del>import {enableFundamentalAPI} from 'shared/ReactFeatureFlags'; <ide> <ide> const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; <ide> <ide> export function findCurrentHostFiberWithNoPortals(parent: Fiber): Fiber | null { <ide> <ide> function findCurrentHostFiberWithNoPortalsImpl(node: Fiber) { <ide> // Next we'll drill down this component to find the first HostComponent/Text. <del> if ( <del> node.tag === HostComponent || <del> node.tag === HostText || <del> (enableFundamentalAPI && node.tag === FundamentalComponent) <del> ) { <add> if (node.tag === HostComponent || node.tag === HostText) { <ide> return node; <ide> } <ide> <ide><path>packages/react-reconciler/src/ReactWorkTags.js <ide> export const LazyComponent = 16; <ide> export const IncompleteClassComponent = 17; <ide> export const DehydratedFragment = 18; <ide> export const SuspenseListComponent = 19; <del>export const FundamentalComponent = 20; <ide> export const ScopeComponent = 21; <ide> export const OffscreenComponent = 22; <ide> export const LegacyHiddenComponent = 23; <ide><path>packages/react-reconciler/src/__tests__/ReactFiberFundamental-test.internal.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @emails react-core <del> */ <del> <del>'use strict'; <del> <del>let React; <del>let ReactNoop; <del>let Scheduler; <del>let ReactFeatureFlags; <del>let ReactTestRenderer; <del>let ReactDOM; <del>let ReactDOMServer; <del> <del>function createReactFundamentalComponent(fundamentalImpl) { <del> return React.unstable_createFundamental(fundamentalImpl); <del>} <del> <del>function init() { <del> jest.resetModules(); <del> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <del> ReactFeatureFlags.enableFundamentalAPI = true; <del> React = require('react'); <del> Scheduler = require('scheduler'); <del>} <del> <del>function initNoopRenderer() { <del> init(); <del> ReactNoop = require('react-noop-renderer'); <del>} <del> <del>function initTestRenderer() { <del> init(); <del> ReactTestRenderer = require('react-test-renderer'); <del>} <del> <del>function initReactDOM() { <del> init(); <del> ReactDOM = require('react-dom'); <del>} <del> <del>function initReactDOMServer() { <del> init(); <del> ReactDOMServer = require('react-dom/server'); <del>} <del> <del>describe('ReactFiberFundamental', () => { <del> describe('NoopRenderer', () => { <del> beforeEach(() => { <del> initNoopRenderer(); <del> }); <del> <del> // @gate experimental <del> it('should render a simple fundamental component with a single child', () => { <del> const FundamentalComponent = createReactFundamentalComponent({ <del> reconcileChildren: true, <del> getInstance(context, props, state) { <del> const instance = { <del> children: [], <del> text: null, <del> type: 'test', <del> }; <del> return instance; <del> }, <del> }); <del> <del> const Test = ({children}) => ( <del> <FundamentalComponent>{children}</FundamentalComponent> <del> ); <del> <del> ReactNoop.render(<Test>Hello world</Test>); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(ReactNoop).toMatchRenderedOutput(<test>Hello world</test>); <del> ReactNoop.render(<Test>Hello world again</Test>); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(ReactNoop).toMatchRenderedOutput(<test>Hello world again</test>); <del> ReactNoop.render(null); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(ReactNoop).toMatchRenderedOutput(null); <del> }); <del> }); <del> <del> describe('NoopTestRenderer', () => { <del> beforeEach(() => { <del> initTestRenderer(); <del> }); <del> <del> // @gate experimental <del> it('should render a simple fundamental component with a single child', () => { <del> const FundamentalComponent = createReactFundamentalComponent({ <del> reconcileChildren: true, <del> getInstance(context, props, state) { <del> const instance = { <del> children: [], <del> props, <del> type: 'test', <del> tag: 'INSTANCE', <del> }; <del> return instance; <del> }, <del> }); <del> <del> const Test = ({children}) => ( <del> <FundamentalComponent>{children}</FundamentalComponent> <del> ); <del> <del> const root = ReactTestRenderer.create(null); <del> root.update(<Test>Hello world</Test>); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(root).toMatchRenderedOutput(<test>Hello world</test>); <del> root.update(<Test>Hello world again</Test>); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(root).toMatchRenderedOutput(<test>Hello world again</test>); <del> root.update(null); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(root).toMatchRenderedOutput(null); <del> }); <del> }); <del> <del> describe('ReactDOM', () => { <del> beforeEach(() => { <del> initReactDOM(); <del> }); <del> <del> // @gate experimental <del> it('should render a simple fundamental component with a single child', () => { <del> const FundamentalComponent = createReactFundamentalComponent({ <del> reconcileChildren: true, <del> getInstance(context, props, state) { <del> const instance = document.createElement('div'); <del> return instance; <del> }, <del> }); <del> <del> const Test = ({children}) => ( <del> <FundamentalComponent>{children}</FundamentalComponent> <del> ); <del> <del> const container = document.createElement('div'); <del> ReactDOM.render(<Test>Hello world</Test>, container); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(container.innerHTML).toBe('<div>Hello world</div>'); <del> ReactDOM.render(<Test>Hello world again</Test>, container); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(container.innerHTML).toBe('<div>Hello world again</div>'); <del> ReactDOM.render(null, container); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(container.innerHTML).toBe(''); <del> }); <del> <del> // @gate experimental <del> it('should render a simple fundamental component without reconcileChildren', () => { <del> const FundamentalComponent = createReactFundamentalComponent({ <del> reconcileChildren: false, <del> getInstance(context, props, state) { <del> const instance = document.createElement('div'); <del> instance.textContent = 'Hello world'; <del> return instance; <del> }, <del> }); <del> <del> const Test = () => <FundamentalComponent />; <del> <del> const container = document.createElement('div'); <del> ReactDOM.render(<Test />, container); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(container.innerHTML).toBe('<div>Hello world</div>'); <del> // Children should be ignored <del> ReactDOM.render(<Test>Hello world again</Test>, container); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(container.innerHTML).toBe('<div>Hello world</div>'); <del> ReactDOM.render(null, container); <del> expect(Scheduler).toFlushWithoutYielding(); <del> expect(container.innerHTML).toBe(''); <del> }); <del> }); <del> <del> describe('ReactDOMServer', () => { <del> beforeEach(() => { <del> initReactDOMServer(); <del> }); <del> <del> // @gate experimental <del> it('should render a simple fundamental component with a single child', () => { <del> const getInstance = jest.fn(); <del> const FundamentalComponent = createReactFundamentalComponent({ <del> reconcileChildren: true, <del> getInstance, <del> getServerSideString(context, props) { <del> return `<div>`; <del> }, <del> getServerSideStringClose(context, props) { <del> return `</div>`; <del> }, <del> }); <del> <del> const Test = ({children}) => ( <del> <FundamentalComponent>{children}</FundamentalComponent> <del> ); <del> <del> expect(getInstance).not.toBeCalled(); <del> let output = ReactDOMServer.renderToString(<Test>Hello world</Test>); <del> expect(output).toBe('<div>Hello world</div>'); <del> output = ReactDOMServer.renderToString(<Test>Hello world again</Test>); <del> expect(output).toBe('<div>Hello world again</div>'); <del> }); <del> <del> // @gate experimental <del> it('should render a simple fundamental component without reconcileChildren', () => { <del> const FundamentalComponent = createReactFundamentalComponent({ <del> reconcileChildren: false, <del> getServerSideString(context, props) { <del> return `<div>Hello world</div>`; <del> }, <del> }); <del> <del> const Test = () => <FundamentalComponent />; <del> <del> let output = ReactDOMServer.renderToString(<Test />); <del> expect(output).toBe('<div>Hello world</div>'); <del> // Children should be ignored <del> output = ReactDOMServer.renderToString(<Test>Hello world again</Test>); <del> expect(output).toBe('<div>Hello world</div>'); <del> }); <del> }); <del>}); <ide><path>packages/react-reconciler/src/forks/ReactFiberHostConfig.custom.js <ide> export const warnsIfNotActing = $$$hostConfig.warnsIfNotActing; <ide> export const supportsMutation = $$$hostConfig.supportsMutation; <ide> export const supportsPersistence = $$$hostConfig.supportsPersistence; <ide> export const supportsHydration = $$$hostConfig.supportsHydration; <del>export const getFundamentalComponentInstance = <del> $$$hostConfig.getFundamentalComponentInstance; <del>export const mountFundamentalComponent = <del> $$$hostConfig.mountFundamentalComponent; <del>export const shouldUpdateFundamentalComponent = <del> $$$hostConfig.shouldUpdateFundamentalComponent; <ide> export const getInstanceFromNode = $$$hostConfig.getInstanceFromNode; <ide> export const isOpaqueHydratingObject = $$$hostConfig.isOpaqueHydratingObject; <ide> export const makeOpaqueHydratingObject = <ide> export const hideInstance = $$$hostConfig.hideInstance; <ide> export const hideTextInstance = $$$hostConfig.hideTextInstance; <ide> export const unhideInstance = $$$hostConfig.unhideInstance; <ide> export const unhideTextInstance = $$$hostConfig.unhideTextInstance; <del>export const updateFundamentalComponent = <del> $$$hostConfig.updateFundamentalComponent; <del>export const unmountFundamentalComponent = <del> $$$hostConfig.unmountFundamentalComponent; <ide> export const clearContainer = $$$hostConfig.clearContainer; <ide> <ide> // ------------------- <ide> export const finalizeContainerChildren = <ide> export const replaceContainerChildren = $$$hostConfig.replaceContainerChildren; <ide> export const cloneHiddenInstance = $$$hostConfig.cloneHiddenInstance; <ide> export const cloneHiddenTextInstance = $$$hostConfig.cloneHiddenTextInstance; <del>export const cloneFundamentalInstance = $$$hostConfig.cloneInstance; <ide> <ide> // ------------------- <ide> // Hydration <ide><path>packages/react-test-renderer/src/ReactTestHostConfig.js <ide> * @flow <ide> */ <ide> <del>import type {ReactFundamentalComponentInstance} from 'shared/ReactTypes'; <del> <ide> import {REACT_OPAQUE_ID_TYPE} from 'shared/ReactSymbols'; <ide> <ide> export type Type = string; <ide> export function unhideTextInstance( <ide> textInstance.isHidden = false; <ide> } <ide> <del>export function getFundamentalComponentInstance( <del> fundamentalInstance: ReactFundamentalComponentInstance<any, any>, <del>): Instance { <del> const {impl, props, state} = fundamentalInstance; <del> return impl.getInstance(null, props, state); <del>} <del> <del>export function mountFundamentalComponent( <del> fundamentalInstance: ReactFundamentalComponentInstance<any, any>, <del>): void { <del> const {impl, instance, props, state} = fundamentalInstance; <del> const onMount = impl.onMount; <del> if (onMount !== undefined) { <del> onMount(null, instance, props, state); <del> } <del>} <del> <del>export function shouldUpdateFundamentalComponent( <del> fundamentalInstance: ReactFundamentalComponentInstance<any, any>, <del>): boolean { <del> const {impl, prevProps, props, state} = fundamentalInstance; <del> const shouldUpdate = impl.shouldUpdate; <del> if (shouldUpdate !== undefined) { <del> return shouldUpdate(null, prevProps, props, state); <del> } <del> return true; <del>} <del> <del>export function updateFundamentalComponent( <del> fundamentalInstance: ReactFundamentalComponentInstance<any, any>, <del>): void { <del> const {impl, instance, prevProps, props, state} = fundamentalInstance; <del> const onUpdate = impl.onUpdate; <del> if (onUpdate !== undefined) { <del> onUpdate(null, instance, prevProps, props, state); <del> } <del>} <del> <del>export function unmountFundamentalComponent( <del> fundamentalInstance: ReactFundamentalComponentInstance<any, any>, <del>): void { <del> const {impl, instance, props, state} = fundamentalInstance; <del> const onUnmount = impl.onUnmount; <del> if (onUnmount !== undefined) { <del> onUnmount(null, instance, props, state); <del> } <del>} <del> <ide> export function getInstanceFromNode(mockNode: Object) { <ide> const instance = nodeToInstanceMap.get(mockNode); <ide> if (instance !== undefined) { <ide><path>packages/react/index.js <ide> export { <ide> SuspenseList, <ide> SuspenseList as unstable_SuspenseList, <ide> unstable_LegacyHidden, <del> unstable_createFundamental, <ide> unstable_Scope, <ide> unstable_useOpaqueIdentifier, <ide> unstable_getCacheForType, <ide><path>packages/react/src/React.js <ide> import { <ide> } from './ReactElementValidator'; <ide> import {createMutableSource} from './ReactMutableSource'; <ide> import ReactSharedInternals from './ReactSharedInternals'; <del>import {createFundamental} from './ReactFundamental'; <ide> import {startTransition} from './ReactStartTransition'; <ide> <ide> // TODO: Move this branching into the other module instead and just re-export. <ide> export { <ide> getCacheForType as unstable_getCacheForType, <ide> useCacheRefresh as unstable_useCacheRefresh, <ide> REACT_CACHE_TYPE as unstable_Cache, <del> // enableFundamentalAPI <del> createFundamental as unstable_createFundamental, <ide> // enableScopeAPI <ide> REACT_SCOPE_TYPE as unstable_Scope, <ide> useOpaqueIdentifier as unstable_useOpaqueIdentifier, <ide><path>packages/react/src/ReactFundamental.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * @flow <del> */ <del> <del>import type { <del> ReactFundamentalImpl, <del> ReactFundamentalComponent, <del>} from 'shared/ReactTypes'; <del>import {REACT_FUNDAMENTAL_TYPE} from 'shared/ReactSymbols'; <del>import {hasBadMapPolyfill} from './BadMapPolyfill'; <del> <del>export function createFundamental<C, H>( <del> impl: ReactFundamentalImpl<C, H>, <del>): ReactFundamentalComponent<C, H> { <del> // We use responder as a Map key later on. When we have a bad <del> // polyfill, then we can't use it as a key as the polyfill tries <del> // to add a property to the object. <del> if (__DEV__ && !hasBadMapPolyfill) { <del> Object.freeze(impl); <del> } <del> const fundamentalComponent = { <del> $$typeof: REACT_FUNDAMENTAL_TYPE, <del> impl, <del> }; <del> if (__DEV__) { <del> Object.freeze(fundamentalComponent); <del> } <del> return fundamentalComponent; <del>} <ide><path>packages/shared/ReactFeatureFlags.js <ide> export const enableSchedulerDebugging = false; <ide> // Disable javascript: URL strings in href for XSS protection. <ide> export const disableJavaScriptURLs = false; <ide> <del>// Experimental Host Component support. <del>export const enableFundamentalAPI = false; <del> <ide> // Experimental Scope support. <ide> export const enableScopeAPI = false; <ide> <ide><path>packages/shared/ReactSymbols.js <ide> export let REACT_SUSPENSE_TYPE = 0xead1; <ide> export let REACT_SUSPENSE_LIST_TYPE = 0xead8; <ide> export let REACT_MEMO_TYPE = 0xead3; <ide> export let REACT_LAZY_TYPE = 0xead4; <del>export let REACT_FUNDAMENTAL_TYPE = 0xead5; <ide> export let REACT_SCOPE_TYPE = 0xead7; <ide> export let REACT_OPAQUE_ID_TYPE = 0xeae0; <ide> export let REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; <ide> if (typeof Symbol === 'function' && Symbol.for) { <ide> REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); <ide> REACT_MEMO_TYPE = symbolFor('react.memo'); <ide> REACT_LAZY_TYPE = symbolFor('react.lazy'); <del> REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); <ide> REACT_SCOPE_TYPE = symbolFor('react.scope'); <ide> REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); <ide> REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); <ide><path>packages/shared/ReactTypes.js <ide> export const DiscreteEvent: EventPriority = 0; <ide> export const UserBlockingEvent: EventPriority = 1; <ide> export const ContinuousEvent: EventPriority = 2; <ide> <del>export type ReactFundamentalComponentInstance<C, H> = {| <del> currentFiber: Object, <del> instance: mixed, <del> prevProps: null | Object, <del> props: Object, <del> impl: ReactFundamentalImpl<C, H>, <del> state: Object, <del>|}; <del> <del>export type ReactFundamentalImpl<C, H> = { <del> displayName: string, <del> reconcileChildren: boolean, <del> getInitialState?: (props: Object) => Object, <del> getInstance: (context: C, props: Object, state: Object) => H, <del> getServerSideString?: (context: C, props: Object) => string, <del> getServerSideStringClose?: (context: C, props: Object) => string, <del> onMount: (context: C, instance: mixed, props: Object, state: Object) => void, <del> shouldUpdate?: ( <del> context: C, <del> prevProps: null | Object, <del> nextProps: Object, <del> state: Object, <del> ) => boolean, <del> onUpdate?: ( <del> context: C, <del> instance: mixed, <del> prevProps: null | Object, <del> nextProps: Object, <del> state: Object, <del> ) => void, <del> onUnmount?: ( <del> context: C, <del> instance: mixed, <del> props: Object, <del> state: Object, <del> ) => void, <del> onHydrate?: (context: C, props: Object, state: Object) => boolean, <del> onFocus?: (context: C, props: Object, state: Object) => boolean, <del> ... <del>}; <del> <del>export type ReactFundamentalComponent<C, H> = {| <del> $$typeof: Symbol | number, <del> impl: ReactFundamentalImpl<C, H>, <del>|}; <del> <ide> export type ReactScope = {| <ide> $$typeof: Symbol | number, <ide> |}; <ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js <ide> export const disableJavaScriptURLs = false; <ide> export const disableInputAttributeSyncing = false; <ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__; <ide> export const warnAboutDeprecatedLifecycles = true; <del>export const enableFundamentalAPI = false; <ide> export const enableScopeAPI = false; <ide> export const enableCreateEventHandleAPI = false; <ide> export const warnAboutUnmockedScheduler = true; <ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js <ide> export const enableCache = false; <ide> export const disableJavaScriptURLs = false; <ide> export const disableInputAttributeSyncing = false; <ide> export const enableSchedulerDebugging = false; <del>export const enableFundamentalAPI = false; <ide> export const enableScopeAPI = false; <ide> export const enableCreateEventHandleAPI = false; <ide> export const warnAboutUnmockedScheduler = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js <ide> export const enableCache = __EXPERIMENTAL__; <ide> export const disableJavaScriptURLs = false; <ide> export const disableInputAttributeSyncing = false; <ide> export const enableSchedulerDebugging = false; <del>export const enableFundamentalAPI = false; <ide> export const enableScopeAPI = false; <ide> export const enableCreateEventHandleAPI = false; <ide> export const warnAboutUnmockedScheduler = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.native.js <ide> export const enableCache = false; <ide> export const disableJavaScriptURLs = false; <ide> export const disableInputAttributeSyncing = false; <ide> export const enableSchedulerDebugging = false; <del>export const enableFundamentalAPI = false; <ide> export const enableScopeAPI = false; <ide> export const enableCreateEventHandleAPI = false; <ide> export const warnAboutUnmockedScheduler = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js <ide> export const enableCache = false; <ide> export const enableSchedulerDebugging = false; <ide> export const disableJavaScriptURLs = false; <ide> export const disableInputAttributeSyncing = false; <del>export const enableFundamentalAPI = false; <ide> export const enableScopeAPI = true; <ide> export const enableCreateEventHandleAPI = false; <ide> export const warnAboutUnmockedScheduler = true; <ide><path>packages/shared/forks/ReactFeatureFlags.testing.js <ide> export const enableCache = false; <ide> export const disableJavaScriptURLs = false; <ide> export const disableInputAttributeSyncing = false; <ide> export const enableSchedulerDebugging = false; <del>export const enableFundamentalAPI = false; <ide> export const enableScopeAPI = false; <ide> export const enableCreateEventHandleAPI = false; <ide> export const warnAboutUnmockedScheduler = false; <ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js <ide> export const enableCache = false; <ide> export const disableJavaScriptURLs = true; <ide> export const disableInputAttributeSyncing = false; <ide> export const enableSchedulerDebugging = false; <del>export const enableFundamentalAPI = false; <ide> export const enableScopeAPI = true; <ide> export const enableCreateEventHandleAPI = true; <ide> export const warnAboutUnmockedScheduler = true; <ide><path>packages/shared/forks/ReactFeatureFlags.www.js <ide> export const disableModulePatternComponents = true; <ide> <ide> export const enableCreateEventHandleAPI = true; <ide> <del>export const enableFundamentalAPI = false; <del> <ide> export const enableScopeAPI = true; <ide> <ide> export const warnAboutUnmockedScheduler = true; <ide><path>packages/shared/isValidElementType.js <ide> import { <ide> REACT_SUSPENSE_LIST_TYPE, <ide> REACT_MEMO_TYPE, <ide> REACT_LAZY_TYPE, <del> REACT_FUNDAMENTAL_TYPE, <ide> REACT_SCOPE_TYPE, <ide> REACT_LEGACY_HIDDEN_TYPE, <ide> REACT_CACHE_TYPE, <ide> export default function isValidElementType(type: mixed) { <ide> type.$$typeof === REACT_PROVIDER_TYPE || <ide> type.$$typeof === REACT_CONTEXT_TYPE || <ide> type.$$typeof === REACT_FORWARD_REF_TYPE || <del> type.$$typeof === REACT_FUNDAMENTAL_TYPE || <ide> // This needs to include all possible module reference object <ide> // types supported by any Flight configuration anywhere since <ide> // we don't know which Flight build this will end up being used
41
Text
Text
convert the number component to listitem
7340fa9d933781747be0c3ac9850e264590fe5cd
<ide><path>docs/docs/lists-and-keys.md <ide> ReactDOM.render( <ide> ); <ide> ``` <ide> <del>[Try it out on Codepen.](https://codepen.io/gaearon/pen/GjPyQr?editors=0011) <add>[Try it out on CodePen.](https://codepen.io/gaearon/pen/GjPyQr?editors=0011) <ide> <ide> This code displays a bullet list of numbers between 1 and 5. <ide> <ide> ReactDOM.render( <ide> ); <ide> ``` <ide> <del>[Try it out on Codepen.](https://codepen.io/gaearon/pen/jrXYRR?editors=0011) <add>[Try it out on CodePen.](https://codepen.io/gaearon/pen/jrXYRR?editors=0011) <ide> <ide> ## Keys <ide> <ide> We don't recommend using indexes for keys if the items can reorder, as that woul <ide> <ide> Keys only make sense in the context of the surrounding array. <ide> <del>For example, if you [extract](/react/docs/components-and-props.html#extracting-components) a `Number` component, you should keep the key on the `<Number />` elements in the array rather than on the root `<li>` element in the `Number` itself. <add>For example, if you [extract](/react/docs/components-and-props.html#extracting-components) a `ListItem` component, you should keep the key on the `<ListItem />` elements in the array rather than on the root `<li>` element in the `ListItem` itself. <ide> <ide> **Example: Incorrect Key Usage** <ide> <ide> ```javascript{4,5,14,15} <del>function Number(props) { <add>function ListItem(props) { <ide> const value = props.value; <ide> return ( <ide> // Wrong! There is no need to specify the key here: <ide> function NumberList(props) { <ide> const numbers = props.numbers; <ide> const listItems = numbers.map((item) => <ide> // Wrong! The key should have been specified here: <del> <Number value={number} /> <add> <ListItem value={number} /> <ide> ); <ide> return ( <ide> <ul> <ide> ReactDOM.render( <ide> **Example: Correct Key Usage** <ide> <ide> ```javascript{2,3,9,10} <del>function Number(props) { <add>function ListItem(props) { <ide> // Correct! There is no need to specify the key here: <ide> return <li>{props.value}</li>; <ide> } <ide> function NumberList(props) { <ide> const numbers = props.numbers; <ide> const listItems = numbers.map((number) => <ide> // Correct! Key should be specified inside the array. <del> <Number key={number.toString()} <del> value={number} /> <add> <ListItem key={number.toString()} <add> value={number} /> <ide> ); <ide> return ( <ide> <ul> <ide> ReactDOM.render( <ide> ); <ide> ``` <ide> <del>[Try it out on Codepen.](https://codepen.io/gaearon/pen/ozJEPy?editors=0010) <add>[Try it out on CodePen.](https://codepen.io/rthor/pen/QKzJKG?editors=0010) <ide> <ide> A good rule of thumb is that elements inside the `map()` call need keys. <ide> <ide> In the examples above we declared a separate `listItems` variable and included i <ide> function NumberList(props) { <ide> const numbers = props.numbers; <ide> const listItems = numbers.map((number) => <del> <Number key={number.toString()} <del> value={number} /> <add> <ListItem key={number.toString()} <add> value={number} /> <ide> ); <ide> return ( <ide> <ul> <ide> function NumberList(props) { <ide> return ( <ide> <ul> <ide> {numbers.map((number) => <del> <Number key={number.toString()} <del> value={number} /> <add> <ListItem key={number.toString()} <add> value={number} /> <ide> )} <ide> </ul> <ide> );
1